Skip to content

Project plan, task, PR, indexing, stalled, and system transitions into notifications #1719

Closed

Description

@propr-dev

Context

A durable Inbox is useful only if lifecycle transitions are converted into notification events consistently. ProPR already publishes task, draft, and indexing updates for Socket.IO; those centralized publication paths are the safest integration points and avoid scattering notification logic through individual UI routes.

Requirements

  • Project DRAFT_UPDATE, TASK_UPDATE, and INDEXING_UPDATE payloads into durable notification events.
  • Generate plan-ready, task-failed, implementation-completed, review-completed, PR-attention, and indexing-failed events.
  • Maintain notification_activity whenever task or indexing state changes.
  • Add a periodic stalled-task detector with a configurable threshold.
  • Project unhealthy system snapshots into deduplicated system-failure events.
  • Notification projection must be best-effort and must never fail the underlying task or socket publication.
  • Use stable deduplication keys based on entity, state, and transition timestamp.
  • Avoid putting raw prompts, logs, secrets, or stack traces into notification bodies.

Acceptance Criteria

  • A plan entering review creates exactly one plan-ready event.
  • A completed review and completed implementation use different notification kinds.
  • A completed task with a PR creates a separate PR-attention event containing the PR URL.
  • Repeated publication of the same payload does not duplicate events.
  • Active work older than NOTIFICATION_STALLED_AFTER_MS creates one stalled notification for that unchanged transition.
  • Returning to a healthy system and failing again can create a new system-failure event.
  • Projection failures are logged and do not reject the original event publisher call.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Aug 2, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    Use the existing cross-process event publication boundary as the primary projector input. This was chosen over modifying every worker job because the centralized events already describe the state seen by the UI and naturally cover retries. A database activity checkpoint supports stalled detection without relying on long-lived timers for individual tasks. Notification projection remains asynchronous and isolated so an unavailable notification table cannot break core execution.

    File: packages/core/src/services/notificationProjector.ts (new file)

    Why this file: It translates shared lifecycle payloads into notification-domain records in one testable location.

    import { db } from '../db/connection.js';
    import { createNotificationEvent } from './notificationService.js';
    import { DRAFT_UPDATE, INDEXING_UPDATE, TASK_UPDATE } from '@propr/shared';
    
    const stringValue = (value: unknown): string | undefined =>
      typeof value === 'string' && value.trim() ? value.trim() : undefined;
    
    const numberValue = (value: unknown): number | undefined =>
      typeof value === 'number' && Number.isFinite(value) ? value : undefined;
    
    const objectValue = (value: unknown): Record<string, unknown> =>
      value && typeof value === 'object' ? value as Record<string, unknown> : {};
    
    const transitionTime = (payload: Record<string, unknown>): string =>
      stringValue(payload.updatedAt) ?? stringValue(payload.timestamp) ?? new Date().toISOString();
    
    async function trackActivity(
      entityType: string,
      entityId: string,
      state: string,
      projectSlug: string | null,
      deepLink: string,
      occurredAt: string,
      terminal: boolean,
    ): Promise<void> {
      await db('notification_activity').insert({
        entity_type: entityType,
        entity_id: entityId,
        state,
        project_slug: projectSlug,
        deep_link: deepLink,
        last_transition_at: occurredAt,
        terminal,
      }).onConflict(['entity_type', 'entity_id']).merge({
        state,
        project_slug: projectSlug,
        deep_link: deepLink,
        last_transition_at: occurredAt,
        terminal,
      });
    }
    
    async function projectDraft(payload: Record<string, unknown>): Promise<void> {
      const draftId = stringValue(payload.draftId) ?? stringValue(payload.draft_id);
      const status = stringValue(payload.status);
      if (!draftId || !status || !['review', 'ready_for_review'].includes(status)) return;
      const occurredAt = transitionTime(payload);
      await createNotificationEvent({
        kind: 'plan_ready',
        category: 'plans',
        title: 'Plan ready for review',
        body: stringValue(payload.name) ?? 'A generated plan is ready for review.',
        targetType: 'plan',
        targetId: draftId,
        projectSlug: stringValue(payload.repository) ?? null,
        deepLink: `/studio/${encodeURIComponent(draftId)}`,
        actions: ['refine', 'approve_execute', 'dismiss'],
        metadata: { issueCount: numberValue(payload.issueCount) },
        dedupeKey: `plan:${draftId}:${status}:${occurredAt}`,
        occurredAt,
      });
    }
    
    async function projectTask(payload: Record<string, unknown>): Promise<void> {
      const taskId = stringValue(payload.taskId) ?? stringValue(payload.id);
      const status = stringValue(payload.status);
      if (!taskId || !status) return;
      const occurredAt = transitionTime(payload);
      const repository = stringValue(payload.repository) ?? null;
      const deepLink = `/tasks/${encodeURIComponent(taskId)}`;
      const terminal = ['completed', 'failed', 'cancelled'].includes(status);
      await trackActivity('task', taskId, status, repository, deepLink, occurredAt, terminal);
    
      if (status === 'failed') {
        await createNotificationEvent({
          kind: 'task_failed',
          category: 'tasks',
          title: 'Task failed',
          // Keep push-safe summaries concise; detailed errors remain behind auth on
          // the task page and are not copied into lock-screen payloads.
          body: stringValue(payload.title) ?? 'A ProPR task needs attention.',
          targetType: 'task',
          targetId: taskId,
          projectSlug: repository,
          deepLink,
          actions: ['follow_up', 'dismiss'],
          dedupeKey: `task:${taskId}:failed:${occurredAt}`,
          occurredAt,
        });
        return;
      }
    
      if (status !== 'completed') return;
      const commandMode = stringValue(payload.commandMode) ?? 'implementation';
      const review = commandMode === 'review';
      await createNotificationEvent({
        kind: review ? 'review_completed' : 'implementation_completed',
        category: 'tasks',
        title: review ? 'Review completed' : 'Implementation completed',
        body: stringValue(payload.title) ?? 'Task results are ready.',
        targetType: 'task',
        targetId: taskId,
        projectSlug: repository,
        deepLink,
        actions: ['follow_up', 'dismiss'],
        dedupeKey: `task:${taskId}:${commandMode}:completed:${occurredAt}`,
        occurredAt,
      });
    
      const prUrl = stringValue(payload.prUrl) ?? stringValue(objectValue(payload.pr).url);
      if (prUrl) {
        await createNotificationEvent({
          kind: 'pr_attention',
          category: 'pull_requests',
          title: 'Pull request ready for attention',
          body: stringValue(payload.title) ?? 'Review the completed pull request.',
          targetType: 'task',
          targetId: taskId,
          projectSlug: repository,
          deepLink,
          prUrl,
          actions: ['open_pr', 'follow_up', 'dismiss'],
          dedupeKey: `task:${taskId}:pr:${prUrl}`,
          occurredAt,
        });
      }
    }
    
    async function projectIndexing(payload: Record<string, unknown>): Promise<void> {
      const repository = stringValue(payload.repository) ?? stringValue(payload.full_name);
      const status = stringValue(payload.status) ?? stringValue(payload.indexing_status);
      if (!repository || !status) return;
      const occurredAt = transitionTime(payload);
      const deepLink = `/repositories?repository=${encodeURIComponent(repository)}`;
      await trackActivity('repository', repository, status, repository, deepLink, occurredAt, status !== 'indexing');
      if (status !== 'failed') return;
      await createNotificationEvent({
        kind: 'indexing_failed',
        category: 'indexing',
        title: 'Repository indexing failed',
        body: `${repository} could not be indexed.`,
        targetType: 'repository',
        targetId: repository,
        projectSlug: repository,
        deepLink,
        actions: ['dismiss'],
        dedupeKey: `indexing:${repository}:failed:${occurredAt}`,
        occurredAt,
      });
    }
    
    export async function projectPublishedEvent(channel: string, rawPayload: unknown): Promise<void> {
      const payload = objectValue(rawPayload);
      if (channel === DRAFT_UPDATE) await projectDraft(payload);
      if (channel === TASK_UPDATE) await projectTask(payload);
      if (channel === INDEXING_UPDATE) await projectIndexing(payload);
    }
    
    export async function projectSystemHealthSnapshot(snapshot: Record<string, unknown>): Promise<void> {
      const failed = Object.entries(snapshot)
        .filter(([, value]) => ['failed', 'stopped', 'disconnected', 'unavailable'].includes(String(value).toLowerCase()))
        .map(([name]) => name)
        .sort();
      if (failed.length === 0) return;
      const minute = new Date().toISOString().slice(0, 16);
      await createNotificationEvent({
        kind: 'system_failed',
        category: 'system',
        title: 'ProPR system failure',
        body: `Unavailable services: ${failed.join(', ')}`,
        targetType: 'system',
        targetId: 'system-health',
        deepLink: '/?panel=system-health',
        actions: ['dismiss'],
        dedupeKey: `system:${failed.join(',')}:${minute}`,
      });
    }

    File: packages/core/src/utils/eventPublisher.ts

    Why this file: This is the centralized lifecycle publication point. Projection is deliberately fire-and-report so notifications cannot block socket delivery or worker progress.

    --- a/packages/core/src/utils/eventPublisher.ts
    +++ b/packages/core/src/utils/eventPublisher.ts
    @@ -1,5 +1,6 @@
    +import { projectPublishedEvent } from '../services/notificationProjector.js';
    @@ -80,6 +81,13 @@
       await this.redis.publish(channel, serializedPayload);
    +
    +  // Notification persistence is a secondary projection of an already accepted
    +  // lifecycle transition. Log failures, but never turn a successful task update
    +  // into a task failure because the optional Inbox projection is unavailable.
    +  void projectPublishedEvent(channel, payload).catch(error => {
    +    logger.warn({ error: (error as Error).message, channel }, 'Notification projection failed');
    +  });

    File: packages/core/src/services/notificationMonitor.ts (new file)

    Why this file: Stalled work is an absence of transitions, so it cannot be detected by an individual transition mapper. A bounded periodic query is more reliable than one timer per task.

    import { db } from '../db/connection.js';
    import logger from '../utils/logger.js';
    import { createNotificationEvent } from './notificationService.js';
    
    const defaultStalledAfterMs = 45 * 60 * 1000;
    
    export async function detectStalledNotifications(now = new Date()): Promise<number> {
      const configured = Number(process.env.NOTIFICATION_STALLED_AFTER_MS ?? defaultStalledAfterMs);
      const stalledAfterMs = Number.isFinite(configured) && configured > 0 ? configured : defaultStalledAfterMs;
      const cutoff = new Date(now.getTime() - stalledAfterMs).toISOString();
      const rows = await db('notification_activity')
        .where({ entity_type: 'task', terminal: false })
        .whereIn('state', ['queued', 'processing', 'claude_execution', 'post_processing'])
        .andWhere('last_transition_at', '<=', cutoff);
    
      for (const row of rows) {
        await createNotificationEvent({
          kind: 'task_stalled',
          category: 'tasks',
          title: 'Task may be stalled',
          body: `Task ${row.entity_id} has remained in ${row.state} without progress.`,
          targetType: 'task',
          targetId: row.entity_id,
          projectSlug: row.project_slug,
          deepLink: row.deep_link,
          actions: ['stop', 'follow_up', 'dismiss'],
          // A new transition changes this key and permits a future legitimate alert.
          dedupeKey: `task:${row.entity_id}:stalled:${row.last_transition_at}`,
          occurredAt: now.toISOString(),
        });
      }
      return rows.length;
    }
    
    export function startNotificationMonitor(): () => void {
      const run = () => void detectStalledNotifications().catch(error => {
        logger.warn({ error: (error as Error).message }, 'Stalled notification scan failed');
      });
      run();
      const timer = setInterval(run, 60_000);
      timer.unref();
      return () => clearInterval(timer);
    }

    File: packages/api/server.ts

    Why this file: The API is already a continuously running authenticated control-plane process. Starting one inexpensive monitor here avoids adding a new container for the focused PWA release.

    --- a/packages/api/server.ts
    +++ b/packages/api/server.ts
    @@ -1,5 +1,6 @@
    +import { startNotificationMonitor } from '@propr/core';
    @@ -220,6 +221,10 @@
    +// The scan is database-backed and idempotent, so an API restart does not lose
    +// stall detection state or duplicate alerts.
    +const stopNotificationMonitor = startNotificationMonitor();
    @@ -260,6 +265,7 @@
    +  stopNotificationMonitor();
  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: 1719/gpt-5.6-sol-project-plan-task-pr-inde-20260802-1619-o9q
    • Base Branch: 1716-epic-failed-to-3m8
    • Worktree: issue-1719-20260802-1619-gpt-5.6-sol-o9q

    🔍 Track Task Execution

  3. added a commit that references this issue on Aug 2, 2026
  4. integry commented on Aug 24, 2026

    @integry
    Owner

    Reimplementation guidance after retiring oversized PR #1734:

    Start clean from the branch selected by base-1716-epic-failed-to-3m8 and implement this issue narrowly. Reuse the notification schema, persistence service, preferences, subscription APIs, and existing lifecycle/event boundaries delivered by #1716-#1718.

    Scope constraints:

    • Project the requested plan, task, PR-attention, indexing, stalled, and system transitions into durable notifications.
    • Add small adapters at existing publication/health boundaries; keep notification projection best-effort and idempotent.
    • Do not redesign authentication/session handling, Docker execution, worker-state persistence, indexing cancellation/state machines, BullMQ retention, or general queue infrastructure.
    • Do not modify already-applied migrations; add a forward migration only if this issue truly needs new state beyond the epic schema.
    • Preserve current authorization boundaries and never expose raw prompts, logs, errors, tokens, or arbitrary external URLs in notification payloads.
    • Add focused projection tests covering deduplication, stale/out-of-order transitions, recipient authorization, URL sanitization, and failure isolation.

    Keep the diff reviewable and directly attributable to #1719. If an existing subsystem cannot support a requested transition without a broad redesign, document the narrow limitation instead of absorbing that redesign into this PR. Run /ultrafix goal=8 max=10 on the resulting PR.

  5. propr-dev commented on Aug 24, 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: 1719/gpt-5.6-sol-project-plan-task-pr-inde-20260824-0029-qxz
    • Base Branch: 1716-epic-failed-to-3m8
    • Worktree: issue-1719-20260824-0029-gpt-5.6-sol-qxz

    🔍 Track Task Execution

  6. added a commit that references this issue on Aug 24, 2026
  7. added a commit that references this issue on Aug 24, 2026
  8. 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