Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Guidance for developing custom slash commands for Claude Code plugins from the official Anthropic repository.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/advanced-workflows.md
1# Advanced Workflow Patterns23Multi-step command sequences and composition patterns for complex workflows.45## Overview67Advanced workflows combine multiple commands, coordinate state across invocations, and create sophisticated automation sequences. These patterns enable building complex functionality from simple command building blocks.89## Multi-Step Command Patterns1011### Sequential Workflow Command1213Commands that guide users through multi-step processes:1415```markdown16---17description: Complete PR review workflow18argument-hint: [pr-number]19allowed-tools: Bash(gh:*), Read, Grep20---2122# PR Review Workflow for #$12324## Step 1: Fetch PR Details25!`gh pr view $1 --json title,body,author,files`2627## Step 2: Review Files28Files changed: !`gh pr diff $1 --name-only`2930For each file:31- Check code quality32- Verify tests exist33- Review documentation3435## Step 3: Run Checks36Test status: !`gh pr checks $1`3738Verify:39- All tests passing40- No merge conflicts41- CI/CD successful4243## Step 4: Provide Feedback4445Summarize:46- Issues found (critical/minor)47- Suggestions for improvement48- Approval recommendation4950Would you like to:511. Approve PR522. Request changes533. Leave comments only5455Reply with your choice and I'll help complete the action.56```5758**Key features:**59- Numbered steps for clarity60- Bash execution for context61- Decision points for user input62- Next action suggestions6364### State-Carrying Workflow6566Commands that maintain state between invocations:6768```markdown69---70description: Initialize deployment workflow71allowed-tools: Write, Bash(git:*)72---7374# Initialize Deployment7576Creating deployment tracking file...7778Current branch: !`git branch --show-current`79Latest commit: !`git log -1 --format=%H`8081Deployment state saved to `.claude/deployment-state.local.md`:8283\`\`\`markdown84---85initialized: true86branch: $(git branch --show-current)87commit: $(git log -1 --format=%H)88timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)89status: initialized90---9192# Deployment Tracking9394Branch: $(git branch --show-current)95Started: $(date)9697Next steps:981. Run tests: /deploy-test992. Build: /deploy-build1003. Deploy: /deploy-execute101\`\`\`102103State saved. Run `/deploy-test` to continue.104```105106**Next command** (`/deploy-test`):107```markdown108---109description: Run deployment tests110allowed-tools: Read, Bash(npm:*)111---112113Reading deployment state from `.claude/deployment-state.local.md`...114115Running tests: !`npm test`116117Updating state to 'tested'...118119Tests complete. Run `/deploy-build` to continue.120```121122**Pattern benefits:**123- Persistent state across commands124- Clear workflow progression125- Safety checkpoints126- Resume capability127128### Conditional Workflow Branching129130Commands that adapt based on conditions:131132```markdown133---134description: Smart deployment workflow135argument-hint: [environment]136allowed-tools: Bash(git:*), Bash(npm:*), Read137---138139# Deploy to $1140141## Pre-flight Checks142143Branch: !`git branch --show-current`144Status: !`git status --short`145146**Checking conditions:**1471481. Branch status:149- If main/master: Require approval150- If feature branch: Warning about target151- If hotfix: Fast-track process1521532. Tests:154!`npm test`155- If tests fail: STOP - fix tests first156- If tests pass: Continue1571583. Environment:159- If $1 = 'production': Extra validation160- If $1 = 'staging': Standard process161- If $1 = 'dev': Minimal checks162163**Workflow decision:**164Based on above, proceeding with: [determined workflow]165166[Conditional steps based on environment and status]167168Ready to deploy? (yes/no)169```170171## Command Composition Patterns172173### Command Chaining174175Commands designed to work together:176177```markdown178---179description: Prepare for code review180---181182# Prepare Code Review183184Running preparation sequence:1851861. Format code: /format-code1872. Run linter: /lint-code1883. Run tests: /test-all1894. Generate coverage: /coverage-report1905. Create review summary: /review-summary191192This is a meta-command. After completing each step above,193I'll compile results and prepare comprehensive review materials.194195Starting sequence...196```197198**Individual commands** are simple:199- `/format-code` - Just formats200- `/lint-code` - Just lints201- `/test-all` - Just tests202203**Composition command** orchestrates them.204205### Pipeline Pattern206207Commands that process output from previous commands:208209```markdown210---211description: Analyze test failures212---213214# Analyze Test Failures215216## Step 1: Get test results217(Run /test-all first if not done)218219Reading test output...220221## Step 2: Categorize failures222- Flaky tests (random failures)223- Consistent failures224- New failures vs existing225226## Step 3: Prioritize227Rank by:228- Impact (critical path vs edge case)229- Frequency (always fails vs sometimes)230- Effort (quick fix vs major work)231232## Step 4: Generate fix plan233For each failure:234- Root cause hypothesis235- Suggested fix approach236- Estimated effort237238Would you like me to:2391. Fix highest priority failure2402. Generate detailed fix plans for all2413. Create GitHub issues for each242```243244### Parallel Execution Pattern245246Commands that coordinate multiple simultaneous operations:247248```markdown249---250description: Run comprehensive validation251allowed-tools: Bash(*), Read252---253254# Comprehensive Validation255256Running validations in parallel...257258Starting:259- Code quality checks260- Security scanning261- Dependency audit262- Performance profiling263264This will take 2-3 minutes. I'll monitor all processes265and report when complete.266267[Poll each process and report progress]268269All validations complete. Summary:270- Quality: PASS (0 issues)271- Security: WARN (2 minor issues)272- Dependencies: PASS273- Performance: PASS (baseline met)274275Details:276[Collated results from all checks]277```278279## Workflow State Management280281### Using .local.md Files282283Store workflow state in plugin-specific files:284285```markdown286.claude/plugin-name-workflow.local.md:287288---289workflow: deployment290stage: testing291started: 2025-01-15T10:30:00Z292environment: staging293branch: feature/new-api294commit: abc123def295tests_passed: false296build_complete: false297---298299# Deployment Workflow State300301Current stage: Testing302Started: 2025-01-15 10:30 UTC303304Completed steps:305- ✅ Validation306- ✅ Branch check307- ⏳ Testing (in progress)308309Pending steps:310- Build311- Deploy312- Smoke tests313```314315**Reading state in commands:**316317```markdown318---319description: Continue deployment workflow320allowed-tools: Read, Write321---322323Reading workflow state from .claude/plugin-name-workflow.local.md...324325Current stage: @.claude/plugin-name-workflow.local.md326327[Parse YAML frontmatter to determine next step]328329Next action based on state: [determined action]330```331332### Workflow Recovery333334Handle interrupted workflows:335336```markdown337---338description: Resume deployment workflow339allowed-tools: Read340---341342# Resume Deployment343344Checking for interrupted workflow...345346State file: @.claude/plugin-name-workflow.local.md347348**Workflow found:**349- Started: [timestamp]350- Environment: [env]351- Last completed: [step]352353**Recovery options:**3541. Resume from last step3552. Restart from beginning3563. Abort and clean up357358Which would you like? (1/2/3)359```360361## Workflow Coordination Patterns362363### Cross-Command Communication364365Commands that signal each other:366367```markdown368---369description: Mark feature complete370allowed-tools: Write371---372373# Mark Feature Complete374375Writing completion marker...376377Creating: .claude/feature-complete.flag378379This signals other commands that feature is ready for:380- Integration testing (/integration-test will auto-detect)381- Documentation generation (/docs-generate will include)382- Release notes (/release-notes will add)383384Feature marked complete.385```386387**Other commands check for flag:**388389```markdown390---391description: Generate release notes392allowed-tools: Read, Bash(git:*)393---394395Checking for completed features...396397if [ -f .claude/feature-complete.flag ]; then398Feature ready for release notes399fi400401[Include in release notes]402```403404### Workflow Locking405406Prevent concurrent workflow execution:407408```markdown409---410description: Start deployment411allowed-tools: Read, Write, Bash412---413414# Start Deployment415416Checking for active deployments...417418if [ -f .claude/deployment.lock ]; then419ERROR: Deployment already in progress420Started: [timestamp from lock file]421422Cannot start concurrent deployment.423Wait for completion or run /deployment-abort424425Exit.426fi427428Creating deployment lock...429430Deployment started. Lock created.431[Proceed with deployment]432```433434**Lock cleanup:**435436```markdown437---438description: Complete deployment439allowed-tools: Write, Bash440---441442Deployment complete.443444Removing deployment lock...445rm .claude/deployment.lock446447Ready for next deployment.448```449450## Advanced Argument Handling451452### Optional Arguments with Defaults453454```markdown455---456description: Deploy with optional version457argument-hint: [environment] [version]458---459460Environment: ${1:-staging}461Version: ${2:-latest}462463Deploying ${2:-latest} to ${1:-staging}...464465Note: Using defaults for missing arguments:466- Environment defaults to 'staging'467- Version defaults to 'latest'468```469470### Argument Validation471472```markdown473---474description: Deploy to validated environment475argument-hint: [environment]476---477478Environment: $1479480Validating environment...481482valid_envs="dev staging production"483if ! echo "$valid_envs" | grep -w "$1" > /dev/null; then484ERROR: Invalid environment '$1'485Valid options: dev, staging, production486Exit.487fi488489Environment validated. Proceeding...490```491492### Argument Transformation493494```markdown495---496description: Deploy with shorthand497argument-hint: [env-shorthand]498---499500Input: $1501502Expanding shorthand:503- d/dev → development504- s/stg → staging505- p/prod → production506507case "$1" in508d|dev) ENV="development";;509s|stg) ENV="staging";;510p|prod) ENV="production";;511*) ENV="$1";;512esac513514Deploying to: $ENV515```516517## Error Handling in Workflows518519### Graceful Failure520521```markdown522---523description: Resilient deployment workflow524---525526# Deployment Workflow527528Running steps with error handling...529530## Step 1: Tests531!`npm test`532533if [ $? -ne 0 ]; then534ERROR: Tests failed535536Options:5371. Fix tests and retry5382. Skip tests (NOT recommended)5393. Abort deployment540541What would you like to do?542543[Wait for user input before continuing]544fi545546## Step 2: Build547[Continue only if Step 1 succeeded]548```549550### Rollback on Failure551552```markdown553---554description: Deployment with rollback555---556557# Deploy with Rollback558559Saving current state for rollback...560Previous version: !`current-version.sh`561562Deploying new version...563564!`deploy.sh`565566if [ $? -ne 0 ]; then567DEPLOYMENT FAILED568569Initiating automatic rollback...570!`rollback.sh`571572Rolled back to previous version.573Check logs for failure details.574fi575576Deployment complete.577```578579### Checkpoint Recovery580581```markdown582---583description: Workflow with checkpoints584---585586# Multi-Stage Deployment587588## Checkpoint 1: Validation589!`validate.sh`590echo "checkpoint:validation" >> .claude/deployment-checkpoints.log591592## Checkpoint 2: Build593!`build.sh`594echo "checkpoint:build" >> .claude/deployment-checkpoints.log595596## Checkpoint 3: Deploy597!`deploy.sh`598echo "checkpoint:deploy" >> .claude/deployment-checkpoints.log599600If any step fails, resume with:601/deployment-resume [last-successful-checkpoint]602```603604## Best Practices605606### Workflow Design6076081. **Clear progression**: Number steps, show current position6092. **Explicit state**: Don't rely on implicit state6103. **User control**: Provide decision points6114. **Error recovery**: Handle failures gracefully6125. **Progress indication**: Show what's done, what's pending613614### Command Composition6156161. **Single responsibility**: Each command does one thing well6172. **Composable design**: Commands work together easily6183. **Standard interfaces**: Consistent input/output formats6194. **Loose coupling**: Commands don't depend on each other's internals620621### State Management6226231. **Persistent state**: Use .local.md files6242. **Atomic updates**: Write complete state files atomically6253. **State validation**: Check state file format/completeness6264. **Cleanup**: Remove stale state files6275. **Documentation**: Document state file formats628629### Error Handling6306311. **Fail fast**: Detect errors early6322. **Clear messages**: Explain what went wrong6333. **Recovery options**: Provide clear next steps6344. **State preservation**: Keep state for recovery6355. **Rollback capability**: Support undoing changes636637## Example: Complete Deployment Workflow638639### Initialize Command640641```markdown642---643description: Initialize deployment644argument-hint: [environment]645allowed-tools: Write, Bash(git:*)646---647648# Initialize Deployment to $1649650Creating workflow state...651652\`\`\`yaml653---654workflow: deployment655environment: $1656branch: !`git branch --show-current`657commit: !`git rev-parse HEAD`658stage: initialized659timestamp: !`date -u +%Y-%m-%dT%H:%M:%SZ`660---661\`\`\`662663Written to .claude/deployment-state.local.md664665Next: Run /deployment-validate666```667668### Validation Command669670```markdown671---672description: Validate deployment673allowed-tools: Read, Bash674---675676Reading state: @.claude/deployment-state.local.md677678Running validation...679- Branch check: PASS680- Tests: PASS681- Build: PASS682683Updating state to 'validated'...684685Next: Run /deployment-execute686```687688### Execution Command689690```markdown691---692description: Execute deployment693allowed-tools: Read, Bash, Write694---695696Reading state: @.claude/deployment-state.local.md697698Executing deployment to [environment]...699700!`deploy.sh [environment]`701702Deployment complete.703Updating state to 'completed'...704705Cleanup: /deployment-cleanup706```707708### Cleanup Command709710```markdown711---712description: Clean up deployment713allowed-tools: Bash714---715716Removing deployment state...717rm .claude/deployment-state.local.md718719Deployment workflow complete.720```721722This complete workflow demonstrates state management, sequential execution, error handling, and clean separation of concerns across multiple commands.723