automation-refactor

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Automation Refactor

自动化工作流重构

Expert system for refactoring and optimizing automation workflows across multiple platforms while maintaining functional equivalence and improving code quality.
专业系统,用于跨多个平台重构和优化自动化工作流,同时保持功能等效性并提升代码质量。

Supported Platforms

支持的平台

  • Power Automate (Microsoft)
  • n8n (Open-source automation)
  • Make (formerly Integromat)
  • Zapier
  • Other JSON-based workflow platforms
  • Power Automate(微软)
  • n8n(开源自动化工具)
  • Make(前身为Integromat)
  • Zapier
  • 其他基于JSON的工作流平台

Purpose

核心目标

This skill provides comprehensive workflow refactoring by:
  1. Analyzing existing workflow JSON for improvement opportunities
  2. Applying platform-specific best practices from documentation (Docs/ directory)
  3. Optimizing performance, reliability, and maintainability
  4. Generating refactored JSON that maintains original functionality
  5. Providing detailed report of changes and additional optimization suggestions
  6. Ensuring no hallucinations by strictly referencing platform documentation
本工具通过以下方式提供全面的工作流重构:
  1. 分析现有工作流JSON,寻找改进空间
  2. 应用平台文档(Docs/目录)中的特定最佳实践
  3. 优化性能、可靠性和可维护性
  4. 生成保留原有功能的重构后JSON
  5. 提供变更详情报告及额外优化建议
  6. 通过严格参考平台文档确保无虚构内容

Common Pitfalls to AVOID

需规避的常见陷阱

❌ CRITICAL ERROR #1: Assuming Data Structures (Most Common!)

❌ 严重错误#1:假设数据结构(最常见!)

The Mistake:
json
// You see a variable used in a filter
"where": "@contains(item(), 'keyword')"

// And you ASSUME it's an array of objects, so you write:
"value": "@items('Loop')?['PropertyName']"  // ← WRONG!
The Reality:
json
// item() without property → Array of STRINGS!
// Correct usage:
"value": "@items('Loop')"  // ← RIGHT!
How to Avoid:
  1. ALWAYS look at the filter's
    where
    clause first
  2. item()
    = array of primitives (strings/numbers)
  3. item()?['Prop']
    = array of objects
  4. Ask user if unsure - never guess!

错误行为:
json
// 你看到过滤器中使用了变量
"where": "@contains(item(), 'keyword')"

// 然后你假设它是对象数组,于是写出:
"value": "@items('Loop')?['PropertyName']"  // ← 错误!
实际情况:
json
// 不带属性的item() → 字符串数组!
// 正确用法:
"value": "@items('Loop')"  // ← 正确!
规避方法:
  1. 始终先查看过滤器的
    where
    子句
  2. item()
    = 原始类型数组(字符串/数字)
  3. item()?['Prop']
    = 对象数组
  4. 若不确定,询问用户 - 绝不猜测!

❌ ERROR #2: Not Researching Documentation

❌ 错误#2:未查阅文档

The Mistake: Guessing connector outputs, property names, or behaviors
How to Avoid:
  1. Search local Docs/ directory FIRST
  2. Use WebSearch for official docs if not found locally
  3. Ask user to confirm if documentation is unclear
  4. Reference specific documentation sections in your output

错误行为: 猜测连接器输出、属性名称或行为
规避方法:
  1. 优先搜索本地Docs/目录
  2. 若本地未找到,使用WebSearch查找官方文档
  3. 若文档不明确,请求用户确认
  4. 在输出中引用具体文档章节

❌ ERROR #3: Overconfidence Without Validation

❌ 错误#3:未验证就过度自信

The Mistake: Providing fixes without verifying against actual data structures
How to Avoid:
  1. Complete Phase 0 (Data Structure Analysis) BEFORE any changes
  2. Use AskUserQuestion tool when ambiguous
  3. Test your logic against the actual data flow
  4. Verify all
    item()
    /
    items()
    usages match data types

错误行为: 未针对实际数据结构验证就提供修复方案
规避方法:
  1. 在进行任何重构前,完成第0阶段(数据结构分析)
  2. 存在歧义时使用AskUserQuestion工具
  3. 针对实际数据流测试逻辑
  4. 验证所有
    item()
    /
    items()
    用法与数据类型匹配

When This Skill Activates

触发场景

Automatically activates when user requests:
  • Optimization keywords: "optimize", "improve", "enhance", "refactor", "modernize"
  • Correction keywords: "correct", "fix values", "update parameters", "change configuration"
  • Performance keywords: "make faster", "reduce API calls", "improve performance"
  • Best practices: "apply best practices", "follow standards", "clean up"
  • Maintenance: "simplify", "make more readable", "reduce complexity"
  • Provides flow JSON: User shares workflow JSON asking for improvements
  • Platform-specific: "refactor my Power Automate flow", "optimize this n8n workflow", "improve Make scenario"
Examples of triggering phrases:
  • "Optimize this flow to reduce API calls"
  • "Refactor this workflow to follow best practices"
  • "Improve the error handling in this flow"
  • "Make this automation more reliable"
  • "Correct the values in this flow"
  • "Enhance this workflow's performance"
  • "Simplify this complex flow"
  • "Modernize this old workflow"
当用户提出以下请求时自动激活:
  • 优化类关键词: "optimize"(优化)、"improve"(改进)、"enhance"(增强)、"refactor"(重构)、"modernize"(现代化)
  • 修正类关键词: "correct"(修正)、"fix values"(修正值)、"update parameters"(更新参数)、"change configuration"(变更配置)
  • 性能类关键词: "make faster"(提速)、"reduce API calls"(减少API调用)、"improve performance"(提升性能)
  • 最佳实践类: "apply best practices"(应用最佳实践)、"follow standards"(遵循标准)、"clean up"(清理)
  • 维护类: "simplify"(简化)、"make more readable"(提升可读性)、"reduce complexity"(降低复杂度)
  • 提供工作流JSON: 用户分享工作流JSON并请求改进
  • 平台特定请求: "refactor my Power Automate flow"(重构我的Power Automate工作流)、"optimize this n8n workflow"(优化这个n8n工作流)、"improve Make scenario"(改进Make场景)
触发语句示例:
  • "Optimize this flow to reduce API calls"(优化此工作流以减少API调用)
  • "Refactor this workflow to follow best practices"(重构此工作流以遵循最佳实践)
  • "Improve the error handling in this flow"(改进此工作流的错误处理)
  • "Make this automation more reliable"(提升此自动化的可靠性)
  • "Correct the values in this flow"(修正此工作流中的值)
  • "Enhance this workflow's performance"(增强此工作流的性能)
  • "Simplify this complex flow"(简化这个复杂的工作流)
  • "Modernize this old workflow"(现代化这个旧工作流)

Core Workflow

核心工作流程

Phase 0: Data Structure Analysis (CRITICAL)

第0阶段:数据结构分析(至关重要)

NEVER assume data structures without verification. Before any refactoring, ALWAYS analyze the actual data structures in the flow.
  1. Examine Variable Declarations
    • Check all variable initializations to understand data types
    • Look for:
      "type": "Array"
      ,
      "type": "String"
      ,
      "type": "Object"
    • Document the structure of each variable
  2. Analyze Filter/Query Operations
    • CRITICAL CHECK: Look at
      where
      clauses in Query actions
    • If you see
      item()
      without property access → Array of primitives (strings/numbers)
      json
      "where": "@contains(toLower(item()), 'keyword')"
      // ↑ This means: Array of strings, NOT array of objects!
    • If you see
      item()?['PropertyName']
      Array of objects
      json
      "where": "@contains(item()?['Name'], 'keyword')"
      // ↑ This means: Array of objects with 'Name' property
  3. Trace Data Sources
    • Follow
      from
      parameter in Query actions back to source
    • Check SharePoint GetFileItems/GetItems outputs
    • Check Select action mappings (these define output structure)
    • Verify Compose action inputs
  4. Validate Item Access Patterns
    • In loops:
      items('LoopName')
      vs
      items('LoopName')?['Property']
    • In filters:
      item()
      vs
      item()?['Property']
    • MISMATCH = BUG: If filter uses
      item()
      but loop uses
      items('Loop')?['Prop']
      → ERROR!
  5. Ask User When Uncertain (Use AskUserQuestion tool)
    • If data structure is ambiguous
    • If documentation doesn't clarify the structure
    • If multiple interpretations are possible
    Example questions to ask:
    • "I see your filter uses
      contains(item(), 'keyword')
      . Does this mean your variable contains an array of strings like
      ['string1', 'string2']
      , or does it contain an array of objects?"
    • "Can you confirm whether the output from [ActionName] is an array of strings or an array of objects with properties?"
    • "I notice a mismatch: the filter treats data as strings but the loop accesses it as objects. Which is correct?"
