Communitygithub.com

反復検索パターン

サブエージェントのコンテキスト問題を解決するために、コンテキスト取得を段階的に絞り込むパターン。サブエージェントが必要なコンテキストを把握していない場合、複数パスにわたって検索を洗練する際に使用します。

反復検索パターン とは?

Iterative Retrieval(反復検索)パターンは、マルチエージェントワークフローにおいて、サブエージェントが必要とするコードベースのコンテキストを効率的に取得するための手法です。通常、サブエージェントは起動時に限られたコンテキストしか持たず、「どのファイルが関連するか」「コードベースで使われている用語は何か」を事前に知ることができません。このパターンは、DISPATCH(初期探索)、EVALUATE(関連性評価)、REFINE(検索条件の洗練)、LOOP(最大3サイクルの反復)の4フェーズからなるループで、段階的にコンテキストを絞り込みます。初期は広いキーワード検索から始め、取得したファイルの関連性をスコアリングし、不足している情報を特定して検索条件を更新します。これにより、過剰なトークン使用を避けつつ、必要なファイルだけを効率的に取得できます。特にコード探索におけるRAG(検索拡張生成)パイプラインの設計や、エージェントのトークン最適化に有効で、Claude Codeや他のAIエージェントフレームワークと統合可能です。

対応~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. 「十分良い」ところで止める - 高関連ファイル3個は中程度のファイル10個より優れている
  5. 確信を持って除外する - 低関連ファイルが関連することはない

関連項目

  • The Longform Guide - サブエージェントオーケストレーションセクション
  • 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.

関連スキル