agentleFS
kaiohenricunhakaiohenricunha/dotbabel/skills/detect-flaky/SKILL.md

detect-flaky

Skill0 starsChanged 2 months agoMITView on GitHub

Detect, diagnose, and fix flaky tests in Python, Go, or JavaScript/TypeScript codebases by repeated execution + root-cause analysis. Triggers on: "detect flaky tests", "find flaky tests", "diagnose flaky tests".

  • Reads credentials

The file

We split this skill into the rules it gives an agent

5 rules. About 0 are common, 5 are distinctive, and 0 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈5

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Symptoms: If diagnosing, what failure rate, error messages, CI context?

    line 121
  2. Distinctive:

    Run the test suite multiple times to detect intermittent failures:

    line 140
  3. Distinctive:

    Consider test dependencies and execution order

    line 166
  4. Distinctive:

    When asked about CI integration, recommend:

    line 297
  5. Distinctive:

    Every finding must be:

    line 330

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

/detect-flaky — Flaky Test Detection and Diagnosis Agent

This agent detects, diagnoses, and fixes flaky tests in Python, Go, and JavaScript/TypeScript codebases.

A test is flaky when it non-deterministically passes or fails without code changes.


Mission (North Star)

Identify flaky tests through:

  1. Static pattern scanning — Regex-based detection of known anti-patterns
  2. Empirical detection — Run tests N times to catch intermittent failures
  3. Root cause diagnosis — Map findings to a curated catalog of causes
  4. Fix generation — Produce concrete before/after code fixes

Your primary outcome is deterministic, trustworthy test suites.


Invocation Examples

/detect-flaky scan this codebase for flaky test patterns

/detect-flaky focus on the Python tests, especially around the API client module

/detect-flaky run Go tests 15 times with race detector and find intermittent failures

/detect-flaky I have a test_payment_flow that fails ~10% of the time in CI, diagnose it

/detect-flaky scan elt/tests/ for timing-related issues

Pattern Catalog (Reference During Analysis)

High Severity (Frequently Flaky)

IDLanguageAnti-PatternDetectionFix
CROSS-TIMEAllTime-dependent assertionstime.Sleep, setTimeout, datetime.now() in assertionsUse deterministic time injection or freeze time
CROSS-RACEAllRace conditions in concurrent test codeShared mutable state across goroutines/threadsUse proper synchronization or test isolation
CROSS-EXTDEPAllUnmocked external dependenciesrequests.get(), http.Get(), fetch() in test filesMock all network calls
PY-MOCK-LEAKPythonMock not cleaned uppatch().start() without stop()Use context manager or addCleanup()
PY-REAL-HTTPPythonReal HTTP in testsrequests, httpx, urllib callsUse responses, httpretty, or respx
PY-RANDOM-SEEDPythonUnseeded randomrandom.choice(), random.randint()Set random.seed() in fixture
GO-PARALLEL-STATEGoShared state in parallel testst.Parallel() with package-level varsUse test-local state or sync primitives
GO-GOROUTINE-LEAKGoGoroutines outliving testgo func() without cleanupUse t.Cleanup() or errgroup
GO-SETENV-PARALLELGoos.Setenv in parallel testsEnvironment mutation + t.Parallel()Use t.Setenv() (Go 1.17+)
GO-RACE-CONDITIONGoData race in testConcurrent map/slice accessRun with -race flag
JS-WAITFOR-TIMINGJS/TSWrong async querygetBy* on async contentUse findBy* or waitFor()
JS-TIMER-LEAKJS/TSFake timers not restoredjest.useFakeTimers() without restoreCall jest.useRealTimers() in afterEach
JS-MOCK-RESTOREJS/TSMock not restoredjest.spyOn() without cleanupUse restoreAllMocks() in afterEach
JS-ACT-MISSINGJS/TSState update outside act()Component updates without act() wrapperWrap state-triggering code in act()

Medium Severity (Sometimes Flaky)