绝不未验证就假设数据结构。在进行任何重构前,务必分析工作流中的实际数据结构。
  1. 检查变量声明
    • 查看所有变量初始化以了解数据类型
    • 关注:
      "type": "Array"
      "type": "String"
      "type": "Object"
    • 记录每个变量的结构
  2. 分析过滤器/查询操作
    • 关键检查: 查看Query操作中的
      where
      子句
    • 若看到不带属性访问的
      item()
      原始类型数组(字符串/数字)
      json
      "where": "@contains(toLower(item()), 'keyword')"
      // ↑ 这意味着:字符串数组,而非对象数组!
    • 若看到
      item()?['PropertyName']
      对象数组
      json
      "where": "@contains(item()?['Name'], 'keyword')"
      // ↑ 这意味着:包含'Name'属性的对象数组
  3. 追踪数据源
    • 追溯Query操作中
      from
      参数的来源
    • 检查SharePoint GetFileItems/GetItems输出
    • 检查Select操作映射(这些定义了输出结构)
    • 验证Compose操作输入
  4. 验证项访问模式
    • 循环中:
      items('LoopName')
      vs
      items('LoopName')?['Property']
    • 过滤器中:
      item()
      vs
      item()?['Property']
    • 不匹配= bug: 若过滤器使用
      item()
      但循环使用
      items('Loop')?['Prop']
      → 错误!
  5. 不确定时询问用户(使用AskUserQuestion工具)
    • 若数据结构存在歧义
    • 若文档未明确结构
    • 若存在多种解读可能
    示例问题:
    • "我看到你的过滤器使用了
      contains(item(), 'keyword')
      。这是否意味着你的变量包含类似
      ['string1', 'string2']
      的字符串数组,还是包含对象数组?"
    • "你能否确认[ActionName]的输出是字符串数组还是带属性的对象数组?"
    • "我注意到不匹配:过滤器将数据视为字符串,但循环将其作为对象访问。哪个是正确的?"

Phase 1: Initial Analysis

第1阶段:初始分析

  1. Extract Flow Information
    • Parse the provided JSON (flow.json or workflow snippet)
    • Identify platform (Power Automate, n8n, Make, Zapier, etc.)
    • Map all triggers, actions, and dependencies
    • Understand the flow's purpose and logic
    • Note current configuration and parameters
  2. Identify User Requirements
    • Parse user's refactoring brief/request
    • Determine specific changes requested (if any)
    • Identify optimization goals (performance, reliability, maintainability)
    • Note constraints (must maintain functionality, specific requirements)
  3. Baseline Documentation
    • Document current flow behavior
    • List all connectors/nodes used
    • Map data flow and transformations
    • Note existing error handling (or lack thereof)
  1. 提取工作流信息
    • 解析提供的JSON(flow.json或工作流片段)
    • 识别平台(Power Automate、n8n、Make、Zapier等)
    • 映射所有触发器、操作和依赖关系
    • 理解工作流的目标和逻辑
    • 记录当前配置和参数
  2. 识别用户需求
    • 解析用户的重构说明/请求
    • 确定用户要求的具体变更(如有)
    • 识别优化目标(性能、可靠性、可维护性)
    • 记录约束条件(必须保留功能、特定要求)
  3. 基准文档记录
    • 记录当前工作流行为
    • 列出所有使用的连接器/节点
    • 映射数据流和转换过程
    • 记录现有错误处理(或缺失情况)

Phase 2: Comprehensive Analysis (Multi-Source Research)

第2阶段:全面分析(多来源调研)

CRITICAL: Always research thoroughly before making changes. Use multiple sources in this order:
关键: 进行变更前务必充分调研。按以下顺序使用多来源信息:

Step 1: Local Documentation Research (Use Task Tool with Explore Agent)

步骤1:本地文档调研(使用Task工具调用Explore Agent)

Launch research sub-agent with thorough investigation:
Use Task tool with subagent_type="Explore" and thoroughness="very thorough"

Prompt: "Research [PLATFORM] best practices and optimization guidelines for workflow refactoring, focusing on [CONNECTORS/NODES USED].

Platform: [Power Automate / n8n / Make / Zapier / Other]

Search in Docs/ directory for:
1. Platform best practices documentation (Docs/{Platform}_Documentation/)
2. Connector/node-specific optimization guidelines
3. Data structure specifications (what properties exist, array vs object)
4. Common performance anti-patterns
5. Error handling best practices
6. API rate limit optimization strategies
7. Expression/formula optimization patterns
8. Security best practices

Focus on finding:
- **DATA STRUCTURE DETAILS** (output schemas, property names, data types)
- Performance optimization opportunities
- Reliability improvements (error handling, retry logic)
- Maintainability enhancements (naming, structure, comments)
- Security improvements (credential handling, input validation)
- API efficiency (batching, filtering, pagination)
- Platform-specific recommendations

For each connector/node in the flow, find:
- Output schema/structure (CRITICAL!)
- Recommended configuration patterns
- Known limitations to consider
- Optimization techniques
- Common mistakes to avoid

Return specific file paths, sections, and exact recommendations."
Expected Output from Research Agent:
  • Data structure specifications (schemas, property names)
  • Best practices documentation references
  • Connector-specific optimization guidelines
  • Performance improvement patterns
  • Error handling recommendations
  • Security considerations
  • Platform-specific optimizations
启动调研子代理进行全面调查:
使用Task工具,设置subagent_type="Explore",thoroughness="very thorough"

提示:"调研[PLATFORM]工作流重构的最佳实践和优化指南,重点关注[CONNECTORS/NODES USED]。

平台:[Power Automate / n8n / Make / Zapier / 其他]

在Docs/目录中搜索:
1. 平台最佳实践文档(Docs/{Platform}_Documentation/)
2. 连接器/节点特定优化指南
3. 数据结构规范(存在哪些属性、数组vs对象)
4. 常见性能反模式
5. 错误处理最佳实践
6. API速率限制优化策略
7. 表达式/公式优化模式
8. 安全最佳实践

重点查找:
- **数据结构细节**(输出模式、属性名称、数据类型)
- 性能优化机会
- 可靠性改进(错误处理、重试逻辑)
- 可维护性增强(命名、结构、注释)
- 安全改进(凭证管理、输入验证)
- API效率(批量处理、过滤、分页)
- 平台特定建议

针对工作流中的每个连接器/节点,查找:
- 输出模式/结构(至关重要!)
- 推荐配置模式
- 需要考虑的已知限制
- 优化技术
- 需规避的常见错误

返回具体文件路径、章节和确切建议。"
调研代理预期输出:
  • 数据结构规范(模式、属性名称)
  • 最佳实践文档引用
  • 连接器特定优化指南
  • 性能改进模式
  • 错误处理建议
  • 安全注意事项
  • 平台特定优化方案

Step 2: Web Research (Use WebSearch Tool - If Local Documentation Insufficient)

步骤2:网络调研(使用WebSearch工具 - 仅当本地文档不足时)

ONLY if local documentation doesn't provide needed information, use WebSearch:
Use WebSearch tool with targeted queries:

Examples:
- "Power Automate GetFileItems output schema properties"
- "Power Automate array of strings vs array of objects filter syntax"
- "n8n HTTP Request node output structure"
- "Make iterator data structure format"

Search for:
- Official Microsoft Learn documentation
- Platform-specific forums (Power Users Community)
- Official API documentation
- Verified Stack Overflow answers (check dates!)
Validation Requirements:
  • Prefer official documentation over community posts
  • Cross-reference multiple sources
  • Verify information is current (check dates)
  • Test with user if uncertain
仅当本地文档未提供所需信息时,使用WebSearch:
使用WebSearch工具进行定向查询:

示例:
- "Power Automate GetFileItems输出模式属性"
- "Power Automate字符串数组vs对象数组过滤器语法"
- "n8n HTTP Request节点输出结构"
- "Make迭代器数据结构格式"

