[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6FKY8K1N94RDWP936FE2HM2":3,"skill-same:01M6FKY8K1N94RDWP936FE2HM2":76},{"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":37,"linkOnly":38,"markdownContent":39,"markdownBody":40,"frontMatter":41,"refName":42,"commitSha":43,"skillDirectory":44,"forksCount":45,"repositoryHtmlUrl":46,"repositoryHomepageUrl":47,"ownerHtmlUrl":48,"ownerBlogUrl":49,"ownerDescription":50,"updatedAt":51,"install":52,"resources":65},"01M6FKY8K1N94RDWP936FE2HM2","fix-flaky-test",null,"Reproduces and fixes flaky or quarantined tests. Tries local reproduction first (fast), then falls back to CI reproduce workflow (reproduce-flaky-tests.yml). Use this when asked to investigate, reproduce, debug, or fix a flaky test, a quarantined test, or an intermittently failing test.","microsoft\u002Faspire","microsoft","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6154722?v=4","01M698VYDXZ6JW5WH3CRV650R8","Microsoft","01M6FKTZ7ND1S9JN6JTVK7A7MD",6426,"MIT","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36],"test","fix flaky test","fix","failing","workflow","when","fixes","tests","local","back","flaky-tests","use","reproduce","investigate","first","ci","fast","debug","2026-11-10 10:12:30",false,"---\nname: fix-flaky-test\ndescription: Reproduces and fixes flaky or quarantined tests. Tries local reproduction first (fast), then falls back to CI reproduce workflow (reproduce-flaky-tests.yml). Use this when asked to investigate, reproduce, debug, or fix a flaky test, a quarantined test, or an intermittently failing test.\n---\n\nYou are a specialized agent for reproducing and fixing flaky tests in the microsoft\u002Faspire repository. You try local reproduction first using `run-test-repeatedly.sh` (Linux\u002FmacOS) or `run-test-repeatedly.ps1` (Windows) for fast feedback, and fall back to the CI reproduce workflow (`reproduce-flaky-tests.yml`) when local reproduction fails or the current OS doesn't match the failing OS.\n\n## ⛔ MANDATORY: Follow the investigate→reproduce→fix→verify cycle\n\n**Do NOT skip ahead to writing a code fix.** Even if you think you already know the root cause, you MUST follow every step in order:\n\n1. **Step 1** — Gather failure data from the issue and read the test code for understanding\n2. **Step 1.5** — Analyze existing quarantine failure logs (may reveal root cause, informs reproduction strategy)\n3. **Step 2** — Try to reproduce locally using `run-test-repeatedly.sh`\u002F`.ps1` (fast path) ← try this FIRST\n4. **Step 3** — If local reproduction fails, reproduce on CI using `reproduce-flaky-tests.yml` (graduated: single-test → quarantine-project → log-based)\n5. **Step 4** — Analyze failure logs to confirm root cause\n6. **Step 5** — Apply fix and verify (local verification first, then CI verification for final validation)\n7. **Step 6** — Clean up investigation branch and create final PR\n\nEach step has a **checkpoint** at the end. Do not proceed to the next step until the checkpoint is satisfied. Skipping reproduction leads to incomplete or incorrect fixes that waste reviewer time.\n\n## Two-Branch Workflow\n\nThis skill uses two branches to keep investigation artifacts separate from the final clean fix:\n\n### Investigation Branch (draft PR)\n- Created from the working branch (or `main`)\n- Named: `\u003Cbase-branch>-investigate` (e.g., `flaky-test0-investigate`)\n- Contains: disabled `ci.yml`, configured `reproduce-flaky-tests.yml`, code fix\n- Opened as a **draft PR** with prominent WIP marking\n- Purpose: CI verification of the fix using the reproduce workflow without triggering full CI\n\n### Fix Branch (final PR)\n- The original working branch (e.g., `flaky-test0`)\n- Contains: only the code fix (clean diff)\n- `ci.yml` enabled, `reproduce-flaky-tests.yml` at defaults\n- Created\u002Fupdated after verification succeeds on the investigation branch\n\n**Why two branches?** Pushing workflow changes (disable ci.yml, configure reproduce workflow) to the same branch as the fix would trigger unwanted CI runs and pollute the final PR diff. The investigation branch isolates this.\n\n## Top-Level Tracking\n\nUse SQL to track the overall investigation state. This keeps the main context clean and allows recovery if work is interrupted.\n\n### Initialize tracking at the start of every investigation:\n\n```sql\nINSERT INTO todos (id, title, description, status) VALUES\n  ('gather-data', 'Gather failure data', 'Read issue, find test code, determine failure rates per OS', 'pending'),\n  ('analyze-existing', 'Analyze existing quarantine logs', 'Download logs from recent quarantine failures to understand the error', 'pending'),\n  ('reproduce-local', 'Reproduce locally', 'Try local reproduction with run-test-repeatedly.sh\u002F.ps1 (fast path)', 'pending'),\n  ('reproduce-ci', 'Reproduce on CI', 'Configure and run reproduce-flaky-tests.yml: single-test first, then quarantine-project if needed', 'pending'),\n  ('analyze', 'Analyze failure logs', 'Download CI logs or review local logs, identify root cause', 'pending'),\n  ('fix', 'Apply fix', 'Write the code fix based on root cause analysis', 'pending'),\n  ('verify', 'Verify fix on CI', 'Re-run reproduce workflow to confirm fix works', 'pending'),\n  ('verify-ci', 'Verify no CI regressions', 'Confirm fix does not introduce regressions in the CI workflow', 'pending'),\n  ('cleanup', 'Clean up investigation', 'Close investigation PR, create clean fix PR', 'pending');\n\nINSERT INTO todo_deps (todo_id, depends_on) VALUES\n  ('analyze-existing', 'gather-data'),\n  ('reproduce-local', 'analyze-existing'),\n  ('reproduce-ci', 'reproduce-local'),\n  ('analyze', 'reproduce-ci'),\n  ('fix', 'analyze'),\n  ('verify', 'fix'),\n  ('verify-ci', 'verify'),\n  ('cleanup', 'verify-ci');\n```\n\n### Store key parameters in session state:\n\n```sql\nCREATE TABLE IF NOT EXISTS session_state (key TEXT PRIMARY KEY, value TEXT);\nINSERT OR REPLACE INTO session_state (key, value) VALUES\n  ('test_method', '\u003CFullyQualifiedMethodName>'),\n  ('test_project', '\u003CProjectShortname>'),\n  ('issue_url', '\u003CGitHubIssueURL>'),\n  ('failure_rate_linux', '\u003Crate or unknown>'),\n  ('failure_rate_windows', '\u003Crate or unknown>'),\n  ('failure_rate_macos', '\u003Crate or unknown>'),\n  ('max_failure_rate', '\u003Chighest rate across OSes>'),\n  ('reproduce_attempt', '1'),\n  ('reproduce_mode', 'single-test'),\n  ('fix_attempt', '1'),\n  ('reproduce_run_id', ''),\n  ('verify_run_id', ''),\n  ('investigation_branch', ''),\n  ('fix_branch', ''),\n  ('user_interaction', 'false');\n```\n\n**Always update todo status as you work** — set to `in_progress` before starting, `done` when complete. Query `SELECT * FROM todos;` to check progress. Store CI run IDs and attempt counts in `session_state`.\n\n### Tracking User Interaction\n\nIf at any point during the investigation you use the `ask_user` tool to get input from the user, immediately update the session state:\n\n```sql\nINSERT OR REPLACE INTO session_state (key, value) VALUES ('user_interaction', 'true');\n```\n\nThis flag determines whether the final PR is labeled as `[automated]` (see Step 6.2).\n\n### Investigation Notes\n\nKeep investigation notes in the **session workspace** (not in the repo). This avoids commit noise from temporary artifacts:\n\n```\n~\u002F.copilot\u002Fsession-state\u002F\u003Csession-id>\u002F\n├── plan.md                # Summary: test name, issue, root cause, fix, status\n└── files\u002F\n    └── failure-logs\u002F      # Downloaded CI failure logs (if any)\n```\n\nUse `plan.md` in the session workspace for running notes and observations. Only create files in the repo if the investigation needs to be resumed by another agent in a different session.\n\n## Overview: The Investigate→Reproduce→Fix→Verify Cycle\n\nThe steps below are sequential and gated. Complete each step fully before moving to the next.\n\n1. Gather failure data from the issue (OS-specific failure rates, error messages) and read the test code for understanding\n2. Analyze existing quarantine failure logs — informs reproduction strategy and may reveal root cause\n3. **Try to reproduce locally** using `run-test-repeatedly.sh` (Linux\u002FmacOS) or `run-test-repeatedly.ps1` (Windows) — this is the fast path (~minutes vs ~30 min for CI). Works when the current OS matches a failing OS.\n4. If local reproduction fails (wrong OS, contention-sensitive, or low failure rate), **reproduce on CI** using `reproduce-flaky-tests.yml` with graduated escalation: single-test → quarantine-project → log-based analysis\n5. Analyze failure logs to identify root cause\n6. Apply a fix. Try local verification first with `run-test-repeatedly.sh`\u002F`.ps1`, then **always validate on CI** as final verification.\n7. Clean up: close investigation branch, create clean fix PR\n\n**Prefer analyzing existing data first.** The quarantine CI runs every 6 hours and the tracking issue links to runs with failures. These logs are often sufficient to diagnose the root cause, but CI reproduction should still be attempted to establish a baseline failure rate.\n\n## Step 1: Gather Failure Data\n\n### Finding the Issue\n\nThe user may provide:\n- A **test method name** (e.g., `DeployAsync_WithMultipleComputeEnvironments_Works`)\n- A **GitHub issue URL** (e.g., `https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fissues\u002F13287`)\n- Both\n\n**If you only have the test name**, find the tracking issue:\n\n1. First check the test code for a `[QuarantinedTest]` attribute — it contains the issue URL:\n   ```bash\n   grep -rn \"QuarantinedTest\" tests\u002F --include=\"*.cs\" | grep \"TestMethodName\"\n   ```\n\n2. If not found there, look up the test in the **quarantine tracking meta-issue** https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fissues\u002F8813 — this issue tracks all quarantined tests with links to their individual issues:\n   ```bash\n   gh issue view 8813 --repo microsoft\u002Faspire\n   ```\n   Search the output for the test name to find its linked issue.\n\n3. If neither source has the issue, **proceed without historical failure data**. Use a default configuration (all 3 OSes, 5×5 iterations) since you don't know which OSes fail or the failure rate.\n\n### From the Issue\n\nQuarantined test issues contain tracking tables with per-OS failure rates over the last 100 runs. This data is critical:\n\n- **Which OSes fail**: Target only those OSes to save runner time\n- **Failure rate**: Determines how many iterations you need for reproduction\n- **Error pattern**: Helps identify root cause before reproducing\n\n```bash\n# Read the issue to get failure data\ngh issue view \u003Cissue-number> --repo microsoft\u002Faspire\n```\n\n### From the Test Code\n\nFind the test method, class, and project. **Read the test source code and its fixture\u002Fsetup** to understand what the test does, how it waits for readiness, and what patterns it uses. This is essential for understanding what you're trying to reproduce and for matching against common flaky test patterns.\n\n```bash\n# Search for the test method\ngrep -rn \"public.*async.*Task.*TestMethodName\\|public.*void.*TestMethodName\" tests\u002F --include=\"*.cs\"\n```\n\n**Consult the flaky test patterns** in `.github\u002Finstructions\u002Ftest-review-guidelines.instructions.md` early. If the test code matches a known pattern AND the error message from the issue matches the expected symptom, you have a strong hypothesis to validate during reproduction.\n\n### Iteration Count Heuristic\n\nBased on the failure rate from the issue tracking data, calculate iterations to achieve **95% probability of seeing at least one failure** (if the bug exists):\n\n| Failure Rate | Runners × Iterations per OS | Total per OS | Confidence |\n|---|---|---|---|\n| >50% | 3 × 3 | 9 | >99% |\n| 20-50% | 5 × 5 | 25 | >99% |\n| 10-20% | 5 × 10 | 50 | >99% |\n| 5-10% | 10 × 10 | 100 | >99% |\n| \u003C5% | 10 × 25 | 250 | >95% |\n\nThe math: for failure rate `p`, need `n ≥ log(0.05) \u002F log(1-p)` iterations for 95% confidence. The table above provides comfortable margins.\n\n### ✅ Step 1 Checkpoint\n\nBefore proceeding to Step 1.5, confirm you have:\n- [ ] The test method name, class, and project path\n- [ ] The issue URL (if available)\n- [ ] Per-OS failure rates (to choose target OSes and iteration counts)\n- [ ] The error message\u002Fpattern from the issue\n- [ ] Read the test source code and its fixture\u002Fsetup for understanding\n- [ ] Checked the Common Flaky Test Patterns table for matches\n- [ ] SQL tracking initialized with all parameters stored\n\n**Do NOT write a fix yet.** You have a hypothesis, but proceed to Step 1.5 to validate it with existing failure data.\n\n## Step 1.5: Analyze Existing Quarantine Failure Logs\n\nBefore running a separate reproduction, check if existing quarantine CI logs already contain the information you need. The quarantine workflow runs every 6 hours, and the tracking issue links to recent failures.\n\n### Finding Failure Logs from Quarantine Runs\n\nThe tracking issue contains ❌ links to failed quarantine runs. Use those run IDs to find the specific job that failed:\n\n```bash\n# Find the failed job for your test project in a quarantine run\ngh api \"repos\u002Fmicrosoft\u002Faspire\u002Factions\u002Fruns\u002F\u003Crun_id>\u002Fjobs?per_page=100&filter=latest\" \\\n  --jq '.jobs[] | select(.name | contains(\"\u003CProjectShortname>\")) | select(.conclusion == \"failure\") | {id: .id, name: .name}'\n```\n\nThen download the logs for that job:\n\n```bash\n# Get logs via the GitHub MCP tool (preferred — handles encoding automatically)\n# Use get_job_logs with the job_id, return_content: true, tail_lines: 300\n\n# Or via CLI\ngh api \"repos\u002Fmicrosoft\u002Faspire\u002Factions\u002Fjobs\u002F\u003Cjob_id>\u002Flogs\" > quarantine-failure.log\n```\n\nSearch the logs for the test name, error message, and stack trace:\n\n```bash\ngrep -i \"TestMethodName\\|TaskCanceled\\|Assert\\|Exception\\|FAIL\" quarantine-failure.log | head -30\n```\n\n### Identifying Contention-Sensitive Tests\n\nA test is likely **contention-sensitive** (fails only when running alongside other tests) if:\n\n1. **It uses `randomizePorts: false`** — fixed ports can conflict with other concurrent tests\n2. **It uses a shared fixture** (collection fixture or class fixture) — startup timing depends on other tests\n3. **It uses `WaitForTextAsync`** — log-based readiness checks are fragile under contention\n4. **It shares a `CancellationTokenSource` across startup and readiness phases** — one phase can starve the other's timeout budget\n5. **The tracking issue shows 0% failure on macOS** (which often has less CI contention) but failures on Linux\u002FWindows\n\nIf you identify contention-sensitive indicators, **note this for Step 3** — single-test CI reproduction may fail, and you'll need to escalate to quarantine-project mode. Do NOT skip reproduction; the graduated escalation in Step 3 handles this.\n\n### ✅ Step 1.5 Checkpoint\n\nBefore proceeding:\n- [ ] Downloaded and examined at least 1-2 quarantine failure logs for the test\n- [ ] Confirmed the error matches the pattern in the tracking issue\n- [ ] Assessed whether the test is contention-sensitive (noted for Step 3 escalation strategy)\n\nProceed to Step 2 for local reproduction.\n\n## Step 2: Try Local Reproduction (Fast Path)\n\nBefore going to CI, try reproducing the failure locally. This gives feedback in minutes instead of 30+ minutes.\n\n### 2.1: Check OS Compatibility\n\n```bash\nuname -s  # Linux, Darwin (macOS), or Windows (via MSYS\u002FGit Bash)\n```\n\nCompare your OS against the failing OSes from Step 1. Local reproduction is viable when:\n- Your OS matches one of the failing OSes, OR\n- The test fails on **all** OSes (OS-independent flakiness)\n\nIf the test only fails on an OS you don't have (e.g., fails only on Windows and you're on Linux), skip to Step 3 (CI reproduction).\n\n### 2.2: Build the Test Project\n\n```bash\n# Restore first if not already done\n.\u002Frestore.sh  # or .\u002Frestore.cmd on Windows\n\n# Build the specific test project\ndotnet build tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj -v:q\n```\n\n### 2.3: Run with run-test-repeatedly script\n\nUse the `run-test-repeatedly.sh` (Linux\u002FmacOS) or `run-test-repeatedly.ps1` (Windows) script in `.agents\u002Fskills\u002Ffix-flaky-test\u002F`. It runs the test command repeatedly with process cleanup between iterations.\n\n**Linux\u002FmacOS:**\n\n```bash\n# Basic usage — run a single test 20 times (stop on first failure)\n.\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002Frun-test-repeatedly.sh -n 20 -- \\\n  dotnet test tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-build \\\n  -- --filter-method \"*.\u003CTestMethodName>\" \\\n  --filter-not-trait \"quarantined=true\" --filter-not-trait \"outerloop=true\"\n```\n\n**Windows (PowerShell):**\n\n```powershell\n# Basic usage — run a single test 20 times (stop on first failure)\n.\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002Frun-test-repeatedly.ps1 -n 20 -- dotnet test tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-build `\n  -- --filter-method \"*.\u003CTestMethodName>\" `\n  --filter-not-trait \"quarantined=true\" --filter-not-trait \"outerloop=true\"\n```\n\n**For quarantined tests**, you need `\u002Fp:RunQuarantinedTests=true` during both build **and** test to prevent the build system from filtering them out:\n\n```bash\ndotnet build tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj -v:q \u002Fp:RunQuarantinedTests=true\n\n# Linux\u002FmacOS\n.\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002Frun-test-repeatedly.sh -n 20 -- \\\n  dotnet test tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-build \\\n  \u002Fp:RunQuarantinedTests=true \\\n  -- --filter-method \"*.\u003CTestMethodName>\"\n\n# Windows (PowerShell)\n.\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002Frun-test-repeatedly.ps1 -n 20 -- dotnet test tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-build `\n  -- --filter-method \"*.\u003CTestMethodName>\"\n```\n\n**Choose iteration count** based on failure rate (same heuristic as CI):\n\n| Failure Rate | Local Iterations | Expected failures |\n|---|---|---|\n| >50% | 10 | ~5+ |\n| 20-50% | 20 | ~4-10 |\n| 10-20% | 30 | ~3-6 |\n| 5-10% | 50 | ~2-5 |\n| \u003C5% | 100 | ~1-5 |\n\n**Script options** (same for both `.sh` and `.ps1`):\n- `-n \u003Ccount>` — Number of iterations (default: 100)\n- `--run-all` — Don't stop on first failure, run all iterations\n- `--help` — Show usage\n\nResults are saved to `\u002Ftmp\u002Ftest-results-\u003Ctimestamp>\u002F` (Linux\u002FmacOS) or `$env:TEMP\\test-results-\u003Ctimestamp>\\` (Windows). Failure logs are in `failure-*.log` files.\n\n### 2.4: Handle Local Reproduction Results\n\n**If the test fails locally**: Reproduction successful ✅. Examine the failure log:\n\n```bash\n# The script prints the results directory path\ncat \u002Ftmp\u002Ftest-results-*\u002Ffailure-*.log\n```\n\nMark `reproduce-local` as `done` in SQL and proceed to Step 4 (root cause analysis) using the local failure logs.\n\n```sql\nUPDATE todos SET status = 'done' WHERE id = 'reproduce-local';\nUPDATE todos SET status = 'done' WHERE id = 'reproduce-ci';  -- skip CI reproduction\nUPDATE todos SET status = 'in_progress' WHERE id = 'analyze';\n```\n\n**If the test passes all local iterations**: Local reproduction failed. This can happen because:\n- The failure is OS-specific and you're on the wrong OS\n- The failure is contention-sensitive (only happens with parallel tests)\n- The failure rate is very low and you didn't run enough iterations\n\nProceed to Step 3 (CI reproduction) for cross-OS, parallel-runner reproduction.\n\n```sql\nUPDATE todos SET status = 'done' WHERE id = 'reproduce-local';\nINSERT OR REPLACE INTO session_state (key, value) VALUES ('local_result', 'no_failures');\n```\n\n### ✅ Step 2 Checkpoint\n\n- [ ] Checked OS compatibility\n- [ ] Ran `run-test-repeatedly.sh`\u002F`.ps1` with appropriate iteration count (or skipped due to OS mismatch)\n- [ ] Recorded result: local failure found → proceed to Step 4, or no failures → proceed to Step 3\n\n## Step 3: Reproduce on CI (Fallback)\n\n### 3.0: Create the Investigation Branch\n\nCreate a separate branch for CI investigation. This branch will have `ci.yml` disabled and `reproduce-flaky-tests.yml` configured, keeping the fix branch clean.\n\n```bash\n# Create investigation branch from the current working branch\ngit checkout -b \u003Cfix-branch>-investigate\n\n# Store the branch names\n```\n\n```sql\nINSERT OR REPLACE INTO session_state (key, value) VALUES\n  ('investigation_branch', '\u003Cfix-branch>-investigate'),\n  ('fix_branch', '\u003Cfix-branch>');\n```\n\n### 3.0a: Disable ci.yml\n\nDisable `ci.yml` so pushing to the investigation branch doesn't trigger full CI:\n\n```yaml\n# .github\u002Fworkflows\u002Fci.yml — add this at the top level, after `name:`\n# Change the `on:` trigger to disable automatic runs:\non:\n  workflow_dispatch: {}  # Only manual trigger, no automatic PR\u002Fpush triggers\n```\n\nThis prevents CI from running on every push to the investigation branch. You will re-enable it when creating the final fix PR.\n\n### 3.1: Configure the Reproduce Workflow\n\nEdit `.github\u002Fworkflows\u002Freproduce-flaky-tests.yml` — change only the `env:` section at the top:\n\n```yaml\nenv:\n  TEST_PROJECT: \"Hosting.Azure\"  # Project shortname\n  TEST_FILTER: '--filter-method \"*.DeployAsync_WithMultipleComputeEnvironments_Works\"'\n  TARGET_OSES: \"windows-latest\"  # Focus on highest-failure-rate OS\n  RUNNERS_PER_OS: \"5\"\n  ITERATIONS_PER_RUNNER: \"5\"\n```\n\n**OS targeting strategy:**\n- **High failure rate (>20%) on one OS**: Target that OS only first — fastest feedback\n- **High rate on multiple OSes**: Target all failing OSes\n- **Low rate or can't reproduce**: Focus on the OS with the highest failure rate, increase iterations\n- **Unknown rates**: Target `ubuntu-latest,windows-latest` with moderate iterations\n\n**Test project shortname mapping**: The workflow resolves `TEST_PROJECT` to a path:\n- Tries `tests\u002F{name}.Tests\u002F{name}.Tests.csproj` first\n- Then `tests\u002FAspire.{name}.Tests\u002FAspire.{name}.Tests.csproj`\n- Examples: `Hosting` → `Aspire.Hosting.Tests`, `Hosting.Azure` → `Aspire.Hosting.Azure.Tests`\n\n**Common filter patterns**:\n```yaml\n# Single test method\nTEST_FILTER: '--filter-method \"*.TestMethodName\"'\n# All tests in a class\nTEST_FILTER: '--filter-class \"*.TestClassName\"'\n# Multiple test methods\nTEST_FILTER: '--filter-method \"*.Test1\" --filter-method \"*.Test2\"'\n```\n\n**For quarantined tests**: The workflow automatically disables the quarantine exclusion filter for both build and test phases (via `\u002Fp:_NonQuarantinedTestRunAdditionalArgs=\"\"`), so quarantined tests are included regardless of their trait. You do NOT need to add any special flags.\n\n**Zero-test detection**: The workflow detects when zero tests execute (e.g., due to a misconfigured filter) and treats it as a failure. If you see \"Zero tests executed\" errors, verify that `TEST_FILTER` matches the actual test name and that quarantine settings are correct.\n\n### 3.2: Push and Open Draft PR\n\nCommit the workflow changes and open a **draft PR** with the investigation template:\n\n```bash\ngit add .github\u002Fworkflows\u002Fci.yml .github\u002Fworkflows\u002Freproduce-flaky-tests.yml\ngit commit -m \"? Investigation: configure CI for flaky test reproduction\n\n⚠️ DO NOT MERGE — This is a temporary investigation branch.\nci.yml disabled, reproduce workflow configured for \u003Ctest name>.\"\ngit push --set-upstream origin \u003Cfix-branch>-investigate\n```\n\nOpen a draft PR with prominent WIP marking:\n\n```bash\ngh pr create --draft --repo microsoft\u002Faspire \\\n  --title \"? [DO NOT MERGE] Investigation: \u003Ctest name>\" \\\n  --body \"## ⚠️ DO NOT MERGE — Investigation Branch\n\nThis is a temporary branch for reproducing and verifying a fix for a flaky test.\n\n**Issue**: #\u003Cissue-number>\n**Test**: \\`\u003CFullyQualifiedTestName>\\`\n\n### What's changed on this branch\n- \\`ci.yml\\` disabled (prevents full CI on investigation pushes)\n- \\`reproduce-flaky-tests.yml\\` configured for the target test\n- Code fix (will be applied after reproduction)\n\n### Status\n- [ ] Reproduction confirmed\n- [ ] Fix applied\n- [ ] Fix verified on CI\n- [ ] Clean fix PR created\n\nThis branch will be deleted after the fix is verified and a clean PR is created.\"\n```\n\n### 3.3: Trigger the Reproduce Workflow\n\n```bash\ngh workflow run reproduce-flaky-tests.yml --repo microsoft\u002Faspire --ref \u003Cfix-branch>-investigate\n```\n\nThis dispatches the workflow from `main` but runs the version from your branch, so your env var edits will be used.\n\n**If the workflow dispatch fails** (e.g. HTTP 403 \"Resource not accessible by integration\"): your GitHub token lacks `actions:write` permission on the repository. This is a non-fatal blocker — continue with the investigation, but you **must** document this in every PR you open (both investigation and fix PRs). Include the exact error, and provide the manual trigger command so a reviewer or maintainer can run it. See the PR template in Step 6.2 for the required format.\n\n### 3.4: Monitor and Cancel\n\n**Monitor the run using polling** (CI runs take 10-30+ minutes):\n\n```bash\n# Find the run ID\ngh run list --repo microsoft\u002Faspire --branch \u003Cbranch> --limit 1 --json databaseId,status\n```\n\nStore the run ID, then poll periodically for completion:\n```sql\nINSERT OR REPLACE INTO session_state (key, value) VALUES ('reproduce_run_id', '\u003Crun-id>');\n```\n\n```bash\n# Poll for completion (use bash mode=\"async\", then read_bash with increasing delays)\n# Avoid `gh run watch` — it produces excessive output that floods the context window.\ngh run view \u003Crun-id> --repo microsoft\u002Faspire --json status,conclusion --jq '{status, conclusion}'\n\n# Check individual job results as they complete\ngh run view \u003Crun-id> --repo microsoft\u002Faspire --json jobs \\\n  --jq '.jobs[] | select(.status == \"completed\") | {name: .name, conclusion: .conclusion}'\n```\n\n**Cancel old runs** when starting new ones to avoid wasting CI resources:\n\n```bash\n# Cancel a specific run\ngh run cancel \u003Crun-id> --repo microsoft\u002Faspire\n\n# Cancel all in-progress runs on your branch (useful when iterating)\ngh run list --repo microsoft\u002Faspire --branch \u003Cbranch> --status in_progress --json databaseId --jq '.[].databaseId' | \\\n  xargs -I {} gh run cancel {} --repo microsoft\u002Faspire\n```\n\nAlways cancel previous reproduce\u002Fverify runs before pushing a new configuration. `workflow_dispatch` runs are NOT auto-cancelled, so you must cancel them manually.\n\n### 3.5: Handle Reproduction Results\n\n**⛔ GATE: Do not proceed past this point until the CI run has completed.**\n\nIf there are failure artifacts, download them:\n\n```bash\n# Download failure artifacts\ngh run download \u003Crun-id> --repo microsoft\u002Faspire --dir \u002Ftmp\u002Ffailure-logs\n\n# Or get logs directly via the GitHub API \u002F MCP tools\ngh api \"repos\u002Fmicrosoft\u002Faspire\u002Factions\u002Fjobs\u002F\u003Cjob_id>\u002Flogs\" > \u002Ftmp\u002Ffailure.log\n```\n\n**Distinguishing test failures from infrastructure failures:**\n\nCI runners sometimes fail due to infrastructure issues, NOT the test itself. Common infrastructure failures include:\n- `Failed to install or invoke dotnet...` (exit code -1073741502 on Windows)\n- `The runner has received a shutdown signal` or runner timeouts\n- Network connectivity errors during `dotnet restore`\n\n**These do NOT count as reproductions.** Check the actual error message — only count iterations where the **test itself** failed with the expected error pattern from the tracking issue.\n\n**If some runners show test failures (the expected error)**: Reproduction successful ✅. Proceed to Step 4.\n\n**If no runners show the expected test failure — scale up and retry:**\n\n```sql\n-- Track the scaling attempt\nINSERT OR REPLACE INTO session_state (key, value)\nVALUES ('reproduce_attempt', CAST((SELECT CAST(value AS INTEGER) FROM session_state WHERE key = 'reproduce_attempt') + 1 AS TEXT));\n```\n\nScale up progressively, focusing on the OS most likely to fail first (based on per-OS failure rates from the issue). Go back to Step 3.1 after each change:\n\n| Attempt | `TARGET_OSES` | `RUNNERS_PER_OS` | `ITERATIONS_PER_RUNNER` | Notes |\n|---------|---------------|-------------------|--------------------------|-------|\n| 1 | Highest-failure-rate OS only | From heuristic table | From heuristic table | Start narrow — one OS, sized by failure rate |\n| 2 | Same single OS | Same | 2× previous | Double `ITERATIONS_PER_RUNNER` only |\n\n**Upper bounds**: Do not exceed `RUNNERS_PER_OS=10` or `ITERATIONS_PER_RUNNER=50` (total matrix entries must stay ≤ 256 per GitHub Actions limits).\n\n**If 2 attempts produce zero test failures → escalate to quarantine-project mode (Step 3.6).**\n\n### 3.6: Quarantine-Project Mode (Contention Escalation)\n\nWhen single-test reproduction fails, the test likely only fails under contention with other tests. Escalate by running **all quarantined tests in the assembly**, which matches what `tests-quarantine.yml` does:\n\nEdit `.github\u002Fworkflows\u002Freproduce-flaky-tests.yml` — change the `TEST_FILTER` to target all quarantined tests:\n\n```yaml\nenv:\n  TEST_PROJECT: \"\u003Csame project>\"\n  TEST_FILTER: '--filter-trait \"quarantined=true\"'  # Run all quarantined tests in this assembly\n  TARGET_OSES: \"\u003Csame as before>\"\n  RUNNERS_PER_OS: \"3\"\n  ITERATIONS_PER_RUNNER: \"3\"\n```\n\nThis recreates the contention environment from the quarantine workflow. Push, trigger, and monitor as before.\n\n**If quarantine-project mode reproduces the failure**: Reproduction successful ✅. Proceed to Step 4. Note: verification (Step 5) should use the same quarantine-project mode to confirm the fix.\n\n**If quarantine-project mode also produces zero failures**: The test requires heavier contention than we can simulate on demand. In this case:\n1. Fall back to analyzing existing quarantine failure logs (from Step 1.5)\n2. Read the test code to identify contention indicators (shared ports, shared fixtures, sequential waits)\n3. Proceed to Step 4 using quarantine logs as your failure evidence\n4. The verification run (Step 5) will still validate your fix in isolation, which is useful even if you can't reproduce the original failure\n5. Note in the PR description that reproduction required full CI contention and the fix relies on log analysis + quarantine monitoring for confirmation\n\n```sql\nINSERT OR REPLACE INTO session_state (key, value) VALUES ('reproduce_mode', 'log-based');\n```\n\n**CRITICAL: Windows log encoding gotcha**\n\nWindows CI log files downloaded as artifacts are encoded as **UTF-16LE**. Running `cat` on them produces garbled output. Convert first:\n\n```bash\n# Convert Windows log to readable UTF-8\niconv -f UTF-16LE -t UTF-8 \u002Ftmp\u002Ffailure-logs\u002Ffailures-windows-latest-1\u002Ftest-output.log > \u002Ftmp\u002Freadable-windows.log\ncat \u002Ftmp\u002Freadable-windows.log\n```\n\n**Tip**: Using `get_job_logs` via GitHub API\u002FMCP tools returns UTF-8 directly, avoiding encoding issues entirely. Prefer API-based log retrieval when possible.\n\n**Alternatively**, search for the error directly:\n\n```bash\n# Search across all failure logs (handles encoding)\nfind \u002Ftmp\u002Ffailure-logs -name \"*.log\" -exec grep -l \"Assert\\|Error\\|Exception\" {} \\;\n```\n\n## Step 4: Identify Root Cause\n\n### Interpreting Reproduction Results\n\n- **Some runners fail, some pass**: This is the expected pattern for a flaky test. Proceed to analyze the failures.\n- **All runners fail (100%)**: Compare against the failure rate from the tracking issue. If the issue says e.g. 84% and you see 100%, that's consistent — proceed. But if the issue says e.g. 10% and you see 100%, this may be an **unrelated issue** (e.g., a build break, a new dependency problem). Investigate whether the failure is the same error as reported in the issue before attempting a fix.\n- **No runners fail**: The test may not be reliably reproducible with your current iteration count. Increase `RUNNERS_PER_OS` and `ITERATIONS_PER_RUNNER` and try again.\n\n### Analyzing Failure Logs\n\nFailure logs may come from local runs (Step 2, in `\u002Ftmp\u002Ftest-results-*\u002F`), CI reproduce runs (Step 3), or existing quarantine runs (Step 1.5). All are valid sources.\n\n**Preferred: Use GitHub API\u002FMCP tools** to get logs directly (avoids encoding issues):\n\n```bash\n# Get job logs via GitHub MCP tool: get_job_logs with job_id, return_content: true, tail_lines: 300\n# Or via CLI:\ngh api \"repos\u002Fmicrosoft\u002Faspire\u002Factions\u002Fjobs\u002F\u003Cjob_id>\u002Flogs\" > \u002Ftmp\u002Ffailure.log\n```\n\n**Delegate log analysis to a sub-agent** to keep the main context clean:\n\n```\nUse a task agent (explore or general-purpose) to analyze the failure logs:\n- Pass the log file paths or content\n- Ask it to identify the specific assertion\u002Fexception\n- Ask it to read the test source code and identify the concurrency\u002Ftiming model\n- Have it return a structured root cause summary\n```\n\nLook for the assertion or exception that failed:\n\n```bash\n# Find the actual test failure in logs\ngrep -A 10 \"FAIL\\|Assert\\.\\|Exception\" \u002Ftmp\u002Ffailure.log | head -50\n\n# For .trx files (XML test results) from downloaded artifacts\nfind \u002Ftmp\u002Ffailure-logs -name \"*.trx\" -exec grep -l 'outcome=\"Failed\"' {} \\;\n```\n\nThen find the corresponding test code and understand the concurrency\u002Ftiming model.\n\n### ✅ Step 4 Checkpoint\n\nBefore proceeding to Step 5, confirm you have:\n- [ ] Examined CI failure logs (from reproduce runs OR existing quarantine runs)\n- [ ] Identified the specific error (assertion failure, exception, timeout)\n- [ ] Read the test source code and identified the root cause\n- [ ] Documented the root cause in your session plan\n\n**Now — and only now — proceed to write the fix.**\n\n## Step 5: Apply Fix and Verify\n\n> **⚠️ DO NOT remove the `[QuarantinedTest]` attribute or close the tracking issue.** Unquarantining is a separate process that happens after 21 days of zero failures in quarantine CI. Your fix PR should contain _only_ the code fix. See Step 6.5 for details.\n\n### 5.1: Apply the Fix\n\n1. Make the code change\n2. **Build locally to confirm it compiles**:\n   ```bash\n   dotnet build tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-restore -v:q\n   ```\n3. Keep `reproduce-flaky-tests.yml` configured for the same test\n\n### 5.2: Local Verification (Fast Pre-Check)\n\n> **Principle: Local runs are a fast pre-check, not a substitute for CI.** Running a test N times on one machine does not have the same statistical power as N runs across separate CI runners. Some flakiness stems from environmental variation (machine load, Docker daemon state, network conditions) that a single machine cannot reproduce. Local verification catches obvious regressions quickly and saves CI round-trips, but CI verification is always required as the final gate.\n\nIf local reproduction succeeded in Step 2, run a quick local verification first:\n\n```bash\n# Rebuild with fix\ndotnet build tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-restore -v:q\n\n# Quick local check — same iteration count as reproduction\n# Linux\u002FmacOS:\n.\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002Frun-test-repeatedly.sh -n 20 -- \\\n  dotnet test tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-build \\\n  -- --filter-method \"*.\u003CTestMethodName>\"\n# Windows (PowerShell):\n# .\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002Frun-test-repeatedly.ps1 -n 20 -- dotnet test tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-build -- --filter-method \"*.\u003CTestMethodName>\"\n```\n\nIf local verification fails, iterate on the fix before going to CI. This saves ~30 minutes per CI round-trip.\n\n### 5.3: Choose CI Verification Scale\n\nCI verification is always required. However, the scale should reflect your **local confidence** — how much evidence you already have that the fix is correct.\n\n#### Assessing Local Confidence\n\nConsider these factors to determine how aggressively to scale CI verification:\n\n**Higher confidence** (scale CI down):\n- Root cause matches a well-known flaky pattern (from the patterns reference)\n- Fix is a mechanical pattern application (e.g., replacing bare `HttpClient` with resilient one)\n- Local reproduction succeeded and the fix eliminated the failure\n- Current OS matches the primarily affected OS\n- Failure rate is high (>20%), making local runs more meaningful\n\n**Lower confidence** (scale CI up):\n- Root cause is a hypothesis, not confirmed by reproduction\n- Fix involves behavioral changes or new logic\n- Local reproduction failed (wrong OS, contention-sensitive, or very low failure rate)\n- Failure is OS-specific and you're on a different OS\n- Failure rate is low (\u003C10%), meaning local runs provide weak signal\n\n#### CI Scale Heuristic\n\nUse the **original failure rate** combined with your local confidence to size the CI verification. The base scale ensures that if the bug were still present, it would manifest with ≥95% probability (`n ≥ log(0.05) \u002F log(1-p)`):\n\n| Original Failure Rate | High Confidence (CI scale) | Low Confidence (CI scale) |\n|---|---|---|\n| >50% | 3 × 3 per OS (9 total) | 3 × 3 per OS (9 total) |\n| 20-50% | 3 × 5 per OS (15 total) | 5 × 5 per OS (25 total) |\n| 10-20% | 5 × 5 per OS (25 total) | 5 × 10 per OS (50 total) |\n| 5-10% | 5 × 10 per OS (50 total) | 10 × 10 per OS (100 total) |\n| \u003C5% | 10 × 10 per OS (100 total) | 10 × 25 per OS (250 total) |\n\nFor tests with very low failure rates (\u003C5%), consider whether the verification is practical within CI budget constraints. If not, document the limitation and rely on the 21-day quarantine monitoring to confirm.\n\n**For contention-sensitive tests** (where quarantine-project mode was needed for reproduction): Use the **same quarantine-project `TEST_FILTER`** for verification. This ensures the fix is validated under the same contention conditions where the failure was observed. If reproduction fell back to log-based analysis, use the low-confidence column and note in the PR that definitive confirmation relies on the 21-day quarantine monitoring.\n\n### 5.4: Push and Verify on CI\n\nPush the fix to the **investigation branch** (where reproduce workflow is already configured):\n\n```bash\ngit add -A\ngit commit -m \"Fix flaky test: \u003Cdescription of fix>\"\ngit push\n```\n\nThen trigger the reproduce workflow to verify:\n\n```bash\ngh workflow run reproduce-flaky-tests.yml --repo microsoft\u002Faspire --ref \u003Cfix-branch>-investigate\n```\n\nIf the workflow dispatch fails due to permissions (HTTP 403), see the guidance in Step 3.3. Continue to Step 6 but document the failure in the PR description.\n\nStore the verification run ID:\n```sql\nINSERT OR REPLACE INTO session_state (key, value) VALUES ('verify_run_id', '\u003Crun-id>');\nINSERT OR REPLACE INTO session_state (key, value) VALUES ('fix_attempt', '1');\n```\n\nWait for CI to complete. Monitor with polling (`gh run view --json status,conclusion`), not `gh run watch`.\n\n### 5.5: Handle Verification Results\n\n**If all iterations pass across all OSes**: The fix is validated ✅. Proceed to Step 6.\n\n**If some iterations still fail**: The fix is incomplete or incorrect. Iterate:\n\n```sql\n-- Track the fix attempt\nINSERT OR REPLACE INTO session_state (key, value)\nVALUES ('fix_attempt', CAST((SELECT CAST(value AS INTEGER) FROM session_state WHERE key = 'fix_attempt') + 1 AS TEXT));\n```\n\n1. Download the new failure logs:\n   ```bash\n   gh run download \u003Crun-id> --repo microsoft\u002Faspire --dir \u002Ftmp\u002Ffailure-logs\n   ```\n2. Analyze the new failure pattern — is it the same error or a different one?\n3. Refine the fix based on the new evidence\n4. Push and re-verify\n\n**After 3 failed fix attempts**: Stop and report findings to the user. The issue may require deeper architectural changes or domain expertise.\n\n## Step 6: Clean Up and Create Final PR\n\nAfter the fix is verified on the investigation branch, create a clean fix PR.\n\n### 6.0: Cancel Any Remaining CI Runs\n\nCancel any in-progress reproduce or verify runs that are no longer needed:\n\n```bash\n# List and cancel any remaining runs on your branch\ngh run list --repo microsoft\u002Faspire --branch \u003Cbranch> --status in_progress --json databaseId,name --jq '.[] | \"\\(.databaseId) \\(.name)\"'\ngh run cancel \u003Crun-id> --repo microsoft\u002Faspire\n```\n\n### 6.1: Cherry-Pick Fix to the Clean Branch\n\nSwitch back to the fix branch and cherry-pick only the code fix commits (not the workflow changes):\n\n```bash\ngit checkout \u003Cfix-branch>\n\n# Cherry-pick the fix commit(s) from the investigation branch\ngit cherry-pick \u003Cfix-commit-sha>\n\n# Verify the fix branch has NO workflow changes\ngit diff main -- .github\u002Fworkflows\u002F  # Should be empty\n```\n\n### 6.1.1: Clean Up Git History\n\nBefore pushing, ensure the fix branch has a clean, linear history with **only** the code fix commit(s). If intermediate commits crept in (e.g. workflow config changes, reverts, debug attempts), squash them down:\n\n```bash\n# Interactive rebase to squash noise commits into the fix\ngit rebase -i $(git merge-base HEAD main)\n\n# In the editor, mark the fix commit as \"pick\" and any noise commits as \"fixup\" or \"drop\"\n# Save and close\n\n# Verify: the branch should have only fix-related commits\ngit log --oneline main..HEAD\n\n# Verify: no unintended file changes\ngit diff main -- .github\u002Fworkflows\u002F  # Should be empty\n```\n\n**Why this matters**: A clean history makes the PR easy to review and avoids confusing commit pairs (config + revert) that produce no net change but clutter the log.\n\n### 6.2: Push and Open Final PR\n\n```bash\ngit push\n```\n\n**Determine the PR title prefix**: Check whether any user interaction occurred during the investigation:\n\n```sql\nSELECT value FROM session_state WHERE key = 'user_interaction';\n```\n\n- If `user_interaction` is `'false'`: prefix the PR title with `[automated] `\n- If `user_interaction` is `'true'`: no prefix\n\nOpen a non-draft PR with the fix. The PR body **must** include a note that it was created using the fix-flaky-test skill:\n\n```bash\ngh pr create --repo microsoft\u002Faspire \\\n  --title \"\u003Cprefix>Fix flaky test: \u003Cdescription>\" \\\n  --body \"## Flaky Test Fix\n\n### Test\n- **Method**: \\`\u003Cfully qualified test name>\\`\n- **Issue**: #\u003Cissue-number>\n\n### Root Cause\n\u003C1-2 sentence description of the root cause>\n\n### Fix\n\u003C1-2 sentence description of what was changed>\n\n### Verification\n| Run | Config | Result |\n|-----|--------|--------|\n| Pre-fix (local) | \u003Citerations>, \u003COS> | **\u003Cpass\u002Ffail>** |\n| Post-fix (local) | \u003Citerations>, \u003COS> | **\u003Cpass\u002Ffail>** |\n| Post-fix (CI) | \u003Crunners × iters × OSes> | **\u003Clink to run>** |\n\n> **If any verification step was skipped or failed** (e.g. workflow dispatch permission error), replace the CI row with a clear explanation:\n> - What step failed and the exact error (e.g. \\\\\\`HTTP 403: Resource not accessible by integration\\\\\\`)\n> - Why it could not be completed (e.g. agent token lacks \\\\\\`actions:write\\\\\\` permission)\n> - The manual command a reviewer can run to complete verification\n> - A link to the investigation PR\u002Fbranch with the pre-configured reproduce workflow\n\n### Verification Rationale\n\u003CBrief explanation of CI scale choice: local confidence level, why that scale was appropriate for the failure rate, and acknowledgment that local runs are a pre-check — not equivalent to CI runs across separate runners.>\n\n### Notes\n- \\`[QuarantinedTest]\\` attribute kept — unquarantining will happen separately after 21 days of zero failures in quarantine CI\n\n---\n> **Note:** This PR intentionally does not close #\u003Cissue-number>. The test will remain quarantined until a separate unquarantine process confirms it has been stable (zero failures) for a sufficient period. Once stability is confirmed, the test will be unquarantined and the issue will be closed.\n\n---\n*This fix was generated using the [fix-flaky-test skill](https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002FSKILL.md).*\"\n```\n\n**If `gh pr create` fails** (e.g. permissions error, API failure): Do **NOT** delete the branch or undo the work. Instead:\n1. Ensure the clean fix branch is pushed to the remote\n2. Tell the user the PR could not be opened, include the exact error message\n3. Provide the branch name and a direct link they can use to open the PR manually (e.g. `https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fcompare\u002Fmain...\u003Cbranch-name>`)\n\n### 6.3: Close the Investigation PR\n\n```bash\n# Close the investigation draft PR\ngh pr close \u003Cinvestigation-pr-number> --repo microsoft\u002Faspire --delete-branch\n```\n\n### 6.4: Verify No CI Regressions\n\nAfter opening the final PR, the regular CI pipeline (`ci.yml`) will run automatically. Monitor it to confirm the fix does not introduce regressions:\n\n```bash\n# Find the CI run for your PR\ngh pr checks \u003Cpr-number> --repo microsoft\u002Faspire\n```\n\nIf CI fails on unrelated tests, that's not your problem — note it in the PR. If CI fails on your changed files or the test project you modified, investigate and fix before marking the task complete.\n\n```sql\nUPDATE todos SET status = 'done' WHERE id = 'verify-ci';\n```\n\n### 6.5: DO NOT Unquarantine or Close the Issue\n\n**Important policy**: A code fix alone is not sufficient to unquarantine a test. The test must have **zero failures across all OSes for 21 consecutive days** in the quarantine CI runs before it can be unquarantined. See `docs\u002Funquarantine-policy.md`.\n\n- **DO NOT** remove the `[QuarantinedTest]` attribute\n- **DO NOT** close the tracking issue\n- A separate process monitors the quarantine CI and handles unquarantining when the 21-day criteria are met\n\n### ✅ Final Validation Checklist\n\nBefore opening the final PR, verify **every item**. This is a hard gate — do not skip any item.\n\n- [ ] Fix is verified on CI via the reproduce workflow (all iterations pass), **OR** if CI could not be triggered (e.g. permissions error), the PR description documents the failure, the exact error, and provides the manual trigger command for a reviewer\n- [ ] **`[QuarantinedTest]` attribute is still present** on the test method (not removed)\n- [ ] **Tracking issue is still open** (not closed)\n- [ ] Clean fix PR is open with only code changes (no workflow modifications)\n- [ ] **Git history is clean**: only fix-related commits, no leftover config\u002Frevert pairs (squash if needed)\n- [ ] PR description includes verification rationale (local confidence, CI scale reasoning)\n- [ ] PR description documents any skipped or failed steps with exact errors and manual remediation commands\n- [ ] Investigation draft PR is closed and branch deleted\n- [ ] No remaining in-progress CI runs on the investigation branch\n- [ ] Summary comment posted (see Response Format below)\n\n**Self-check**: Run `git diff` on the fix branch and scan for any unintended changes — removed test attributes, workflow file edits, or unrelated modifications.\n\n```sql\nUPDATE todos SET status = 'done' WHERE id = 'cleanup';\n```\n\n## Key Technical Details\n\n### Build System Quarantine Filtering\n\n`eng\u002FTesting.targets` auto-appends `--filter-not-trait \"quarantined=true\"` to test arguments via the `TestRunnerAdditionalArguments` MSBuild property. The filter value is defined in `eng\u002FTesting.props`, and the composed property is evaluated during `dotnet test` even with `--no-build`, so it must be handled in both build and test commands:\n\n- **Reproduce workflow**: Overrides `_NonQuarantinedTestRunAdditionalArgs` to empty, removing the quarantine exclusion filter for all tests\n- **Local reproduction**: Pass `\u002Fp:RunQuarantinedTests=true` to both `dotnet build` and `dotnet test`\n\n`Testing.targets` also adds `--ignore-exit-code 8` via `MtpBaseArgs`, which masks zero-test runs as successes. The workflow and `run-test-repeatedly` scripts detect this by checking test output for the `Total:` count indicator.\n\n### test-reproduce.yml Architecture\n\nThe workflow:\n1. **Setup job**: Parses env vars, generates a matrix of `{os, index}` combinations\n2. **Reproduce jobs** (parallel): Each runner builds the test project once, then loops through iterations with DCP process cleanup between runs\n3. **Results job**: Aggregates pass\u002Ffail across all runners into a summary table\n\nFailed iterations upload their test output as artifacts named `failures-\u003Cos>-\u003Cindex>`.\n\n### workflow_dispatch Behavior\n\n`workflow_dispatch` requires the workflow file to exist on the **default branch** (`main`). Key implications:\n\n- You can dispatch it against any branch with `gh workflow run reproduce-flaky-tests.yml --ref \u003Cbranch>`. GitHub discovers the workflow from `main` but runs the version from the specified `--ref`. This means your investigation branch's env var edits will be used.\n- The investigation branch has `ci.yml` disabled, so pushes don't trigger full CI — only `workflow_dispatch` of the reproduce workflow is used.\n- **Creating a new workflow file on a feature branch won't help** — GitHub won't discover it via `workflow_dispatch` until it's merged to `main`.\n\n## Response Format\n\nAfter completing a flaky test fix, provide a summary:\n\n```markdown\n## Flaky Test Fix Summary\n\n### Test\n- **Method**: `Namespace.Type.Method`\n- **Issue**: #XXXXX\n- **Project**: `tests\u002FAspire.{Project}.Tests\u002F`\n\n### Failure Data\n| OS | Failure Rate |\n|---|---|\n| Windows | XX% |\n| Linux | XX% |\n\n### Root Cause\nBrief description of what caused the flaky behavior.\n\n### Fix\nDescription of the code change.\n\n### Verification\n| Run | Config | Result |\n|-----|--------|--------|\n| Pre-fix | X runners × Y iters × Z OSes | N failures ❌ |\n| Post-fix | X runners × Y iters × Z OSes | All passed ✅ |\n\n### Files Changed\n- `path\u002Fto\u002Ffile.cs` — description\n\n### Next Steps\n- Test remains quarantined — will be unquarantined after 21 days of zero failures\n- Issue #XXXXX remains open — will be closed by the unquarantine process\n```\n\n## Important Constraints\n\n- **Reproduce before fixing**: Always confirm the failure is reproducible before attempting a fix — try locally first, then CI. Use graduated escalation: single-test → quarantine-project → log-based (see Steps 3.5 and 3.6)\n- **Try local first**: Use `run-test-repeatedly.sh` (Linux\u002FmacOS) or `run-test-repeatedly.ps1` (Windows) for fast feedback (~minutes). Fall back to CI when local reproduction fails (wrong OS, contention-sensitive, very low failure rate)\n- **Detect your OS**: Check with `uname -s` to decide if local reproduction is viable for the failing OS\n- **Quarantined tests need \u002Fp:RunQuarantinedTests=true**: The build system filters them out by default. Pass this property to both `dotnet build` and `dotnet test` commands for local reproduction. The CI reproduce workflow handles this automatically.\n- **Watch for zero-test runs**: If the test runner reports zero tests executed (exit code 8, masked by `--ignore-exit-code 8`), the filter or quarantine settings are misconfigured. The `run-test-repeatedly` scripts and reproduce workflow detect this automatically.\n- **Keep investigation notes in session workspace**: Use `plan.md` and `files\u002F` in the session workspace, not a directory in the repo\n- **Use two branches**: Investigation branch (draft PR with disabled ci.yml) for reproduce\u002Fverify; fix branch (clean PR with only code changes) for the final submission\n- **Distinguish infrastructure vs test failures**: CI runners sometimes fail due to infrastructure issues (e.g., `Failed to install or invoke dotnet...` on Windows). These do NOT count as test reproductions. Always verify the error matches the expected test failure pattern.\n- **DO NOT unquarantine or close issue**: The test stays quarantined until 21 days of zero failures (see `docs\u002Funquarantine-policy.md`)\n- **Scale verification to failure rate**: A 50% failure rate test needs fewer verification iterations than a 5% failure rate test. Use the verification heuristic table.\n- **Match verification mode to reproduction mode**: If reproduction required quarantine-project mode, use the same mode for verification. Store the mode in `session_state` (`reproduce_mode`).\n- **Target specific OSes**: Focus on the OS with the highest failure rate first. Only expand to multiple OSes when the rate is high (>20%) on multiple OSes or when initial attempts don't reproduce.\n- **Build-verify everything**: After fixes, after any test attribute changes\n- **Don't fix unrelated issues**: If you encounter unrelated test failures, ignore them\n- **Windows UTF-16LE**: Always handle encoding when reading Windows CI logs downloaded as files (not needed when using `get_job_logs` via GitHub API\u002FMCP, which returns UTF-8)\n- **Prefer polling over `gh run watch`**: Use `gh run view --json status,conclusion` to check CI status — `gh run watch` produces excessive output that floods the context window\n- **Use sub-agents for heavy work**: Delegate log analysis and CI monitoring to sub-agents to keep main context clean\n- **Track state in SQL**: Use the todos table and session_state for tracking progress across the investigate→reproduce→fix→verify cycle\n\n## Appendix: Flaky Test Patterns Reference\n\nCommon flaky test patterns are documented in `.github\u002Finstructions\u002Ftest-review-guidelines.instructions.md`. Consult that file during Step 1 (gather data) to form hypotheses, and during Step 4 (analysis) to confirm root causes.\n","You are a specialized agent for reproducing and fixing flaky tests in the microsoft\u002Faspire repository. You try local reproduction first using `run-test-repeatedly.sh` (Linux\u002FmacOS) or `run-test-repeatedly.ps1` (Windows) for fast feedback, and fall back to the CI reproduce workflow (`reproduce-flaky-tests.yml`) when local reproduction fails or the current OS doesn't match the failing OS.\n\n## ⛔ MANDATORY: Follow the investigate→reproduce→fix→verify cycle\n\n**Do NOT skip ahead to writing a code fix.** Even if you think you already know the root cause, you MUST follow every step in order:\n\n1. **Step 1** — Gather failure data from the issue and read the test code for understanding\n2. **Step 1.5** — Analyze existing quarantine failure logs (may reveal root cause, informs reproduction strategy)\n3. **Step 2** — Try to reproduce locally using `run-test-repeatedly.sh`\u002F`.ps1` (fast path) ← try this FIRST\n4. **Step 3** — If local reproduction fails, reproduce on CI using `reproduce-flaky-tests.yml` (graduated: single-test → quarantine-project → log-based)\n5. **Step 4** — Analyze failure logs to confirm root cause\n6. **Step 5** — Apply fix and verify (local verification first, then CI verification for final validation)\n7. **Step 6** — Clean up investigation branch and create final PR\n\nEach step has a **checkpoint** at the end. Do not proceed to the next step until the checkpoint is satisfied. Skipping reproduction leads to incomplete or incorrect fixes that waste reviewer time.\n\n## Two-Branch Workflow\n\nThis skill uses two branches to keep investigation artifacts separate from the final clean fix:\n\n### Investigation Branch (draft PR)\n- Created from the working branch (or `main`)\n- Named: `\u003Cbase-branch>-investigate` (e.g., `flaky-test0-investigate`)\n- Contains: disabled `ci.yml`, configured `reproduce-flaky-tests.yml`, code fix\n- Opened as a **draft PR** with prominent WIP marking\n- Purpose: CI verification of the fix using the reproduce workflow without triggering full CI\n\n### Fix Branch (final PR)\n- The original working branch (e.g., `flaky-test0`)\n- Contains: only the code fix (clean diff)\n- `ci.yml` enabled, `reproduce-flaky-tests.yml` at defaults\n- Created\u002Fupdated after verification succeeds on the investigation branch\n\n**Why two branches?** Pushing workflow changes (disable ci.yml, configure reproduce workflow) to the same branch as the fix would trigger unwanted CI runs and pollute the final PR diff. The investigation branch isolates this.\n\n## Top-Level Tracking\n\nUse SQL to track the overall investigation state. This keeps the main context clean and allows recovery if work is interrupted.\n\n### Initialize tracking at the start of every investigation:\n\n```sql\nINSERT INTO todos (id, title, description, status) VALUES\n  ('gather-data', 'Gather failure data', 'Read issue, find test code, determine failure rates per OS', 'pending'),\n  ('analyze-existing', 'Analyze existing quarantine logs', 'Download logs from recent quarantine failures to understand the error', 'pending'),\n  ('reproduce-local', 'Reproduce locally', 'Try local reproduction with run-test-repeatedly.sh\u002F.ps1 (fast path)', 'pending'),\n  ('reproduce-ci', 'Reproduce on CI', 'Configure and run reproduce-flaky-tests.yml: single-test first, then quarantine-project if needed', 'pending'),\n  ('analyze', 'Analyze failure logs', 'Download CI logs or review local logs, identify root cause', 'pending'),\n  ('fix', 'Apply fix', 'Write the code fix based on root cause analysis', 'pending'),\n  ('verify', 'Verify fix on CI', 'Re-run reproduce workflow to confirm fix works', 'pending'),\n  ('verify-ci', 'Verify no CI regressions', 'Confirm fix does not introduce regressions in the CI workflow', 'pending'),\n  ('cleanup', 'Clean up investigation', 'Close investigation PR, create clean fix PR', 'pending');\n\nINSERT INTO todo_deps (todo_id, depends_on) VALUES\n  ('analyze-existing', 'gather-data'),\n  ('reproduce-local', 'analyze-existing'),\n  ('reproduce-ci', 'reproduce-local'),\n  ('analyze', 'reproduce-ci'),\n  ('fix', 'analyze'),\n  ('verify', 'fix'),\n  ('verify-ci', 'verify'),\n  ('cleanup', 'verify-ci');\n```\n\n### Store key parameters in session state:\n\n```sql\nCREATE TABLE IF NOT EXISTS session_state (key TEXT PRIMARY KEY, value TEXT);\nINSERT OR REPLACE INTO session_state (key, value) VALUES\n  ('test_method', '\u003CFullyQualifiedMethodName>'),\n  ('test_project', '\u003CProjectShortname>'),\n  ('issue_url', '\u003CGitHubIssueURL>'),\n  ('failure_rate_linux', '\u003Crate or unknown>'),\n  ('failure_rate_windows', '\u003Crate or unknown>'),\n  ('failure_rate_macos', '\u003Crate or unknown>'),\n  ('max_failure_rate', '\u003Chighest rate across OSes>'),\n  ('reproduce_attempt', '1'),\n  ('reproduce_mode', 'single-test'),\n  ('fix_attempt', '1'),\n  ('reproduce_run_id', ''),\n  ('verify_run_id', ''),\n  ('investigation_branch', ''),\n  ('fix_branch', ''),\n  ('user_interaction', 'false');\n```\n\n**Always update todo status as you work** — set to `in_progress` before starting, `done` when complete. Query `SELECT * FROM todos;` to check progress. Store CI run IDs and attempt counts in `session_state`.\n\n### Tracking User Interaction\n\nIf at any point during the investigation you use the `ask_user` tool to get input from the user, immediately update the session state:\n\n```sql\nINSERT OR REPLACE INTO session_state (key, value) VALUES ('user_interaction', 'true');\n```\n\nThis flag determines whether the final PR is labeled as `[automated]` (see Step 6.2).\n\n### Investigation Notes\n\nKeep investigation notes in the **session workspace** (not in the repo). This avoids commit noise from temporary artifacts:\n\n```\n~\u002F.copilot\u002Fsession-state\u002F\u003Csession-id>\u002F\n├── plan.md                # Summary: test name, issue, root cause, fix, status\n└── files\u002F\n    └── failure-logs\u002F      # Downloaded CI failure logs (if any)\n```\n\nUse `plan.md` in the session workspace for running notes and observations. Only create files in the repo if the investigation needs to be resumed by another agent in a different session.\n\n## Overview: The Investigate→Reproduce→Fix→Verify Cycle\n\nThe steps below are sequential and gated. Complete each step fully before moving to the next.\n\n1. Gather failure data from the issue (OS-specific failure rates, error messages) and read the test code for understanding\n2. Analyze existing quarantine failure logs — informs reproduction strategy and may reveal root cause\n3. **Try to reproduce locally** using `run-test-repeatedly.sh` (Linux\u002FmacOS) or `run-test-repeatedly.ps1` (Windows) — this is the fast path (~minutes vs ~30 min for CI). Works when the current OS matches a failing OS.\n4. If local reproduction fails (wrong OS, contention-sensitive, or low failure rate), **reproduce on CI** using `reproduce-flaky-tests.yml` with graduated escalation: single-test → quarantine-project → log-based analysis\n5. Analyze failure logs to identify root cause\n6. Apply a fix. Try local verification first with `run-test-repeatedly.sh`\u002F`.ps1`, then **always validate on CI** as final verification.\n7. Clean up: close investigation branch, create clean fix PR\n\n**Prefer analyzing existing data first.** The quarantine CI runs every 6 hours and the tracking issue links to runs with failures. These logs are often sufficient to diagnose the root cause, but CI reproduction should still be attempted to establish a baseline failure rate.\n\n## Step 1: Gather Failure Data\n\n### Finding the Issue\n\nThe user may provide:\n- A **test method name** (e.g., `DeployAsync_WithMultipleComputeEnvironments_Works`)\n- A **GitHub issue URL** (e.g., `https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fissues\u002F13287`)\n- Both\n\n**If you only have the test name**, find the tracking issue:\n\n1. First check the test code for a `[QuarantinedTest]` attribute — it contains the issue URL:\n   ```bash\n   grep -rn \"QuarantinedTest\" tests\u002F --include=\"*.cs\" | grep \"TestMethodName\"\n   ```\n\n2. If not found there, look up the test in the **quarantine tracking meta-issue** https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fissues\u002F8813 — this issue tracks all quarantined tests with links to their individual issues:\n   ```bash\n   gh issue view 8813 --repo microsoft\u002Faspire\n   ```\n   Search the output for the test name to find its linked issue.\n\n3. If neither source has the issue, **proceed without historical failure data**. Use a default configuration (all 3 OSes, 5×5 iterations) since you don't know which OSes fail or the failure rate.\n\n### From the Issue\n\nQuarantined test issues contain tracking tables with per-OS failure rates over the last 100 runs. This data is critical:\n\n- **Which OSes fail**: Target only those OSes to save runner time\n- **Failure rate**: Determines how many iterations you need for reproduction\n- **Error pattern**: Helps identify root cause before reproducing\n\n```bash\n# Read the issue to get failure data\ngh issue view \u003Cissue-number> --repo microsoft\u002Faspire\n```\n\n### From the Test Code\n\nFind the test method, class, and project. **Read the test source code and its fixture\u002Fsetup** to understand what the test does, how it waits for readiness, and what patterns it uses. This is essential for understanding what you're trying to reproduce and for matching against common flaky test patterns.\n\n```bash\n# Search for the test method\ngrep -rn \"public.*async.*Task.*TestMethodName\\|public.*void.*TestMethodName\" tests\u002F --include=\"*.cs\"\n```\n\n**Consult the flaky test patterns** in `.github\u002Finstructions\u002Ftest-review-guidelines.instructions.md` early. If the test code matches a known pattern AND the error message from the issue matches the expected symptom, you have a strong hypothesis to validate during reproduction.\n\n### Iteration Count Heuristic\n\nBased on the failure rate from the issue tracking data, calculate iterations to achieve **95% probability of seeing at least one failure** (if the bug exists):\n\n| Failure Rate | Runners × Iterations per OS | Total per OS | Confidence |\n|---|---|---|---|\n| >50% | 3 × 3 | 9 | >99% |\n| 20-50% | 5 × 5 | 25 | >99% |\n| 10-20% | 5 × 10 | 50 | >99% |\n| 5-10% | 10 × 10 | 100 | >99% |\n| \u003C5% | 10 × 25 | 250 | >95% |\n\nThe math: for failure rate `p`, need `n ≥ log(0.05) \u002F log(1-p)` iterations for 95% confidence. The table above provides comfortable margins.\n\n### ✅ Step 1 Checkpoint\n\nBefore proceeding to Step 1.5, confirm you have:\n- [ ] The test method name, class, and project path\n- [ ] The issue URL (if available)\n- [ ] Per-OS failure rates (to choose target OSes and iteration counts)\n- [ ] The error message\u002Fpattern from the issue\n- [ ] Read the test source code and its fixture\u002Fsetup for understanding\n- [ ] Checked the Common Flaky Test Patterns table for matches\n- [ ] SQL tracking initialized with all parameters stored\n\n**Do NOT write a fix yet.** You have a hypothesis, but proceed to Step 1.5 to validate it with existing failure data.\n\n## Step 1.5: Analyze Existing Quarantine Failure Logs\n\nBefore running a separate reproduction, check if existing quarantine CI logs already contain the information you need. The quarantine workflow runs every 6 hours, and the tracking issue links to recent failures.\n\n### Finding Failure Logs from Quarantine Runs\n\nThe tracking issue contains ❌ links to failed quarantine runs. Use those run IDs to find the specific job that failed:\n\n```bash\n# Find the failed job for your test project in a quarantine run\ngh api \"repos\u002Fmicrosoft\u002Faspire\u002Factions\u002Fruns\u002F\u003Crun_id>\u002Fjobs?per_page=100&filter=latest\" \\\n  --jq '.jobs[] | select(.name | contains(\"\u003CProjectShortname>\")) | select(.conclusion == \"failure\") | {id: .id, name: .name}'\n```\n\nThen download the logs for that job:\n\n```bash\n# Get logs via the GitHub MCP tool (preferred — handles encoding automatically)\n# Use get_job_logs with the job_id, return_content: true, tail_lines: 300\n\n# Or via CLI\ngh api \"repos\u002Fmicrosoft\u002Faspire\u002Factions\u002Fjobs\u002F\u003Cjob_id>\u002Flogs\" > quarantine-failure.log\n```\n\nSearch the logs for the test name, error message, and stack trace:\n\n```bash\ngrep -i \"TestMethodName\\|TaskCanceled\\|Assert\\|Exception\\|FAIL\" quarantine-failure.log | head -30\n```\n\n### Identifying Contention-Sensitive Tests\n\nA test is likely **contention-sensitive** (fails only when running alongside other tests) if:\n\n1. **It uses `randomizePorts: false`** — fixed ports can conflict with other concurrent tests\n2. **It uses a shared fixture** (collection fixture or class fixture) — startup timing depends on other tests\n3. **It uses `WaitForTextAsync`** — log-based readiness checks are fragile under contention\n4. **It shares a `CancellationTokenSource` across startup and readiness phases** — one phase can starve the other's timeout budget\n5. **The tracking issue shows 0% failure on macOS** (which often has less CI contention) but failures on Linux\u002FWindows\n\nIf you identify contention-sensitive indicators, **note this for Step 3** — single-test CI reproduction may fail, and you'll need to escalate to quarantine-project mode. Do NOT skip reproduction; the graduated escalation in Step 3 handles this.\n\n### ✅ Step 1.5 Checkpoint\n\nBefore proceeding:\n- [ ] Downloaded and examined at least 1-2 quarantine failure logs for the test\n- [ ] Confirmed the error matches the pattern in the tracking issue\n- [ ] Assessed whether the test is contention-sensitive (noted for Step 3 escalation strategy)\n\nProceed to Step 2 for local reproduction.\n\n## Step 2: Try Local Reproduction (Fast Path)\n\nBefore going to CI, try reproducing the failure locally. This gives feedback in minutes instead of 30+ minutes.\n\n### 2.1: Check OS Compatibility\n\n```bash\nuname -s  # Linux, Darwin (macOS), or Windows (via MSYS\u002FGit Bash)\n```\n\nCompare your OS against the failing OSes from Step 1. Local reproduction is viable when:\n- Your OS matches one of the failing OSes, OR\n- The test fails on **all** OSes (OS-independent flakiness)\n\nIf the test only fails on an OS you don't have (e.g., fails only on Windows and you're on Linux), skip to Step 3 (CI reproduction).\n\n### 2.2: Build the Test Project\n\n```bash\n# Restore first if not already done\n.\u002Frestore.sh  # or .\u002Frestore.cmd on Windows\n\n# Build the specific test project\ndotnet build tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj -v:q\n```\n\n### 2.3: Run with run-test-repeatedly script\n\nUse the `run-test-repeatedly.sh` (Linux\u002FmacOS) or `run-test-repeatedly.ps1` (Windows) script in `.agents\u002Fskills\u002Ffix-flaky-test\u002F`. It runs the test command repeatedly with process cleanup between iterations.\n\n**Linux\u002FmacOS:**\n\n```bash\n# Basic usage — run a single test 20 times (stop on first failure)\n.\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002Frun-test-repeatedly.sh -n 20 -- \\\n  dotnet test tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-build \\\n  -- --filter-method \"*.\u003CTestMethodName>\" \\\n  --filter-not-trait \"quarantined=true\" --filter-not-trait \"outerloop=true\"\n```\n\n**Windows (PowerShell):**\n\n```powershell\n# Basic usage — run a single test 20 times (stop on first failure)\n.\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002Frun-test-repeatedly.ps1 -n 20 -- dotnet test tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-build `\n  -- --filter-method \"*.\u003CTestMethodName>\" `\n  --filter-not-trait \"quarantined=true\" --filter-not-trait \"outerloop=true\"\n```\n\n**For quarantined tests**, you need `\u002Fp:RunQuarantinedTests=true` during both build **and** test to prevent the build system from filtering them out:\n\n```bash\ndotnet build tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj -v:q \u002Fp:RunQuarantinedTests=true\n\n# Linux\u002FmacOS\n.\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002Frun-test-repeatedly.sh -n 20 -- \\\n  dotnet test tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-build \\\n  \u002Fp:RunQuarantinedTests=true \\\n  -- --filter-method \"*.\u003CTestMethodName>\"\n\n# Windows (PowerShell)\n.\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002Frun-test-repeatedly.ps1 -n 20 -- dotnet test tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-build `\n  -- --filter-method \"*.\u003CTestMethodName>\"\n```\n\n**Choose iteration count** based on failure rate (same heuristic as CI):\n\n| Failure Rate | Local Iterations | Expected failures |\n|---|---|---|\n| >50% | 10 | ~5+ |\n| 20-50% | 20 | ~4-10 |\n| 10-20% | 30 | ~3-6 |\n| 5-10% | 50 | ~2-5 |\n| \u003C5% | 100 | ~1-5 |\n\n**Script options** (same for both `.sh` and `.ps1`):\n- `-n \u003Ccount>` — Number of iterations (default: 100)\n- `--run-all` — Don't stop on first failure, run all iterations\n- `--help` — Show usage\n\nResults are saved to `\u002Ftmp\u002Ftest-results-\u003Ctimestamp>\u002F` (Linux\u002FmacOS) or `$env:TEMP\\test-results-\u003Ctimestamp>\\` (Windows). Failure logs are in `failure-*.log` files.\n\n### 2.4: Handle Local Reproduction Results\n\n**If the test fails locally**: Reproduction successful ✅. Examine the failure log:\n\n```bash\n# The script prints the results directory path\ncat \u002Ftmp\u002Ftest-results-*\u002Ffailure-*.log\n```\n\nMark `reproduce-local` as `done` in SQL and proceed to Step 4 (root cause analysis) using the local failure logs.\n\n```sql\nUPDATE todos SET status = 'done' WHERE id = 'reproduce-local';\nUPDATE todos SET status = 'done' WHERE id = 'reproduce-ci';  -- skip CI reproduction\nUPDATE todos SET status = 'in_progress' WHERE id = 'analyze';\n```\n\n**If the test passes all local iterations**: Local reproduction failed. This can happen because:\n- The failure is OS-specific and you're on the wrong OS\n- The failure is contention-sensitive (only happens with parallel tests)\n- The failure rate is very low and you didn't run enough iterations\n\nProceed to Step 3 (CI reproduction) for cross-OS, parallel-runner reproduction.\n\n```sql\nUPDATE todos SET status = 'done' WHERE id = 'reproduce-local';\nINSERT OR REPLACE INTO session_state (key, value) VALUES ('local_result', 'no_failures');\n```\n\n### ✅ Step 2 Checkpoint\n\n- [ ] Checked OS compatibility\n- [ ] Ran `run-test-repeatedly.sh`\u002F`.ps1` with appropriate iteration count (or skipped due to OS mismatch)\n- [ ] Recorded result: local failure found → proceed to Step 4, or no failures → proceed to Step 3\n\n## Step 3: Reproduce on CI (Fallback)\n\n### 3.0: Create the Investigation Branch\n\nCreate a separate branch for CI investigation. This branch will have `ci.yml` disabled and `reproduce-flaky-tests.yml` configured, keeping the fix branch clean.\n\n```bash\n# Create investigation branch from the current working branch\ngit checkout -b \u003Cfix-branch>-investigate\n\n# Store the branch names\n```\n\n```sql\nINSERT OR REPLACE INTO session_state (key, value) VALUES\n  ('investigation_branch', '\u003Cfix-branch>-investigate'),\n  ('fix_branch', '\u003Cfix-branch>');\n```\n\n### 3.0a: Disable ci.yml\n\nDisable `ci.yml` so pushing to the investigation branch doesn't trigger full CI:\n\n```yaml\n# .github\u002Fworkflows\u002Fci.yml — add this at the top level, after `name:`\n# Change the `on:` trigger to disable automatic runs:\non:\n  workflow_dispatch: {}  # Only manual trigger, no automatic PR\u002Fpush triggers\n```\n\nThis prevents CI from running on every push to the investigation branch. You will re-enable it when creating the final fix PR.\n\n### 3.1: Configure the Reproduce Workflow\n\nEdit `.github\u002Fworkflows\u002Freproduce-flaky-tests.yml` — change only the `env:` section at the top:\n\n```yaml\nenv:\n  TEST_PROJECT: \"Hosting.Azure\"  # Project shortname\n  TEST_FILTER: '--filter-method \"*.DeployAsync_WithMultipleComputeEnvironments_Works\"'\n  TARGET_OSES: \"windows-latest\"  # Focus on highest-failure-rate OS\n  RUNNERS_PER_OS: \"5\"\n  ITERATIONS_PER_RUNNER: \"5\"\n```\n\n**OS targeting strategy:**\n- **High failure rate (>20%) on one OS**: Target that OS only first — fastest feedback\n- **High rate on multiple OSes**: Target all failing OSes\n- **Low rate or can't reproduce**: Focus on the OS with the highest failure rate, increase iterations\n- **Unknown rates**: Target `ubuntu-latest,windows-latest` with moderate iterations\n\n**Test project shortname mapping**: The workflow resolves `TEST_PROJECT` to a path:\n- Tries `tests\u002F{name}.Tests\u002F{name}.Tests.csproj` first\n- Then `tests\u002FAspire.{name}.Tests\u002FAspire.{name}.Tests.csproj`\n- Examples: `Hosting` → `Aspire.Hosting.Tests`, `Hosting.Azure` → `Aspire.Hosting.Azure.Tests`\n\n**Common filter patterns**:\n```yaml\n# Single test method\nTEST_FILTER: '--filter-method \"*.TestMethodName\"'\n# All tests in a class\nTEST_FILTER: '--filter-class \"*.TestClassName\"'\n# Multiple test methods\nTEST_FILTER: '--filter-method \"*.Test1\" --filter-method \"*.Test2\"'\n```\n\n**For quarantined tests**: The workflow automatically disables the quarantine exclusion filter for both build and test phases (via `\u002Fp:_NonQuarantinedTestRunAdditionalArgs=\"\"`), so quarantined tests are included regardless of their trait. You do NOT need to add any special flags.\n\n**Zero-test detection**: The workflow detects when zero tests execute (e.g., due to a misconfigured filter) and treats it as a failure. If you see \"Zero tests executed\" errors, verify that `TEST_FILTER` matches the actual test name and that quarantine settings are correct.\n\n### 3.2: Push and Open Draft PR\n\nCommit the workflow changes and open a **draft PR** with the investigation template:\n\n```bash\ngit add .github\u002Fworkflows\u002Fci.yml .github\u002Fworkflows\u002Freproduce-flaky-tests.yml\ngit commit -m \"? Investigation: configure CI for flaky test reproduction\n\n⚠️ DO NOT MERGE — This is a temporary investigation branch.\nci.yml disabled, reproduce workflow configured for \u003Ctest name>.\"\ngit push --set-upstream origin \u003Cfix-branch>-investigate\n```\n\nOpen a draft PR with prominent WIP marking:\n\n```bash\ngh pr create --draft --repo microsoft\u002Faspire \\\n  --title \"? [DO NOT MERGE] Investigation: \u003Ctest name>\" \\\n  --body \"## ⚠️ DO NOT MERGE — Investigation Branch\n\nThis is a temporary branch for reproducing and verifying a fix for a flaky test.\n\n**Issue**: #\u003Cissue-number>\n**Test**: \\`\u003CFullyQualifiedTestName>\\`\n\n### What's changed on this branch\n- \\`ci.yml\\` disabled (prevents full CI on investigation pushes)\n- \\`reproduce-flaky-tests.yml\\` configured for the target test\n- Code fix (will be applied after reproduction)\n\n### Status\n- [ ] Reproduction confirmed\n- [ ] Fix applied\n- [ ] Fix verified on CI\n- [ ] Clean fix PR created\n\nThis branch will be deleted after the fix is verified and a clean PR is created.\"\n```\n\n### 3.3: Trigger the Reproduce Workflow\n\n```bash\ngh workflow run reproduce-flaky-tests.yml --repo microsoft\u002Faspire --ref \u003Cfix-branch>-investigate\n```\n\nThis dispatches the workflow from `main` but runs the version from your branch, so your env var edits will be used.\n\n**If the workflow dispatch fails** (e.g. HTTP 403 \"Resource not accessible by integration\"): your GitHub token lacks `actions:write` permission on the repository. This is a non-fatal blocker — continue with the investigation, but you **must** document this in every PR you open (both investigation and fix PRs). Include the exact error, and provide the manual trigger command so a reviewer or maintainer can run it. See the PR template in Step 6.2 for the required format.\n\n### 3.4: Monitor and Cancel\n\n**Monitor the run using polling** (CI runs take 10-30+ minutes):\n\n```bash\n# Find the run ID\ngh run list --repo microsoft\u002Faspire --branch \u003Cbranch> --limit 1 --json databaseId,status\n```\n\nStore the run ID, then poll periodically for completion:\n```sql\nINSERT OR REPLACE INTO session_state (key, value) VALUES ('reproduce_run_id', '\u003Crun-id>');\n```\n\n```bash\n# Poll for completion (use bash mode=\"async\", then read_bash with increasing delays)\n# Avoid `gh run watch` — it produces excessive output that floods the context window.\ngh run view \u003Crun-id> --repo microsoft\u002Faspire --json status,conclusion --jq '{status, conclusion}'\n\n# Check individual job results as they complete\ngh run view \u003Crun-id> --repo microsoft\u002Faspire --json jobs \\\n  --jq '.jobs[] | select(.status == \"completed\") | {name: .name, conclusion: .conclusion}'\n```\n\n**Cancel old runs** when starting new ones to avoid wasting CI resources:\n\n```bash\n# Cancel a specific run\ngh run cancel \u003Crun-id> --repo microsoft\u002Faspire\n\n# Cancel all in-progress runs on your branch (useful when iterating)\ngh run list --repo microsoft\u002Faspire --branch \u003Cbranch> --status in_progress --json databaseId --jq '.[].databaseId' | \\\n  xargs -I {} gh run cancel {} --repo microsoft\u002Faspire\n```\n\nAlways cancel previous reproduce\u002Fverify runs before pushing a new configuration. `workflow_dispatch` runs are NOT auto-cancelled, so you must cancel them manually.\n\n### 3.5: Handle Reproduction Results\n\n**⛔ GATE: Do not proceed past this point until the CI run has completed.**\n\nIf there are failure artifacts, download them:\n\n```bash\n# Download failure artifacts\ngh run download \u003Crun-id> --repo microsoft\u002Faspire --dir \u002Ftmp\u002Ffailure-logs\n\n# Or get logs directly via the GitHub API \u002F MCP tools\ngh api \"repos\u002Fmicrosoft\u002Faspire\u002Factions\u002Fjobs\u002F\u003Cjob_id>\u002Flogs\" > \u002Ftmp\u002Ffailure.log\n```\n\n**Distinguishing test failures from infrastructure failures:**\n\nCI runners sometimes fail due to infrastructure issues, NOT the test itself. Common infrastructure failures include:\n- `Failed to install or invoke dotnet...` (exit code -1073741502 on Windows)\n- `The runner has received a shutdown signal` or runner timeouts\n- Network connectivity errors during `dotnet restore`\n\n**These do NOT count as reproductions.** Check the actual error message — only count iterations where the **test itself** failed with the expected error pattern from the tracking issue.\n\n**If some runners show test failures (the expected error)**: Reproduction successful ✅. Proceed to Step 4.\n\n**If no runners show the expected test failure — scale up and retry:**\n\n```sql\n-- Track the scaling attempt\nINSERT OR REPLACE INTO session_state (key, value)\nVALUES ('reproduce_attempt', CAST((SELECT CAST(value AS INTEGER) FROM session_state WHERE key = 'reproduce_attempt') + 1 AS TEXT));\n```\n\nScale up progressively, focusing on the OS most likely to fail first (based on per-OS failure rates from the issue). Go back to Step 3.1 after each change:\n\n| Attempt | `TARGET_OSES` | `RUNNERS_PER_OS` | `ITERATIONS_PER_RUNNER` | Notes |\n|---------|---------------|-------------------|--------------------------|-------|\n| 1 | Highest-failure-rate OS only | From heuristic table | From heuristic table | Start narrow — one OS, sized by failure rate |\n| 2 | Same single OS | Same | 2× previous | Double `ITERATIONS_PER_RUNNER` only |\n\n**Upper bounds**: Do not exceed `RUNNERS_PER_OS=10` or `ITERATIONS_PER_RUNNER=50` (total matrix entries must stay ≤ 256 per GitHub Actions limits).\n\n**If 2 attempts produce zero test failures → escalate to quarantine-project mode (Step 3.6).**\n\n### 3.6: Quarantine-Project Mode (Contention Escalation)\n\nWhen single-test reproduction fails, the test likely only fails under contention with other tests. Escalate by running **all quarantined tests in the assembly**, which matches what `tests-quarantine.yml` does:\n\nEdit `.github\u002Fworkflows\u002Freproduce-flaky-tests.yml` — change the `TEST_FILTER` to target all quarantined tests:\n\n```yaml\nenv:\n  TEST_PROJECT: \"\u003Csame project>\"\n  TEST_FILTER: '--filter-trait \"quarantined=true\"'  # Run all quarantined tests in this assembly\n  TARGET_OSES: \"\u003Csame as before>\"\n  RUNNERS_PER_OS: \"3\"\n  ITERATIONS_PER_RUNNER: \"3\"\n```\n\nThis recreates the contention environment from the quarantine workflow. Push, trigger, and monitor as before.\n\n**If quarantine-project mode reproduces the failure**: Reproduction successful ✅. Proceed to Step 4. Note: verification (Step 5) should use the same quarantine-project mode to confirm the fix.\n\n**If quarantine-project mode also produces zero failures**: The test requires heavier contention than we can simulate on demand. In this case:\n1. Fall back to analyzing existing quarantine failure logs (from Step 1.5)\n2. Read the test code to identify contention indicators (shared ports, shared fixtures, sequential waits)\n3. Proceed to Step 4 using quarantine logs as your failure evidence\n4. The verification run (Step 5) will still validate your fix in isolation, which is useful even if you can't reproduce the original failure\n5. Note in the PR description that reproduction required full CI contention and the fix relies on log analysis + quarantine monitoring for confirmation\n\n```sql\nINSERT OR REPLACE INTO session_state (key, value) VALUES ('reproduce_mode', 'log-based');\n```\n\n**CRITICAL: Windows log encoding gotcha**\n\nWindows CI log files downloaded as artifacts are encoded as **UTF-16LE**. Running `cat` on them produces garbled output. Convert first:\n\n```bash\n# Convert Windows log to readable UTF-8\niconv -f UTF-16LE -t UTF-8 \u002Ftmp\u002Ffailure-logs\u002Ffailures-windows-latest-1\u002Ftest-output.log > \u002Ftmp\u002Freadable-windows.log\ncat \u002Ftmp\u002Freadable-windows.log\n```\n\n**Tip**: Using `get_job_logs` via GitHub API\u002FMCP tools returns UTF-8 directly, avoiding encoding issues entirely. Prefer API-based log retrieval when possible.\n\n**Alternatively**, search for the error directly:\n\n```bash\n# Search across all failure logs (handles encoding)\nfind \u002Ftmp\u002Ffailure-logs -name \"*.log\" -exec grep -l \"Assert\\|Error\\|Exception\" {} \\;\n```\n\n## Step 4: Identify Root Cause\n\n### Interpreting Reproduction Results\n\n- **Some runners fail, some pass**: This is the expected pattern for a flaky test. Proceed to analyze the failures.\n- **All runners fail (100%)**: Compare against the failure rate from the tracking issue. If the issue says e.g. 84% and you see 100%, that's consistent — proceed. But if the issue says e.g. 10% and you see 100%, this may be an **unrelated issue** (e.g., a build break, a new dependency problem). Investigate whether the failure is the same error as reported in the issue before attempting a fix.\n- **No runners fail**: The test may not be reliably reproducible with your current iteration count. Increase `RUNNERS_PER_OS` and `ITERATIONS_PER_RUNNER` and try again.\n\n### Analyzing Failure Logs\n\nFailure logs may come from local runs (Step 2, in `\u002Ftmp\u002Ftest-results-*\u002F`), CI reproduce runs (Step 3), or existing quarantine runs (Step 1.5). All are valid sources.\n\n**Preferred: Use GitHub API\u002FMCP tools** to get logs directly (avoids encoding issues):\n\n```bash\n# Get job logs via GitHub MCP tool: get_job_logs with job_id, return_content: true, tail_lines: 300\n# Or via CLI:\ngh api \"repos\u002Fmicrosoft\u002Faspire\u002Factions\u002Fjobs\u002F\u003Cjob_id>\u002Flogs\" > \u002Ftmp\u002Ffailure.log\n```\n\n**Delegate log analysis to a sub-agent** to keep the main context clean:\n\n```\nUse a task agent (explore or general-purpose) to analyze the failure logs:\n- Pass the log file paths or content\n- Ask it to identify the specific assertion\u002Fexception\n- Ask it to read the test source code and identify the concurrency\u002Ftiming model\n- Have it return a structured root cause summary\n```\n\nLook for the assertion or exception that failed:\n\n```bash\n# Find the actual test failure in logs\ngrep -A 10 \"FAIL\\|Assert\\.\\|Exception\" \u002Ftmp\u002Ffailure.log | head -50\n\n# For .trx files (XML test results) from downloaded artifacts\nfind \u002Ftmp\u002Ffailure-logs -name \"*.trx\" -exec grep -l 'outcome=\"Failed\"' {} \\;\n```\n\nThen find the corresponding test code and understand the concurrency\u002Ftiming model.\n\n### ✅ Step 4 Checkpoint\n\nBefore proceeding to Step 5, confirm you have:\n- [ ] Examined CI failure logs (from reproduce runs OR existing quarantine runs)\n- [ ] Identified the specific error (assertion failure, exception, timeout)\n- [ ] Read the test source code and identified the root cause\n- [ ] Documented the root cause in your session plan\n\n**Now — and only now — proceed to write the fix.**\n\n## Step 5: Apply Fix and Verify\n\n> **⚠️ DO NOT remove the `[QuarantinedTest]` attribute or close the tracking issue.** Unquarantining is a separate process that happens after 21 days of zero failures in quarantine CI. Your fix PR should contain _only_ the code fix. See Step 6.5 for details.\n\n### 5.1: Apply the Fix\n\n1. Make the code change\n2. **Build locally to confirm it compiles**:\n   ```bash\n   dotnet build tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-restore -v:q\n   ```\n3. Keep `reproduce-flaky-tests.yml` configured for the same test\n\n### 5.2: Local Verification (Fast Pre-Check)\n\n> **Principle: Local runs are a fast pre-check, not a substitute for CI.** Running a test N times on one machine does not have the same statistical power as N runs across separate CI runners. Some flakiness stems from environmental variation (machine load, Docker daemon state, network conditions) that a single machine cannot reproduce. Local verification catches obvious regressions quickly and saves CI round-trips, but CI verification is always required as the final gate.\n\nIf local reproduction succeeded in Step 2, run a quick local verification first:\n\n```bash\n# Rebuild with fix\ndotnet build tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-restore -v:q\n\n# Quick local check — same iteration count as reproduction\n# Linux\u002FmacOS:\n.\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002Frun-test-repeatedly.sh -n 20 -- \\\n  dotnet test tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-build \\\n  -- --filter-method \"*.\u003CTestMethodName>\"\n# Windows (PowerShell):\n# .\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002Frun-test-repeatedly.ps1 -n 20 -- dotnet test tests\u002F\u003CTestProject>.Tests\u002F\u003CTestProject>.Tests.csproj --no-build -- --filter-method \"*.\u003CTestMethodName>\"\n```\n\nIf local verification fails, iterate on the fix before going to CI. This saves ~30 minutes per CI round-trip.\n\n### 5.3: Choose CI Verification Scale\n\nCI verification is always required. However, the scale should reflect your **local confidence** — how much evidence you already have that the fix is correct.\n\n#### Assessing Local Confidence\n\nConsider these factors to determine how aggressively to scale CI verification:\n\n**Higher confidence** (scale CI down):\n- Root cause matches a well-known flaky pattern (from the patterns reference)\n- Fix is a mechanical pattern application (e.g., replacing bare `HttpClient` with resilient one)\n- Local reproduction succeeded and the fix eliminated the failure\n- Current OS matches the primarily affected OS\n- Failure rate is high (>20%), making local runs more meaningful\n\n**Lower confidence** (scale CI up):\n- Root cause is a hypothesis, not confirmed by reproduction\n- Fix involves behavioral changes or new logic\n- Local reproduction failed (wrong OS, contention-sensitive, or very low failure rate)\n- Failure is OS-specific and you're on a different OS\n- Failure rate is low (\u003C10%), meaning local runs provide weak signal\n\n#### CI Scale Heuristic\n\nUse the **original failure rate** combined with your local confidence to size the CI verification. The base scale ensures that if the bug were still present, it would manifest with ≥95% probability (`n ≥ log(0.05) \u002F log(1-p)`):\n\n| Original Failure Rate | High Confidence (CI scale) | Low Confidence (CI scale) |\n|---|---|---|\n| >50% | 3 × 3 per OS (9 total) | 3 × 3 per OS (9 total) |\n| 20-50% | 3 × 5 per OS (15 total) | 5 × 5 per OS (25 total) |\n| 10-20% | 5 × 5 per OS (25 total) | 5 × 10 per OS (50 total) |\n| 5-10% | 5 × 10 per OS (50 total) | 10 × 10 per OS (100 total) |\n| \u003C5% | 10 × 10 per OS (100 total) | 10 × 25 per OS (250 total) |\n\nFor tests with very low failure rates (\u003C5%), consider whether the verification is practical within CI budget constraints. If not, document the limitation and rely on the 21-day quarantine monitoring to confirm.\n\n**For contention-sensitive tests** (where quarantine-project mode was needed for reproduction): Use the **same quarantine-project `TEST_FILTER`** for verification. This ensures the fix is validated under the same contention conditions where the failure was observed. If reproduction fell back to log-based analysis, use the low-confidence column and note in the PR that definitive confirmation relies on the 21-day quarantine monitoring.\n\n### 5.4: Push and Verify on CI\n\nPush the fix to the **investigation branch** (where reproduce workflow is already configured):\n\n```bash\ngit add -A\ngit commit -m \"Fix flaky test: \u003Cdescription of fix>\"\ngit push\n```\n\nThen trigger the reproduce workflow to verify:\n\n```bash\ngh workflow run reproduce-flaky-tests.yml --repo microsoft\u002Faspire --ref \u003Cfix-branch>-investigate\n```\n\nIf the workflow dispatch fails due to permissions (HTTP 403), see the guidance in Step 3.3. Continue to Step 6 but document the failure in the PR description.\n\nStore the verification run ID:\n```sql\nINSERT OR REPLACE INTO session_state (key, value) VALUES ('verify_run_id', '\u003Crun-id>');\nINSERT OR REPLACE INTO session_state (key, value) VALUES ('fix_attempt', '1');\n```\n\nWait for CI to complete. Monitor with polling (`gh run view --json status,conclusion`), not `gh run watch`.\n\n### 5.5: Handle Verification Results\n\n**If all iterations pass across all OSes**: The fix is validated ✅. Proceed to Step 6.\n\n**If some iterations still fail**: The fix is incomplete or incorrect. Iterate:\n\n```sql\n-- Track the fix attempt\nINSERT OR REPLACE INTO session_state (key, value)\nVALUES ('fix_attempt', CAST((SELECT CAST(value AS INTEGER) FROM session_state WHERE key = 'fix_attempt') + 1 AS TEXT));\n```\n\n1. Download the new failure logs:\n   ```bash\n   gh run download \u003Crun-id> --repo microsoft\u002Faspire --dir \u002Ftmp\u002Ffailure-logs\n   ```\n2. Analyze the new failure pattern — is it the same error or a different one?\n3. Refine the fix based on the new evidence\n4. Push and re-verify\n\n**After 3 failed fix attempts**: Stop and report findings to the user. The issue may require deeper architectural changes or domain expertise.\n\n## Step 6: Clean Up and Create Final PR\n\nAfter the fix is verified on the investigation branch, create a clean fix PR.\n\n### 6.0: Cancel Any Remaining CI Runs\n\nCancel any in-progress reproduce or verify runs that are no longer needed:\n\n```bash\n# List and cancel any remaining runs on your branch\ngh run list --repo microsoft\u002Faspire --branch \u003Cbranch> --status in_progress --json databaseId,name --jq '.[] | \"\\(.databaseId) \\(.name)\"'\ngh run cancel \u003Crun-id> --repo microsoft\u002Faspire\n```\n\n### 6.1: Cherry-Pick Fix to the Clean Branch\n\nSwitch back to the fix branch and cherry-pick only the code fix commits (not the workflow changes):\n\n```bash\ngit checkout \u003Cfix-branch>\n\n# Cherry-pick the fix commit(s) from the investigation branch\ngit cherry-pick \u003Cfix-commit-sha>\n\n# Verify the fix branch has NO workflow changes\ngit diff main -- .github\u002Fworkflows\u002F  # Should be empty\n```\n\n### 6.1.1: Clean Up Git History\n\nBefore pushing, ensure the fix branch has a clean, linear history with **only** the code fix commit(s). If intermediate commits crept in (e.g. workflow config changes, reverts, debug attempts), squash them down:\n\n```bash\n# Interactive rebase to squash noise commits into the fix\ngit rebase -i $(git merge-base HEAD main)\n\n# In the editor, mark the fix commit as \"pick\" and any noise commits as \"fixup\" or \"drop\"\n# Save and close\n\n# Verify: the branch should have only fix-related commits\ngit log --oneline main..HEAD\n\n# Verify: no unintended file changes\ngit diff main -- .github\u002Fworkflows\u002F  # Should be empty\n```\n\n**Why this matters**: A clean history makes the PR easy to review and avoids confusing commit pairs (config + revert) that produce no net change but clutter the log.\n\n### 6.2: Push and Open Final PR\n\n```bash\ngit push\n```\n\n**Determine the PR title prefix**: Check whether any user interaction occurred during the investigation:\n\n```sql\nSELECT value FROM session_state WHERE key = 'user_interaction';\n```\n\n- If `user_interaction` is `'false'`: prefix the PR title with `[automated] `\n- If `user_interaction` is `'true'`: no prefix\n\nOpen a non-draft PR with the fix. The PR body **must** include a note that it was created using the fix-flaky-test skill:\n\n```bash\ngh pr create --repo microsoft\u002Faspire \\\n  --title \"\u003Cprefix>Fix flaky test: \u003Cdescription>\" \\\n  --body \"## Flaky Test Fix\n\n### Test\n- **Method**: \\`\u003Cfully qualified test name>\\`\n- **Issue**: #\u003Cissue-number>\n\n### Root Cause\n\u003C1-2 sentence description of the root cause>\n\n### Fix\n\u003C1-2 sentence description of what was changed>\n\n### Verification\n| Run | Config | Result |\n|-----|--------|--------|\n| Pre-fix (local) | \u003Citerations>, \u003COS> | **\u003Cpass\u002Ffail>** |\n| Post-fix (local) | \u003Citerations>, \u003COS> | **\u003Cpass\u002Ffail>** |\n| Post-fix (CI) | \u003Crunners × iters × OSes> | **\u003Clink to run>** |\n\n> **If any verification step was skipped or failed** (e.g. workflow dispatch permission error), replace the CI row with a clear explanation:\n> - What step failed and the exact error (e.g. \\\\\\`HTTP 403: Resource not accessible by integration\\\\\\`)\n> - Why it could not be completed (e.g. agent token lacks \\\\\\`actions:write\\\\\\` permission)\n> - The manual command a reviewer can run to complete verification\n> - A link to the investigation PR\u002Fbranch with the pre-configured reproduce workflow\n\n### Verification Rationale\n\u003CBrief explanation of CI scale choice: local confidence level, why that scale was appropriate for the failure rate, and acknowledgment that local runs are a pre-check — not equivalent to CI runs across separate runners.>\n\n### Notes\n- \\`[QuarantinedTest]\\` attribute kept — unquarantining will happen separately after 21 days of zero failures in quarantine CI\n\n---\n> **Note:** This PR intentionally does not close #\u003Cissue-number>. The test will remain quarantined until a separate unquarantine process confirms it has been stable (zero failures) for a sufficient period. Once stability is confirmed, the test will be unquarantined and the issue will be closed.\n\n---\n*This fix was generated using the [fix-flaky-test skill](https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002FSKILL.md).*\"\n```\n\n**If `gh pr create` fails** (e.g. permissions error, API failure): Do **NOT** delete the branch or undo the work. Instead:\n1. Ensure the clean fix branch is pushed to the remote\n2. Tell the user the PR could not be opened, include the exact error message\n3. Provide the branch name and a direct link they can use to open the PR manually (e.g. `https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fcompare\u002Fmain...\u003Cbranch-name>`)\n\n### 6.3: Close the Investigation PR\n\n```bash\n# Close the investigation draft PR\ngh pr close \u003Cinvestigation-pr-number> --repo microsoft\u002Faspire --delete-branch\n```\n\n### 6.4: Verify No CI Regressions\n\nAfter opening the final PR, the regular CI pipeline (`ci.yml`) will run automatically. Monitor it to confirm the fix does not introduce regressions:\n\n```bash\n# Find the CI run for your PR\ngh pr checks \u003Cpr-number> --repo microsoft\u002Faspire\n```\n\nIf CI fails on unrelated tests, that's not your problem — note it in the PR. If CI fails on your changed files or the test project you modified, investigate and fix before marking the task complete.\n\n```sql\nUPDATE todos SET status = 'done' WHERE id = 'verify-ci';\n```\n\n### 6.5: DO NOT Unquarantine or Close the Issue\n\n**Important policy**: A code fix alone is not sufficient to unquarantine a test. The test must have **zero failures across all OSes for 21 consecutive days** in the quarantine CI runs before it can be unquarantined. See `docs\u002Funquarantine-policy.md`.\n\n- **DO NOT** remove the `[QuarantinedTest]` attribute\n- **DO NOT** close the tracking issue\n- A separate process monitors the quarantine CI and handles unquarantining when the 21-day criteria are met\n\n### ✅ Final Validation Checklist\n\nBefore opening the final PR, verify **every item**. This is a hard gate — do not skip any item.\n\n- [ ] Fix is verified on CI via the reproduce workflow (all iterations pass), **OR** if CI could not be triggered (e.g. permissions error), the PR description documents the failure, the exact error, and provides the manual trigger command for a reviewer\n- [ ] **`[QuarantinedTest]` attribute is still present** on the test method (not removed)\n- [ ] **Tracking issue is still open** (not closed)\n- [ ] Clean fix PR is open with only code changes (no workflow modifications)\n- [ ] **Git history is clean**: only fix-related commits, no leftover config\u002Frevert pairs (squash if needed)\n- [ ] PR description includes verification rationale (local confidence, CI scale reasoning)\n- [ ] PR description documents any skipped or failed steps with exact errors and manual remediation commands\n- [ ] Investigation draft PR is closed and branch deleted\n- [ ] No remaining in-progress CI runs on the investigation branch\n- [ ] Summary comment posted (see Response Format below)\n\n**Self-check**: Run `git diff` on the fix branch and scan for any unintended changes — removed test attributes, workflow file edits, or unrelated modifications.\n\n```sql\nUPDATE todos SET status = 'done' WHERE id = 'cleanup';\n```\n\n## Key Technical Details\n\n### Build System Quarantine Filtering\n\n`eng\u002FTesting.targets` auto-appends `--filter-not-trait \"quarantined=true\"` to test arguments via the `TestRunnerAdditionalArguments` MSBuild property. The filter value is defined in `eng\u002FTesting.props`, and the composed property is evaluated during `dotnet test` even with `--no-build`, so it must be handled in both build and test commands:\n\n- **Reproduce workflow**: Overrides `_NonQuarantinedTestRunAdditionalArgs` to empty, removing the quarantine exclusion filter for all tests\n- **Local reproduction**: Pass `\u002Fp:RunQuarantinedTests=true` to both `dotnet build` and `dotnet test`\n\n`Testing.targets` also adds `--ignore-exit-code 8` via `MtpBaseArgs`, which masks zero-test runs as successes. The workflow and `run-test-repeatedly` scripts detect this by checking test output for the `Total:` count indicator.\n\n### test-reproduce.yml Architecture\n\nThe workflow:\n1. **Setup job**: Parses env vars, generates a matrix of `{os, index}` combinations\n2. **Reproduce jobs** (parallel): Each runner builds the test project once, then loops through iterations with DCP process cleanup between runs\n3. **Results job**: Aggregates pass\u002Ffail across all runners into a summary table\n\nFailed iterations upload their test output as artifacts named `failures-\u003Cos>-\u003Cindex>`.\n\n### workflow_dispatch Behavior\n\n`workflow_dispatch` requires the workflow file to exist on the **default branch** (`main`). Key implications:\n\n- You can dispatch it against any branch with `gh workflow run reproduce-flaky-tests.yml --ref \u003Cbranch>`. GitHub discovers the workflow from `main` but runs the version from the specified `--ref`. This means your investigation branch's env var edits will be used.\n- The investigation branch has `ci.yml` disabled, so pushes don't trigger full CI — only `workflow_dispatch` of the reproduce workflow is used.\n- **Creating a new workflow file on a feature branch won't help** — GitHub won't discover it via `workflow_dispatch` until it's merged to `main`.\n\n## Response Format\n\nAfter completing a flaky test fix, provide a summary:\n\n```markdown\n## Flaky Test Fix Summary\n\n### Test\n- **Method**: `Namespace.Type.Method`\n- **Issue**: #XXXXX\n- **Project**: `tests\u002FAspire.{Project}.Tests\u002F`\n\n### Failure Data\n| OS | Failure Rate |\n|---|---|\n| Windows | XX% |\n| Linux | XX% |\n\n### Root Cause\nBrief description of what caused the flaky behavior.\n\n### Fix\nDescription of the code change.\n\n### Verification\n| Run | Config | Result |\n|-----|--------|--------|\n| Pre-fix | X runners × Y iters × Z OSes | N failures ❌ |\n| Post-fix | X runners × Y iters × Z OSes | All passed ✅ |\n\n### Files Changed\n- `path\u002Fto\u002Ffile.cs` — description\n\n### Next Steps\n- Test remains quarantined — will be unquarantined after 21 days of zero failures\n- Issue #XXXXX remains open — will be closed by the unquarantine process\n```\n\n## Important Constraints\n\n- **Reproduce before fixing**: Always confirm the failure is reproducible before attempting a fix — try locally first, then CI. Use graduated escalation: single-test → quarantine-project → log-based (see Steps 3.5 and 3.6)\n- **Try local first**: Use `run-test-repeatedly.sh` (Linux\u002FmacOS) or `run-test-repeatedly.ps1` (Windows) for fast feedback (~minutes). Fall back to CI when local reproduction fails (wrong OS, contention-sensitive, very low failure rate)\n- **Detect your OS**: Check with `uname -s` to decide if local reproduction is viable for the failing OS\n- **Quarantined tests need \u002Fp:RunQuarantinedTests=true**: The build system filters them out by default. Pass this property to both `dotnet build` and `dotnet test` commands for local reproduction. The CI reproduce workflow handles this automatically.\n- **Watch for zero-test runs**: If the test runner reports zero tests executed (exit code 8, masked by `--ignore-exit-code 8`), the filter or quarantine settings are misconfigured. The `run-test-repeatedly` scripts and reproduce workflow detect this automatically.\n- **Keep investigation notes in session workspace**: Use `plan.md` and `files\u002F` in the session workspace, not a directory in the repo\n- **Use two branches**: Investigation branch (draft PR with disabled ci.yml) for reproduce\u002Fverify; fix branch (clean PR with only code changes) for the final submission\n- **Distinguish infrastructure vs test failures**: CI runners sometimes fail due to infrastructure issues (e.g., `Failed to install or invoke dotnet...` on Windows). These do NOT count as test reproductions. Always verify the error matches the expected test failure pattern.\n- **DO NOT unquarantine or close issue**: The test stays quarantined until 21 days of zero failures (see `docs\u002Funquarantine-policy.md`)\n- **Scale verification to failure rate**: A 50% failure rate test needs fewer verification iterations than a 5% failure rate test. Use the verification heuristic table.\n- **Match verification mode to reproduction mode**: If reproduction required quarantine-project mode, use the same mode for verification. Store the mode in `session_state` (`reproduce_mode`).\n- **Target specific OSes**: Focus on the OS with the highest failure rate first. Only expand to multiple OSes when the rate is high (>20%) on multiple OSes or when initial attempts don't reproduce.\n- **Build-verify everything**: After fixes, after any test attribute changes\n- **Don't fix unrelated issues**: If you encounter unrelated test failures, ignore them\n- **Windows UTF-16LE**: Always handle encoding when reading Windows CI logs downloaded as files (not needed when using `get_job_logs` via GitHub API\u002FMCP, which returns UTF-8)\n- **Prefer polling over `gh run watch`**: Use `gh run view --json status,conclusion` to check CI status — `gh run watch` produces excessive output that floods the context window\n- **Use sub-agents for heavy work**: Delegate log analysis and CI monitoring to sub-agents to keep main context clean\n- **Track state in SQL**: Use the todos table and session_state for tracking progress across the investigate→reproduce→fix→verify cycle\n\n## Appendix: Flaky Test Patterns Reference\n\nCommon flaky test patterns are documented in `.github\u002Finstructions\u002Ftest-review-guidelines.instructions.md`. Consult that file during Step 1 (gather data) to form hypotheses, and during Step 4 (analysis) to confirm root causes.\n",{"name":5,"description":7},"main","cec61ac9b795bbfd9913f0c7196689b0d7a215d7",".agents\u002Fskills\u002Ffix-flaky-test",1039,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire","https:\u002F\u002Faspire.dev","https:\u002F\u002Fgithub.com\u002Fmicrosoft","https:\u002F\u002Fopensource.microsoft.com","Open source projects and samples from Microsoft","2026-11-15 00:32:23",{"source":8,"skillName":5,"commands":53,"prompt":63,"zipAvailable":64},[54,57,60],{"tool":55,"command":56},"npx","npx skills add microsoft\u002Faspire --skill fix-flaky-test",{"tool":58,"command":59},"bunx","bunx skills add microsoft\u002Faspire --skill fix-flaky-test",{"tool":61,"command":62},"pnpm","pnpm dlx skills add microsoft\u002Faspire --skill fix-flaky-test","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002FSKILL.md",true,[66,72],{"path":67,"resourceType":68,"resourceTypeDesc":69,"sizeBytes":70,"sourceHtmlUrl":71},"run-test-repeatedly.ps1","SCRIPT","脚本",14457,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002Frun-test-repeatedly.ps1",{"path":73,"resourceType":68,"resourceTypeDesc":69,"sizeBytes":74,"sourceHtmlUrl":75},"run-test-repeatedly.sh",10694,"https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ffix-flaky-test\u002Frun-test-repeatedly.sh",[77,101,123,133,151,177],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":37},"01M6FKZQPMA7VRA0PRBZRDFJTX","vscode-extension","Use when investigating, developing, debugging, testing, or reviewing Aspire VS Code extension behavior under extension\u002F, including extension UI, command, debugger, RPC, DCP, MCP, and CLI-integration issues or features.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fvscode-extension\u002FSKILL.md",[],[84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,30,100,24],"vscode","vscode extension","extension","testing","MCP","cli","aspire","debugging","code","issues","rpc","ui","integration","debugger","command","behavior","features",{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":37},"01M6FKZJG81XP80SVWFBJVMDWN","update-container-images","Updates Docker container image tags used by Aspire hosting integrations. Queries registries for newer tags, uses LLM to determine version-compatible updates, and applies changes. Use this when asked to update container image versions.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fupdate-container-images\u002FSKILL.md",[],[108,109,110,111,112,113,114,90,115,30,116,117,118,119,120,121,122,24],"container images","update","container","images","update container images","image","docker","integrations","version","hosting","queries","tags","updates","for","changes",{"skillNo":124,"name":125,"nameZh":6,"description":126,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":127,"categories":128,"keywords":129,"publishedAt":37},"01M6FKZDY1MY0QA62EYSDG5NHW","test-management","Quarantines or disables flaky\u002Fproblematic tests using the QuarantineTools utility","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ftest-management\u002FSKILL.md",[],[19,130,131,26,132],"management","test management","utility",{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":137,"categories":138,"keywords":139,"publishedAt":37},"01M6FKZAQ428JX8F6NSA19XBQJ","startup-perf","Measures Aspire startup profiling with CLI self-profile capture and dashboard export traces.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fstartup-perf\u002FSKILL.md",[],[140,141,142,89,143,90,144,145,146,147,148,149,150],"perf","startup","startup perf","dashboard","profiling","capture","profile","export","self","with","traces",{"skillNo":152,"name":153,"nameZh":6,"description":154,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":155,"categories":156,"keywords":157,"publishedAt":37},"01M6FKZ4W4J0ET0Q0C2Z30HYRV","reviewing-aspire-architecture","Use only when the user explicitly requests a deep Aspire architectural or pattern review of an existing PR or diff, or when a generic reviewer escalates a named Aspire-domain question it cannot resolve. Do not use for ordinary review, implementation, debugging, explanation, or design discussion—even when a PR is referenced—and never select it from changed file paths alone.","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Freviewing-aspire-architecture\u002FSKILL.md",[],[158,90,159,160,161,162,91,163,164,165,166,30,167,168,169,170,171,172,173,174,121,175,176,24],"architecture","reviewing aspire architecture","design","review","pr","file","select","reviewer","question","diff","never","only","do","domain","pattern","deep","paths","Existing","generic",{"skillNo":178,"name":179,"nameZh":6,"description":180,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":181,"categories":182,"keywords":183,"publishedAt":37},"01M6FKYZ44BEPJNV8VQ0X73CZR","pr-testing","Use when asked to test a microsoft\u002Faspire pull request, including CLI, hosting, dashboard, component, template, and VS Code extension changes. Also covers testing PRs that change CI infrastructure — GitHub Actions (workflows, actions, gh-aw agentic workflows, CI scripts under .github\u002F and eng\u002F) and Azure DevOps pipelines (eng\u002Fpipelines, eng\u002Fcommon).","https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Faspire\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fpr-testing\u002FSKILL.md",[],[87,162,184,89,185,186,143,187,188,189,190,191,90,192,92,193,34,194,195,196,30,197,117,198,86,199,122,200],"pr testing","github","agentic","workflows","change","component","agentic workflows","azure devops","infrastructure","actions","github actions","template","common","devops","pipelines","scripts","prs"]