Communitygithub.com

recuperação-iterativa

Padrão para refinar progressivamente a recuperação de contexto, resolvendo o problema de contexto de subagentes. Use quando um subagente não tem o contexto necessário e a recuperação precisa ser refinada em múltiplas passagens.

O que é recuperação-iterativa?

A habilidade de **Recuperação Iterativa** resolve o 'problema de contexto' em fluxos de trabalho com múltiplos agentes, onde subagentes não sabem qual contexto precisam até começarem a trabalhar. Ela implementa um loop de quatro fases (DISPATCH, EVALUATE, REFINE, LOOP) que refina progressivamente a busca por arquivos e informações relevantes. Isso é especialmente útil ao lidar com falhas de 'contexto muito grande' ou 'contexto ausente', otimizando o uso de tokens em orquestração de agentes. A habilidade suporta qualquer plataforma de agente (como Claude Code, Cursor, Codex) que permita recuperação de código, fornecendo um padrão de código e prompts que guiam o agente a buscar, avaliar e refinar sua busca até obter contexto suficiente (máximo de 3 ciclos).

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/iterative-retrieval

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Padrão de Recuperação Iterativa

Resolve o "problema de contexto" em fluxos de trabalho com múltiplos agentes, onde subagentes não sabem qual contexto precisam até começarem a trabalhar.

Quando Ativar

  • Ao gerar subagentes que precisam de contexto do código que não podem prever antecipadamente
  • Construindo fluxos de trabalho com múltiplos agentes onde o contexto é progressivamente refinado
  • Encontrando falhas de "contexto muito grande" ou "contexto ausente" em tarefas de agente
  • Projetando pipelines de recuperação do tipo RAG para exploração de código
  • Otimizando o uso de tokens na orquestração de agentes

O Problema

Subagentes são gerados com contexto limitado. Eles não sabem:

  • Quais arquivos contêm código relevante
  • Quais padrões existem no código
  • Qual terminologia o projeto usa

Abordagens padrão falham:

  • Enviar tudo: Excede os limites de contexto
  • Não enviar nada: O agente carece de informações críticas
  • Adivinhar o que é necessário: Frequentemente errado

A Solução: Recuperação Iterativa

Um loop de 4 fases que refina progressivamente o contexto:

┌─────────────────────────────────────────────┐
│                                             │
│   ┌──────────┐      ┌──────────┐            │
│   │ DISPATCH │─────│ EVALUATE │            │
│   └──────────┘      └──────────┘            │
│        ▲                  │                 │
│        │                  ▼                 │
│   ┌──────────┐      ┌──────────┐            │
│   │   LOOP   │─────│  REFINE  │            │
│   └──────────┘      └──────────┘            │
│                                             │
│        Máx. 3 ciclos, depois prosseguir     │
└─────────────────────────────────────────────┘

Fase 1: DISPATCH

Consulta inicial ampla para reunir arquivos candidatos:

// Começar com intenção de alto nível
const initialQuery = {
  patterns: ['src/**/*.ts', 'lib/**/*.ts'],
  keywords: ['authentication', 'user', 'session'],
  excludes: ['*.test.ts', '*.spec.ts']
};

// Despachar para agente de recuperação
const candidates = await retrieveFiles(initialQuery);

Fase 2: EVALUATE

Avaliar o conteúdo recuperado quanto à relevância:

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)
  }));
}

Critérios de pontuação:

  • Alta (0.8-1.0): Implementa diretamente a funcionalidade alvo
  • Média (0.5-0.7): Contém padrões ou tipos relacionados
  • Baixa (0.2-0.4): Tangencialmente relacionado
  • Nenhuma (0-0.2): Não relevante, excluir

Fase 3: REFINE

Atualizar os critérios de busca com base na avaliação:

function refineQuery(evaluation, previousQuery) {
  return {
    // Adicionar novos padrões descobertos em arquivos de alta relevância
    patterns: [...previousQuery.patterns, ...extractPatterns(evaluation)],

    // Adicionar terminologia encontrada no código
    keywords: [...previousQuery.keywords, ...extractKeywords(evaluation)],

    // Excluir caminhos irrelevantes confirmados
    excludes: [...previousQuery.excludes, ...evaluation
      .filter(e => e.relevance < 0.2)
      .map(e => e.path)
    ],

    // Focar em lacunas específicas
    focusAreas: evaluation
      .flatMap(e => e.missingContext)
      .filter(unique)
  };
}

Fase 4: LOOP

Repetir com critérios refinados (máximo de 3 ciclos):

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);

    // Verificar se temos contexto suficiente
    const highRelevance = evaluation.filter(e => e.relevance >= 0.7);
    if (highRelevance.length >= 3 && !hasCriticalGaps(evaluation)) {
      return highRelevance;
    }

    // Refinar e continuar
    query = refineQuery(evaluation, query);
    bestContext = mergeContext(bestContext, highRelevance);
  }

  return bestContext;
}

Exemplos Práticos

Exemplo 1: Contexto para Correção de Bug

Tarefa: "Corrigir o bug de expiração do token de autenticação"

Ciclo 1:
  DISPATCH: Procurar por "token", "auth", "expiry" em src/**
  EVALUATE: Encontrado auth.ts (0.9), tokens.ts (0.8), user.ts (0.3)
  REFINE: Adicionar keywords "refresh", "jwt"; excluir user.ts

Ciclo 2:
  DISPATCH: Procurar termos refinados
  EVALUATE: Encontrado session-manager.ts (0.95), jwt-utils.ts (0.85)
  REFINE: Contexto suficiente (2 arquivos de alta relevância)

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

Exemplo 2: Implementação de Funcionalidade

Tarefa: "Adicionar limitação de taxa aos endpoints da API"

Ciclo 1:
  DISPATCH: Procurar "rate", "limit", "api" em routes/**
  EVALUATE: Sem correspondências - o código usa terminologia "throttle"
  REFINE: Adicionar keywords "throttle", "middleware"

Ciclo 2:
  DISPATCH: Procurar termos refinados
  EVALUATE: Encontrado throttle.ts (0.9), middleware/index.ts (0.7)
  REFINE: Necessário padrões de roteador

Ciclo 3:
  DISPATCH: Procurar padrões "router", "express"
  EVALUATE: Encontrado router-setup.ts (0.8)
  REFINE: Contexto suficiente

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

Integração com Agentes

Use em prompts de agente:

Ao recuperar contexto para esta tarefa:
1. Comece com uma busca ampla por palavras-chave
2. Avalie a relevância de cada arquivo (escala 0-1)
3. Identifique qual contexto ainda está faltando
4. Refine os critérios de busca e repita (máx. 3 ciclos)
5. Retorne arquivos com relevância >= 0.7

Melhores Práticas

  1. Comece amplo, estreite progressivamente - Não especifique demais as consultas iniciais
  2. Aprenda a terminologia do código - O primeiro ciclo geralmente revela convenções de nomenclatura
  3. Acompanhe o que está faltando - A identificação explícita de lacunas impulsiona o refinamento
  4. Pare quando estiver "bom o suficiente" - 3 arquivos de alta relevância vencem 10 medíocres
  5. Exclua com confiança - Arquivos de baixa relevância não se tornarão relevantes

Relacionados

  • O Guia Detalhado - Seção de orquestração de subagentes
  • Habilidade continuous-learning - Para padrões que melhoram com o tempo
  • Definições de agente incluídas com ECC (caminho de instalação manual: agents/)

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

Habilidades Relacionadas