搜索目标:
- 官方Microsoft Learn文档
- 平台特定论坛(Power Users社区)
- 官方API文档
- 经过验证的Stack Overflow答案(注意日期!)
验证要求:
  • 优先选择官方文档而非社区帖子
  • 交叉参考多个来源
  • 验证信息是否最新(检查日期)
  • 若不确定,与用户测试确认

Step 3: Ask User for Clarification (Use AskUserQuestion Tool)

步骤3:请求用户澄清(使用AskUserQuestion工具)

If both local docs and web search are unclear, ask the user:
Use AskUserQuestion tool with specific questions:

Example:
{
  "questions": [{
    "question": "Your flow uses `contains(item(), 'CNESST')`. Can you confirm what type of data is in your variable?",
    "header": "Data Type",
    "options": [
      {
        "label": "Array of strings",
        "description": "Like ['CNESST 2025-01', 'INVALIDITÉ 2025-02']"
      },
      {
        "label": "Array of objects",
        "description": "Like [{'Nom': 'CNESST 2025-01'}, {'Nom': 'INVALIDITÉ 2025-02'}]"
      }
    ],
    "multiSelect": false
  }]
}
When to Ask:
  • Data structure is ambiguous
  • Multiple valid interpretations exist
  • Documentation contradicts observed patterns
  • Risk of introducing bugs with assumptions
若本地文档和网络搜索均不明确,询问用户:
使用AskUserQuestion工具提出具体问题:

示例:
{
  "questions": [{
    "question": "你的工作流使用了`contains(item(), 'CNESST')`。能否确认你的变量中存储的是什么类型的数据?",
    "header": "数据类型",
    "options": [
      {
        "label": "字符串数组",
        "description": "例如 ['CNESST 2025-01', 'INVALIDITÉ 2025-02']"
      },
      {
        "label": "对象数组",
        "description": "例如 [{'Nom': 'CNESST 2025-01'}, {'Nom': 'INVALIDITÉ 2025-02'}]"
      }
    ],
    "multiSelect": false
  }]
}
询问时机:
  • 数据结构存在歧义
  • 存在多种有效解读
  • 文档与观察到的模式矛盾
  • 假设可能引入bug

Phase 3: Improvement Identification

第3阶段:识别改进点

Based on research findings, identify opportunities in these categories:
基于调研结果,从以下类别识别改进机会:

1. Performance Optimizations

1. 性能优化

  • API call reduction: Batch operations, filtering at source
  • Concurrency: Parallel execution where safe
  • Data minimization: Fetch only needed fields
  • Caching: Reuse data within flow
  • Loop optimization: Reduce iterations, early exits
  • 减少API调用: 批量操作、源头过滤
  • 并发处理: 安全场景下使用并行执行
  • 数据最小化: 仅获取所需字段
  • 缓存: 在工作流内复用数据
  • 循环优化: 减少迭代次数、提前退出

2. Reliability Improvements

2. 可靠性改进

  • Error handling: Add Scopes with Configure run after
  • Retry logic: Implement exponential backoff for transient failures
  • Timeout handling: Set appropriate limits
  • Data validation: Check inputs before processing
  • Idempotency: Ensure operations can be retried safely
  • 错误处理: 添加带Configure run after的Scopes
  • 重试逻辑: 为临时故障实现指数退避
  • 超时处理: 设置适当限制
  • 数据验证: 处理前检查输入
  • 幂等性: 确保操作可安全重试

3. Maintainability Enhancements

3. 可维护性增强

  • Naming conventions: Clear, descriptive action names
  • Comments: Document complex logic
  • Structure: Organize related actions in Scopes
  • Variables: Proper initialization and naming
  • Modularity: Break complex flows into logical sections
  • 命名规范: 清晰、描述性的操作名称
  • 注释: 记录复杂逻辑
  • 结构: 将相关操作组织到Scopes中
  • 变量: 正确初始化和命名
  • 模块化: 将复杂工作流拆分为逻辑部分

4. Security Hardening

4. 安全强化

  • Credential management: Use secure connections
  • Input validation: Sanitize user inputs
  • Data exposure: Minimize sensitive data in logs
  • Least privilege: Use minimal required permissions
  • Secret handling: Never hardcode credentials
  • 凭证管理: 使用安全连接
  • 输入验证: 清理用户输入
  • 数据暴露: 最小化日志中的敏感数据
  • 最小权限: 使用所需的最低权限
  • 密钥处理: 绝不硬编码凭证

5. Best Practices Compliance

5. 最佳实践合规

  • Platform standards: Follow official guidelines
  • Connector patterns: Use recommended approaches
  • Expression optimization: Simplify complex expressions
  • Resource cleanup: Ensure proper disposal
  • Monitoring: Add telemetry for critical operations
  • 平台标准: 遵循官方指南
  • 连接器模式: 使用推荐方法
  • 表达式优化: 简化复杂表达式
  • 资源清理: 确保正确释放资源
  • 监控: 为关键操作添加遥测

Phase 4: Prioritization & Change Planning

第4阶段:优先级排序与变更规划

  1. Categorize Improvements
    • Critical: Must fix (security, reliability issues)
    • High impact: Significant performance/reliability gains
    • Medium impact: Moderate improvements
    • Low impact: Nice-to-have enhancements
  2. User Request Alignment
    • Prioritize changes explicitly requested by user
    • Ensure requested changes are safe and valid
    • Propose alternatives if request conflicts with best practices
  3. Functional Equivalence Check
    • Verify refactoring maintains original behavior
    • Document any intentional behavior changes
    • Ensure data transformations remain identical
    • Validate output compatibility
  4. Create Change Plan
    • List all improvements to implement
    • Note improvements identified but not implemented (for suggestions)
    • Explain rationale for each change
    • Reference documentation sources
  1. 分类改进点
    • 关键: 必须修复(安全、可靠性问题)
    • 高影响: 显著提升性能/可靠性
    • 中影响: 中等改进
    • 低影响: 锦上添花的增强
  2. 对齐用户请求
    • 优先处理用户明确要求的变更
    • 确保请求的变更安全有效
    • 若请求与最佳实践冲突,提出替代方案
  3. 功能等效性检查
    • 验证重构是否保留原有行为
    • 记录所有有意的行为变更
    • 确保数据转换保持一致
    • 验证输出兼容性
  4. 创建变更计划
    • 列出所有要实现的改进
    • 记录已识别但未实现的改进(作为建议)
    • 解释每项变更的理由
    • 参考文档来源

Phase 5: Refactored JSON Generation (Use Task Tool with Flow-Builder Agent)

第5阶段:生成重构后JSON(使用Task工具调用Flow-Builder Agent)

CRITICAL: Use the Task tool to launch a flow-builder agent for JSON generation.
Launch flow-builder sub-agent:
Use Task tool with subagent_type="general-purpose"

Prompt: "Generate complete refactored workflow JSON for [PLATFORM] with the following requirements:

Platform: [Power Automate / n8n / Make / Zapier / Other]
Original Flow: [ORIGINAL_JSON]
User Requirements: [USER_REFACTORING_REQUEST]
Best Practices Found: [RESEARCH_FINDINGS]
Improvements to Implement: [CHANGE_PLAN]

Create a complete, valid workflow JSON that:
1. Maintains 100% functional equivalence to original (unless user requested changes)
2. Implements all high-priority improvements
3. Adds comprehensive error handling (platform-specific)
4. Optimizes for performance (batching, filtering, concurrency)
5. Follows platform best practices from documentation
6. Includes clear, descriptive action names
7. Adds comments explaining complex logic
8. Uses valid IDs/GUIDs as required by platform
9. Has correct dependencies/execution order
10. Is ready for copy-paste into platform's import/code feature
11. Respects API limits with appropriate delays/batching
12. Includes proper initialization of all variables
13. Validates inputs before processing
14. Implements retry logic for transient failures

Platform-specific requirements:
- Power Automate: Use Scopes for error handling, proper runAfter chains
- n8n: Use Error Trigger nodes, proper node connections
- Make: Use error handlers, proper routing
- Zapier: Use error paths, filters

Return ONLY the complete JSON with no placeholders or TODOs."
Expected Output from Flow-Builder Agent:
  • Complete, syntactically valid JSON (platform-specific format)
  • All required structure elements for the platform
  • Proper IDs/GUIDs for all operations
  • Correct expression/formula syntax
  • Complete execution chains/dependencies
  • Comprehensive error handling
  • Performance optimizations applied
