Claude Code Dynamic Workflows 学习笔记
1. 核心定义 【官方事实】
1.1 Dynamic Workflows 是什么
Dynamic Workflows(动态工作流)是 Claude Code 用 JavaScript workflow script 大规模编排 subagents(子代理)的机制。Claude 为任务写脚本,runtime 在后台执行,主会话保持响应。
A dynamic workflow is a JavaScript script that orchestrates subagents at scale. Claude writes the script for the task you describe, and a runtime executes it in the background while your session stays responsive.
- 形式:JS 脚本
- 内容:编排 subagents
- 写法:Claude 为任务写
- 执行:runtime 后台执行
- 效果:主会话保持响应
1.2 与其他多代理机制的区别
| 机制 | 本质 | 编排权 | 中间结果 | 规模 |
|---|---|---|---|---|
| Subagents | Claude 临时生成的工作者 | Claude 逐轮 | Claude 上下文窗口 | 每轮几个 |
| Skills | Claude 遵循的指令 | Claude 跟随 prompt | Claude 上下文窗口 | 接近 subagent |
| Agent teams | lead agent 监督 peer sessions | lead agent 逐轮 | 共享任务列表 | 少数长期对等 |
| Workflows | runtime 执行的脚本 | 脚本 | 脚本变量 | 数十到数百 agents |
核心差异:Workflow 把“计划”从 Claude 上下文移到代码里,因此中间结果保存在脚本变量中,编排本身可保存、可复用。
1.3 适用边界
官方示例:全仓库 bug 扫描、500 文件迁移、多来源交叉核查研究、多角度方案评审。
社区经验场景:大规模代码迁移 / 重构、深度研究与带引用报告、文档事实核查、对抗式验证、候选项排序、工单 triage、故障排查。
1.4 常用 workflow 模式 【社区说法】
| 模式 | 核心做法 | 适合任务 |
|---|---|---|
| 分类后路由 | 先判断任务 / 对象类型,再分派给 specialist agent | 工单 triage、规则分流、不同文件类型处理 |
| 并行拆分后汇总 | 按文件、模块、章节、候选项或检查维度 fan-out,再汇总 | 大规模迁移、批量审计、文档核查 |
| 对抗式验证 | finder 提发现,verifier / refuter 专门尝试反驳 | 安全审计、事实核查、高风险结论确认 |
| 生成后筛选 | 多个 agent 生成候选,再按 rubric 评分、去重、筛选 | 命名、文案、设计方向、prompt 方案 |
| 锦标赛式比较 | 候选两两比较或分组晋级,避免一次性全局排序质量下降 | 大量候选排序、主观方案评审 |
| 循环直到无新发现 | 多轮 finder 搜索,连续若干轮没有新结果后停止 | bug sweep、规则违反扫描、资料穷尽式研究 |
| 假设面板 + 反驳 | 多个 agent 提根因假设,再由 verifier/refuter 检验 | 故障排查、复杂问题诊断 |
| 读取者 / 执行者隔离 | 低权限 agent 读取不可信内容,高权限 agent 只接收清洗摘要 | 公开网页、issue、工单、用户提交内容处理 |
不适合:单文件小改动、目标模糊且不可验证的任务、纯确定性 IO / 定时 / ETL / SLA 工作流。
2. 可用性、启用条件与运行限制
2.1 可用性 【官方事实】
| 项 | 说明 |
|---|---|
| 阶段 | research preview |
| 版本 | Claude Code v2.1.154+ |
| 计划 | 所有付费计划可用;Pro 需在 /config 启用 |
| Provider | Anthropic API、Amazon Bedrock、Google Cloud Vertex AI、Microsoft Foundry |
| 表面 | CLI、Desktop、IDE 扩展、claude -p、Agent SDK 等 |
2.2 script 机制 【官方事实】 【脚本原语事实】
| 机制 | 用途 | 证据等级 |
|---|---|---|
| JavaScript script | 编排 subagents | 官方事实 |
args | saved workflow 接收输入 | 官方事实 |
agent() | 启动 subagent | 脚本原语事实 |
parallel() | barrier 型并行,等待全部完成 | 脚本原语事实 |
pipeline() | 流水线逐项穿过多个 stage | 脚本原语事实 |
phase() / log() | 阶段分组 / 进度日志 | 脚本原语事实 |
budget | 读取预算 total / spent() / remaining() | 脚本原语事实 |
agent()、parallel()、pipeline()、budget 的字段表;这些应标为 workflow script 中实测可用 / 可观察到的脚本原语,而不是官方页面正文直接给出的稳定 API 参考。2.3 parallel vs pipeline
| 函数 | 语义 | 适合场景 |
|---|---|---|
parallel(thunks) | barrier:全部并行,全部返回后继续 | 下一步必须看到所有结果,如全局去重 / 排序 / 早停 |
pipeline(items, ...stages) | 每个 item 独立穿过各 stage,快项不等慢项 | 多文件迁移、逐项审查、发现后立即验证 |
2.4 限制与权限
- 最多 16 个并发 agents;每次运行最多 1000 agents。
- 无中途用户输入;阶段间人工签署应拆成多个 workflow。
- 脚本不能直接文件系统 / shell;读写文件、运行命令由 agent 通过工具完成。
- 同一 session 内可恢复;退出 Claude Code 后,下次 session 从头启动。
- subagents 以
acceptEdits模式运行,文件编辑自动批准;但 shell、network fetch、不在 allowlist 的 MCP tools 仍可能提示。 - workflow 脚本不是 Node.js 全能力;不要依赖 filesystem / Node API,也避免
Date.now()、Math.random()等非确定性调用。
3. workflow script 的结构输出:两条路线
3.1 schema 的定位 【脚本原语事实】 【实测现象】
schema 是 runtime 支持的结构化输出机制。是否使用 schema 是工程取舍:schema 路线更干净、更强约束,但 schema mismatch 可能导致 agent 失败;防御式 JSON 路线更宽容,但要自己写 tryParseJson、isValidFinding、fallback。
实测中,schema 模式可能因结构化输出不匹配导致 agent 失败;防御式 JSON 路线适合更重视容错与兜底产物的场景。
3.2 路线 A:schema 结构化输出路线
const result = await agent('...', {
label: 'review:item-a',
phase: 'Review',
schema: SOME_JSON_SCHEMA,
})
| 优点 | 风险 |
|---|---|
| 返回对象更干净;runtime 帮忙验证 schema;下游代码更简单 | schema mismatch 可能导致 agent 失败;schema 太复杂或 prompt 不匹配时更敏感 |
3.3 路线 B:防御式 JSON 路线
agent 返回(可能是字符串)
→ tryParseJson 提取 JSON
→ isValidFinding / isValidVerdict 严格过滤
→ buildLocalReport 本地兜底
适合 schema 模式在当前环境不稳定、希望失败不拖垮整个 workflow、目标是尽量返回 useful artifact 的场景。
3.4 StructuredOutput 的正确理解
Error: agent({schema}): subagent completed without calling
StructuredOutput (after 2 in-conversation nudges)
StructuredOutput 不是用户 prompt 里应该手动要求调用的普通业务工具;它更像 runtime 在 schema 模式下注入 / 期待的内部结构化输出机制。4. 防御式 workflow 模式 【实测现象】
4.1 tryParseJson
function tryParseJson(s) {
if (s === null || s === undefined) return null
if (typeof s === 'object') return s
if (typeof s !== 'string') return null
try { return JSON.parse(s) } catch (_) {}
for (let i = 0; i < s.length; i++) {
const ch = s[i]
if (ch !== '{' && ch !== '[') continue
// ...扫描平衡 JSON 块
}
return null
}
4.2 isValidFinding / isValidVerdict
const SEVERITIES = ['low', 'medium', 'high', 'critical']
const CONFIDENCES = ['low', 'medium', 'high']
const STATUSES = ['confirmed', 'uncertain', 'refuted']
function isValidFinding(f) {
return !!f
&& typeof f.id === 'string' && f.id.length > 0
&& typeof f.summary === 'string' && f.summary.length > 0
&& typeof f.severity === 'string' && SEVERITIES.includes(f.severity)
&& typeof f.confidence === 'string' && CONFIDENCES.includes(f.confidence)
&& typeof f.rationale === 'string' && f.rationale.length > 0
}
4.3 buildLocalReport
const report = isValidReport(reportParsed)
? reportParsed
: buildLocalReport(annotated)
核心思想:不完全依赖 synthesize agent;即便 synthesize agent 失败,脚本也能从 annotated findings 拼出 useful artifact。
4.4 prompt 三件套
TASK: <具体目标>
Return ONE JSON object with exactly these fields:
{ id, summary, severity, confidence, rationale }
BOUNDARY:
- Return ONLY the JSON object. No prose, no markdown fences.
- Do not invent file paths, line numbers, or function names.
5. 实测错误清单 【实测现象】
| 做法 | 风险 / 后果 | 推荐处理 |
|---|---|---|
| 使用 schema 路线 | schema mismatch 可能导致 agent 失败 | 保持 schema 简洁,并让 prompt 与 schema 对齐;若失败容忍度更重要,可改用防御式 JSON 路线 |
| 业务 prompt 中要求“调用 StructuredOutput 工具” | 可能误导 agent | 不在业务 prompt 中提 StructuredOutput |
| 告诉 agent “runtime 会校验你的输出” | 污染 prompt、引入无关机制描述 | 只明确业务 shape / boundary |
| 在业务 prompt 中混入 runtime 内部机制描述 | 污染 prompt、引入无关信息 | prompt 只描述任务、返回结构和边界;脚本层负责解析、过滤和兜底 |
findings 为空
findings 为空 ≠ 一定没发现问题;可能是 agent 返回字符串 / prose / 非结构化对象,导致过滤失败。应看 transcript、加 tryParseJson、强化 Return ONLY JSON。
6. agent() 字段与模型路由
6.1 默认模型行为 【官方事实】
Every agent in a workflow uses your session's model unless the script routes a stage to a different one.
6.2 agent() 字段 【脚本原语事实】
await agent(prompt, {
label: 'review:item-a',
phase: 'Review',
model: 'claude-haiku-4-5',
schema: SOME_SCHEMA,
})
agent(prompt, { label, phase, schema }) 可返回结构化对象,agent(prompt, { label, phase, model }) 可正常返回文本。官方 workflows 页面说明了 phase 展示和 model 路由概念,但没有把 label / phase / model / schema 列为稳定公开 API 字段表。6.3 模型路由
const MODEL_REGISTRY = {
cheap: 'claude-haiku-4-5',
strong: 'claude-opus-4-8',
}
await agent(prompt, {
label: 'triage:item-b',
phase: 'Triage',
model: MODEL_REGISTRY.cheap,
})
7. args、保存与触发方式 【官方事实】
7.1 args
saved workflow 可通过 args 接收输入。脚本中读取全局变量 args;未传入时为 undefined。
> Run /triage-issues on issues 1024, 1025, and 1030
7.2 保存位置
| 位置 | 路径 | 特点 |
|---|---|---|
| 项目级 | .claude/workflows/ | 随项目共享 |
| 用户级 | ~/.claude/workflows/ | 多项目可用,仅自己可见 |
| 同名优先 | 项目级 | 项目 workflow 覆盖同名用户 workflow |
7.3 触发方式
/deep-research内置 workflow- prompt 中包含
ultracode - 自然语言明确要求 “use a workflow” / “run a workflow” / “fan out agents”
/effort ultracode:对实质性任务自动规划 workflow- 保存后通过
/<name>运行
8. 用户侧核心能力
8.1 判断何时用
适合:多文件 / 大规模 / 可并行 / 可验证 / 需要对抗验证或多角度比较
不适合:单文件小改动 / 目标模糊 / 纯确定性集成 / 成本高于收益
8.2 写 workflow request 的 8 个要素
| 要素 | 含义 |
|---|---|
| Goal | 我要完成什么 |
| Scope | 检查哪里、不检查哪里 |
| Permission | 只读还是允许修改 |
| Target items | 处理对象 |
| Checks | 检查项 |
| Evidence | 每个发现必须有证据 |
| Verification | 高危要反驳 / 独立验证 |
| Output | 最终报告格式 |
8.3 审查 script
- meta / phases 是否清楚。
- agent() 字段是否符合实测可用写法,如
{ label, phase, model, schema }。 - 如果使用 schema:schema 是否过复杂,prompt 是否与 schema 一致。
- 如果不用 schema:是否有
tryParseJson。 - 是否有严格过滤与 fallback。
- prompt 是否有 TASK / shape / BOUNDARY,且不要提 runtime 内部机制。
- parallel / pipeline 是否选对。
8.4 不可信输入隔离
处理公开网页、issue、工单等不可信内容时,应隔离低权限读取 agent 与高权限执行 agent,避免原始恶意内容直接影响高权限操作。
9. 社区文章核对结论 【社区说法】
9.1 可采纳为社区经验
- 动态 workflow 把计划移入代码。
- 多 agent 隔离上下文,降低长上下文漂移。
- 适合迁移、审计、研究、事实核查、对抗验证。
- 常见模式:fan-out 汇总、对抗验证、生成筛选、锦标赛比较、循环直到无新发现。
- 成本较高,小任务不值得。
/workflows可查看进度,按s保存。
9.2 不要直接写成官方事实
- Bun 从 Zig 到 Rust 重写使用 Dynamic Workflows 的具体数据。
- Anthropic 内部团队已使用数月。
- 某个案例具体用了多少 agents、多少 tokens、耗时多久。
- “Claude API 支持 workflows”这类笼统表述;更准确是 Claude Code surfaces、
claude -p、Agent SDK。 - “恢复后继续”必须限定为同一 Claude Code session 内。
10. 关键口诀
workflow script 负责调度。真正读文件、改文件、跑命令的是 subagent。
schema 路线:
agent(prompt, { schema }),返回更干净但失败更硬。防御式 JSON 路线:不传 schema,靠
tryParseJson / isValidX / fallback 兜底。verifier prompt:
TRY TO REFUTE、Do NOT just agree。11. 调试原则
11.1 证据等级
官方事实 > 脚本原语事实 > 实测现象 > 社区说法 > 教学推测
11.2 排障顺序
- 先看
/workflows进度和 agent 详情。 - 再看 transcript 中 agent 实际返回了什么。
- 判断是 schema 路线失败,还是防御式 JSON 路线解析 / 过滤失败。
- schema 失败:简化 schema、强化 prompt,或改走防御式 JSON。
- findings 空:检查
tryParseJson、isValidFinding、prompt shape。
11.3 成本与范围
- 大任务先小范围试跑。
/workflows视图看每个 agent 的 token 使用。- 可在 prompt 中要求某些阶段使用较小模型。
- 可用
budget在脚本中控制后续 agent 调用。
12. 相关资源
12.1 官方文档
12.2 社区文章
- https://x.com/PandaTalk8/status/2063918562318946740
- https://x.com/trq212/status/2061907337154367865
- https://x.com/0xCodez/status/2062127385923776831
- https://x.com/knoYee_/status/2062144250532561370
- https://x.com/AlphaSignalAI/status/2060361091474223504
- https://x.com/so_ainsight/status/2060598271161291042
🧪 复习测验
Q1:Dynamic Workflows 最核心的机制是什么?
Q2:哪些任务更适合使用 Dynamic Workflows?(多选)
Q3:关于 schema 路线与防御式 JSON 路线,哪种说法正确?
Q4:关于 parallel() 与 pipeline(),哪些说法正确?(多选)
Q5:关于 workflow 恢复能力,哪种说法正确?
Q6:哪些属于官方 workflows 页面明确说明的内容?(多选)
Q7:把防御式 JSON 路线按数据流排序
- ≡ agent 返回(可能是字符串或 prose)
- ≡ tryParseJson 提取 JSON
- ≡ isValidFinding / isValidVerdict 严格过滤
- ≡ buildLocalReport / fallback 兜底