mcpField
I
iterative-retrieval

iterative-retrieval

github.com/joneqianAgent 工作流3248 次安装37 周前更新
代码仓库

关于 iterative-retrieval

iterative-retrieval 是面向多 Agent 工作流的上下文检索模式,适用于需要为子 Agent 找到相关代码的开发任务。它通过检索、相关性评估、调整条件和循环,逐步补全上下文,最多执行 3 轮。

主要功能

  1. 01分阶段检索代码文件
  2. 02按任务评估文件相关性
  3. 03识别缺失上下文
  4. 04根据发现调整检索条件
  5. 05最多循环 3 轮

适用场景

  1. 01为 Bug 修复查找相关代码
  2. 02为功能开发定位实现模式
  3. 03发现代码库使用的术语
  4. 04筛除低相关文件以控制上下文

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/joneqian/claude-skills-suite --skill iterative-retrieval

安装后在 Claude Code 中输入/iterative-retrieval确认已加载。

详细介绍

迭代检索模式

解决多 Agent 工作流中的“上下文问题”:子 Agent 在开始工作之前,不知道自己需要哪些上下文。

问题

子 Agent 启动时,获得的上下文有限。他们不知道:

  • 哪些文件包含相关代码
  • 代码库中有哪些模式
  • 项目使用哪些术语

常见方法都行不通:

  • 发送所有内容:超出上下文限制
  • 什么都不发送:Agent 缺少关键信息
  • 猜测需要什么:往往猜错

解决方案:迭代检索

一个分 4 个阶段、逐步优化上下文的循环:

┌─────────────────────────────────────────────┐
│                                             │
│   ┌──────────┐      ┌──────────┐            │
│   │ DISPATCH │─────▶│ EVALUATE │            │
│   └──────────┘      └──────────┘            │
│        ▲                  │                 │
│        │                  ▼                 │
│   ┌──────────┐      ┌──────────┐            │
│   │   LOOP   │◀─────│  REFINE  │            │
│   └──────────┘      └──────────┘            │
│                                             │
│        Max 3 cycles, then proceed           │
└─────────────────────────────────────────────┘
阶段 1:分发

先发起宽泛查询,收集候选文件:

// Start with high-level intent
const initialQuery = {
  patterns: ['src/**/*.ts', 'lib/**/*.ts'],
  keywords: ['authentication', 'user', 'session'],
  excludes: ['*.test.ts', '*.spec.ts']
};

// Dispatch to retrieval agent
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 {
    // Add new patterns discovered in high-relevance files
    patterns: [...previousQuery.patterns, ...extractPatterns(evaluation)],

    // Add terminology found in codebase
    keywords: [...previousQuery.keywords, ...extractKeywords(evaluation)],

    // Exclude confirmed irrelevant paths
    excludes: [...previousQuery.excludes, ...evaluation
      .filter(e => e.relevance < 0.2)
      .map(e => e.path)
    ],

    // Target specific gaps
    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);

    // Check if we have sufficient context
    const highRelevance = evaluation.filter(e => e.relevance >= 0.7);
    if (highRelevance.length >= 3 && !hasCriticalGaps(evaluation)) {
      return highRelevance;
    }

    // Refine and continue
    query = refineQuery(evaluation, query);
    bestContext = mergeContext(bestContext, highRelevance);
  }

  return bestContext;
}

实际示例

示例 1:Bug 修复上下文
Task: "Fix the authentication token expiry bug"

Cycle 1:
  DISPATCH: Search for "token", "auth", "expiry" in src/**
  EVALUATE: Found auth.ts (0.9), tokens.ts (0.8), user.ts (0.3)
  REFINE: Add "refresh", "jwt" keywords; exclude user.ts

Cycle 2:
  DISPATCH: Search refined terms
  EVALUATE: Found session-manager.ts (0.95), jwt-utils.ts (0.85)
  REFINE: Sufficient context (2 high-relevance files)

Result: auth.ts, tokens.ts, session-manager.ts, jwt-utils.ts
示例 2:功能实现
Task: "Add rate limiting to API endpoints"

Cycle 1:
  DISPATCH: Search "rate", "limit", "api" in routes/**
  EVALUATE: No matches - codebase uses "throttle" terminology
  REFINE: Add "throttle", "middleware" keywords

Cycle 2:
  DISPATCH: Search refined terms
  EVALUATE: Found throttle.ts (0.9), middleware/index.ts (0.7)
  REFINE: Need router patterns

Cycle 3:
  DISPATCH: Search "router", "express" patterns
  EVALUATE: Found router-setup.ts (0.8)
  REFINE: Sufficient context

Result: throttle.ts, middleware/index.ts, router-setup.ts

与 Agent 集成

在 Agent 提示词中使用:

When retrieving context for this task:
1. Start with broad keyword search
2. Evaluate each file's relevance (0-1 scale)
3. Identify what context is still missing
4. Refine search criteria and repeat (max 3 cycles)
5. Return files with relevance >= 0.7

最佳实践

  1. 先宽后窄,逐步收敛 - 初始查询不要设定过多限制
  2. 了解代码库术语 - 第一轮通常会揭示命名约定
  3. 记录缺失内容 - 明确指出缺口有助于细化查询
  4. 适可而止 - 3 个高度相关的文件胜过 10 个一般相关的文件
  5. 果断排除 - 相关性低的文件不会变得相关

相关内容

  • 长篇指南 - 子 Agent 编排部分
  • continuous-learning 技能 - 用于随时间改进的模式
  • ~/.claude/agents/ 中的 Agent 定义

评论

支持 Markdown