关键: 使用Task工具启动flow-builder代理生成JSON。
启动flow-builder子代理:
使用Task工具,设置subagent_type="general-purpose"

提示:"为[PLATFORM]生成完整的重构后工作流JSON,满足以下要求:

平台:[Power Automate / n8n / Make / Zapier / 其他]
原始工作流:[ORIGINAL_JSON]
用户需求:[USER_REFACTORING_REQUEST]
找到的最佳实践:[RESEARCH_FINDINGS]
要实现的改进:[CHANGE_PLAN]

创建完整、有效的工作流JSON,需满足:
1. 与原始工作流100%功能等效(除非用户要求变更)
2. 实现所有高优先级改进
3. 添加全面的错误处理(平台特定)
4. 优化性能(批量处理、过滤、并发)
5. 遵循文档中的平台最佳实践
6. 使用清晰、描述性的操作名称
7. 添加注释解释复杂逻辑
8. 使用平台要求的有效ID/GUID
9. 具有正确的依赖关系/执行顺序
10. 可直接复制粘贴到平台的导入/代码功能中
11. 通过适当延迟/批量处理遵守API限制
12. 正确初始化所有变量
13. 处理前验证输入
14. 为临时故障实现重试逻辑

平台特定要求:
- Power Automate:使用Scopes进行错误处理,正确的runAfter链
- n8n:使用Error Trigger节点,正确的节点连接
- Make:使用错误处理程序,正确的路由
- Zapier:使用错误路径、过滤器

仅返回完整的JSON,无占位符或TODO。"
Flow-Builder Agent预期输出:
  • 完整、语法有效的JSON(平台特定格式)
  • 平台所需的所有结构元素
  • 所有操作的正确ID/GUID
  • 正确的表达式/公式语法
  • 完整的执行链/依赖关系
  • 全面的错误处理
  • 已应用性能优化

Phase 6: Validation & Quality Check

第6阶段:验证与质量检查

Before finalizing output:
  1. Functional Validation
    • Original triggers maintained
    • Original actions preserved (unless change requested)
    • Data transformations identical
    • Outputs remain compatible
    • Error paths handled
  2. Technical Validation
    • JSON syntax valid
    • Platform-specific format correct
    • All IDs/GUIDs unique
    • Dependencies properly ordered
    • Expressions syntactically correct
  3. Optimization Validation
    • Performance improvements applied
    • Error handling comprehensive
    • Best practices followed
    • Security considerations addressed
    • Documentation references accurate
  4. Platform Validation
    • Connector limits respected
    • API patterns correct
    • Authentication properly configured
    • Platform-specific features used correctly
交付输出前:
  1. 功能验证
    • 保留原始触发器
    • 保留原始操作(除非用户要求变更)
    • 数据转换一致
    • 输出保持兼容
    • 错误路径已处理
  2. 技术验证
    • JSON语法有效
    • 平台特定格式正确
    • 所有ID/GUID唯一
    • 依赖关系顺序正确
    • 表达式语法正确
  3. 优化验证
    • 已应用性能改进
    • 错误处理全面
    • 遵循最佳实践
    • 已考虑安全因素
    • 文档引用准确
  4. 平台验证
    • 遵守连接器限制
    • API模式正确
    • 身份验证配置正确
    • 正确使用平台特定功能

Phase 7: Report Generation

第7阶段:生成报告

Generate comprehensive refactoring report:
生成全面的重构报告:

Report Structure

报告结构

markdown
undefined
markdown
undefined

Workflow Refactoring Report

工作流重构报告

Summary

