:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(reminders): add reminders product (MCP/AI surface) (#63579)
Yasen56d8d4e50c6b
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex 3d4ae559159f..a228b7b24fee 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -907,6 +907,7 @@ rules:|KernelRuntime|MCPServerInstallation|PersistedFolder+ |Reminder|SessionRecordingViewed|UserHomeSettings|UserProductList@@ -978,6 +979,7 @@ rules:|InsightViewed|KernelRuntime|PersistedFolder+ |Reminder|SessionRecordingViewed|UserHomeSettings|UserProductListdiff --git a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsxindex 91376de17f41..3a7623dd875d 100644--- a/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx+++ b/frontend/src/lib/components/NotificationsMenu/NotificationRow.tsx@@ -50,6 +50,10 @@ export const REALTIME_NOTIFICATION_TYPE_META: Record<string, { label: string; delabel: 'Usage spikes',description: 'When billing detects a usage spike for one of your accounts',},+ reminder: {+ label: 'Reminders',+ description: 'When a reminder you scheduled is due',+ },web_analytics_digest: {label: 'Web analytics digest',description: 'Your weekly Web analytics summary is ready!',diff --git a/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx b/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsxindex 9a212d4d9beb..f72a9e53f0d5 100644--- a/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx+++ b/frontend/src/lib/components/NotificationsMenu/notificationToasts.tsx@@ -1,6 +1,7 @@import {IconBug,IconCheckCircle,+ IconClock,IconComment,IconFlask,IconFolder,@@ -27,6 +28,7 @@ const NOTIFICATION_TYPE_ICONS: Record<string, JSX.Element> = {experiment_concluded: <IconFlask className="size-5 text-primary shrink-0" />,project_created: <IconFolder className="size-5 text-primary shrink-0" />,usage_spike: <IconTrending className="size-5 text-warning shrink-0" />,+ reminder: <IconClock className="size-5 text-primary shrink-0" />,web_analytics_digest: <IconPieChart className="size-5 text-primary shrink-0" />,achievement_unlocked: <IconStar className="size-5 text-warning shrink-0" />,}diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionsTable.stories.tsx b/frontend/src/scenes/subscriptions/components/SubscriptionsTable.stories.tsxindex 9475718c8528..88ff03d7532a 100644--- a/frontend/src/scenes/subscriptions/components/SubscriptionsTable.stories.tsx+++ b/frontend/src/scenes/subscriptions/components/SubscriptionsTable.stories.tsx@@ -6,8 +6,8 @@ import { LemonButton } from '@posthog/lemon-ui'import type { PaginationManual } from '@posthog/lemon-ui'import type { SubscriptionApi } from '@posthog/products-subscriptions/frontend/generated/api.schemas'import {+ RecurrenceIntervalEnumApi,ResourceTypeEnumApi,- SubscriptionFrequencyEnumApi,TargetTypeEnumApi,} from '@posthog/products-subscriptions/frontend/generated/api.schemas'@@ -35,7 +35,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [target_type: TargetTypeEnumApi.Email,target_value:- frequency: SubscriptionFrequencyEnumApi.Weekly,+ frequency: RecurrenceIntervalEnumApi.Weekly,interval: 1,start_date: '2022-01-01T00:00:00Z',created_at: '2023-04-27T10:04:37.977401Z',@@ -56,7 +56,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [dashboard_export_insights: [101, 102],target_type: TargetTypeEnumApi.Slack,target_value: 'C12345|#alerts-analytics-platform',- frequency: SubscriptionFrequencyEnumApi.Daily,+ frequency: RecurrenceIntervalEnumApi.Daily,interval: 1,start_date: '2022-01-01T00:00:00Z',created_at: '2023-04-27T10:04:37.977401Z',@@ -78,7 +78,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [dashboard_export_insights: [],target_type: TargetTypeEnumApi.Email,target_value: '[email protected]',- frequency: SubscriptionFrequencyEnumApi.Monthly,+ frequency: RecurrenceIntervalEnumApi.Monthly,interval: 1,start_date: '2022-01-01T00:00:00Z',created_at: '2023-04-27T10:04:37.977401Z',@@ -99,7 +99,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [dashboard_export_insights: [],target_type: TargetTypeEnumApi.Slack,target_value: 'C1234567890|#automation-alerts',- frequency: SubscriptionFrequencyEnumApi.Weekly,+ frequency: RecurrenceIntervalEnumApi.Weekly,interval: 1,start_date: '2022-01-01T00:00:00Z',created_at: '2023-04-27T10:04:37.977401Z',@@ -120,7 +120,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [dashboard_export_insights: [],target_type: TargetTypeEnumApi.Slack,target_value: 'C99999|#archived-channel',- frequency: SubscriptionFrequencyEnumApi.Weekly,+ frequency: RecurrenceIntervalEnumApi.Weekly,interval: 1,start_date: '2022-01-01T00:00:00Z',created_at: '2023-04-27T10:04:37.977401Z',@@ -143,7 +143,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [dashboard_export_insights: [],target_type: TargetTypeEnumApi.Email,target_value: '[email protected]',- frequency: SubscriptionFrequencyEnumApi.Weekly,+ frequency: RecurrenceIntervalEnumApi.Weekly,interval: 1,start_date: '2022-01-01T00:00:00Z',created_at: '2023-04-27T10:04:37.977401Z',@@ -183,7 +183,7 @@ function buildMockSubscriptions(total: number): SubscriptionApi[] {dashboard_export_insights: [],target_type: isSlack ? TargetTypeEnumApi.Slack : TargetTypeEnumApi.Email,target_value: isSlack ? `C${n}|#channel-${n}` : `analyst${n}@posthog.com`,- frequency: SubscriptionFrequencyEnumApi.Weekly,+ frequency: RecurrenceIntervalEnumApi.Weekly,interval: 1,start_date: '2022-01-01T00:00:00Z',created_at: '2023-04-27T10:04:37.977401Z',diff --git a/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.ts b/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.tsindex 040c25338a13..9a8592df38d0 100644--- a/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.ts+++ b/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.ts@@ -1,7 +1,7 @@import {+ RecurrenceIntervalEnumApi,ResourceTypeEnumApi,SubscriptionDeliveryStatusEnumApi,- SubscriptionFrequencyEnumApi,TargetTypeEnumApi,type SubscriptionApi,type SubscriptionDeliveryApi,@@ -27,7 +27,7 @@ export const MOCK_SUBSCRIPTION_INSIGHT: SubscriptionApi = {dashboard_export_insights: [],target_type: TargetTypeEnumApi.Email,target_value: '[email protected]',- frequency: SubscriptionFrequencyEnumApi.Weekly,+ frequency: RecurrenceIntervalEnumApi.Weekly,interval: 1,start_date: '2022-01-01T00:00:00Z',created_at: '2023-04-27T10:04:37.977401Z',@@ -58,7 +58,7 @@ export const MOCK_SUBSCRIPTION_DASHBOARD: SubscriptionApi = {dashboard_export_insights: [101],target_type: TargetTypeEnumApi.Slack,target_value: 'C12345|#alerts-analytics-platform',- frequency: SubscriptionFrequencyEnumApi.Daily,+ frequency: RecurrenceIntervalEnumApi.Daily,interval: 1,start_date: '2022-01-01T00:00:00Z',created_at: '2023-04-27T10:04:37.977401Z',diff --git a/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.ts b/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.tsindex 0b451d611419..d7dc2eb23ecd 100644--- a/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.ts+++ b/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.ts@@ -5,8 +5,8 @@ import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'import {+ RecurrenceIntervalEnumApi,ResourceTypeEnumApi,- SubscriptionFrequencyEnumApi,SubscriptionsDeliveriesListStatus,TargetTypeEnumApi,} from '@posthog/products-subscriptions/frontend/generated/api.schemas'@@ -40,7 +40,7 @@ const MOCK_SUBSCRIPTION: SubscriptionApi = {dashboard_export_insights: [],target_type: TargetTypeEnumApi.Email,target_value: '[email protected]',- frequency: SubscriptionFrequencyEnumApi.Weekly,+ frequency: RecurrenceIntervalEnumApi.Weekly,interval: 1,start_date: '2022-01-01T00:00:00Z',created_at: '2023-04-27T10:04:37.977401Z',@@ -62,7 +62,7 @@ const MOCK_AI_SUBSCRIPTION: SubscriptionApi = {dashboard_export_insights: [],target_type: TargetTypeEnumApi.Email,target_value: '[email protected]',- frequency: SubscriptionFrequencyEnumApi.Weekly,+ frequency: RecurrenceIntervalEnumApi.Weekly,interval: 1,start_date: '2022-01-01T00:00:00Z',created_at: '2023-04-27T10:04:37.977401Z',diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9817ea449ebc..21fc62b94361 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3718,6 +3718,8 @@ importers:products/product_tours: {}+ products/reminders: {}+products/replay:dependencies:'@posthog/icons':diff --git a/posthog/models/scoping/baseline_unmigrated.txt b/posthog/models/scoping/baseline_unmigrated.txtindex aedc2dd98ddd..c815879df6e4 100644--- a/posthog/models/scoping/baseline_unmigrated.txt+++ b/posthog/models/scoping/baseline_unmigrated.txt@@ -132,6 +132,7 @@ PropertyAccessControlQueryTabStateQuickFilterQuickFilterContext+ReminderReplayObservationReplayScannerRepoRoutingRulediff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 41fcca4dde7b..a15815c3c1e6 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -92,6 +92,7 @@ PRODUCTS_APPS = ["products.managed_migrations.backend.apps.ManagedMigrationsConfig","products.replay.backend.apps.ReplayConfig","products.cohorts.backend.apps.CohortsConfig",+ "products.reminders.backend.apps.RemindersConfig",]INSTALLED_APPS = [@@ -493,6 +494,7 @@ SPECTACULAR_SETTINGS = {"TaskRunStatusEnum": "products.tasks.backend.models.TaskRun.Status","TaskRunEnvironmentEnum": "products.tasks.backend.models.TaskRun.Environment","ModelEnum": "products.batch_exports.backend.models.batch_export.BatchExport.Model",+ "RecurrenceIntervalEnum": "products.reminders.backend.models.reminder.Reminder.RecurrenceInterval","ScannerModelEnum": "products.replay_vision.backend.models.replay_scanner.ScannerModel","ScannerTypeEnum": "products.replay_vision.backend.models.replay_scanner.ScannerType","ScannerProviderEnum": "products.replay_vision.backend.models.replay_scanner.ScannerProvider",diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 2308bb67aeab..114a0f898345 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -82,6 +82,7 @@ from products.feature_flags.backend.tasks import (refresh_expiring_flags_cache_entries,)from products.logs.backend.tasks import logs_alert_events_cleanup_task+from products.reminders.backend.tasks import process_due_remindersfrom products.streamlit_apps.backend.facade.api import (auto_restart_crashed_streamlit_sandboxes,cleanup_deleted_streamlit_app_zips,@@ -487,6 +488,13 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="process scheduled changes",)+ add_periodic_task_with_expiry(+ sender,+ crontab(minute="*"),+ process_due_reminders.s(),+ name="process due reminders",+ )+if clear_clickhouse_crontab := get_crontab(settings.CLEAR_CLICKHOUSE_REMOVED_DATA_SCHEDULE_CRON):sender.add_periodic_task(clear_clickhouse_crontab,diff --git a/products/error_tracking/backend/notifications.py b/products/error_tracking/backend/notifications.pyindex 4a51d0a70e39..19b4fdb632c4 100644--- a/products/error_tracking/backend/notifications.py+++ b/products/error_tracking/backend/notifications.py@@ -23,7 +23,7 @@ class _AssignerExcludingResolver(RecipientsResolver):super().__init__()self._assigner_id = assigner_id- def resolve(self, target_type: TargetType, target_id: str, team_id: int) -> list[int]:+ def resolve(self, target_type: TargetType, target_id: str, team_id: int | None) -> list[int]:users = super().resolve(target_type, target_id, team_id)return [uid for uid in users if uid != self._assigner_id]diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex 1e26dff7cb5e..998c6b8ed981 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -1251,9 +1251,10 @@ export const ModelNameEnumApi = {* * `monthly` - monthly* * `yearly` - yearly*/-export type RecurrenceIntervalEnumApi = (typeof RecurrenceIntervalEnumApi)[keyof typeof RecurrenceIntervalEnumApi]+export type ScheduledChangeRecurrenceIntervalEnumApi =+ (typeof ScheduledChangeRecurrenceIntervalEnumApi)[keyof typeof ScheduledChangeRecurrenceIntervalEnumApi]-export const RecurrenceIntervalEnumApi = {+export const ScheduledChangeRecurrenceIntervalEnumApi = {Daily: 'daily',Weekly: 'weekly',Monthly: 'monthly',@@ -1294,7 +1295,7 @@ export interface ScheduledChangeApi {* * `weekly` - weekly* * `monthly` - monthly* * `yearly` - yearly */- recurrence_interval?: RecurrenceIntervalEnumApi | null+ recurrence_interval?: ScheduledChangeRecurrenceIntervalEnumApi | null/*** @maxLength 100* @nullable@@ -1354,7 +1355,7 @@ export interface PatchedScheduledChangeApi {* * `weekly` - weekly* * `monthly` - monthly* * `yearly` - yearly */- recurrence_interval?: RecurrenceIntervalEnumApi | null+ recurrence_interval?: ScheduledChangeRecurrenceIntervalEnumApi | null/*** @maxLength 100* @nullablediff --git a/products/notifications/backend/facade/contracts.py b/products/notifications/backend/facade/contracts.pyindex 227bca04ee9a..e92bae31e8ae 100644--- a/products/notifications/backend/facade/contracts.py+++ b/products/notifications/backend/facade/contracts.py@@ -2,6 +2,7 @@ from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Any+from uuid import UUIDfrom products.notifications.backend.facade.enums import (NotificationResourceType,@@ -17,12 +18,13 @@ if TYPE_CHECKING:@dataclass(frozen=True)class NotificationData:- team_id: intnotification_type: NotificationTypetitle: strbody: strtarget_type: TargetTypetarget_id: str+ team_id: int | None = None+ organization_id: UUID | None = Noneresource_type: NotificationResourceType | None = Noneresource_id: str = ""source_url: str = ""diff --git a/products/notifications/backend/facade/enums.py b/products/notifications/backend/facade/enums.pyindex 705bce8ed748..86de06e041f4 100644--- a/products/notifications/backend/facade/enums.py+++ b/products/notifications/backend/facade/enums.py@@ -15,6 +15,7 @@ class NotificationType(str, Enum):PIPELINE_FAILURE = "pipeline_failure"PROJECT_CREATED = "project_created"USAGE_SPIKE = "usage_spike"+ REMINDER = "reminder"WEB_ANALYTICS_DIGEST = "web_analytics_digest"ACHIEVEMENT_UNLOCKED = "achievement_unlocked"diff --git a/products/notifications/backend/logic.py b/products/notifications/backend/logic.pyindex 74e39cd74fd8..21a68020c21a 100644--- a/products/notifications/backend/logic.py+++ b/products/notifications/backend/logic.py@@ -5,7 +5,7 @@ import posthoganalyticsfrom posthog.kafka_client.routing import get_producerfrom posthog.kafka_client.topics import KAFKA_NOTIFICATION_EVENTS-from posthog.models import Team, User+from posthog.models import Organization, Team, Userfrom products.notifications.backend.cache import invalidate_unread_count_for_usersfrom products.notifications.backend.facade.contracts import NotificationData@@ -50,9 +50,10 @@ def _publish_to_kafka(event: NotificationEvent) -> None:def _filter_by_user_preferences(user_ids: list[int],notification_type: NotificationType,- team_id: int,+ team_id: int | None,) -> list[int]:- if not user_ids:+ # Per-team preferences only apply to team-level notifications; org-level dispatch has no team key to gate on.+ if not user_ids or team_id is None:return user_idsrows = User.objects.filter(id__in=user_ids).values_list("id", "partial_notification_settings")type_key = notification_type.value@@ -88,14 +89,24 @@ def has_been_dispatched(def create_notification(data: NotificationData) -> NotificationEvent | None:- try:- team = Team.objects.select_related("organization").get(id=data.team_id)- except Team.DoesNotExist:- logger.warning("notifications.team_not_found", team_id=data.team_id)+ team: Team | None = None+ if data.team_id is not None:+ try:+ team = Team.objects.select_related("organization").get(id=data.team_id)+ except Team.DoesNotExist:+ logger.warning("notifications.team_not_found", team_id=data.team_id)+ return None+ organization = team.organization+ elif data.organization_id is not None:+ try:+ organization = Organization.objects.get(id=data.organization_id)+ except Organization.DoesNotExist:+ logger.warning("notifications.organization_not_found", organization_id=data.organization_id)+ return None+ else:+ logger.warning("notifications.no_target_scope")return None- organization = team.organization-if not posthoganalytics.feature_enabled("real-time-notifications",str(organization.id),@@ -108,7 +119,7 @@ def create_notification(data: NotificationData) -> NotificationEvent | None:resolver = data.resolver or RecipientsResolver()resolved_user_ids = resolver.resolve(data.target_type, data.target_id, data.team_id)- if data.resource_type and str(data.resource_type) in AC_RESOURCE_TYPES:+ if team is not None and data.resource_type and str(data.resource_type) in AC_RESOURCE_TYPES:resolved_user_ids = resolver.filter_by_access_control(resolved_user_ids, str(data.resource_type), team)# Per-user pref filter must run AFTER AC — prefs cannot override access denials.diff --git a/products/notifications/backend/migrations/0016_alter_notificationevent_notification_type.py b/products/notifications/backend/migrations/0016_alter_notificationevent_notification_type.pynew file mode 100644index 000000000000..2b5446546155--- /dev/null+++ b/products/notifications/backend/migrations/0016_alter_notificationevent_notification_type.py@@ -0,0 +1,33 @@+# Generated by Django 5.2.14 on 2026-06-17 14:04++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("notifications", "0015_alter_notificationevent_notification_type"),+ ]++ operations = [+ migrations.AlterField(+ model_name="notificationevent",+ name="notification_type",+ field=models.CharField(+ choices=[+ ("comment_mention", "COMMENT_MENTION"),+ ("alert_firing", "ALERT_FIRING"),+ ("issue_assigned", "ISSUE_ASSIGNED"),+ ("approval_requested", "APPROVAL_REQUESTED"),+ ("approval_resolved", "APPROVAL_RESOLVED"),+ ("experiment_concluded", "EXPERIMENT_CONCLUDED"),+ ("pipeline_failure", "PIPELINE_FAILURE"),+ ("project_created", "PROJECT_CREATED"),+ ("usage_spike", "USAGE_SPIKE"),+ ("reminder", "REMINDER"),+ ("web_analytics_digest", "WEB_ANALYTICS_DIGEST"),+ ("achievement_unlocked", "ACHIEVEMENT_UNLOCKED"),+ ],+ max_length=32,+ ),+ ),+ ]diff --git a/products/notifications/backend/migrations/max_migration.txt b/products/notifications/backend/migrations/max_migration.txtindex a5144865891f..e3841da58bdf 100644--- a/products/notifications/backend/migrations/max_migration.txt+++ b/products/notifications/backend/migrations/max_migration.txt@@ -1 +1 @@-0015_alter_notificationevent_notification_type+0016_alter_notificationevent_notification_typediff --git a/products/notifications/backend/resolvers.py b/products/notifications/backend/resolvers.pyindex a7f62d36c968..800e735f6c60 100644--- a/products/notifications/backend/resolvers.py+++ b/products/notifications/backend/resolvers.py@@ -12,7 +12,7 @@ logger = structlog.get_logger(__name__)class RecipientsResolver:- def resolve(self, target_type: TargetType, target_id: str, team_id: int) -> list[int]:+ def resolve(self, target_type: TargetType, target_id: str, team_id: int | None) -> list[int]:if target_type == TargetType.USER:return [int(target_id)]elif target_type == TargetType.TEAM:diff --git a/products/reminders/__init__.py b/products/reminders/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/reminders/backend/__init__.py b/products/reminders/backend/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/reminders/backend/api/__init__.py b/products/reminders/backend/api/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/reminders/backend/api/reminder.py b/products/reminders/backend/api/reminder.pynew file mode 100644index 000000000000..f00c692516b7--- /dev/null+++ b/products/reminders/backend/api/reminder.py@@ -0,0 +1,244 @@+from datetime import datetime+from typing import Any, cast+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError++from django.db.models import QuerySet+from django.utils import timezone++from drf_spectacular.utils import extend_schema+from rest_framework import serializers, viewsets+from rest_framework.exceptions import ValidationError+from rest_framework.permissions import IsAuthenticated++from posthog.api.shared import UserBasicSerializer+from posthog.auth import PersonalAPIKeyAuthentication, SessionAuthentication+from posthog.models import Organization, Team, User+from posthog.permissions import APIScopePermission+from posthog.user_permissions import UserPermissions++from products.reminders.backend.constants import MAX_ACTIVE_REMINDERS_PER_USER, RESOURCE_MODELS, RESOURCE_TYPES+from products.reminders.backend.models import Reminder+from products.reminders.backend.scheduling import compute_next_fire_at, exceeds_daily_frequency_cap, resolve_timezone+++class ReminderSerializer(serializers.ModelSerializer):+ created_by = UserBasicSerializer(read_only=True)+ # User-scoped endpoint: the user picks the org/team from their own memberships and+ # _validate_membership enforces access — there is no single org/team in request context+ # for the scoped PK fields to derive from, so suppress the IDOR scoping rule here.+ organization = serializers.PrimaryKeyRelatedField( # nosemgrep: unscoped-primary-key-related-field+ queryset=Organization.objects.all(),+ help_text="ID of the organization this reminder belongs to. You must be a member of it.",+ )+ team = serializers.PrimaryKeyRelatedField( # nosemgrep: unscoped-primary-key-related-field+ queryset=Team.objects.all(),+ required=False,+ allow_null=True,+ help_text=(+ "Optional ID of the project this reminder is scoped to. "+ "Required when targeting a specific resource. Must belong to the chosen organization."+ ),+ )++ class Meta:+ model = Reminder+ fields = [+ "id",+ "organization",+ "team",+ "title",+ "message",+ "resource_type",+ "resource_id",+ "scheduled_at",+ "recurrence_interval",+ "cron_expression",+ "timezone",+ "end_date",+ "next_fire_at",+ "last_fired_at",+ "status",+ "created_by",+ "created_at",+ "updated_at",+ ]+ read_only_fields = [+ "id",+ "next_fire_at",+ "last_fired_at",+ "status",+ "created_by",+ "created_at",+ "updated_at",+ ]+ extra_kwargs = {+ "title": {"help_text": "Short text shown as the notification title when the reminder fires."},+ "message": {"help_text": "Optional longer body for the notification."},+ "resource_type": {+ "help_text": (+ f"Optional PostHog resource this reminder is about. One of: {', '.join(RESOURCE_TYPES)}. "+ "Resources are project-scoped, so a team must be set when this is provided."+ ),+ },+ "resource_id": {"help_text": "ID of the referenced resource; must exist in the chosen project."},+ "scheduled_at": {"help_text": "For a one-off reminder: when it should fire (ISO 8601, future)."},+ "recurrence_interval": {+ "help_text": "For a recurring reminder: daily, weekly, monthly, or yearly.",+ },+ "cron_expression": {+ "help_text": (+ "For a recurring reminder: a 5-field cron expression (e.g. '0 9 * * 1' = Mondays 9am). "+ "May fire at most 4 times per day. Mutually exclusive with recurrence_interval."+ ),+ },+ "timezone": {+ "help_text": (+ "IANA timezone the schedule resolves in (e.g. 'America/New_York'). "+ "Defaults to the project timezone when a team is set, otherwise UTC."+ ),+ },+ "end_date": {+ "help_text": "Optional: recurring reminders stop (status=completed) after this time.",+ },+ }++ def validate_timezone(self, value: str) -> str:+ try:+ ZoneInfo(value)+ except (ZoneInfoNotFoundError, ValueError):+ raise ValidationError(f"Unknown timezone: {value}")+ return value++ def _validate_membership(self, organization: Organization | None, team: Team | None) -> None:+ if organization is None:+ raise ValidationError("An organization is required.")++ user = cast(User, self.context["request"].user)+ permissions = UserPermissions(user)++ if organization.id not in permissions.organization_memberships:+ raise ValidationError("You are not a member of this organization.")++ if team is not None:+ if team.organization_id != organization.id:+ raise ValidationError("The team does not belong to the chosen organization.")+ if permissions.team(team).effective_membership_level is None:+ raise ValidationError("You do not have access to this team.")++ def _validate_resource(self, attrs: dict[str, Any], team: Team | None) -> None:+ instance = self.instance+ resource_type = attrs.get("resource_type", getattr(instance, "resource_type", None))+ resource_id = attrs.get("resource_id", getattr(instance, "resource_id", None))++ if not (resource_type or resource_id):+ return++ if not (resource_type and resource_id):+ raise ValidationError("resource_type and resource_id must be provided together.")+ if team is None:+ raise ValidationError("A team must be set to attach a resource to a reminder.")+ if resource_type not in RESOURCE_MODELS:+ raise ValidationError(f"Unknown resource_type: {resource_type}")++ model, lookup_field, _ = RESOURCE_MODELS[resource_type]+ if not model._default_manager.filter(team=team, **{lookup_field: resource_id}).exists():+ raise ValidationError(f"No {resource_type} with id {resource_id} in this project.")++ def _validate_active_cap(self) -> None:+ instance = self.instance+ if instance is not None and getattr(instance, "status", None) != Reminder.Status.ACTIVE:+ return++ user = self.context["request"].user+ active = Reminder.objects.filter(created_by=user, status=Reminder.Status.ACTIVE, deleted=False)+ if instance is not None:+ active = active.exclude(id=instance.id)+ if active.count() >= MAX_ACTIVE_REMINDERS_PER_USER:+ raise ValidationError(f"You already have {MAX_ACTIVE_REMINDERS_PER_USER} active reminders.")++ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:+ instance = self.instance++ organization = attrs.get("organization", getattr(instance, "organization", None))+ team = attrs.get("team", getattr(instance, "team", None))++ scheduled_at = attrs.get("scheduled_at", getattr(instance, "scheduled_at", None))+ interval = attrs.get("recurrence_interval", getattr(instance, "recurrence_interval", None))+ cron = attrs.get("cron_expression", getattr(instance, "cron_expression", None))++ if sum([bool(scheduled_at), bool(interval), bool(cron)]) != 1:+ raise ValidationError("Provide exactly one of scheduled_at, recurrence_interval, or cron_expression.")++ # Only enforce a future time on new or still-active reminders; a fired one-off keeps its+ # past scheduled_at, and editing its title/message shouldn't be rejected over that.+ is_active = instance is None or instance.status == Reminder.Status.ACTIVE+ if scheduled_at and is_active and scheduled_at <= timezone.now():+ raise ValidationError("scheduled_at must be in the future.")++ if cron and exceeds_daily_frequency_cap(cron):+ raise ValidationError("Schedule fires too often; a reminder may fire at most 4 times per day.")++ self._validate_membership(organization, team)+ self._validate_resource(attrs, team)+ self._validate_active_cap()++ return attrs++ def _initial_next_fire_at(self, validated: dict[str, Any], tz_name: str) -> datetime:+ if validated.get("scheduled_at"):+ return validated["scheduled_at"]+ tz = resolve_timezone(validated.get("timezone") or tz_name)+ return compute_next_fire_at(+ timezone.now(),+ interval=validated.get("recurrence_interval"),+ cron_expression=validated.get("cron_expression"),+ tz=tz,+ )++ def create(self, validated_data: dict[str, Any]) -> Reminder:+ request = self.context["request"]+ team: Team | None = validated_data.get("team")+ validated_data["created_by"] = request.user++ default_tz = team.timezone if team is not None else "UTC"+ if not validated_data.get("timezone"):+ validated_data["timezone"] = default_tz+ validated_data["next_fire_at"] = self._initial_next_fire_at(validated_data, default_tz)+ return super().create(validated_data)++ def update(self, instance: Reminder, validated_data: dict[str, Any]) -> Reminder:+ schedule_changed = any(+ k in validated_data for k in ("scheduled_at", "recurrence_interval", "cron_expression", "timezone")+ )+ reminder = super().update(instance, validated_data)+ if schedule_changed and reminder.status == Reminder.Status.ACTIVE:+ merged = {+ "scheduled_at": reminder.scheduled_at,+ "recurrence_interval": reminder.recurrence_interval,+ "cron_expression": reminder.cron_expression,+ "timezone": reminder.timezone,+ }+ default_tz = reminder.team.timezone if reminder.team_id else "UTC"+ reminder.next_fire_at = self._initial_next_fire_at(merged, default_tz)+ reminder.save(update_fields=["next_fire_at"])+ return reminder+++@extend_schema(extensions={"x-product": "reminders"})+class ReminderViewSet(viewsets.ModelViewSet):+ scope_object = "user"+ serializer_class = ReminderSerializer+ permission_classes = [IsAuthenticated, APIScopePermission]+ authentication_classes = [PersonalAPIKeyAuthentication, SessionAuthentication]+ queryset = Reminder.objects.none()++ def get_queryset(self) -> QuerySet[Reminder]:+ return (+ Reminder.objects.filter(created_by=cast(User, self.request.user), deleted=False)+ .select_related("created_by", "team", "organization")+ .order_by("-created_at")+ )++ def perform_destroy(self, instance: Reminder) -> None:+ instance.deleted = True+ instance.save(update_fields=["deleted"])diff --git a/products/reminders/backend/api/test/__init__.py b/products/reminders/backend/api/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/reminders/backend/api/test/test_reminder.py b/products/reminders/backend/api/test/test_reminder.pynew file mode 100644index 000000000000..428e11b764b4--- /dev/null+++ b/products/reminders/backend/api/test/test_reminder.py@@ -0,0 +1,175 @@+from datetime import UTC, datetime, timedelta++from posthog.test.base import APIBaseTest++from rest_framework import status++from posthog.models import Organization, Team++from products.reminders.backend.models import Reminder+++class TestReminderAPI(APIBaseTest):+ def _url(self, suffix: str = "") -> str:+ return f"/api/reminders/{suffix}"++ def _payload(self, **overrides: object) -> dict[str, object]:+ future = (datetime.now(UTC) + timedelta(days=1)).isoformat()+ payload: dict[str, object] = {+ "organization": str(self.organization.id),+ "title": "Check funnel",+ "scheduled_at": future,+ }+ payload.update(overrides)+ return payload++ def test_create_one_off_reminder(self) -> None:+ future = (datetime.now(UTC) + timedelta(days=1)).isoformat()+ response = self.client.post(self._url(), self._payload(scheduled_at=future))+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ body = response.json()+ self.assertEqual(body["title"], "Check funnel")+ self.assertEqual(body["status"], "active")+ reminder = Reminder.objects.get(id=body["id"])+ self.assertEqual(reminder.created_by, self.user)+ self.assertEqual(reminder.organization_id, self.organization.id)+ assert reminder.next_fire_at is not None+ self.assertEqual(reminder.next_fire_at.isoformat(), future)++ def test_create_recurring_cron_reminder(self) -> None:+ response = self.client.post(+ self._url(),+ self._payload(+ title="Weekly review",+ scheduled_at=None,+ cron_expression="0 9 * * 1",+ timezone="America/New_York",+ ),+ )+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ reminder = Reminder.objects.get(id=response.json()["id"])+ self.assertIsNotNone(reminder.next_fire_at)++ def test_create_with_team(self) -> None:+ response = self.client.post(self._url(), self._payload(team=self.team.id))+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())+ reminder = Reminder.objects.get(id=response.json()["id"])+ self.assertEqual(reminder.team_id, self.team.id)++ def test_rejects_two_schedule_sources(self) -> None:+ response = self.client.post(self._url(), self._payload(recurrence_interval="daily"))+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_rejects_no_schedule(self) -> None:+ response = self.client.post(self._url(), self._payload(scheduled_at=None))+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_rejects_too_frequent_cron(self) -> None:+ response = self.client.post(self._url(), self._payload(scheduled_at=None, cron_expression="*/10 * * * *"))+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_rejects_past_scheduled_at(self) -> None:+ past = (datetime.now(UTC) - timedelta(days=1)).isoformat()+ response = self.client.post(self._url(), self._payload(scheduled_at=past))+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_update_completed_one_off_title_allowed(self) -> None:+ reminder = Reminder.objects.create(+ organization=self.organization,+ created_by=self.user,+ title="old",+ status=Reminder.Status.COMPLETED,+ scheduled_at=datetime.now(UTC) - timedelta(days=1),+ next_fire_at=datetime.now(UTC) - timedelta(days=1),+ )+ response = self.client.patch(self._url(f"{reminder.id}/"), {"title": "new"})+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ reminder.refresh_from_db()+ self.assertEqual(reminder.title, "new")+ self.assertEqual(reminder.status, Reminder.Status.COMPLETED)++ def test_rejects_resource_without_team(self) -> None:+ response = self.client.post(+ self._url(),+ self._payload(resource_type="dashboard", resource_id="99999"),+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_rejects_missing_resource_in_team(self) -> None:+ response = self.client.post(+ self._url(),+ self._payload(team=self.team.id, resource_type="dashboard", resource_id="99999"),+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_rejects_invalid_timezone(self) -> None:+ response = self.client.post(self._url(), self._payload(timezone="Mars/Phobos"))+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_rejects_organization_user_is_not_member_of(self) -> None:+ other_org = Organization.objects.create(name="Other")+ response = self.client.post(self._url(), self._payload(organization=str(other_org.id)))+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_rejects_team_in_other_organization(self) -> None:+ other_org = Organization.objects.create(name="Other")+ other_team = Team.objects.create(organization=other_org, name="Other team")+ response = self.client.post(self._url(), self._payload(team=other_team.id))+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_active_cap_enforced(self) -> None:+ for i in range(50):+ Reminder.objects.create(+ organization=self.organization,+ created_by=self.user,+ title=f"r{i}",+ scheduled_at=datetime.now(UTC) + timedelta(days=1),+ next_fire_at=datetime.now(UTC) + timedelta(days=1),+ )+ response = self.client.post(self._url(), self._payload(title="over"))+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_list_only_returns_own_reminders(self) -> None:+ other = self._create_user("[email protected]")+ Reminder.objects.create(+ organization=self.organization,+ created_by=other,+ title="theirs",+ scheduled_at=datetime.now(UTC) + timedelta(days=1),+ next_fire_at=datetime.now(UTC) + timedelta(days=1),+ )+ Reminder.objects.create(+ organization=self.organization,+ created_by=self.user,+ title="mine",+ scheduled_at=datetime.now(UTC) + timedelta(days=1),+ next_fire_at=datetime.now(UTC) + timedelta(days=1),+ )+ response = self.client.get(self._url())+ titles = [r["title"] for r in response.json()["results"]]+ self.assertEqual(titles, ["mine"])++ def test_cannot_get_others_reminder(self) -> None:+ other = self._create_user("[email protected]")+ reminder = Reminder.objects.create(+ organization=self.organization,+ created_by=other,+ title="theirs",+ scheduled_at=datetime.now(UTC) + timedelta(days=1),+ next_fire_at=datetime.now(UTC) + timedelta(days=1),+ )+ response = self.client.get(self._url(f"{reminder.id}/"))+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ def test_delete_soft_deletes(self) -> None:+ reminder = Reminder.objects.create(+ organization=self.organization,+ created_by=self.user,+ title="mine",+ scheduled_at=datetime.now(UTC) + timedelta(days=1),+ next_fire_at=datetime.now(UTC) + timedelta(days=1),+ )+ response = self.client.delete(self._url(f"{reminder.id}/"))+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ reminder.refresh_from_db()+ self.assertTrue(reminder.deleted)diff --git a/products/reminders/backend/apps.py b/products/reminders/backend/apps.pynew file mode 100644index 000000000000..eae3350a2154--- /dev/null+++ b/products/reminders/backend/apps.py@@ -0,0 +1,7 @@+from django.apps import AppConfig+++class RemindersConfig(AppConfig):+ default_auto_field = "django.db.models.BigAutoField"+ name = "products.reminders.backend"+ label = "reminders"diff --git a/products/reminders/backend/constants.py b/products/reminders/backend/constants.pynew file mode 100644index 000000000000..0a01dd18f4e8--- /dev/null+++ b/products/reminders/backend/constants.py@@ -0,0 +1,33 @@+from django.db import models++from posthog.session_recordings.models.session_recording import SessionRecording++from products.dashboards.backend.models.dashboard import Dashboard+from products.error_tracking.backend.models import ErrorTrackingIssue+from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.notebooks.backend.models import Notebook+from products.product_analytics.backend.models.insight import Insight+from products.surveys.backend.models import Survey++# resource_type -> (model, lookup_field, frontend_path_segment)+# lookup_field is the column used to match resource_id within the team.+# frontend_path_segment builds the notification deep link: /project/{project_id}/{segment}/{resource_id}+RESOURCE_MODELS: dict[str, tuple[type[models.Model], str, str]] = {+ "dashboard": (Dashboard, "pk", "dashboard"),+ "insight": (Insight, "short_id", "insights"),+ "experiment": (Experiment, "pk", "experiments"),+ "feature_flag": (FeatureFlag, "pk", "feature_flags"),+ "survey": (Survey, "pk", "surveys"),+ "notebook": (Notebook, "short_id", "notebooks"),+ "replay": (SessionRecording, "session_id", "replay"),+ "error_tracking": (ErrorTrackingIssue, "pk", "error_tracking"),+}++RESOURCE_TYPES: tuple[str, ...] = tuple(RESOURCE_MODELS.keys())++# Max reminders a single user may have in the `active` status per team.+MAX_ACTIVE_REMINDERS_PER_USER = 50++# A schedule may fire at most this many times in any 24h window.+MAX_FIRES_PER_DAY = 4diff --git a/products/reminders/backend/firing.py b/products/reminders/backend/firing.pynew file mode 100644index 000000000000..e2c8e44b2d3e--- /dev/null+++ b/products/reminders/backend/firing.py@@ -0,0 +1,132 @@+from datetime import datetime++from django.db import OperationalError, transaction+from django.utils import timezone++import structlog++from posthog.exceptions_capture import capture_exception++from products.notifications.backend.facade.api import (+ NotificationData,+ NotificationType,+ Priority,+ TargetType,+ create_notification,+)+from products.reminders.backend.constants import RESOURCE_MODELS+from products.reminders.backend.models import Reminder+from products.reminders.backend.scheduling import compute_next_fire_at, resolve_timezone++logger = structlog.get_logger(__name__)++MAX_RETRY_ATTEMPTS = 5+MAX_CATCHUP_ITERATIONS = 1000+++def _build_source_url(reminder: Reminder) -> str:+ if reminder.team is None or not (reminder.resource_type and reminder.resource_id):+ return ""+ mapping = RESOURCE_MODELS.get(reminder.resource_type)+ if not mapping:+ return ""+ _, _, segment = mapping+ return f"/project/{reminder.team.project_id}/{segment}/{reminder.resource_id}"+++def _fire(reminder: Reminder) -> None:+ if reminder.team_id is not None:+ data = NotificationData(+ team_id=reminder.team_id,+ notification_type=NotificationType.REMINDER,+ priority=Priority.CRITICAL,+ title=reminder.title,+ body=reminder.message,+ target_type=TargetType.USER,+ target_id=str(reminder.created_by_id),+ source_url=_build_source_url(reminder),+ )+ else:+ data = NotificationData(+ organization_id=reminder.organization_id,+ notification_type=NotificationType.REMINDER,+ priority=Priority.CRITICAL,+ title=reminder.title,+ body=reminder.message,+ target_type=TargetType.USER,+ target_id=str(reminder.created_by_id),+ source_url="",+ )+ create_notification(data)+++def _advance(reminder: Reminder, now: datetime) -> None:+ if not (reminder.recurrence_interval or reminder.cron_expression):+ reminder.status = Reminder.Status.COMPLETED+ return+ tz = resolve_timezone(reminder.timezone)+ assert reminder.next_fire_at is not None # due rows are filtered on next_fire_at__lte+ next_fire = compute_next_fire_at(+ reminder.next_fire_at,+ interval=reminder.recurrence_interval,+ cron_expression=reminder.cron_expression,+ tz=tz,+ )+ iterations = 0+ while next_fire <= now and iterations < MAX_CATCHUP_ITERATIONS:+ next_fire = compute_next_fire_at(+ next_fire, interval=reminder.recurrence_interval, cron_expression=reminder.cron_expression, tz=tz+ )+ iterations += 1+ if reminder.end_date and next_fire > reminder.end_date:+ reminder.status = Reminder.Status.COMPLETED+ else:+ reminder.next_fire_at = next_fire+++def process_due_reminders() -> None:+ try:+ with transaction.atomic():+ due = (+ Reminder.objects.filter(status=Reminder.Status.ACTIVE, deleted=False, next_fire_at__lte=timezone.now())+ .select_related("team", "organization", "created_by")+ .select_for_update(nowait=True, of=("self",))+ .order_by("next_fire_at")[:10000]+ )+ for reminder in due:+ now = timezone.now()+ if reminder.created_by_id is None:+ reminder.status = Reminder.Status.COMPLETED+ reminder.last_error = "Reminder has no owner (creator was deleted)."+ reminder.save(update_fields=["status", "last_error", "updated_at"])+ continue+ if (+ reminder.end_date+ and reminder.end_date <= now+ and (reminder.recurrence_interval or reminder.cron_expression)+ ):+ reminder.status = Reminder.Status.COMPLETED+ reminder.save(update_fields=["status", "updated_at"])+ continue+ try:+ _fire(reminder)+ reminder.last_fired_at = now+ reminder.failure_count = 0+ reminder.last_error = None+ _advance(reminder, now)+ reminder.save()+ except Exception as e:+ reminder.failure_count += 1+ reminder.last_error = str(e)+ if reminder.failure_count >= MAX_RETRY_ATTEMPTS:+ if reminder.recurrence_interval or reminder.cron_expression:+ _advance(reminder, now)+ # Give the next window a fresh retry budget, like a successful fire does.+ reminder.failure_count = 0+ reminder.last_error = None+ else:+ reminder.status = Reminder.Status.ERRORED+ reminder.save()+ capture_exception(e)+ except OperationalError:+ passdiff --git a/products/reminders/backend/migrations/0001_initial.py b/products/reminders/backend/migrations/0001_initial.pynew file mode 100644index 000000000000..fbc705098cf4--- /dev/null+++ b/products/reminders/backend/migrations/0001_initial.py@@ -0,0 +1,140 @@+# Generated by Django 5.2.14 on 2026-06-15 14:58++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ initial = True++ dependencies = [+ ("posthog", "1219_filesystemfoldercontextgeneration"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.CreateModel(+ name="Reminder",+ fields=[+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("title", models.CharField(max_length=255)),+ ("message", models.TextField(blank=True, default="")),+ (+ "resource_type",+ models.CharField(blank=True, max_length=50, null=True),+ ),+ (+ "resource_id",+ models.CharField(blank=True, max_length=200, null=True),+ ),+ ("scheduled_at", models.DateTimeField(blank=True, null=True)),+ (+ "recurrence_interval",+ models.CharField(+ blank=True,+ choices=[+ ("daily", "Daily"),+ ("weekly", "Weekly"),+ ("monthly", "Monthly"),+ ("yearly", "Yearly"),+ ],+ max_length=20,+ null=True,+ ),+ ),+ (+ "cron_expression",+ models.CharField(blank=True, max_length=100, null=True),+ ),+ ("timezone", models.CharField(default="UTC", max_length=64)),+ ("end_date", models.DateTimeField(blank=True, null=True)),+ ("next_fire_at", models.DateTimeField(blank=True, null=True)),+ ("last_fired_at", models.DateTimeField(blank=True, null=True)),+ ("failure_count", models.IntegerField(default=0)),+ ("last_error", models.TextField(blank=True, null=True)),+ (+ "status",+ models.CharField(+ choices=[+ ("active", "Active"),+ ("completed", "Completed"),+ ("errored", "Errored"),+ ],+ default="active",+ max_length=20,+ ),+ ),+ ("deleted", models.BooleanField(default=False)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "organization",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.organization",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ ],+ options={+ "indexes": [+ models.Index(+ condition=models.Q(("deleted", False), ("status", "active")),+ fields=["next_fire_at"],+ name="reminders_active_due_idx",+ )+ ],+ "constraints": [+ models.CheckConstraint(+ condition=models.Q(+ models.Q(+ ("cron_expression__isnull", True),+ ("recurrence_interval__isnull", True),+ ("scheduled_at__isnull", False),+ ),+ models.Q(+ ("cron_expression__isnull", True),+ ("recurrence_interval__isnull", False),+ ("scheduled_at__isnull", True),+ ),+ models.Q(+ ("cron_expression__isnull", False),+ ("recurrence_interval__isnull", True),+ ("scheduled_at__isnull", True),+ ),+ _connector="OR",+ ),+ name="reminders_schedule_exactly_one",+ )+ ],+ },+ ),+ ]diff --git a/products/reminders/backend/migrations/__init__.py b/products/reminders/backend/migrations/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/reminders/backend/migrations/max_migration.txt b/products/reminders/backend/migrations/max_migration.txtnew file mode 100644index 000000000000..cbab66dde92a--- /dev/null+++ b/products/reminders/backend/migrations/max_migration.txt@@ -0,0 +1 @@+0001_initialdiff --git a/products/reminders/backend/models/__init__.py b/products/reminders/backend/models/__init__.pynew file mode 100644index 000000000000..3ac8501cc965--- /dev/null+++ b/products/reminders/backend/models/__init__.py@@ -0,0 +1,3 @@+from products.reminders.backend.models.reminder import Reminder++__all__ = ["Reminder"]diff --git a/products/reminders/backend/models/reminder.py b/products/reminders/backend/models/reminder.pynew file mode 100644index 000000000000..277bc75d896c--- /dev/null+++ b/products/reminders/backend/models/reminder.py@@ -0,0 +1,62 @@+from django.db import models+from django.db.models import Q++from posthog.models.utils import CreatedMetaFields, RootTeamMixin, UpdatedMetaFields, UUIDModel+++class Reminder(RootTeamMixin, CreatedMetaFields, UpdatedMetaFields, UUIDModel):+ class Status(models.TextChoices):+ ACTIVE = "active", "Active"+ COMPLETED = "completed", "Completed"+ ERRORED = "errored", "Errored"++ class RecurrenceInterval(models.TextChoices):+ DAILY = "daily", "Daily"+ WEEKLY = "weekly", "Weekly"+ MONTHLY = "monthly", "Monthly"+ YEARLY = "yearly", "Yearly"++ organization = models.ForeignKey("posthog.Organization", on_delete=models.CASCADE)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, null=True, blank=True)++ title = models.CharField(max_length=255)+ message = models.TextField(blank=True, default="")++ resource_type = models.CharField(max_length=50, null=True, blank=True)+ resource_id = models.CharField(max_length=200, null=True, blank=True)++ scheduled_at = models.DateTimeField(null=True, blank=True)+ recurrence_interval = models.CharField(max_length=20, choices=RecurrenceInterval.choices, null=True, blank=True)+ cron_expression = models.CharField(max_length=100, null=True, blank=True)+ timezone = models.CharField(max_length=64, default="UTC")+ end_date = models.DateTimeField(null=True, blank=True)++ next_fire_at = models.DateTimeField(null=True, blank=True)+ last_fired_at = models.DateTimeField(null=True, blank=True)+ failure_count = models.IntegerField(default=0)+ last_error = models.TextField(null=True, blank=True)++ status = models.CharField(max_length=20, choices=Status.choices, default=Status.ACTIVE)+ deleted = models.BooleanField(default=False)++ class Meta:+ indexes = [+ models.Index(+ fields=["next_fire_at"],+ name="reminders_active_due_idx",+ condition=Q(status="active", deleted=False),+ ),+ ]+ constraints = [+ models.CheckConstraint(+ name="reminders_schedule_exactly_one",+ condition=(+ Q(scheduled_at__isnull=False, recurrence_interval__isnull=True, cron_expression__isnull=True)+ | Q(scheduled_at__isnull=True, recurrence_interval__isnull=False, cron_expression__isnull=True)+ | Q(scheduled_at__isnull=True, recurrence_interval__isnull=True, cron_expression__isnull=False)+ ),+ ),+ ]++ def __str__(self) -> str:+ return f"{self.title} (org={self.organization_id}, team={self.team_id}, user={self.created_by_id})"diff --git a/products/reminders/backend/routes.py b/products/reminders/backend/routes.pynew file mode 100644index 000000000000..3969ce86e4e9--- /dev/null+++ b/products/reminders/backend/routes.py@@ -0,0 +1,7 @@+from posthog.api.routing import RouterRegistry++from products.reminders.backend.api import reminder+++def register_routes(routers: RouterRegistry) -> None:+ routers.root.register(r"reminders", reminder.ReminderViewSet, "reminders")diff --git a/products/reminders/backend/scheduling.py b/products/reminders/backend/scheduling.pynew file mode 100644index 000000000000..90f3e8ca2829--- /dev/null+++ b/products/reminders/backend/scheduling.py@@ -0,0 +1,70 @@+from datetime import UTC, datetime, timedelta+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError++from croniter import croniter # type: ignore[import-untyped,unused-ignore]+from dateutil.relativedelta import relativedelta++from products.reminders.backend.constants import MAX_FIRES_PER_DAY++UTC_ZONE = ZoneInfo("UTC")+++def resolve_timezone(tz_name: str | None) -> ZoneInfo:+ if not tz_name:+ return UTC_ZONE+ try:+ return ZoneInfo(tz_name)+ except ZoneInfoNotFoundError:+ return UTC_ZONE+++def _next_interval(current: datetime, interval: str) -> datetime:+ if interval == "daily":+ return current + relativedelta(days=1)+ if interval == "weekly":+ return current + relativedelta(weeks=1)+ if interval == "monthly":+ return current + relativedelta(months=1)+ if interval == "yearly":+ return current + relativedelta(years=1)+ raise ValueError(f"Unknown recurrence interval: {interval}")+++def _next_cron(cron_expression: str, current: datetime, tz: ZoneInfo) -> datetime:+ reference = current.astimezone(tz)+ return croniter(cron_expression, reference).get_next(datetime).astimezone(UTC)+++def compute_next_fire_at(+ current: datetime,+ *,+ interval: str | None,+ cron_expression: str | None,+ tz: ZoneInfo,+) -> datetime:+ if cron_expression:+ return _next_cron(cron_expression, current, tz)+ if interval:+ return _next_interval(current, interval)+ raise ValueError("Recurring reminder requires interval or cron_expression")+++def exceeds_daily_frequency_cap(cron_expression: str) -> bool:+ # Count fires across a representative 24h window for every weekday, so a cron pinned+ # to a single day (e.g. "* * * * 2") can't slip past the cap by avoiding the samples.+ week_start = datetime(2026, 6, 15, 0, 0, tzinfo=UTC) # Monday+ for offset in range(7):+ start = week_start + timedelta(days=offset)+ window_end = start + timedelta(days=1)+ # Seed just before the window so a fire landing exactly on `start` is counted+ # (croniter.get_next returns the first fire strictly after the seed).+ itr = croniter(cron_expression, start - timedelta(microseconds=1))+ fires = 0+ while True:+ nxt = itr.get_next(datetime)+ if nxt >= window_end:+ break+ fires += 1+ if fires > MAX_FIRES_PER_DAY:+ return True+ return Falsediff --git a/products/reminders/backend/tasks.py b/products/reminders/backend/tasks.pynew file mode 100644index 000000000000..5f72d4e02dcd--- /dev/null+++ b/products/reminders/backend/tasks.py@@ -0,0 +1,8 @@+from celery import shared_task+++@shared_task(ignore_result=True)+def process_due_reminders() -> None:+ from products.reminders.backend.firing import process_due_reminders as _process # noqa: PLC0415++ _process()diff --git a/products/reminders/backend/test/__init__.py b/products/reminders/backend/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/reminders/backend/test/test_firing.py b/products/reminders/backend/test/test_firing.pynew file mode 100644index 000000000000..f6c64ff3b514--- /dev/null+++ b/products/reminders/backend/test/test_firing.py@@ -0,0 +1,130 @@+from datetime import UTC, datetime++from freezegun import freeze_time+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from products.reminders.backend.firing import process_due_reminders+from products.reminders.backend.models import Reminder+++class TestProcessDueReminders(BaseTest):+ @freeze_time("2026-06-15T09:00:00Z")+ @patch("products.reminders.backend.firing.create_notification")+ def test_one_off_fires_and_completes(self, mock_create: MagicMock) -> None:+ reminder = Reminder.objects.create(+ organization=self.organization,+ team=self.team,+ created_by=self.user,+ title="Check funnel",+ scheduled_at=datetime(2026, 6, 15, 8, 59, tzinfo=UTC),+ next_fire_at=datetime(2026, 6, 15, 8, 59, tzinfo=UTC),+ )+ process_due_reminders()+ mock_create.assert_called_once()+ reminder.refresh_from_db()+ self.assertEqual(reminder.status, Reminder.Status.COMPLETED)+ self.assertEqual(reminder.last_fired_at, datetime(2026, 6, 15, 9, 0, tzinfo=UTC))++ @freeze_time("2026-06-15T09:00:00Z")+ @patch("products.reminders.backend.firing.create_notification")+ def test_recurring_advances_and_stays_active(self, mock_create: MagicMock) -> None:+ reminder = Reminder.objects.create(+ organization=self.organization,+ team=self.team,+ created_by=self.user,+ title="Daily",+ recurrence_interval="daily",+ next_fire_at=datetime(2026, 6, 15, 8, 59, tzinfo=UTC),+ )+ process_due_reminders()+ reminder.refresh_from_db()+ self.assertEqual(reminder.status, Reminder.Status.ACTIVE)+ self.assertEqual(reminder.next_fire_at, datetime(2026, 6, 16, 8, 59, tzinfo=UTC))++ @freeze_time("2026-06-15T09:00:00Z")+ @patch("products.reminders.backend.firing.create_notification")+ def test_not_yet_due_is_skipped(self, mock_create: MagicMock) -> None:+ Reminder.objects.create(+ organization=self.organization,+ team=self.team,+ created_by=self.user,+ title="Later",+ scheduled_at=datetime(2026, 6, 15, 10, 0, tzinfo=UTC),+ next_fire_at=datetime(2026, 6, 15, 10, 0, tzinfo=UTC),+ )+ process_due_reminders()+ mock_create.assert_not_called()++ @freeze_time("2026-06-15T09:00:00Z")+ @patch("products.reminders.backend.firing.create_notification")+ def test_recurring_catch_up_fires_once(self, mock_create: MagicMock) -> None:+ reminder = Reminder.objects.create(+ organization=self.organization,+ team=self.team,+ created_by=self.user,+ title="Daily",+ recurrence_interval="daily",+ next_fire_at=datetime(2026, 6, 10, 8, 59, tzinfo=UTC),+ )+ process_due_reminders()+ mock_create.assert_called_once()+ reminder.refresh_from_db()+ assert reminder.next_fire_at is not None+ self.assertGreater(reminder.next_fire_at, datetime(2026, 6, 15, 9, 0, tzinfo=UTC))++ @freeze_time("2026-06-15T09:00:00Z")+ @patch("products.reminders.backend.firing.create_notification", side_effect=RuntimeError("boom"))+ def test_one_off_errors_after_retries(self, mock_create: MagicMock) -> None:+ reminder = Reminder.objects.create(+ organization=self.organization,+ team=self.team,+ created_by=self.user,+ title="Boom",+ scheduled_at=datetime(2026, 6, 15, 8, 59, tzinfo=UTC),+ next_fire_at=datetime(2026, 6, 15, 8, 59, tzinfo=UTC),+ failure_count=4,+ )+ process_due_reminders()+ reminder.refresh_from_db()+ self.assertEqual(reminder.status, Reminder.Status.ERRORED)+ self.assertIn("boom", reminder.last_error or "")++ @freeze_time("2026-06-15T09:00:00Z")+ @patch("products.reminders.backend.firing.create_notification", side_effect=RuntimeError("boom"))+ def test_recurring_resets_retry_budget_after_advance(self, mock_create: MagicMock) -> None:+ reminder = Reminder.objects.create(+ organization=self.organization,+ team=self.team,+ created_by=self.user,+ title="Daily boom",+ recurrence_interval="daily",+ next_fire_at=datetime(2026, 6, 15, 8, 59, tzinfo=UTC),+ failure_count=4,+ )+ process_due_reminders()+ reminder.refresh_from_db()+ # Threshold hit -> advance to the next window with a fresh budget, not stuck at >= max.+ self.assertEqual(reminder.status, Reminder.Status.ACTIVE)+ self.assertEqual(reminder.failure_count, 0)+ self.assertIsNone(reminder.last_error)+ self.assertEqual(reminder.next_fire_at, datetime(2026, 6, 16, 8, 59, tzinfo=UTC))++ @freeze_time("2026-06-15T09:00:00Z")+ @patch("products.reminders.backend.firing.create_notification")+ def test_org_level_fires_and_completes(self, mock_create: MagicMock) -> None:+ reminder = Reminder.objects.create(+ organization=self.organization,+ team=None,+ created_by=self.user,+ title="Org-wide",+ scheduled_at=datetime(2026, 6, 15, 8, 59, tzinfo=UTC),+ next_fire_at=datetime(2026, 6, 15, 8, 59, tzinfo=UTC),+ )+ process_due_reminders()+ mock_create.assert_called_once()+ data = mock_create.call_args.args[0]+ self.assertEqual(data.organization_id, self.organization.id)+ self.assertIsNone(data.team_id)+ reminder.refresh_from_db()+ self.assertEqual(reminder.status, Reminder.Status.COMPLETED)diff --git a/products/reminders/backend/test/test_scheduling.py b/products/reminders/backend/test/test_scheduling.pynew file mode 100644index 000000000000..9ba0f2fa5604--- /dev/null+++ b/products/reminders/backend/test/test_scheduling.py@@ -0,0 +1,60 @@+from datetime import UTC, datetime+from zoneinfo import ZoneInfo++from django.test import SimpleTestCase++from parameterized import parameterized++from products.reminders.backend.scheduling import compute_next_fire_at, exceeds_daily_frequency_cap, resolve_timezone+++class TestComputeNextFireAt(SimpleTestCase):+ @parameterized.expand(+ [+ ("daily", datetime(2026, 6, 15, 9, 0, tzinfo=UTC), datetime(2026, 6, 16, 9, 0, tzinfo=UTC)),+ ("weekly", datetime(2026, 6, 15, 9, 0, tzinfo=UTC), datetime(2026, 6, 22, 9, 0, tzinfo=UTC)),+ ]+ )+ def test_interval_advances(self, interval: str, current: datetime, expected: datetime) -> None:+ result = compute_next_fire_at(current, interval=interval, cron_expression=None, tz=ZoneInfo("UTC"))+ self.assertEqual(result, expected)++ def test_cron_resolves_in_timezone(self) -> None:+ # 9am weekdays in New York (UTC-4 in June) => 13:00 UTC+ current = datetime(2026, 6, 15, 13, 0, tzinfo=UTC) # a Monday+ result = compute_next_fire_at(+ current, interval=None, cron_expression="0 9 * * 1-5", tz=ZoneInfo("America/New_York")+ )+ self.assertEqual(result, datetime(2026, 6, 16, 13, 0, tzinfo=UTC))+++class TestDailyFrequencyCap(SimpleTestCase):+ @parameterized.expand(+ [+ ("0 9 * * *", False),+ ("0 9,12,15,18 * * *", False),+ ("0 9,12,15,18,21 * * *", True),+ ("*/30 * * * *", True),+ ("* * * * *", True),+ ("0 0,6,12,18 * * *", False), # 4 fires including midnight => at cap, allowed+ ("0 0,6,12,18,23 * * *", True), # 5 fires including midnight => over cap, rejected+ ("* * * * 2", True), # every minute, Tuesdays only => must not slip the cap+ ("*/10 * * * 4", True), # every 10 min, Thursdays only => over cap+ ("0 9 * * 3", False), # once on Wednesdays => within cap+ ]+ )+ def test_cron_frequency(self, cron_expression: str, expected_exceeds: bool) -> None:+ self.assertEqual(exceeds_daily_frequency_cap(cron_expression), expected_exceeds)+++class TestResolveTimezone(SimpleTestCase):+ @parameterized.expand(+ [+ (None, "UTC"),+ ("", "UTC"),+ ("Mars/Phobos", "UTC"),+ ("America/New_York", "America/New_York"),+ ]+ )+ def test_resolve_timezone(self, tz_name: str | None, expected: str) -> None:+ self.assertEqual(resolve_timezone(tz_name), ZoneInfo(expected))diff --git a/products/reminders/frontend/generated/api.schemas.ts b/products/reminders/frontend/generated/api.schemas.tsnew file mode 100644index 000000000000..c1b13ca75d11--- /dev/null+++ b/products/reminders/frontend/generated/api.schemas.ts@@ -0,0 +1,245 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+/**+ * * `daily` - Daily+ * * `weekly` - Weekly+ * * `monthly` - Monthly+ * * `yearly` - Yearly+ */+export type RecurrenceIntervalEnumApi = (typeof RecurrenceIntervalEnumApi)[keyof typeof RecurrenceIntervalEnumApi]++export const RecurrenceIntervalEnumApi = {+ Daily: 'daily',+ Weekly: 'weekly',+ Monthly: 'monthly',+ Yearly: 'yearly',+} as const++export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]++export const BlankEnumApi = {+ '': '',+} as const++/**+ * * `active` - Active+ * * `completed` - Completed+ * * `errored` - Errored+ */+export type ReminderStatusEnumApi = (typeof ReminderStatusEnumApi)[keyof typeof ReminderStatusEnumApi]++export const ReminderStatusEnumApi = {+ Active: 'active',+ Completed: 'completed',+ Errored: 'errored',+} as const++/**+ * * `engineering` - Engineering+ * * `data` - Data+ * * `product` - Product Management+ * * `founder` - Founder+ * * `leadership` - Leadership+ * * `marketing` - Marketing+ * * `sales` - Sales / Success+ * * `other` - Other+ */+export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]++export const RoleAtOrganizationEnumApi = {+ Engineering: 'engineering',+ Data: 'data',+ Product: 'product',+ Founder: 'founder',+ Leadership: 'leadership',+ Marketing: 'marketing',+ Sales: 'sales',+ Other: 'other',+} as const++/**+ * @nullable+ */+export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null++export interface UserBasicApi {+ readonly id: number+ readonly uuid: string+ /**+ * @maxLength 200+ * @nullable+ */+ distinct_id?: string | null+ /** @maxLength 150 */+ first_name?: string+ /** @maxLength 150 */+ last_name?: string+ /** @maxLength 254 */+ email: string+ /** @nullable */+ is_email_verified?: boolean | null+ /** @nullable */+ readonly hedgehog_config: UserBasicApiHedgehogConfig+ role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null+}++export interface ReminderApi {+ readonly id: string+ /** ID of the organization this reminder belongs to. You must be a member of it. */+ organization: string+ /**+ * Optional ID of the project this reminder is scoped to. Required when targeting a specific resource. Must belong to the chosen organization.+ * @nullable+ */+ team?: number | null+ /**+ * Short text shown as the notification title when the reminder fires.+ * @maxLength 255+ */+ title: string+ /** Optional longer body for the notification. */+ message?: string+ /**+ * Optional PostHog resource this reminder is about. One of: dashboard, insight, experiment, feature_flag, survey, notebook, replay, error_tracking. Resources are project-scoped, so a team must be set when this is provided.+ * @maxLength 50+ * @nullable+ */+ resource_type?: string | null+ /**+ * ID of the referenced resource; must exist in the chosen project.+ * @maxLength 200+ * @nullable+ */+ resource_id?: string | null+ /**+ * For a one-off reminder: when it should fire (ISO 8601, future).+ * @nullable+ */+ scheduled_at?: string | null+ /** For a recurring reminder: daily, weekly, monthly, or yearly.+ *+ * * `daily` - Daily+ * * `weekly` - Weekly+ * * `monthly` - Monthly+ * * `yearly` - Yearly */+ recurrence_interval?: RecurrenceIntervalEnumApi | BlankEnumApi | null+ /**+ * For a recurring reminder: a 5-field cron expression (e.g. '0 9 * * 1' = Mondays 9am). May fire at most 4 times per day. Mutually exclusive with recurrence_interval.+ * @maxLength 100+ * @nullable+ */+ cron_expression?: string | null+ /**+ * IANA timezone the schedule resolves in (e.g. 'America/New_York'). Defaults to the project timezone when a team is set, otherwise UTC.+ * @maxLength 64+ */+ timezone?: string+ /**+ * Optional: recurring reminders stop (status=completed) after this time.+ * @nullable+ */+ end_date?: string | null+ /** @nullable */+ readonly next_fire_at: string | null+ /** @nullable */+ readonly last_fired_at: string | null+ readonly status: ReminderStatusEnumApi+ readonly created_by: UserBasicApi+ readonly created_at: string+ /** @nullable */+ readonly updated_at: string | null+}++export interface PaginatedReminderListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: ReminderApi[]+}++export interface PatchedReminderApi {+ readonly id?: string+ /** ID of the organization this reminder belongs to. You must be a member of it. */+ organization?: string+ /**+ * Optional ID of the project this reminder is scoped to. Required when targeting a specific resource. Must belong to the chosen organization.+ * @nullable+ */+ team?: number | null+ /**+ * Short text shown as the notification title when the reminder fires.+ * @maxLength 255+ */+ title?: string+ /** Optional longer body for the notification. */+ message?: string+ /**+ * Optional PostHog resource this reminder is about. One of: dashboard, insight, experiment, feature_flag, survey, notebook, replay, error_tracking. Resources are project-scoped, so a team must be set when this is provided.+ * @maxLength 50+ * @nullable+ */+ resource_type?: string | null+ /**+ * ID of the referenced resource; must exist in the chosen project.+ * @maxLength 200+ * @nullable+ */+ resource_id?: string | null+ /**+ * For a one-off reminder: when it should fire (ISO 8601, future).+ * @nullable+ */+ scheduled_at?: string | null+ /** For a recurring reminder: daily, weekly, monthly, or yearly.+ *+ * * `daily` - Daily+ * * `weekly` - Weekly+ * * `monthly` - Monthly+ * * `yearly` - Yearly */+ recurrence_interval?: RecurrenceIntervalEnumApi | BlankEnumApi | null+ /**+ * For a recurring reminder: a 5-field cron expression (e.g. '0 9 * * 1' = Mondays 9am). May fire at most 4 times per day. Mutually exclusive with recurrence_interval.+ * @maxLength 100+ * @nullable+ */+ cron_expression?: string | null+ /**+ * IANA timezone the schedule resolves in (e.g. 'America/New_York'). Defaults to the project timezone when a team is set, otherwise UTC.+ * @maxLength 64+ */+ timezone?: string+ /**+ * Optional: recurring reminders stop (status=completed) after this time.+ * @nullable+ */+ end_date?: string | null+ /** @nullable */+ readonly next_fire_at?: string | null+ /** @nullable */+ readonly last_fired_at?: string | null+ readonly status?: ReminderStatusEnumApi+ readonly created_by?: UserBasicApi+ readonly created_at?: string+ /** @nullable */+ readonly updated_at?: string | null+}++export type RemindersListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}diff --git a/products/reminders/frontend/generated/api.ts b/products/reminders/frontend/generated/api.tsnew file mode 100644index 000000000000..aa3259be9b8d--- /dev/null+++ b/products/reminders/frontend/generated/api.ts@@ -0,0 +1,124 @@+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * To modify these types, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import type { PaginatedReminderListApi, PatchedReminderApi, ReminderApi, RemindersListParams } from './api.schemas'++// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B++type WritableKeys<T> = {+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>+}[keyof T]++type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never++type Writable<T> = Pick<T, WritableKeys<T>>+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]+ ? {+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]+ }+ : DistributeReadOnlyOverUnions<T>++export const getRemindersListUrl = (params?: RemindersListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0 ? `/api/reminders/?${stringifiedParams}` : `/api/reminders/`+}++export const remindersList = async (+ params?: RemindersListParams,+ options?: RequestInit+): Promise<PaginatedReminderListApi> => {+ return apiMutator<PaginatedReminderListApi>(getRemindersListUrl(params), {+ ...options,+ method: 'GET',+ })+}++export const getRemindersCreateUrl = () => {+ return `/api/reminders/`+}++export const remindersCreate = async (+ reminderApi: NonReadonly<ReminderApi>,+ options?: RequestInit+): Promise<ReminderApi> => {+ return apiMutator<ReminderApi>(getRemindersCreateUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(reminderApi),+ })+}++export const getRemindersRetrieveUrl = (id: string) => {+ return `/api/reminders/${id}/`+}++export const remindersRetrieve = async (id: string, options?: RequestInit): Promise<ReminderApi> => {+ return apiMutator<ReminderApi>(getRemindersRetrieveUrl(id), {+ ...options,+ method: 'GET',+ })+}++export const getRemindersUpdateUrl = (id: string) => {+ return `/api/reminders/${id}/`+}++export const remindersUpdate = async (+ id: string,+ reminderApi: NonReadonly<ReminderApi>,+ options?: RequestInit+): Promise<ReminderApi> => {+ return apiMutator<ReminderApi>(getRemindersUpdateUrl(id), {+ ...options,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(reminderApi),+ })+}++export const getRemindersPartialUpdateUrl = (id: string) => {+ return `/api/reminders/${id}/`+}++export const remindersPartialUpdate = async (+ id: string,+ patchedReminderApi?: NonReadonly<PatchedReminderApi>,+ options?: RequestInit+): Promise<ReminderApi> => {+ return apiMutator<ReminderApi>(getRemindersPartialUpdateUrl(id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedReminderApi),+ })+}++export const getRemindersDestroyUrl = (id: string) => {+ return `/api/reminders/${id}/`+}++export const remindersDestroy = async (id: string, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getRemindersDestroyUrl(id), {+ ...options,+ method: 'DELETE',+ })+}diff --git a/products/reminders/frontend/generated/api.zod.ts b/products/reminders/frontend/generated/api.zod.tsnew file mode 100644index 000000000000..2591574e2b9c--- /dev/null+++ b/products/reminders/frontend/generated/api.zod.ts@@ -0,0 +1,227 @@+/**+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.+ * To modify these schemas, update the Django serializers or views, then run:+ * hogli build:openapi+ * Questions or issues? #team-devex on Slack+ *+ * PostHog API - generated+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++export const remindersCreateBodyTitleMax = 255++export const remindersCreateBodyResourceTypeMax = 50++export const remindersCreateBodyResourceIdMax = 200++export const remindersCreateBodyCronExpressionMax = 100++export const remindersCreateBodyTimezoneMax = 64++export const RemindersCreateBody = /* @__PURE__ */ zod.object({+ organization: zod.uuid().describe('ID of the organization this reminder belongs to. You must be a member of it.'),+ team: zod+ .number()+ .nullish()+ .describe(+ 'Optional ID of the project this reminder is scoped to. Required when targeting a specific resource. Must belong to the chosen organization.'+ ),+ title: zod+ .string()+ .max(remindersCreateBodyTitleMax)+ .describe('Short text shown as the notification title when the reminder fires.'),+ message: zod.string().optional().describe('Optional longer body for the notification.'),+ resource_type: zod+ .string()+ .max(remindersCreateBodyResourceTypeMax)+ .nullish()+ .describe(+ 'Optional PostHog resource this reminder is about. One of: dashboard, insight, experiment, feature_flag, survey, notebook, replay, error_tracking. Resources are project-scoped, so a team must be set when this is provided.'+ ),+ resource_id: zod+ .string()+ .max(remindersCreateBodyResourceIdMax)+ .nullish()+ .describe('ID of the referenced resource; must exist in the chosen project.'),+ scheduled_at: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('For a one-off reminder: when it should fire (ISO 8601, future).'),+ recurrence_interval: zod+ .union([+ zod+ .enum(['daily', 'weekly', 'monthly', 'yearly'])+ .describe('\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly'),+ zod.enum(['']),+ zod.null(),+ ])+ .optional()+ .describe(+ 'For a recurring reminder: daily, weekly, monthly, or yearly.\n\n\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly'+ ),+ cron_expression: zod+ .string()+ .max(remindersCreateBodyCronExpressionMax)+ .nullish()+ .describe(+ "For a recurring reminder: a 5-field cron expression (e.g. '0 9 \* \* 1' = Mondays 9am). May fire at most 4 times per day. Mutually exclusive with recurrence_interval."+ ),+ timezone: zod+ .string()+ .max(remindersCreateBodyTimezoneMax)+ .optional()+ .describe(+ "IANA timezone the schedule resolves in (e.g. 'America\/New_York'). Defaults to the project timezone when a team is set, otherwise UTC."+ ),+ end_date: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('Optional: recurring reminders stop (status=completed) after this time.'),+})++export const remindersUpdateBodyTitleMax = 255++export const remindersUpdateBodyResourceTypeMax = 50++export const remindersUpdateBodyResourceIdMax = 200++export const remindersUpdateBodyCronExpressionMax = 100++export const remindersUpdateBodyTimezoneMax = 64++export const RemindersUpdateBody = /* @__PURE__ */ zod.object({+ organization: zod.uuid().describe('ID of the organization this reminder belongs to. You must be a member of it.'),+ team: zod+ .number()+ .nullish()+ .describe(+ 'Optional ID of the project this reminder is scoped to. Required when targeting a specific resource. Must belong to the chosen organization.'+ ),+ title: zod+ .string()+ .max(remindersUpdateBodyTitleMax)+ .describe('Short text shown as the notification title when the reminder fires.'),+ message: zod.string().optional().describe('Optional longer body for the notification.'),+ resource_type: zod+ .string()+ .max(remindersUpdateBodyResourceTypeMax)+ .nullish()+ .describe(+ 'Optional PostHog resource this reminder is about. One of: dashboard, insight, experiment, feature_flag, survey, notebook, replay, error_tracking. Resources are project-scoped, so a team must be set when this is provided.'+ ),+ resource_id: zod+ .string()+ .max(remindersUpdateBodyResourceIdMax)+ .nullish()+ .describe('ID of the referenced resource; must exist in the chosen project.'),+ scheduled_at: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('For a one-off reminder: when it should fire (ISO 8601, future).'),+ recurrence_interval: zod+ .union([+ zod+ .enum(['daily', 'weekly', 'monthly', 'yearly'])+ .describe('\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly'),+ zod.enum(['']),+ zod.null(),+ ])+ .optional()+ .describe(+ 'For a recurring reminder: daily, weekly, monthly, or yearly.\n\n\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly'+ ),+ cron_expression: zod+ .string()+ .max(remindersUpdateBodyCronExpressionMax)+ .nullish()+ .describe(+ "For a recurring reminder: a 5-field cron expression (e.g. '0 9 \* \* 1' = Mondays 9am). May fire at most 4 times per day. Mutually exclusive with recurrence_interval."+ ),+ timezone: zod+ .string()+ .max(remindersUpdateBodyTimezoneMax)+ .optional()+ .describe(+ "IANA timezone the schedule resolves in (e.g. 'America\/New_York'). Defaults to the project timezone when a team is set, otherwise UTC."+ ),+ end_date: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('Optional: recurring reminders stop (status=completed) after this time.'),+})++export const remindersPartialUpdateBodyTitleMax = 255++export const remindersPartialUpdateBodyResourceTypeMax = 50++export const remindersPartialUpdateBodyResourceIdMax = 200++export const remindersPartialUpdateBodyCronExpressionMax = 100++export const remindersPartialUpdateBodyTimezoneMax = 64++export const RemindersPartialUpdateBody = /* @__PURE__ */ zod.object({+ organization: zod+ .uuid()+ .optional()+ .describe('ID of the organization this reminder belongs to. You must be a member of it.'),+ team: zod+ .number()+ .nullish()+ .describe(+ 'Optional ID of the project this reminder is scoped to. Required when targeting a specific resource. Must belong to the chosen organization.'+ ),+ title: zod+ .string()+ .max(remindersPartialUpdateBodyTitleMax)+ .optional()+ .describe('Short text shown as the notification title when the reminder fires.'),+ message: zod.string().optional().describe('Optional longer body for the notification.'),+ resource_type: zod+ .string()+ .max(remindersPartialUpdateBodyResourceTypeMax)+ .nullish()+ .describe(+ 'Optional PostHog resource this reminder is about. One of: dashboard, insight, experiment, feature_flag, survey, notebook, replay, error_tracking. Resources are project-scoped, so a team must be set when this is provided.'+ ),+ resource_id: zod+ .string()+ .max(remindersPartialUpdateBodyResourceIdMax)+ .nullish()+ .describe('ID of the referenced resource; must exist in the chosen project.'),+ scheduled_at: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('For a one-off reminder: when it should fire (ISO 8601, future).'),+ recurrence_interval: zod+ .union([+ zod+ .enum(['daily', 'weekly', 'monthly', 'yearly'])+ .describe('\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly'),+ zod.enum(['']),+ zod.null(),+ ])+ .optional()+ .describe(+ 'For a recurring reminder: daily, weekly, monthly, or yearly.\n\n\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly'+ ),+ cron_expression: zod+ .string()+ .max(remindersPartialUpdateBodyCronExpressionMax)+ .nullish()+ .describe(+ "For a recurring reminder: a 5-field cron expression (e.g. '0 9 \* \* 1' = Mondays 9am). May fire at most 4 times per day. Mutually exclusive with recurrence_interval."+ ),+ timezone: zod+ .string()+ .max(remindersPartialUpdateBodyTimezoneMax)+ .optional()+ .describe(+ "IANA timezone the schedule resolves in (e.g. 'America\/New_York'). Defaults to the project timezone when a team is set, otherwise UTC."+ ),+ end_date: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('Optional: recurring reminders stop (status=completed) after this time.'),+})diff --git a/products/reminders/mcp/tools.yaml b/products/reminders/mcp/tools.yamlnew file mode 100644index 000000000000..f5e2922a3894--- /dev/null+++ b/products/reminders/mcp/tools.yaml@@ -0,0 +1,91 @@+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.+# The tool list and operation IDs are kept in sync automatically:+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all+#+# To enable a tool, set enabled: true and add required scopes + annotations.+# All other fields (title, description, enrich_url, etc.) are yours to configure.+category: Reminders+feature: reminders+url_prefix: /+ui_apps: {}+tools:+ reminder-create:+ operation: reminders_create+ enabled: true+ scopes:+ - user:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Create reminder+ description: >+ Create a reminder for yourself. Set organization (required) and optionally team to scope it to a project.+ Use a one-off reminder by setting scheduled_at (a future ISO 8601 time), or a recurring reminder by setting+ recurrence_interval (daily/weekly/monthly/yearly) OR cron_expression (5-field, max 4 fires/day). Set+ timezone to the user's IANA timezone so wall-clock times resolve correctly. Optionally attach a resource the+ reminder is about via resource_type + resource_id (e.g. a dashboard) — the notification will link to it.+ Reminders fire as in-app notifications when due. Proactively offer to create a reminder when the user+ mentions needing periodic checks, monitoring, recurring reviews, or follow-ups on a metric, dashboard, or+ task — reminders are how they get recurring in-app notifications without manual polling.+ exclude_params:+ - next_fire_at+ - last_fired_at+ - status+ reminder-delete:+ operation: reminders_destroy+ enabled: true+ scopes:+ - user:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: true+ title: Delete reminder+ description: Delete a reminder by ID. This stops it from firing.+ soft_delete: true+ reminder-get:+ operation: reminders_retrieve+ enabled: true+ scopes:+ - user:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Get reminder+ description: Get a single reminder by ID.+ reminder-update:+ operation: reminders_partial_update+ enabled: true+ scopes:+ - user:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: false+ title: Update reminder+ description: >+ Update a reminder's title, message, schedule, timezone, end date, or attached resource. Changing the+ schedule recomputes the next fire time.+ exclude_params:+ - next_fire_at+ - last_fired_at+ - status+ reminders-list:+ operation: reminders_list+ enabled: true+ scopes:+ - user:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List reminders+ description: >+ List your reminders in the current project, including their schedule, status (active/completed/errored), and+ next fire time.+ reminders-update:+ operation: reminders_update+ enabled: falsediff --git a/products/reminders/package.json b/products/reminders/package.jsonnew file mode 100644index 000000000000..c3e32a8071ff--- /dev/null+++ b/products/reminders/package.json@@ -0,0 +1,6 @@+{+ "name": "@posthog/products-reminders",+ "scripts": {+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"+ }+}diff --git a/products/reminders/product.yaml b/products/reminders/product.yamlnew file mode 100644index 000000000000..c51f58950bd1--- /dev/null+++ b/products/reminders/product.yaml@@ -0,0 +1,3 @@+name: Reminders+owners:+ - team-analytics-platformdiff --git a/products/reminders/skills/managing-reminders/SKILL.md b/products/reminders/skills/managing-reminders/SKILL.mdnew file mode 100644index 000000000000..8c54e1562deb--- /dev/null+++ b/products/reminders/skills/managing-reminders/SKILL.md@@ -0,0 +1,141 @@+---+name: managing-reminders+description: 'Create and manage PostHog reminders — private, human-paced nudges that fire as in-app notifications on a schedule, optionally linked to a PostHog resource. Use when the user says "remind me to…", wants a one-off or recurring nudge (daily/weekly/monthly/yearly, a cron schedule, or a specific date/time), wants to be reminded to look at a dashboard, insight, experiment, feature flag, survey, notebook, replay, or error, or wants to list, change, or cancel their reminders. Covers when to pick a reminder over an alert or subscription, the one-off vs recurring vs cron schedule field mappings, timezones, and attaching a resource.'+---++# Managing reminders++This skill guides you through creating and managing PostHog reminders.+A reminder is a private, human-paced nudge to yourself: it fires an in-app notification+on a schedule, with no condition attached. It can optionally link to a PostHog resource.++## When to use this skill++Use this skill when the user:++- Says "remind me to…", "nudge me", "ping me", or "don't let me forget"+- Wants a one-off reminder at a specific date/time+- Wants a recurring reminder (every day, weekly, every Monday, weekdays, monthly, etc.)+- Wants to be reminded to review a specific dashboard, insight, experiment, flag, survey, notebook, replay, or error+- Wants to see, change, or cancel reminders they have set++## Reminder vs alert vs subscription++These three look similar but solve different jobs. Pick the right one:++- **Reminder** — a human-paced nudge to yourself with **no condition**. It just fires an+ in-app notification on a schedule ("remind me to review the launch dashboard every Monday").+ If the user says **"remind me to…"**, it is a reminder.+- **Alert** — watches an insight's metric on a schedule and notifies only when a+ **threshold or anomaly condition is met** ("tell me if signups drop below 100").+- **Subscription** — delivers an insight or dashboard **export/snapshot** on a schedule via+ email, Slack, or webhook ("email me this dashboard every morning").++If there is a condition to evaluate, it is an alert. If there is an export to deliver, it is a+subscription. If it is just a timed nudge to a person, it is a reminder.++## Scheduling shapes++A reminder uses **exactly one** of `scheduled_at`, `recurrence_interval`, or `cron_expression`.+Providing zero or more than one is rejected.++### One-off++Set `scheduled_at` to a future ISO 8601 timestamp. The reminder fires once, then becomes `completed`.++| User says | Field |+| --------------------------- | ---------------------------------------------------- |+| "remind me tomorrow at 3pm" | `scheduled_at: <tomorrow 15:00 in the user's tz>` |+| "remind me on Jan 5 at 9am" | `scheduled_at: "2026-01-05T09:00:00"` (+ `timezone`) |++### Preset recurring++Set `recurrence_interval` to one of `daily`, `weekly`, `monthly`, `yearly`.++| User says | Field |+| ------------- | -------------------------------- |+| "every day" | `recurrence_interval: "daily"` |+| "every week" | `recurrence_interval: "weekly"` |+| "every month" | `recurrence_interval: "monthly"` |+| "every year" | `recurrence_interval: "yearly"` |++### Cron recurring++Set `cron_expression` to a 5-field cron string (`min hour day-of-month month day-of-week`) when+the cadence is a specific weekday or time the presets can't express.++| User says | Field |+| -------------------------- | --------------------------------- |+| "every Monday at 9am" | `cron_expression: "0 9 * * 1"` |+| "weekdays at 8:30" | `cron_expression: "30 8 * * 1-5"` |+| "1st of the month at noon" | `cron_expression: "0 12 1 * *"` |++A reminder may fire **at most 4 times per day** — a more frequent cron (e.g. hourly) is rejected.++## Timezone++Always pass `timezone` as the user's IANA zone (e.g. `"America/New_York"`) when you know it, so+wall-clock times like "9am" resolve to the right moment. If omitted, it defaults to the **project+timezone**. Cron and preset schedules resolve in this zone; `scheduled_at` is an absolute instant,+so include its offset or rely on the same zone.++## Attaching a resource++To link the reminder to a PostHog object, set `resource_type` and `resource_id` **together**.+The fired notification deep-links to that object. The resource must already exist in the project.++| `resource_type` | `resource_id` is the… |+| ---------------- | --------------------- |+| `dashboard` | numeric id |+| `insight` | short_id |+| `experiment` | numeric id |+| `feature_flag` | numeric id |+| `survey` | id |+| `notebook` | short_id |+| `replay` | session_id |+| `error_tracking` | issue id |++Resolve the id first if the user gives you a name or URL (e.g. fetch the insight to get its+`short_id`). Omit both fields for a standalone reminder with no linked resource.++## Privacy and lifecycle++- Reminders are **private to the creating user** and scoped to the **current project**. Other+ users never see them.+- They fire as **in-app notifications** — not email, Slack, or webhook.+- A **one-off** becomes `completed` after it fires.+- A **recurring** reminder stays `active` until deleted, or until its optional `end_date` passes+ (then it becomes `completed`).+- A one-off whose delivery permanently fails becomes `errored` — surface this via `reminders-list`+ when reporting on a user's reminders.++## The MCP tools++- `reminder-create` — create a reminder+- `reminders-list` — list the user's reminders (schedule, status, next fire time)+- `reminder-get` — get one reminder by id+- `reminder-update` — update title, message, schedule, timezone, end date, or attached resource+ (changing the schedule recomputes the next fire time)+- `reminder-delete` — delete a reminder, which stops it firing++## Worked example++User: "Remind me to review the launch dashboard every Monday at 9am."++1. Resolve the dashboard id (e.g. dashboard `67`).+2. Pick the schedule shape: a specific weekday + time → cron.+3. Pass the user's timezone if known.+4. Call `reminder-create`:++```json+{+ "title": "Review the launch dashboard",+ "resource_type": "dashboard",+ "resource_id": "67",+ "cron_expression": "0 9 * * 1",+ "timezone": "America/New_York"+}+```++Confirm back to the user when it will next fire (use `next_fire_at` from the response), and that+it will keep firing weekly until they delete it.diff --git a/products/subscriptions/frontend/generated/api.schemas.ts b/products/subscriptions/frontend/generated/api.schemas.tsindex 2e2f2541feb4..70a63db29c88 100644--- a/products/subscriptions/frontend/generated/api.schemas.ts+++ b/products/subscriptions/frontend/generated/api.schemas.ts@@ -37,10 +37,9 @@ export const TargetTypeEnumApi = {* * `monthly` - Monthly* * `yearly` - Yearly*/-export type SubscriptionFrequencyEnumApi =- (typeof SubscriptionFrequencyEnumApi)[keyof typeof SubscriptionFrequencyEnumApi]+export type RecurrenceIntervalEnumApi = (typeof RecurrenceIntervalEnumApi)[keyof typeof RecurrenceIntervalEnumApi]-export const SubscriptionFrequencyEnumApi = {+export const RecurrenceIntervalEnumApi = {Daily: 'daily',Weekly: 'weekly',Monthly: 'monthly',@@ -169,7 +168,7 @@ export interface SubscriptionApi {* * `weekly` - Weekly* * `monthly` - Monthly* * `yearly` - Yearly */- frequency: SubscriptionFrequencyEnumApi+ frequency: RecurrenceIntervalEnumApi/*** Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.* @minimum 1@@ -313,7 +312,7 @@ export interface PatchedSubscriptionApi {* * `weekly` - Weekly* * `monthly` - Monthly* * `yearly` - Yearly */- frequency?: SubscriptionFrequencyEnumApi+ frequency?: RecurrenceIntervalEnumApi/*** Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.* @minimum 1diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 3b2c90a50f10..e19e24876324 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -5653,6 +5653,76 @@},"system_prompt_hint": "List persons behind a trends data point"},+ "reminder-create": {+ "description": "Create a reminder for yourself. Set organization (required) and optionally team to scope it to a project. Use a one-off reminder by setting scheduled_at (a future ISO 8601 time), or a recurring reminder by setting recurrence_interval (daily/weekly/monthly/yearly) OR cron_expression (5-field, max 4 fires/day). Set timezone to the user's IANA timezone so wall-clock times resolve correctly. Optionally attach a resource the reminder is about via resource_type + resource_id (e.g. a dashboard) — the notification will link to it. Reminders fire as in-app notifications when due. Proactively offer to create a reminder when the user mentions needing periodic checks, monitoring, recurring reviews, or follow-ups on a metric, dashboard, or task — reminders are how they get recurring in-app notifications without manual polling.",+ "category": "Reminders",+ "feature": "reminders",+ "summary": "Create reminder",+ "title": "Create reminder",+ "required_scopes": ["user:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "reminder-delete": {+ "description": "Delete a reminder by ID. This stops it from firing.",+ "category": "Reminders",+ "feature": "reminders",+ "summary": "Delete reminder",+ "title": "Delete reminder",+ "required_scopes": ["user:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "reminder-get": {+ "description": "Get a single reminder by ID.",+ "category": "Reminders",+ "feature": "reminders",+ "summary": "Get reminder",+ "title": "Get reminder",+ "required_scopes": ["user:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "reminder-update": {+ "description": "Update a reminder's title, message, schedule, timezone, end date, or attached resource. Changing the schedule recomputes the next fire time.",+ "category": "Reminders",+ "feature": "reminders",+ "summary": "Update reminder",+ "title": "Update reminder",+ "required_scopes": ["user:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "reminders-list": {+ "description": "List your reminders in the current project, including their schedule, status (active/completed/errored), and next fire time.",+ "category": "Reminders",+ "feature": "reminders",+ "summary": "List reminders",+ "title": "List reminders",+ "required_scopes": ["user:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"role-get": {"description": "Get details of a specific role including its name, creation date, and creator.","category": "Platform Features",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 59c8870712e7..60d7ad8634fd 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -6118,6 +6118,76 @@"readOnlyHint": true}},+ "reminder-create": {+ "description": "Create a reminder for yourself. Set organization (required) and optionally team to scope it to a project. Use a one-off reminder by setting scheduled_at (a future ISO 8601 time), or a recurring reminder by setting recurrence_interval (daily/weekly/monthly/yearly) OR cron_expression (5-field, max 4 fires/day). Set timezone to the user's IANA timezone so wall-clock times resolve correctly. Optionally attach a resource the reminder is about via resource_type + resource_id (e.g. a dashboard) — the notification will link to it. Reminders fire as in-app notifications when due. Proactively offer to create a reminder when the user mentions needing periodic checks, monitoring, recurring reviews, or follow-ups on a metric, dashboard, or task — reminders are how they get recurring in-app notifications without manual polling.",+ "category": "Reminders",+ "feature": "reminders",+ "summary": "Create reminder",+ "title": "Create reminder",+ "required_scopes": ["user:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "reminder-delete": {+ "description": "Delete a reminder by ID. This stops it from firing.",+ "category": "Reminders",+ "feature": "reminders",+ "summary": "Delete reminder",+ "title": "Delete reminder",+ "required_scopes": ["user:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "reminder-get": {+ "description": "Get a single reminder by ID.",+ "category": "Reminders",+ "feature": "reminders",+ "summary": "Get reminder",+ "title": "Get reminder",+ "required_scopes": ["user:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },+ "reminder-update": {+ "description": "Update a reminder's title, message, schedule, timezone, end date, or attached resource. Changing the schedule recomputes the next fire time.",+ "category": "Reminders",+ "feature": "reminders",+ "summary": "Update reminder",+ "title": "Update reminder",+ "required_scopes": ["user:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ }+ },+ "reminders-list": {+ "description": "List your reminders in the current project, including their schedule, status (active/completed/errored), and next fire time.",+ "category": "Reminders",+ "feature": "reminders",+ "summary": "List reminders",+ "title": "List reminders",+ "required_scopes": ["user:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"role-get": {"description": "Get details of a specific role including its name, creation date, and creator.","category": "Platform Features",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 0a8e924b8d10..c4407a51b2a2 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -29550,6 +29550,112 @@ export namespace Schemas {results: QuickFilter[];}+ /**+ * * `daily` - Daily+ * * `weekly` - Weekly+ * * `monthly` - Monthly+ * * `yearly` - Yearly+ */+ export type RecurrenceIntervalEnum = typeof RecurrenceIntervalEnum[keyof typeof RecurrenceIntervalEnum];+++ export const RecurrenceIntervalEnum = {+ Daily: 'daily',+ Weekly: 'weekly',+ Monthly: 'monthly',+ Yearly: 'yearly',+ } as const;++ /**+ * * `active` - Active+ * * `completed` - Completed+ * * `errored` - Errored+ */+ export type ReminderStatusEnum = typeof ReminderStatusEnum[keyof typeof ReminderStatusEnum];+++ export const ReminderStatusEnum = {+ Active: 'active',+ Completed: 'completed',+ Errored: 'errored',+ } as const;++ export interface Reminder {+ readonly id: string;+ /** ID of the organization this reminder belongs to. You must be a member of it. */+ organization: string;+ /**+ * Optional ID of the project this reminder is scoped to. Required when targeting a specific resource. Must belong to the chosen organization.+ * @nullable+ */+ team?: number | null;+ /**+ * Short text shown as the notification title when the reminder fires.+ * @maxLength 255+ */+ title: string;+ /** Optional longer body for the notification. */+ message?: string;+ /**+ * Optional PostHog resource this reminder is about. One of: dashboard, insight, experiment, feature_flag, survey, notebook, replay, error_tracking. Resources are project-scoped, so a team must be set when this is provided.+ * @maxLength 50+ * @nullable+ */+ resource_type?: string | null;+ /**+ * ID of the referenced resource; must exist in the chosen project.+ * @maxLength 200+ * @nullable+ */+ resource_id?: string | null;+ /**+ * For a one-off reminder: when it should fire (ISO 8601, future).+ * @nullable+ */+ scheduled_at?: string | null;+ /** For a recurring reminder: daily, weekly, monthly, or yearly.+ *+ * * `daily` - Daily+ * * `weekly` - Weekly+ * * `monthly` - Monthly+ * * `yearly` - Yearly */+ recurrence_interval?: RecurrenceIntervalEnum | BlankEnum | null;+ /**+ * For a recurring reminder: a 5-field cron expression (e.g. '0 9 * * 1' = Mondays 9am). May fire at most 4 times per day. Mutually exclusive with recurrence_interval.+ * @maxLength 100+ * @nullable+ */+ cron_expression?: string | null;+ /**+ * IANA timezone the schedule resolves in (e.g. 'America/New_York'). Defaults to the project timezone when a team is set, otherwise UTC.+ * @maxLength 64+ */+ timezone?: string;+ /**+ * Optional: recurring reminders stop (status=completed) after this time.+ * @nullable+ */+ end_date?: string | null;+ /** @nullable */+ readonly next_fire_at: string | null;+ /** @nullable */+ readonly last_fired_at: string | null;+ readonly status: ReminderStatusEnum;+ readonly created_by: UserBasic;+ readonly created_at: string;+ /** @nullable */+ readonly updated_at: string | null;+ }++ export interface PaginatedReminderList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: Reminder[];+ }+/*** * `monitor` - Monitor* * `classifier` - Classifier@@ -29940,10 +30046,10 @@ export namespace Schemas {* * `monthly` - monthly* * `yearly` - yearly*/- export type RecurrenceIntervalEnum = typeof RecurrenceIntervalEnum[keyof typeof RecurrenceIntervalEnum];+ export type ScheduledChangeRecurrenceIntervalEnum = typeof ScheduledChangeRecurrenceIntervalEnum[keyof typeof ScheduledChangeRecurrenceIntervalEnum];- export const RecurrenceIntervalEnum = {+ export const ScheduledChangeRecurrenceIntervalEnum = {Daily: 'daily',Weekly: 'weekly',Monthly: 'monthly',@@ -29984,7 +30090,7 @@ export namespace Schemas {* * `weekly` - weekly* * `monthly` - monthly* * `yearly` - yearly */- recurrence_interval?: RecurrenceIntervalEnum | null;+ recurrence_interval?: ScheduledChangeRecurrenceIntervalEnum | null;/*** @maxLength 100* @nullable@@ -30644,22 +30750,6 @@ export namespace Schemas {Slack: 'slack',} as const;- /**- * * `daily` - Daily- * * `weekly` - Weekly- * * `monthly` - Monthly- * * `yearly` - Yearly- */- export type SubscriptionFrequencyEnum = typeof SubscriptionFrequencyEnum[keyof typeof SubscriptionFrequencyEnum];--- export const SubscriptionFrequencyEnum = {- Daily: 'daily',- Weekly: 'weekly',- Monthly: 'monthly',- Yearly: 'yearly',- } as const;-/*** * `monday` - Monday* * `tuesday` - Tuesday@@ -30727,7 +30817,7 @@ export namespace Schemas {* * `weekly` - Weekly* * `monthly` - Monthly* * `yearly` - Yearly */- frequency: SubscriptionFrequencyEnum;+ frequency: RecurrenceIntervalEnum;/*** Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.* @minimum 1@@ -36974,6 +37064,73 @@ export namespace Schemas {readonly updated_at?: string;}+ export interface PatchedReminder {+ readonly id?: string;+ /** ID of the organization this reminder belongs to. You must be a member of it. */+ organization?: string;+ /**+ * Optional ID of the project this reminder is scoped to. Required when targeting a specific resource. Must belong to the chosen organization.+ * @nullable+ */+ team?: number | null;+ /**+ * Short text shown as the notification title when the reminder fires.+ * @maxLength 255+ */+ title?: string;+ /** Optional longer body for the notification. */+ message?: string;+ /**+ * Optional PostHog resource this reminder is about. One of: dashboard, insight, experiment, feature_flag, survey, notebook, replay, error_tracking. Resources are project-scoped, so a team must be set when this is provided.+ * @maxLength 50+ * @nullable+ */+ resource_type?: string | null;+ /**+ * ID of the referenced resource; must exist in the chosen project.+ * @maxLength 200+ * @nullable+ */+ resource_id?: string | null;+ /**+ * For a one-off reminder: when it should fire (ISO 8601, future).+ * @nullable+ */+ scheduled_at?: string | null;+ /** For a recurring reminder: daily, weekly, monthly, or yearly.+ *+ * * `daily` - Daily+ * * `weekly` - Weekly+ * * `monthly` - Monthly+ * * `yearly` - Yearly */+ recurrence_interval?: RecurrenceIntervalEnum | BlankEnum | null;+ /**+ * For a recurring reminder: a 5-field cron expression (e.g. '0 9 * * 1' = Mondays 9am). May fire at most 4 times per day. Mutually exclusive with recurrence_interval.+ * @maxLength 100+ * @nullable+ */+ cron_expression?: string | null;+ /**+ * IANA timezone the schedule resolves in (e.g. 'America/New_York'). Defaults to the project timezone when a team is set, otherwise UTC.+ * @maxLength 64+ */+ timezone?: string;+ /**+ * Optional: recurring reminders stop (status=completed) after this time.+ * @nullable+ */+ end_date?: string | null;+ /** @nullable */+ readonly next_fire_at?: string | null;+ /** @nullable */+ readonly last_fired_at?: string | null;+ readonly status?: ReminderStatusEnum;+ readonly created_by?: UserBasic;+ readonly created_at?: string;+ /** @nullable */+ readonly updated_at?: string | null;+ }+export interface PatchedRemovePersonRequest {/** Person UUID to remove from the cohort */person_id?: string;@@ -37160,7 +37317,7 @@ export namespace Schemas {* * `weekly` - weekly* * `monthly` - monthly* * `yearly` - yearly */- recurrence_interval?: RecurrenceIntervalEnum | null;+ recurrence_interval?: ScheduledChangeRecurrenceIntervalEnum | null;/*** @maxLength 100* @nullable@@ -37473,7 +37630,7 @@ export namespace Schemas {* * `weekly` - Weekly* * `monthly` - Monthly* * `yearly` - Yearly */- frequency?: SubscriptionFrequencyEnum;+ frequency?: RecurrenceIntervalEnum;/*** Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.* @minimum 1@@ -60896,6 +61053,17 @@ export namespace Schemas {types?: string;};+ export type RemindersListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type UsersListParams = {email?: string;is_staff?: boolean;diff --git a/services/mcp/src/generated/reminders/api.ts b/services/mcp/src/generated/reminders/api.tsnew file mode 100644index 000000000000..5e2264e883bb--- /dev/null+++ b/services/mcp/src/generated/reminders/api.ts@@ -0,0 +1,172 @@+/**+ * Auto-generated from the Django backend OpenAPI schema.+ * MCP service uses these Zod schemas for generated tool handlers.+ * To regenerate: hogli build:openapi+ *+ * PostHog API - MCP 5 enabled ops+ * OpenAPI spec version: 1.0.0+ */+import * as zod from 'zod'++export const RemindersListQueryParams = /* @__PURE__ */ zod.object({+ limit: zod.number().optional().describe('Number of results to return per page.'),+ offset: zod.number().optional().describe('The initial index from which to return the results.'),+})++export const remindersCreateBodyTitleMax = 255++export const remindersCreateBodyResourceTypeMax = 50++export const remindersCreateBodyResourceIdMax = 200++export const remindersCreateBodyCronExpressionMax = 100++export const remindersCreateBodyTimezoneMax = 64++export const RemindersCreateBody = /* @__PURE__ */ zod.object({+ organization: zod.string().describe('ID of the organization this reminder belongs to. You must be a member of it.'),+ team: zod+ .number()+ .nullish()+ .describe(+ 'Optional ID of the project this reminder is scoped to. Required when targeting a specific resource. Must belong to the chosen organization.'+ ),+ title: zod+ .string()+ .max(remindersCreateBodyTitleMax)+ .describe('Short text shown as the notification title when the reminder fires.'),+ message: zod.string().optional().describe('Optional longer body for the notification.'),+ resource_type: zod+ .string()+ .max(remindersCreateBodyResourceTypeMax)+ .nullish()+ .describe(+ 'Optional PostHog resource this reminder is about. One of: dashboard, insight, experiment, feature_flag, survey, notebook, replay, error_tracking. Resources are project-scoped, so a team must be set when this is provided.'+ ),+ resource_id: zod+ .string()+ .max(remindersCreateBodyResourceIdMax)+ .nullish()+ .describe('ID of the referenced resource; must exist in the chosen project.'),+ scheduled_at: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('For a one-off reminder: when it should fire (ISO 8601, future).'),+ recurrence_interval: zod+ .union([+ zod+ .enum(['daily', 'weekly', 'monthly', 'yearly'])+ .describe('* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly'),+ zod.enum(['']),+ zod.null(),+ ])+ .optional()+ .describe(+ 'For a recurring reminder: daily, weekly, monthly, or yearly.\n\n* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly'+ ),+ cron_expression: zod+ .string()+ .max(remindersCreateBodyCronExpressionMax)+ .nullish()+ .describe(+ "For a recurring reminder: a 5-field cron expression (e.g. '0 9 * * 1' = Mondays 9am). May fire at most 4 times per day. Mutually exclusive with recurrence_interval."+ ),+ timezone: zod+ .string()+ .max(remindersCreateBodyTimezoneMax)+ .optional()+ .describe(+ "IANA timezone the schedule resolves in (e.g. 'America/New_York'). Defaults to the project timezone when a team is set, otherwise UTC."+ ),+ end_date: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('Optional: recurring reminders stop (status=completed) after this time.'),+})++export const RemindersRetrieveParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this reminder.'),+})++export const RemindersPartialUpdateParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this reminder.'),+})++export const remindersPartialUpdateBodyTitleMax = 255++export const remindersPartialUpdateBodyResourceTypeMax = 50++export const remindersPartialUpdateBodyResourceIdMax = 200++export const remindersPartialUpdateBodyCronExpressionMax = 100++export const remindersPartialUpdateBodyTimezoneMax = 64++export const RemindersPartialUpdateBody = /* @__PURE__ */ zod.object({+ organization: zod+ .string()+ .optional()+ .describe('ID of the organization this reminder belongs to. You must be a member of it.'),+ team: zod+ .number()+ .nullish()+ .describe(+ 'Optional ID of the project this reminder is scoped to. Required when targeting a specific resource. Must belong to the chosen organization.'+ ),+ title: zod+ .string()+ .max(remindersPartialUpdateBodyTitleMax)+ .optional()+ .describe('Short text shown as the notification title when the reminder fires.'),+ message: zod.string().optional().describe('Optional longer body for the notification.'),+ resource_type: zod+ .string()+ .max(remindersPartialUpdateBodyResourceTypeMax)+ .nullish()+ .describe(+ 'Optional PostHog resource this reminder is about. One of: dashboard, insight, experiment, feature_flag, survey, notebook, replay, error_tracking. Resources are project-scoped, so a team must be set when this is provided.'+ ),+ resource_id: zod+ .string()+ .max(remindersPartialUpdateBodyResourceIdMax)+ .nullish()+ .describe('ID of the referenced resource; must exist in the chosen project.'),+ scheduled_at: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('For a one-off reminder: when it should fire (ISO 8601, future).'),+ recurrence_interval: zod+ .union([+ zod+ .enum(['daily', 'weekly', 'monthly', 'yearly'])+ .describe('* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly'),+ zod.enum(['']),+ zod.null(),+ ])+ .optional()+ .describe(+ 'For a recurring reminder: daily, weekly, monthly, or yearly.\n\n* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly'+ ),+ cron_expression: zod+ .string()+ .max(remindersPartialUpdateBodyCronExpressionMax)+ .nullish()+ .describe(+ "For a recurring reminder: a 5-field cron expression (e.g. '0 9 * * 1' = Mondays 9am). May fire at most 4 times per day. Mutually exclusive with recurrence_interval."+ ),+ timezone: zod+ .string()+ .max(remindersPartialUpdateBodyTimezoneMax)+ .optional()+ .describe(+ "IANA timezone the schedule resolves in (e.g. 'America/New_York'). Defaults to the project timezone when a team is set, otherwise UTC."+ ),+ end_date: zod.iso+ .datetime({ offset: true })+ .nullish()+ .describe('Optional: recurring reminders stop (status=completed) after this time.'),+})++export const RemindersDestroyParams = /* @__PURE__ */ zod.object({+ id: zod.string().describe('A UUID string identifying this reminder.'),+})diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.tsindex fdf49c016fad..c1854e47e4e8 100644--- a/services/mcp/src/tools/generated/index.ts+++ b/services/mcp/src/tools/generated/index.ts@@ -38,6 +38,7 @@ import { GENERATED_TOOLS as platform_features } from './platform_features'import { GENERATED_TOOLS as product_analytics } from './product_analytics'import { GENERATED_TOOLS as proxyRecords } from './proxy-records'import { GENERATED_TOOLS as queryWrappers } from './query-wrappers'+import { GENERATED_TOOLS as reminders } from './reminders'import { GENERATED_TOOLS as replay } from './replay'import { GENERATED_TOOLS as replay_vision } from './replay_vision'import { GENERATED_TOOLS as signals } from './signals'@@ -90,6 +91,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =...product_analytics,...proxyRecords,...queryWrappers,+ ...reminders,...replay,...replay_vision,...signals,diff --git a/services/mcp/src/tools/generated/reminders.ts b/services/mcp/src/tools/generated/reminders.tsnew file mode 100644index 000000000000..8c39b4a74d67--- /dev/null+++ b/services/mcp/src/tools/generated/reminders.ts@@ -0,0 +1,167 @@+// AUTO-GENERATED from products/reminders/mcp/tools.yaml + OpenAPI — do not edit+import { z } from 'zod'++import type { Schemas } from '@/api/generated'+import {+ RemindersCreateBody,+ RemindersDestroyParams,+ RemindersListQueryParams,+ RemindersPartialUpdateBody,+ RemindersPartialUpdateParams,+ RemindersRetrieveParams,+} from '@/generated/reminders/api'+import { withPostHogUrl, type WithPostHogUrl } from '@/tools/tool-utils'+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'++const ReminderCreateSchema = RemindersCreateBody++const reminderCreate = (): ToolBase<typeof ReminderCreateSchema, Schemas.Reminder> => ({+ name: 'reminder-create',+ schema: ReminderCreateSchema,+ handler: async (context: Context, params: z.infer<typeof ReminderCreateSchema>) => {+ const body: Record<string, unknown> = {}+ if (params.organization !== undefined) {+ body['organization'] = params.organization+ }+ if (params.team !== undefined) {+ body['team'] = params.team+ }+ if (params.title !== undefined) {+ body['title'] = params.title+ }+ if (params.message !== undefined) {+ body['message'] = params.message+ }+ if (params.resource_type !== undefined) {+ body['resource_type'] = params.resource_type+ }+ if (params.resource_id !== undefined) {+ body['resource_id'] = params.resource_id+ }+ if (params.scheduled_at !== undefined) {+ body['scheduled_at'] = params.scheduled_at+ }+ if (params.recurrence_interval !== undefined) {+ body['recurrence_interval'] = params.recurrence_interval+ }+ if (params.cron_expression !== undefined) {+ body['cron_expression'] = params.cron_expression+ }+ if (params.timezone !== undefined) {+ body['timezone'] = params.timezone+ }+ if (params.end_date !== undefined) {+ body['end_date'] = params.end_date+ }+ const result = await context.api.request<Schemas.Reminder>({+ method: 'POST',+ path: `/api/reminders/`,+ body,+ })+ return result+ },+})++const ReminderDeleteSchema = RemindersDestroyParams++const reminderDelete = (): ToolBase<typeof ReminderDeleteSchema, Schemas.Reminder> => ({+ name: 'reminder-delete',+ schema: ReminderDeleteSchema,+ handler: async (context: Context, params: z.infer<typeof ReminderDeleteSchema>) => {+ const result = await context.api.request<Schemas.Reminder>({+ method: 'PATCH',+ path: `/api/reminders/${encodeURIComponent(String(params.id))}/`,+ body: { deleted: true },+ })+ return result+ },+})++const ReminderGetSchema = RemindersRetrieveParams++const reminderGet = (): ToolBase<typeof ReminderGetSchema, Schemas.Reminder> => ({+ name: 'reminder-get',+ schema: ReminderGetSchema,+ handler: async (context: Context, params: z.infer<typeof ReminderGetSchema>) => {+ const result = await context.api.request<Schemas.Reminder>({+ method: 'GET',+ path: `/api/reminders/${encodeURIComponent(String(params.id))}/`,+ })+ return result+ },+})++const ReminderUpdateSchema = RemindersPartialUpdateParams.extend(RemindersPartialUpdateBody.shape)++const reminderUpdate = (): ToolBase<typeof ReminderUpdateSchema, Schemas.Reminder> => ({+ name: 'reminder-update',+ schema: ReminderUpdateSchema,+ handler: async (context: Context, params: z.infer<typeof ReminderUpdateSchema>) => {+ const body: Record<string, unknown> = {}+ if (params.organization !== undefined) {+ body['organization'] = params.organization+ }+ if (params.team !== undefined) {+ body['team'] = params.team+ }+ if (params.title !== undefined) {+ body['title'] = params.title+ }+ if (params.message !== undefined) {+ body['message'] = params.message+ }+ if (params.resource_type !== undefined) {+ body['resource_type'] = params.resource_type+ }+ if (params.resource_id !== undefined) {+ body['resource_id'] = params.resource_id+ }+ if (params.scheduled_at !== undefined) {+ body['scheduled_at'] = params.scheduled_at+ }+ if (params.recurrence_interval !== undefined) {+ body['recurrence_interval'] = params.recurrence_interval+ }+ if (params.cron_expression !== undefined) {+ body['cron_expression'] = params.cron_expression+ }+ if (params.timezone !== undefined) {+ body['timezone'] = params.timezone+ }+ if (params.end_date !== undefined) {+ body['end_date'] = params.end_date+ }+ const result = await context.api.request<Schemas.Reminder>({+ method: 'PATCH',+ path: `/api/reminders/${encodeURIComponent(String(params.id))}/`,+ body,+ })+ return result+ },+})++const RemindersListSchema = RemindersListQueryParams++const remindersList = (): ToolBase<typeof RemindersListSchema, WithPostHogUrl<Schemas.PaginatedReminderList>> => ({+ name: 'reminders-list',+ schema: RemindersListSchema,+ handler: async (context: Context, params: z.infer<typeof RemindersListSchema>) => {+ const result = await context.api.request<Schemas.PaginatedReminderList>({+ method: 'GET',+ path: `/api/reminders/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ },+ })+ return await withPostHogUrl(context, result, '/')+ },+})++export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {+ 'reminder-create': reminderCreate,+ 'reminder-delete': reminderDelete,+ 'reminder-get': reminderGet,+ 'reminder-update': reminderUpdate,+ 'reminders-list': remindersList,+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-create.jsonnew file mode 100644index 000000000000..be5ccd9d4208--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-create.json@@ -0,0 +1,115 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "cron_expression": {+ "anyOf": [+ {+ "maxLength": 100,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "For a recurring reminder: a 5-field cron expression (e.g. '0 9 * * 1' = Mondays 9am). May fire at most 4 times per day. Mutually exclusive with recurrence_interval."+ },+ "end_date": {+ "anyOf": [+ {+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional: recurring reminders stop (status=completed) after this time."+ },+ "message": {+ "description": "Optional longer body for the notification.",+ "type": "string"+ },+ "organization": {+ "description": "ID of the organization this reminder belongs to. You must be a member of it.",+ "type": "string"+ },+ "recurrence_interval": {+ "anyOf": [+ {+ "description": "* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly",+ "enum": ["daily", "weekly", "monthly", "yearly"],+ "type": "string"+ },+ {+ "enum": [""],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "For a recurring reminder: daily, weekly, monthly, or yearly.\n\n* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly"+ },+ "resource_id": {+ "anyOf": [+ {+ "maxLength": 200,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "ID of the referenced resource; must exist in the chosen project."+ },+ "resource_type": {+ "anyOf": [+ {+ "maxLength": 50,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional PostHog resource this reminder is about. One of: dashboard, insight, experiment, feature_flag, survey, notebook, replay, error_tracking. Resources are project-scoped, so a team must be set when this is provided."+ },+ "scheduled_at": {+ "anyOf": [+ {+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "For a one-off reminder: when it should fire (ISO 8601, future)."+ },+ "team": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional ID of the project this reminder is scoped to. Required when targeting a specific resource. Must belong to the chosen organization."+ },+ "timezone": {+ "description": "IANA timezone the schedule resolves in (e.g. 'America/New_York'). Defaults to the project timezone when a team is set, otherwise UTC.",+ "maxLength": 64,+ "type": "string"+ },+ "title": {+ "description": "Short text shown as the notification title when the reminder fires.",+ "maxLength": 255,+ "type": "string"+ }+ },+ "required": ["organization", "title"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-delete.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-delete.jsonnew file mode 100644index 000000000000..fc9b0b5d4e2d--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-delete.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this reminder.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-get.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-get.jsonnew file mode 100644index 000000000000..fc9b0b5d4e2d--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-get.json@@ -0,0 +1,11 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A UUID string identifying this reminder.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-update.jsonnew file mode 100644index 000000000000..1076218a9ddd--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-update.json@@ -0,0 +1,119 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "cron_expression": {+ "anyOf": [+ {+ "maxLength": 100,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "For a recurring reminder: a 5-field cron expression (e.g. '0 9 * * 1' = Mondays 9am). May fire at most 4 times per day. Mutually exclusive with recurrence_interval."+ },+ "end_date": {+ "anyOf": [+ {+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional: recurring reminders stop (status=completed) after this time."+ },+ "id": {+ "description": "A UUID string identifying this reminder.",+ "type": "string"+ },+ "message": {+ "description": "Optional longer body for the notification.",+ "type": "string"+ },+ "organization": {+ "description": "ID of the organization this reminder belongs to. You must be a member of it.",+ "type": "string"+ },+ "recurrence_interval": {+ "anyOf": [+ {+ "description": "* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly",+ "enum": ["daily", "weekly", "monthly", "yearly"],+ "type": "string"+ },+ {+ "enum": [""],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "For a recurring reminder: daily, weekly, monthly, or yearly.\n\n* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly"+ },+ "resource_id": {+ "anyOf": [+ {+ "maxLength": 200,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "ID of the referenced resource; must exist in the chosen project."+ },+ "resource_type": {+ "anyOf": [+ {+ "maxLength": 50,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional PostHog resource this reminder is about. One of: dashboard, insight, experiment, feature_flag, survey, notebook, replay, error_tracking. Resources are project-scoped, so a team must be set when this is provided."+ },+ "scheduled_at": {+ "anyOf": [+ {+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$",+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "For a one-off reminder: when it should fire (ISO 8601, future)."+ },+ "team": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional ID of the project this reminder is scoped to. Required when targeting a specific resource. Must belong to the chosen organization."+ },+ "timezone": {+ "description": "IANA timezone the schedule resolves in (e.g. 'America/New_York'). Defaults to the project timezone when a team is set, otherwise UTC.",+ "maxLength": 64,+ "type": "string"+ },+ "title": {+ "description": "Short text shown as the notification title when the reminder fires.",+ "maxLength": 255,+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/reminders-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/reminders-list.jsonnew file mode 100644index 000000000000..8331b796ac73--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/reminders-list.json@@ -0,0 +1,14 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "limit": {+ "description": "Number of results to return per page.",+ "type": "number"+ },+ "offset": {+ "description": "The initial index from which to return the results.",+ "type": "number"+ }+ },+ "type": "object"+}diff --git a/tach.toml b/tach.tomlindex 4023888cba4d..964bb93b7196 100644--- a/tach.toml+++ b/tach.toml@@ -97,6 +97,7 @@ depends_on = ["products.posthog_ai","products.product_analytics","products.product_tours",+ "products.reminders","products.replay","products.replay_vision","products.revenue_analytics",@@ -485,6 +486,21 @@ depends_on = []layer = "modules"+[[modules]]+path = "products.reminders"+depends_on = [+ "posthog",+ "products.dashboards",+ "products.error_tracking",+ "products.experiments",+ "products.feature_flags",+ "products.notebooks",+ "products.notifications",+ "products.product_analytics",+ "products.surveys",+]+layer = "modules"+[[modules]]path = "products.replay"depends_on = [