--- name: iterative-retrieval description: Progressive context retrieval for AI agents — start broad, then narrow. Use when working with large codebases, debugging complex issues, or when initial search was insufficient. --- # Iterative Retrieval Pattern Based on ECC iterative-retrieval skill. ## The Problem AI agents working with large codebases often retrieve too much (wasting tokens) or too little (missing context). Iterative retrieval solves this by refining context progressively. ## The Pattern ### Iteration 1: Broad Scan - Get high-level structure: directory listing, file names - Identify relevant files/directories - Read entry points and interfaces ### Iteration 2: Targeted Deep Dive - Read specific files identified in Iteration 1 - Focus on functions/classes relevant to the task - Map data flow and dependencies ### Iteration 3: Context Enrichment - Read test files for expected behavior - Read related code that was discovered - Check git history for recent changes ### Iteration 4: Resolution - Synthesize all findings - Identify the exact issue or solution - Implement with full context ## When to Use - First attempt didn't find the root cause - Bug involves multiple files/modules - Need to understand a feature before modifying it - Large function or file (need selective reading) - Dependency chain spans many layers ## Techniques ### Use offset/limit for large files Don't read entire 2000-line files. Read relevant sections: ``` read file.ts offset=50 limit=100 # Read lines 50-150 ``` ### Use grep to find patterns first ```bash grep -rn "function_name" src/ # Find where defined grep -rn "import.*module" src/ # Find usage git log --oneline -10 -- path/ # Recent changes ``` ### Build a mental map After each iteration, update your understanding: - What files are relevant? - What is the data flow? - Where is the issue likely to be? - What am I still missing? ## Avoiding Token Waste - Stop iterating when you have enough context to act - Don't read files that aren't directly relevant - Use targeted searches instead of broad reads - Summarize findings to reduce context in next iteration - Use read file with offset/limit for large files ## Exit Criteria Stop iterating when: 1. You understand the code flow relevant to your task 2. You've identified the exact location of the issue 3. You have enough context to implement a solution 4. Additional reading won't change your approach