摘要

  • Platform: [Platform name]
  • Flow Name: [Flow identifier]
  • Refactoring Goals: [User's objectives]
  • Changes Applied: [Number of improvements implemented]
  • Functional Impact: [Maintained equivalence / Intentional changes]
  • 平台: [平台名称]
  • 工作流名称: [工作流标识]
  • 重构目标: [用户目标]
  • 已应用变更: [已实现的改进数量]
  • 功能影响: [保留等效性 / 有意变更]

Changes Implemented

已实现的变更

Performance Optimizations

性能优化

  • [List of performance improvements with before/after impact]
  • Example: "Reduced API calls from 100 to 10 by implementing batch operations"
  • [列出性能改进及前后影响]
  • 示例:"通过实现批量操作,将API调用从100次减少到10次"

Reliability Improvements

可靠性改进

  • [List of reliability enhancements]
  • Example: "Added error handling scope with retry logic for transient failures"
  • [列出可靠性增强措施]
  • 示例:"添加带重试逻辑的错误处理Scope以应对临时故障"

Maintainability Enhancements

可维护性增强

  • [List of code quality improvements]
  • Example: "Renamed 15 actions for clarity, organized into logical scopes"
  • [列出代码质量改进]
  • 示例:"为15个操作重命名以提升清晰度,组织到逻辑Scopes中"

Security Hardening

安全强化

  • [List of security improvements]
  • Example: "Replaced hardcoded credentials with secure connection references"
  • [列出安全改进]
  • 示例:"将硬编码凭证替换为安全连接引用"

Best Practices Applied

已应用的最佳实践

  • [List of platform best practices implemented]
  • Example: "Implemented proper variable initialization per Power Automate guidelines"
  • [列出已实现的平台最佳实践]
  • 示例:"按照Power Automate指南实现正确的变量初始化"

Documentation References

文档引用

[List of specific documentation files and sections consulted]
  • Docs/{Platform}_Documentation/{Connector}/overview.md - [Section name]
  • Docs/{Platform}_Documentation/best-practices.md - [Section name]
[列出参考的具体文档文件和章节]
  • Docs/{Platform}_Documentation/{Connector}/overview.md - [章节名称]
  • Docs/{Platform}_Documentation/best-practices.md - [章节名称]

Additional Optimization Opportunities

额外优化机会

High Priority (Recommended)

高优先级(推荐)

  • [Improvements identified but not implemented, with rationale]
  • Example: "Consider implementing caching for frequently accessed data (requires architectural change)"
  • [已识别但未实现的改进及理由]
  • 示例:"考虑为频繁访问的数据实现缓存(需要架构变更)"

Medium Priority

中优先级

  • [Medium-impact optimizations for future consideration]
  • [未来可考虑的中等影响优化]

Low Priority

低优先级

  • [Nice-to-have improvements]
  • [锦上添花的改进]

Testing Recommendations

测试建议

Functional Testing

功能测试

  1. [Step-by-step testing plan to verify functional equivalence]
  2. Test with same inputs as original flow
  3. Verify outputs match expected results
  1. [验证功能等效性的分步测试计划]
  2. 使用与原始工作流相同的输入测试
  3. 验证输出符合预期结果

Performance Testing

性能测试

  1. [How to measure performance improvements]
  2. Compare run duration with original flow
  3. Monitor API call counts
  1. [如何衡量性能改进]
  2. 与原始工作流比较运行时长
  3. 监控API调用次数

Error Testing

错误测试

  1. [How to verify error handling works]
  2. Test failure scenarios
  3. Verify retry logic
  1. [如何验证错误处理是否有效]
  2. 测试故障场景
  3. 验证重试逻辑

Migration Guide

迁移指南

Deployment Steps

部署步骤

  1. [Step-by-step instructions to deploy refactored flow]
  2. Backup original flow
  3. Import refactored JSON
  4. Update connections if needed
  5. Test thoroughly before production
  1. [部署重构后工作流的分步说明]
  2. 备份原始工作流
  3. 导入重构后的JSON
  4. 必要时更新连接
  5. 生产环境部署前全面测试

Rollback Plan

回滚计划

[How to revert if issues arise]
[出现问题时的回滚方法]

Next Steps

后续步骤

  1. Review changes and approve
  2. Test in development environment
  3. Deploy to production
  4. Monitor for first 24-48 hours
  5. Consider additional optimizations listed above

Refactoring Completed: [Timestamp] Documentation Consulted: [Number of docs referenced] Confidence Level: High (all changes based on official documentation)
undefined
  1. 审核变更并批准
  2. 在开发环境测试
  3. 部署到生产环境
  4. 监控前24-48小时
  5. 考虑上述额外优化

重构完成时间: [时间戳] 参考文档数量: [参考的文档数量] 置信度: 高(所有变更基于官方文档)
undefined

Output Format

输出格式

ALWAYS provide two deliverables:
始终提供两个交付物:

1. Refactored JSON File

1. 重构后JSON文件

json
{
  "comment": "Refactored workflow - [Date] - Implements [key improvements]",
  "definition": {
    // Complete, valid, platform-specific JSON
    // Ready for copy-paste/import
    // No placeholders or TODOs
  }
}
json
{
  "comment": "Refactored workflow - [日期] - 实现了[关键改进]",
  "definition": {
    // 完整、有效、平台特定的JSON
    // 可直接复制粘贴/导入
    // 无占位符或TODO
  }
}

2. Refactoring Report

2. 重构报告

  • Structured markdown report as detailed above
  • Clear explanation of all changes
  • Documentation references
  • Additional suggestions
  • Testing and deployment guidance
  • 结构化markdown报告(如上所述)
  • 所有变更的清晰说明
  • 文档引用
  • 额外建议
  • 测试和部署指南

Critical Requirements

关键要求

Documentation-First Approach

文档优先方法

NEVER hallucinate or guess. Always:
  1. Use Task tool with Explore agent to research Docs/{Platform}_Documentation/
  2. Reference specific files and sections
  3. Quote exact best practices from documentation
  4. Verify optimizations against documented constraints
  5. Adapt to platform-specific requirements
绝不虚构或猜测。始终:
  1. 使用Task工具调用Explore代理调研Docs/{Platform}_Documentation/
  2. 引用具体文件和章节
  3. 引用文档中的确切最佳实践
  4. 对照文档约束验证优化
  5. 适配平台特定要求

Functional Equivalence Guarantee

功能等效性保证

NEVER change behavior unless explicitly requested. Always:
  1. Maintain exact same triggers
  2. Preserve all actions and their logic
  3. Keep data transformations identical
  4. Ensure outputs remain compatible
  5. Document any intentional changes clearly
除非明确要求,绝不改变行为。始终:
  1. 保留完全相同的触发器
  2. 保留所有操作及其逻辑
  3. 保持数据转换一致
  4. 确保输出兼容
  5. 清晰记录所有有意的变更

Complete JSON Output

完整JSON输出

NEVER output partial or placeholder JSON. Always:
  1. Use Task tool with flow-builder agent
  2. Include all required structure elements
  3. Generate valid IDs/GUIDs
  4. Ensure syntactic validity
  5. Make JSON immediately ready for import
  6. Follow platform-specific format
绝不输出部分或占位符JSON。始终:
  1. 使用Task工具调用flow-builder代理
  2. 包含所有必需的结构元素
  3. 生成有效ID/GUID
  4. 确保语法有效
  5. 使JSON可立即导入
  6. 遵循平台特定格式

Quality Assurance Checklist

质量保证清单

Before delivering output, verify:
Data Structure Validation (CRITICAL - New!):
  • Analyzed all filter/query
    where
    clauses for data type indicators
  • Verified
    item()
    vs
    item()?['Property']
    consistency throughout flow
  • Checked loop
    items()
    usage matches source data structure
  • Traced all variable sources to understand actual data types
  • Asked user for clarification if structure was ambiguous
  • No assumptions made about object properties without verification
Technical Validation:
  • Platform identified correctly
  • Research agent consulted Docs/{Platform}_Documentation/
  • Searched web if local docs insufficient
  • All improvements reference documentation (local or web)
  • Flow-builder agent generated complete JSON
  • JSON follows platform-specific format
  • JSON syntax valid (no placeholders)
  • All expressions syntactically correct
Functional Validation:
  • Functional equivalence maintained (unless changes requested)
  • Data transformations work with actual data types
  • No property access on primitive types (strings, numbers)
  • Array handling matches actual array content type
Deliverables:
  • Report includes all required sections
  • Additional optimizations suggested
  • Testing recommendations provided
  • Deployment guidance included
  • Data structure bugs identified and fixed
交付输出前,验证:
数据结构验证(关键 - 新增!):
  • 分析了所有过滤器/查询
    where
    子句的类型指示
  • 验证了整个工作流中
    item()
    vs
    item()?['Property']
    的一致性
  • 检查了循环
    items()
    用法与源数据结构匹配
  • 追溯了所有变量源以理解实际数据类型
  • 若结构存在歧义,已询问用户
  • 未在未验证的情况下假设对象属性
技术验证:
  • 正确识别平台
  • 已调用调研代理查阅Docs/{Platform}_Documentation/
  • 若本地文档不足,已进行网络搜索
  • 所有改进均参考文档(本地或网络)
  • flow-builder代理生成了完整JSON
  • JSON遵循平台特定格式
  • JSON语法有效(无占位符)
  • 所有表达式语法正确
功能验证:
  • 保留功能等效性(除非用户要求变更)
  • 数据转换适用于实际数据类型
  • 未对原始类型(字符串、数字)进行属性访问
  • 数组处理与实际数组内容类型匹配
交付物:
  • 报告包含所有必需章节
  • 已建议额外优化
  • 提供了测试建议
  • 包含部署指南
  • 已识别并修复数据结构bug

Refactoring Patterns

重构模式

Pattern 1: API Call Reduction

模式1:减少API调用

Before (100 API calls):
json
{
  "Apply_to_each": {
    "foreach": "@body('Get_all_items')?['value']",
    "actions": {
      "Get_user_details": {
        "type": "ApiConnection",
        "inputs": {
          "host": {"connectionName": "shared_office365users"},
          "method": "get",
          "path": "/users/@{items('Apply_to_each')?['Email']}"
        }
      }
    }
  }
}
After (1 API call with $expand):
json
{
  "Get_all_items_with_users": {
    "type": "ApiConnection",
    "inputs": {
      "host": {"connectionName": "shared_sharepointonline"},
      "method": "get",
      "path": "/datasets/@{parameters('site')}/tables/@{parameters('list')}/items",
      "queries": {
        "$expand": "Author,Editor",
        "$select": "Id,Title,Author/DisplayName,Author/Email"
      }
    }
  }
}
Impact: 99% API call reduction, 10x faster execution

重构前(100次API调用):
json
{
  "Apply_to_each": {
    "foreach": "@body('Get_all_items')?['value']",
    "actions": {
      "Get_user_details": {
        "type": "ApiConnection",
        "inputs": {
          "host": {"connectionName": "shared_office365users"},
          "method": "get",
          "path": "/users/@{items('Apply_to_each')?['Email']}"
        }
      }
    }
  }
}
重构后(1次带$expand的API调用):
json
{
  "Get_all_items_with_users": {
    "type": "ApiConnection",
    "inputs": {
      "host": {"connectionName": "shared_sharepointonline"},
      "method": "get",
      "path": "/datasets/@{parameters('site')}/tables/@{parameters('list')}/items",
      "queries": {
        "$expand": "Author,Editor",
        "$select": "Id,Title,Author/DisplayName,Author/Email"
      }
    }
  }
}
影响: 减少99%的API调用,执行速度提升10倍

Pattern 2: Error Handling Addition

模式2:添加错误处理

Before (no error handling):
json
{
  "Send_email": {
    "type": "ApiConnection",
    "inputs": {
      "host": {"connectionName": "shared_office365"},
      "method": "post",
      "path": "/Mail"
    }
  }
}
After (comprehensive error handling):
json
{
  "Try_Send_Email": {
    "type": "Scope",
    "actions": {
      "Send_email": {
        "type": "ApiConnection",
        "inputs": {
          "host": {"connectionName": "shared_office365"},
          "method": "post",
          "path": "/Mail"
        }
      }
    }
  },
  "Catch_Email_Error": {
    "type": "Scope",
    "runAfter": {
      "Try_Send_Email": ["Failed", "TimedOut"]
    },
    "actions": {
      "Log_Error": {
        "type": "Compose",
        "inputs": {
          "error": "@result('Try_Send_Email')",
          "timestamp": "@utcNow()"
        }
      },
      "Notify_Admin": {
        "type": "ApiConnection",
        "inputs": {
          "host": {"connectionName": "shared_office365"},
          "method": "post",
          "path": "/Mail",
          "body": {
            "To": "admin@company.com",
            "Subject": "Flow Error: Email Send Failed",
            "Body": "@body('Log_Error')"
          }
        }
      }
    }
  }
}
Impact: Failures tracked, admin notified, debugging simplified

重构前(无错误处理):
json
{
  "Send_email": {
    "type": "ApiConnection",
    "inputs": {
      "host": {"connectionName": "shared_office365"},
      "method": "post",
      "path": "/Mail"
    }
  }
}
重构后(全面错误处理):
json
{
  "Try_Send_Email": {
    "type": "Scope",
    "actions": {
      "Send_email": {
        "type": "ApiConnection",
        "inputs": {
          "host": {"connectionName": "shared_office365"},
          "method": "post",
          "path": "/Mail"
        }
      }
    }
  },
  "Catch_Email_Error": {
    "type": "Scope",
    "runAfter": {
      "Try_Send_Email": ["Failed", "TimedOut"]
    },
    "actions": {
      "Log_Error": {
        "type": "Compose",
        "inputs": {
          "error": "@result('Try_Send_Email')",
          "timestamp": "@utcNow()"
        }
      },
      "Notify_Admin": {
        "type": "ApiConnection",
        "inputs": {
          "host": {"connectionName": "shared_office365"},
          "method": "post",
          "path": "/Mail",
          "body": {
            "To": "admin@company.com",
            "Subject": "Flow Error: Email Send Failed",
            "Body": "@body('Log_Error')"
          }
        }
      }
    }
  }
}
影响: 可追踪故障、通知管理员、简化调试

Pattern 3: Performance - Concurrency Optimization

模式3:性能 - 并发优化

Before (sequential, slow):
json
{
  "Apply_to_each": {
    "foreach": "@body('Get_items')?['value']",
    "actions": {
      "Independent_HTTP_Call": {
        "type": "Http",
        "inputs": {
          "method": "POST",
          "uri": "https://api.example.com/process",
          "body": "@item()"
        }
      }
    }
  }
}
After (parallel, 5x faster):
json
{
  "Apply_to_each": {
    "foreach": "@body('Get_items')?['value']",
    "runtimeConfiguration": {
      "concurrency": {
        "repetitions": 10
      }
    },
    "actions": {
      "Independent_HTTP_Call": {
        "type": "Http",
        "inputs": {
          "method": "POST",
          "uri": "https://api.example.com/process",
          "body": "@item()"
        }
      }
    }
  }
}
Impact: 5x faster for independent operations (use only when operations don't depend on each other)

重构前(串行,速度慢):
json
{
  "Apply_to_each": {
    "foreach": "@body('Get_items')?['value']",
    "actions": {
      "Independent_HTTP_Call": {
        "type": "Http",
        "inputs": {
          "method": "POST",
          "uri": "https://api.example.com/process",
          "body": "@item()"
        }
      }
    }
  }
}
重构后(并行,速度提升5倍):
json
{
  "Apply_to_each": {
    "foreach": "@body('Get_items')?['value']",
    "runtimeConfiguration": {
      "concurrency": {
        "repetitions": 10
      }
    },
    "actions": {
      "Independent_HTTP_Call": {
        "type": "Http",
        "inputs": {
          "method": "POST",
          "uri": "https://api.example.com/process",
          "body": "@item()"
        }
      }
    }
  }
}
影响: 独立操作速度提升5倍(仅当操作无依赖时使用)

Pattern 4: Maintainability - Clear Naming

模式4:可维护性 - 清晰命名

Before (cryptic names):
json
{
  "actions": {
    "Compose": {
      "type": "Compose",
      "inputs": "@body('HTTP')?['data']"
    },
    "Compose_2": {
      "type": "Compose",
      "inputs": "@first(body('Compose'))"
    },
    "HTTP_2": {
      "type": "Http",
      "inputs": {
        "uri": "https://api.example.com/send",
        "body": "@body('Compose_2')"
      }
    }
  }
}
After (descriptive names):
json
{
  "actions": {
    "Extract_User_Data_From_API_Response": {
      "type": "Compose",
      "inputs": "@body('Get_Users_From_External_API')?['data']"
    },
    "Get_First_Active_User": {
      "type": "Compose",
      "inputs": "@first(body('Extract_User_Data_From_API_Response'))"
    },
    "Send_Welcome_Email_To_User": {
      "type": "Http",
      "inputs": {
        "uri": "https://api.example.com/send",
        "body": "@body('Get_First_Active_User')"
      }
    }
  }
}
Impact: Immediately understandable logic, easier maintenance

重构前(名称晦涩):
json
{
  "actions": {
    "Compose": {
      "type": "Compose",
      "inputs": "@body('HTTP')?['data']"
    },
    "Compose_2": {
      "type": "Compose",
      "inputs": "@first(body('Compose'))"
    },
    "HTTP_2": {
      "type": "Http",
      "inputs": {
        "uri": "https://api.example.com/send",
        "body": "@body('Compose_2')"
      }
    }
  }
}
重构后(描述性名称):
json
{
  "actions": {
    "Extract_User_Data_From_API_Response": {
      "type": "Compose",
      "inputs": "@body('Get_Users_From_External_API')?['data']"
    },
    "Get_First_Active_User": {
      "type": "Compose",
      "inputs": "@first(body('Extract_User_Data_From_API_Response'))"
    },
    "Send_Welcome_Email_To_User": {
      "type": "Http",
      "inputs": {
        "uri": "https://api.example.com/send",
        "body": "@body('Get_First_Active_User')"
      }
    }
  }
}
影响: 逻辑一目了然,更易于维护

Pattern 5: Security - Credential Hardening

模式5:安全 - 凭证强化

Before (insecure):
json
{
  "HTTP_Call": {
    "type": "Http",
    "inputs": {
      "uri": "https://api.example.com/data",
      "headers": {
        "Authorization": "Bearer sk-1234567890abcdef"
      }
    }
  }
}
After (secure):
json
{
  "Initialize_API_Key": {
    "type": "InitializeVariable",
    "inputs": {
      "variables": [{
        "name": "APIKey",
        "type": "String",
        "value": "@parameters('SecureAPIKey')"
      }]
    }
  },
  "HTTP_Call": {
    "type": "Http",
    "inputs": {
      "uri": "https://api.example.com/data",
      "authentication": {
        "type": "Raw",
        "value": "@concat('Bearer ', variables('APIKey'))"
      }
    },
    "runAfter": {
      "Initialize_API_Key": ["Succeeded"]
    }
  }
}
Impact: Credentials in secure parameters, not hardcoded in JSON

重构前(不安全):
json
{
  "HTTP_Call": {
    "type": "Http",
    "inputs": {
      "uri": "https://api.example.com/data",
      "headers": {
        "Authorization": "Bearer sk-1234567890abcdef"
      }
    }
  }
}
重构后(安全):
json
{
  "Initialize_API_Key": {
    "type": "InitializeVariable",
    "inputs": {
      "variables": [{
        "name": "APIKey",
        "type": "String",
        "value": "@parameters('SecureAPIKey')"
      }]
    }
  },
  "HTTP_Call": {
    "type": "Http",
    "inputs": {
      "uri": "https://api.example.com/data",
      "authentication": {
        "type": "Raw",
        "value": "@concat('Bearer ', variables('APIKey'))"
      }
    },
    "runAfter": {
      "Initialize_API_Key": ["Succeeded"]
    }
  }
}
影响: 凭证存储在安全参数中,而非硬编码到JSON

Platform-Specific Considerations

平台特定注意事项

Power Automate

Power Automate

Key Optimizations:
  • Use
    $expand
    and
    $select
    in OData queries
  • Implement Scopes for error handling
  • Set concurrency for independent operations
  • Use "Get items" over "List items" (pagination support)
  • Filter at source with
    $filter
    queries
Best Practices Documentation:
Docs/PowerAutomateDocs/

关键优化:
  • 在OData查询中使用
    $expand
    $select
  • 实现Scopes进行错误处理
  • 为独立操作设置并发
  • 使用"Get items"而非"List items"(支持分页)
  • 使用
    $filter
    查询在源头过滤
最佳实践文档:
Docs/PowerAutomateDocs/

n8n

n8n

Key Optimizations:
  • Use "Split in Batches" node for large datasets
  • Implement Error Trigger nodes
  • Enable "Always Output Data" for better debugging
  • Use "HTTP Request" node with batching
  • Leverage "Code" node for complex transformations
Best Practices Documentation:
Docs/N8NDocs/

关键优化:
  • 对大型数据集使用"Split in Batches"节点
  • 实现Error Trigger节点
  • 启用"Always Output Data"以提升调试体验
  • 使用"HTTP Request"节点进行批量处理
  • 利用"Code"节点进行复杂转换
最佳实践文档:
Docs/N8NDocs/

Make

Make

Key Optimizations:
  • Use filters to reduce operations
  • Implement error handlers on all routes
  • Use aggregators for batch operations
  • Set appropriate scheduling intervals
  • Use routers for conditional logic

关键优化:
  • 使用过滤器减少操作
  • 在所有路由上实现错误处理程序
  • 使用聚合器进行批量操作
  • 设置适当的调度间隔
  • 使用路由器处理条件逻辑

Zapier

Zapier

Key Optimizations:
  • Use multi-step zaps efficiently
  • Implement error paths
  • Use filters to reduce task usage
  • Leverage built-in apps over webhooks
  • Use formatter for data transformation

关键优化:
  • 高效使用多步骤zap
  • 实现错误路径
  • 使用过滤器减少任务使用量
  • 优先使用内置应用而非webhook
  • 使用formatter进行数据转换

Sub-Agent Coordination

子代理协调

Research Agent (Explore)

调研代理(Explore)

Purpose: Find best practices and optimization guidelines
Input Requirements:
  • Platform name
  • Connectors/nodes used
  • Current pain points (if known)
Expected Output:
  • Documentation file paths
  • Specific optimization recommendations
  • Limitation warnings
  • Security considerations
Invocation:
Task tool, subagent_type="Explore", thoroughness="very thorough"
目标: 查找最佳实践和优化指南
输入要求:
  • 平台名称
  • 使用的连接器/节点
  • 当前痛点(如有)
预期输出:
  • 文档文件路径
  • 具体优化建议
  • 限制警告
  • 安全注意事项
调用方式:
Task工具,subagent_type="Explore",thoroughness="very thorough"

Flow-Builder Agent

Flow-Builder代理

Purpose: Generate complete, optimized workflow JSON
Input Requirements:
  • Original flow JSON
  • User requirements
  • Research findings
  • Change plan
Expected Output:
  • Complete JSON structure
  • All optimizations applied
  • Valid syntax
  • No placeholders
Invocation:
Task tool, subagent_type="general-purpose"
目标: 生成完整、优化的工作流JSON
输入要求:
  • 原始工作流JSON
  • 用户需求
  • 调研结果
  • 变更计划
预期输出:
  • 完整JSON结构
  • 已应用所有优化
  • 语法有效
  • 无占位符
调用方式:
Task工具,subagent_type="general-purpose"

Examples

示例

Example 1: Data Structure Bug (Real Case Study)

示例1:数据结构Bug(真实案例)

User: "Fix the DossierPlusRécent variable assignment - it's filtering on array but accessing wrong property"
Input Flow:
json
{
  "Filtrer_dossier_CNESST": {
    "type": "Query",
    "inputs": {
      "from": "@variables('ListeDesDossier')",
      "where": "@contains(toLower(item()), 'cnesst')"  // ← item() without property!
    }
  },
  "LoopCNESST": {
    "foreach": "@body('Filtrer_dossier_CNESST')",
    "actions": {
      "DossierPlusRécent_CNESST": {
        "type": "SetVariable",
        "inputs": {
          "name": "DossierPlusRecent",
          "value": "@items('LoopCNESST')?['Nom']"  // ← BUG: Accessing 'Nom' property!
        }
      }
    }
  }
}
Analysis Process:
  1. Phase 0 - Data Structure Analysis:
    • Check filter:
      contains(toLower(item()), 'cnesst')
      uses
      item()
      without property
    • CONCLUSION:
      ListeDesDossier
      is array of strings, NOT array of objects!
    • Examples:
      ["CNESST 2025-01-15", "CNESST 2025-02-20", "INVALIDITÉ 2025-01-10"]
  2. Identify Bug:
    • Loop iterates over strings:
      ["CNESST 2025-01-15", ...]
    • But tries to access:
      items('LoopCNESST')?['Nom']
      (treating string as object)
    • ERROR: Can't access property on string primitive!
  3. Correct Fix:
    json
    "DossierPlusRécent_CNESST": {
      "type": "SetVariable",
      "inputs": {
        "name": "DossierPlusRecent",
        "value": "@items('LoopCNESST')"  // ← CORRECT: Direct string value
      }
    }
  4. Also Fix DEBUG Action:
    json
    "DEBUG_jour_CNESST": {
      "type": "Compose",
      "inputs": "@int(substring(substring(
        if(
          contains(split(items('LoopCNESST'), '.')[0], '_'),  // ← Remove ?['Nom']
          last(split(split(items('LoopCNESST'), '.')[0], '_')),
          last(split(split(items('LoopCNESST'), '.')[0], ' '))
        ), 0, 10), 8, 2))"
    }
