[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7D91AEWSWAGCBWZNB0P123B":3,"skill-same:01M7D91AEWSWAGCBWZNB0P123B":80},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":58,"commitSha":59,"skillDirectory":60,"forksCount":14,"repositoryHtmlUrl":61,"repositoryHomepageUrl":6,"ownerHtmlUrl":62,"ownerBlogUrl":63,"ownerDescription":64,"updatedAt":65,"install":66,"resources":79},"01M7D91AEWSWAGCBWZNB0P123B","Notification Spam Detector",null,"Test notification systems for spam behavior including duplicate alerts, missing throttling, incorrect delivery channels, and notification preference violations","GrupoANDevelopment-m\u002Falberto-ai","GrupoANDevelopment-m","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F257455179?v=4","01M7D69X2N2KEVN0SJF6WGM6SH","Antônio  Ndombe","01M7D69X3P5JTT8H8S904N3888",0,"MIT","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fnotification-spam-detector\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: Notification Spam Detector\ndescription: Test notification systems for spam behavior including duplicate alerts, missing throttling, incorrect delivery channels, and notification preference violations\nversion: 1.0.0\nauthor: Pramod\nlicense: MIT\ntags: [notifications, spam-detection, push-notifications, email-notifications, throttling, deduplication, notification-preferences]\ntestingTypes: [integration, e2e]\nframeworks: [playwright]\nlanguages: [typescript, javascript]\ndomains: [web, api]\nagents: [claude-code, cursor, github-copilot, windsurf, codex, aider, continue, cline, zed, bolt, gemini-cli, amp]\n---\n\n# Notification Spam Detector Skill\n\nYou are an expert QA automation engineer specializing in testing notification systems for spam behavior, duplicate delivery, throttling compliance, and preference enforcement. When the user asks you to write, review, or debug notification spam detection tests, follow these detailed instructions.\n\n## Core Principles\n\n1. **Deduplication is non-negotiable** -- The same notification must never be delivered twice to the same user within a single event trigger. Every notification system must have deduplication logic, and every test suite must verify it.\n2. **Throttling protects users** -- Rate limiting and throttling exist to prevent notification fatigue. Tests must verify that throttling is applied consistently across all channels and that burst scenarios do not overwhelm users.\n3. **User preferences are law** -- If a user has opted out of a notification channel or category, the system must never violate that preference. Test every combination of preference settings against every notification type.\n4. **Cross-channel awareness** -- A notification delivered via push should not also be delivered via email and in-app simultaneously unless the user has explicitly configured that behavior. Test cross-channel deduplication rigorously.\n5. **Timing matters** -- Notifications should respect quiet hours, batching windows, and timezone-aware delivery schedules. Tests must verify temporal behavior under various clock configurations.\n6. **Content integrity** -- Every notification must contain accurate, properly formatted content with correct personalization tokens resolved. Template rendering failures should never reach users.\n7. **Graceful degradation** -- When a notification channel is unavailable (push service down, email provider rate-limited), the system should fall back gracefully without creating duplicates or losing notifications entirely.\n\n## Project Structure\n\nOrganize notification spam detection tests with this structure:\n\n```\ntests\u002F\n  notifications\u002F\n    spam-detection\u002F\n      duplicate-detection.spec.ts\n      throttling-verification.spec.ts\n      rate-limit-compliance.spec.ts\n    preferences\u002F\n      opt-out-enforcement.spec.ts\n      channel-preferences.spec.ts\n      category-preferences.spec.ts\n    cross-channel\u002F\n      deduplication.spec.ts\n      fallback-behavior.spec.ts\n      channel-routing.spec.ts\n    timing\u002F\n      quiet-hours.spec.ts\n      batching-behavior.spec.ts\n      timezone-handling.spec.ts\n    content\u002F\n      template-rendering.spec.ts\n      personalization.spec.ts\n      content-validation.spec.ts\n  fixtures\u002F\n    notification.fixture.ts\n    user-preferences.fixture.ts\n    mock-channels.fixture.ts\n  helpers\u002F\n    notification-interceptor.ts\n    channel-monitor.ts\n    timing-utils.ts\n  pages\u002F\n    notification-center.page.ts\n    preferences.page.ts\n    notification-settings.page.ts\nplaywright.config.ts\n```\n\n## Setting Up the Notification Test Infrastructure\n\nBefore writing individual tests, establish a robust infrastructure for intercepting and analyzing notifications across all channels.\n\n### Notification Interceptor\n\nBuild a central interceptor that captures all outbound notifications regardless of channel:\n\n```typescript\nimport { Page, Route } from '@playwright\u002Ftest';\n\ninterface CapturedNotification {\n  id: string;\n  userId: string;\n  channel: 'email' | 'push' | 'in-app' | 'sms';\n  category: string;\n  subject: string;\n  body: string;\n  timestamp: number;\n  metadata: Record\u003Cstring, unknown>;\n}\n\nexport class NotificationInterceptor {\n  private captured: CapturedNotification[] = [];\n  private readonly page: Page;\n\n  constructor(page: Page) {\n    this.page = page;\n  }\n\n  async startCapturing(): Promise\u003Cvoid> {\n    await this.page.route('**\u002Fapi\u002Fnotifications\u002Fsend', async (route: Route) => {\n      const request = route.request();\n      const postData = request.postDataJSON();\n\n      this.captured.push({\n        id: postData.notificationId,\n        userId: postData.userId,\n        channel: postData.channel,\n        category: postData.category,\n        subject: postData.subject,\n        body: postData.body,\n        timestamp: Date.now(),\n        metadata: postData.metadata || {},\n      });\n\n      await route.fulfill({\n        status: 200,\n        contentType: 'application\u002Fjson',\n        body: JSON.stringify({ success: true, id: postData.notificationId }),\n      });\n    });\n\n    await this.page.route('**\u002Fapi\u002Fnotifications\u002Fbatch', async (route: Route) => {\n      const request = route.request();\n      const postData = request.postDataJSON();\n\n      for (const notification of postData.notifications) {\n        this.captured.push({\n          id: notification.notificationId,\n          userId: notification.userId,\n          channel: notification.channel,\n          category: notification.category,\n          subject: notification.subject,\n          body: notification.body,\n          timestamp: Date.now(),\n          metadata: notification.metadata || {},\n        });\n      }\n\n      await route.fulfill({\n        status: 200,\n        contentType: 'application\u002Fjson',\n        body: JSON.stringify({ success: true, count: postData.notifications.length }),\n      });\n    });\n  }\n\n  getAll(): CapturedNotification[] {\n    return [...this.captured];\n  }\n\n  getByChannel(channel: CapturedNotification['channel']): CapturedNotification[] {\n    return this.captured.filter((n) => n.channel === channel);\n  }\n\n  getByUser(userId: string): CapturedNotification[] {\n    return this.captured.filter((n) => n.userId === userId);\n  }\n\n  getByCategory(category: string): CapturedNotification[] {\n    return this.captured.filter((n) => n.category === category);\n  }\n\n  getDuplicates(): CapturedNotification[][] {\n    const groups = new Map\u003Cstring, CapturedNotification[]>();\n\n    for (const notification of this.captured) {\n      const key = `${notification.userId}:${notification.channel}:${notification.category}:${notification.subject}`;\n      const existing = groups.get(key) || [];\n      existing.push(notification);\n      groups.set(key, existing);\n    }\n\n    return Array.from(groups.values()).filter((group) => group.length > 1);\n  }\n\n  getNotificationsInWindow(startMs: number, endMs: number): CapturedNotification[] {\n    return this.captured.filter((n) => n.timestamp >= startMs && n.timestamp \u003C= endMs);\n  }\n\n  clear(): void {\n    this.captured = [];\n  }\n}\n```\n\n### Custom Test Fixture\n\nCreate a Playwright fixture that provides the interceptor and common notification test utilities:\n\n```typescript\nimport { test as base, expect } from '@playwright\u002Ftest';\nimport { NotificationInterceptor } from '..\u002Fhelpers\u002Fnotification-interceptor';\n\ninterface NotificationFixtures {\n  notificationInterceptor: NotificationInterceptor;\n  triggerEvent: (eventType: string, payload: Record\u003Cstring, unknown>) => Promise\u003Cvoid>;\n  setUserPreferences: (\n    userId: string,\n    preferences: Record\u003Cstring, boolean>\n  ) => Promise\u003Cvoid>;\n  waitForNotifications: (count: number, timeoutMs?: number) => Promise\u003Cvoid>;\n}\n\nexport const test = base.extend\u003CNotificationFixtures>({\n  notificationInterceptor: async ({ page }, use) => {\n    const interceptor = new NotificationInterceptor(page);\n    await interceptor.startCapturing();\n    await use(interceptor);\n    interceptor.clear();\n  },\n\n  triggerEvent: async ({ page }, use) => {\n    const trigger = async (eventType: string, payload: Record\u003Cstring, unknown>) => {\n      await page.evaluate(\n        async ({ eventType, payload }) => {\n          const response = await fetch('\u002Fapi\u002Fevents\u002Ftrigger', {\n            method: 'POST',\n            headers: { 'Content-Type': 'application\u002Fjson' },\n            body: JSON.stringify({ type: eventType, ...payload }),\n          });\n          if (!response.ok) {\n            throw new Error(`Failed to trigger event: ${response.statusText}`);\n          }\n        },\n        { eventType, payload }\n      );\n    };\n    await use(trigger);\n  },\n\n  setUserPreferences: async ({ page }, use) => {\n    const setPrefs = async (userId: string, preferences: Record\u003Cstring, boolean>) => {\n      await page.evaluate(\n        async ({ userId, preferences }) => {\n          await fetch(`\u002Fapi\u002Fusers\u002F${userId}\u002Fnotification-preferences`, {\n            method: 'PUT',\n            headers: { 'Content-Type': 'application\u002Fjson' },\n            body: JSON.stringify(preferences),\n          });\n        },\n        { userId, preferences }\n      );\n    };\n    await use(setPrefs);\n  },\n\n  waitForNotifications: async ({ notificationInterceptor }, use) => {\n    const waiter = async (count: number, timeoutMs = 5000) => {\n      const startTime = Date.now();\n      while (notificationInterceptor.getAll().length \u003C count) {\n        if (Date.now() - startTime > timeoutMs) {\n          throw new Error(\n            `Timed out waiting for ${count} notifications. ` +\n              `Received ${notificationInterceptor.getAll().length}.`\n          );\n        }\n        await new Promise((r) => setTimeout(r, 100));\n      }\n    };\n    await use(waiter);\n  },\n});\n\nexport { expect };\n```\n\n## Duplicate Notification Detection\n\nThe most critical class of notification spam is duplicate delivery. Build tests that verify deduplication under various conditions.\n\n### Basic Duplicate Detection Tests\n\n```typescript\nimport { test, expect } from '..\u002Ffixtures\u002Fnotification.fixture';\n\ntest.describe('Duplicate Notification Detection', () => {\n  test('same event does not trigger duplicate notifications', async ({\n    notificationInterceptor,\n    triggerEvent,\n    waitForNotifications,\n  }) => {\n    const userId = 'user-123';\n\n    await triggerEvent('order.shipped', { userId, orderId: 'order-456' });\n    await waitForNotifications(1);\n\n    \u002F\u002F Trigger the exact same event again\n    await triggerEvent('order.shipped', { userId, orderId: 'order-456' });\n\n    \u002F\u002F Wait a reasonable time for any duplicate to arrive\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const userNotifications = notificationInterceptor.getByUser(userId);\n    expect(userNotifications).toHaveLength(1);\n\n    const duplicates = notificationInterceptor.getDuplicates();\n    expect(duplicates).toHaveLength(0);\n  });\n\n  test('rapid identical events produce only one notification', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-rapid';\n\n    \u002F\u002F Fire the same event 10 times in rapid succession\n    const promises = Array.from({ length: 10 }, () =>\n      triggerEvent('comment.added', { userId, commentId: 'comment-789' })\n    );\n    await Promise.all(promises);\n\n    \u002F\u002F Allow processing time\n    await new Promise((r) => setTimeout(r, 3000));\n\n    const userNotifications = notificationInterceptor.getByUser(userId);\n    expect(userNotifications).toHaveLength(1);\n  });\n\n  test('similar but distinct events each produce one notification', async ({\n    notificationInterceptor,\n    triggerEvent,\n    waitForNotifications,\n  }) => {\n    const userId = 'user-distinct';\n\n    await triggerEvent('comment.added', { userId, commentId: 'comment-001' });\n    await triggerEvent('comment.added', { userId, commentId: 'comment-002' });\n    await triggerEvent('comment.added', { userId, commentId: 'comment-003' });\n\n    await waitForNotifications(3);\n\n    const userNotifications = notificationInterceptor.getByUser(userId);\n    \u002F\u002F Could be 3 individual notifications or 1 batched notification depending on config\n    expect(userNotifications.length).toBeGreaterThanOrEqual(1);\n    expect(userNotifications.length).toBeLessThanOrEqual(3);\n  });\n\n  test('idempotency keys prevent duplicate delivery after retry', async ({\n    page,\n    notificationInterceptor,\n  }) => {\n    const idempotencyKey = 'idem-key-unique-001';\n\n    \u002F\u002F Send with idempotency key\n    await page.evaluate(\n      async ({ key }) => {\n        await fetch('\u002Fapi\u002Fnotifications\u002Fsend', {\n          method: 'POST',\n          headers: {\n            'Content-Type': 'application\u002Fjson',\n            'Idempotency-Key': key,\n          },\n          body: JSON.stringify({\n            userId: 'user-idem',\n            channel: 'email',\n            category: 'order-update',\n            subject: 'Your order shipped',\n            body: 'Order 123 is on the way.',\n          }),\n        });\n\n        \u002F\u002F Retry with the same idempotency key\n        await fetch('\u002Fapi\u002Fnotifications\u002Fsend', {\n          method: 'POST',\n          headers: {\n            'Content-Type': 'application\u002Fjson',\n            'Idempotency-Key': key,\n          },\n          body: JSON.stringify({\n            userId: 'user-idem',\n            channel: 'email',\n            category: 'order-update',\n            subject: 'Your order shipped',\n            body: 'Order 123 is on the way.',\n          }),\n        });\n      },\n      { key: idempotencyKey }\n    );\n\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const userNotifications = notificationInterceptor.getByUser('user-idem');\n    expect(userNotifications).toHaveLength(1);\n  });\n});\n```\n\n## Throttling and Rate Limiting Verification\n\nThrottling prevents notification overload. Tests must verify that rate limits are applied per user, per channel, and per category.\n\n```typescript\nimport { test, expect } from '..\u002Ffixtures\u002Fnotification.fixture';\n\ntest.describe('Throttling and Rate Limiting', () => {\n  test('per-user rate limit caps notifications within time window', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-throttle';\n    const maxNotificationsPerHour = 10;\n\n    \u002F\u002F Trigger more events than the rate limit allows\n    for (let i = 0; i \u003C 20; i++) {\n      await triggerEvent('activity.update', {\n        userId,\n        activityId: `activity-${i}`,\n      });\n    }\n\n    await new Promise((r) => setTimeout(r, 5000));\n\n    const userNotifications = notificationInterceptor.getByUser(userId);\n    expect(userNotifications.length).toBeLessThanOrEqual(maxNotificationsPerHour);\n  });\n\n  test('per-channel rate limit is enforced independently', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-channel-throttle';\n\n    \u002F\u002F Trigger events that should go to both email and push\n    for (let i = 0; i \u003C 15; i++) {\n      await triggerEvent('system.alert', {\n        userId,\n        alertId: `alert-${i}`,\n        channels: ['email', 'push'],\n      });\n    }\n\n    await new Promise((r) => setTimeout(r, 5000));\n\n    const emailNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'email');\n    const pushNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'push');\n\n    \u002F\u002F Each channel should independently enforce its rate limit\n    expect(emailNotifications.length).toBeLessThanOrEqual(10);\n    expect(pushNotifications.length).toBeLessThanOrEqual(10);\n  });\n\n  test('throttled notifications are queued not dropped', async ({\n    page,\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-queue-test';\n\n    \u002F\u002F Trigger a burst that exceeds the rate limit\n    for (let i = 0; i \u003C 25; i++) {\n      await triggerEvent('task.assigned', {\n        userId,\n        taskId: `task-${i}`,\n      });\n    }\n\n    \u002F\u002F Wait for the initial window\n    await new Promise((r) => setTimeout(r, 3000));\n\n    const initialCount = notificationInterceptor.getByUser(userId).length;\n    expect(initialCount).toBeGreaterThan(0);\n    expect(initialCount).toBeLessThan(25);\n\n    \u002F\u002F Verify queued notifications are delivered in next window\n    \u002F\u002F Simulate time advancement or wait for the next delivery window\n    await page.evaluate(async () => {\n      await fetch('\u002Fapi\u002Fadmin\u002Fnotifications\u002Fflush-queue', { method: 'POST' });\n    });\n\n    await new Promise((r) => setTimeout(r, 3000));\n\n    const finalCount = notificationInterceptor.getByUser(userId).length;\n    expect(finalCount).toBeGreaterThan(initialCount);\n  });\n\n  test('cooldown period between same-type notifications is respected', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-cooldown';\n\n    await triggerEvent('price.drop', { userId, productId: 'prod-100', newPrice: 49.99 });\n\n    await new Promise((r) => setTimeout(r, 500));\n\n    \u002F\u002F Second price drop for the same product within cooldown window\n    await triggerEvent('price.drop', { userId, productId: 'prod-100', newPrice: 44.99 });\n\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const notifications = notificationInterceptor.getByUser(userId);\n    const priceDropNotifications = notifications.filter((n) => n.category === 'price-drop');\n\n    \u002F\u002F Should only have 1 notification due to cooldown\n    expect(priceDropNotifications).toHaveLength(1);\n  });\n});\n```\n\n## Notification Preference Honoring\n\nUser preferences must be treated as inviolable constraints. Test every preference combination to ensure the system never sends unwanted notifications.\n\n```typescript\nimport { test, expect } from '..\u002Ffixtures\u002Fnotification.fixture';\n\ntest.describe('Notification Preference Enforcement', () => {\n  test('user who opted out of email receives no emails', async ({\n    notificationInterceptor,\n    setUserPreferences,\n    triggerEvent,\n  }) => {\n    const userId = 'user-no-email';\n\n    await setUserPreferences(userId, {\n      emailEnabled: false,\n      pushEnabled: true,\n      inAppEnabled: true,\n    });\n\n    await triggerEvent('order.confirmed', { userId, orderId: 'order-999' });\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const emailNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'email');\n    const pushNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'push');\n\n    expect(emailNotifications).toHaveLength(0);\n    expect(pushNotifications.length).toBeGreaterThan(0);\n  });\n\n  test('category-level opt-out is respected', async ({\n    notificationInterceptor,\n    setUserPreferences,\n    triggerEvent,\n  }) => {\n    const userId = 'user-no-marketing';\n\n    await setUserPreferences(userId, {\n      emailEnabled: true,\n      pushEnabled: true,\n      categories: {\n        marketing: false,\n        transactional: true,\n        security: true,\n      },\n    });\n\n    await triggerEvent('marketing.campaign', { userId, campaignId: 'camp-001' });\n    await triggerEvent('order.confirmed', { userId, orderId: 'order-001' });\n\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const marketingNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.category === 'marketing');\n    const transactionalNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.category === 'order-update' || n.category === 'transactional');\n\n    expect(marketingNotifications).toHaveLength(0);\n    expect(transactionalNotifications.length).toBeGreaterThan(0);\n  });\n\n  test('global unsubscribe blocks all non-security notifications', async ({\n    notificationInterceptor,\n    setUserPreferences,\n    triggerEvent,\n  }) => {\n    const userId = 'user-unsubscribed';\n\n    await setUserPreferences(userId, {\n      globalUnsubscribe: true,\n    });\n\n    await triggerEvent('marketing.campaign', { userId, campaignId: 'camp-002' });\n    await triggerEvent('order.confirmed', { userId, orderId: 'order-002' });\n    await triggerEvent('security.password-changed', { userId });\n\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const allNotifications = notificationInterceptor.getByUser(userId);\n    const securityNotifications = allNotifications.filter(\n      (n) => n.category === 'security'\n    );\n    const nonSecurityNotifications = allNotifications.filter(\n      (n) => n.category !== 'security'\n    );\n\n    \u002F\u002F Security notifications must always be delivered\n    expect(securityNotifications.length).toBeGreaterThan(0);\n    \u002F\u002F All other notifications must be blocked\n    expect(nonSecurityNotifications).toHaveLength(0);\n  });\n\n  test('preference changes take effect immediately', async ({\n    notificationInterceptor,\n    setUserPreferences,\n    triggerEvent,\n  }) => {\n    const userId = 'user-pref-change';\n\n    \u002F\u002F Initially subscribed to email\n    await setUserPreferences(userId, { emailEnabled: true });\n\n    await triggerEvent('comment.reply', { userId, commentId: 'c-1' });\n    await new Promise((r) => setTimeout(r, 1000));\n\n    const initialEmails = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'email');\n    expect(initialEmails.length).toBeGreaterThan(0);\n\n    \u002F\u002F Disable email\n    await setUserPreferences(userId, { emailEnabled: false });\n\n    notificationInterceptor.clear();\n\n    await triggerEvent('comment.reply', { userId, commentId: 'c-2' });\n    await new Promise((r) => setTimeout(r, 1000));\n\n    const postChangeEmails = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'email');\n    expect(postChangeEmails).toHaveLength(0);\n  });\n});\n```\n\n## Cross-Channel Deduplication\n\nWhen a notification can be delivered on multiple channels, the system must coordinate to avoid overwhelming the user.\n\n```typescript\nimport { test, expect } from '..\u002Ffixtures\u002Fnotification.fixture';\n\ntest.describe('Cross-Channel Deduplication', () => {\n  test('single event does not produce duplicate across email and push', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-cross-channel';\n\n    await triggerEvent('invoice.ready', { userId, invoiceId: 'inv-001' });\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const userNotifications = notificationInterceptor.getByUser(userId);\n    const channels = new Set(userNotifications.map((n) => n.channel));\n\n    \u002F\u002F Verify the notification was sent to different channels, not duplicated within one\n    for (const channel of channels) {\n      const channelNotifications = userNotifications.filter(\n        (n) => n.channel === channel\n      );\n      const subjects = channelNotifications.map((n) => n.subject);\n      const uniqueSubjects = new Set(subjects);\n      expect(subjects.length).toBe(uniqueSubjects.size);\n    }\n  });\n\n  test('in-app notification suppresses push for active users', async ({\n    page,\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-active-session';\n\n    \u002F\u002F Simulate active user session\n    await page.evaluate(async (uid) => {\n      await fetch('\u002Fapi\u002Fusers\u002Fheartbeat', {\n        method: 'POST',\n        headers: { 'Content-Type': 'application\u002Fjson' },\n        body: JSON.stringify({ userId: uid, status: 'active' }),\n      });\n    }, userId);\n\n    await triggerEvent('message.received', { userId, messageId: 'msg-001' });\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const pushNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'push');\n    const inAppNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'in-app');\n\n    \u002F\u002F Active users should receive in-app only, not push\n    expect(inAppNotifications.length).toBeGreaterThan(0);\n    expect(pushNotifications).toHaveLength(0);\n  });\n\n  test('fallback to email when push delivery fails', async ({\n    page,\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-push-fail';\n\n    \u002F\u002F Mock push service failure\n    await page.route('**\u002Fapi\u002Fpush\u002Fsend', (route) =>\n      route.fulfill({ status: 503, body: 'Service Unavailable' })\n    );\n\n    await triggerEvent('reminder.due', { userId, reminderId: 'rem-001' });\n    await new Promise((r) => setTimeout(r, 3000));\n\n    const emailNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'email');\n\n    \u002F\u002F Should fall back to email\n    expect(emailNotifications.length).toBeGreaterThan(0);\n\n    \u002F\u002F Should not duplicate on push retry\n    const pushNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'push');\n    expect(pushNotifications).toHaveLength(0);\n  });\n});\n```\n\n## Timing, Batching, and Quiet Hours\n\nVerify that the notification system respects temporal constraints including batching windows, quiet hours, and timezone-aware scheduling.\n\n```typescript\nimport { test, expect } from '..\u002Ffixtures\u002Fnotification.fixture';\n\ntest.describe('Timing and Batching Behavior', () => {\n  test('notifications are batched within configured window', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-batch';\n\n    \u002F\u002F Trigger multiple events in quick succession\n    for (let i = 0; i \u003C 5; i++) {\n      await triggerEvent('file.shared', {\n        userId,\n        fileId: `file-${i}`,\n        sharedBy: `user-sharer-${i}`,\n      });\n      await new Promise((r) => setTimeout(r, 200));\n    }\n\n    await new Promise((r) => setTimeout(r, 5000));\n\n    const userNotifications = notificationInterceptor.getByUser(userId);\n    const emailNotifications = userNotifications.filter((n) => n.channel === 'email');\n\n    \u002F\u002F Should batch into a single digest email rather than 5 separate ones\n    expect(emailNotifications.length).toBeLessThanOrEqual(2);\n  });\n\n  test('quiet hours are respected based on user timezone', async ({\n    page,\n    notificationInterceptor,\n    setUserPreferences,\n    triggerEvent,\n  }) => {\n    const userId = 'user-quiet-hours';\n\n    await setUserPreferences(userId, {\n      quietHoursEnabled: true,\n      quietHoursStart: '22:00',\n      quietHoursEnd: '08:00',\n      timezone: 'America\u002FNew_York',\n    });\n\n    \u002F\u002F Mock the server time to be within quiet hours for the user\n    await page.evaluate(() => {\n      \u002F\u002F Override Date to simulate 2:00 AM Eastern Time\n      const mockDate = new Date('2025-01-15T07:00:00.000Z'); \u002F\u002F 2 AM ET\n      const originalDate = Date;\n      globalThis.Date = class extends originalDate {\n        constructor(...args: any[]) {\n          if (args.length === 0) return new originalDate(mockDate);\n          return new (originalDate as any)(...args);\n        }\n        static now() {\n          return mockDate.getTime();\n        }\n      } as any;\n    });\n\n    await triggerEvent('comment.mention', { userId, commentId: 'c-quiet' });\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const pushNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'push');\n\n    \u002F\u002F Push notifications should be suppressed during quiet hours\n    expect(pushNotifications).toHaveLength(0);\n  });\n\n  test('deferred notifications are delivered after quiet hours end', async ({\n    page,\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-deferred';\n\n    \u002F\u002F Trigger during quiet hours\n    await triggerEvent('team.invite', { userId, teamId: 'team-001' });\n    await new Promise((r) => setTimeout(r, 1000));\n\n    const duringQuietHours = notificationInterceptor.getByUser(userId);\n    const pushDuringQuiet = duringQuietHours.filter((n) => n.channel === 'push');\n    expect(pushDuringQuiet).toHaveLength(0);\n\n    \u002F\u002F Simulate time advancing past quiet hours\n    await page.evaluate(async () => {\n      await fetch('\u002Fapi\u002Fadmin\u002Fnotifications\u002Fprocess-deferred', { method: 'POST' });\n    });\n\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const afterQuietHours = notificationInterceptor.getByUser(userId);\n    expect(afterQuietHours.length).toBeGreaterThan(0);\n  });\n});\n```\n\n## Unsubscribe Flow Testing\n\nThe unsubscribe flow is legally required in many jurisdictions (CAN-SPAM, GDPR). Test that it works flawlessly.\n\n```typescript\nimport { test, expect } from '..\u002Ffixtures\u002Fnotification.fixture';\n\ntest.describe('Unsubscribe Flow', () => {\n  test('one-click unsubscribe link works from email', async ({ page }) => {\n    \u002F\u002F Navigate to unsubscribe URL with token\n    const unsubscribeUrl = '\u002Funsubscribe?token=valid-test-token&category=marketing';\n\n    await page.goto(unsubscribeUrl);\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Should show confirmation page\n    await expect(page.getByText(\u002Funsubscribed\u002Fi)).toBeVisible();\n    await expect(page.getByText(\u002Fmarketing\u002Fi)).toBeVisible();\n  });\n\n  test('unsubscribe actually prevents future notifications', async ({\n    page,\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-unsub-test';\n\n    \u002F\u002F Perform unsubscribe\n    await page.goto(`\u002Funsubscribe?token=valid-token-${userId}&category=marketing`);\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Try to trigger a marketing notification\n    notificationInterceptor.clear();\n    await triggerEvent('marketing.weekly-digest', { userId });\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const marketingNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.category === 'marketing');\n\n    expect(marketingNotifications).toHaveLength(0);\n  });\n\n  test('unsubscribe from one category does not affect others', async ({\n    page,\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-partial-unsub';\n\n    \u002F\u002F Unsubscribe from marketing only\n    await page.goto(`\u002Funsubscribe?token=valid-token-${userId}&category=marketing`);\n    await page.waitForLoadState('networkidle');\n\n    notificationInterceptor.clear();\n    await triggerEvent('marketing.promo', { userId });\n    await triggerEvent('order.shipped', { userId, orderId: 'order-partial' });\n\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const marketing = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.category === 'marketing');\n    const transactional = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.category !== 'marketing');\n\n    expect(marketing).toHaveLength(0);\n    expect(transactional.length).toBeGreaterThan(0);\n  });\n\n  test('invalid unsubscribe token shows error', async ({ page }) => {\n    await page.goto('\u002Funsubscribe?token=invalid-garbage-token&category=marketing');\n    await page.waitForLoadState('networkidle');\n\n    await expect(page.getByText(\u002Finvalid|expired\u002Fi)).toBeVisible();\n  });\n});\n```\n\n## Notification Content Validation\n\nEnsure notification content is correctly rendered, personalized, and free of template artifacts.\n\n```typescript\nimport { test, expect } from '..\u002Ffixtures\u002Fnotification.fixture';\n\ntest.describe('Notification Content Validation', () => {\n  test('personalization tokens are resolved', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-personalized';\n\n    await triggerEvent('welcome.new-user', {\n      userId,\n      userName: 'Alice Johnson',\n    });\n\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const notifications = notificationInterceptor.getByUser(userId);\n    for (const notification of notifications) {\n      \u002F\u002F Should not contain unresolved template tokens\n      expect(notification.body).not.toContain('{{');\n      expect(notification.body).not.toContain('}}');\n      expect(notification.subject).not.toContain('{{');\n\n      \u002F\u002F Should contain the actual personalized value\n      expect(notification.body).toContain('Alice');\n    }\n  });\n\n  test('notification body does not contain HTML in plain text channels', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-content-check';\n\n    await triggerEvent('report.ready', { userId, reportId: 'rpt-001' });\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const pushNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'push');\n\n    for (const notification of pushNotifications) {\n      expect(notification.body).not.toMatch(\u002F\u003C[^>]+>\u002F);\n    }\n  });\n\n  test('notification links are absolute URLs', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-links';\n\n    await triggerEvent('task.assigned', { userId, taskId: 'task-link-test' });\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const emailNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'email');\n\n    for (const notification of emailNotifications) {\n      const urlPattern = \u002Fhttps?:\\\u002F\\\u002F[^\\s\"\u003C]+\u002Fg;\n      const urls = notification.body.match(urlPattern) || [];\n      for (const url of urls) {\n        expect(url).toMatch(\u002F^https?:\\\u002F\\\u002F\u002F);\n        expect(url).not.toContain('localhost');\n      }\n    }\n  });\n});\n```\n\n## Configuration\n\n### Playwright Configuration for Notification Testing\n\n```typescript\nimport { defineConfig } from '@playwright\u002Ftest';\n\nexport default defineConfig({\n  testDir: '.\u002Ftests\u002Fnotifications',\n  timeout: 30000,\n  retries: 1,\n  workers: 1, \u002F\u002F Sequential to avoid notification interference between tests\n  use: {\n    baseURL: process.env.BASE_URL || 'http:\u002F\u002Flocalhost:3000',\n    trace: 'on-first-retry',\n    screenshot: 'only-on-failure',\n  },\n  projects: [\n    {\n      name: 'notification-spam',\n      testMatch: '**\u002Fspam-detection\u002F**',\n    },\n    {\n      name: 'notification-preferences',\n      testMatch: '**\u002Fpreferences\u002F**',\n    },\n    {\n      name: 'cross-channel',\n      testMatch: '**\u002Fcross-channel\u002F**',\n    },\n    {\n      name: 'timing',\n      testMatch: '**\u002Ftiming\u002F**',\n    },\n  ],\n});\n```\n\n### Environment Variables\n\n```bash\n# .env.test\nBASE_URL=http:\u002F\u002Flocalhost:3000\nNOTIFICATION_THROTTLE_WINDOW_MS=3600000\nNOTIFICATION_MAX_PER_WINDOW=10\nNOTIFICATION_BATCH_DELAY_MS=5000\nNOTIFICATION_QUIET_HOURS_ENABLED=true\nNOTIFICATION_COOLDOWN_MS=300000\n```\n\n## Best Practices\n\n1. **Run notification tests sequentially** -- Parallel execution can cause cross-test contamination when notifications from one test leak into another test's assertions. Use `workers: 1` in the Playwright configuration for notification test suites.\n\n2. **Clear notification state between tests** -- Always reset the notification interceptor, user preferences, and any queued notifications between test runs. Use the fixture teardown to ensure clean state.\n\n3. **Test at the API level first** -- Before writing full E2E notification tests, build integration tests that exercise the notification service directly. This catches logic bugs faster than browser-based tests.\n\n4. **Use deterministic time** -- Mock the system clock when testing time-dependent behavior like quiet hours, batching windows, and cooldown periods. Do not rely on real-time waits for time-sensitive logic.\n\n5. **Verify both positive and negative cases** -- For every \"notification should be delivered\" test, write a corresponding \"notification should NOT be delivered\" test. Spam detection is as much about absence as presence.\n\n6. **Test preference migration** -- When adding new notification categories or channels, verify that existing users receive sensible defaults and that their existing preferences are not overwritten.\n\n7. **Monitor notification counts in CI** -- Add assertions that verify the total number of notifications sent during a test suite run. A sudden increase often indicates a deduplication regression.\n\n8. **Test with multiple users simultaneously** -- Verify that throttling and deduplication work correctly when multiple users trigger the same event. Per-user isolation must not leak across user boundaries.\n\n9. **Validate notification metadata** -- Beyond subject and body, verify that notifications carry correct metadata such as category, priority, action URLs, and tracking identifiers.\n\n10. **Test notification delivery order** -- When multiple notifications are queued, verify they are delivered in the expected order (typically chronological or priority-based).\n\n11. **Include load testing for notification pipelines** -- The spam detection logic itself can become a bottleneck. Verify that deduplication, throttling, and preference lookups perform within latency budgets under load.\n\n12. **Test across notification service restarts** -- Ensure that in-flight notifications, queued deliveries, and throttle counters survive service restarts without causing duplicates or drops.\n\n## Anti-Patterns to Avoid\n\n1. **Relying on sleep-based timing** -- Do not use `await new Promise(r => setTimeout(r, 10000))` to wait for notifications. Build proper polling or event-based waiting mechanisms that check for the expected notification count.\n\n2. **Testing only the happy path** -- If you only test \"notification arrives,\" you miss the entire purpose of spam detection testing. The majority of your tests should verify that unwanted notifications are suppressed.\n\n3. **Hardcoding rate limits in tests** -- Do not hardcode throttle values like `expect(notifications).toHaveLength(10)`. Read the configuration from the same source as the application to keep tests in sync with production settings.\n\n4. **Ignoring cross-channel interactions** -- Testing email deduplication in isolation while ignoring that push and in-app notifications may also be sent is a common oversight. Always verify the complete notification footprint across all channels.\n\n5. **Sharing user state across tests** -- Using the same user ID across multiple test files without cleanup creates flaky tests because throttle counters, preference caches, and notification history persist. Generate unique user IDs or clean up thoroughly.\n\n6. **Skipping unsubscribe verification** -- Unsubscribe is a legal requirement in many jurisdictions. Treating it as a low-priority test is a compliance risk. Always include unsubscribe flow tests in your notification test suite.\n\n7. **Not testing notification content** -- Verifying that a notification was delivered is only half the job. If the notification body contains unresolved template variables like `{{user.name}}` or raw HTML, it is still a bug.\n\n## Debugging Tips\n\n1. **Enable notification service logging** -- Set the notification service log level to DEBUG in test environments. Every decision point (deduplicated, throttled, queued, delivered, suppressed) should produce a log entry with the notification ID and reason.\n\n2. **Add trace IDs to notifications** -- Include a unique trace ID in every notification that links back to the triggering event. When debugging duplicate deliveries, the trace ID reveals whether two notifications came from the same event or different events.\n\n3. **Inspect the deduplication cache** -- Most deduplication systems use a cache (Redis, in-memory) to track recently sent notifications. When duplicates slip through, check whether the cache key format is correct and whether the TTL is appropriate.\n\n4. **Check throttle counter state** -- When throttling appears to malfunction, inspect the raw counter values in the backing store. Common issues include counters not resetting at window boundaries, race conditions in counter increments, and timezone mismatches in window calculations.\n\n5. **Verify event ordering** -- When batching produces unexpected results, log the timestamps of all events in the batch window. Out-of-order event delivery can cause the batching algorithm to create incorrect groups.\n\n6. **Use Playwright's trace viewer** -- Enable `trace: 'on'` to capture a full timeline of network requests, including notification API calls. The trace viewer shows request\u002Fresponse payloads and timing, making it easy to spot duplicate sends.\n\n7. **Monitor the dead letter queue** -- Failed notifications typically end up in a dead letter queue. If notifications appear to be missing, check whether they failed delivery and were moved to the DLQ instead of being dropped silently.\n\n8. **Test preference cache invalidation** -- When preference changes do not take effect immediately, the issue is almost always cache invalidation. Verify that the preference cache is cleared or updated when the user modifies their settings.\n\n9. **Compare event counts vs notification counts** -- Maintain counters for events received and notifications sent. The ratio between these numbers should be predictable based on your deduplication and throttling configuration. A deviation indicates a logic bug.\n\n10. **Isolate channel-specific failures** -- When debugging cross-channel issues, temporarily disable all channels except one. This isolates whether the problem is in the routing logic, the channel adapter, or the deduplication layer.\n","# Notification Spam Detector Skill\n\nYou are an expert QA automation engineer specializing in testing notification systems for spam behavior, duplicate delivery, throttling compliance, and preference enforcement. When the user asks you to write, review, or debug notification spam detection tests, follow these detailed instructions.\n\n## Core Principles\n\n1. **Deduplication is non-negotiable** -- The same notification must never be delivered twice to the same user within a single event trigger. Every notification system must have deduplication logic, and every test suite must verify it.\n2. **Throttling protects users** -- Rate limiting and throttling exist to prevent notification fatigue. Tests must verify that throttling is applied consistently across all channels and that burst scenarios do not overwhelm users.\n3. **User preferences are law** -- If a user has opted out of a notification channel or category, the system must never violate that preference. Test every combination of preference settings against every notification type.\n4. **Cross-channel awareness** -- A notification delivered via push should not also be delivered via email and in-app simultaneously unless the user has explicitly configured that behavior. Test cross-channel deduplication rigorously.\n5. **Timing matters** -- Notifications should respect quiet hours, batching windows, and timezone-aware delivery schedules. Tests must verify temporal behavior under various clock configurations.\n6. **Content integrity** -- Every notification must contain accurate, properly formatted content with correct personalization tokens resolved. Template rendering failures should never reach users.\n7. **Graceful degradation** -- When a notification channel is unavailable (push service down, email provider rate-limited), the system should fall back gracefully without creating duplicates or losing notifications entirely.\n\n## Project Structure\n\nOrganize notification spam detection tests with this structure:\n\n```\ntests\u002F\n  notifications\u002F\n    spam-detection\u002F\n      duplicate-detection.spec.ts\n      throttling-verification.spec.ts\n      rate-limit-compliance.spec.ts\n    preferences\u002F\n      opt-out-enforcement.spec.ts\n      channel-preferences.spec.ts\n      category-preferences.spec.ts\n    cross-channel\u002F\n      deduplication.spec.ts\n      fallback-behavior.spec.ts\n      channel-routing.spec.ts\n    timing\u002F\n      quiet-hours.spec.ts\n      batching-behavior.spec.ts\n      timezone-handling.spec.ts\n    content\u002F\n      template-rendering.spec.ts\n      personalization.spec.ts\n      content-validation.spec.ts\n  fixtures\u002F\n    notification.fixture.ts\n    user-preferences.fixture.ts\n    mock-channels.fixture.ts\n  helpers\u002F\n    notification-interceptor.ts\n    channel-monitor.ts\n    timing-utils.ts\n  pages\u002F\n    notification-center.page.ts\n    preferences.page.ts\n    notification-settings.page.ts\nplaywright.config.ts\n```\n\n## Setting Up the Notification Test Infrastructure\n\nBefore writing individual tests, establish a robust infrastructure for intercepting and analyzing notifications across all channels.\n\n### Notification Interceptor\n\nBuild a central interceptor that captures all outbound notifications regardless of channel:\n\n```typescript\nimport { Page, Route } from '@playwright\u002Ftest';\n\ninterface CapturedNotification {\n  id: string;\n  userId: string;\n  channel: 'email' | 'push' | 'in-app' | 'sms';\n  category: string;\n  subject: string;\n  body: string;\n  timestamp: number;\n  metadata: Record\u003Cstring, unknown>;\n}\n\nexport class NotificationInterceptor {\n  private captured: CapturedNotification[] = [];\n  private readonly page: Page;\n\n  constructor(page: Page) {\n    this.page = page;\n  }\n\n  async startCapturing(): Promise\u003Cvoid> {\n    await this.page.route('**\u002Fapi\u002Fnotifications\u002Fsend', async (route: Route) => {\n      const request = route.request();\n      const postData = request.postDataJSON();\n\n      this.captured.push({\n        id: postData.notificationId,\n        userId: postData.userId,\n        channel: postData.channel,\n        category: postData.category,\n        subject: postData.subject,\n        body: postData.body,\n        timestamp: Date.now(),\n        metadata: postData.metadata || {},\n      });\n\n      await route.fulfill({\n        status: 200,\n        contentType: 'application\u002Fjson',\n        body: JSON.stringify({ success: true, id: postData.notificationId }),\n      });\n    });\n\n    await this.page.route('**\u002Fapi\u002Fnotifications\u002Fbatch', async (route: Route) => {\n      const request = route.request();\n      const postData = request.postDataJSON();\n\n      for (const notification of postData.notifications) {\n        this.captured.push({\n          id: notification.notificationId,\n          userId: notification.userId,\n          channel: notification.channel,\n          category: notification.category,\n          subject: notification.subject,\n          body: notification.body,\n          timestamp: Date.now(),\n          metadata: notification.metadata || {},\n        });\n      }\n\n      await route.fulfill({\n        status: 200,\n        contentType: 'application\u002Fjson',\n        body: JSON.stringify({ success: true, count: postData.notifications.length }),\n      });\n    });\n  }\n\n  getAll(): CapturedNotification[] {\n    return [...this.captured];\n  }\n\n  getByChannel(channel: CapturedNotification['channel']): CapturedNotification[] {\n    return this.captured.filter((n) => n.channel === channel);\n  }\n\n  getByUser(userId: string): CapturedNotification[] {\n    return this.captured.filter((n) => n.userId === userId);\n  }\n\n  getByCategory(category: string): CapturedNotification[] {\n    return this.captured.filter((n) => n.category === category);\n  }\n\n  getDuplicates(): CapturedNotification[][] {\n    const groups = new Map\u003Cstring, CapturedNotification[]>();\n\n    for (const notification of this.captured) {\n      const key = `${notification.userId}:${notification.channel}:${notification.category}:${notification.subject}`;\n      const existing = groups.get(key) || [];\n      existing.push(notification);\n      groups.set(key, existing);\n    }\n\n    return Array.from(groups.values()).filter((group) => group.length > 1);\n  }\n\n  getNotificationsInWindow(startMs: number, endMs: number): CapturedNotification[] {\n    return this.captured.filter((n) => n.timestamp >= startMs && n.timestamp \u003C= endMs);\n  }\n\n  clear(): void {\n    this.captured = [];\n  }\n}\n```\n\n### Custom Test Fixture\n\nCreate a Playwright fixture that provides the interceptor and common notification test utilities:\n\n```typescript\nimport { test as base, expect } from '@playwright\u002Ftest';\nimport { NotificationInterceptor } from '..\u002Fhelpers\u002Fnotification-interceptor';\n\ninterface NotificationFixtures {\n  notificationInterceptor: NotificationInterceptor;\n  triggerEvent: (eventType: string, payload: Record\u003Cstring, unknown>) => Promise\u003Cvoid>;\n  setUserPreferences: (\n    userId: string,\n    preferences: Record\u003Cstring, boolean>\n  ) => Promise\u003Cvoid>;\n  waitForNotifications: (count: number, timeoutMs?: number) => Promise\u003Cvoid>;\n}\n\nexport const test = base.extend\u003CNotificationFixtures>({\n  notificationInterceptor: async ({ page }, use) => {\n    const interceptor = new NotificationInterceptor(page);\n    await interceptor.startCapturing();\n    await use(interceptor);\n    interceptor.clear();\n  },\n\n  triggerEvent: async ({ page }, use) => {\n    const trigger = async (eventType: string, payload: Record\u003Cstring, unknown>) => {\n      await page.evaluate(\n        async ({ eventType, payload }) => {\n          const response = await fetch('\u002Fapi\u002Fevents\u002Ftrigger', {\n            method: 'POST',\n            headers: { 'Content-Type': 'application\u002Fjson' },\n            body: JSON.stringify({ type: eventType, ...payload }),\n          });\n          if (!response.ok) {\n            throw new Error(`Failed to trigger event: ${response.statusText}`);\n          }\n        },\n        { eventType, payload }\n      );\n    };\n    await use(trigger);\n  },\n\n  setUserPreferences: async ({ page }, use) => {\n    const setPrefs = async (userId: string, preferences: Record\u003Cstring, boolean>) => {\n      await page.evaluate(\n        async ({ userId, preferences }) => {\n          await fetch(`\u002Fapi\u002Fusers\u002F${userId}\u002Fnotification-preferences`, {\n            method: 'PUT',\n            headers: { 'Content-Type': 'application\u002Fjson' },\n            body: JSON.stringify(preferences),\n          });\n        },\n        { userId, preferences }\n      );\n    };\n    await use(setPrefs);\n  },\n\n  waitForNotifications: async ({ notificationInterceptor }, use) => {\n    const waiter = async (count: number, timeoutMs = 5000) => {\n      const startTime = Date.now();\n      while (notificationInterceptor.getAll().length \u003C count) {\n        if (Date.now() - startTime > timeoutMs) {\n          throw new Error(\n            `Timed out waiting for ${count} notifications. ` +\n              `Received ${notificationInterceptor.getAll().length}.`\n          );\n        }\n        await new Promise((r) => setTimeout(r, 100));\n      }\n    };\n    await use(waiter);\n  },\n});\n\nexport { expect };\n```\n\n## Duplicate Notification Detection\n\nThe most critical class of notification spam is duplicate delivery. Build tests that verify deduplication under various conditions.\n\n### Basic Duplicate Detection Tests\n\n```typescript\nimport { test, expect } from '..\u002Ffixtures\u002Fnotification.fixture';\n\ntest.describe('Duplicate Notification Detection', () => {\n  test('same event does not trigger duplicate notifications', async ({\n    notificationInterceptor,\n    triggerEvent,\n    waitForNotifications,\n  }) => {\n    const userId = 'user-123';\n\n    await triggerEvent('order.shipped', { userId, orderId: 'order-456' });\n    await waitForNotifications(1);\n\n    \u002F\u002F Trigger the exact same event again\n    await triggerEvent('order.shipped', { userId, orderId: 'order-456' });\n\n    \u002F\u002F Wait a reasonable time for any duplicate to arrive\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const userNotifications = notificationInterceptor.getByUser(userId);\n    expect(userNotifications).toHaveLength(1);\n\n    const duplicates = notificationInterceptor.getDuplicates();\n    expect(duplicates).toHaveLength(0);\n  });\n\n  test('rapid identical events produce only one notification', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-rapid';\n\n    \u002F\u002F Fire the same event 10 times in rapid succession\n    const promises = Array.from({ length: 10 }, () =>\n      triggerEvent('comment.added', { userId, commentId: 'comment-789' })\n    );\n    await Promise.all(promises);\n\n    \u002F\u002F Allow processing time\n    await new Promise((r) => setTimeout(r, 3000));\n\n    const userNotifications = notificationInterceptor.getByUser(userId);\n    expect(userNotifications).toHaveLength(1);\n  });\n\n  test('similar but distinct events each produce one notification', async ({\n    notificationInterceptor,\n    triggerEvent,\n    waitForNotifications,\n  }) => {\n    const userId = 'user-distinct';\n\n    await triggerEvent('comment.added', { userId, commentId: 'comment-001' });\n    await triggerEvent('comment.added', { userId, commentId: 'comment-002' });\n    await triggerEvent('comment.added', { userId, commentId: 'comment-003' });\n\n    await waitForNotifications(3);\n\n    const userNotifications = notificationInterceptor.getByUser(userId);\n    \u002F\u002F Could be 3 individual notifications or 1 batched notification depending on config\n    expect(userNotifications.length).toBeGreaterThanOrEqual(1);\n    expect(userNotifications.length).toBeLessThanOrEqual(3);\n  });\n\n  test('idempotency keys prevent duplicate delivery after retry', async ({\n    page,\n    notificationInterceptor,\n  }) => {\n    const idempotencyKey = 'idem-key-unique-001';\n\n    \u002F\u002F Send with idempotency key\n    await page.evaluate(\n      async ({ key }) => {\n        await fetch('\u002Fapi\u002Fnotifications\u002Fsend', {\n          method: 'POST',\n          headers: {\n            'Content-Type': 'application\u002Fjson',\n            'Idempotency-Key': key,\n          },\n          body: JSON.stringify({\n            userId: 'user-idem',\n            channel: 'email',\n            category: 'order-update',\n            subject: 'Your order shipped',\n            body: 'Order 123 is on the way.',\n          }),\n        });\n\n        \u002F\u002F Retry with the same idempotency key\n        await fetch('\u002Fapi\u002Fnotifications\u002Fsend', {\n          method: 'POST',\n          headers: {\n            'Content-Type': 'application\u002Fjson',\n            'Idempotency-Key': key,\n          },\n          body: JSON.stringify({\n            userId: 'user-idem',\n            channel: 'email',\n            category: 'order-update',\n            subject: 'Your order shipped',\n            body: 'Order 123 is on the way.',\n          }),\n        });\n      },\n      { key: idempotencyKey }\n    );\n\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const userNotifications = notificationInterceptor.getByUser('user-idem');\n    expect(userNotifications).toHaveLength(1);\n  });\n});\n```\n\n## Throttling and Rate Limiting Verification\n\nThrottling prevents notification overload. Tests must verify that rate limits are applied per user, per channel, and per category.\n\n```typescript\nimport { test, expect } from '..\u002Ffixtures\u002Fnotification.fixture';\n\ntest.describe('Throttling and Rate Limiting', () => {\n  test('per-user rate limit caps notifications within time window', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-throttle';\n    const maxNotificationsPerHour = 10;\n\n    \u002F\u002F Trigger more events than the rate limit allows\n    for (let i = 0; i \u003C 20; i++) {\n      await triggerEvent('activity.update', {\n        userId,\n        activityId: `activity-${i}`,\n      });\n    }\n\n    await new Promise((r) => setTimeout(r, 5000));\n\n    const userNotifications = notificationInterceptor.getByUser(userId);\n    expect(userNotifications.length).toBeLessThanOrEqual(maxNotificationsPerHour);\n  });\n\n  test('per-channel rate limit is enforced independently', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-channel-throttle';\n\n    \u002F\u002F Trigger events that should go to both email and push\n    for (let i = 0; i \u003C 15; i++) {\n      await triggerEvent('system.alert', {\n        userId,\n        alertId: `alert-${i}`,\n        channels: ['email', 'push'],\n      });\n    }\n\n    await new Promise((r) => setTimeout(r, 5000));\n\n    const emailNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'email');\n    const pushNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'push');\n\n    \u002F\u002F Each channel should independently enforce its rate limit\n    expect(emailNotifications.length).toBeLessThanOrEqual(10);\n    expect(pushNotifications.length).toBeLessThanOrEqual(10);\n  });\n\n  test('throttled notifications are queued not dropped', async ({\n    page,\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-queue-test';\n\n    \u002F\u002F Trigger a burst that exceeds the rate limit\n    for (let i = 0; i \u003C 25; i++) {\n      await triggerEvent('task.assigned', {\n        userId,\n        taskId: `task-${i}`,\n      });\n    }\n\n    \u002F\u002F Wait for the initial window\n    await new Promise((r) => setTimeout(r, 3000));\n\n    const initialCount = notificationInterceptor.getByUser(userId).length;\n    expect(initialCount).toBeGreaterThan(0);\n    expect(initialCount).toBeLessThan(25);\n\n    \u002F\u002F Verify queued notifications are delivered in next window\n    \u002F\u002F Simulate time advancement or wait for the next delivery window\n    await page.evaluate(async () => {\n      await fetch('\u002Fapi\u002Fadmin\u002Fnotifications\u002Fflush-queue', { method: 'POST' });\n    });\n\n    await new Promise((r) => setTimeout(r, 3000));\n\n    const finalCount = notificationInterceptor.getByUser(userId).length;\n    expect(finalCount).toBeGreaterThan(initialCount);\n  });\n\n  test('cooldown period between same-type notifications is respected', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-cooldown';\n\n    await triggerEvent('price.drop', { userId, productId: 'prod-100', newPrice: 49.99 });\n\n    await new Promise((r) => setTimeout(r, 500));\n\n    \u002F\u002F Second price drop for the same product within cooldown window\n    await triggerEvent('price.drop', { userId, productId: 'prod-100', newPrice: 44.99 });\n\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const notifications = notificationInterceptor.getByUser(userId);\n    const priceDropNotifications = notifications.filter((n) => n.category === 'price-drop');\n\n    \u002F\u002F Should only have 1 notification due to cooldown\n    expect(priceDropNotifications).toHaveLength(1);\n  });\n});\n```\n\n## Notification Preference Honoring\n\nUser preferences must be treated as inviolable constraints. Test every preference combination to ensure the system never sends unwanted notifications.\n\n```typescript\nimport { test, expect } from '..\u002Ffixtures\u002Fnotification.fixture';\n\ntest.describe('Notification Preference Enforcement', () => {\n  test('user who opted out of email receives no emails', async ({\n    notificationInterceptor,\n    setUserPreferences,\n    triggerEvent,\n  }) => {\n    const userId = 'user-no-email';\n\n    await setUserPreferences(userId, {\n      emailEnabled: false,\n      pushEnabled: true,\n      inAppEnabled: true,\n    });\n\n    await triggerEvent('order.confirmed', { userId, orderId: 'order-999' });\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const emailNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'email');\n    const pushNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'push');\n\n    expect(emailNotifications).toHaveLength(0);\n    expect(pushNotifications.length).toBeGreaterThan(0);\n  });\n\n  test('category-level opt-out is respected', async ({\n    notificationInterceptor,\n    setUserPreferences,\n    triggerEvent,\n  }) => {\n    const userId = 'user-no-marketing';\n\n    await setUserPreferences(userId, {\n      emailEnabled: true,\n      pushEnabled: true,\n      categories: {\n        marketing: false,\n        transactional: true,\n        security: true,\n      },\n    });\n\n    await triggerEvent('marketing.campaign', { userId, campaignId: 'camp-001' });\n    await triggerEvent('order.confirmed', { userId, orderId: 'order-001' });\n\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const marketingNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.category === 'marketing');\n    const transactionalNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.category === 'order-update' || n.category === 'transactional');\n\n    expect(marketingNotifications).toHaveLength(0);\n    expect(transactionalNotifications.length).toBeGreaterThan(0);\n  });\n\n  test('global unsubscribe blocks all non-security notifications', async ({\n    notificationInterceptor,\n    setUserPreferences,\n    triggerEvent,\n  }) => {\n    const userId = 'user-unsubscribed';\n\n    await setUserPreferences(userId, {\n      globalUnsubscribe: true,\n    });\n\n    await triggerEvent('marketing.campaign', { userId, campaignId: 'camp-002' });\n    await triggerEvent('order.confirmed', { userId, orderId: 'order-002' });\n    await triggerEvent('security.password-changed', { userId });\n\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const allNotifications = notificationInterceptor.getByUser(userId);\n    const securityNotifications = allNotifications.filter(\n      (n) => n.category === 'security'\n    );\n    const nonSecurityNotifications = allNotifications.filter(\n      (n) => n.category !== 'security'\n    );\n\n    \u002F\u002F Security notifications must always be delivered\n    expect(securityNotifications.length).toBeGreaterThan(0);\n    \u002F\u002F All other notifications must be blocked\n    expect(nonSecurityNotifications).toHaveLength(0);\n  });\n\n  test('preference changes take effect immediately', async ({\n    notificationInterceptor,\n    setUserPreferences,\n    triggerEvent,\n  }) => {\n    const userId = 'user-pref-change';\n\n    \u002F\u002F Initially subscribed to email\n    await setUserPreferences(userId, { emailEnabled: true });\n\n    await triggerEvent('comment.reply', { userId, commentId: 'c-1' });\n    await new Promise((r) => setTimeout(r, 1000));\n\n    const initialEmails = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'email');\n    expect(initialEmails.length).toBeGreaterThan(0);\n\n    \u002F\u002F Disable email\n    await setUserPreferences(userId, { emailEnabled: false });\n\n    notificationInterceptor.clear();\n\n    await triggerEvent('comment.reply', { userId, commentId: 'c-2' });\n    await new Promise((r) => setTimeout(r, 1000));\n\n    const postChangeEmails = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'email');\n    expect(postChangeEmails).toHaveLength(0);\n  });\n});\n```\n\n## Cross-Channel Deduplication\n\nWhen a notification can be delivered on multiple channels, the system must coordinate to avoid overwhelming the user.\n\n```typescript\nimport { test, expect } from '..\u002Ffixtures\u002Fnotification.fixture';\n\ntest.describe('Cross-Channel Deduplication', () => {\n  test('single event does not produce duplicate across email and push', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-cross-channel';\n\n    await triggerEvent('invoice.ready', { userId, invoiceId: 'inv-001' });\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const userNotifications = notificationInterceptor.getByUser(userId);\n    const channels = new Set(userNotifications.map((n) => n.channel));\n\n    \u002F\u002F Verify the notification was sent to different channels, not duplicated within one\n    for (const channel of channels) {\n      const channelNotifications = userNotifications.filter(\n        (n) => n.channel === channel\n      );\n      const subjects = channelNotifications.map((n) => n.subject);\n      const uniqueSubjects = new Set(subjects);\n      expect(subjects.length).toBe(uniqueSubjects.size);\n    }\n  });\n\n  test('in-app notification suppresses push for active users', async ({\n    page,\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-active-session';\n\n    \u002F\u002F Simulate active user session\n    await page.evaluate(async (uid) => {\n      await fetch('\u002Fapi\u002Fusers\u002Fheartbeat', {\n        method: 'POST',\n        headers: { 'Content-Type': 'application\u002Fjson' },\n        body: JSON.stringify({ userId: uid, status: 'active' }),\n      });\n    }, userId);\n\n    await triggerEvent('message.received', { userId, messageId: 'msg-001' });\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const pushNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'push');\n    const inAppNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'in-app');\n\n    \u002F\u002F Active users should receive in-app only, not push\n    expect(inAppNotifications.length).toBeGreaterThan(0);\n    expect(pushNotifications).toHaveLength(0);\n  });\n\n  test('fallback to email when push delivery fails', async ({\n    page,\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-push-fail';\n\n    \u002F\u002F Mock push service failure\n    await page.route('**\u002Fapi\u002Fpush\u002Fsend', (route) =>\n      route.fulfill({ status: 503, body: 'Service Unavailable' })\n    );\n\n    await triggerEvent('reminder.due', { userId, reminderId: 'rem-001' });\n    await new Promise((r) => setTimeout(r, 3000));\n\n    const emailNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'email');\n\n    \u002F\u002F Should fall back to email\n    expect(emailNotifications.length).toBeGreaterThan(0);\n\n    \u002F\u002F Should not duplicate on push retry\n    const pushNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'push');\n    expect(pushNotifications).toHaveLength(0);\n  });\n});\n```\n\n## Timing, Batching, and Quiet Hours\n\nVerify that the notification system respects temporal constraints including batching windows, quiet hours, and timezone-aware scheduling.\n\n```typescript\nimport { test, expect } from '..\u002Ffixtures\u002Fnotification.fixture';\n\ntest.describe('Timing and Batching Behavior', () => {\n  test('notifications are batched within configured window', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-batch';\n\n    \u002F\u002F Trigger multiple events in quick succession\n    for (let i = 0; i \u003C 5; i++) {\n      await triggerEvent('file.shared', {\n        userId,\n        fileId: `file-${i}`,\n        sharedBy: `user-sharer-${i}`,\n      });\n      await new Promise((r) => setTimeout(r, 200));\n    }\n\n    await new Promise((r) => setTimeout(r, 5000));\n\n    const userNotifications = notificationInterceptor.getByUser(userId);\n    const emailNotifications = userNotifications.filter((n) => n.channel === 'email');\n\n    \u002F\u002F Should batch into a single digest email rather than 5 separate ones\n    expect(emailNotifications.length).toBeLessThanOrEqual(2);\n  });\n\n  test('quiet hours are respected based on user timezone', async ({\n    page,\n    notificationInterceptor,\n    setUserPreferences,\n    triggerEvent,\n  }) => {\n    const userId = 'user-quiet-hours';\n\n    await setUserPreferences(userId, {\n      quietHoursEnabled: true,\n      quietHoursStart: '22:00',\n      quietHoursEnd: '08:00',\n      timezone: 'America\u002FNew_York',\n    });\n\n    \u002F\u002F Mock the server time to be within quiet hours for the user\n    await page.evaluate(() => {\n      \u002F\u002F Override Date to simulate 2:00 AM Eastern Time\n      const mockDate = new Date('2025-01-15T07:00:00.000Z'); \u002F\u002F 2 AM ET\n      const originalDate = Date;\n      globalThis.Date = class extends originalDate {\n        constructor(...args: any[]) {\n          if (args.length === 0) return new originalDate(mockDate);\n          return new (originalDate as any)(...args);\n        }\n        static now() {\n          return mockDate.getTime();\n        }\n      } as any;\n    });\n\n    await triggerEvent('comment.mention', { userId, commentId: 'c-quiet' });\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const pushNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'push');\n\n    \u002F\u002F Push notifications should be suppressed during quiet hours\n    expect(pushNotifications).toHaveLength(0);\n  });\n\n  test('deferred notifications are delivered after quiet hours end', async ({\n    page,\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-deferred';\n\n    \u002F\u002F Trigger during quiet hours\n    await triggerEvent('team.invite', { userId, teamId: 'team-001' });\n    await new Promise((r) => setTimeout(r, 1000));\n\n    const duringQuietHours = notificationInterceptor.getByUser(userId);\n    const pushDuringQuiet = duringQuietHours.filter((n) => n.channel === 'push');\n    expect(pushDuringQuiet).toHaveLength(0);\n\n    \u002F\u002F Simulate time advancing past quiet hours\n    await page.evaluate(async () => {\n      await fetch('\u002Fapi\u002Fadmin\u002Fnotifications\u002Fprocess-deferred', { method: 'POST' });\n    });\n\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const afterQuietHours = notificationInterceptor.getByUser(userId);\n    expect(afterQuietHours.length).toBeGreaterThan(0);\n  });\n});\n```\n\n## Unsubscribe Flow Testing\n\nThe unsubscribe flow is legally required in many jurisdictions (CAN-SPAM, GDPR). Test that it works flawlessly.\n\n```typescript\nimport { test, expect } from '..\u002Ffixtures\u002Fnotification.fixture';\n\ntest.describe('Unsubscribe Flow', () => {\n  test('one-click unsubscribe link works from email', async ({ page }) => {\n    \u002F\u002F Navigate to unsubscribe URL with token\n    const unsubscribeUrl = '\u002Funsubscribe?token=valid-test-token&category=marketing';\n\n    await page.goto(unsubscribeUrl);\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Should show confirmation page\n    await expect(page.getByText(\u002Funsubscribed\u002Fi)).toBeVisible();\n    await expect(page.getByText(\u002Fmarketing\u002Fi)).toBeVisible();\n  });\n\n  test('unsubscribe actually prevents future notifications', async ({\n    page,\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-unsub-test';\n\n    \u002F\u002F Perform unsubscribe\n    await page.goto(`\u002Funsubscribe?token=valid-token-${userId}&category=marketing`);\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Try to trigger a marketing notification\n    notificationInterceptor.clear();\n    await triggerEvent('marketing.weekly-digest', { userId });\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const marketingNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.category === 'marketing');\n\n    expect(marketingNotifications).toHaveLength(0);\n  });\n\n  test('unsubscribe from one category does not affect others', async ({\n    page,\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-partial-unsub';\n\n    \u002F\u002F Unsubscribe from marketing only\n    await page.goto(`\u002Funsubscribe?token=valid-token-${userId}&category=marketing`);\n    await page.waitForLoadState('networkidle');\n\n    notificationInterceptor.clear();\n    await triggerEvent('marketing.promo', { userId });\n    await triggerEvent('order.shipped', { userId, orderId: 'order-partial' });\n\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const marketing = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.category === 'marketing');\n    const transactional = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.category !== 'marketing');\n\n    expect(marketing).toHaveLength(0);\n    expect(transactional.length).toBeGreaterThan(0);\n  });\n\n  test('invalid unsubscribe token shows error', async ({ page }) => {\n    await page.goto('\u002Funsubscribe?token=invalid-garbage-token&category=marketing');\n    await page.waitForLoadState('networkidle');\n\n    await expect(page.getByText(\u002Finvalid|expired\u002Fi)).toBeVisible();\n  });\n});\n```\n\n## Notification Content Validation\n\nEnsure notification content is correctly rendered, personalized, and free of template artifacts.\n\n```typescript\nimport { test, expect } from '..\u002Ffixtures\u002Fnotification.fixture';\n\ntest.describe('Notification Content Validation', () => {\n  test('personalization tokens are resolved', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-personalized';\n\n    await triggerEvent('welcome.new-user', {\n      userId,\n      userName: 'Alice Johnson',\n    });\n\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const notifications = notificationInterceptor.getByUser(userId);\n    for (const notification of notifications) {\n      \u002F\u002F Should not contain unresolved template tokens\n      expect(notification.body).not.toContain('{{');\n      expect(notification.body).not.toContain('}}');\n      expect(notification.subject).not.toContain('{{');\n\n      \u002F\u002F Should contain the actual personalized value\n      expect(notification.body).toContain('Alice');\n    }\n  });\n\n  test('notification body does not contain HTML in plain text channels', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-content-check';\n\n    await triggerEvent('report.ready', { userId, reportId: 'rpt-001' });\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const pushNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'push');\n\n    for (const notification of pushNotifications) {\n      expect(notification.body).not.toMatch(\u002F\u003C[^>]+>\u002F);\n    }\n  });\n\n  test('notification links are absolute URLs', async ({\n    notificationInterceptor,\n    triggerEvent,\n  }) => {\n    const userId = 'user-links';\n\n    await triggerEvent('task.assigned', { userId, taskId: 'task-link-test' });\n    await new Promise((r) => setTimeout(r, 2000));\n\n    const emailNotifications = notificationInterceptor\n      .getByUser(userId)\n      .filter((n) => n.channel === 'email');\n\n    for (const notification of emailNotifications) {\n      const urlPattern = \u002Fhttps?:\\\u002F\\\u002F[^\\s\"\u003C]+\u002Fg;\n      const urls = notification.body.match(urlPattern) || [];\n      for (const url of urls) {\n        expect(url).toMatch(\u002F^https?:\\\u002F\\\u002F\u002F);\n        expect(url).not.toContain('localhost');\n      }\n    }\n  });\n});\n```\n\n## Configuration\n\n### Playwright Configuration for Notification Testing\n\n```typescript\nimport { defineConfig } from '@playwright\u002Ftest';\n\nexport default defineConfig({\n  testDir: '.\u002Ftests\u002Fnotifications',\n  timeout: 30000,\n  retries: 1,\n  workers: 1, \u002F\u002F Sequential to avoid notification interference between tests\n  use: {\n    baseURL: process.env.BASE_URL || 'http:\u002F\u002Flocalhost:3000',\n    trace: 'on-first-retry',\n    screenshot: 'only-on-failure',\n  },\n  projects: [\n    {\n      name: 'notification-spam',\n      testMatch: '**\u002Fspam-detection\u002F**',\n    },\n    {\n      name: 'notification-preferences',\n      testMatch: '**\u002Fpreferences\u002F**',\n    },\n    {\n      name: 'cross-channel',\n      testMatch: '**\u002Fcross-channel\u002F**',\n    },\n    {\n      name: 'timing',\n      testMatch: '**\u002Ftiming\u002F**',\n    },\n  ],\n});\n```\n\n### Environment Variables\n\n```bash\n# .env.test\nBASE_URL=http:\u002F\u002Flocalhost:3000\nNOTIFICATION_THROTTLE_WINDOW_MS=3600000\nNOTIFICATION_MAX_PER_WINDOW=10\nNOTIFICATION_BATCH_DELAY_MS=5000\nNOTIFICATION_QUIET_HOURS_ENABLED=true\nNOTIFICATION_COOLDOWN_MS=300000\n```\n\n## Best Practices\n\n1. **Run notification tests sequentially** -- Parallel execution can cause cross-test contamination when notifications from one test leak into another test's assertions. Use `workers: 1` in the Playwright configuration for notification test suites.\n\n2. **Clear notification state between tests** -- Always reset the notification interceptor, user preferences, and any queued notifications between test runs. Use the fixture teardown to ensure clean state.\n\n3. **Test at the API level first** -- Before writing full E2E notification tests, build integration tests that exercise the notification service directly. This catches logic bugs faster than browser-based tests.\n\n4. **Use deterministic time** -- Mock the system clock when testing time-dependent behavior like quiet hours, batching windows, and cooldown periods. Do not rely on real-time waits for time-sensitive logic.\n\n5. **Verify both positive and negative cases** -- For every \"notification should be delivered\" test, write a corresponding \"notification should NOT be delivered\" test. Spam detection is as much about absence as presence.\n\n6. **Test preference migration** -- When adding new notification categories or channels, verify that existing users receive sensible defaults and that their existing preferences are not overwritten.\n\n7. **Monitor notification counts in CI** -- Add assertions that verify the total number of notifications sent during a test suite run. A sudden increase often indicates a deduplication regression.\n\n8. **Test with multiple users simultaneously** -- Verify that throttling and deduplication work correctly when multiple users trigger the same event. Per-user isolation must not leak across user boundaries.\n\n9. **Validate notification metadata** -- Beyond subject and body, verify that notifications carry correct metadata such as category, priority, action URLs, and tracking identifiers.\n\n10. **Test notification delivery order** -- When multiple notifications are queued, verify they are delivered in the expected order (typically chronological or priority-based).\n\n11. **Include load testing for notification pipelines** -- The spam detection logic itself can become a bottleneck. Verify that deduplication, throttling, and preference lookups perform within latency budgets under load.\n\n12. **Test across notification service restarts** -- Ensure that in-flight notifications, queued deliveries, and throttle counters survive service restarts without causing duplicates or drops.\n\n## Anti-Patterns to Avoid\n\n1. **Relying on sleep-based timing** -- Do not use `await new Promise(r => setTimeout(r, 10000))` to wait for notifications. Build proper polling or event-based waiting mechanisms that check for the expected notification count.\n\n2. **Testing only the happy path** -- If you only test \"notification arrives,\" you miss the entire purpose of spam detection testing. The majority of your tests should verify that unwanted notifications are suppressed.\n\n3. **Hardcoding rate limits in tests** -- Do not hardcode throttle values like `expect(notifications).toHaveLength(10)`. Read the configuration from the same source as the application to keep tests in sync with production settings.\n\n4. **Ignoring cross-channel interactions** -- Testing email deduplication in isolation while ignoring that push and in-app notifications may also be sent is a common oversight. Always verify the complete notification footprint across all channels.\n\n5. **Sharing user state across tests** -- Using the same user ID across multiple test files without cleanup creates flaky tests because throttle counters, preference caches, and notification history persist. Generate unique user IDs or clean up thoroughly.\n\n6. **Skipping unsubscribe verification** -- Unsubscribe is a legal requirement in many jurisdictions. Treating it as a low-priority test is a compliance risk. Always include unsubscribe flow tests in your notification test suite.\n\n7. **Not testing notification content** -- Verifying that a notification was delivered is only half the job. If the notification body contains unresolved template variables like `{{user.name}}` or raw HTML, it is still a bug.\n\n## Debugging Tips\n\n1. **Enable notification service logging** -- Set the notification service log level to DEBUG in test environments. Every decision point (deduplicated, throttled, queued, delivered, suppressed) should produce a log entry with the notification ID and reason.\n\n2. **Add trace IDs to notifications** -- Include a unique trace ID in every notification that links back to the triggering event. When debugging duplicate deliveries, the trace ID reveals whether two notifications came from the same event or different events.\n\n3. **Inspect the deduplication cache** -- Most deduplication systems use a cache (Redis, in-memory) to track recently sent notifications. When duplicates slip through, check whether the cache key format is correct and whether the TTL is appropriate.\n\n4. **Check throttle counter state** -- When throttling appears to malfunction, inspect the raw counter values in the backing store. Common issues include counters not resetting at window boundaries, race conditions in counter increments, and timezone mismatches in window calculations.\n\n5. **Verify event ordering** -- When batching produces unexpected results, log the timestamps of all events in the batch window. Out-of-order event delivery can cause the batching algorithm to create incorrect groups.\n\n6. **Use Playwright's trace viewer** -- Enable `trace: 'on'` to capture a full timeline of network requests, including notification API calls. The trace viewer shows request\u002Fresponse payloads and timing, making it easy to spot duplicate sends.\n\n7. **Monitor the dead letter queue** -- Failed notifications typically end up in a dead letter queue. If notifications appear to be missing, check whether they failed delivery and were moved to the DLQ instead of being dropped silently.\n\n8. **Test preference cache invalidation** -- When preference changes do not take effect immediately, the issue is almost always cache invalidation. Verify that the preference cache is cleared or updated when the user modifies their settings.\n\n9. **Compare event counts vs notification counts** -- Maintain counters for events received and notifications sent. The ratio between these numbers should be predictable based on your deduplication and throttling configuration. A deviation indicates a logic bug.\n\n10. **Isolate channel-specific failures** -- When debugging cross-channel issues, temporarily disable all channels except one. This isolates whether the problem is in the routing logic, the channel adapter, or the deduplication layer.\n",{"name":5,"tags":24,"agents":32,"author":45,"domains":46,"license":15,"version":49,"languages":50,"frameworks":53,"description":7,"testingTypes":55},[25,26,27,28,29,30,31],"notifications","spam-detection","push-notifications","email-notifications","throttling","deduplication","notification-preferences",[33,34,35,36,37,38,39,40,41,42,43,44],"claude-code","cursor","github-copilot","windsurf","codex","aider","continue","cline","zed","bolt","gemini-cli","amp","Pramod",[47,48],"web","api","1.0.0",[51,52],"typescript","javascript",[54],"playwright",[56,57],"integration","e2e","main","eac438ea9216a7cb8a570cab803eb01eeafc6793","skills\u002Fqa\u002Fnotification-spam-detector","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m","https:\u002F\u002Fid-preview--d5bef06d-6c9e-4563-a3d4-a855b9d61610.lovable.app\u002F","Eu sou Antonio B. B. Ndombe \r\nEu sou um Pesquisador e desenvolvedor de sistema autonomia cognitivos, fundador de sistemas ODCs ( organismos digital conscientes)","2026-11-04 06:53:39",{"source":8,"skillName":5,"commands":67,"prompt":77,"zipAvailable":78},[68,71,74],{"tool":69,"command":70},"npx","npx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"Notification Spam Detector\"",{"tool":72,"command":73},"bunx","bunx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"Notification Spam Detector\"",{"tool":75,"command":76},"pnpm","pnpm dlx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"Notification Spam Detector\"","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fnotification-spam-detector\u002FSKILL.md",true,[],[81,89,96,103,110,117],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7DASC6FSCJP49JZBSK0NY1Z","nemoclaw-user-reference","Describes the NemoClaw integration layer and blueprint architecture and how they orchestrate compatible agent sandboxes. Use when looking up architecture, agent integration, plugin structure, or blueprint design. Trigger keywords - nemoclaw architecture, nemoclaw agent architecture, nemoclaw plugin blueprint structure, nemoclaw vs openshell, which cli, nemoclaw cli, openshell cli, sandbox commands, nemoclaw cli commands, nemoclaw command reference, nemoclaw network policy, sandbox egress control operator approval, nemoclaw troubleshooting, nemoclaw debug sandbox issues.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-reference\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":19},"01M7DAS5S79VK33XFGVAM2TFWF","nemoclaw-user-overview","Explains how OpenClaw, OpenShell, and NemoClaw form the ecosystem, NemoClaw's position in the stack, what NemoClaw adds beyond the community sandbox, and when to prefer NemoClaw versus integrating OpenShell and OpenClaw directly. Use when users ask about the relationship between OpenClaw, OpenShell, and NemoClaw, or when to use NemoClaw versus OpenShell. Trigger keywords - nemoclaw ecosystem, openclaw openshell, nemoclaw vs openshell, sandboxed openclaw, how nemoclaw works, nemoclaw sandbox lifecycle blueprint, nemoclaw overview, openclaw always-on assistants, nvidia openshell, nvidia nemotron, nemoclaw release notes, nemoclaw changelog.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-overview\u002FSKILL.md",[],[],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":19},"01M7DAS0PQEMET5MNGZ1ABSZVS","nemoclaw-user-monitor-sandbox","Inspects sandbox health, traces agent behavior, and diagnoses problems. Use when monitoring a running sandbox, debugging agent issues, or checking sandbox logs. Trigger keywords - monitor nemoclaw sandbox, debug nemoclaw agent issues.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-monitor-sandbox\u002FSKILL.md",[],[],{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":19},"01M7DARQYGF7E9A69VH6S3CGN9","nemoclaw-user-manage-sandboxes","Explains operational tasks after the quickstart: listing sandboxes, status and health checks, logs, diagnostics, port forwards, multiple sandboxes, credential reset, rebuilds, network presets, upgrades, and uninstall. Trigger keywords - manage nemoclaw sandboxes, nemoclaw status, nemoclaw list, nemoclaw dashboard port, nemoclaw rebuild, nemoclaw upgrade sandboxes, nemoclaw uninstall, sandbox mutability, sandbox runtime configuration, sandbox rebuild, nemoclaw backup, nemoclaw restore, workspace backup, openshell sandbox download upload, nemoclaw messaging channels, nemoclaw telegram, nemoclaw discord, nemoclaw slack, nemoclaw wechat, nemoclaw whatsapp, openshell channel messaging, nemoclaw workspace files, soul.md, user.md, identity.md, agents.md, sandbox persistence.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-manage-sandboxes\u002FSKILL.md",[],[],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":19},"01M7DARH8BRTG51TRCAB7YWDJ4","nemoclaw-user-manage-policy","Adds, removes, or modifies allowed endpoints in the sandbox policy. Use when customizing network policy, changing egress rules, or configuring sandbox endpoint access. Trigger keywords - customize nemoclaw network policy, sandbox egress policy configuration, nemoclaw integration policy examples, post-install policy setup, openshell approval workflow, policy preset, nemoclaw approve network requests, sandbox egress approval tui.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-manage-policy\u002FSKILL.md",[],[],{"skillNo":118,"name":119,"nameZh":6,"description":120,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":121,"categories":122,"keywords":123,"publishedAt":19},"01M7DARAT62M2VR37590VCZ5NS","nemoclaw-user-get-started","Installs NemoClaw, launches a sandbox, and runs the first agent prompt. Use when onboarding, installing, or launching a NemoClaw sandbox for the first time. Trigger keywords - nemoclaw quickstart, install nemoclaw openclaw sandbox, nemohermes quickstart, hermes agent nemoclaw, run hermes openshell sandbox, nemoclaw prerequisites, nemoclaw supported platforms, nemoclaw hardware software, nemoclaw windows wsl2 setup, nemoclaw install windows docker desktop.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-get-started\u002FSKILL.md",[],[]]