Communitygithub.com

반복 검색 패턴

서브에이전트가 필요한 컨텍스트를 모르는 상황에서 검색을 점진적으로 개선하여 컨텍스트 문제를 해결하는 패턴입니다.

반복 검색 패턴란 무엇인가요?

이 스킬은 다중 에이전트 워크플로우에서 서브에이전트가 미리 필요한 컨텍스트를 알 수 없을 때 발생하는 '컨텍스트 문제'를 해결합니다. DISPATCH(초기 광범위 검색), EVALUATE(관련성 평가), REFINE(검색 기준 개선), LOOP(최대 3회 반복)의 4단계 루프를 통해 점진적으로 컨텍스트를 정제합니다. 예를 들어, 인증 토큰 만료 버그 수정 작업에서 처음에 'token', 'auth', 'expiry' 키워드로 검색하다가 관련 파일을 발견하면 'refresh', 'jwt' 같은 새로운 키워드를 추가하여 검색 범위를 좁혀 나갑니다. 이 패턴은 Claude Code, Cursor, Codex 등 다양한 AI 에이전트 플랫폼에서 사용할 수 있으며, 모든 컨텍스트를 한 번에 보내는 방식(컨텍스트 초과), 아무 컨텍스트도 보내지 않는 방식(정보 부족), 또는 추측에 의존하는 방식(부정확)의 문제를 효과적으로 해결합니다. 최대 3사이클 후에는 '충분히 좋은' 컨텍스트를 반환하여 토큰 사용을 최적화합니다.

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

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

반복 검색 패턴은(는) 무엇을 하나요?

서브에이전트가 작업을 시작할 때까지 필요한 컨텍스트를 알 수 없는 다중 에이전트 워크플로우의 '컨텍스트 문제'를 해결합니다.

활성화 시점

  • 서브에이전트가 미리 예측할 수 없는 코드베이스 컨텍스트가 필요할 때
  • 컨텍스트가 점진적으로 정제되는 다중 에이전트 워크플로우를 구축할 때
  • 에이전트 작업에서 '컨텍스트가 너무 큼' 또는 '컨텍스트 누락' 오류가 발생할 때
  • 코드 탐색을 위한 RAG(Retrieval-Augmented Generation) 파이프라인을 설계할 때
  • 에이전트 오케스트레이션에서 토큰 사용을 최적화할 때

문제점

서브에이전트는 제한된 컨텍스트로 생성됩니다. 서브에이전트는 다음을 알지 못합니다:

  • 관련 코드가 포함된 파일
  • 코드베이스에 존재하는 패턴
  • 프로젝트가 사용하는 용어

표준 접근 방식은 실패합니다:

  • 모든 것 전송: 컨텍스트 한도 초과
  • 아무것도 전송 안 함: 에이전트가 중요한 정보를 상실
  • 필요한 것 추측: 종종 틀림

해결책: 반복 검색

컨텍스트를 점진적으로 정제하는 4단계 루프:

┌─────────────────────────────────────────────┐
│                                             │
│   ┌──────────┐      ┌──────────┐            │
│   │ DISPATCH │─────│ EVALUATE │            │
│   └──────────┘      └──────────┘            │
│        ▲                  │                 │
│        │                  ▼                 │
│   ┌──────────┐      ┌──────────┐            │
│   │   LOOP   │─────│  REFINE  │            │
│   └──────────┘      └──────────┘            │
│                                             │
│        최대 3사이클 후 진행                  │
└─────────────────────────────────────────────┘

1단계: DISPATCH (전송)

후보 파일을 수집하기 위한 초기 광범위 질의:

// 높은 수준의 의도로 시작
const initialQuery = {
  patterns: ['src/**/*.ts', 'lib/**/*.ts'],
  keywords: ['authentication', 'user', 'session'],
  excludes: ['*.test.ts', '*.spec.ts']
};

// 검색 에이전트로 전송
const candidates = await retrieveFiles(initialQuery);

2단계: EVALUATE (평가)

검색된 콘텐츠의 관련성 평가:

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

평가 기준:

  • 높음 (0.8-1.0): 대상 기능을 직접 구현
  • 중간 (0.5-0.7): 관련 패턴 또는 유형 포함
  • 낮음 (0.2-0.4): 간접적으로 관련
  • 없음 (0-0.2): 관련 없음, 제외