Key Lesson:
  • ALWAYS check filter syntax first:
    item()
    vs
    item()?['Prop']
    tells you the data structure
  • NEVER assume objects with properties without verification
  • ASK USER if ambiguous
Output:
  • Corrected JSON with proper string handling
  • Explanation of the bug and why it occurred
  • Prevention tips for future

用户: "修复DossierPlusRécent变量赋值 - 它在数组上过滤但访问了错误的属性"
输入工作流:
json
{
  "Filtrer_dossier_CNESST": {
    "type": "Query",
    "inputs": {
      "from": "@variables('ListeDesDossier')",
      "where": "@contains(toLower(item()), 'cnesst')"  // ← 不带属性的item()!
    }
  },
  "LoopCNESST": {
    "foreach": "@body('Filtrer_dossier_CNESST')",
    "actions": {
      "DossierPlusRécent_CNESST": {
        "type": "SetVariable",
        "inputs": {
          "name": "DossierPlusRecent",
          "value": "@items('LoopCNESST')?['Nom']"  // ← Bug: 访问'Nom'属性!
        }
      }
    }
  }
}
分析过程:
  1. 第0阶段 - 数据结构分析:
    • 检查过滤器:
      contains(toLower(item()), 'cnesst')
      使用不带属性的
      item()
    • 结论:
      ListeDesDossier
      字符串数组,而非对象数组!
    • 示例:
      ["CNESST 2025-01-15", "CNESST 2025-02-20", "INVALIDITÉ 2025-01-10"]
  2. 识别Bug:
    • 循环遍历字符串:
      ["CNESST 2025-01-15", ...]
    • 但尝试访问:
      items('LoopCNESST')?['Nom']
      (将字符串视为对象)
    • 错误: 无法访问原始类型字符串的属性!
  3. 正确修复:
    json
    "DossierPlusRécent_CNESST": {
      "type": "SetVariable",
      "inputs": {
        "name": "DossierPlusRecent",
        "value": "@items('LoopCNESST')"  // ← 正确: 直接使用字符串值
      }
    }
  4. 同时修复DEBUG操作:
    json
    "DEBUG_jour_CNESST": {
      "type": "Compose",
      "inputs": "@int(substring(substring(
        if(
          contains(split(items('LoopCNESST'), '.')[0], '_'),  // ← 移除?['Nom']
          last(split(split(items('LoopCNESST'), '.')[0], '_')),
          last(split(split(items('LoopCNESST'), '.')[0], ' '))
        ), 0, 10), 8, 2))"
    }
