Communitygithub.com

迭代式检索

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

迭代式检索 是什么?

迭代式检索模式主要解决多代理工作流中的“上下文问题”——子代理在开始工作前无法预知需要哪些上下文。该模式通过一个四阶段循环(分发→评估→精炼→循环,最多3次)实现:首先进行宽泛的关键词搜索以收集候选文件,然后评估检索结果的相关性并识别缺失上下文,接着根据评估结果调整搜索标准(添加新关键词、排除无关路径),最后重复循环直到收集到足够的上下文。该模式支持多种代理平台(如Claude Code、Cursor、Codex),有效避免了“全部发送”导致上下文超限和“发送太少”导致信息不足的问题。通过逐步精炼检索策略,它将高相关性文件(评分≥0.7)返回给子代理,同时优化了token使用。文档还提供了bug修复和功能实现的实际示例,展示了如何通过自适应学习项目术语来逐步缩小搜索范围,最终获得最相关的代码上下文。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/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:Bug修复上下文

任务:“修复认证Token过期Bug”

第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/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.

相关技能