Communitygithub.com

迭代检索模式

用于逐步精炼上下文检索的模式,解决子代理上下文问题。当子代理缺乏上下文且需要通过多次传递优化检索时使用。

迭代检索模式 是什么?

迭代检索模式(Iterative Retrieval Pattern)专为解决多代理工作流中的“上下文问题”而设计。在多代理场景中,子代理往往在被分发任务时无法预先得知所需的完整代码库上下文,从而导致“上下文过大”或“上下文缺失”等失败。该模式通过一个四阶段循环来逐步精炼检索:先进行广泛的初始查询(DISPATCH),然后评估已获取内容的关联性(EVALUATE),根据评估结果优化搜索条件(REFINE),最后重复循环(LOOP),最多执行3次。每次循环都会从代码库中学习术语、排除无关文件、并聚焦缺失的上下文。该模式在Claude Code、Cursor等代理工具中特别有用,可通过提示词或代码集成,避免一次性发送过多或过少上下文的问题,从而优化Token使用并提升任务成功率。

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

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

迭代检索模式 是做什么的?

解决多代理工作流中的“上下文问题”——子代理需要先工作才知道需要什么上下文。

何时激活

  • 分发子代理时,子代理需要无法预知的代码库上下文
  • 构建需要逐步精炼上下文的多代理工作流
  • 遇到代理任务中的“上下文过大”或“缺失上下文”错误
  • 为代码探索设计类似 RAG 的检索管道
  • 优化代理编排中的 Token 使用

问题

子代理被分发时只有有限的上下文。它们不知道:

  • 哪些文件包含相关代码
  • 代码库中存在哪些模式
  • 项目使用了什么术语

标准方法均会失败:

  • 发送所有内容:超出上下文限制
  • 不发送任何内容:代理缺少关键信息
  • 猜测所需内容:通常错误

解法:迭代检索

一个四阶段循环,逐步精炼上下文:

┌─────────────────────────────────────────────┐
│                                             │
│   ┌──────────┐      ┌──────────┐            │
│   │  分发    │─────│  评估    │            │
│   └──────────┘      └──────────┘            │
│        ▲                  │                 │
│        │                  ▼                 │
│   ┌──────────┐      ┌──────────┐            │
│   │  循环    │─────│  精炼    │            │
│   └──────────┘      └──────────┘            │
│                                             │
│          最多 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:故障修复上下文

任务:“修复认证令牌过期错误”

周期 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.

相关技能