Expert automation workflow refactoring tool for Power Automate, n8n, Make, Zapier and other platforms. Optimizes existing flows by improving performance, reliability, maintainability, and best practices compliance. Triggers when user wants to improve, optimize, refactor, correct values, enhance, or modernize workflows. Analyzes JSON, suggests improvements, outputs refactored flow maintaining original functionality unless changes requested.
Optimizes automation workflows across Power Automate, n8n, Make, and Zapier by analyzing flow JSON for performance, reliability, and maintainability improvements. Triggers when users request optimization, refactoring, or correction of workflows, applying platform-specific best practices while maintaining functional equivalence.
/plugin marketplace add MacroMan5/AutomationHelper_plugins/plugin install automation-helper@automation-helper-marketplaceThis skill inherits all available tools. When active, it can use any tool Claude has access to.
Expert system for refactoring and optimizing automation workflows across multiple platforms while maintaining functional equivalence and improving code quality.
This skill provides comprehensive workflow refactoring by:
The Mistake:
// 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:
// item() without property → Array of STRINGS!
// Correct usage:
"value": "@items('Loop')" // ← RIGHT!
How to Avoid:
where clause firstitem() = array of primitives (strings/numbers)item()?['Prop'] = array of objectsThe Mistake: Guessing connector outputs, property names, or behaviors
How to Avoid:
The Mistake: Providing fixes without verifying against actual data structures
How to Avoid:
item() / items() usages match data typesAutomatically activates when user requests:
Examples of triggering phrases:
NEVER assume data structures without verification. Before any refactoring, ALWAYS analyze the actual data structures in the flow.
Examine Variable Declarations
"type": "Array", "type": "String", "type": "Object"Analyze Filter/Query Operations
where clauses in Query actionsitem() without property access → Array of primitives (strings/numbers)
"where": "@contains(toLower(item()), 'keyword')"
// ↑ This means: Array of strings, NOT array of objects!
item()?['PropertyName'] → Array of objects
"where": "@contains(item()?['Name'], 'keyword')"
// ↑ This means: Array of objects with 'Name' property
Trace Data Sources
from parameter in Query actions back to sourceValidate Item Access Patterns
items('LoopName') vs items('LoopName')?['Property']item() vs item()?['Property']item() but loop uses items('Loop')?['Prop'] → ERROR!Ask User When Uncertain (Use AskUserQuestion tool)
Example questions to ask:
contains(item(), 'keyword'). Does this mean your variable contains an array of strings like ['string1', 'string2'], or does it contain an array of objects?"Extract Flow Information
Identify User Requirements
Baseline Documentation
CRITICAL: Always research thoroughly before making changes. Use multiple sources in this order:
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:
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:
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:
Based on research findings, identify opportunities in these categories:
Categorize Improvements
User Request Alignment
Functional Equivalence Check
Create Change Plan
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:
Before finalizing output:
Functional Validation
Technical Validation
Optimization Validation
Platform Validation
Generate comprehensive refactoring report:
# 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"
### Reliability Improvements
- [List of reliability enhancements]
- Example: "Added error handling scope with retry logic for transient failures"
### Maintainability Enhancements
- [List of code quality improvements]
- Example: "Renamed 15 actions for clarity, organized into logical 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"
## 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]
## 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
### Performance Testing
1. [How to measure performance improvements]
2. Compare run duration with original flow
3. Monitor API call counts
### Error Testing
1. [How to verify error handling works]
2. Test failure scenarios
3. Verify retry logic
## 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
### 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)
ALWAYS provide two deliverables:
{
"comment": "Refactored workflow - [Date] - Implements [key improvements]",
"definition": {
// Complete, valid, platform-specific JSON
// Ready for copy-paste/import
// No placeholders or TODOs
}
}
NEVER hallucinate or guess. Always:
NEVER change behavior unless explicitly requested. Always:
NEVER output partial or placeholder JSON. Always:
Before delivering output, verify:
Data Structure Validation (CRITICAL - New!):
where clauses for data type indicatorsitem() vs item()?['Property'] consistency throughout flowitems() usage matches source data structureTechnical Validation:
Functional Validation:
Deliverables:
Before (100 API calls):
{
"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):
{
"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
Before (no error handling):
{
"Send_email": {
"type": "ApiConnection",
"inputs": {
"host": {"connectionName": "shared_office365"},
"method": "post",
"path": "/Mail"
}
}
}
After (comprehensive error handling):
{
"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
Before (sequential, slow):
{
"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):
{
"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)
Before (cryptic names):
{
"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):
{
"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
Before (insecure):
{
"HTTP_Call": {
"type": "Http",
"inputs": {
"uri": "https://api.example.com/data",
"headers": {
"Authorization": "Bearer sk-1234567890abcdef"
}
}
}
}
After (secure):
{
"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
Key Optimizations:
$expand and $select in OData queries$filter queriesBest Practices Documentation: Docs/PowerAutomateDocs/
Key Optimizations:
Best Practices Documentation: Docs/N8NDocs/
Key Optimizations:
Key Optimizations:
Purpose: Find best practices and optimization guidelines
Input Requirements:
Expected Output:
Invocation:
Task tool, subagent_type="Explore", thoroughness="very thorough"
Purpose: Generate complete, optimized workflow JSON
Input Requirements:
Expected Output:
Invocation:
Task tool, subagent_type="general-purpose"
User: "Fix the DossierPlusRécent variable assignment - it's filtering on array but accessing wrong property"
Input Flow:
{
"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:
Phase 0 - Data Structure Analysis:
contains(toLower(item()), 'cnesst') uses item() without propertyListeDesDossier is array of strings, NOT array of objects!["CNESST 2025-01-15", "CNESST 2025-02-20", "INVALIDITÉ 2025-01-10"]Identify Bug:
["CNESST 2025-01-15", ...]items('LoopCNESST')?['Nom'] (treating string as object)Correct Fix:
"DossierPlusRécent_CNESST": {
"type": "SetVariable",
"inputs": {
"name": "DossierPlusRecent",
"value": "@items('LoopCNESST')" // ← CORRECT: Direct string value
}
}
Also Fix DEBUG Action:
"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:
item() vs item()?['Prop'] tells you the data structureOutput:
User: "Optimize this Power Automate flow to reduce execution time"
Input Flow: Flow with 100 sequential API calls
Workflow:
Output:
User: "Refactor this flow to follow Power Automate best practices"
Input Flow: Working but poorly structured flow
Workflow:
Output:
User: "Add comprehensive error handling to this workflow"
Input Flow: Flow with no error handling
Workflow:
Output:
Use automation-debugger instead if:
Use automation-validator after refactoring to:
User messages that trigger this skill:
Version: 2.0 Last Updated: 2025-10-31 Platforms: Power Automate, n8n, Make, Zapier + extensible
Major Improvements:
Key Changes:
item() vs item()?['Property'] patterns in filtersLessons Learned:
contains(item(), 'x') = array of stringsThis skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create command with file references", "interactive command", "use AskUserQuestion in command", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code.
This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.
This skill should be used when the user asks to "create a hook", "add a PreToolUse/PostToolUse/Stop hook", "validate tool use", "implement prompt-based hooks", "use ${CLAUDE_PLUGIN_ROOT}", "set up event-driven automation", "block dangerous commands", or mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API.