IDLanguageAnti-PatternDetectionFix
CROSS-RANDOMAllUnseeded RNGrand, random, Math.random()Seed RNG or inject deterministic values
CROSS-FLOATAllExact float equality== on float resultsUse pytest.approx(), tolerance comparisons
CROSS-ENVAllEnvironment variable mutationos.Setenv, process.env.X =Restore original values in cleanup
CROSS-ORDERAllTest order dependencyTests pass alone, fail togetherIsolate state, use fresh fixtures
PY-FIXTURE-SCOPEPythonSession/module fixtures with mutable statescope="session" with list/dictUse function scope or immutable fixtures
PY-ASYNC-LOOPPythonManual event loop managementasyncio.get_event_loop(), loop.run_until_complete()Use pytest-asyncio with @pytest.mark.asyncio
PY-TEMPFILEPythonHardcoded temp paths/tmp/test_file.txtUse tmp_path fixture or tempfile
GO-CHANNEL-TIMINGGoShort channel timeoutsselect with time.After(10ms)Use longer timeouts or remove timing dependency
GO-MAP-ORDERGoMap iteration order assertionsLoop over map, assert orderSort keys first or use deterministic structure
GO-HTTP-SERVERGoTest server port conflictsHardcoded ports in testsUse httptest.NewServer() with dynamic ports
JS-SNAPSHOT-FRAGILEJS/TSBrittle snapshotsLarge objects, timestamps in snapshotsExclude volatile fields, use smaller snapshots
JS-ASYNC-UNMOUNTJS/TSState update after unmountAsync callback on unmounted componentUse cleanup functions, abort controllers
JS-FETCH-MOCKJS/TSIncomplete fetch mockMissing error/timeout casesMock all fetch scenarios

Low Severity (Occasionally Flaky)

IDLanguageAnti-PatternDetectionFix
CROSS-HARDCODED-PATHAllHardcoded absolute paths/home/, /Users/, C:\ in testsUse relative paths or fixtures
PY-PARAMETRIZE-IDPythonNon-deterministic test IDs@pytest.mark.parametrize with dictsUse explicit ids= parameter
PY-MONKEYPATCH-SCOPEPythonMonkeypatch scope mismatchMonkeypatch in wrong scopeMatch monkeypatch scope to fixture scope
GO-TESTMAIN-EXITGoMissing os.Exit in TestMainTestMain without os.Exit(m.Run())Always call os.Exit(m.Run())
GO-BUILD-TAGSGoBuild tag inconsistencyTests pass locally, fail in CIEnsure consistent build tags
JS-SNAPSHOT-LARGEJS/TSLarge snapshot filestoMatchSnapshot() on complex outputUse toMatchInlineSnapshot() or targeted assertions
JS-CONSOLE-MOCKJS/TSConsole methods not mockedTests output noise, may have timingMock console.* methods

Analysis Protocol

Phase 1: Understand the Request

Parse the user's request to determine:

  1. Scope: Specific directory, file, test name, or entire codebase?
  2. Language: Python, Go, JS/TS, or all?
  3. Mode: Static scan, empirical detection, or diagnosis of known flaky test?
  4. Symptoms: If diagnosing, what failure rate, error messages, CI context?

Phase 2: Static Pattern Scan

For static analysis, scan test files for patterns from the catalog.

Python test files: **/test_*.py, **/*_test.py, **/tests/**/*.py Go test files: **/*_test.go JS/TS test files: **/*.test.{js,ts,jsx,tsx}, **/*.spec.{js,ts,jsx,tsx}, **/__tests__/**/*.{js,ts,jsx,tsx}

For each match:

  1. Identify the pattern ID
  2. Extract the offending code snippet
  3. Explain why it causes flakiness
  4. Provide a concrete fix

Phase 3: Empirical Detection (If Requested)

Run the test suite multiple times to detect intermittent failures:

# Python
for i in {1..10}; do pytest <path> --tb=no -q 2>&1; done | tee results.txt

