PluginBench
Skill
Pass
Audit score 90

iterative-retrieval

affaan-m/everything-claude-code

Progressively refine context retrieval in multi-agent workflows to solve the subagent context problem

What is iterative-retrieval?

A 4-phase loop pattern (dispatch, evaluate, refine, loop) that iteratively narrows down relevant codebase context for spawned subagents. Use this when subagents cannot predict upfront what context they need, or when you're hitting context limits or missing-context failures in agent tasks.

  • Dispatch broad initial queries to gather candidate files based on patterns and keywords
  • Evaluate retrieved files for relevance using a 0-1 scoring scale with explicit gap identification
  • Refine search criteria based on evaluation results, adding discovered terminology and patterns
  • Loop up to 3 cycles to progressively narrow context until high-relevance files are found
  • Merge and return only files with relevance >= 0.7 to optimize token usage

How to install iterative-retrieval

npx skills add https://github.com/affaan-m/everything-claude-code --skill iterative-retrieval
Claude Code
Cursor
Windsurf
Cline

How to use iterative-retrieval

  1. 1.Start with a high-level task description and initial broad search criteria (patterns, keywords, excludes)
  2. 2.Dispatch the query to retrieve candidate files from the codebase
  3. 3.Evaluate each retrieved file for relevance to the task, scoring 0-1 and identifying missing context gaps
  4. 4.Refine the query by adding discovered patterns/keywords and excluding low-relevance files
  5. 5.Repeat steps 2-4 up to 3 times until you have 3+ high-relevance files (>= 0.7) with no critical gaps
  6. 6.Return the merged high-relevance context to the subagent

Use cases

Good for
  • Fixing bugs where the subagent must discover which files contain the relevant code before starting work
  • Implementing new features in unfamiliar codebases where terminology is unknown upfront
  • Spawning multiple subagents on the same codebase to avoid redundant context gathering
  • Building RAG-like retrieval pipelines for code exploration and multi-agent orchestration
  • Optimizing token usage by avoiding sending entire codebase or guessing context needs
Who it's for
  • Multi-agent workflow designers
  • Code agents spawning subagents (Claude Code, Cursor)
  • Teams building agent orchestration systems
  • Developers optimizing token usage in large codebases

iterative-retrieval FAQ

How many cycles should I run?

Maximum 3 cycles. Stop earlier if you have 3+ files with relevance >= 0.7 and no critical gaps. More cycles rarely improve results and waste tokens.

What relevance scores should I target?

High (0.8-1.0) for files directly implementing target functionality, Medium (0.5-0.7) for related patterns, Low (0.2-0.4) for tangential content. Include only files >= 0.7 in final context.

How do I identify missing context?

During evaluation, explicitly note what information is referenced but not present in retrieved files (e.g., 'file imports from utils but utils not retrieved'). Use these gaps to refine keywords and patterns in the next cycle.

Should I send everything if context is small?

No. Even in small codebases, iterative retrieval helps agents discover terminology and patterns they don't know to search for initially. The pattern scales from small to large projects.

How does this differ from standard RAG?

Iterative retrieval is agent-aware: it explicitly models that agents don't know what they need upfront, includes relevance evaluation and gap identification, and limits cycles to prevent infinite loops while optimizing for agent success.

Full instructions (SKILL.md)

Source of truth, from affaan-m/everything-claude-code.


name: iterative-retrieval description: Pattern for progressively refining context retrieval to solve the subagent context problem metadata: origin: ECC

Iterative Retrieval Pattern

Solves the "context problem" in multi-agent workflows where subagents don't know what context they need until they start working.

When to Activate

  • Spawning subagents that need codebase context they cannot predict upfront
  • Building multi-agent workflows where context is progressively refined
  • Encountering "context too large" or "missing context" failures in agent tasks
  • Designing RAG-like retrieval pipelines for code exploration
  • Optimizing token usage in agent orchestration

The Problem

Subagents are spawned with limited context. They don't know:

  • Which files contain relevant code
  • What patterns exist in the codebase
  • What terminology the project uses

Standard approaches fail:

  • Send everything: Exceeds context limits
  • Send nothing: Agent lacks critical information
  • Guess what's needed: Often wrong

The Solution: Iterative Retrieval

A 4-phase loop that progressively refines context:

┌─────────────────────────────────────────────┐
│                                             │
│   ┌──────────┐      ┌──────────┐            │
│   │ DISPATCH │─────│ EVALUATE │            │
│   └──────────┘      └──────────┘            │
│        ▲                  │                 │
│        │                  ▼                 │
│   ┌──────────┐      ┌──────────┐            │
│   │   LOOP   │─────│  REFINE  │            │
│   └──────────┘      └──────────┘            │
│                                             │
│        Max 3 cycles, then proceed           │
└─────────────────────────────────────────────┘