3단계: REFINE (정제)

평가를 기반으로 검색 기준 업데이트:

function refineQuery(evaluation, previousQuery) {
  return {
    // 높은 관련성 파일에서 발견된 새 패턴 추가
    patterns: [...previousQuery.patterns, ...extractPatterns(evaluation)],

    // 코드베이스에서 발견된 용어 추가
    keywords: [...previousQuery.keywords, ...extractKeywords(evaluation)],

    // 관련 없는 경로 제외 확인
    excludes: [...previousQuery.excludes, ...evaluation
      .filter(e => e.relevance < 0.2)
      .map(e => e.path)
    ],

    // 특정 격차 대상 지정
    focusAreas: evaluation
      .flatMap(e => e.missingContext)
      .filter(unique)
  };
}

4단계: LOOP (반복)

정제된 기준으로 반복 (최대 3사이클):

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

    // 충분한 컨텍스트를 가지고 있는지 확인
    const highRelevance = evaluation.filter(e => e.relevance >= 0.7);
    if (highRelevance.length >= 3 && !hasCriticalGaps(evaluation)) {
      return highRelevance;
    }

    // 정제 후 계속
    query = refineQuery(evaluation, query);
    bestContext = mergeContext(bestContext, highRelevance);
  }

  return bestContext;
}

실용 예제

예제 1: 버그 수정 컨텍스트

Task: "인증 토큰 만료 버그 수정"

Cycle 1:
  DISPATCH: src/**에서 "token", "auth", "expiry" 검색
  EVALUATE: auth.ts (0.9), tokens.ts (0.8), user.ts (0.3) 발견
  REFINE: "refresh", "jwt" 키워드 추가; user.ts 제외

Cycle 2:
  DISPATCH: 정제된 용어 검색
  EVALUATE: session-manager.ts (0.95), jwt-utils.ts (0.85) 발견
  REFINE: 충분한 컨텍스트 (높은 관련성 파일 2개)

결과: auth.ts, tokens.ts, session-manager.ts, jwt-utils.ts

예제 2: 기능 구현

Task: "API 엔드포인트에 속도 제한 추가"

Cycle 1:
  DISPATCH: routes/**에서 "rate", "limit", "api" 검색
  EVALUATE: 일치 항목 없음 - 코드베이스가 "throttle" 용어 사용
  REFINE: "throttle", "middleware" 키워드 추가

Cycle 2:
  DISPATCH: 정제된 용어 검색
  EVALUATE: throttle.ts (0.9), middleware/index.ts (0.7) 발견
  REFINE: 라우터 패턴 필요

Cycle 3:
  DISPATCH: "router", "express" 패턴 검색
  EVALUATE: router-setup.ts (0.8) 발견
  REFINE: 충분한 컨텍스트

결과: throttle.ts, middleware/index.ts, router-setup.ts

에이전트와의 통합

에이전트 프롬프트에서 사용:

이 작업을 위해 컨텍스트를 검색할 때:
1. 광범위한 키워드 검색으로 시작
2. 각 파일의 관련성 평가 (0-1 척도)
3. 여전히 누락된 컨텍스트 식별
4. 검색 기준을 정제하고 반복 (최대 3사이클)
5. 관련성 >= 0.7인 파일 반환

모범 사례

  1. 광범위하게 시작, 점진적으로 좁히기 - 초기 질의를 과도하게 지정하지 마세요
  2. 코드베이스 용어 학습 - 첫 번째 사이클에서 종종 명명 규칙을 드러냅니다
  3. 누락된 항목 추적 - 명시적인 격차 식별이 정제를 주도합니다
  4. '충분히 좋은' 상태에서 중단 - 평범한 파일 10개보다 높은 관련성 파일 3개가 낫습니다
  5. 확실히 제외 - 관련성이 낮은 파일은 관련성이 높아지지 않습니다

관련 자료

  • 장문 가이드 - 서브에이전트 오케스트레이션 섹션
  • 지속적-학습 스킬 - 시간이 지남에 따라 개선되는 패턴용
  • ECC와 함께 제공되는 에이전트 정의 (수동 설치 경로: 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.

관련 스킬