Skip to content

Define the durable notification domain model and database schema #1716

Closed

Description

@propr-dev

Context

The PWA, mobile Inbox, Web Push delivery, notification preferences, and icon badging all need one durable source of truth. Deriving notifications independently in the browser would lose events while the app is closed and would make push delivery, dismissal, and badge counts disagree.

This issue establishes the shared notification contract and SQLite tables. It intentionally does not expose API routes or send push messages; later issues build those layers on this foundation.

Requirements

  • Define notification kinds for plans, tasks, reviews, pull requests, indexing, and system failures.
  • Define target, action, preference, push-subscription, and API response types in @propr/shared.
  • Store immutable notification events separately from per-user read/dismiss state.
  • Store per-user notification preferences and push subscriptions.
  • Store Web Push delivery attempts for retry and deduplication.
  • Store latest task/indexing activity so a later monitor can identify stalled work.
  • Add indexes for unread Inbox queries, event deduplication, and delivery retries.
  • Use ISO-8601 timestamps consistently because SQLite timestamp behavior varies by driver.

Acceptance Criteria

  • Database migrations create and roll back all notification tables successfully.
  • Re-running an event with the same deduplication key cannot create a duplicate.
  • Multiple users can read or dismiss the same event independently.
  • Push subscription endpoints are unique and can be revoked without deleting audit history.
  • Shared types compile for the backend and propr-ui.
  • Existing migrations and application startup continue to work on a new and upgraded database.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Aug 2, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    Use an immutable event plus per-user receipt model. This was chosen instead of putting user_id directly on each event because operational events belong to the ProPR instance and may be relevant to several authenticated users. Per-user receipt rows preserve independent read and dismissal state without duplicating event payloads. A browser-only event store was rejected because it cannot power push while the browser is closed. Computing the Inbox from task tables on every request was rejected because it cannot preserve dismissal state or an auditable notification history.

    File: packages/shared/src/notifications.ts (new file)

    Why this file: This is the transport-neutral contract shared by the API, core services, service worker client, and React UI. Centralizing the string unions prevents backend/frontend action names from drifting.

    export const NOTIFICATION_KINDS = [
      'plan_ready',
      'task_failed',
      'task_stalled',
      'implementation_completed',
      'review_completed',
      'pr_attention',
      'indexing_failed',
      'system_failed',
    ] as const;
    
    export type NotificationKind = typeof NOTIFICATION_KINDS[number];
    
    export const NOTIFICATION_ACTIONS = [
      'stop',
      'follow_up',
      'dismiss',
      'open_pr',
      'refine',
      'approve_execute',
    ] as const;
    
    export type NotificationAction = typeof NOTIFICATION_ACTIONS[number];
    export type NotificationTargetType = 'plan' | 'task' | 'repository' | 'system';
    export type NotificationCategory = 'plans' | 'tasks' | 'pull_requests' | 'indexing' | 'system';
    
    export interface NotificationEvent {
      id: string;
      kind: NotificationKind;
      category: NotificationCategory;
      title: string;
      body: string;
      targetType: NotificationTargetType;
      targetId: string;
      projectSlug?: string | null;
      deepLink: string;
      prUrl?: string | null;
      actions: NotificationAction[];
      metadata: Record<string, unknown>;
      occurredAt: string;
      readAt?: string | null;
      dismissedAt?: string | null;
    }
    
    export interface NotificationPreferences {
      enabled: boolean;
      pushEnabled: boolean;
      badgeEnabled: boolean;
      quietHoursStart: string | null;
      quietHoursEnd: string | null;
      timezone: string;
      categories: Record<NotificationCategory, boolean>;
    }
    
    export const DEFAULT_NOTIFICATION_PREFERENCES: NotificationPreferences = {
      enabled: true,
      pushEnabled: false,
      badgeEnabled: true,
      quietHoursStart: null,
      quietHoursEnd: null,
      timezone: 'UTC',
      // Keep all event classes visible in the Inbox by default. Push remains opt-in
      // because browsers require a user gesture before notification permission.
      categories: {
        plans: true,
        tasks: true,
        pull_requests: true,
        indexing: true,
        system: true,
      },
    };
    
    export interface WebPushSubscriptionInput {
      endpoint: string;
      expirationTime: number | null;
      keys: {
        p256dh: string;
        auth: string;
      };
    }
    
    export interface NotificationListResponse {
      notifications: NotificationEvent[];
      unreadCount: number;
      nextCursor: string | null;
    }
    
    export interface NotificationConfigResponse {
      configured: boolean;
      vapidPublicKey: string | null;
    }

    File: packages/shared/src/index.ts

    Why this file: All consumers import shared contracts through the package barrel. Re-exporting here preserves that established import pattern.

    --- a/packages/shared/src/index.ts
    +++ b/packages/shared/src/index.ts
    @@ -1,3 +1,4 @@
    +export * from './notifications.js';

    File: packages/core/src/db/migrations/202608020001_create_notifications.ts (new file)

    Why this file: The migration creates the durable server-side state required before API or push features are enabled. Separate receipts and deliveries avoid mixing user interaction state with transport retry state.

    import type { Knex } from 'knex';
    
    export async function up(knex: Knex): Promise<void> {
      await knex.schema.createTable('notification_events', table => {
        table.string('id', 36).primary();
        table.string('kind', 64).notNullable();
        table.string('category', 32).notNullable();
        table.string('target_type', 32).notNullable();
        table.string('target_id', 255).notNullable();
        table.string('project_slug', 255).nullable();
        table.text('title').notNullable();
        table.text('body').notNullable();
        table.text('deep_link').notNullable();
        table.text('pr_url').nullable();
        table.text('actions_json').notNullable().defaultTo('[]');
        table.text('metadata_json').notNullable().defaultTo('{}');
        // A producer-provided key makes repeated socket updates and worker retries
        // idempotent without relying on process-local memory.
        table.string('dedupe_key', 512).notNullable().unique();
        table.string('occurred_at', 32).notNullable();
        table.string('created_at', 32).notNullable();
        table.index(['occurred_at'], 'notification_events_occurred_idx');
        table.index(['category', 'occurred_at'], 'notification_events_category_idx');
      });
    
      await knex.schema.createTable('notification_receipts', table => {
        table.string('event_id', 36).notNullable()
          .references('id').inTable('notification_events').onDelete('CASCADE');
        table.string('user_id', 255).notNullable();
        table.string('read_at', 32).nullable();
        table.string('dismissed_at', 32).nullable();
        // One row per event/user keeps read and dismissal state independent while
        // preventing duplicate receipts during concurrent mobile requests.
        table.primary(['event_id', 'user_id']);
        table.index(['user_id', 'dismissed_at'], 'notification_receipts_user_idx');
      });
    
      await knex.schema.createTable('notification_preferences', table => {
        table.string('user_id', 255).primary();
        table.boolean('enabled').notNullable().defaultTo(true);
        table.boolean('push_enabled').notNullable().defaultTo(false);
        table.boolean('badge_enabled').notNullable().defaultTo(true);
        table.string('quiet_hours_start', 5).nullable();
        table.string('quiet_hours_end', 5).nullable();
        table.string('timezone', 64).notNullable().defaultTo('UTC');
        table.text('categories_json').notNullable();
        table.string('updated_at', 32).notNullable();
      });
    
      await knex.schema.createTable('push_subscriptions', table => {
        table.string('id', 36).primary();
        table.string('user_id', 255).notNullable();
        table.text('endpoint').notNullable().unique();
        table.text('p256dh').notNullable();
        table.text('auth').notNullable();
        table.bigInteger('expiration_time').nullable();
        table.text('user_agent').nullable();
        table.string('created_at', 32).notNullable();
        table.string('updated_at', 32).notNullable();
        table.string('revoked_at', 32).nullable();
        table.index(['user_id', 'revoked_at'], 'push_subscriptions_user_idx');
      });
    
      await knex.schema.createTable('notification_deliveries', table => {
        table.string('id', 36).primary();
        table.string('event_id', 36).notNullable()
          .references('id').inTable('notification_events').onDelete('CASCADE');
        table.string('subscription_id', 36).notNullable()
          .references('id').inTable('push_subscriptions').onDelete('CASCADE');
        table.string('status', 16).notNullable().defaultTo('pending');
        table.integer('attempt_count').notNullable().defaultTo(0);
        table.string('next_attempt_at', 32).notNullable();
        table.text('last_error').nullable();
        table.string('delivered_at', 32).nullable();
        table.string('updated_at', 32).notNullable();
        table.unique(['event_id', 'subscription_id']);
        table.index(['status', 'next_attempt_at'], 'notification_deliveries_retry_idx');
      });
    
      await knex.schema.createTable('notification_activity', table => {
        table.string('entity_type', 32).notNullable();
        table.string('entity_id', 255).notNullable();
        table.string('state', 64).notNullable();
        table.string('project_slug', 255).nullable();
        table.text('deep_link').notNullable();
        table.string('last_transition_at', 32).notNullable();
        table.boolean('terminal').notNullable().defaultTo(false);
        table.primary(['entity_type', 'entity_id']);
        table.index(['terminal', 'last_transition_at'], 'notification_activity_stall_idx');
      });
    }
    
    export async function down(knex: Knex): Promise<void> {
      // Drop dependents first so foreign-key-enabled SQLite installations can roll
      // the migration back without violating references.
      await knex.schema.dropTableIfExists('notification_activity');
      await knex.schema.dropTableIfExists('notification_deliveries');
      await knex.schema.dropTableIfExists('push_subscriptions');
      await knex.schema.dropTableIfExists('notification_preferences');
      await knex.schema.dropTableIfExists('notification_receipts');
      await knex.schema.dropTableIfExists('notification_events');
    }
  2. propr-dev commented on Aug 2, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using codex agent with gpt-5.6-sol model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: codex
    • Model: gpt-5.6-sol
    • Branch: 1716/gpt-5.6-sol-define-the-durable-notifi-20260802-0734-owc
    • Base Branch: 1716-epic-failed-to-3m8
    • Worktree: issue-1716-20260802-0734-gpt-5.6-sol-owc

    🔍 Track Task Execution

  3. added a commit that references this issue on Aug 2, 2026
  4. added a commit that references this issue on Aug 2, 2026
  5. added a commit that references this issue on Aug 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions