Skip to content

Deduplicate Inbox notifications and automatically close stale PR/system items #1984

Closed

Description

@propr-dev

Context

The Inbox is currently accumulating repeated notifications for the same actionable state. Examples include multiple Pull request needs attention cards for the same PR and repeated claudeAuth is not reporting a healthy status cards. It also leaves stale cards visible after the underlying condition is no longer actionable, such as PR-related Inbox items after the PR has been merged.

This happens because notification events are immutable audit records, but the Inbox view needs a lifecycle on top of those records. The current projection creates new events for repeated PR attention and stores system-health failure state only in API process memory, so restarts or multiple API instances can create duplicate system failure cards.

Requirements

  1. Automatically dismiss PR-related Inbox notifications when a PR is merged.
  2. Keep only one active pull_request attention card per repository and PR, while still allowing newer work to replace an older card.
  3. Deduplicate system failure notifications across repeated /api/status snapshots, process restarts, and multiple API instances.
  4. Automatically dismiss system failure cards once the component reports healthy again.
  5. Preserve notification audit rows; only update per-recipient Inbox state through notification_user_states.dismissed_at.
  6. Add regression tests for PR notification closure, PR attention replacement, and cross-instance system failure deduplication.

Implementation Specification

Modify the backend notification lifecycle, not just frontend rendering. Add service-level helpers in NotificationService to dismiss matching notification receipts, persist system failure projection state in a new migration, update NotificationProjectionService to use the persistent state table, and close PR-related notifications from the PR webhook tracking path.