关键教训:
  • 始终先检查过滤器语法:
    item()
    vs
    item()?['Prop']
    会告诉你数据结构
  • 绝不未验证就假设存在带属性的对象
  • 存在歧义时询问用户
输出:
  • 修复后的JSON,正确处理字符串
  • 解释Bug及其产生原因
  • 未来预防技巧

Example 2: Performance Optimization Request

示例2:性能优化请求

User: "Optimize this Power Automate flow to reduce execution time"
Input Flow: Flow with 100 sequential API calls
Workflow:
  1. Analyze: Identify sequential API calls bottleneck
  2. Research: Launch Explore agent → Find batching and concurrency guidelines
  3. Plan: Replace sequential calls with batch operation + parallel processing
  4. Build: Launch flow-builder agent → Generate optimized JSON
  5. Report: Document 90% execution time reduction
  6. Suggest: Additional caching opportunities
Output:
  • Refactored JSON with batch operations
  • Report showing before/after metrics
  • Additional optimization suggestions

用户: "优化这个Power Automate工作流以减少执行时间"
输入工作流: 包含100次串行API调用的工作流
工作流程:
  1. 分析: 识别串行API调用瓶颈
  2. 调研: 启动Explore代理 → 查找批量处理和并发指南
  3. 规划: 用批量操作+并行处理替换串行调用
  4. 构建: 启动flow-builder代理 → 生成优化后的JSON
  5. 报告: 记录执行时间减少90%
  6. 建议: 额外的缓存机会
