[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7D8KZ6W3HNJD92REREF445S":3,"skill-same:01M7D8KZ6W3HNJD92REREF445S":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},"01M7D8KZ6W3HNJD92REREF445S","Flaky Test Quarantine",null,"Detect, quarantine, and systematically fix flaky tests with automated retry analysis, root cause categorization, and CI pipeline integration for test reliability","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\u002Fflaky-test-quarantine\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: Flaky Test Quarantine\ndescription: Detect, quarantine, and systematically fix flaky tests with automated retry analysis, root cause categorization, and CI pipeline integration for test reliability\nversion: 1.0.0\nauthor: Pramod\nlicense: MIT\ntags: [flaky-tests, test-reliability, quarantine, test-retry, ci-stability, test-maintenance, non-deterministic]\ntestingTypes: [code-quality, e2e]\nframeworks: [playwright, jest, vitest]\nlanguages: [typescript, javascript]\ndomains: [devops]\nagents: [claude-code, cursor, github-copilot, windsurf, codex, aider, continue, cline, zed, bolt, gemini-cli, amp]\n---\n\n# Flaky Test Quarantine\n\nFlaky tests are tests that produce different outcomes (pass or fail) when run against the same code under the same conditions. They erode confidence in the test suite, train developers to ignore failures, and slow down CI pipelines with unnecessary retries. A single flaky test in a suite of 500 can cause the entire pipeline to require re-runs, wasting developer time and compute resources. This skill provides a systematic approach to detecting, quarantining, categorizing, and fixing flaky tests while maintaining CI pipeline stability.\n\n## Core Principles\n\n1. **Detection Before Quarantine**: A test must be proven flaky through repeated execution before it is quarantined. A single failure does not make a test flaky; it might indicate a real bug. Multi-run analysis with statistical tracking separates genuine flakiness from legitimate failures.\n\n2. **Quarantine Is Not Deletion**: Quarantined tests must remain in the codebase and continue running in a separate pipeline. Quarantine is a temporary holding pattern that prevents flaky tests from blocking the main pipeline while preserving the test and tracking its behavior.\n\n3. **Root Cause Categorization Drives Fixes**: Different types of flakiness require different fixing strategies. Timing issues need explicit waits, state leakage needs proper cleanup, external dependencies need mocking, and race conditions need synchronization. Categorizing the root cause directs the fix.\n\n4. **Flakiness Is Measurable**: Track the flakiness rate (failures per total runs) for every test over time. This metric determines quarantine decisions, fix prioritization, and verifies that fixes actually resolved the issue.\n\n5. **Zero-Tolerance Pipeline**: The main CI pipeline must be green to merge. Allowing occasional failures or manual re-runs normalizes flakiness and makes it impossible to distinguish real failures from known flaky ones.\n\n6. **Fix the Root Cause, Not the Symptom**: Adding retries or increasing timeouts masks flakiness without fixing it. These approaches hide real issues and increase overall test execution time. Address the underlying non-determinism.\n\n7. **Isolation Verification**: After fixing a flaky test, verify the fix by running the test in isolation and in the full suite multiple times. Some flakiness only manifests under specific ordering or parallel execution conditions.\n\n## Project Structure\n\n```\nproject-root\u002F\n├── tests\u002F\n│   ├── e2e\u002F\n│   │   ├── checkout.spec.ts\n│   │   ├── search.spec.ts\n│   │   └── user-profile.spec.ts\n│   ├── unit\u002F\n│   │   ├── payment.test.ts\n│   │   └── cart.test.ts\n│   └── quarantine\u002F\n│       ├── README.md\n│       └── quarantine-registry.json\n├── scripts\u002F\n│   ├── detect-flaky.ts\n│   ├── quarantine-manager.ts\n│   ├── flaky-report.ts\n│   └── verify-fix.ts\n├── .github\u002F\n│   └── workflows\u002F\n│       ├── main-ci.yml\n│       ├── quarantine-ci.yml\n│       └── flaky-detection.yml\n├── config\u002F\n│   ├── playwright.config.ts\n│   ├── jest.config.ts\n│   └── vitest.config.ts\n└── flaky-test.config.ts\n```\n\n## Flaky Test Detection\n\n### Multi-Run Detection Script\n\nThe most reliable way to detect flaky tests is to run the test suite multiple times and compare results. A test that fails even once across multiple runs of identical code is flaky.\n\n```typescript\n\u002F\u002F scripts\u002Fdetect-flaky.ts\nimport { execSync } from 'child_process';\nimport * as fs from 'fs';\n\ninterface TestResult {\n  testName: string;\n  file: string;\n  runs: number;\n  passes: number;\n  failures: number;\n  flakinessRate: number;\n  failureMessages: string[];\n}\n\ninterface DetectionConfig {\n  runs: number;\n  testCommand: string;\n  resultPattern: string;\n  flakinessThreshold: number;\n}\n\nconst config: DetectionConfig = {\n  runs: 10,\n  testCommand: 'npx playwright test --reporter=json',\n  resultPattern: 'test-results\u002Fresults.json',\n  flakinessThreshold: 0.1, \u002F\u002F 10% failure rate = flaky\n};\n\nasync function detectFlakyTests(): Promise\u003CTestResult[]> {\n  const resultsByTest = new Map\u003Cstring, TestResult>();\n\n  console.log(`Running test suite ${config.runs} times to detect flaky tests...`);\n\n  for (let run = 1; run \u003C= config.runs; run++) {\n    console.log(`\\n--- Run ${run}\u002F${config.runs} ---`);\n\n    try {\n      execSync(config.testCommand, {\n        stdio: 'pipe',\n        env: {\n          ...process.env,\n          PLAYWRIGHT_JSON_OUTPUT_NAME: `test-results\u002Frun-${run}.json`,\n        },\n      });\n    } catch {\n      \u002F\u002F Test failures are expected; we continue regardless\n    }\n\n    const resultsFile = `test-results\u002Frun-${run}.json`;\n    if (!fs.existsSync(resultsFile)) continue;\n\n    const results = JSON.parse(fs.readFileSync(resultsFile, 'utf-8'));\n\n    for (const suite of results.suites || []) {\n      for (const spec of suite.specs || []) {\n        const key = `${suite.file}::${spec.title}`;\n\n        if (!resultsByTest.has(key)) {\n          resultsByTest.set(key, {\n            testName: spec.title,\n            file: suite.file,\n            runs: 0,\n            passes: 0,\n            failures: 0,\n            flakinessRate: 0,\n            failureMessages: [],\n          });\n        }\n\n        const entry = resultsByTest.get(key)!;\n        entry.runs++;\n\n        const passed = spec.tests.every((t: any) => t.status === 'passed');\n        if (passed) {\n          entry.passes++;\n        } else {\n          entry.failures++;\n          const failMsg = spec.tests\n            .filter((t: any) => t.status === 'failed')\n            .map((t: any) => t.results?.[0]?.error?.message || 'Unknown error')\n            .join('; ');\n          entry.failureMessages.push(failMsg);\n        }\n      }\n    }\n  }\n\n  \u002F\u002F Calculate flakiness rates\n  const allResults: TestResult[] = [];\n  for (const result of resultsByTest.values()) {\n    result.flakinessRate = result.failures \u002F result.runs;\n    allResults.push(result);\n  }\n\n  \u002F\u002F Filter to only flaky tests (failed some but not all runs)\n  const flakyTests = allResults.filter(\n    (r) => r.flakinessRate > 0 && r.flakinessRate \u003C 1 && r.flakinessRate >= config.flakinessThreshold\n  );\n\n  console.log(`\\nDetected ${flakyTests.length} flaky tests out of ${allResults.length} total tests`);\n\n  \u002F\u002F Write report\n  fs.writeFileSync(\n    'test-results\u002Fflaky-detection-report.json',\n    JSON.stringify(\n      {\n        timestamp: new Date().toISOString(),\n        totalRuns: config.runs,\n        totalTests: allResults.length,\n        flakyTests: flakyTests.sort((a, b) => b.flakinessRate - a.flakinessRate),\n      },\n      null,\n      2\n    )\n  );\n\n  return flakyTests;\n}\n\ndetectFlakyTests().catch(console.error);\n```\n\n### Automated Flaky Detection in CI\n\n```yaml\n# .github\u002Fworkflows\u002Fflaky-detection.yml\nname: Flaky Test Detection\non:\n  schedule:\n    - cron: '0 2 * * 0'   # Run weekly at 2 AM Sunday\n  workflow_dispatch:        # Manual trigger\n\njobs:\n  detect-flaky:\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        run: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-node@v4\n        with:\n          node-version: 20\n      - run: npm ci\n      - run: npx playwright install --with-deps\n      - name: Run test suite (attempt ${{ matrix.run }})\n        run: npx playwright test --reporter=json\n        continue-on-error: true\n        env:\n          PLAYWRIGHT_JSON_OUTPUT_NAME: results-${{ matrix.run }}.json\n      - uses: actions\u002Fupload-artifact@v4\n        with:\n          name: results-${{ matrix.run }}\n          path: results-${{ matrix.run }}.json\n\n  analyze:\n    needs: detect-flaky\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fdownload-artifact@v4\n        with:\n          path: all-results\n      - name: Analyze flakiness\n        run: npx ts-node scripts\u002Fanalyze-flaky-results.ts all-results\u002F\n      - name: Create issue if flaky tests found\n        if: steps.analyze.outputs.flaky_count > 0\n        uses: actions\u002Fgithub-script@v7\n        with:\n          script: |\n            const report = require('.\u002Fflaky-report.json');\n            await github.rest.issues.create({\n              owner: context.repo.owner,\n              repo: context.repo.repo,\n              title: `Flaky Tests Detected: ${report.count} tests`,\n              body: report.markdown,\n              labels: ['flaky-test', 'test-reliability'],\n            });\n```\n\n## Automatic Quarantine Tagging\n\n### Quarantine Registry\n\n```typescript\n\u002F\u002F tests\u002Fquarantine\u002Fquarantine-registry.json\n{\n  \"version\": 1,\n  \"lastUpdated\": \"2024-06-15T10:00:00.000Z\",\n  \"quarantinedTests\": [\n    {\n      \"id\": \"q-001\",\n      \"testName\": \"should complete checkout with PayPal\",\n      \"file\": \"tests\u002Fe2e\u002Fcheckout.spec.ts\",\n      \"quarantinedAt\": \"2024-06-10T14:30:00.000Z\",\n      \"quarantinedBy\": \"ci-bot\",\n      \"reason\": \"Flakiness rate 35% over last 50 runs\",\n      \"rootCause\": \"timing\",\n      \"rootCauseDetail\": \"PayPal iframe loads inconsistently, waitForSelector timeout\",\n      \"flakinessRate\": 0.35,\n      \"priority\": \"high\",\n      \"assignee\": \"team-payments\",\n      \"jiraTicket\": \"QA-1234\",\n      \"status\": \"investigating\"\n    },\n    {\n      \"id\": \"q-002\",\n      \"testName\": \"should display search results with filters\",\n      \"file\": \"tests\u002Fe2e\u002Fsearch.spec.ts\",\n      \"quarantinedAt\": \"2024-06-12T09:00:00.000Z\",\n      \"quarantinedBy\": \"developer-jane\",\n      \"reason\": \"Intermittent failure on CI (passes locally)\",\n      \"rootCause\": \"state-leakage\",\n      \"rootCauseDetail\": \"Previous test leaves search index in dirty state\",\n      \"flakinessRate\": 0.20,\n      \"priority\": \"medium\",\n      \"assignee\": \"team-search\",\n      \"jiraTicket\": \"QA-1235\",\n      \"status\": \"fix-in-progress\"\n    }\n  ]\n}\n```\n\n### Quarantine Manager\n\n```typescript\n\u002F\u002F scripts\u002Fquarantine-manager.ts\nimport * as fs from 'fs';\nimport * as path from 'path';\n\ninterface QuarantineEntry {\n  id: string;\n  testName: string;\n  file: string;\n  quarantinedAt: string;\n  quarantinedBy: string;\n  reason: string;\n  rootCause: RootCause;\n  rootCauseDetail: string;\n  flakinessRate: number;\n  priority: 'critical' | 'high' | 'medium' | 'low';\n  assignee: string;\n  jiraTicket?: string;\n  status: 'new' | 'investigating' | 'fix-in-progress' | 'fix-ready' | 'verified';\n}\n\ntype RootCause =\n  | 'timing'\n  | 'state-leakage'\n  | 'external-dependency'\n  | 'race-condition'\n  | 'resource-contention'\n  | 'environment-specific'\n  | 'test-data'\n  | 'unknown';\n\nconst REGISTRY_PATH = path.resolve(__dirname, '..\u002Ftests\u002Fquarantine\u002Fquarantine-registry.json');\n\nfunction loadRegistry(): { version: number; quarantinedTests: QuarantineEntry[] } {\n  if (!fs.existsSync(REGISTRY_PATH)) {\n    return { version: 1, quarantinedTests: [] };\n  }\n  return JSON.parse(fs.readFileSync(REGISTRY_PATH, 'utf-8'));\n}\n\nfunction saveRegistry(registry: { version: number; quarantinedTests: QuarantineEntry[] }): void {\n  registry.lastUpdated = new Date().toISOString();\n  fs.writeFileSync(REGISTRY_PATH, JSON.stringify(registry, null, 2));\n}\n\nexport function quarantineTest(entry: Omit\u003CQuarantineEntry, 'id' | 'quarantinedAt'>): void {\n  const registry = loadRegistry();\n  const id = `q-${String(registry.quarantinedTests.length + 1).padStart(3, '0')}`;\n\n  registry.quarantinedTests.push({\n    ...entry,\n    id,\n    quarantinedAt: new Date().toISOString(),\n  });\n\n  saveRegistry(registry);\n  console.log(`Quarantined test: ${entry.testName} (${id})`);\n}\n\nexport function unquarantineTest(id: string): void {\n  const registry = loadRegistry();\n  const index = registry.quarantinedTests.findIndex((t) => t.id === id);\n\n  if (index === -1) {\n    console.error(`Test ${id} not found in quarantine`);\n    return;\n  }\n\n  const removed = registry.quarantinedTests.splice(index, 1)[0];\n  saveRegistry(registry);\n  console.log(`Unquarantined test: ${removed.testName} (${id})`);\n}\n\nexport function getQuarantinedTestNames(): Set\u003Cstring> {\n  const registry = loadRegistry();\n  return new Set(registry.quarantinedTests.map((t) => t.testName));\n}\n```\n\n### Playwright Quarantine Integration\n\n```typescript\n\u002F\u002F config\u002Fplaywright.config.ts\nimport { defineConfig, devices } from '@playwright\u002Ftest';\nimport * as fs from 'fs';\n\n\u002F\u002F Load quarantine registry\nconst quarantineRegistry = JSON.parse(\n  fs.readFileSync('tests\u002Fquarantine\u002Fquarantine-registry.json', 'utf-8')\n);\nconst quarantinedFiles = new Set(\n  quarantineRegistry.quarantinedTests.map((t: any) => t.file)\n);\n\nconst isQuarantineRun = process.env.QUARANTINE_RUN === 'true';\n\nexport default defineConfig({\n  testDir: '.\u002Ftests\u002Fe2e',\n\n  \u002F\u002F In main pipeline: exclude quarantined test files\n  \u002F\u002F In quarantine pipeline: only run quarantined test files\n  testMatch: isQuarantineRun\n    ? [...quarantinedFiles].map((f) => f.replace('tests\u002Fe2e\u002F', ''))\n    : undefined,\n  testIgnore: isQuarantineRun\n    ? undefined\n    : [...quarantinedFiles].map((f) => f.replace('tests\u002Fe2e\u002F', '')),\n\n  retries: isQuarantineRun ? 3 : 0,   \u002F\u002F Retries only in quarantine pipeline\n  timeout: 30000,\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\n  projects: [\n    {\n      name: 'chromium',\n      use: { ...devices['Desktop Chrome'] },\n    },\n  ],\n\n  reporter: [\n    ['html', { open: 'never' }],\n    ['json', { outputFile: 'test-results\u002Fresults.json' }],\n  ],\n});\n```\n\n### Annotation-Based Quarantine with Custom Fixture\n\n```typescript\n\u002F\u002F tests\u002Fe2e\u002Ffixtures\u002Fquarantine-fixture.ts\nimport { test as base } from '@playwright\u002Ftest';\nimport * as fs from 'fs';\n\ninterface QuarantineInfo {\n  isQuarantined: boolean;\n  reason?: string;\n  jiraTicket?: string;\n}\n\nconst quarantineRegistry = JSON.parse(\n  fs.readFileSync('tests\u002Fquarantine\u002Fquarantine-registry.json', 'utf-8')\n);\n\nconst quarantinedMap = new Map(\n  quarantineRegistry.quarantinedTests.map((t: any) => [t.testName, t])\n);\n\nexport const test = base.extend\u003C{ quarantine: QuarantineInfo }>({\n  quarantine: async ({}, use, testInfo) => {\n    const entry = quarantinedMap.get(testInfo.title);\n    const isQuarantineRun = process.env.QUARANTINE_RUN === 'true';\n\n    if (entry && !isQuarantineRun) {\n      testInfo.annotations.push({\n        type: 'quarantine',\n        description: `Quarantined: ${entry.reason} (${entry.jiraTicket || 'no ticket'})`,\n      });\n      test.skip(true, `Quarantined: ${entry.reason}`);\n    }\n\n    await use({\n      isQuarantined: !!entry,\n      reason: entry?.reason,\n      jiraTicket: entry?.jiraTicket,\n    });\n  },\n});\n\nexport { expect } from '@playwright\u002Ftest';\n```\n\n### Using the Quarantine Fixture in Tests\n\n```typescript\n\u002F\u002F tests\u002Fe2e\u002Fcheckout.spec.ts\nimport { test, expect } from '.\u002Ffixtures\u002Fquarantine-fixture';\n\ntest.describe('Checkout Flow', () => {\n  test('should complete checkout with credit card', async ({ page }) => {\n    \u002F\u002F This test is stable - runs normally\n    await page.goto('\u002Fproducts\u002F1');\n    await page.click('[data-testid=\"add-to-cart\"]');\n    await page.goto('\u002Fcheckout');\n    await page.fill('[data-testid=\"card-number\"]', '4242424242424242');\n    await page.click('[data-testid=\"place-order\"]');\n    await expect(page.locator('[data-testid=\"order-confirmation\"]')).toBeVisible();\n  });\n\n  test('should complete checkout with PayPal', async ({ page, quarantine }) => {\n    \u002F\u002F This test is in the quarantine registry - will be skipped in main pipeline\n    await page.goto('\u002Fproducts\u002F1');\n    await page.click('[data-testid=\"add-to-cart\"]');\n    await page.goto('\u002Fcheckout');\n    await page.click('[data-testid=\"pay-with-paypal\"]');\n    \u002F\u002F PayPal iframe interaction...\n    await expect(page.locator('[data-testid=\"order-confirmation\"]')).toBeVisible();\n  });\n});\n```\n\n## Root Cause Categories and Fixing Strategies\n\n### Timing Issues\n\nTiming flakiness occurs when tests assume operations complete within a fixed time. The fix is to replace arbitrary timeouts with explicit condition waits.\n\n```typescript\n\u002F\u002F FLAKY: Uses fixed timeout\ntest('should show notification after save', async ({ page }) => {\n  await page.click('[data-testid=\"save-button\"]');\n  await page.waitForTimeout(2000); \u002F\u002F Arbitrary wait - FLAKY\n  const notification = page.locator('[data-testid=\"notification\"]');\n  await expect(notification).toBeVisible();\n});\n\n\u002F\u002F FIXED: Waits for specific condition\ntest('should show notification after save', async ({ page }) => {\n  await page.click('[data-testid=\"save-button\"]');\n  const notification = page.locator('[data-testid=\"notification\"]');\n  await expect(notification).toBeVisible({ timeout: 10000 }); \u002F\u002F Explicit condition wait\n});\n```\n\n### State Leakage Between Tests\n\nState leakage happens when one test modifies shared state (database, browser storage, global variables) that another test depends on.\n\n```typescript\n\u002F\u002F FLAKY: Tests share state\ntest.describe('User Settings', () => {\n  test('should enable dark mode', async ({ page }) => {\n    await page.goto('\u002Fsettings');\n    await page.click('[data-testid=\"dark-mode-toggle\"]');\n    \u002F\u002F Leaves dark mode enabled for next test\n  });\n\n  test('should show default light theme', async ({ page }) => {\n    await page.goto('\u002Fsettings');\n    \u002F\u002F FAILS if previous test ran first and enabled dark mode\n    await expect(page.locator('body')).toHaveClass(\u002Flight-theme\u002F);\n  });\n});\n\n\u002F\u002F FIXED: Each test manages its own state\ntest.describe('User Settings', () => {\n  test.beforeEach(async ({ page }) => {\n    \u002F\u002F Reset user preferences before each test\n    await page.evaluate(() => localStorage.clear());\n    await page.request.post('\u002Fapi\u002Ftest\u002Freset-user-preferences');\n  });\n\n  test('should enable dark mode', async ({ page }) => {\n    await page.goto('\u002Fsettings');\n    await page.click('[data-testid=\"dark-mode-toggle\"]');\n    await expect(page.locator('body')).toHaveClass(\u002Fdark-theme\u002F);\n  });\n\n  test('should show default light theme', async ({ page }) => {\n    await page.goto('\u002Fsettings');\n    await expect(page.locator('body')).toHaveClass(\u002Flight-theme\u002F);\n  });\n});\n```\n\n### External Dependency Flakiness\n\n```typescript\n\u002F\u002F FLAKY: Depends on external payment API availability\ntest('should process payment', async ({ page }) => {\n  await page.goto('\u002Fcheckout');\n  await page.fill('[data-testid=\"card\"]', '4242424242424242');\n  await page.click('[data-testid=\"pay\"]');\n  \u002F\u002F External payment gateway may be slow or down\n  await expect(page.locator('[data-testid=\"success\"]')).toBeVisible();\n});\n\n\u002F\u002F FIXED: Mock external dependency\ntest('should process payment', async ({ page }) => {\n  \u002F\u002F Intercept external API calls\n  await page.route('**\u002Fapi.stripe.com\u002F**', async (route) => {\n    await route.fulfill({\n      status: 200,\n      contentType: 'application\u002Fjson',\n      body: JSON.stringify({\n        id: 'pi_mock_123',\n        status: 'succeeded',\n        amount: 2999,\n      }),\n    });\n  });\n\n  await page.goto('\u002Fcheckout');\n  await page.fill('[data-testid=\"card\"]', '4242424242424242');\n  await page.click('[data-testid=\"pay\"]');\n  await expect(page.locator('[data-testid=\"success\"]')).toBeVisible();\n});\n```\n\n### Race Conditions\n\n```typescript\n\u002F\u002F FLAKY: Race condition between navigation and assertion\ntest('should load dashboard data', async ({ page }) => {\n  await page.goto('\u002Fdashboard');\n  \u002F\u002F Data might not have loaded yet\n  const count = await page.locator('[data-testid=\"item-count\"]').textContent();\n  expect(parseInt(count!)).toBeGreaterThan(0);\n});\n\n\u002F\u002F FIXED: Wait for the data to be in the expected state\ntest('should load dashboard data', async ({ page }) => {\n  await page.goto('\u002Fdashboard');\n\n  \u002F\u002F Wait for the loading state to complete\n  await page.waitForResponse((response) =>\n    response.url().includes('\u002Fapi\u002Fdashboard') && response.status() === 200\n  );\n\n  \u002F\u002F Now assert on the data\n  const countLocator = page.locator('[data-testid=\"item-count\"]');\n  await expect(countLocator).not.toHaveText('0');\n  const count = await countLocator.textContent();\n  expect(parseInt(count!)).toBeGreaterThan(0);\n});\n```\n\n## Retry with Exponential Backoff\n\n```typescript\n\u002F\u002F scripts\u002Fretry-runner.ts\nimport { execSync } from 'child_process';\n\ninterface RetryConfig {\n  maxRetries: number;\n  baseDelay: number;      \u002F\u002F milliseconds\n  maxDelay: number;       \u002F\u002F milliseconds\n  backoffMultiplier: number;\n}\n\nconst defaultConfig: RetryConfig = {\n  maxRetries: 3,\n  baseDelay: 1000,\n  maxDelay: 30000,\n  backoffMultiplier: 2,\n};\n\nexport async function runWithRetry(\n  command: string,\n  config: RetryConfig = defaultConfig\n): Promise\u003C{ success: boolean; attempts: number; lastError?: string }> {\n  let lastError = '';\n\n  for (let attempt = 1; attempt \u003C= config.maxRetries + 1; attempt++) {\n    try {\n      console.log(`Attempt ${attempt}\u002F${config.maxRetries + 1}: ${command}`);\n      execSync(command, { stdio: 'inherit' });\n      return { success: true, attempts: attempt };\n    } catch (error: any) {\n      lastError = error.message;\n      console.log(`Attempt ${attempt} failed: ${lastError}`);\n\n      if (attempt \u003C= config.maxRetries) {\n        const delay = Math.min(\n          config.baseDelay * Math.pow(config.backoffMultiplier, attempt - 1),\n          config.maxDelay\n        );\n        const jitter = delay * (0.5 + Math.random() * 0.5); \u002F\u002F Add jitter\n        console.log(`Retrying in ${Math.round(jitter)}ms...`);\n        await new Promise((resolve) => setTimeout(resolve, jitter));\n      }\n    }\n  }\n\n  return { success: false, attempts: config.maxRetries + 1, lastError };\n}\n```\n\n## Flakiness Rate Tracking\n\n```typescript\n\u002F\u002F scripts\u002Fflaky-report.ts\nimport * as fs from 'fs';\n\ninterface TestHistory {\n  testName: string;\n  file: string;\n  recentRuns: Array\u003C{\n    date: string;\n    passed: boolean;\n    duration: number;\n    ciRunId: string;\n  }>;\n  totalRuns: number;\n  totalFailures: number;\n  flakinessRate: number;\n  trend: 'improving' | 'stable' | 'degrading';\n  lastFailure: string | null;\n  averageDuration: number;\n}\n\nconst HISTORY_PATH = 'test-results\u002Fflakiness-history.json';\n\nexport function updateHistory(runResults: any[], ciRunId: string): void {\n  const history: Map\u003Cstring, TestHistory> = loadHistory();\n\n  for (const result of runResults) {\n    const key = `${result.file}::${result.testName}`;\n\n    if (!history.has(key)) {\n      history.set(key, {\n        testName: result.testName,\n        file: result.file,\n        recentRuns: [],\n        totalRuns: 0,\n        totalFailures: 0,\n        flakinessRate: 0,\n        trend: 'stable',\n        lastFailure: null,\n        averageDuration: 0,\n      });\n    }\n\n    const entry = history.get(key)!;\n    entry.recentRuns.push({\n      date: new Date().toISOString(),\n      passed: result.passed,\n      duration: result.duration,\n      ciRunId,\n    });\n\n    \u002F\u002F Keep last 100 runs\n    if (entry.recentRuns.length > 100) {\n      entry.recentRuns = entry.recentRuns.slice(-100);\n    }\n\n    entry.totalRuns++;\n    if (!result.passed) {\n      entry.totalFailures++;\n      entry.lastFailure = new Date().toISOString();\n    }\n\n    \u002F\u002F Calculate flakiness rate over recent runs\n    const recentFailures = entry.recentRuns.filter((r) => !r.passed).length;\n    entry.flakinessRate = recentFailures \u002F entry.recentRuns.length;\n\n    \u002F\u002F Calculate trend (compare last 25 runs with previous 25)\n    if (entry.recentRuns.length >= 50) {\n      const recent25 = entry.recentRuns.slice(-25);\n      const previous25 = entry.recentRuns.slice(-50, -25);\n      const recentRate = recent25.filter((r) => !r.passed).length \u002F 25;\n      const previousRate = previous25.filter((r) => !r.passed).length \u002F 25;\n\n      if (recentRate \u003C previousRate - 0.05) entry.trend = 'improving';\n      else if (recentRate > previousRate + 0.05) entry.trend = 'degrading';\n      else entry.trend = 'stable';\n    }\n\n    entry.averageDuration =\n      entry.recentRuns.reduce((sum, r) => sum + r.duration, 0) \u002F entry.recentRuns.length;\n  }\n\n  saveHistory(history);\n  generateReport(history);\n}\n\nfunction generateReport(history: Map\u003Cstring, TestHistory>): void {\n  const flakyTests = [...history.values()]\n    .filter((t) => t.flakinessRate > 0 && t.flakinessRate \u003C 1)\n    .sort((a, b) => b.flakinessRate - a.flakinessRate);\n\n  const report = {\n    generatedAt: new Date().toISOString(),\n    summary: {\n      totalTests: history.size,\n      flakyTests: flakyTests.length,\n      flakinessPercentage: ((flakyTests.length \u002F history.size) * 100).toFixed(1),\n      criticalFlaky: flakyTests.filter((t) => t.flakinessRate > 0.3).length,\n      degradingTests: flakyTests.filter((t) => t.trend === 'degrading').length,\n    },\n    tests: flakyTests.map((t) => ({\n      testName: t.testName,\n      file: t.file,\n      flakinessRate: `${(t.flakinessRate * 100).toFixed(1)}%`,\n      trend: t.trend,\n      totalRuns: t.totalRuns,\n      lastFailure: t.lastFailure,\n      averageDuration: `${Math.round(t.averageDuration)}ms`,\n    })),\n  };\n\n  fs.writeFileSync('test-results\u002Fflakiness-report.json', JSON.stringify(report, null, 2));\n  console.log(`Flakiness report: ${flakyTests.length} flaky tests detected`);\n}\n\nfunction loadHistory(): Map\u003Cstring, TestHistory> {\n  if (!fs.existsSync(HISTORY_PATH)) return new Map();\n  const data = JSON.parse(fs.readFileSync(HISTORY_PATH, 'utf-8'));\n  return new Map(Object.entries(data));\n}\n\nfunction saveHistory(history: Map\u003Cstring, TestHistory>): void {\n  fs.writeFileSync(HISTORY_PATH, JSON.stringify(Object.fromEntries(history), null, 2));\n}\n```\n\n## CI Integration\n\n### Main Pipeline (Excludes Quarantined Tests)\n\n```yaml\n# .github\u002Fworkflows\u002Fmain-ci.yml\nname: Main CI Pipeline\non:\n  push:\n    branches: [main]\n  pull_request:\n\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-node@v4\n        with:\n          node-version: 20\n      - run: npm ci\n      - run: npx playwright install --with-deps\n\n      # Run tests excluding quarantined tests (zero retries)\n      - name: Run stable tests\n        run: npx playwright test --retries=0\n        env:\n          QUARANTINE_RUN: 'false'\n\n      - name: Upload results\n        if: always()\n        uses: actions\u002Fupload-artifact@v4\n        with:\n          name: test-results\n          path: test-results\u002F\n```\n\n### Quarantine Pipeline (Runs Only Quarantined Tests)\n\n```yaml\n# .github\u002Fworkflows\u002Fquarantine-ci.yml\nname: Quarantine Pipeline\non:\n  push:\n    branches: [main]\n  schedule:\n    - cron: '0 *\u002F4 * * *'   # Every 4 hours\n\njobs:\n  quarantine-tests:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-node@v4\n        with:\n          node-version: 20\n      - run: npm ci\n      - run: npx playwright install --with-deps\n\n      # Run only quarantined tests with retries\n      - name: Run quarantined tests\n        run: npx playwright test --retries=3\n        continue-on-error: true  # Don't fail the pipeline\n        env:\n          QUARANTINE_RUN: 'true'\n\n      - name: Update flakiness tracking\n        run: npx ts-node scripts\u002Fflaky-report.ts\n        env:\n          CI_RUN_ID: ${{ github.run_id }}\n\n      - name: Check for recovered tests\n        run: |\n          npx ts-node scripts\u002Fcheck-recovered.ts\n        # Outputs tests that passed all retries, candidates for unquarantine\n```\n\n## Test Isolation Verification\n\n```typescript\n\u002F\u002F scripts\u002Fverify-fix.ts\nimport { execSync } from 'child_process';\n\ninterface VerificationResult {\n  testName: string;\n  isolatedRuns: { passed: number; failed: number };\n  suiteRuns: { passed: number; failed: number };\n  verdict: 'fixed' | 'still-flaky' | 'order-dependent';\n}\n\nasync function verifyFix(testFile: string, testName: string): Promise\u003CVerificationResult> {\n  const RUNS = 20;\n  const result: VerificationResult = {\n    testName,\n    isolatedRuns: { passed: 0, failed: 0 },\n    suiteRuns: { passed: 0, failed: 0 },\n    verdict: 'still-flaky',\n  };\n\n  console.log(`Verifying fix for \"${testName}\" with ${RUNS} runs...`);\n\n  \u002F\u002F Phase 1: Run the test in isolation\n  console.log('\\nPhase 1: Isolated runs');\n  for (let i = 0; i \u003C RUNS; i++) {\n    try {\n      execSync(\n        `npx playwright test \"${testFile}\" --grep \"${testName}\" --retries=0`,\n        { stdio: 'pipe' }\n      );\n      result.isolatedRuns.passed++;\n    } catch {\n      result.isolatedRuns.failed++;\n    }\n  }\n  console.log(`  Isolated: ${result.isolatedRuns.passed}\u002F${RUNS} passed`);\n\n  \u002F\u002F Phase 2: Run the test within the full suite\n  console.log('\\nPhase 2: Full suite runs');\n  for (let i = 0; i \u003C RUNS; i++) {\n    try {\n      execSync(`npx playwright test --retries=0`, { stdio: 'pipe' });\n      result.suiteRuns.passed++;\n    } catch {\n      result.suiteRuns.failed++;\n    }\n  }\n  console.log(`  Suite: ${result.suiteRuns.passed}\u002F${RUNS} passed`);\n\n  \u002F\u002F Determine verdict\n  if (result.isolatedRuns.failed === 0 && result.suiteRuns.failed === 0) {\n    result.verdict = 'fixed';\n  } else if (result.isolatedRuns.failed === 0 && result.suiteRuns.failed > 0) {\n    result.verdict = 'order-dependent';\n  } else {\n    result.verdict = 'still-flaky';\n  }\n\n  console.log(`\\nVerdict: ${result.verdict}`);\n  return result;\n}\n```\n\n## Configuration\n\n### Jest Quarantine Configuration\n\n```typescript\n\u002F\u002F config\u002Fjest.config.ts\nimport type { Config } from 'jest';\nimport * as fs from 'fs';\n\nconst quarantineRegistry = JSON.parse(\n  fs.readFileSync('tests\u002Fquarantine\u002Fquarantine-registry.json', 'utf-8')\n);\nconst quarantinedPatterns = quarantineRegistry.quarantinedTests.map(\n  (t: any) => t.file\n);\n\nconst isQuarantineRun = process.env.QUARANTINE_RUN === 'true';\n\nconst config: Config = {\n  testMatch: ['**\u002F*.test.ts'],\n  testPathIgnorePatterns: isQuarantineRun ? [] : quarantinedPatterns,\n  testPathPattern: isQuarantineRun ? quarantinedPatterns.join('|') : undefined,\n\n  \u002F\u002F No retries in main pipeline\n  ...(isQuarantineRun ? {} : { bail: 1 }),\n\n  reporters: [\n    'default',\n    ['jest-junit', { outputDirectory: 'test-results', outputName: 'junit.xml' }],\n  ],\n};\n\nexport default config;\n```\n\n### Vitest Quarantine Configuration\n\n```typescript\n\u002F\u002F config\u002Fvitest.config.ts\nimport { defineConfig } from 'vitest\u002Fconfig';\nimport * as fs from 'fs';\n\nconst quarantineRegistry = JSON.parse(\n  fs.readFileSync('tests\u002Fquarantine\u002Fquarantine-registry.json', 'utf-8')\n);\nconst quarantinedFiles = quarantineRegistry.quarantinedTests.map((t: any) => t.file);\n\nconst isQuarantineRun = process.env.QUARANTINE_RUN === 'true';\n\nexport default defineConfig({\n  test: {\n    include: isQuarantineRun ? quarantinedFiles : ['tests\u002F**\u002F*.test.ts'],\n    exclude: isQuarantineRun ? [] : quarantinedFiles,\n    retry: isQuarantineRun ? 3 : 0,\n    reporters: ['verbose', 'json'],\n    outputFile: 'test-results\u002Fresults.json',\n  },\n});\n```\n\n## Best Practices\n\n1. **Establish a flakiness budget.** Set a target for overall suite flakiness (e.g., less than 2% of tests are flaky at any time). Track this metric and treat exceeding the budget as a team priority.\n\n2. **Automate quarantine decisions.** When a test exceeds a configurable flakiness threshold (e.g., 15% failure rate over 50 runs), automatically quarantine it and create a tracking ticket.\n\n3. **Run quarantined tests in a separate CI job.** This keeps the main pipeline reliable while still executing quarantined tests to track their behavior and detect if a code change inadvertently fixes them.\n\n4. **Assign ownership for quarantined tests.** Every quarantined test should have an assignee and a tracking ticket. Unowned quarantined tests accumulate indefinitely.\n\n5. **Set time limits on quarantine.** A test quarantined for more than 30 days without progress should be escalated. Indefinite quarantine is equivalent to deletion.\n\n6. **Fix by root cause category.** Maintain a playbook for each root cause type. Timing issues require wait-for-condition patterns, state leakage requires setup\u002Fteardown improvements, and external dependencies require mocking.\n\n7. **Verify fixes with multi-run confirmation.** A fix is not verified by a single passing run. Run the previously flaky test at least 20 times in both isolated and full-suite modes to confirm stability.\n\n8. **Use test annotations to communicate quarantine status.** Annotate quarantined tests in the code so developers reviewing test files understand which tests are quarantined and why.\n\n9. **Track flakiness trends over time.** Monitor whether the overall flakiness rate is improving or degrading. This reveals systemic issues and measures the effectiveness of reliability efforts.\n\n10. **Review test infrastructure alongside test code.** Flakiness often originates from CI runner resource constraints, Docker networking issues, or shared test databases. Investigate infrastructure when flakiness patterns span unrelated tests.\n\n## Anti-Patterns to Avoid\n\n1. **Adding retries to the main pipeline as a permanent solution.** Retries mask flakiness and increase pipeline duration. They should only be used temporarily in quarantine pipelines while fixes are in progress.\n\n2. **Deleting flaky tests instead of fixing them.** Flaky tests often cover real functionality. Deleting them trades test reliability for reduced test coverage. Always fix first; only delete if the test provides no value.\n\n3. **Increasing timeouts globally to address timing flakiness.** Raising the global timeout from 30 seconds to 60 seconds slows down the entire suite and does not fix the underlying issue. Use targeted explicit waits.\n\n4. **Blaming the test framework for flakiness.** While framework bugs exist, the vast majority of flakiness is caused by test design issues. Investigate test code before concluding the framework is at fault.\n\n5. **Quarantining tests without creating tracking tickets.** Quarantine without accountability leads to a growing graveyard of disabled tests. Every quarantine action must create a tracked work item.\n\n6. **Running flaky detection only once.** Flakiness evolves as the codebase changes. Schedule weekly flaky detection runs to catch newly flaky tests before they accumulate.\n\n7. **Fixing flakiness by adding sleep statements.** Fixed sleeps are inherently unreliable because system performance varies. Replace sleeps with condition-based waits that react to actual state changes.\n\n## Debugging Tips\n\n1. **Enable trace recording on retry.** Configure Playwright to capture traces on first retry (`trace: 'on-first-retry'`). Traces provide a complete timeline of actions, network requests, and DOM snapshots for diagnosing intermittent failures.\n\n2. **Compare passing and failing run logs side by side.** The difference between a passing and failing run often reveals the root cause: a missing API response, a slower DOM update, or a different data state.\n\n3. **Check test execution order.** Run the failing test after specific other tests to identify order-dependent flakiness. Use `--shard` or randomized ordering to expose hidden dependencies.\n\n4. **Examine CI runner resource utilization.** High CPU or memory usage on CI runners causes timing-related flakiness. Check runner metrics during test execution to identify resource contention.\n\n5. **Look for time-zone and locale sensitivity.** Tests that pass in one time zone but fail in another often involve date formatting or comparison. CI runners may use different locales than development machines.\n\n6. **Inspect network timing in traces.** Network-related flakiness shows up as variable response times or timeout errors in traces. Consider mocking slow or unreliable external services.\n\n7. **Run the test in a loop locally.** Use `for i in $(seq 1 50); do npx playwright test \"test-name\" || echo \"FAILED on run $i\"; done` to reproduce flakiness locally before attempting a fix.\n\n8. **Check for shared mutable state.** Global variables, module-level caches, and singleton patterns can leak state between tests when running in parallel. Review test setup and teardown for completeness.\n\n9. **Verify database cleanup completeness.** If tests share a database, ensure that beforeEach\u002FafterEach hooks clean up all relevant tables. Missing cleanup of junction tables or audit logs is a common cause of state leakage.\n\n10. **Use deterministic test data.** Random data generation without fixed seeds can cause tests to pass or fail depending on the generated values. Use seeded random generators or fixed test data when determinism matters.\n","# Flaky Test Quarantine\n\nFlaky tests are tests that produce different outcomes (pass or fail) when run against the same code under the same conditions. They erode confidence in the test suite, train developers to ignore failures, and slow down CI pipelines with unnecessary retries. A single flaky test in a suite of 500 can cause the entire pipeline to require re-runs, wasting developer time and compute resources. This skill provides a systematic approach to detecting, quarantining, categorizing, and fixing flaky tests while maintaining CI pipeline stability.\n\n## Core Principles\n\n1. **Detection Before Quarantine**: A test must be proven flaky through repeated execution before it is quarantined. A single failure does not make a test flaky; it might indicate a real bug. Multi-run analysis with statistical tracking separates genuine flakiness from legitimate failures.\n\n2. **Quarantine Is Not Deletion**: Quarantined tests must remain in the codebase and continue running in a separate pipeline. Quarantine is a temporary holding pattern that prevents flaky tests from blocking the main pipeline while preserving the test and tracking its behavior.\n\n3. **Root Cause Categorization Drives Fixes**: Different types of flakiness require different fixing strategies. Timing issues need explicit waits, state leakage needs proper cleanup, external dependencies need mocking, and race conditions need synchronization. Categorizing the root cause directs the fix.\n\n4. **Flakiness Is Measurable**: Track the flakiness rate (failures per total runs) for every test over time. This metric determines quarantine decisions, fix prioritization, and verifies that fixes actually resolved the issue.\n\n5. **Zero-Tolerance Pipeline**: The main CI pipeline must be green to merge. Allowing occasional failures or manual re-runs normalizes flakiness and makes it impossible to distinguish real failures from known flaky ones.\n\n6. **Fix the Root Cause, Not the Symptom**: Adding retries or increasing timeouts masks flakiness without fixing it. These approaches hide real issues and increase overall test execution time. Address the underlying non-determinism.\n\n7. **Isolation Verification**: After fixing a flaky test, verify the fix by running the test in isolation and in the full suite multiple times. Some flakiness only manifests under specific ordering or parallel execution conditions.\n\n## Project Structure\n\n```\nproject-root\u002F\n├── tests\u002F\n│   ├── e2e\u002F\n│   │   ├── checkout.spec.ts\n│   │   ├── search.spec.ts\n│   │   └── user-profile.spec.ts\n│   ├── unit\u002F\n│   │   ├── payment.test.ts\n│   │   └── cart.test.ts\n│   └── quarantine\u002F\n│       ├── README.md\n│       └── quarantine-registry.json\n├── scripts\u002F\n│   ├── detect-flaky.ts\n│   ├── quarantine-manager.ts\n│   ├── flaky-report.ts\n│   └── verify-fix.ts\n├── .github\u002F\n│   └── workflows\u002F\n│       ├── main-ci.yml\n│       ├── quarantine-ci.yml\n│       └── flaky-detection.yml\n├── config\u002F\n│   ├── playwright.config.ts\n│   ├── jest.config.ts\n│   └── vitest.config.ts\n└── flaky-test.config.ts\n```\n\n## Flaky Test Detection\n\n### Multi-Run Detection Script\n\nThe most reliable way to detect flaky tests is to run the test suite multiple times and compare results. A test that fails even once across multiple runs of identical code is flaky.\n\n```typescript\n\u002F\u002F scripts\u002Fdetect-flaky.ts\nimport { execSync } from 'child_process';\nimport * as fs from 'fs';\n\ninterface TestResult {\n  testName: string;\n  file: string;\n  runs: number;\n  passes: number;\n  failures: number;\n  flakinessRate: number;\n  failureMessages: string[];\n}\n\ninterface DetectionConfig {\n  runs: number;\n  testCommand: string;\n  resultPattern: string;\n  flakinessThreshold: number;\n}\n\nconst config: DetectionConfig = {\n  runs: 10,\n  testCommand: 'npx playwright test --reporter=json',\n  resultPattern: 'test-results\u002Fresults.json',\n  flakinessThreshold: 0.1, \u002F\u002F 10% failure rate = flaky\n};\n\nasync function detectFlakyTests(): Promise\u003CTestResult[]> {\n  const resultsByTest = new Map\u003Cstring, TestResult>();\n\n  console.log(`Running test suite ${config.runs} times to detect flaky tests...`);\n\n  for (let run = 1; run \u003C= config.runs; run++) {\n    console.log(`\\n--- Run ${run}\u002F${config.runs} ---`);\n\n    try {\n      execSync(config.testCommand, {\n        stdio: 'pipe',\n        env: {\n          ...process.env,\n          PLAYWRIGHT_JSON_OUTPUT_NAME: `test-results\u002Frun-${run}.json`,\n        },\n      });\n    } catch {\n      \u002F\u002F Test failures are expected; we continue regardless\n    }\n\n    const resultsFile = `test-results\u002Frun-${run}.json`;\n    if (!fs.existsSync(resultsFile)) continue;\n\n    const results = JSON.parse(fs.readFileSync(resultsFile, 'utf-8'));\n\n    for (const suite of results.suites || []) {\n      for (const spec of suite.specs || []) {\n        const key = `${suite.file}::${spec.title}`;\n\n        if (!resultsByTest.has(key)) {\n          resultsByTest.set(key, {\n            testName: spec.title,\n            file: suite.file,\n            runs: 0,\n            passes: 0,\n            failures: 0,\n            flakinessRate: 0,\n            failureMessages: [],\n          });\n        }\n\n        const entry = resultsByTest.get(key)!;\n        entry.runs++;\n\n        const passed = spec.tests.every((t: any) => t.status === 'passed');\n        if (passed) {\n          entry.passes++;\n        } else {\n          entry.failures++;\n          const failMsg = spec.tests\n            .filter((t: any) => t.status === 'failed')\n            .map((t: any) => t.results?.[0]?.error?.message || 'Unknown error')\n            .join('; ');\n          entry.failureMessages.push(failMsg);\n        }\n      }\n    }\n  }\n\n  \u002F\u002F Calculate flakiness rates\n  const allResults: TestResult[] = [];\n  for (const result of resultsByTest.values()) {\n    result.flakinessRate = result.failures \u002F result.runs;\n    allResults.push(result);\n  }\n\n  \u002F\u002F Filter to only flaky tests (failed some but not all runs)\n  const flakyTests = allResults.filter(\n    (r) => r.flakinessRate > 0 && r.flakinessRate \u003C 1 && r.flakinessRate >= config.flakinessThreshold\n  );\n\n  console.log(`\\nDetected ${flakyTests.length} flaky tests out of ${allResults.length} total tests`);\n\n  \u002F\u002F Write report\n  fs.writeFileSync(\n    'test-results\u002Fflaky-detection-report.json',\n    JSON.stringify(\n      {\n        timestamp: new Date().toISOString(),\n        totalRuns: config.runs,\n        totalTests: allResults.length,\n        flakyTests: flakyTests.sort((a, b) => b.flakinessRate - a.flakinessRate),\n      },\n      null,\n      2\n    )\n  );\n\n  return flakyTests;\n}\n\ndetectFlakyTests().catch(console.error);\n```\n\n### Automated Flaky Detection in CI\n\n```yaml\n# .github\u002Fworkflows\u002Fflaky-detection.yml\nname: Flaky Test Detection\non:\n  schedule:\n    - cron: '0 2 * * 0'   # Run weekly at 2 AM Sunday\n  workflow_dispatch:        # Manual trigger\n\njobs:\n  detect-flaky:\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        run: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-node@v4\n        with:\n          node-version: 20\n      - run: npm ci\n      - run: npx playwright install --with-deps\n      - name: Run test suite (attempt ${{ matrix.run }})\n        run: npx playwright test --reporter=json\n        continue-on-error: true\n        env:\n          PLAYWRIGHT_JSON_OUTPUT_NAME: results-${{ matrix.run }}.json\n      - uses: actions\u002Fupload-artifact@v4\n        with:\n          name: results-${{ matrix.run }}\n          path: results-${{ matrix.run }}.json\n\n  analyze:\n    needs: detect-flaky\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fdownload-artifact@v4\n        with:\n          path: all-results\n      - name: Analyze flakiness\n        run: npx ts-node scripts\u002Fanalyze-flaky-results.ts all-results\u002F\n      - name: Create issue if flaky tests found\n        if: steps.analyze.outputs.flaky_count > 0\n        uses: actions\u002Fgithub-script@v7\n        with:\n          script: |\n            const report = require('.\u002Fflaky-report.json');\n            await github.rest.issues.create({\n              owner: context.repo.owner,\n              repo: context.repo.repo,\n              title: `Flaky Tests Detected: ${report.count} tests`,\n              body: report.markdown,\n              labels: ['flaky-test', 'test-reliability'],\n            });\n```\n\n## Automatic Quarantine Tagging\n\n### Quarantine Registry\n\n```typescript\n\u002F\u002F tests\u002Fquarantine\u002Fquarantine-registry.json\n{\n  \"version\": 1,\n  \"lastUpdated\": \"2024-06-15T10:00:00.000Z\",\n  \"quarantinedTests\": [\n    {\n      \"id\": \"q-001\",\n      \"testName\": \"should complete checkout with PayPal\",\n      \"file\": \"tests\u002Fe2e\u002Fcheckout.spec.ts\",\n      \"quarantinedAt\": \"2024-06-10T14:30:00.000Z\",\n      \"quarantinedBy\": \"ci-bot\",\n      \"reason\": \"Flakiness rate 35% over last 50 runs\",\n      \"rootCause\": \"timing\",\n      \"rootCauseDetail\": \"PayPal iframe loads inconsistently, waitForSelector timeout\",\n      \"flakinessRate\": 0.35,\n      \"priority\": \"high\",\n      \"assignee\": \"team-payments\",\n      \"jiraTicket\": \"QA-1234\",\n      \"status\": \"investigating\"\n    },\n    {\n      \"id\": \"q-002\",\n      \"testName\": \"should display search results with filters\",\n      \"file\": \"tests\u002Fe2e\u002Fsearch.spec.ts\",\n      \"quarantinedAt\": \"2024-06-12T09:00:00.000Z\",\n      \"quarantinedBy\": \"developer-jane\",\n      \"reason\": \"Intermittent failure on CI (passes locally)\",\n      \"rootCause\": \"state-leakage\",\n      \"rootCauseDetail\": \"Previous test leaves search index in dirty state\",\n      \"flakinessRate\": 0.20,\n      \"priority\": \"medium\",\n      \"assignee\": \"team-search\",\n      \"jiraTicket\": \"QA-1235\",\n      \"status\": \"fix-in-progress\"\n    }\n  ]\n}\n```\n\n### Quarantine Manager\n\n```typescript\n\u002F\u002F scripts\u002Fquarantine-manager.ts\nimport * as fs from 'fs';\nimport * as path from 'path';\n\ninterface QuarantineEntry {\n  id: string;\n  testName: string;\n  file: string;\n  quarantinedAt: string;\n  quarantinedBy: string;\n  reason: string;\n  rootCause: RootCause;\n  rootCauseDetail: string;\n  flakinessRate: number;\n  priority: 'critical' | 'high' | 'medium' | 'low';\n  assignee: string;\n  jiraTicket?: string;\n  status: 'new' | 'investigating' | 'fix-in-progress' | 'fix-ready' | 'verified';\n}\n\ntype RootCause =\n  | 'timing'\n  | 'state-leakage'\n  | 'external-dependency'\n  | 'race-condition'\n  | 'resource-contention'\n  | 'environment-specific'\n  | 'test-data'\n  | 'unknown';\n\nconst REGISTRY_PATH = path.resolve(__dirname, '..\u002Ftests\u002Fquarantine\u002Fquarantine-registry.json');\n\nfunction loadRegistry(): { version: number; quarantinedTests: QuarantineEntry[] } {\n  if (!fs.existsSync(REGISTRY_PATH)) {\n    return { version: 1, quarantinedTests: [] };\n  }\n  return JSON.parse(fs.readFileSync(REGISTRY_PATH, 'utf-8'));\n}\n\nfunction saveRegistry(registry: { version: number; quarantinedTests: QuarantineEntry[] }): void {\n  registry.lastUpdated = new Date().toISOString();\n  fs.writeFileSync(REGISTRY_PATH, JSON.stringify(registry, null, 2));\n}\n\nexport function quarantineTest(entry: Omit\u003CQuarantineEntry, 'id' | 'quarantinedAt'>): void {\n  const registry = loadRegistry();\n  const id = `q-${String(registry.quarantinedTests.length + 1).padStart(3, '0')}`;\n\n  registry.quarantinedTests.push({\n    ...entry,\n    id,\n    quarantinedAt: new Date().toISOString(),\n  });\n\n  saveRegistry(registry);\n  console.log(`Quarantined test: ${entry.testName} (${id})`);\n}\n\nexport function unquarantineTest(id: string): void {\n  const registry = loadRegistry();\n  const index = registry.quarantinedTests.findIndex((t) => t.id === id);\n\n  if (index === -1) {\n    console.error(`Test ${id} not found in quarantine`);\n    return;\n  }\n\n  const removed = registry.quarantinedTests.splice(index, 1)[0];\n  saveRegistry(registry);\n  console.log(`Unquarantined test: ${removed.testName} (${id})`);\n}\n\nexport function getQuarantinedTestNames(): Set\u003Cstring> {\n  const registry = loadRegistry();\n  return new Set(registry.quarantinedTests.map((t) => t.testName));\n}\n```\n\n### Playwright Quarantine Integration\n\n```typescript\n\u002F\u002F config\u002Fplaywright.config.ts\nimport { defineConfig, devices } from '@playwright\u002Ftest';\nimport * as fs from 'fs';\n\n\u002F\u002F Load quarantine registry\nconst quarantineRegistry = JSON.parse(\n  fs.readFileSync('tests\u002Fquarantine\u002Fquarantine-registry.json', 'utf-8')\n);\nconst quarantinedFiles = new Set(\n  quarantineRegistry.quarantinedTests.map((t: any) => t.file)\n);\n\nconst isQuarantineRun = process.env.QUARANTINE_RUN === 'true';\n\nexport default defineConfig({\n  testDir: '.\u002Ftests\u002Fe2e',\n\n  \u002F\u002F In main pipeline: exclude quarantined test files\n  \u002F\u002F In quarantine pipeline: only run quarantined test files\n  testMatch: isQuarantineRun\n    ? [...quarantinedFiles].map((f) => f.replace('tests\u002Fe2e\u002F', ''))\n    : undefined,\n  testIgnore: isQuarantineRun\n    ? undefined\n    : [...quarantinedFiles].map((f) => f.replace('tests\u002Fe2e\u002F', '')),\n\n  retries: isQuarantineRun ? 3 : 0,   \u002F\u002F Retries only in quarantine pipeline\n  timeout: 30000,\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\n  projects: [\n    {\n      name: 'chromium',\n      use: { ...devices['Desktop Chrome'] },\n    },\n  ],\n\n  reporter: [\n    ['html', { open: 'never' }],\n    ['json', { outputFile: 'test-results\u002Fresults.json' }],\n  ],\n});\n```\n\n### Annotation-Based Quarantine with Custom Fixture\n\n```typescript\n\u002F\u002F tests\u002Fe2e\u002Ffixtures\u002Fquarantine-fixture.ts\nimport { test as base } from '@playwright\u002Ftest';\nimport * as fs from 'fs';\n\ninterface QuarantineInfo {\n  isQuarantined: boolean;\n  reason?: string;\n  jiraTicket?: string;\n}\n\nconst quarantineRegistry = JSON.parse(\n  fs.readFileSync('tests\u002Fquarantine\u002Fquarantine-registry.json', 'utf-8')\n);\n\nconst quarantinedMap = new Map(\n  quarantineRegistry.quarantinedTests.map((t: any) => [t.testName, t])\n);\n\nexport const test = base.extend\u003C{ quarantine: QuarantineInfo }>({\n  quarantine: async ({}, use, testInfo) => {\n    const entry = quarantinedMap.get(testInfo.title);\n    const isQuarantineRun = process.env.QUARANTINE_RUN === 'true';\n\n    if (entry && !isQuarantineRun) {\n      testInfo.annotations.push({\n        type: 'quarantine',\n        description: `Quarantined: ${entry.reason} (${entry.jiraTicket || 'no ticket'})`,\n      });\n      test.skip(true, `Quarantined: ${entry.reason}`);\n    }\n\n    await use({\n      isQuarantined: !!entry,\n      reason: entry?.reason,\n      jiraTicket: entry?.jiraTicket,\n    });\n  },\n});\n\nexport { expect } from '@playwright\u002Ftest';\n```\n\n### Using the Quarantine Fixture in Tests\n\n```typescript\n\u002F\u002F tests\u002Fe2e\u002Fcheckout.spec.ts\nimport { test, expect } from '.\u002Ffixtures\u002Fquarantine-fixture';\n\ntest.describe('Checkout Flow', () => {\n  test('should complete checkout with credit card', async ({ page }) => {\n    \u002F\u002F This test is stable - runs normally\n    await page.goto('\u002Fproducts\u002F1');\n    await page.click('[data-testid=\"add-to-cart\"]');\n    await page.goto('\u002Fcheckout');\n    await page.fill('[data-testid=\"card-number\"]', '4242424242424242');\n    await page.click('[data-testid=\"place-order\"]');\n    await expect(page.locator('[data-testid=\"order-confirmation\"]')).toBeVisible();\n  });\n\n  test('should complete checkout with PayPal', async ({ page, quarantine }) => {\n    \u002F\u002F This test is in the quarantine registry - will be skipped in main pipeline\n    await page.goto('\u002Fproducts\u002F1');\n    await page.click('[data-testid=\"add-to-cart\"]');\n    await page.goto('\u002Fcheckout');\n    await page.click('[data-testid=\"pay-with-paypal\"]');\n    \u002F\u002F PayPal iframe interaction...\n    await expect(page.locator('[data-testid=\"order-confirmation\"]')).toBeVisible();\n  });\n});\n```\n\n## Root Cause Categories and Fixing Strategies\n\n### Timing Issues\n\nTiming flakiness occurs when tests assume operations complete within a fixed time. The fix is to replace arbitrary timeouts with explicit condition waits.\n\n```typescript\n\u002F\u002F FLAKY: Uses fixed timeout\ntest('should show notification after save', async ({ page }) => {\n  await page.click('[data-testid=\"save-button\"]');\n  await page.waitForTimeout(2000); \u002F\u002F Arbitrary wait - FLAKY\n  const notification = page.locator('[data-testid=\"notification\"]');\n  await expect(notification).toBeVisible();\n});\n\n\u002F\u002F FIXED: Waits for specific condition\ntest('should show notification after save', async ({ page }) => {\n  await page.click('[data-testid=\"save-button\"]');\n  const notification = page.locator('[data-testid=\"notification\"]');\n  await expect(notification).toBeVisible({ timeout: 10000 }); \u002F\u002F Explicit condition wait\n});\n```\n\n### State Leakage Between Tests\n\nState leakage happens when one test modifies shared state (database, browser storage, global variables) that another test depends on.\n\n```typescript\n\u002F\u002F FLAKY: Tests share state\ntest.describe('User Settings', () => {\n  test('should enable dark mode', async ({ page }) => {\n    await page.goto('\u002Fsettings');\n    await page.click('[data-testid=\"dark-mode-toggle\"]');\n    \u002F\u002F Leaves dark mode enabled for next test\n  });\n\n  test('should show default light theme', async ({ page }) => {\n    await page.goto('\u002Fsettings');\n    \u002F\u002F FAILS if previous test ran first and enabled dark mode\n    await expect(page.locator('body')).toHaveClass(\u002Flight-theme\u002F);\n  });\n});\n\n\u002F\u002F FIXED: Each test manages its own state\ntest.describe('User Settings', () => {\n  test.beforeEach(async ({ page }) => {\n    \u002F\u002F Reset user preferences before each test\n    await page.evaluate(() => localStorage.clear());\n    await page.request.post('\u002Fapi\u002Ftest\u002Freset-user-preferences');\n  });\n\n  test('should enable dark mode', async ({ page }) => {\n    await page.goto('\u002Fsettings');\n    await page.click('[data-testid=\"dark-mode-toggle\"]');\n    await expect(page.locator('body')).toHaveClass(\u002Fdark-theme\u002F);\n  });\n\n  test('should show default light theme', async ({ page }) => {\n    await page.goto('\u002Fsettings');\n    await expect(page.locator('body')).toHaveClass(\u002Flight-theme\u002F);\n  });\n});\n```\n\n### External Dependency Flakiness\n\n```typescript\n\u002F\u002F FLAKY: Depends on external payment API availability\ntest('should process payment', async ({ page }) => {\n  await page.goto('\u002Fcheckout');\n  await page.fill('[data-testid=\"card\"]', '4242424242424242');\n  await page.click('[data-testid=\"pay\"]');\n  \u002F\u002F External payment gateway may be slow or down\n  await expect(page.locator('[data-testid=\"success\"]')).toBeVisible();\n});\n\n\u002F\u002F FIXED: Mock external dependency\ntest('should process payment', async ({ page }) => {\n  \u002F\u002F Intercept external API calls\n  await page.route('**\u002Fapi.stripe.com\u002F**', async (route) => {\n    await route.fulfill({\n      status: 200,\n      contentType: 'application\u002Fjson',\n      body: JSON.stringify({\n        id: 'pi_mock_123',\n        status: 'succeeded',\n        amount: 2999,\n      }),\n    });\n  });\n\n  await page.goto('\u002Fcheckout');\n  await page.fill('[data-testid=\"card\"]', '4242424242424242');\n  await page.click('[data-testid=\"pay\"]');\n  await expect(page.locator('[data-testid=\"success\"]')).toBeVisible();\n});\n```\n\n### Race Conditions\n\n```typescript\n\u002F\u002F FLAKY: Race condition between navigation and assertion\ntest('should load dashboard data', async ({ page }) => {\n  await page.goto('\u002Fdashboard');\n  \u002F\u002F Data might not have loaded yet\n  const count = await page.locator('[data-testid=\"item-count\"]').textContent();\n  expect(parseInt(count!)).toBeGreaterThan(0);\n});\n\n\u002F\u002F FIXED: Wait for the data to be in the expected state\ntest('should load dashboard data', async ({ page }) => {\n  await page.goto('\u002Fdashboard');\n\n  \u002F\u002F Wait for the loading state to complete\n  await page.waitForResponse((response) =>\n    response.url().includes('\u002Fapi\u002Fdashboard') && response.status() === 200\n  );\n\n  \u002F\u002F Now assert on the data\n  const countLocator = page.locator('[data-testid=\"item-count\"]');\n  await expect(countLocator).not.toHaveText('0');\n  const count = await countLocator.textContent();\n  expect(parseInt(count!)).toBeGreaterThan(0);\n});\n```\n\n## Retry with Exponential Backoff\n\n```typescript\n\u002F\u002F scripts\u002Fretry-runner.ts\nimport { execSync } from 'child_process';\n\ninterface RetryConfig {\n  maxRetries: number;\n  baseDelay: number;      \u002F\u002F milliseconds\n  maxDelay: number;       \u002F\u002F milliseconds\n  backoffMultiplier: number;\n}\n\nconst defaultConfig: RetryConfig = {\n  maxRetries: 3,\n  baseDelay: 1000,\n  maxDelay: 30000,\n  backoffMultiplier: 2,\n};\n\nexport async function runWithRetry(\n  command: string,\n  config: RetryConfig = defaultConfig\n): Promise\u003C{ success: boolean; attempts: number; lastError?: string }> {\n  let lastError = '';\n\n  for (let attempt = 1; attempt \u003C= config.maxRetries + 1; attempt++) {\n    try {\n      console.log(`Attempt ${attempt}\u002F${config.maxRetries + 1}: ${command}`);\n      execSync(command, { stdio: 'inherit' });\n      return { success: true, attempts: attempt };\n    } catch (error: any) {\n      lastError = error.message;\n      console.log(`Attempt ${attempt} failed: ${lastError}`);\n\n      if (attempt \u003C= config.maxRetries) {\n        const delay = Math.min(\n          config.baseDelay * Math.pow(config.backoffMultiplier, attempt - 1),\n          config.maxDelay\n        );\n        const jitter = delay * (0.5 + Math.random() * 0.5); \u002F\u002F Add jitter\n        console.log(`Retrying in ${Math.round(jitter)}ms...`);\n        await new Promise((resolve) => setTimeout(resolve, jitter));\n      }\n    }\n  }\n\n  return { success: false, attempts: config.maxRetries + 1, lastError };\n}\n```\n\n## Flakiness Rate Tracking\n\n```typescript\n\u002F\u002F scripts\u002Fflaky-report.ts\nimport * as fs from 'fs';\n\ninterface TestHistory {\n  testName: string;\n  file: string;\n  recentRuns: Array\u003C{\n    date: string;\n    passed: boolean;\n    duration: number;\n    ciRunId: string;\n  }>;\n  totalRuns: number;\n  totalFailures: number;\n  flakinessRate: number;\n  trend: 'improving' | 'stable' | 'degrading';\n  lastFailure: string | null;\n  averageDuration: number;\n}\n\nconst HISTORY_PATH = 'test-results\u002Fflakiness-history.json';\n\nexport function updateHistory(runResults: any[], ciRunId: string): void {\n  const history: Map\u003Cstring, TestHistory> = loadHistory();\n\n  for (const result of runResults) {\n    const key = `${result.file}::${result.testName}`;\n\n    if (!history.has(key)) {\n      history.set(key, {\n        testName: result.testName,\n        file: result.file,\n        recentRuns: [],\n        totalRuns: 0,\n        totalFailures: 0,\n        flakinessRate: 0,\n        trend: 'stable',\n        lastFailure: null,\n        averageDuration: 0,\n      });\n    }\n\n    const entry = history.get(key)!;\n    entry.recentRuns.push({\n      date: new Date().toISOString(),\n      passed: result.passed,\n      duration: result.duration,\n      ciRunId,\n    });\n\n    \u002F\u002F Keep last 100 runs\n    if (entry.recentRuns.length > 100) {\n      entry.recentRuns = entry.recentRuns.slice(-100);\n    }\n\n    entry.totalRuns++;\n    if (!result.passed) {\n      entry.totalFailures++;\n      entry.lastFailure = new Date().toISOString();\n    }\n\n    \u002F\u002F Calculate flakiness rate over recent runs\n    const recentFailures = entry.recentRuns.filter((r) => !r.passed).length;\n    entry.flakinessRate = recentFailures \u002F entry.recentRuns.length;\n\n    \u002F\u002F Calculate trend (compare last 25 runs with previous 25)\n    if (entry.recentRuns.length >= 50) {\n      const recent25 = entry.recentRuns.slice(-25);\n      const previous25 = entry.recentRuns.slice(-50, -25);\n      const recentRate = recent25.filter((r) => !r.passed).length \u002F 25;\n      const previousRate = previous25.filter((r) => !r.passed).length \u002F 25;\n\n      if (recentRate \u003C previousRate - 0.05) entry.trend = 'improving';\n      else if (recentRate > previousRate + 0.05) entry.trend = 'degrading';\n      else entry.trend = 'stable';\n    }\n\n    entry.averageDuration =\n      entry.recentRuns.reduce((sum, r) => sum + r.duration, 0) \u002F entry.recentRuns.length;\n  }\n\n  saveHistory(history);\n  generateReport(history);\n}\n\nfunction generateReport(history: Map\u003Cstring, TestHistory>): void {\n  const flakyTests = [...history.values()]\n    .filter((t) => t.flakinessRate > 0 && t.flakinessRate \u003C 1)\n    .sort((a, b) => b.flakinessRate - a.flakinessRate);\n\n  const report = {\n    generatedAt: new Date().toISOString(),\n    summary: {\n      totalTests: history.size,\n      flakyTests: flakyTests.length,\n      flakinessPercentage: ((flakyTests.length \u002F history.size) * 100).toFixed(1),\n      criticalFlaky: flakyTests.filter((t) => t.flakinessRate > 0.3).length,\n      degradingTests: flakyTests.filter((t) => t.trend === 'degrading').length,\n    },\n    tests: flakyTests.map((t) => ({\n      testName: t.testName,\n      file: t.file,\n      flakinessRate: `${(t.flakinessRate * 100).toFixed(1)}%`,\n      trend: t.trend,\n      totalRuns: t.totalRuns,\n      lastFailure: t.lastFailure,\n      averageDuration: `${Math.round(t.averageDuration)}ms`,\n    })),\n  };\n\n  fs.writeFileSync('test-results\u002Fflakiness-report.json', JSON.stringify(report, null, 2));\n  console.log(`Flakiness report: ${flakyTests.length} flaky tests detected`);\n}\n\nfunction loadHistory(): Map\u003Cstring, TestHistory> {\n  if (!fs.existsSync(HISTORY_PATH)) return new Map();\n  const data = JSON.parse(fs.readFileSync(HISTORY_PATH, 'utf-8'));\n  return new Map(Object.entries(data));\n}\n\nfunction saveHistory(history: Map\u003Cstring, TestHistory>): void {\n  fs.writeFileSync(HISTORY_PATH, JSON.stringify(Object.fromEntries(history), null, 2));\n}\n```\n\n## CI Integration\n\n### Main Pipeline (Excludes Quarantined Tests)\n\n```yaml\n# .github\u002Fworkflows\u002Fmain-ci.yml\nname: Main CI Pipeline\non:\n  push:\n    branches: [main]\n  pull_request:\n\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-node@v4\n        with:\n          node-version: 20\n      - run: npm ci\n      - run: npx playwright install --with-deps\n\n      # Run tests excluding quarantined tests (zero retries)\n      - name: Run stable tests\n        run: npx playwright test --retries=0\n        env:\n          QUARANTINE_RUN: 'false'\n\n      - name: Upload results\n        if: always()\n        uses: actions\u002Fupload-artifact@v4\n        with:\n          name: test-results\n          path: test-results\u002F\n```\n\n### Quarantine Pipeline (Runs Only Quarantined Tests)\n\n```yaml\n# .github\u002Fworkflows\u002Fquarantine-ci.yml\nname: Quarantine Pipeline\non:\n  push:\n    branches: [main]\n  schedule:\n    - cron: '0 *\u002F4 * * *'   # Every 4 hours\n\njobs:\n  quarantine-tests:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-node@v4\n        with:\n          node-version: 20\n      - run: npm ci\n      - run: npx playwright install --with-deps\n\n      # Run only quarantined tests with retries\n      - name: Run quarantined tests\n        run: npx playwright test --retries=3\n        continue-on-error: true  # Don't fail the pipeline\n        env:\n          QUARANTINE_RUN: 'true'\n\n      - name: Update flakiness tracking\n        run: npx ts-node scripts\u002Fflaky-report.ts\n        env:\n          CI_RUN_ID: ${{ github.run_id }}\n\n      - name: Check for recovered tests\n        run: |\n          npx ts-node scripts\u002Fcheck-recovered.ts\n        # Outputs tests that passed all retries, candidates for unquarantine\n```\n\n## Test Isolation Verification\n\n```typescript\n\u002F\u002F scripts\u002Fverify-fix.ts\nimport { execSync } from 'child_process';\n\ninterface VerificationResult {\n  testName: string;\n  isolatedRuns: { passed: number; failed: number };\n  suiteRuns: { passed: number; failed: number };\n  verdict: 'fixed' | 'still-flaky' | 'order-dependent';\n}\n\nasync function verifyFix(testFile: string, testName: string): Promise\u003CVerificationResult> {\n  const RUNS = 20;\n  const result: VerificationResult = {\n    testName,\n    isolatedRuns: { passed: 0, failed: 0 },\n    suiteRuns: { passed: 0, failed: 0 },\n    verdict: 'still-flaky',\n  };\n\n  console.log(`Verifying fix for \"${testName}\" with ${RUNS} runs...`);\n\n  \u002F\u002F Phase 1: Run the test in isolation\n  console.log('\\nPhase 1: Isolated runs');\n  for (let i = 0; i \u003C RUNS; i++) {\n    try {\n      execSync(\n        `npx playwright test \"${testFile}\" --grep \"${testName}\" --retries=0`,\n        { stdio: 'pipe' }\n      );\n      result.isolatedRuns.passed++;\n    } catch {\n      result.isolatedRuns.failed++;\n    }\n  }\n  console.log(`  Isolated: ${result.isolatedRuns.passed}\u002F${RUNS} passed`);\n\n  \u002F\u002F Phase 2: Run the test within the full suite\n  console.log('\\nPhase 2: Full suite runs');\n  for (let i = 0; i \u003C RUNS; i++) {\n    try {\n      execSync(`npx playwright test --retries=0`, { stdio: 'pipe' });\n      result.suiteRuns.passed++;\n    } catch {\n      result.suiteRuns.failed++;\n    }\n  }\n  console.log(`  Suite: ${result.suiteRuns.passed}\u002F${RUNS} passed`);\n\n  \u002F\u002F Determine verdict\n  if (result.isolatedRuns.failed === 0 && result.suiteRuns.failed === 0) {\n    result.verdict = 'fixed';\n  } else if (result.isolatedRuns.failed === 0 && result.suiteRuns.failed > 0) {\n    result.verdict = 'order-dependent';\n  } else {\n    result.verdict = 'still-flaky';\n  }\n\n  console.log(`\\nVerdict: ${result.verdict}`);\n  return result;\n}\n```\n\n## Configuration\n\n### Jest Quarantine Configuration\n\n```typescript\n\u002F\u002F config\u002Fjest.config.ts\nimport type { Config } from 'jest';\nimport * as fs from 'fs';\n\nconst quarantineRegistry = JSON.parse(\n  fs.readFileSync('tests\u002Fquarantine\u002Fquarantine-registry.json', 'utf-8')\n);\nconst quarantinedPatterns = quarantineRegistry.quarantinedTests.map(\n  (t: any) => t.file\n);\n\nconst isQuarantineRun = process.env.QUARANTINE_RUN === 'true';\n\nconst config: Config = {\n  testMatch: ['**\u002F*.test.ts'],\n  testPathIgnorePatterns: isQuarantineRun ? [] : quarantinedPatterns,\n  testPathPattern: isQuarantineRun ? quarantinedPatterns.join('|') : undefined,\n\n  \u002F\u002F No retries in main pipeline\n  ...(isQuarantineRun ? {} : { bail: 1 }),\n\n  reporters: [\n    'default',\n    ['jest-junit', { outputDirectory: 'test-results', outputName: 'junit.xml' }],\n  ],\n};\n\nexport default config;\n```\n\n### Vitest Quarantine Configuration\n\n```typescript\n\u002F\u002F config\u002Fvitest.config.ts\nimport { defineConfig } from 'vitest\u002Fconfig';\nimport * as fs from 'fs';\n\nconst quarantineRegistry = JSON.parse(\n  fs.readFileSync('tests\u002Fquarantine\u002Fquarantine-registry.json', 'utf-8')\n);\nconst quarantinedFiles = quarantineRegistry.quarantinedTests.map((t: any) => t.file);\n\nconst isQuarantineRun = process.env.QUARANTINE_RUN === 'true';\n\nexport default defineConfig({\n  test: {\n    include: isQuarantineRun ? quarantinedFiles : ['tests\u002F**\u002F*.test.ts'],\n    exclude: isQuarantineRun ? [] : quarantinedFiles,\n    retry: isQuarantineRun ? 3 : 0,\n    reporters: ['verbose', 'json'],\n    outputFile: 'test-results\u002Fresults.json',\n  },\n});\n```\n\n## Best Practices\n\n1. **Establish a flakiness budget.** Set a target for overall suite flakiness (e.g., less than 2% of tests are flaky at any time). Track this metric and treat exceeding the budget as a team priority.\n\n2. **Automate quarantine decisions.** When a test exceeds a configurable flakiness threshold (e.g., 15% failure rate over 50 runs), automatically quarantine it and create a tracking ticket.\n\n3. **Run quarantined tests in a separate CI job.** This keeps the main pipeline reliable while still executing quarantined tests to track their behavior and detect if a code change inadvertently fixes them.\n\n4. **Assign ownership for quarantined tests.** Every quarantined test should have an assignee and a tracking ticket. Unowned quarantined tests accumulate indefinitely.\n\n5. **Set time limits on quarantine.** A test quarantined for more than 30 days without progress should be escalated. Indefinite quarantine is equivalent to deletion.\n\n6. **Fix by root cause category.** Maintain a playbook for each root cause type. Timing issues require wait-for-condition patterns, state leakage requires setup\u002Fteardown improvements, and external dependencies require mocking.\n\n7. **Verify fixes with multi-run confirmation.** A fix is not verified by a single passing run. Run the previously flaky test at least 20 times in both isolated and full-suite modes to confirm stability.\n\n8. **Use test annotations to communicate quarantine status.** Annotate quarantined tests in the code so developers reviewing test files understand which tests are quarantined and why.\n\n9. **Track flakiness trends over time.** Monitor whether the overall flakiness rate is improving or degrading. This reveals systemic issues and measures the effectiveness of reliability efforts.\n\n10. **Review test infrastructure alongside test code.** Flakiness often originates from CI runner resource constraints, Docker networking issues, or shared test databases. Investigate infrastructure when flakiness patterns span unrelated tests.\n\n## Anti-Patterns to Avoid\n\n1. **Adding retries to the main pipeline as a permanent solution.** Retries mask flakiness and increase pipeline duration. They should only be used temporarily in quarantine pipelines while fixes are in progress.\n\n2. **Deleting flaky tests instead of fixing them.** Flaky tests often cover real functionality. Deleting them trades test reliability for reduced test coverage. Always fix first; only delete if the test provides no value.\n\n3. **Increasing timeouts globally to address timing flakiness.** Raising the global timeout from 30 seconds to 60 seconds slows down the entire suite and does not fix the underlying issue. Use targeted explicit waits.\n\n4. **Blaming the test framework for flakiness.** While framework bugs exist, the vast majority of flakiness is caused by test design issues. Investigate test code before concluding the framework is at fault.\n\n5. **Quarantining tests without creating tracking tickets.** Quarantine without accountability leads to a growing graveyard of disabled tests. Every quarantine action must create a tracked work item.\n\n6. **Running flaky detection only once.** Flakiness evolves as the codebase changes. Schedule weekly flaky detection runs to catch newly flaky tests before they accumulate.\n\n7. **Fixing flakiness by adding sleep statements.** Fixed sleeps are inherently unreliable because system performance varies. Replace sleeps with condition-based waits that react to actual state changes.\n\n## Debugging Tips\n\n1. **Enable trace recording on retry.** Configure Playwright to capture traces on first retry (`trace: 'on-first-retry'`). Traces provide a complete timeline of actions, network requests, and DOM snapshots for diagnosing intermittent failures.\n\n2. **Compare passing and failing run logs side by side.** The difference between a passing and failing run often reveals the root cause: a missing API response, a slower DOM update, or a different data state.\n\n3. **Check test execution order.** Run the failing test after specific other tests to identify order-dependent flakiness. Use `--shard` or randomized ordering to expose hidden dependencies.\n\n4. **Examine CI runner resource utilization.** High CPU or memory usage on CI runners causes timing-related flakiness. Check runner metrics during test execution to identify resource contention.\n\n5. **Look for time-zone and locale sensitivity.** Tests that pass in one time zone but fail in another often involve date formatting or comparison. CI runners may use different locales than development machines.\n\n6. **Inspect network timing in traces.** Network-related flakiness shows up as variable response times or timeout errors in traces. Consider mocking slow or unreliable external services.\n\n7. **Run the test in a loop locally.** Use `for i in $(seq 1 50); do npx playwright test \"test-name\" || echo \"FAILED on run $i\"; done` to reproduce flakiness locally before attempting a fix.\n\n8. **Check for shared mutable state.** Global variables, module-level caches, and singleton patterns can leak state between tests when running in parallel. Review test setup and teardown for completeness.\n\n9. **Verify database cleanup completeness.** If tests share a database, ensure that beforeEach\u002FafterEach hooks clean up all relevant tables. Missing cleanup of junction tables or audit logs is a common cause of state leakage.\n\n10. **Use deterministic test data.** Random data generation without fixed seeds can cause tests to pass or fail depending on the generated values. Use seeded random generators or fixed test data when determinism matters.\n",{"name":5,"tags":24,"agents":32,"author":45,"domains":46,"license":15,"version":48,"languages":49,"frameworks":52,"description":7,"testingTypes":56},[25,26,27,28,29,30,31],"flaky-tests","test-reliability","quarantine","test-retry","ci-stability","test-maintenance","non-deterministic",[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],"devops","1.0.0",[50,51],"typescript","javascript",[53,54,55],"playwright","jest","vitest",[57,58],"code-quality","e2e","main","eac438ea9216a7cb8a570cab803eb01eeafc6793","skills\u002Fqa\u002Fflaky-test-quarantine","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 \"Flaky Test Quarantine\"",{"tool":73,"command":74},"bunx","bunx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"Flaky Test Quarantine\"",{"tool":76,"command":77},"pnpm","pnpm dlx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"Flaky Test Quarantine\"","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fflaky-test-quarantine\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",[],[]]