Acceptance Criteria

  • A merged PR no longer appears in Inbox Needs attention or completed PR-related cards after the merge webhook is processed.
  • Repeated task completions for the same PR leave only one active Pull request needs attention Inbox card.
  • Repeated unhealthy claudeAuth status snapshots create one active system failure card, even across two NotificationProjectionService instances.
  • A recovered system component dismisses its previous system failure card.
  • Existing read/dismiss behavior remains idempotent per user.
  • The notification and projection test suites pass.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Aug 29, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    This implementation adds lifecycle reconciliation at the notification persistence/projection layer because stale and duplicate Inbox cards are backend state problems, not only presentation problems. Frontend-only filtering was rejected because it would leave unread counts, push delivery, and other clients inconsistent. Changing notification event immutability was also rejected because event rows are audit records; the correct mutable state is the per-recipient notification_user_states row.

    The key trade-off is that automatic closure is modeled as a system dismissal. This keeps the schema simple, preserves historical events, and makes the existing list API hide irrelevant notifications without introducing a new user-visible resolved_at concept.

    File: packages/core/src/db/migrations/20260829000000_add_notification_projection_state.js (new file)

    Why this file: System health deduplication cannot rely on in-memory maps because /api/status can be served by multiple API processes or after a restart. This migration gives projections a small durable state table that records the currently open system failure period.

    /**
     * Persist notification projection state that cannot safely live in one API process.
     *
     * The notification event table remains immutable. This table stores only the current
     * projection cursor for stateful producers, allowing repeated snapshots to find the
     * already-open failure period instead of creating duplicate Inbox cards.
     */
    
    const TABLE_NAME = 'notification_projection_state';
    
    /** @param {import('knex').Knex} knex */
    export async function up(knex) {
      const exists = await knex.schema.hasTable(TABLE_NAME);
      if (exists) return;
    
      await knex.schema.createTable(TABLE_NAME, table => {
        // Scope keeps this table extensible without creating one table per producer.
        // The first user is system health, keyed by component name.
        table.text('scope').notNullable();
        table.text('subject_key').notNullable();
    
        // Store the latest unhealthy status because a component changing from one
        // bad state to another should replace the visible Inbox card.
        table.text('status').notNullable();
        table.text('opened_at').notNullable();
        table.text('latest_seen_at').notNullable();
        table.text('closed_at').nullable();
    
        // Linking the generated event lets recovery dismiss exactly the relevant
        // Inbox receipts while preserving the immutable event row for audit history.
        table.text('notification_event_id').nullable()
          .references('event_id')
          .inTable('notification_events')
          .onDelete('SET NULL');
    
        table.text('created_at').notNullable();
        table.text('updated_at').notNullable();
    
        table.primary(['scope', 'subject_key']);
        table.index(['scope', 'closed_at']);
        table.index(['notification_event_id']);
      });
    }
    
    /** @param {import('knex').Knex} knex */
    export async function down(knex) {
      await knex.schema.dropTableIfExists(TABLE_NAME);
    }

    File: packages/core/src/services/notificationService.ts

    Why this file: NotificationService owns Inbox state transitions. Adding reusable dismissal helpers here keeps automatic closure consistent with manual dismissal and avoids duplicating JSON-target parsing in projection or webhook code.

    --- a/packages/core/src/services/notificationService.ts
    +++ b/packages/core/src/services/notificationService.ts
    @@
     export interface NotificationListOptions {
         cursor?: string | null;
         limit?: number;
         includeDismissed?: boolean;
     }
    +
    +export interface NotificationAutoDismissOptions {
    +    kinds?: readonly NotificationKind[];
    +    exceptEventIds?: readonly string[];
    +}
    @@
     function eventSelectColumns(): string[] {
    @@
     }
    +
    +function eventOnlySelectColumns(): string[] {
    +    return [
    +        'event_id',
    +        'deduplication_key',
    +        'kind',
    +        'severity',
    +        'target_json',
    +        'title',
    +        'body',
    +        'action_json',
    +        'advertised_actions_json',
    +        'metadata_json',
    +        'occurred_at',
    +        'created_at'
    +    ];
    +}
    +
    +const PR_RELATED_NOTIFICATION_KINDS: readonly NotificationKind[] = [
    +    'task',
    +    'review',
    +    'pull_request'
    +];
    +
    +function assertRepositoryName(value: string): void {
    +    // Reuse the published repository byte limit before querying target JSON so
    +    // automatic cleanup cannot become a path for unbounded database scans.
    +    if (
    +        typeof value !== 'string'
    +        || !/^[^/\s]+\/[^/\s]+$/.test(value)
    +        || Buffer.byteLength(value, 'utf8') > NOTIFICATION_PAYLOAD_LIMITS.repositoryBytes
    +    ) {
    +        throw new TypeError('notification repository must be a bounded owner/name value');
    +    }
    +}
    +
    +function assertPositiveInteger(value: number, path: string): void {
    +    // PR numbers come from GitHub payloads or validated notification targets.
    +    // Guard again here because this helper can be called directly by webhook code.
    +    if (!Number.isSafeInteger(value) || value <= 0) {
    +        throw new TypeError(`${path} must be a positive integer`);
    +    }
    +}
    +
    +function notificationPullRequestIdentity(event: NotificationEvent): { repository: string; prNumber: number } | null {
    +    switch (event.target.type) {
    +        case 'task':
    +            return event.target.prNumber === undefined
    +                ? null
    +                : { repository: event.target.repository, prNumber: event.target.prNumber };
    +        case 'review':
    +        case 'pull_request':
    +            return { repository: event.target.repository, prNumber: event.target.prNumber };
    +        default:
    +            return null;
    +    }
    +}
    +
    +function notificationMatchesPullRequest(event: NotificationEvent, repository: string, prNumber: number): boolean {
    +    const identity = notificationPullRequestIdentity(event);
    +    return identity !== null
    +        && identity.prNumber === prNumber
    +        && identity.repository.toLowerCase() === repository.toLowerCase();
    +}
    @@
         async dismissNotification(
             userId: string,
             eventId: string
         ): Promise<NotificationStateResponse | null> {
             return this.updateInboxTimestamp(userId, eventId, 'dismissed_at');
         }
    +
    +    async dismissNotificationEventForAllRecipients(eventId: string): Promise<number> {
    +        return this.dismissNotificationEventsForAllRecipients([eventId]);
    +    }
    +
    +    async dismissNotificationEventsForAllRecipients(eventIds: readonly string[]): Promise<number> {
    +        const uniqueEventIds = [...new Set(eventIds)];
    +        for (const eventId of uniqueEventIds) {
    +            assertIdentifier(eventId, 'notification eventId');
    +        }
    +        if (uniqueEventIds.length === 0) return 0;
    +
    +        const timestamp = normalizeISO8601Timestamp(this.now());
    +        const updated = await this.database('notification_user_states')
    +            .whereIn('event_id', uniqueEventIds)
    +            .where({ inbox_enabled: true })
    +            .whereNull('dismissed_at')
    +            .update({ dismissed_at: timestamp });
    +
    +        return Number(updated ?? 0);
    +    }
    +
    +    async dismissNotificationsForPullRequest(
    +        repository: string,
    +        prNumber: number,
    +        options: NotificationAutoDismissOptions = {}
    +    ): Promise<number> {
    +        assertRepositoryName(repository);
    +        assertPositiveInteger(prNumber, 'notification pull request number');
    +        return this.dismissMatchingNotifications(
    +            options.kinds ?? PR_RELATED_NOTIFICATION_KINDS,
    +            event => notificationMatchesPullRequest(event, repository, prNumber),
    +            options.exceptEventIds ?? []
    +        );
    +    }
    +
    +    async dismissNotificationsForSystemComponent(
    +        component: string,
    +        options: NotificationAutoDismissOptions = {}
    +    ): Promise<number> {
    +        assertIdentifier(component, 'notification system component');
    +        return this.dismissMatchingNotifications(
    +            options.kinds ?? ['system_failure'],
    +            event => event.target.type === 'system_failure' && event.target.component === component,
    +            options.exceptEventIds ?? []
    +        );
    +    }
    +
    +    private async dismissMatchingNotifications(
    +        kinds: readonly NotificationKind[],
    +        matches: (event: NotificationEvent) => boolean,
    +        exceptEventIds: readonly string[]
    +    ): Promise<number> {
    +        const uniqueKinds = [...new Set(kinds)];
    +        const except = new Set(exceptEventIds);
    +        for (const eventId of except) {
    +            assertIdentifier(eventId, 'notification eventId');
    +        }
    +        if (uniqueKinds.length === 0) return 0;
    +
    +        const rows = await this.database<NotificationEventRow>('notification_events')
    +            .select(eventOnlySelectColumns())
    +            .whereIn('kind', uniqueKinds);
    +        const matchingEventIds = rows.flatMap(row => {
    +            const event = toNotificationEvent(row);
    +            // Exclusions let a producer create the newest replacement event first,
    +            // then close older matching receipts without accidentally hiding the
    +            // freshly-created notification during idempotent redelivery.
    +            return !except.has(event.id) && matches(event) ? [event.id] : [];
    +        });
    +
    +        return this.dismissNotificationEventsForAllRecipients(matchingEventIds);
    +    }
    @@
     export const dismissNotification = notificationService.dismissNotification
         .bind(notificationService) as NotificationService['dismissNotification'];
    +export const dismissNotificationEventForAllRecipients = notificationService.dismissNotificationEventForAllRecipients
    +    .bind(notificationService) as NotificationService['dismissNotificationEventForAllRecipients'];
    +export const dismissNotificationEventsForAllRecipients = notificationService.dismissNotificationEventsForAllRecipients
    +    .bind(notificationService) as NotificationService['dismissNotificationEventsForAllRecipients'];
    +export const dismissNotificationsForPullRequest = notificationService.dismissNotificationsForPullRequest
    +    .bind(notificationService) as NotificationService['dismissNotificationsForPullRequest'];
    +export const dismissNotificationsForSystemComponent = notificationService.dismissNotificationsForSystemComponent
    +    .bind(notificationService) as NotificationService['dismissNotificationsForSystemComponent'];
     export const getNotificationPreferences = notificationService.getNotificationPreferences

    File: packages/api/services/notificationProjectionService.ts

    Why this file: This service creates the duplicated PR attention and system failure cards. It must create replacement PR attention events safely and use durable projection state for system failures.

    --- a/packages/api/services/notificationProjectionService.ts
    +++ b/packages/api/services/notificationProjectionService.ts
    @@
       NotificationService,
       type CreateNotificationEventInput,
    +  type NotificationAutoDismissOptions,
       type NotificationRecipient,
     } from '@propr/core';
    @@
       type NotificationEventAction,
    +  type NotificationEvent,
       type NotificationKind,
       type TaskUpdatePayload,
     } from '@propr/shared';
    @@
     const TERMINAL_ACTIVITY_STATUSES = new Set(['completed', 'failed', 'cancelled']);
    +const NOTIFICATION_PROJECTION_STATE_TABLE = 'notification_projection_state';
    +const SYSTEM_FAILURE_SCOPE = 'system_failure';
    @@
     interface NotificationEventWriter {
       createNotificationEvent<K extends NotificationKind>(
         input: CreateNotificationEventInput<K>,
         recipients?: readonly NotificationRecipient[],
    -  ): Promise<unknown>;
    +  ): Promise<NotificationEvent<K>>;
    +  dismissNotificationEventForAllRecipients?: (eventId: string) => Promise<number>;
    +  dismissNotificationEventsForAllRecipients?: (eventIds: readonly string[]) => Promise<number>;
    +  dismissNotificationsForPullRequest?: (
    +    repository: string,
    +    prNumber: number,
    +    options?: NotificationAutoDismissOptions,
    +  ) => Promise<number>;
    +  dismissNotificationsForSystemComponent?: (
    +    component: string,
    +    options?: NotificationAutoDismissOptions,
    +  ) => Promise<number>;
     }
    @@
     interface SystemFailureTransition {
       status: string;
    -  occurredAt: string;
    +  openedAt: string;
    +  shouldNotify: boolean;
    +  previousEventId?: string;
    +}
    +
    +interface SystemFailureStateRow {
    +  scope: string;
    +  subject_key: string;
    +  status: string;
    +  opened_at: string;
    +  latest_seen_at: string;
    +  closed_at: string | null;
    +  notification_event_id: string | null;
    +  created_at: string;
    +  updated_at: string;
     }
    @@
    -  private readonly systemFailures = new Map<string, SystemFailureTransition>();
    -  private readonly latestSystemSnapshotAt = new Map<string, string>();
       private stalledTimer: NodeJS.Timeout | undefined;
    @@
    -      await this.notifications.createNotificationEvent({
    +      const prAttentionEvent = await this.notifications.createNotificationEvent({
             deduplicationKey: stableKey('pr-attention', payload.taskId, context.prNumber, occurredAt),
             kind: 'pull_request',
             severity: 'info',
    @@
             ...pullRequestAction(pullRequestUrl),
             occurredAt,
           }, recipients);
    +      // Create the newest attention event before closing older PR attention
    +      // receipts. This ordering preserves idempotent redelivery: if this same
    +      // task update is replayed, createNotificationEvent returns the existing
    +      // event and the exclusion below prevents hiding it.
    +      await this.notifications.dismissNotificationsForPullRequest?.(
    +        context.repository,
    +        context.prNumber,
    +        { kinds: ['pull_request'], exceptEventIds: [prAttentionEvent.id] },
    +      );
         }
       }
    @@
    -      const latestSnapshotAt = this.latestSystemSnapshotAt.get(component);
    -      if (latestSnapshotAt !== undefined && snapshotAt < latestSnapshotAt) continue;
    -      this.latestSystemSnapshotAt.set(component, snapshotAt);
           if (healthyValues.has(rawStatus)) {
    -        this.systemFailures.delete(component);
    +        const closed = await this.closeSystemFailureTransition(component, snapshotAt);
    +        if (closed?.eventId) {
    +          await this.notifications.dismissNotificationEventForAllRecipients?.(closed.eventId);
    +        } else {
    +          await this.notifications.dismissNotificationsForSystemComponent?.(component);
    +        }
             continue;
           }
     
    -      let transition = this.systemFailures.get(component);
    -      if (!transition || transition.status !== rawStatus) {
    -        transition = { status: rawStatus, occurredAt: snapshotAt };
    -        this.systemFailures.set(component, transition);
    -      }
    -      await this.notifications.createNotificationEvent({
    +      const transition = await this.openSystemFailureTransition(component, rawStatus, snapshotAt);
    +      if (transition.previousEventId) {
    +        await this.notifications.dismissNotificationEventForAllRecipients?.(transition.previousEventId);
    +      }
    +      if (!transition.shouldNotify) continue;
    +
    +      const event = await this.notifications.createNotificationEvent({
             deduplicationKey: stableKey(
    -          'system-failure', component, transition.status, transition.occurredAt,
    +          'system-failure', component, transition.status, transition.openedAt,
             ),
             kind: 'system_failure',
             severity: 'error',
             target: { type: 'system_failure', component },
             title: 'System component unhealthy',
             body: `${component} is not reporting a healthy status.`,
             actions: ['dismiss'],
    -        occurredAt: transition.occurredAt,
    +        metadata: { status: transition.status },
    +        occurredAt: transition.openedAt,
           }, recipients);
    +      await this.linkSystemFailureNotification(component, transition.status, transition.openedAt, event.id, snapshotAt);
         }
       }
    +
    +  private async openSystemFailureTransition(
    +    component: string,
    +    status: string,
    +    snapshotAt: string,
    +  ): Promise<SystemFailureTransition> {
    +    return this.database.transaction(async transaction => {
    +      const existing = await transaction<SystemFailureStateRow>(NOTIFICATION_PROJECTION_STATE_TABLE)
    +        .where({ scope: SYSTEM_FAILURE_SCOPE, subject_key: component })
    +        .first();
    +
    +      if (!existing) {
    +        await transaction(NOTIFICATION_PROJECTION_STATE_TABLE).insert({
    +          scope: SYSTEM_FAILURE_SCOPE,
    +          subject_key: component,
    +          status,
    +          opened_at: snapshotAt,
    +          latest_seen_at: snapshotAt,
    +          closed_at: null,
    +          notification_event_id: null,
    +          created_at: snapshotAt,
    +          updated_at: snapshotAt,
    +        });
    +        return { status, openedAt: snapshotAt, shouldNotify: true };
    +      }
    +
    +      if (existing.closed_at === null && existing.status === status) {
    +        await transaction(NOTIFICATION_PROJECTION_STATE_TABLE)
    +          .where({ scope: SYSTEM_FAILURE_SCOPE, subject_key: component })
    +          .update({ latest_seen_at: snapshotAt, updated_at: snapshotAt });
    +        return {
    +          status,
    +          openedAt: existing.opened_at,
    +          // If a previous projection crashed after recording state but before
    +          // linking the event, retry creation instead of leaving the Inbox silent.
    +          shouldNotify: existing.notification_event_id === null,
    +        };
    +      }
    +
    +      await transaction(NOTIFICATION_PROJECTION_STATE_TABLE)
    +        .where({ scope: SYSTEM_FAILURE_SCOPE, subject_key: component })
    +        .update({
    +          status,
    +          opened_at: snapshotAt,
    +          latest_seen_at: snapshotAt,
    +          closed_at: null,
    +          notification_event_id: null,
    +          updated_at: snapshotAt,
    +        });
    +      return {
    +        status,
    +        openedAt: snapshotAt,
    +        shouldNotify: true,
    +        previousEventId: existing.closed_at === null ? existing.notification_event_id ?? undefined : undefined,
    +      };
    +    });
    +  }
    +
    +  private async closeSystemFailureTransition(
    +    component: string,
    +    snapshotAt: string,
    +  ): Promise<{ eventId?: string } | undefined> {
    +    return this.database.transaction(async transaction => {
    +      const existing = await transaction<SystemFailureStateRow>(NOTIFICATION_PROJECTION_STATE_TABLE)
    +        .where({ scope: SYSTEM_FAILURE_SCOPE, subject_key: component })
    +        .whereNull('closed_at')
    +        .first();
    +      if (!existing) return undefined;
    +
    +      await transaction(NOTIFICATION_PROJECTION_STATE_TABLE)
    +        .where({ scope: SYSTEM_FAILURE_SCOPE, subject_key: component, opened_at: existing.opened_at })
    +        .whereNull('closed_at')
    +        .update({ closed_at: snapshotAt, latest_seen_at: snapshotAt, updated_at: snapshotAt });
    +
    +      return { eventId: existing.notification_event_id ?? undefined };
    +    });
    +  }
    +
    +  private async linkSystemFailureNotification(
    +    component: string,
    +    status: string,
    +    openedAt: string,
    +    eventId: string,
    +    snapshotAt: string,
    +  ): Promise<void> {
    +    // Link conditionally so an older async projection cannot attach its event to
    +    // a state row that has already recovered or changed status.
    +    await this.database(NOTIFICATION_PROJECTION_STATE_TABLE)
    +      .where({ scope: SYSTEM_FAILURE_SCOPE, subject_key: component, status, opened_at: openedAt })
    +      .whereNull('closed_at')
    +      .update({ notification_event_id: eventId, latest_seen_at: snapshotAt, updated_at: snapshotAt });
    +  }
     
       private async loadTaskContext(payload: TaskUpdatePayload): Promise<TaskContext | undefined> {

    File: packages/core/src/webhook/planIssueTracking.ts

    Why this file: PR merge relevance is known in the webhook tracking path for every intake mode. Closing PR notifications here makes the behavior work for routing websocket, polling, and direct webhook deployments.

    --- a/packages/core/src/webhook/planIssueTracking.ts
    +++ b/packages/core/src/webhook/planIssueTracking.ts
    @@
     import { loadPrLabel } from '../config/configManager.js';
    +import { dismissNotificationsForPullRequest } from '../services/notificationService.js';
    @@
     async function checkRenamesFromPRBody(
    @@
     }
    +
    +async function closeMergedPrInboxNotifications(
    +    repository: string,
    +    prNumber: number,
    +    log: ReturnType<typeof logger.withCorrelation>
    +): Promise<void> {
    +    try {
    +        // Merged PRs are no longer actionable in Inbox. Close matching receipts
    +        // instead of deleting immutable events so notification history remains
    +        // auditable while active Inbox views stay relevant.
    +        const dismissed = await dismissNotificationsForPullRequest(repository, prNumber);
    +        if (dismissed > 0) {
    +            log.info({ repository, prNumber, dismissed }, 'Closed stale Inbox notifications for merged PR');
    +        }
    +    } catch (error) {
    +        log.warn({ repository, prNumber, error: (error as Error).message }, 'Failed to close merged PR Inbox notifications');
    +    }
    +}
    @@
             await checkRenamesFromPRBody(payload, repository, prNumber, log);
    +        if (action === 'closed' && payload.pull_request.merged === true) {
    +            await closeMergedPrInboxNotifications(repository, prNumber, log);
    +        }
     
             const prTitle = payload.pull_request.title || '';

    File: packages/api/test/notificationProjectionService.test.ts

    Why this file: The projection service is where duplicate PR attention and duplicate system health notifications are created. These tests protect the new lifecycle behavior directly.

    --- a/packages/api/test/notificationProjectionService.test.ts
    +++ b/packages/api/test/notificationProjectionService.test.ts
    @@
     import { up as addNotificationPreferenceApis } from '../../core/src/db/migrations/20260802010000_add_notification_preference_apis.js';
     import { up as addAdvertisedActions } from '../../core/src/db/migrations/20260824020000_add_notification_advertised_actions.js';
    +import { up as addNotificationProjectionState } from '../../core/src/db/migrations/20260829000000_add_notification_projection_state.js';
     import { NotificationProjectionService } from '../services/notificationProjectionService.js';
    @@
       await createNotificationSchema(database);
       await addNotificationPreferenceApis(database);
       await addAdvertisedActions(database);
    +  await addNotificationProjectionState(database);
    @@
       test('deduplicates one unhealthy period and allows a later failure after recovery', async () => {
    @@
       });
    +
    +  test('deduplicates system failures across projection instances and closes them on recovery', async () => {
    +    const first = new NotificationProjectionService({
    +      database,
    +      notificationService: new NotificationService({ database, now: () => new Date(clock) }),
    +      now: () => new Date(clock),
    +      stalledAfterMs: 10_000,
    +    });
    +    const second = new NotificationProjectionService({
    +      database,
    +      notificationService: new NotificationService({ database, now: () => new Date(clock) }),
    +      now: () => new Date(clock),
    +      stalledAfterMs: 10_000,
    +    });
    +    const unhealthy = {
    +      timestamp: iso(), api: 'healthy', redis: 'connected', daemon: 'running',
    +      worker: 'running', githubAuth: 'connected', githubEventIntakeStatus: 'active',
    +      claudeAuth: 'disconnected', indexing: 'idle',
    +    };
    +
    +    await first.projectSystemSnapshot(unhealthy);
    +    clock += 1_000;
    +    await second.projectSystemSnapshot({ ...unhealthy, timestamp: iso() });
    +
    +    assert.equal(await database('notification_events').where({ kind: 'system_failure' }).count('* as count').first().then(row => Number(row?.count)), 1);
    +    let listed = await new NotificationService({ database }).listNotifications('admin-user');
    +    assert.equal(listed.notifications.some(notification => notification.target.type === 'system_failure'), true);
    +
    +    clock += 1_000;
    +    await second.projectSystemSnapshot({ ...unhealthy, timestamp: iso(), claudeAuth: 'connected' });
    +
    +    listed = await new NotificationService({ database }).listNotifications('admin-user');
    +    assert.equal(listed.notifications.some(notification => notification.target.type === 'system_failure'), false);
    +  });
    +
    +  test('keeps only the newest active PR attention notification for a pull request', async () => {
    +    const firstAt = iso();
    +    const secondAt = iso(1_000);
    +    await database('tasks').insert([
    +      {
    +        task_id: 'task-pr-attention-first', repository: 'integry/propr', issue_number: 10,
    +        pr_number: 77, task_type: 'issue', initial_job_data: '{}',
    +      },
    +      {
    +        task_id: 'task-pr-attention-second', repository: 'integry/propr', issue_number: 11,
    +        pr_number: 77, task_type: 'issue', initial_job_data: '{}',
    +      },
    +    ]);
    +    await database('task_history').insert([
    +      { task_id: 'task-pr-attention-first', state: 'completed', timestamp: firstAt, metadata: '{}' },
    +      { task_id: 'task-pr-attention-second', state: 'completed', timestamp: secondAt, metadata: '{}' },
    +    ]);
    +
    +    await projection.projectTaskUpdate({
    +      eventType: TASK_UPDATE, taskId: 'task-pr-attention-first', state: 'completed',
    +      repository: 'integry/propr', issueNumber: 10, timestamp: firstAt,
    +    });
    +    clock += 1_000;
    +    await projection.projectTaskUpdate({
    +      eventType: TASK_UPDATE, taskId: 'task-pr-attention-second', state: 'completed',
    +      repository: 'integry/propr', issueNumber: 11, timestamp: secondAt,
    +    });
    +
    +    const listed = await new NotificationService({ database }).listNotifications('admin-user');
    +    const activePrAttention = listed.notifications.filter(notification =>
    +      notification.kind === 'pull_request'
    +      && notification.target.type === 'pull_request'
    +      && notification.target.prNumber === 77);
    +    assert.equal(activePrAttention.length, 1);
    +    assert.equal(activePrAttention[0].body, 'PR #77 is ready for attention.');
    +  });

    File: packages/core/test/notificationService.test.ts

    Why this file: The service-level auto-dismiss helpers are shared by PR merge handling and projection replacement. Unit coverage here verifies the mutable receipt behavior independent of projection logic.

    --- a/packages/core/test/notificationService.test.ts
    +++ b/packages/core/test/notificationService.test.ts
    @@
         test('keeps read and dismissed state idempotent and isolated per user', async () => {
    @@
         });
    +
    +    test('auto-dismisses matching PR and system notifications without deleting events', async () => {
    +        await service.createNotificationEvent({
    +            eventId: 'pr-attention-old',
    +            deduplicationKey: 'pr-attention-old-key',
    +            kind: 'pull_request',
    +            target: { type: 'pull_request', repository: 'integry/propr', prNumber: 42 },
    +            title: 'Pull request needs attention',
    +            body: 'PR #42 is ready for attention.',
    +            recipients: ['user-a', 'user-b']
    +        });
    +        await service.createNotificationEvent({
    +            eventId: 'pr-attention-new',
    +            deduplicationKey: 'pr-attention-new-key',
    +            kind: 'pull_request',
    +            target: { type: 'pull_request', repository: 'integry/propr', prNumber: 42 },
    +            title: 'Pull request needs attention',
    +            body: 'PR #42 is ready for attention.',
    +            recipients: ['user-a']
    +        });
    +        await service.createNotificationEvent({
    +            eventId: 'system-claude-auth',
    +            deduplicationKey: 'system-claude-auth-key',
    +            kind: 'system_failure',
    +            target: { type: 'system_failure', component: 'claudeAuth' },
    +            title: 'System component unhealthy',
    +            body: 'claudeAuth is not reporting a healthy status.',
    +            recipients: ['user-a']
    +        });
    +
    +        const prDismissed = await service.dismissNotificationsForPullRequest(
    +            'integry/propr',
    +            42,
    +            { kinds: ['pull_request'], exceptEventIds: ['pr-attention-new'] }
    +        );
    +        assert.equal(prDismissed, 2);
    +        assert.deepEqual(
    +            (await service.listNotifications('user-a')).notifications.map(notification => notification.id),
    +            ['system-claude-auth', 'pr-attention-new']
    +        );
    +        assert.equal(
    +            await database('notification_events').where({ event_id: 'pr-attention-old' }).count('* as count').first().then(row => Number(row?.count)),
    +            1,
    +            'automatic closure must preserve immutable notification event history'
    +        );
    +
    +        const systemDismissed = await service.dismissNotificationsForSystemComponent('claudeAuth');
    +        assert.equal(systemDismissed, 1);
    +        assert.deepEqual(
    +            (await service.listNotifications('user-a')).notifications.map(notification => notification.id),
    +            ['pr-attention-new']
    +        );
    +    });
     
         test('rejects malformed pagination inputs and clamps large valid limits', async () => {

    Verification

    Run these focused checks after implementation:

    npm test -- packages/api/test/notificationProjectionService.test.ts
    npm test -- packages/core/test/notificationService.test.ts
    npm test -- packages/api/test/mergedPrTaskCancellation.test.ts
    npm run typecheck
  2. propr-dev commented on Aug 29, 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: 1984/gpt-5.6-sol-deduplicate-inbox-notific-20260829-2104-y8t
    • Base Branch: main
    • Worktree: issue-1984-20260829-2104-gpt-5.6-sol-y8t

    🔍 Track Task Execution

  3. added a commit that references this issue on Aug 29, 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