# Go
for i in {1..10}; do go test -race -count=1 <package> 2>&1; done | tee results.txt

# JavaScript (Jest)
for i in {1..10}; do npm test -- --testPathPattern=<pattern> 2>&1; done | tee results.txt

Analyze results for:

  • Tests that flip between pass/fail
  • Tests that timeout inconsistently
  • Tests with different failure messages across runs

Phase 4: Root Cause Diagnosis

For each identified flaky test:

  1. Map to pattern catalog entry
  2. Explain the non-determinism source
  3. Identify the specific line(s) causing flakiness
  4. Consider test dependencies and execution order

Phase 5: Fix Generation

Produce concrete fixes:

### Fix for `test_user_creation` (PY-MOCK-LEAK)

**Before:**

```python
def test_user_creation():
    mock_db = patch('app.db.connection').start()
    # test code...
    # Missing: mock_db.stop()
```

After:

def test_user_creation():
    with patch('app.db.connection') as mock_db:
        # test code...
        # Automatically cleaned up

Why this fixes it: The context manager ensures the mock is always stopped, even if the test fails or raises an exception.


---

## Tool Usage

### Scripts (If Available)

```bash
# Fast static scan
python scripts/scan_patterns.py --lang python --format text

# Empirical detection
python scripts/detect_flaky.py --lang python --runs 10 --output report.json

Direct Commands

# Python - find time-dependent code in tests
grep -rn "time.sleep\|datetime.now\|time.time" --include="test_*.py"

# Go - find parallel tests with shared state
grep -rn "t.Parallel()" --include="*_test.go" -A5 | grep -E "var |= "

# JS - find missing async handling
grep -rn "getByText\|getByRole" --include="*.test.tsx" | grep -v "await\|findBy"

# Run with race detector (Go)
go test -race -count=5 ./...

# Run pytest multiple times
pytest --count=10 -x  # requires pytest-repeat

MCP Tool Usage

Use ToolSearch with direct selection:

select:mcp__analyzer__ruff-check      # Python linting
select:mcp__filesystem__search_files  # Find test files

Output Format

Summary Report

# Flaky Test Analysis: [scope]

**Scan Date:** YYYY-MM-DD
**Files Scanned:** X test files
**Patterns Checked:** 30+
**Method:** [Static scan / Empirical (N runs) / Diagnosis]

## Findings Summary

| Severity | Count | Top Patterns                |
| -------- | ----- | --------------------------- |
| High     | X     | CROSS-TIME, PY-MOCK-LEAK    |
| Medium   | X     | CROSS-RANDOM, JS-TIMER-LEAK |
| Low      | X     | CROSS-HARDCODED-PATH        |

## High Severity Issues

### 1. [Pattern ID]: [File:Line]

**Code:**

```language
// problematic code
```

Problem: [Explanation of why this causes flakiness]

Fix:

// fixed code

Verification: [How to confirm the fix works]


Recommendations

  1. [Prioritized action item]
  2. [Prioritized action item]
  3. [Prioritized action item]

---

## CI Integration Guidance

When asked about CI integration, recommend:

```yaml
# GitHub Actions example
name: Flaky Test Check
on: [pull_request]

jobs:
  flaky-scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Scan for flaky patterns
        run: |
          python scripts/scan_patterns.py \
            --min-severity MEDIUM \
            --format json \
            --output flaky-report.json
        continue-on-error: true

      - name: Upload report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: flaky-test-report
          path: flaky-report.json

Quality Standards

Every finding must be:

  • Actionable: Specific file, line, and fix
  • Justified: Clear explanation of the flakiness mechanism
  • Prioritized: Severity based on impact and frequency
  • Verifiable: How to confirm the fix works

Never report:

  • Style issues unrelated to flakiness
  • Theoretical issues without evidence
  • Issues in non-test code (unless directly causing test flakiness)

Ready State

Await user command with scope and intent:

/detect-flaky [scope] [optional: language, mode, specific test name]

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.