Communitygithub.com

반복 검색 패턴

서브 에이전트의 컨텍스트 문제를 해결하기 위해 검색을 점진적으로 정제하는 패턴입니다. 서브 에이전트가 필요한 컨텍스트를 충분히 갖추지 못했을 때 사용합니다.

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

이 스킬인 **반복 검색 패턴(Iterative Retrieval Pattern)**은 멀티 에이전트 워크플로에서 서브 에이전트에 필요한 코드베이스 컨텍스트를 점진적으로 확보하는 방법을 제공합니다. 서브 에이전트는 시작 전에 필요한 모든 컨텍스트를 예측하기 어렵기 때문에, 초기 검색 후 결과를 평가하고 부족한 부분을 식별하여 검색 조건을 정제하는 4단계(DISPATCH → EVALUATE → REFINE → LOOP) 반복 루프를 통해 최적의 컨텍스트를 확보합니다. 최대 3사이클로 제한되며, 관련성 점수가 0.7 이상인 파일이 3개 이상 확보되면 조기 종료하여 토큰 사용을 최적화합니다. 주로 Claude Code, Cursor, Codex 등 AI 에이전트 도구와 함께 사용되며, 버그 수정이나 새 기능 구현 시 관련 파일을 자동으로 찾아내는 데 유용합니다. 또한 RAG(검색 증강 생성) 스타일의 코드 검색 파이프라인을 설계할 때도 적용할 수 있습니다.

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

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

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

문서

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

서브 에이전트가 작업을 시작하기 전에 필요한 컨텍스트를 미리 알지 못하는 멀티 에이전트 워크플로의 "컨텍스트 문제"를 해결합니다.

활성화 시점

  • 예측할 수 없는 코드베이스 컨텍스트가 필요한 서브 에이전트를 생성할 때
  • 컨텍스트가 점진적으로 정제되는 멀티 에이전트 워크플로를 구축할 때
  • 에이전트 작업에서 "컨텍스트가 너무 큼" 또는 "컨텍스트 누락" 오류가 발생할 때
  • 코드 탐색을 위한 RAG(검색 증강 생성) 스타일 검색 파이프라인을 설계할 때
  • 에이전트 오케스트레이션에서 토큰 사용량을 최적화할 때

문제

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

  • 어떤 파일에 관련 코드가 있는지
  • 코드베이스에 어떤 패턴이 존재하는지
  • 프로젝트에서 사용하는 용어가 무엇인지

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

  • 모든 것을 보내기: 컨텍스트 제한 초과
  • 아무것도 보내지 않기: 에이전트가 중요한 정보 부족
  • 필요한 것을 추측하기: 종종 틀림

해결책: 반복 검색

컨텍스트를 점진적으로 정제하는 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: 버그 수정 컨텍스트

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

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

사이클 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: 기능 구현

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

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

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

사이클 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. 자신 있게 제외 - 낮은 관련성 파일은 관련성이 생기지 않습니다

관련 항목

  • 장문 가이드 - 서브 에이전트 오케스트레이션 섹션
  • continuous-learning 스킬 - 시간이 지남에 따라 개선되는 패턴
  • 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/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

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.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

관련 스킬