[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7D9PD28NK3GCEV5Z6RDMY7F":3,"skill-same:01M7D9PD28NK3GCEV5Z6RDMY7F":81},{"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":59,"commitSha":60,"skillDirectory":61,"forksCount":14,"repositoryHtmlUrl":62,"repositoryHomepageUrl":6,"ownerHtmlUrl":63,"ownerBlogUrl":64,"ownerDescription":65,"updatedAt":66,"install":67,"resources":80},"01M7D9PD28NK3GCEV5Z6RDMY7F","Stale Cache Finder",null,"Identify stale cache issues across browser cache, CDN layers, API response caching, and application-level caches that cause users to see outdated content","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\u002Fstale-cache-finder\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: Stale Cache Finder\ndescription: Identify stale cache issues across browser cache, CDN layers, API response caching, and application-level caches that cause users to see outdated content\nversion: 1.0.0\nauthor: Pramod\nlicense: MIT\ntags: [cache-testing, stale-cache, cdn, cache-invalidation, cache-busting, etag, cache-headers, browser-cache]\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# Stale Cache Finder Skill\n\nYou are an expert QA automation engineer specializing in cache correctness testing. When the user asks you to write, review, or debug tests for stale cache issues, follow these detailed instructions to identify caching defects across browser caches, CDN layers, API response caches, service workers, and application-level caching systems.\n\n## Core Principles\n\n1. **Cache correctness over cache performance** -- A fast response that serves stale data is worse than a slower response that serves correct data. Always prioritize correctness in cache testing, then optimize for performance.\n2. **Test the full cache chain** -- Modern web applications have multiple cache layers: browser memory cache, disk cache, service worker cache, CDN edge cache, reverse proxy cache, and application-level cache. Test each layer independently and verify they interact correctly.\n3. **Verify after mutation** -- The most critical cache tests verify that caches are properly invalidated after data mutations. Every write operation (create, update, delete) should be followed by a read that confirms the cache reflects the new state.\n4. **Assert on headers, not assumptions** -- Never assume cache behavior based on how you configured it. Always verify the actual `Cache-Control`, `ETag`, `Last-Modified`, `Age`, and `X-Cache` headers in responses.\n5. **Test cache across deployments** -- Stale cache issues frequently appear during deployments when old cached assets reference new APIs or vice versa. Simulate deployment scenarios in your test suite.\n6. **Reproduce user complaints** -- \"I still see the old version\" is one of the most common user complaints. Build tests that simulate the exact user journey: visit page, data changes, revisit page, verify updated content.\n\n## Project Structure\n\nOrganize stale cache testing projects with this structure:\n\n```\ntests\u002F\n  cache\u002F\n    headers\u002F\n      cache-control.spec.ts\n      etag-validation.spec.ts\n      last-modified.spec.ts\n      vary-header.spec.ts\n    cdn\u002F\n      cdn-invalidation.spec.ts\n      edge-cache.spec.ts\n      purge-verification.spec.ts\n    service-worker\u002F\n      sw-cache-audit.spec.ts\n      sw-update-flow.spec.ts\n    api-cache\u002F\n      response-cache.spec.ts\n      stale-while-revalidate.spec.ts\n    browser\u002F\n      disk-cache.spec.ts\n      memory-cache.spec.ts\n      storage-cache.spec.ts\n    post-deployment\u002F\n      asset-version.spec.ts\n      cache-busting.spec.ts\n  helpers\u002F\n    cache-header-parser.ts\n    cdn-client.ts\n    cache-inspector.ts\n  fixtures\u002F\n    cache-test.fixture.ts\nplaywright.config.ts\n```\n\n## Cache Header Validation\n\nCache headers are the foundation of caching behavior. Incorrect headers cause all downstream cache layers to behave incorrectly.\n\n### Cache-Control Header Testing\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ninterface CacheExpectation {\n  urlPattern: string | RegExp;\n  expectedDirectives: string[];\n  forbiddenDirectives?: string[];\n  maxAgeRange?: { min: number; max: number };\n  description: string;\n}\n\nconst CACHE_EXPECTATIONS: CacheExpectation[] = [\n  {\n    urlPattern: \u002F\\.(js|css)(\\?.*)?$\u002F,\n    expectedDirectives: ['public', 'max-age', 'immutable'],\n    maxAgeRange: { min: 2592000, max: 31536000 }, \u002F\u002F 30 days to 1 year\n    description: 'Static assets should be cached long-term with immutable',\n  },\n  {\n    urlPattern: \u002F\\.(png|jpg|jpeg|gif|svg|webp|avif)(\\?.*)?$\u002F,\n    expectedDirectives: ['public', 'max-age'],\n    maxAgeRange: { min: 86400, max: 31536000 }, \u002F\u002F 1 day to 1 year\n    description: 'Images should be cached with public directive',\n  },\n  {\n    urlPattern: \u002F\\\u002Fapi\\\u002F\u002F,\n    expectedDirectives: ['no-store'],\n    forbiddenDirectives: ['public'],\n    description: 'API responses should not be cached by default',\n  },\n  {\n    urlPattern: \u002F\\.html$\u002F,\n    expectedDirectives: ['no-cache'],\n    forbiddenDirectives: ['immutable'],\n    description: 'HTML pages should revalidate on every request',\n  },\n  {\n    urlPattern: \u002F\\\u002Fapi\\\u002Fpublic\\\u002F\u002F,\n    expectedDirectives: ['public', 's-maxage'],\n    maxAgeRange: { min: 60, max: 3600 }, \u002F\u002F 1 min to 1 hour\n    description: 'Public API endpoints should use s-maxage for CDN caching',\n  },\n];\n\nfunction parseCacheControl(header: string): Map\u003Cstring, string | boolean> {\n  const directives = new Map\u003Cstring, string | boolean>();\n  header.split(',').forEach((part) => {\n    const trimmed = part.trim();\n    const [key, value] = trimmed.split('=');\n    directives.set(key.trim(), value ? value.trim() : true);\n  });\n  return directives;\n}\n\ntest.describe('Cache-Control Header Validation', () => {\n  test('all responses should have correct Cache-Control headers', async ({ page }) => {\n    const violations: string[] = [];\n\n    page.on('response', (response) => {\n      const url = response.url();\n      const cacheControl = response.headers()['cache-control'];\n\n      for (const expectation of CACHE_EXPECTATIONS) {\n        const matches =\n          typeof expectation.urlPattern === 'string'\n            ? url.includes(expectation.urlPattern)\n            : expectation.urlPattern.test(url);\n\n        if (!matches) continue;\n\n        if (!cacheControl) {\n          violations.push(\n            `Missing Cache-Control for ${url} (${expectation.description})`\n          );\n          continue;\n        }\n\n        const directives = parseCacheControl(cacheControl);\n\n        for (const required of expectation.expectedDirectives) {\n          if (required === 'max-age') {\n            if (!directives.has('max-age') && !directives.has('s-maxage')) {\n              violations.push(\n                `${url}: missing max-age directive (${expectation.description})`\n              );\n            }\n          } else if (!directives.has(required)) {\n            violations.push(\n              `${url}: missing \"${required}\" directive (${expectation.description})`\n            );\n          }\n        }\n\n        if (expectation.forbiddenDirectives) {\n          for (const forbidden of expectation.forbiddenDirectives) {\n            if (directives.has(forbidden)) {\n              violations.push(\n                `${url}: has forbidden \"${forbidden}\" directive (${expectation.description})`\n              );\n            }\n          }\n        }\n\n        if (expectation.maxAgeRange) {\n          const maxAge = parseInt(\n            (directives.get('max-age') || directives.get('s-maxage') || '0') as string,\n            10\n          );\n          if (maxAge \u003C expectation.maxAgeRange.min || maxAge > expectation.maxAgeRange.max) {\n            violations.push(\n              `${url}: max-age=${maxAge} outside expected range [${expectation.maxAgeRange.min}, ${expectation.maxAgeRange.max}]`\n            );\n          }\n        }\n      }\n    });\n\n    await page.goto('\u002F');\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Navigate to a few key pages to capture more responses\n    const routes = ['\u002Fdashboard', '\u002Fsettings', '\u002Fabout'];\n    for (const route of routes) {\n      await page.goto(route);\n      await page.waitForLoadState('networkidle');\n    }\n\n    if (violations.length > 0) {\n      console.log('Cache-Control violations:');\n      violations.forEach((v) => console.log(`  - ${v}`));\n    }\n\n    expect(violations).toHaveLength(0);\n  });\n});\n```\n\n### ETag and Last-Modified Validation\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ntest.describe('ETag Validation', () => {\n  test('API responses should include ETag headers', async ({ request }) => {\n    const response = await request.get('\u002Fapi\u002Fpublic\u002Fskills');\n\n    const etag = response.headers()['etag'];\n    expect(etag, 'API response missing ETag header').toBeDefined();\n\n    \u002F\u002F Verify conditional request works\n    const conditionalResponse = await request.get('\u002Fapi\u002Fpublic\u002Fskills', {\n      headers: { 'If-None-Match': etag },\n    });\n\n    expect(conditionalResponse.status()).toBe(304);\n  });\n\n  test('ETag should change when content changes', async ({ request }) => {\n    \u002F\u002F First request to get initial ETag\n    const response1 = await request.get('\u002Fapi\u002Fpublic\u002Fskills');\n    const etag1 = response1.headers()['etag'];\n\n    \u002F\u002F Modify data (via API or direct DB mutation)\n    await request.post('\u002Fapi\u002Fskills', {\n      data: {\n        name: 'Test Skill',\n        description: 'A test skill for cache validation that verifies ETags change properly',\n        version: '1.0.0',\n      },\n    });\n\n    \u002F\u002F Second request should have a different ETag\n    const response2 = await request.get('\u002Fapi\u002Fpublic\u002Fskills');\n    const etag2 = response2.headers()['etag'];\n\n    expect(etag2).not.toBe(etag1);\n  });\n\n  test('Last-Modified should be present and accurate', async ({ request }) => {\n    const response = await request.get('\u002Fapi\u002Fpublic\u002Fskills\u002F1');\n    const lastModified = response.headers()['last-modified'];\n\n    expect(lastModified, 'Missing Last-Modified header').toBeDefined();\n\n    const lastModifiedDate = new Date(lastModified);\n    expect(lastModifiedDate.getTime()).not.toBeNaN();\n\n    \u002F\u002F Verify conditional request with If-Modified-Since\n    const conditionalResponse = await request.get('\u002Fapi\u002Fpublic\u002Fskills\u002F1', {\n      headers: { 'If-Modified-Since': lastModified },\n    });\n\n    expect(conditionalResponse.status()).toBe(304);\n  });\n});\n```\n\n### Vary Header Verification\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ntest.describe('Vary Header Verification', () => {\n  test('API responses should include appropriate Vary headers', async ({ request }) => {\n    const response = await request.get('\u002Fapi\u002Fpublic\u002Fskills');\n    const vary = response.headers()['vary'];\n\n    expect(vary, 'Missing Vary header on API response').toBeDefined();\n\n    \u002F\u002F API should vary on Accept and Accept-Encoding at minimum\n    const varyParts = vary.split(',').map((v: string) => v.trim().toLowerCase());\n    expect(varyParts).toContain('accept');\n    expect(varyParts).toContain('accept-encoding');\n  });\n\n  test('locale-dependent responses should Vary on Accept-Language', async ({ request }) => {\n    const response = await request.get('\u002Fapi\u002Fpublic\u002Fcontent', {\n      headers: { 'Accept-Language': 'en-US' },\n    });\n    const vary = response.headers()['vary'];\n\n    expect(vary).toBeDefined();\n    const varyParts = vary.split(',').map((v: string) => v.trim().toLowerCase());\n    expect(varyParts).toContain('accept-language');\n  });\n\n  test('auth-dependent responses should Vary on Authorization', async ({ request }) => {\n    const response = await request.get('\u002Fapi\u002Fdashboard');\n    const vary = response.headers()['vary'];\n\n    expect(vary).toBeDefined();\n    const varyParts = vary.split(',').map((v: string) => v.trim().toLowerCase());\n    expect(varyParts).toContain('authorization');\n  });\n});\n```\n\n## CDN Cache Testing\n\nCDN caches add a layer of complexity because they cache at the edge, geographically distributed from the origin.\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ninterface CDNCacheResult {\n  url: string;\n  cacheStatus: string;  \u002F\u002F HIT, MISS, STALE, BYPASS\n  age: number;\n  edgeLocation?: string;\n}\n\nasync function checkCDNCacheStatus(\n  url: string,\n  headers?: Record\u003Cstring, string>\n): Promise\u003CCDNCacheResult> {\n  const response = await fetch(url, { headers });\n\n  \u002F\u002F Common CDN cache status headers\n  const cacheStatus =\n    response.headers.get('x-cache') ||\n    response.headers.get('cf-cache-status') ||       \u002F\u002F Cloudflare\n    response.headers.get('x-vercel-cache') ||         \u002F\u002F Vercel\n    response.headers.get('x-cdn-cache-status') ||\n    response.headers.get('x-fastly-cache-status') ||  \u002F\u002F Fastly\n    'UNKNOWN';\n\n  const age = parseInt(response.headers.get('age') || '0', 10);\n  const edgeLocation =\n    response.headers.get('x-served-by') ||\n    response.headers.get('cf-ray') ||\n    response.headers.get('x-vercel-id');\n\n  return {\n    url,\n    cacheStatus: cacheStatus.toUpperCase(),\n    age,\n    edgeLocation: edgeLocation || undefined,\n  };\n}\n\ntest.describe('CDN Cache Testing', () => {\n  test('static assets should be served from CDN cache', async () => {\n    const staticAssets = [\n      '\u002Fassets\u002Fmain.js',\n      '\u002Fassets\u002Fstyles.css',\n      '\u002Fimages\u002Flogo.svg',\n    ];\n\n    for (const asset of staticAssets) {\n      const baseUrl = process.env.BASE_URL || 'https:\u002F\u002Fexample.com';\n\n      \u002F\u002F First request may be a MISS\n      await checkCDNCacheStatus(`${baseUrl}${asset}`);\n\n      \u002F\u002F Second request should be a HIT\n      const result = await checkCDNCacheStatus(`${baseUrl}${asset}`);\n\n      expect(\n        ['HIT', 'STALE'].includes(result.cacheStatus),\n        `${asset}: expected CDN cache HIT but got ${result.cacheStatus}`\n      ).toBe(true);\n    }\n  });\n\n  test('CDN should respect s-maxage for API responses', async () => {\n    const baseUrl = process.env.BASE_URL || 'https:\u002F\u002Fexample.com';\n    const url = `${baseUrl}\u002Fapi\u002Fpublic\u002Fskills`;\n\n    const response = await fetch(url);\n    const cacheControl = response.headers.get('cache-control') || '';\n\n    \u002F\u002F Verify s-maxage is present for CDN-cached APIs\n    expect(cacheControl).toContain('s-maxage');\n\n    const sMaxAge = parseInt(\n      cacheControl.match(\u002Fs-maxage=(\\d+)\u002F)?.[1] || '0',\n      10\n    );\n    expect(sMaxAge).toBeGreaterThan(0);\n  });\n\n  test('CDN should purge cache after content update', async ({ request }) => {\n    const baseUrl = process.env.BASE_URL || 'https:\u002F\u002Fexample.com';\n\n    \u002F\u002F Get initial content\n    const before = await fetch(`${baseUrl}\u002Fapi\u002Fpublic\u002Fskills\u002Ftest-skill`);\n    const beforeBody = await before.json();\n    const beforeEtag = before.headers.get('etag');\n\n    \u002F\u002F Update the content\n    await request.patch('\u002Fapi\u002Fskills\u002Ftest-skill', {\n      data: { description: `Updated at ${Date.now()}` },\n    });\n\n    \u002F\u002F Allow time for cache invalidation propagation\n    await new Promise((resolve) => setTimeout(resolve, 5000));\n\n    \u002F\u002F Verify CDN serves the updated content\n    const after = await fetch(`${baseUrl}\u002Fapi\u002Fpublic\u002Fskills\u002Ftest-skill`);\n    const afterBody = await after.json();\n    const afterEtag = after.headers.get('etag');\n\n    expect(afterBody.description).not.toBe(beforeBody.description);\n    expect(afterEtag).not.toBe(beforeEtag);\n  });\n});\n```\n\n## Service Worker Cache Auditing\n\nService workers intercept network requests and can serve stale content indefinitely if not managed correctly.\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ntest.describe('Service Worker Cache Auditing', () => {\n  test('service worker should not cache API responses', async ({ page }) => {\n    await page.goto('\u002F');\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Check what the service worker has cached\n    const cachedUrls = await page.evaluate(async () => {\n      const cacheNames = await caches.keys();\n      const allUrls: string[] = [];\n\n      for (const name of cacheNames) {\n        const cache = await caches.open(name);\n        const keys = await cache.keys();\n        allUrls.push(...keys.map((k) => k.url));\n      }\n\n      return allUrls;\n    });\n\n    \u002F\u002F API responses should NOT be in the service worker cache\n    const cachedApiUrls = cachedUrls.filter((url) => url.includes('\u002Fapi\u002F'));\n    expect(\n      cachedApiUrls,\n      `Service worker is caching API responses: ${cachedApiUrls.join(', ')}`\n    ).toHaveLength(0);\n  });\n\n  test('service worker should update cached assets on new deployment', async ({ page }) => {\n    await page.goto('\u002F');\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Get the current service worker version\n    const swVersion = await page.evaluate(async () => {\n      const registration = await navigator.serviceWorker.getRegistration();\n      if (!registration?.active) return null;\n\n      \u002F\u002F Most SWs expose a version via a custom message\n      return new Promise\u003Cstring | null>((resolve) => {\n        const channel = new MessageChannel();\n        channel.port1.onmessage = (event) => resolve(event.data.version);\n        registration.active!.postMessage({ type: 'GET_VERSION' }, [channel.port2]);\n        setTimeout(() => resolve(null), 2000);\n      });\n    });\n\n    \u002F\u002F Trigger a service worker update check\n    const updateFound = await page.evaluate(async () => {\n      const registration = await navigator.serviceWorker.getRegistration();\n      if (!registration) return false;\n\n      await registration.update();\n      return registration.waiting !== null || registration.installing !== null;\n    });\n\n    \u002F\u002F If an update is available, verify it activates\n    if (updateFound) {\n      \u002F\u002F Wait for the new service worker to activate\n      await page.evaluate(async () => {\n        const registration = await navigator.serviceWorker.getRegistration();\n        if (registration?.waiting) {\n          registration.waiting.postMessage({ type: 'SKIP_WAITING' });\n        }\n      });\n\n      await page.waitForTimeout(2000);\n\n      \u002F\u002F Verify the old caches are cleaned up\n      const remainingCaches = await page.evaluate(async () => {\n        return await caches.keys();\n      });\n\n      \u002F\u002F Should not have old versioned caches lingering\n      const oldCaches = remainingCaches.filter((name) =>\n        name.includes('v1') || name.includes('old')\n      );\n      expect(oldCaches).toHaveLength(0);\n    }\n  });\n\n  test('service worker should serve fresh content after skip-waiting', async ({ page }) => {\n    await page.goto('\u002F');\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Get content before any update\n    const contentBefore = await page.locator('h1').first().textContent();\n\n    \u002F\u002F Force service worker update and activation\n    await page.evaluate(async () => {\n      const registration = await navigator.serviceWorker.getRegistration();\n      if (registration) {\n        await registration.update();\n        if (registration.waiting) {\n          registration.waiting.postMessage({ type: 'SKIP_WAITING' });\n        }\n      }\n    });\n\n    \u002F\u002F Reload and verify content is fresh\n    await page.reload();\n    await page.waitForLoadState('networkidle');\n\n    const contentAfter = await page.locator('h1').first().textContent();\n\n    \u002F\u002F Content should at minimum be non-empty (not a broken cache response)\n    expect(contentAfter).toBeTruthy();\n    expect(contentAfter!.length).toBeGreaterThan(0);\n  });\n});\n```\n\n## Stale-While-Revalidate Testing\n\nThe `stale-while-revalidate` directive allows serving stale content while fetching fresh content in the background. Testing this behavior requires timing-aware assertions.\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ntest.describe('Stale-While-Revalidate Behavior', () => {\n  test('SWR responses should eventually serve fresh content', async ({ request }) => {\n    \u002F\u002F First request -- populates the cache\n    const response1 = await request.get('\u002Fapi\u002Fpublic\u002Ffeed');\n    expect(response1.ok()).toBe(true);\n    const body1 = await response1.json();\n\n    \u002F\u002F Wait for the max-age to expire but within SWR window\n    \u002F\u002F Assuming max-age=60, stale-while-revalidate=300\n    const cacheControl = response1.headers()['cache-control'];\n    const maxAge = parseInt(cacheControl.match(\u002Fmax-age=(\\d+)\u002F)?.[1] || '60', 10);\n\n    \u002F\u002F In testing, we simulate passage of time by waiting slightly longer than max-age\n    \u002F\u002F For a real test, you might use a test server that controls time\n    await new Promise((resolve) => setTimeout(resolve, (maxAge + 1) * 1000));\n\n    \u002F\u002F Second request -- should get stale content but trigger revalidation\n    const response2 = await request.get('\u002Fapi\u002Fpublic\u002Ffeed');\n    const age2 = parseInt(response2.headers()['age'] || '0', 10);\n\n    \u002F\u002F The response might be stale (age > max-age)\n    if (age2 > maxAge) {\n      \u002F\u002F This is the SWR behavior -- stale content served immediately\n      \u002F\u002F Wait for background revalidation to complete\n      await new Promise((resolve) => setTimeout(resolve, 2000));\n\n      \u002F\u002F Third request should now have fresh content\n      const response3 = await request.get('\u002Fapi\u002Fpublic\u002Ffeed');\n      const age3 = parseInt(response3.headers()['age'] || '0', 10);\n      expect(age3).toBeLessThan(maxAge);\n    }\n  });\n\n  test('SWR should not serve content beyond stale-while-revalidate window', async ({\n    request,\n  }) => {\n    const response = await request.get('\u002Fapi\u002Fpublic\u002Ffeed');\n    const cacheControl = response.headers()['cache-control'] || '';\n\n    if (cacheControl.includes('stale-while-revalidate')) {\n      const swrWindow = parseInt(\n        cacheControl.match(\u002Fstale-while-revalidate=(\\d+)\u002F)?.[1] || '0',\n        10\n      );\n\n      \u002F\u002F Verify the SWR window is reasonable\n      expect(swrWindow).toBeGreaterThan(0);\n      expect(swrWindow).toBeLessThanOrEqual(86400); \u002F\u002F Max 1 day\n    }\n  });\n});\n```\n\n## Cache Key Collision Detection\n\nCache key collisions happen when different content is cached under the same key, causing one user to see another user's data.\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ntest.describe('Cache Key Collision Detection', () => {\n  test('authenticated endpoints should not share cached responses', async ({ request }) => {\n    \u002F\u002F Request as User A\n    const responseA = await request.get('\u002Fapi\u002Fdashboard', {\n      headers: { Authorization: 'Bearer token-user-a' },\n    });\n    const dataA = await responseA.json();\n\n    \u002F\u002F Request as User B\n    const responseB = await request.get('\u002Fapi\u002Fdashboard', {\n      headers: { Authorization: 'Bearer token-user-b' },\n    });\n    const dataB = await responseB.json();\n\n    \u002F\u002F These should contain different user-specific data\n    expect(dataA.userId).not.toBe(dataB.userId);\n\n    \u002F\u002F Verify that User B did not receive User A's cached response\n    expect(dataB.userId).toBe('user-b');\n  });\n\n  test('query parameter variations should produce distinct cache entries', async ({\n    request,\n  }) => {\n    const response1 = await request.get('\u002Fapi\u002Fpublic\u002Fskills?page=1&sort=newest');\n    const body1 = await response1.json();\n\n    const response2 = await request.get('\u002Fapi\u002Fpublic\u002Fskills?page=2&sort=newest');\n    const body2 = await response2.json();\n\n    const response3 = await request.get('\u002Fapi\u002Fpublic\u002Fskills?page=1&sort=popular');\n    const body3 = await response3.json();\n\n    \u002F\u002F Each variation should return different content\n    expect(JSON.stringify(body1)).not.toBe(JSON.stringify(body2));\n    expect(JSON.stringify(body1)).not.toBe(JSON.stringify(body3));\n  });\n\n  test('locale-specific responses should not collide', async ({ request }) => {\n    const enResponse = await request.get('\u002Fapi\u002Fpublic\u002Fcontent', {\n      headers: { 'Accept-Language': 'en-US' },\n    });\n    const enBody = await enResponse.json();\n\n    const deResponse = await request.get('\u002Fapi\u002Fpublic\u002Fcontent', {\n      headers: { 'Accept-Language': 'de-DE' },\n    });\n    const deBody = await deResponse.json();\n\n    \u002F\u002F Content should differ by locale\n    expect(enBody.locale).not.toBe(deBody.locale);\n  });\n});\n```\n\n## Post-Deployment Cache Busting Verification\n\nDeployments are the most common trigger for stale cache issues. Old JavaScript bundles may reference old API contracts, causing runtime errors.\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ntest.describe('Post-Deployment Cache Busting', () => {\n  test('JavaScript bundles should have content-hashed filenames', async ({ page }) => {\n    const scriptUrls: string[] = [];\n\n    page.on('response', (response) => {\n      if (response.url().endsWith('.js')) {\n        scriptUrls.push(response.url());\n      }\n    });\n\n    await page.goto('\u002F');\n    await page.waitForLoadState('networkidle');\n\n    for (const url of scriptUrls) {\n      \u002F\u002F Content-hashed filenames typically look like: main.abc123.js or main-abc123.js\n      const hasContentHash = \u002F[.-][a-f0-9]{6,}\\.js\u002F.test(url);\n      expect(\n        hasContentHash,\n        `Script ${url} does not have a content hash in filename`\n      ).toBe(true);\n    }\n  });\n\n  test('CSS files should have content-hashed filenames', async ({ page }) => {\n    const cssUrls: string[] = [];\n\n    page.on('response', (response) => {\n      const contentType = response.headers()['content-type'] || '';\n      if (contentType.includes('text\u002Fcss') || response.url().endsWith('.css')) {\n        cssUrls.push(response.url());\n      }\n    });\n\n    await page.goto('\u002F');\n    await page.waitForLoadState('networkidle');\n\n    for (const url of cssUrls) {\n      const hasContentHash = \u002F[.-][a-f0-9]{6,}\\.css\u002F.test(url);\n      expect(\n        hasContentHash,\n        `CSS file ${url} does not have a content hash in filename`\n      ).toBe(true);\n    }\n  });\n\n  test('HTML should reference current asset versions after deployment', async ({ page }) => {\n    await page.goto('\u002F');\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Get all script and link tags\n    const assetRefs = await page.evaluate(() => {\n      const scripts = Array.from(document.querySelectorAll('script[src]')).map(\n        (s) => (s as HTMLScriptElement).src\n      );\n      const links = Array.from(\n        document.querySelectorAll('link[rel=\"stylesheet\"]')\n      ).map((l) => (l as HTMLLinkElement).href);\n      return { scripts, links };\n    });\n\n    \u002F\u002F Verify all referenced assets are actually reachable\n    for (const src of [...assetRefs.scripts, ...assetRefs.links]) {\n      const response = await page.request.get(src);\n      expect(\n        response.ok(),\n        `Asset not found (possible stale HTML cache): ${src}`\n      ).toBe(true);\n    }\n  });\n\n  test('API version header should match deployed version', async ({ request }) => {\n    const response = await request.get('\u002Fapi\u002Fhealth');\n    const apiVersion = response.headers()['x-api-version'];\n    const deployId = response.headers()['x-deployment-id'];\n\n    expect(apiVersion).toBeDefined();\n\n    \u002F\u002F If a deployment ID is available, verify it matches expectations\n    if (deployId && process.env.EXPECTED_DEPLOYMENT_ID) {\n      expect(deployId).toBe(process.env.EXPECTED_DEPLOYMENT_ID);\n    }\n  });\n});\n```\n\n## Browser Storage Cache Testing\n\nApplications often cache data in localStorage, sessionStorage, or IndexedDB. Stale data in these stores can cause subtle bugs.\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ntest.describe('Browser Storage Cache Testing', () => {\n  test('localStorage cache should be invalidated on data mutation', async ({ page }) => {\n    await page.goto('\u002Fdashboard');\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Check what is cached in localStorage\n    const cachedData = await page.evaluate(() => {\n      const cache: Record\u003Cstring, string> = {};\n      for (let i = 0; i \u003C localStorage.length; i++) {\n        const key = localStorage.key(i)!;\n        if (key.startsWith('cache:') || key.startsWith('data:')) {\n          cache[key] = localStorage.getItem(key)!;\n        }\n      }\n      return cache;\n    });\n\n    \u002F\u002F Perform a mutation\n    await page.locator('[data-testid=\"update-profile\"]').click();\n    await page.fill('[data-testid=\"name-input\"]', 'Updated Name');\n    await page.locator('[data-testid=\"save-button\"]').click();\n    await page.waitForResponse('**\u002Fapi\u002Fprofile');\n\n    \u002F\u002F Verify the cached data was invalidated or updated\n    const updatedCache = await page.evaluate(() => {\n      const cache: Record\u003Cstring, string> = {};\n      for (let i = 0; i \u003C localStorage.length; i++) {\n        const key = localStorage.key(i)!;\n        if (key.startsWith('cache:') || key.startsWith('data:')) {\n          cache[key] = localStorage.getItem(key)!;\n        }\n      }\n      return cache;\n    });\n\n    \u002F\u002F Cache entries related to profile should be updated or removed\n    for (const [key, value] of Object.entries(cachedData)) {\n      if (key.includes('profile') || key.includes('user')) {\n        const newValue = updatedCache[key];\n        expect(\n          newValue !== value || newValue === undefined,\n          `localStorage key \"${key}\" was not invalidated after mutation`\n        ).toBe(true);\n      }\n    }\n  });\n\n  test('cached data should have TTL and not persist forever', async ({ page }) => {\n    await page.goto('\u002Fdashboard');\n    await page.waitForLoadState('networkidle');\n\n    const cacheEntries = await page.evaluate(() => {\n      const entries: { key: string; hasTimestamp: boolean; age: number | null }[] = [];\n      for (let i = 0; i \u003C localStorage.length; i++) {\n        const key = localStorage.key(i)!;\n        const value = localStorage.getItem(key)!;\n\n        let hasTimestamp = false;\n        let age: number | null = null;\n\n        try {\n          const parsed = JSON.parse(value);\n          if (parsed.timestamp || parsed.cachedAt || parsed.expiresAt) {\n            hasTimestamp = true;\n            const ts = parsed.timestamp || parsed.cachedAt;\n            if (ts) {\n              age = Date.now() - new Date(ts).getTime();\n            }\n          }\n        } catch {\n          \u002F\u002F Not JSON, ignore\n        }\n\n        if (key.startsWith('cache:')) {\n          entries.push({ key, hasTimestamp, age });\n        }\n      }\n      return entries;\n    });\n\n    for (const entry of cacheEntries) {\n      expect(\n        entry.hasTimestamp,\n        `Cache entry \"${entry.key}\" has no timestamp -- cannot determine staleness`\n      ).toBe(true);\n\n      if (entry.age !== null) {\n        \u002F\u002F Cache entries older than 24 hours are suspicious\n        const maxAge = 24 * 60 * 60 * 1000; \u002F\u002F 24 hours in ms\n        expect(\n          entry.age,\n          `Cache entry \"${entry.key}\" is ${Math.round(entry.age \u002F 3600000)}h old`\n        ).toBeLessThan(maxAge);\n      }\n    }\n  });\n});\n```\n\n## Configuration\n\n### Playwright Configuration for Cache Testing\n\n```typescript\n\u002F\u002F playwright.config.ts\nimport { defineConfig, devices } from '@playwright\u002Ftest';\n\nexport default defineConfig({\n  testDir: '.\u002Ftests\u002Fcache',\n  fullyParallel: false, \u002F\u002F Cache tests may interfere with each other\n  retries: 1,\n  reporter: [\n    ['html', { open: 'never' }],\n    ['json', { outputFile: 'cache-test-results.json' }],\n  ],\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: 'cache-headers',\n      testMatch: '**\u002Fheaders\u002F**',\n      use: {\n        ...devices['Desktop Chrome'],\n        \u002F\u002F Disable browser cache for header tests\n        bypassCSP: true,\n      },\n    },\n    {\n      name: 'cdn-cache',\n      testMatch: '**\u002Fcdn\u002F**',\n      use: {\n        ...devices['Desktop Chrome'],\n      },\n    },\n    {\n      name: 'service-worker',\n      testMatch: '**\u002Fservice-worker\u002F**',\n      use: {\n        ...devices['Desktop Chrome'],\n        serviceWorkers: 'allow',\n      },\n    },\n    {\n      name: 'browser-cache',\n      testMatch: '**\u002Fbrowser\u002F**',\n      use: {\n        ...devices['Desktop Chrome'],\n      },\n    },\n  ],\n});\n```\n\n## Best Practices\n\n1. **Always validate Cache-Control headers on every response** -- Do not rely on server configuration alone. Add automated tests that verify every response type has the correct caching headers.\n\n2. **Use content-hashed filenames for all static assets** -- Content hashing (e.g., `main.abc123.js`) ensures that new deployments serve new files while old cached files remain valid for users who have not refreshed.\n\n3. **Set `no-store` on authenticated API responses** -- User-specific data must never be cached by shared caches (CDN, proxy). Use `Cache-Control: no-store` for any response that contains user-specific content.\n\n4. **Include `Vary` headers for content negotiation** -- When responses vary by `Accept-Language`, `Accept`, or `Authorization`, the `Vary` header must declare these. Missing `Vary` headers cause cache key collisions.\n\n5. **Test cache behavior after every deployment** -- Run a post-deployment smoke test that verifies cached assets are accessible, HTML references current asset versions, and API responses are fresh.\n\n6. **Implement cache versioning in service workers** -- Service worker caches must be versioned. On each deployment, the new service worker should create new cache entries and delete old versioned caches.\n\n7. **Use `s-maxage` for CDN caching separate from browser caching** -- `s-maxage` controls CDN cache duration independently from `max-age`. This allows short browser cache times with longer CDN cache times.\n\n8. **Add cache TTL to all application-level cache entries** -- Every entry in localStorage, Redis, or in-memory caches must have an explicit expiration time. Cache entries without TTL persist forever and become stale silently.\n\n9. **Monitor cache hit rates in production** -- Low cache hit rates indicate misconfigured caching. High hit rates with user complaints indicate stale cache serving. Track both metrics.\n\n10. **Test the `no-cache` vs `no-store` distinction** -- `no-cache` means \"revalidate before use\" (still caches, but checks freshness). `no-store` means \"never cache at all\". Using the wrong one causes either stale content or unnecessary requests.\n\n11. **Purge CDN cache as part of the deployment pipeline** -- Automate CDN cache purging in your CI\u002FCD pipeline. Manual purging is error-prone and delays fresh content delivery.\n\n12. **Test with multiple browsers** -- Browser caching implementations differ. Chrome, Firefox, and Safari handle `Cache-Control` directives slightly differently, especially around `stale-while-revalidate` and service worker interactions.\n\n## Anti-Patterns to Avoid\n\n1. **Using `Cache-Control: no-cache` when you mean `no-store`** -- `no-cache` still caches the response; it just requires revalidation. For sensitive data, always use `no-store` to prevent any caching.\n\n2. **Relying on CDN purge without verification** -- CDN purge APIs are eventually consistent. A purge request does not guarantee instant cache invalidation across all edge locations. Always verify with a follow-up request.\n\n3. **Caching responses without `Vary` headers** -- If your endpoint returns different content based on request headers (Accept-Language, Authorization), missing `Vary` headers will cause the CDN to serve the wrong cached response to the wrong user.\n\n4. **Setting long `max-age` on HTML documents** -- HTML pages are the entry point for loading all other assets. A long `max-age` on HTML means users will not receive updated asset references until the HTML cache expires. Use `no-cache` or short `max-age` for HTML.\n\n5. **Storing sensitive data in browser cache without encryption** -- Browser disk cache stores response bodies in plaintext. Sensitive data cached to disk can be read by other applications or users on shared computers.\n\n6. **Ignoring service worker cache during testing** -- Service workers operate independently of the browser's HTTP cache. A test that clears the browser cache but ignores the service worker cache will still see stale content.\n\n7. **Using timestamps as cache busters in query strings** -- Appending `?t=1234567890` to URLs defeats caching entirely and wastes CDN bandwidth. Use content-hashed filenames instead, which only change when content actually changes.\n\n## Debugging Tips\n\n1. **Use Chrome DevTools Network panel with \"Disable cache\" unchecked** -- The \"Disable cache\" checkbox in DevTools prevents testing real cache behavior. Turn it off to see actual cache hits and misses in the Size column.\n\n2. **Check the `Age` header to determine how long content has been cached** -- The `Age` header (in seconds) tells you how long the response has been in a shared cache. A high `Age` value on content that should be fresh indicates a stale cache problem.\n\n3. **Use `curl -I` to inspect response headers without browser interference** -- Browsers add their own caching behavior. Use `curl -I \u003Curl>` to see the raw response headers from the server without any browser-side caching modifications.\n\n4. **Verify service worker state in Application tab** -- Chrome DevTools Application tab shows registered service workers, their status (active, waiting, installing), and the contents of each cache storage. This is essential for debugging service worker caching issues.\n\n5. **Check for cache poisoning with different request variations** -- Test the same URL with different `Accept`, `Accept-Language`, and `Authorization` headers. If you receive the same cached response regardless of header variations, the cache is not respecting `Vary`.\n\n6. **Monitor the `X-Cache` header across multiple requests** -- Make the same request 3-4 times in sequence. The first should show `MISS`, and subsequent requests should show `HIT`. If all show `MISS`, caching is not working. If all show `HIT` after content changes, the cache is stale.\n\n7. **Use Lighthouse to audit cache policy** -- Lighthouse's \"Serve static assets with an efficient cache policy\" audit identifies resources with short or missing cache lifetimes. Run this after deployments to verify caching is configured correctly.\n\n8. **Compare `ETag` values before and after data changes** -- If the `ETag` does not change after you modify data, the server is generating ETags incorrectly (possibly from a stale cache layer). Track ETags across mutations to verify they update.\n\n9. **Test with `Cache-Control: no-cache` request header** -- Sending `Cache-Control: no-cache` in your request forces the server (and most CDNs) to bypass cache and return a fresh response. Compare this fresh response to the normally cached response to verify they match.\n\n10. **Check for `Set-Cookie` headers on cached responses** -- Responses with `Set-Cookie` headers should never be cached by shared caches. If you see `Set-Cookie` alongside `Cache-Control: public`, this is a serious bug that can leak session cookies between users.\n","# Stale Cache Finder Skill\n\nYou are an expert QA automation engineer specializing in cache correctness testing. When the user asks you to write, review, or debug tests for stale cache issues, follow these detailed instructions to identify caching defects across browser caches, CDN layers, API response caches, service workers, and application-level caching systems.\n\n## Core Principles\n\n1. **Cache correctness over cache performance** -- A fast response that serves stale data is worse than a slower response that serves correct data. Always prioritize correctness in cache testing, then optimize for performance.\n2. **Test the full cache chain** -- Modern web applications have multiple cache layers: browser memory cache, disk cache, service worker cache, CDN edge cache, reverse proxy cache, and application-level cache. Test each layer independently and verify they interact correctly.\n3. **Verify after mutation** -- The most critical cache tests verify that caches are properly invalidated after data mutations. Every write operation (create, update, delete) should be followed by a read that confirms the cache reflects the new state.\n4. **Assert on headers, not assumptions** -- Never assume cache behavior based on how you configured it. Always verify the actual `Cache-Control`, `ETag`, `Last-Modified`, `Age`, and `X-Cache` headers in responses.\n5. **Test cache across deployments** -- Stale cache issues frequently appear during deployments when old cached assets reference new APIs or vice versa. Simulate deployment scenarios in your test suite.\n6. **Reproduce user complaints** -- \"I still see the old version\" is one of the most common user complaints. Build tests that simulate the exact user journey: visit page, data changes, revisit page, verify updated content.\n\n## Project Structure\n\nOrganize stale cache testing projects with this structure:\n\n```\ntests\u002F\n  cache\u002F\n    headers\u002F\n      cache-control.spec.ts\n      etag-validation.spec.ts\n      last-modified.spec.ts\n      vary-header.spec.ts\n    cdn\u002F\n      cdn-invalidation.spec.ts\n      edge-cache.spec.ts\n      purge-verification.spec.ts\n    service-worker\u002F\n      sw-cache-audit.spec.ts\n      sw-update-flow.spec.ts\n    api-cache\u002F\n      response-cache.spec.ts\n      stale-while-revalidate.spec.ts\n    browser\u002F\n      disk-cache.spec.ts\n      memory-cache.spec.ts\n      storage-cache.spec.ts\n    post-deployment\u002F\n      asset-version.spec.ts\n      cache-busting.spec.ts\n  helpers\u002F\n    cache-header-parser.ts\n    cdn-client.ts\n    cache-inspector.ts\n  fixtures\u002F\n    cache-test.fixture.ts\nplaywright.config.ts\n```\n\n## Cache Header Validation\n\nCache headers are the foundation of caching behavior. Incorrect headers cause all downstream cache layers to behave incorrectly.\n\n### Cache-Control Header Testing\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ninterface CacheExpectation {\n  urlPattern: string | RegExp;\n  expectedDirectives: string[];\n  forbiddenDirectives?: string[];\n  maxAgeRange?: { min: number; max: number };\n  description: string;\n}\n\nconst CACHE_EXPECTATIONS: CacheExpectation[] = [\n  {\n    urlPattern: \u002F\\.(js|css)(\\?.*)?$\u002F,\n    expectedDirectives: ['public', 'max-age', 'immutable'],\n    maxAgeRange: { min: 2592000, max: 31536000 }, \u002F\u002F 30 days to 1 year\n    description: 'Static assets should be cached long-term with immutable',\n  },\n  {\n    urlPattern: \u002F\\.(png|jpg|jpeg|gif|svg|webp|avif)(\\?.*)?$\u002F,\n    expectedDirectives: ['public', 'max-age'],\n    maxAgeRange: { min: 86400, max: 31536000 }, \u002F\u002F 1 day to 1 year\n    description: 'Images should be cached with public directive',\n  },\n  {\n    urlPattern: \u002F\\\u002Fapi\\\u002F\u002F,\n    expectedDirectives: ['no-store'],\n    forbiddenDirectives: ['public'],\n    description: 'API responses should not be cached by default',\n  },\n  {\n    urlPattern: \u002F\\.html$\u002F,\n    expectedDirectives: ['no-cache'],\n    forbiddenDirectives: ['immutable'],\n    description: 'HTML pages should revalidate on every request',\n  },\n  {\n    urlPattern: \u002F\\\u002Fapi\\\u002Fpublic\\\u002F\u002F,\n    expectedDirectives: ['public', 's-maxage'],\n    maxAgeRange: { min: 60, max: 3600 }, \u002F\u002F 1 min to 1 hour\n    description: 'Public API endpoints should use s-maxage for CDN caching',\n  },\n];\n\nfunction parseCacheControl(header: string): Map\u003Cstring, string | boolean> {\n  const directives = new Map\u003Cstring, string | boolean>();\n  header.split(',').forEach((part) => {\n    const trimmed = part.trim();\n    const [key, value] = trimmed.split('=');\n    directives.set(key.trim(), value ? value.trim() : true);\n  });\n  return directives;\n}\n\ntest.describe('Cache-Control Header Validation', () => {\n  test('all responses should have correct Cache-Control headers', async ({ page }) => {\n    const violations: string[] = [];\n\n    page.on('response', (response) => {\n      const url = response.url();\n      const cacheControl = response.headers()['cache-control'];\n\n      for (const expectation of CACHE_EXPECTATIONS) {\n        const matches =\n          typeof expectation.urlPattern === 'string'\n            ? url.includes(expectation.urlPattern)\n            : expectation.urlPattern.test(url);\n\n        if (!matches) continue;\n\n        if (!cacheControl) {\n          violations.push(\n            `Missing Cache-Control for ${url} (${expectation.description})`\n          );\n          continue;\n        }\n\n        const directives = parseCacheControl(cacheControl);\n\n        for (const required of expectation.expectedDirectives) {\n          if (required === 'max-age') {\n            if (!directives.has('max-age') && !directives.has('s-maxage')) {\n              violations.push(\n                `${url}: missing max-age directive (${expectation.description})`\n              );\n            }\n          } else if (!directives.has(required)) {\n            violations.push(\n              `${url}: missing \"${required}\" directive (${expectation.description})`\n            );\n          }\n        }\n\n        if (expectation.forbiddenDirectives) {\n          for (const forbidden of expectation.forbiddenDirectives) {\n            if (directives.has(forbidden)) {\n              violations.push(\n                `${url}: has forbidden \"${forbidden}\" directive (${expectation.description})`\n              );\n            }\n          }\n        }\n\n        if (expectation.maxAgeRange) {\n          const maxAge = parseInt(\n            (directives.get('max-age') || directives.get('s-maxage') || '0') as string,\n            10\n          );\n          if (maxAge \u003C expectation.maxAgeRange.min || maxAge > expectation.maxAgeRange.max) {\n            violations.push(\n              `${url}: max-age=${maxAge} outside expected range [${expectation.maxAgeRange.min}, ${expectation.maxAgeRange.max}]`\n            );\n          }\n        }\n      }\n    });\n\n    await page.goto('\u002F');\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Navigate to a few key pages to capture more responses\n    const routes = ['\u002Fdashboard', '\u002Fsettings', '\u002Fabout'];\n    for (const route of routes) {\n      await page.goto(route);\n      await page.waitForLoadState('networkidle');\n    }\n\n    if (violations.length > 0) {\n      console.log('Cache-Control violations:');\n      violations.forEach((v) => console.log(`  - ${v}`));\n    }\n\n    expect(violations).toHaveLength(0);\n  });\n});\n```\n\n### ETag and Last-Modified Validation\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ntest.describe('ETag Validation', () => {\n  test('API responses should include ETag headers', async ({ request }) => {\n    const response = await request.get('\u002Fapi\u002Fpublic\u002Fskills');\n\n    const etag = response.headers()['etag'];\n    expect(etag, 'API response missing ETag header').toBeDefined();\n\n    \u002F\u002F Verify conditional request works\n    const conditionalResponse = await request.get('\u002Fapi\u002Fpublic\u002Fskills', {\n      headers: { 'If-None-Match': etag },\n    });\n\n    expect(conditionalResponse.status()).toBe(304);\n  });\n\n  test('ETag should change when content changes', async ({ request }) => {\n    \u002F\u002F First request to get initial ETag\n    const response1 = await request.get('\u002Fapi\u002Fpublic\u002Fskills');\n    const etag1 = response1.headers()['etag'];\n\n    \u002F\u002F Modify data (via API or direct DB mutation)\n    await request.post('\u002Fapi\u002Fskills', {\n      data: {\n        name: 'Test Skill',\n        description: 'A test skill for cache validation that verifies ETags change properly',\n        version: '1.0.0',\n      },\n    });\n\n    \u002F\u002F Second request should have a different ETag\n    const response2 = await request.get('\u002Fapi\u002Fpublic\u002Fskills');\n    const etag2 = response2.headers()['etag'];\n\n    expect(etag2).not.toBe(etag1);\n  });\n\n  test('Last-Modified should be present and accurate', async ({ request }) => {\n    const response = await request.get('\u002Fapi\u002Fpublic\u002Fskills\u002F1');\n    const lastModified = response.headers()['last-modified'];\n\n    expect(lastModified, 'Missing Last-Modified header').toBeDefined();\n\n    const lastModifiedDate = new Date(lastModified);\n    expect(lastModifiedDate.getTime()).not.toBeNaN();\n\n    \u002F\u002F Verify conditional request with If-Modified-Since\n    const conditionalResponse = await request.get('\u002Fapi\u002Fpublic\u002Fskills\u002F1', {\n      headers: { 'If-Modified-Since': lastModified },\n    });\n\n    expect(conditionalResponse.status()).toBe(304);\n  });\n});\n```\n\n### Vary Header Verification\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ntest.describe('Vary Header Verification', () => {\n  test('API responses should include appropriate Vary headers', async ({ request }) => {\n    const response = await request.get('\u002Fapi\u002Fpublic\u002Fskills');\n    const vary = response.headers()['vary'];\n\n    expect(vary, 'Missing Vary header on API response').toBeDefined();\n\n    \u002F\u002F API should vary on Accept and Accept-Encoding at minimum\n    const varyParts = vary.split(',').map((v: string) => v.trim().toLowerCase());\n    expect(varyParts).toContain('accept');\n    expect(varyParts).toContain('accept-encoding');\n  });\n\n  test('locale-dependent responses should Vary on Accept-Language', async ({ request }) => {\n    const response = await request.get('\u002Fapi\u002Fpublic\u002Fcontent', {\n      headers: { 'Accept-Language': 'en-US' },\n    });\n    const vary = response.headers()['vary'];\n\n    expect(vary).toBeDefined();\n    const varyParts = vary.split(',').map((v: string) => v.trim().toLowerCase());\n    expect(varyParts).toContain('accept-language');\n  });\n\n  test('auth-dependent responses should Vary on Authorization', async ({ request }) => {\n    const response = await request.get('\u002Fapi\u002Fdashboard');\n    const vary = response.headers()['vary'];\n\n    expect(vary).toBeDefined();\n    const varyParts = vary.split(',').map((v: string) => v.trim().toLowerCase());\n    expect(varyParts).toContain('authorization');\n  });\n});\n```\n\n## CDN Cache Testing\n\nCDN caches add a layer of complexity because they cache at the edge, geographically distributed from the origin.\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ninterface CDNCacheResult {\n  url: string;\n  cacheStatus: string;  \u002F\u002F HIT, MISS, STALE, BYPASS\n  age: number;\n  edgeLocation?: string;\n}\n\nasync function checkCDNCacheStatus(\n  url: string,\n  headers?: Record\u003Cstring, string>\n): Promise\u003CCDNCacheResult> {\n  const response = await fetch(url, { headers });\n\n  \u002F\u002F Common CDN cache status headers\n  const cacheStatus =\n    response.headers.get('x-cache') ||\n    response.headers.get('cf-cache-status') ||       \u002F\u002F Cloudflare\n    response.headers.get('x-vercel-cache') ||         \u002F\u002F Vercel\n    response.headers.get('x-cdn-cache-status') ||\n    response.headers.get('x-fastly-cache-status') ||  \u002F\u002F Fastly\n    'UNKNOWN';\n\n  const age = parseInt(response.headers.get('age') || '0', 10);\n  const edgeLocation =\n    response.headers.get('x-served-by') ||\n    response.headers.get('cf-ray') ||\n    response.headers.get('x-vercel-id');\n\n  return {\n    url,\n    cacheStatus: cacheStatus.toUpperCase(),\n    age,\n    edgeLocation: edgeLocation || undefined,\n  };\n}\n\ntest.describe('CDN Cache Testing', () => {\n  test('static assets should be served from CDN cache', async () => {\n    const staticAssets = [\n      '\u002Fassets\u002Fmain.js',\n      '\u002Fassets\u002Fstyles.css',\n      '\u002Fimages\u002Flogo.svg',\n    ];\n\n    for (const asset of staticAssets) {\n      const baseUrl = process.env.BASE_URL || 'https:\u002F\u002Fexample.com';\n\n      \u002F\u002F First request may be a MISS\n      await checkCDNCacheStatus(`${baseUrl}${asset}`);\n\n      \u002F\u002F Second request should be a HIT\n      const result = await checkCDNCacheStatus(`${baseUrl}${asset}`);\n\n      expect(\n        ['HIT', 'STALE'].includes(result.cacheStatus),\n        `${asset}: expected CDN cache HIT but got ${result.cacheStatus}`\n      ).toBe(true);\n    }\n  });\n\n  test('CDN should respect s-maxage for API responses', async () => {\n    const baseUrl = process.env.BASE_URL || 'https:\u002F\u002Fexample.com';\n    const url = `${baseUrl}\u002Fapi\u002Fpublic\u002Fskills`;\n\n    const response = await fetch(url);\n    const cacheControl = response.headers.get('cache-control') || '';\n\n    \u002F\u002F Verify s-maxage is present for CDN-cached APIs\n    expect(cacheControl).toContain('s-maxage');\n\n    const sMaxAge = parseInt(\n      cacheControl.match(\u002Fs-maxage=(\\d+)\u002F)?.[1] || '0',\n      10\n    );\n    expect(sMaxAge).toBeGreaterThan(0);\n  });\n\n  test('CDN should purge cache after content update', async ({ request }) => {\n    const baseUrl = process.env.BASE_URL || 'https:\u002F\u002Fexample.com';\n\n    \u002F\u002F Get initial content\n    const before = await fetch(`${baseUrl}\u002Fapi\u002Fpublic\u002Fskills\u002Ftest-skill`);\n    const beforeBody = await before.json();\n    const beforeEtag = before.headers.get('etag');\n\n    \u002F\u002F Update the content\n    await request.patch('\u002Fapi\u002Fskills\u002Ftest-skill', {\n      data: { description: `Updated at ${Date.now()}` },\n    });\n\n    \u002F\u002F Allow time for cache invalidation propagation\n    await new Promise((resolve) => setTimeout(resolve, 5000));\n\n    \u002F\u002F Verify CDN serves the updated content\n    const after = await fetch(`${baseUrl}\u002Fapi\u002Fpublic\u002Fskills\u002Ftest-skill`);\n    const afterBody = await after.json();\n    const afterEtag = after.headers.get('etag');\n\n    expect(afterBody.description).not.toBe(beforeBody.description);\n    expect(afterEtag).not.toBe(beforeEtag);\n  });\n});\n```\n\n## Service Worker Cache Auditing\n\nService workers intercept network requests and can serve stale content indefinitely if not managed correctly.\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ntest.describe('Service Worker Cache Auditing', () => {\n  test('service worker should not cache API responses', async ({ page }) => {\n    await page.goto('\u002F');\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Check what the service worker has cached\n    const cachedUrls = await page.evaluate(async () => {\n      const cacheNames = await caches.keys();\n      const allUrls: string[] = [];\n\n      for (const name of cacheNames) {\n        const cache = await caches.open(name);\n        const keys = await cache.keys();\n        allUrls.push(...keys.map((k) => k.url));\n      }\n\n      return allUrls;\n    });\n\n    \u002F\u002F API responses should NOT be in the service worker cache\n    const cachedApiUrls = cachedUrls.filter((url) => url.includes('\u002Fapi\u002F'));\n    expect(\n      cachedApiUrls,\n      `Service worker is caching API responses: ${cachedApiUrls.join(', ')}`\n    ).toHaveLength(0);\n  });\n\n  test('service worker should update cached assets on new deployment', async ({ page }) => {\n    await page.goto('\u002F');\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Get the current service worker version\n    const swVersion = await page.evaluate(async () => {\n      const registration = await navigator.serviceWorker.getRegistration();\n      if (!registration?.active) return null;\n\n      \u002F\u002F Most SWs expose a version via a custom message\n      return new Promise\u003Cstring | null>((resolve) => {\n        const channel = new MessageChannel();\n        channel.port1.onmessage = (event) => resolve(event.data.version);\n        registration.active!.postMessage({ type: 'GET_VERSION' }, [channel.port2]);\n        setTimeout(() => resolve(null), 2000);\n      });\n    });\n\n    \u002F\u002F Trigger a service worker update check\n    const updateFound = await page.evaluate(async () => {\n      const registration = await navigator.serviceWorker.getRegistration();\n      if (!registration) return false;\n\n      await registration.update();\n      return registration.waiting !== null || registration.installing !== null;\n    });\n\n    \u002F\u002F If an update is available, verify it activates\n    if (updateFound) {\n      \u002F\u002F Wait for the new service worker to activate\n      await page.evaluate(async () => {\n        const registration = await navigator.serviceWorker.getRegistration();\n        if (registration?.waiting) {\n          registration.waiting.postMessage({ type: 'SKIP_WAITING' });\n        }\n      });\n\n      await page.waitForTimeout(2000);\n\n      \u002F\u002F Verify the old caches are cleaned up\n      const remainingCaches = await page.evaluate(async () => {\n        return await caches.keys();\n      });\n\n      \u002F\u002F Should not have old versioned caches lingering\n      const oldCaches = remainingCaches.filter((name) =>\n        name.includes('v1') || name.includes('old')\n      );\n      expect(oldCaches).toHaveLength(0);\n    }\n  });\n\n  test('service worker should serve fresh content after skip-waiting', async ({ page }) => {\n    await page.goto('\u002F');\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Get content before any update\n    const contentBefore = await page.locator('h1').first().textContent();\n\n    \u002F\u002F Force service worker update and activation\n    await page.evaluate(async () => {\n      const registration = await navigator.serviceWorker.getRegistration();\n      if (registration) {\n        await registration.update();\n        if (registration.waiting) {\n          registration.waiting.postMessage({ type: 'SKIP_WAITING' });\n        }\n      }\n    });\n\n    \u002F\u002F Reload and verify content is fresh\n    await page.reload();\n    await page.waitForLoadState('networkidle');\n\n    const contentAfter = await page.locator('h1').first().textContent();\n\n    \u002F\u002F Content should at minimum be non-empty (not a broken cache response)\n    expect(contentAfter).toBeTruthy();\n    expect(contentAfter!.length).toBeGreaterThan(0);\n  });\n});\n```\n\n## Stale-While-Revalidate Testing\n\nThe `stale-while-revalidate` directive allows serving stale content while fetching fresh content in the background. Testing this behavior requires timing-aware assertions.\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ntest.describe('Stale-While-Revalidate Behavior', () => {\n  test('SWR responses should eventually serve fresh content', async ({ request }) => {\n    \u002F\u002F First request -- populates the cache\n    const response1 = await request.get('\u002Fapi\u002Fpublic\u002Ffeed');\n    expect(response1.ok()).toBe(true);\n    const body1 = await response1.json();\n\n    \u002F\u002F Wait for the max-age to expire but within SWR window\n    \u002F\u002F Assuming max-age=60, stale-while-revalidate=300\n    const cacheControl = response1.headers()['cache-control'];\n    const maxAge = parseInt(cacheControl.match(\u002Fmax-age=(\\d+)\u002F)?.[1] || '60', 10);\n\n    \u002F\u002F In testing, we simulate passage of time by waiting slightly longer than max-age\n    \u002F\u002F For a real test, you might use a test server that controls time\n    await new Promise((resolve) => setTimeout(resolve, (maxAge + 1) * 1000));\n\n    \u002F\u002F Second request -- should get stale content but trigger revalidation\n    const response2 = await request.get('\u002Fapi\u002Fpublic\u002Ffeed');\n    const age2 = parseInt(response2.headers()['age'] || '0', 10);\n\n    \u002F\u002F The response might be stale (age > max-age)\n    if (age2 > maxAge) {\n      \u002F\u002F This is the SWR behavior -- stale content served immediately\n      \u002F\u002F Wait for background revalidation to complete\n      await new Promise((resolve) => setTimeout(resolve, 2000));\n\n      \u002F\u002F Third request should now have fresh content\n      const response3 = await request.get('\u002Fapi\u002Fpublic\u002Ffeed');\n      const age3 = parseInt(response3.headers()['age'] || '0', 10);\n      expect(age3).toBeLessThan(maxAge);\n    }\n  });\n\n  test('SWR should not serve content beyond stale-while-revalidate window', async ({\n    request,\n  }) => {\n    const response = await request.get('\u002Fapi\u002Fpublic\u002Ffeed');\n    const cacheControl = response.headers()['cache-control'] || '';\n\n    if (cacheControl.includes('stale-while-revalidate')) {\n      const swrWindow = parseInt(\n        cacheControl.match(\u002Fstale-while-revalidate=(\\d+)\u002F)?.[1] || '0',\n        10\n      );\n\n      \u002F\u002F Verify the SWR window is reasonable\n      expect(swrWindow).toBeGreaterThan(0);\n      expect(swrWindow).toBeLessThanOrEqual(86400); \u002F\u002F Max 1 day\n    }\n  });\n});\n```\n\n## Cache Key Collision Detection\n\nCache key collisions happen when different content is cached under the same key, causing one user to see another user's data.\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ntest.describe('Cache Key Collision Detection', () => {\n  test('authenticated endpoints should not share cached responses', async ({ request }) => {\n    \u002F\u002F Request as User A\n    const responseA = await request.get('\u002Fapi\u002Fdashboard', {\n      headers: { Authorization: 'Bearer token-user-a' },\n    });\n    const dataA = await responseA.json();\n\n    \u002F\u002F Request as User B\n    const responseB = await request.get('\u002Fapi\u002Fdashboard', {\n      headers: { Authorization: 'Bearer token-user-b' },\n    });\n    const dataB = await responseB.json();\n\n    \u002F\u002F These should contain different user-specific data\n    expect(dataA.userId).not.toBe(dataB.userId);\n\n    \u002F\u002F Verify that User B did not receive User A's cached response\n    expect(dataB.userId).toBe('user-b');\n  });\n\n  test('query parameter variations should produce distinct cache entries', async ({\n    request,\n  }) => {\n    const response1 = await request.get('\u002Fapi\u002Fpublic\u002Fskills?page=1&sort=newest');\n    const body1 = await response1.json();\n\n    const response2 = await request.get('\u002Fapi\u002Fpublic\u002Fskills?page=2&sort=newest');\n    const body2 = await response2.json();\n\n    const response3 = await request.get('\u002Fapi\u002Fpublic\u002Fskills?page=1&sort=popular');\n    const body3 = await response3.json();\n\n    \u002F\u002F Each variation should return different content\n    expect(JSON.stringify(body1)).not.toBe(JSON.stringify(body2));\n    expect(JSON.stringify(body1)).not.toBe(JSON.stringify(body3));\n  });\n\n  test('locale-specific responses should not collide', async ({ request }) => {\n    const enResponse = await request.get('\u002Fapi\u002Fpublic\u002Fcontent', {\n      headers: { 'Accept-Language': 'en-US' },\n    });\n    const enBody = await enResponse.json();\n\n    const deResponse = await request.get('\u002Fapi\u002Fpublic\u002Fcontent', {\n      headers: { 'Accept-Language': 'de-DE' },\n    });\n    const deBody = await deResponse.json();\n\n    \u002F\u002F Content should differ by locale\n    expect(enBody.locale).not.toBe(deBody.locale);\n  });\n});\n```\n\n## Post-Deployment Cache Busting Verification\n\nDeployments are the most common trigger for stale cache issues. Old JavaScript bundles may reference old API contracts, causing runtime errors.\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ntest.describe('Post-Deployment Cache Busting', () => {\n  test('JavaScript bundles should have content-hashed filenames', async ({ page }) => {\n    const scriptUrls: string[] = [];\n\n    page.on('response', (response) => {\n      if (response.url().endsWith('.js')) {\n        scriptUrls.push(response.url());\n      }\n    });\n\n    await page.goto('\u002F');\n    await page.waitForLoadState('networkidle');\n\n    for (const url of scriptUrls) {\n      \u002F\u002F Content-hashed filenames typically look like: main.abc123.js or main-abc123.js\n      const hasContentHash = \u002F[.-][a-f0-9]{6,}\\.js\u002F.test(url);\n      expect(\n        hasContentHash,\n        `Script ${url} does not have a content hash in filename`\n      ).toBe(true);\n    }\n  });\n\n  test('CSS files should have content-hashed filenames', async ({ page }) => {\n    const cssUrls: string[] = [];\n\n    page.on('response', (response) => {\n      const contentType = response.headers()['content-type'] || '';\n      if (contentType.includes('text\u002Fcss') || response.url().endsWith('.css')) {\n        cssUrls.push(response.url());\n      }\n    });\n\n    await page.goto('\u002F');\n    await page.waitForLoadState('networkidle');\n\n    for (const url of cssUrls) {\n      const hasContentHash = \u002F[.-][a-f0-9]{6,}\\.css\u002F.test(url);\n      expect(\n        hasContentHash,\n        `CSS file ${url} does not have a content hash in filename`\n      ).toBe(true);\n    }\n  });\n\n  test('HTML should reference current asset versions after deployment', async ({ page }) => {\n    await page.goto('\u002F');\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Get all script and link tags\n    const assetRefs = await page.evaluate(() => {\n      const scripts = Array.from(document.querySelectorAll('script[src]')).map(\n        (s) => (s as HTMLScriptElement).src\n      );\n      const links = Array.from(\n        document.querySelectorAll('link[rel=\"stylesheet\"]')\n      ).map((l) => (l as HTMLLinkElement).href);\n      return { scripts, links };\n    });\n\n    \u002F\u002F Verify all referenced assets are actually reachable\n    for (const src of [...assetRefs.scripts, ...assetRefs.links]) {\n      const response = await page.request.get(src);\n      expect(\n        response.ok(),\n        `Asset not found (possible stale HTML cache): ${src}`\n      ).toBe(true);\n    }\n  });\n\n  test('API version header should match deployed version', async ({ request }) => {\n    const response = await request.get('\u002Fapi\u002Fhealth');\n    const apiVersion = response.headers()['x-api-version'];\n    const deployId = response.headers()['x-deployment-id'];\n\n    expect(apiVersion).toBeDefined();\n\n    \u002F\u002F If a deployment ID is available, verify it matches expectations\n    if (deployId && process.env.EXPECTED_DEPLOYMENT_ID) {\n      expect(deployId).toBe(process.env.EXPECTED_DEPLOYMENT_ID);\n    }\n  });\n});\n```\n\n## Browser Storage Cache Testing\n\nApplications often cache data in localStorage, sessionStorage, or IndexedDB. Stale data in these stores can cause subtle bugs.\n\n```typescript\nimport { test, expect } from '@playwright\u002Ftest';\n\ntest.describe('Browser Storage Cache Testing', () => {\n  test('localStorage cache should be invalidated on data mutation', async ({ page }) => {\n    await page.goto('\u002Fdashboard');\n    await page.waitForLoadState('networkidle');\n\n    \u002F\u002F Check what is cached in localStorage\n    const cachedData = await page.evaluate(() => {\n      const cache: Record\u003Cstring, string> = {};\n      for (let i = 0; i \u003C localStorage.length; i++) {\n        const key = localStorage.key(i)!;\n        if (key.startsWith('cache:') || key.startsWith('data:')) {\n          cache[key] = localStorage.getItem(key)!;\n        }\n      }\n      return cache;\n    });\n\n    \u002F\u002F Perform a mutation\n    await page.locator('[data-testid=\"update-profile\"]').click();\n    await page.fill('[data-testid=\"name-input\"]', 'Updated Name');\n    await page.locator('[data-testid=\"save-button\"]').click();\n    await page.waitForResponse('**\u002Fapi\u002Fprofile');\n\n    \u002F\u002F Verify the cached data was invalidated or updated\n    const updatedCache = await page.evaluate(() => {\n      const cache: Record\u003Cstring, string> = {};\n      for (let i = 0; i \u003C localStorage.length; i++) {\n        const key = localStorage.key(i)!;\n        if (key.startsWith('cache:') || key.startsWith('data:')) {\n          cache[key] = localStorage.getItem(key)!;\n        }\n      }\n      return cache;\n    });\n\n    \u002F\u002F Cache entries related to profile should be updated or removed\n    for (const [key, value] of Object.entries(cachedData)) {\n      if (key.includes('profile') || key.includes('user')) {\n        const newValue = updatedCache[key];\n        expect(\n          newValue !== value || newValue === undefined,\n          `localStorage key \"${key}\" was not invalidated after mutation`\n        ).toBe(true);\n      }\n    }\n  });\n\n  test('cached data should have TTL and not persist forever', async ({ page }) => {\n    await page.goto('\u002Fdashboard');\n    await page.waitForLoadState('networkidle');\n\n    const cacheEntries = await page.evaluate(() => {\n      const entries: { key: string; hasTimestamp: boolean; age: number | null }[] = [];\n      for (let i = 0; i \u003C localStorage.length; i++) {\n        const key = localStorage.key(i)!;\n        const value = localStorage.getItem(key)!;\n\n        let hasTimestamp = false;\n        let age: number | null = null;\n\n        try {\n          const parsed = JSON.parse(value);\n          if (parsed.timestamp || parsed.cachedAt || parsed.expiresAt) {\n            hasTimestamp = true;\n            const ts = parsed.timestamp || parsed.cachedAt;\n            if (ts) {\n              age = Date.now() - new Date(ts).getTime();\n            }\n          }\n        } catch {\n          \u002F\u002F Not JSON, ignore\n        }\n\n        if (key.startsWith('cache:')) {\n          entries.push({ key, hasTimestamp, age });\n        }\n      }\n      return entries;\n    });\n\n    for (const entry of cacheEntries) {\n      expect(\n        entry.hasTimestamp,\n        `Cache entry \"${entry.key}\" has no timestamp -- cannot determine staleness`\n      ).toBe(true);\n\n      if (entry.age !== null) {\n        \u002F\u002F Cache entries older than 24 hours are suspicious\n        const maxAge = 24 * 60 * 60 * 1000; \u002F\u002F 24 hours in ms\n        expect(\n          entry.age,\n          `Cache entry \"${entry.key}\" is ${Math.round(entry.age \u002F 3600000)}h old`\n        ).toBeLessThan(maxAge);\n      }\n    }\n  });\n});\n```\n\n## Configuration\n\n### Playwright Configuration for Cache Testing\n\n```typescript\n\u002F\u002F playwright.config.ts\nimport { defineConfig, devices } from '@playwright\u002Ftest';\n\nexport default defineConfig({\n  testDir: '.\u002Ftests\u002Fcache',\n  fullyParallel: false, \u002F\u002F Cache tests may interfere with each other\n  retries: 1,\n  reporter: [\n    ['html', { open: 'never' }],\n    ['json', { outputFile: 'cache-test-results.json' }],\n  ],\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: 'cache-headers',\n      testMatch: '**\u002Fheaders\u002F**',\n      use: {\n        ...devices['Desktop Chrome'],\n        \u002F\u002F Disable browser cache for header tests\n        bypassCSP: true,\n      },\n    },\n    {\n      name: 'cdn-cache',\n      testMatch: '**\u002Fcdn\u002F**',\n      use: {\n        ...devices['Desktop Chrome'],\n      },\n    },\n    {\n      name: 'service-worker',\n      testMatch: '**\u002Fservice-worker\u002F**',\n      use: {\n        ...devices['Desktop Chrome'],\n        serviceWorkers: 'allow',\n      },\n    },\n    {\n      name: 'browser-cache',\n      testMatch: '**\u002Fbrowser\u002F**',\n      use: {\n        ...devices['Desktop Chrome'],\n      },\n    },\n  ],\n});\n```\n\n## Best Practices\n\n1. **Always validate Cache-Control headers on every response** -- Do not rely on server configuration alone. Add automated tests that verify every response type has the correct caching headers.\n\n2. **Use content-hashed filenames for all static assets** -- Content hashing (e.g., `main.abc123.js`) ensures that new deployments serve new files while old cached files remain valid for users who have not refreshed.\n\n3. **Set `no-store` on authenticated API responses** -- User-specific data must never be cached by shared caches (CDN, proxy). Use `Cache-Control: no-store` for any response that contains user-specific content.\n\n4. **Include `Vary` headers for content negotiation** -- When responses vary by `Accept-Language`, `Accept`, or `Authorization`, the `Vary` header must declare these. Missing `Vary` headers cause cache key collisions.\n\n5. **Test cache behavior after every deployment** -- Run a post-deployment smoke test that verifies cached assets are accessible, HTML references current asset versions, and API responses are fresh.\n\n6. **Implement cache versioning in service workers** -- Service worker caches must be versioned. On each deployment, the new service worker should create new cache entries and delete old versioned caches.\n\n7. **Use `s-maxage` for CDN caching separate from browser caching** -- `s-maxage` controls CDN cache duration independently from `max-age`. This allows short browser cache times with longer CDN cache times.\n\n8. **Add cache TTL to all application-level cache entries** -- Every entry in localStorage, Redis, or in-memory caches must have an explicit expiration time. Cache entries without TTL persist forever and become stale silently.\n\n9. **Monitor cache hit rates in production** -- Low cache hit rates indicate misconfigured caching. High hit rates with user complaints indicate stale cache serving. Track both metrics.\n\n10. **Test the `no-cache` vs `no-store` distinction** -- `no-cache` means \"revalidate before use\" (still caches, but checks freshness). `no-store` means \"never cache at all\". Using the wrong one causes either stale content or unnecessary requests.\n\n11. **Purge CDN cache as part of the deployment pipeline** -- Automate CDN cache purging in your CI\u002FCD pipeline. Manual purging is error-prone and delays fresh content delivery.\n\n12. **Test with multiple browsers** -- Browser caching implementations differ. Chrome, Firefox, and Safari handle `Cache-Control` directives slightly differently, especially around `stale-while-revalidate` and service worker interactions.\n\n## Anti-Patterns to Avoid\n\n1. **Using `Cache-Control: no-cache` when you mean `no-store`** -- `no-cache` still caches the response; it just requires revalidation. For sensitive data, always use `no-store` to prevent any caching.\n\n2. **Relying on CDN purge without verification** -- CDN purge APIs are eventually consistent. A purge request does not guarantee instant cache invalidation across all edge locations. Always verify with a follow-up request.\n\n3. **Caching responses without `Vary` headers** -- If your endpoint returns different content based on request headers (Accept-Language, Authorization), missing `Vary` headers will cause the CDN to serve the wrong cached response to the wrong user.\n\n4. **Setting long `max-age` on HTML documents** -- HTML pages are the entry point for loading all other assets. A long `max-age` on HTML means users will not receive updated asset references until the HTML cache expires. Use `no-cache` or short `max-age` for HTML.\n\n5. **Storing sensitive data in browser cache without encryption** -- Browser disk cache stores response bodies in plaintext. Sensitive data cached to disk can be read by other applications or users on shared computers.\n\n6. **Ignoring service worker cache during testing** -- Service workers operate independently of the browser's HTTP cache. A test that clears the browser cache but ignores the service worker cache will still see stale content.\n\n7. **Using timestamps as cache busters in query strings** -- Appending `?t=1234567890` to URLs defeats caching entirely and wastes CDN bandwidth. Use content-hashed filenames instead, which only change when content actually changes.\n\n## Debugging Tips\n\n1. **Use Chrome DevTools Network panel with \"Disable cache\" unchecked** -- The \"Disable cache\" checkbox in DevTools prevents testing real cache behavior. Turn it off to see actual cache hits and misses in the Size column.\n\n2. **Check the `Age` header to determine how long content has been cached** -- The `Age` header (in seconds) tells you how long the response has been in a shared cache. A high `Age` value on content that should be fresh indicates a stale cache problem.\n\n3. **Use `curl -I` to inspect response headers without browser interference** -- Browsers add their own caching behavior. Use `curl -I \u003Curl>` to see the raw response headers from the server without any browser-side caching modifications.\n\n4. **Verify service worker state in Application tab** -- Chrome DevTools Application tab shows registered service workers, their status (active, waiting, installing), and the contents of each cache storage. This is essential for debugging service worker caching issues.\n\n5. **Check for cache poisoning with different request variations** -- Test the same URL with different `Accept`, `Accept-Language`, and `Authorization` headers. If you receive the same cached response regardless of header variations, the cache is not respecting `Vary`.\n\n6. **Monitor the `X-Cache` header across multiple requests** -- Make the same request 3-4 times in sequence. The first should show `MISS`, and subsequent requests should show `HIT`. If all show `MISS`, caching is not working. If all show `HIT` after content changes, the cache is stale.\n\n7. **Use Lighthouse to audit cache policy** -- Lighthouse's \"Serve static assets with an efficient cache policy\" audit identifies resources with short or missing cache lifetimes. Run this after deployments to verify caching is configured correctly.\n\n8. **Compare `ETag` values before and after data changes** -- If the `ETag` does not change after you modify data, the server is generating ETags incorrectly (possibly from a stale cache layer). Track ETags across mutations to verify they update.\n\n9. **Test with `Cache-Control: no-cache` request header** -- Sending `Cache-Control: no-cache` in your request forces the server (and most CDNs) to bypass cache and return a fresh response. Compare this fresh response to the normally cached response to verify they match.\n\n10. **Check for `Set-Cookie` headers on cached responses** -- Responses with `Set-Cookie` headers should never be cached by shared caches. If you see `Set-Cookie` alongside `Cache-Control: public`, this is a serious bug that can leak session cookies between users.\n",{"name":5,"tags":24,"agents":33,"author":46,"domains":47,"license":15,"version":50,"languages":51,"frameworks":54,"description":7,"testingTypes":56},[25,26,27,28,29,30,31,32],"cache-testing","stale-cache","cdn","cache-invalidation","cache-busting","etag","cache-headers","browser-cache",[34,35,36,37,38,39,40,41,42,43,44,45],"claude-code","cursor","github-copilot","windsurf","codex","aider","continue","cline","zed","bolt","gemini-cli","amp","Pramod",[48,49],"web","api","1.0.0",[52,53],"typescript","javascript",[55],"playwright",[57,58],"integration","e2e","main","eac438ea9216a7cb8a570cab803eb01eeafc6793","skills\u002Fqa\u002Fstale-cache-finder","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":68,"prompt":78,"zipAvailable":79},[69,72,75],{"tool":70,"command":71},"npx","npx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"Stale Cache Finder\"",{"tool":73,"command":74},"bunx","bunx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"Stale Cache Finder\"",{"tool":76,"command":77},"pnpm","pnpm dlx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"Stale Cache Finder\"","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fstale-cache-finder\u002FSKILL.md",true,[],[82,90,97,104,111,118],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"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":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"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":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"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":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"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":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":117,"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":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":124,"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",[],[]]