Phase 1: DISPATCH

Initial broad query to gather candidate files:

// Start with high-level intent
const initialQuery = {
  patterns: ['src/**/*.ts', 'lib/**/*.ts'],
  keywords: ['authentication', 'user', 'session'],
  excludes: ['*.test.ts', '*.spec.ts']
};

// Dispatch to retrieval agent
const candidates = await retrieveFiles(initialQuery);

Phase 2: EVALUATE

Assess retrieved content for relevance:

function evaluateRelevance(files, task) {
  return files.map(file => ({
    path: file.path,
    relevance: scoreRelevance(file.content, task),
    reason: explainRelevance(file.content, task),
    missingContext: identifyGaps(file.content, task)
  }));
}

Scoring criteria:

  • High (0.8-1.0): Directly implements target functionality
  • Medium (0.5-0.7): Contains related patterns or types
  • Low (0.2-0.4): Tangentially related
  • None (0-0.2): Not relevant, exclude

Phase 3: REFINE

Update search criteria based on evaluation:

function refineQuery(evaluation, previousQuery) {
  return {
    // Add new patterns discovered in high-relevance files
    patterns: [...previousQuery.patterns, ...extractPatterns(evaluation)],

    // Add terminology found in codebase
    keywords: [...previousQuery.keywords, ...extractKeywords(evaluation)],

    // Exclude confirmed irrelevant paths
    excludes: [...previousQuery.excludes, ...evaluation
      .filter(e => e.relevance < 0.2)
      .map(e => e.path)
    ],

    // Target specific gaps
    focusAreas: evaluation
      .flatMap(e => e.missingContext)
      .filter(unique)
  };
}

Phase 4: LOOP

Repeat with refined criteria (max 3 cycles):

async function iterativeRetrieve(task, maxCycles = 3) {
  let query = createInitialQuery(task);
  let bestContext = [];

  for (let cycle = 0; cycle < maxCycles; cycle++) {
    const candidates = await retrieveFiles(query);
    const evaluation = evaluateRelevance(candidates, task);

    // Check if we have sufficient context
    const highRelevance = evaluation.filter(e => e.relevance >= 0.7);
    if (highRelevance.length >= 3 && !hasCriticalGaps(evaluation)) {
      return highRelevance;
    }

    // Refine and continue
    query = refineQuery(evaluation, query);
    bestContext = mergeContext(bestContext, highRelevance);
  }

  return bestContext;
}

Practical Examples

Example 1: Bug Fix Context

Task: "Fix the authentication token expiry bug"

Cycle 1:
  DISPATCH: Search for "token", "auth", "expiry" in src/**
  EVALUATE: Found auth.ts (0.9), tokens.ts (0.8), user.ts (0.3)
  REFINE: Add "refresh", "jwt" keywords; exclude user.ts

Cycle 2:
  DISPATCH: Search refined terms
  EVALUATE: Found session-manager.ts (0.95), jwt-utils.ts (0.85)
  REFINE: Sufficient context (2 high-relevance files)

Result: auth.ts, tokens.ts, session-manager.ts, jwt-utils.ts

Example 2: Feature Implementation

Task: "Add rate limiting to API endpoints"

Cycle 1:
  DISPATCH: Search "rate", "limit", "api" in routes/**
  EVALUATE: No matches - codebase uses "throttle" terminology
  REFINE: Add "throttle", "middleware" keywords

Cycle 2:
  DISPATCH: Search refined terms
  EVALUATE: Found throttle.ts (0.9), middleware/index.ts (0.7)
  REFINE: Need router patterns

Cycle 3:
  DISPATCH: Search "router", "express" patterns
  EVALUATE: Found router-setup.ts (0.8)
  REFINE: Sufficient context

Result: throttle.ts, middleware/index.ts, router-setup.ts

Integration with Agents

Use in agent prompts:

When retrieving context for this task:
1. Start with broad keyword search
2. Evaluate each file's relevance (0-1 scale)
3. Identify what context is still missing
4. Refine search criteria and repeat (max 3 cycles)
5. Return files with relevance >= 0.7

Best Practices

  1. Start broad, narrow progressively - Don't over-specify initial queries
  2. Learn codebase terminology - First cycle often reveals naming conventions
  3. Track what's missing - Explicit gap identification drives refinement
  4. Stop at "good enough" - 3 high-relevance files beats 10 mediocre ones
  5. Exclude confidently - Low-relevance files won't become relevant

Related

  • The Longform Guide - Subagent orchestration section
  • continuous-learning skill - For patterns that improve over time
  • Agent definitions bundled with ECC (manual install path: agents/)