Communitygithub.com

疊代式檢索

一種逐步精煉上下文檢索的模式,用於解決子代理的上下文問題。當子代理缺乏所需上下文,且需要跨多次檢索來精煉時使用。

疊代式檢索 是什麼?

此技能定義了一個「疊代式檢索模式」,專門解決多代理工作流程中常見的「上下文問題」——即子代理在開始工作前不知道自己需要哪些程式碼庫上下文。該模式透過一個四階段的循環(分派、評估、精煉、重複)來逐步收斂相關檔案,避免一次性發送過多內容而超出Token限制,或是僅憑猜測導致資訊不足。它特別適用於需要動態探索程式碼庫的情境,例如修復Bug或開發新功能時。技能文件提供了完整的實作概念、評估相關性的評分標準、JavaScript範例程式碼、以及與Bug修復和功能實作相關的實際應用案例。此模式支援在多代理系統(如Claude Code、Codex等)中以提示詞形式整合,並建議最多進行3次疊代循環,以達到「足夠好」的上下文品質。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/iterative-retrieval

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

疊代式檢索模式

解決多代理工作流程中的「上下文問題」——子代理在開始工作前不知道他們需要什麼上下文。

啟用時機

  • 生成需要程式碼庫上下文但無法事先預測的子代理
  • 構建逐步精煉上下文的多代理工作流程
  • 遇到代理任務中「上下文過大」或「缺少上下文」的失敗情況
  • 設計用於程式碼探索的 RAG 風格檢索管道
  • 優化代理編排中的 Token 使用量

問題

子代理生成時僅有有限的上下文。他們不知道:

  • 哪些檔案包含相關程式碼
  • 程式碼庫中存在哪些模式
  • 專案使用了什麼術語

標準方法會失敗:

  • 發送所有內容:超出上下文限制
  • 不發送任何內容:代理缺乏關鍵資訊
  • 猜測需要什麼:常常出錯

解決方案:疊代式檢索

一個逐步精煉上下文的4階段循環:

┌─────────────────────────────────────────────┐
│                                             │
│   ┌──────────┐      ┌──────────┐            │
│   │  分派   │─────│  評估   │            │
│   └──────────┘      └──────────┘            │
│        ▲                  │                 │
│        │                  ▼                 │
│   ┌──────────┐      ┌──────────┐            │
│   │  循環   │─────│  精煉   │            │
│   └──────────┘      └──────────┘            │
│                                             │
│        最多 3 次循環,然後繼續                 │
└─────────────────────────────────────────────┘

階段 1:分派

初始的廣泛查詢,用於收集候選檔案:

// 從高層意圖開始
const initialQuery = {
  patterns: ['src/**/*.ts', 'lib/**/*.ts'],
  keywords: ['authentication', 'user', 'session'],
  excludes: ['*.test.ts', '*.spec.ts']
};

// 分派給檢索代理
const candidates = await retrieveFiles(initialQuery);

階段 2:評估

評估檢索內容的相關性:

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:精煉

根據評估更新搜尋條件:

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:循環

使用精煉後的條件重複執行(最多 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:Bug 修復上下文

任務:「修復驗證 Token 到期錯誤」

第 1 輪:
  分派:在 src/** 中搜尋「token」、「auth」、「expiry」
  評估:找到 auth.ts (0.9), tokens.ts (0.8), user.ts (0.3)
  精煉:加入「refresh」、「jwt」關鍵字;排除 user.ts

第 2 輪:
  分派:搜尋精煉後的詞彙
  評估:找到 session-manager.ts (0.95), jwt-utils.ts (0.85)
  精煉:擁有足夠的上下文(2 個高相關性檔案)

結果:auth.ts, tokens.ts, session-manager.ts, jwt-utils.ts

範例 2:功能實作

任務:「為 API 端點加入速率限制」

第 1 輪:
  分派:在 routes/** 中搜尋「rate」、「limit」、「api」
  評估:無符合項目——程式碼庫使用「throttle」術語
  精煉:加入「throttle」、「middleware」關鍵字

第 2 輪:
  分派:搜尋精煉後的詞彙
  評估:找到 throttle.ts (0.9), middleware/index.ts (0.7)
  精煉:需要路由器模式

第 3 輪:
  分派:搜尋「router」、「express」模式
  評估:找到 router-setup.ts (0.8)
  精煉:擁有足夠的上下文

結果: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. 有信心地排除——低相關性檔案不會變得相關

相關資源

  • 長篇指南 - 子代理編排章節
  • 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.

相關技能