/** * Notification model for the factory. Notifications are lightweight records * created by factory events (stalls, state changes, errors, PR updates). */ import { DEFAULT_QUIET_HOURS, isQuietHours, normalizeQuietHours, type QuietHours } from '../lib/quiet-hours.ts' export type NotificationSeverity = 'info' | 'warning' | 'error' export type NotificationCategory = | 'stall' | 'needs-kent' | 'state-change' | 'pr-update' | 'error' | 'health' | 'agent' | 'merge' export type NotificationStatus = 'unread' | 'read' export type Notification = { id: string projectId: string title: string body: string severity: NotificationSeverity category: NotificationCategory status: NotificationStatus /** Work item or plan id this notification relates to, if any. */ itemId: string | null /** Source that created this notification (e.g. 'sweep', 'health', 'webhook'). */ source: string createdAt: string } export type NotificationRule = { /** Which categories produce notifications for this project. Empty means all. */ categories: NotificationCategory[] /** Minimum severity to notify. Default 'info' (everything). */ minSeverity: NotificationSeverity /** Whether Discord output is enabled for this project. */ discordEnabled: boolean /** Whether bot wake output is enabled for this project. */ wakeEnabled: boolean /** Web push to subscribed devices. Default true; nothing is sent until a device subscribes. */ pushEnabled: boolean /** A new card with any of these labels is pushed. Default `['sentry', 'signal']`. */ pushLabels: string[] /** Push new needs-attention cards and `needs-kent` notifications. Default true. */ pushNeedsAttention: boolean /** * Push a card when its priority is at or above this (0 is highest), on * create and when it is raised to it. Default 1 (P0 and P1). null turns * priority pushes off. */ pushMinPriority: number | null /** * Card pushes during quiet hours wait for the morning digest, except * cards at or above this priority (default 0: P0 pushes any time). */ pushQuietHoursBypassPriority: number | null /** Quiet hours for card pushes. Default 22 to 8 America/Denver. */ quietHours: QuietHours } export type NotificationRules = { /** Default rules for projects without specific overrides. */ defaults: NotificationRule /** Per-project overrides. */ projects: Record> } export const ALL_CATEGORIES: NotificationCategory[] = [ 'stall', 'needs-kent', 'state-change', 'pr-update', 'error', 'health', 'agent', 'merge', ] export const SEVERITY_ORDER: Record = { info: 0, warning: 1, error: 2 } export function defaultNotificationRules(): NotificationRules { return { defaults: { categories: [], minSeverity: 'info', discordEnabled: false, wakeEnabled: false, pushEnabled: true, pushLabels: ['sentry', 'signal'], pushNeedsAttention: true, pushMinPriority: 1, pushQuietHoursBypassPriority: 0, quietHours: { ...DEFAULT_QUIET_HOURS }, }, projects: {}, } } export function resolveRules(rules: NotificationRules, projectId: string): NotificationRule { // Stored rules from before the push channel existed lack its fields; fill them from the defaults. const base = { ...defaultNotificationRules().defaults, ...(rules?.defaults ?? {}) } const override = rules?.projects?.[projectId] const merged = override ? { ...base, ...override } : base return { ...merged, quietHours: normalizeQuietHours(merged.quietHours), pushMinPriority: normPriority(merged.pushMinPriority), pushQuietHoursBypassPriority: normPriority(merged.pushQuietHoursBypassPriority) } } function normPriority(v: unknown): number | null { return typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= 3 ? v : null } export type CardPushDecision = { send: 'now' | 'hold' | 'none'; reason: string } /** * Card push decision: why a card is pushed (needs attention, label, or * priority), and whether quiet hours hold it for the morning digest. */ export function decideCardPush( rule: NotificationRule, card: { labels: string[]; needsKent: boolean; priority: number | null }, now: number, ): CardPushDecision { if (!rule.pushEnabled) return { send: 'none', reason: 'push off' } let reason: string | null = null if (typeof rule.pushMinPriority === 'number' && card.priority !== null && card.priority <= rule.pushMinPriority) reason = `P${card.priority}` else if (shouldPushCard(rule, card)) reason = rule.pushNeedsAttention && card.needsKent ? 'needs attention' : 'label' if (!reason) return { send: 'none', reason: 'no rule matched' } const bypass = typeof rule.pushQuietHoursBypassPriority === 'number' && card.priority !== null && card.priority <= rule.pushQuietHoursBypassPriority if (!bypass && isQuietHours(now, rule.quietHours)) return { send: 'hold', reason: `${reason}, quiet hours` } return { send: 'now', reason } } /** Should a new card be pushed under this rule? */ export function shouldPushCard(rule: NotificationRule, card: { labels: string[]; needsKent: boolean }): boolean { if (!rule.pushEnabled) return false if (rule.pushNeedsAttention && card.needsKent) return true const want = new Set((rule.pushLabels ?? []).map((l) => l.toLowerCase())) return card.labels.some((l) => want.has(l.toLowerCase()) || (l.toLowerCase().startsWith('source:') && want.has(l.toLowerCase().slice(7)))) } export function shouldNotify(rule: NotificationRule, category: NotificationCategory, severity: NotificationSeverity): boolean { if (rule.categories.length > 0 && !rule.categories.includes(category)) return false if (SEVERITY_ORDER[severity] < SEVERITY_ORDER[rule.minSeverity]) return false return true } export function newNotificationId(): string { return `notif_${crypto.randomUUID().replace(/-/g, '').slice(0, 16)}` }