输出:
  • 带批量操作的重构后JSON
  • 显示前后指标的报告
  • 额外优化建议

Example 2: Best Practices Application

示例3:最佳实践应用

User: "Refactor this flow to follow Power Automate best practices"
Input Flow: Working but poorly structured flow
Workflow:
  1. Analyze: Identify deviations from best practices
  2. Research: Launch Explore agent → Find official best practices documentation
  3. Plan: Add error handling, improve naming, add comments
  4. Build: Launch flow-builder agent → Generate refactored JSON
  5. Report: Document all improvements with documentation references
  6. Suggest: Consider breaking into child flows for modularity
Output:
  • Refactored JSON with best practices applied
  • Report listing all improvements
  • Future enhancement suggestions

用户: "重构这个工作流以遵循Power Automate最佳实践"
输入工作流: 可运行但结构不佳的工作流
工作流程:
  1. 分析: 识别与最佳实践的偏差
  2. 调研: 启动Explore代理 → 查找官方最佳实践文档
  3. 规划: 添加错误处理、改进命名、添加注释
  4. 构建: 启动flow-builder代理 → 生成重构后JSON
  5. 报告: 记录所有改进并引用文档
  6. 建议: 考虑拆分为子工作流以提升模块化
输出:
  • 已应用最佳实践的重构后JSON
  • 列出所有改进的报告
  • 未来增强建议

Example 3: Error Handling Enhancement

示例4:错误处理增强

User: "Add comprehensive error handling to this workflow"
Input Flow: Flow with no error handling
Workflow:
  1. Analyze: Map all failure points
  2. Research: Launch Explore agent → Find error handling patterns
  3. Plan: Add Scopes, Configure run after, retry logic
  4. Build: Launch flow-builder agent → Generate hardened JSON
  5. Report: Document error handling strategy
  6. Suggest: Add monitoring and alerting
Output:
  • Refactored JSON with comprehensive error handling
  • Report explaining error handling approach
  • Monitoring recommendations

用户: "为这个工作流添加全面的错误处理"
输入工作流: 无错误处理的工作流
工作流程:
  1. 分析: 映射所有故障点
  2. 调研: 启动Explore代理 → 查找错误处理模式
  3. 规划: 添加Scopes、配置run after、重试逻辑
  4. 构建: 启动flow-builder代理 → 生成强化后的JSON
  5. 报告: 记录错误处理策略
  6. 建议: 添加监控和告警
输出:
  • 带全面错误处理的重构后JSON
  • 解释错误处理方法的报告
  • 监控建议

When to Escalate

何时升级

Use automation-debugger instead if:
  • Flow has existing errors that need fixing first
  • Root cause analysis needed before refactoring
  • Complex error patterns require investigation
Use automation-validator after refactoring to:
  • Validate refactored JSON before deployment
  • Ensure no issues introduced
  • Get pre-deployment confidence
若出现以下情况,改用automation-debugger:
  • 工作流存在现有错误需先修复
  • 重构前需要根因分析
  • 复杂错误模式需要调查
重构完成后使用automation-validator:
  • 部署前验证重构后的JSON
  • 确保未引入问题
  • 提升部署前的置信度

Best Practices

最佳实践

  1. Always preserve functionality unless explicitly requested to change
  2. Document every change with rationale and documentation reference
  3. Suggest additional improvements beyond what was implemented
  4. Provide testing guidance to verify functional equivalence
  5. Include deployment instructions for smooth rollout
  6. Reference documentation for every optimization decision
  7. Be transparent about limitations and trade-offs
  8. Validate thoroughly before delivering output
  1. 始终保留功能,除非明确要求变更
  2. 记录每项变更,说明理由并引用文档
  3. 建议额外改进,超出已实现的内容
  4. 提供测试指导,验证功能等效性
  5. 包含部署说明,确保顺利上线
  6. 每项优化决策都引用文档
  7. 透明说明限制和权衡
  8. 交付前全面验证

Skill Invocation Examples

技能触发示例

User messages that trigger this skill:
  • "Optimize this Power Automate flow for better performance"
  • "Refactor this workflow to follow best practices"
  • "Improve the error handling in this flow.json"
  • "Make this automation more reliable"
  • "Correct the API call parameters in this flow"
  • "Enhance this workflow to reduce execution time"
  • "Simplify this complex n8n workflow"
  • "Modernize this old Make scenario"
  • "Add retry logic to this flow"
  • "Reduce the number of API calls in this automation"
  • "Make this flow more maintainable"
  • "Apply security best practices to this workflow"

Version: 2.0 Last Updated: 2025-10-31 Platforms: Power Automate, n8n, Make, Zapier + extensible
触发此技能的用户消息:
  • "Optimize this Power Automate flow for better performance"(优化这个Power Automate工作流以提升性能)
  • "Refactor this workflow to follow best practices"(重构这个工作流以遵循最佳实践)
  • "Improve the error handling in this flow.json"(改进这个flow.json的错误处理)
  • "Make this automation more reliable"(提升这个自动化的可靠性)
  • "Correct the API call parameters in this flow"(修正这个工作流中的API调用参数)
  • "Enhance this workflow to reduce execution time"(增强这个工作流以减少执行时间)
  • "Simplify this complex n8n workflow"(简化这个复杂的n8n工作流)
  • "Modernize this old Make scenario"(现代化这个旧的Make场景)
  • "Add retry logic to this flow"(为这个工作流添加重试逻辑)
  • "Reduce the number of API calls in this automation"(减少这个自动化中的API调用次数)
  • "Make this flow more maintainable"(提升这个工作流的可维护性)
  • "Apply security best practices to this workflow"(为这个工作流应用安全最佳实践)

版本: 2.0 最后更新: 2025-10-31 支持平台: Power Automate、n8n、Make、Zapier + 可扩展

Changelog

更新日志

Version 2.0 (2025-10-31)

版本2.0 (2025-10-31)

Major Improvements:
  • ✅ Added Phase 0: Data Structure Analysis (CRITICAL) - Prevents hallucinations about data types
  • ✅ Added Multi-Source Research Strategy - Local docs → Web → Ask user
  • ✅ Added Common Pitfalls section - Highlights most frequent errors
  • ✅ Added Real Case Study example - Data structure bug from actual debugging session
  • ✅ Enhanced Quality Assurance Checklist - Now includes data structure validation
  • ✅ Added AskUserQuestion workflow - Clarify ambiguous structures proactively
  • ✅ Added WebSearch integration - Fallback when local docs insufficient
Key Changes:
  • Never assume array structures (strings vs objects) without verification
  • Always check
    item()
    vs
    item()?['Property']
    patterns in filters
  • Ask user when uncertain rather than guessing
  • Search web for official documentation if local docs don't have answer
  • Validate data type consistency throughout flow before making changes
Lessons Learned:
  • Mismatched data structure assumptions are the #1 source of refactoring bugs
  • Filter syntax reveals data types:
    contains(item(), 'x')
    = array of strings
  • Always trace data sources back to understand actual structures
  • User confirmation beats confident assumptions
主要改进:
  • ✅ 添加第0阶段:数据结构分析(至关重要)- 防止对数据类型的虚构假设
  • ✅ 添加多来源调研策略 - 本地文档→网络→询问用户
  • ✅ 添加常见陷阱章节 - 突出最频繁的错误
  • ✅ 添加真实案例研究示例 - 来自实际调试会话的数据结构bug
  • ✅ 增强质量保证清单 - 现在包含数据结构验证
  • ✅ 添加AskUserQuestion工作流 - 主动澄清歧义结构
  • ✅ 添加WebSearch集成 - 本地文档不足时的备选方案
关键变更:
  • 绝不未验证就假设数组结构(字符串vs对象)
  • 始终检查过滤器中的
    item()
    vs
    item()?['Property']
    模式
  • 不确定时询问用户而非猜测
  • 本地文档不足时搜索官方文档
  • 变更前验证整个工作流的数据类型一致性
经验教训:
  • 数据结构假设不匹配是重构bug的第一大来源
  • 过滤器语法揭示数据类型:
    contains(item(), 'x')
    = 字符串数组
  • 始终追溯数据源以理解实际结构
  • 用户确认优于自信的假设