spacehub

surshar / claude-code

Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.

Built by Anthropic · github.com/anthropics

claude-code / plugins / plugin-dev / skills / command-development / references / advanced-workflows.md
722 lines · 13.3 KBPreviewCodeRaw
1# Advanced Workflow Patterns
2
3Multi-step command sequences and composition patterns for complex workflows.
4
5## Overview
6
7Advanced workflows combine multiple commands, coordinate state across invocations, and create sophisticated automation sequences. These patterns enable building complex functionality from simple command building blocks.
8
9## Multi-Step Command Patterns
10
11### Sequential Workflow Command
12
13Commands that guide users through multi-step processes:
14
15```markdown
16---
17description: Complete PR review workflow
18argument-hint: [pr-number]
19allowed-tools: Bash(gh:*), Read, Grep
20---
21
22# PR Review Workflow for #$1
23
24## Step 1: Fetch PR Details
25!`gh pr view $1 --json title,body,author,files`
26
27## Step 2: Review Files
28Files changed: !`gh pr diff $1 --name-only`
29
30For each file:
31- Check code quality
32- Verify tests exist
33- Review documentation
34
35## Step 3: Run Checks
36Test status: !`gh pr checks $1`
37
38Verify:
39- All tests passing
40- No merge conflicts
41- CI/CD successful
42
43## Step 4: Provide Feedback
44
45Summarize:
46- Issues found (critical/minor)
47- Suggestions for improvement
48- Approval recommendation
49
50Would you like to:
511. Approve PR
522. Request changes
533. Leave comments only
54
55Reply with your choice and I'll help complete the action.
56```
57
58**Key features:**
59- Numbered steps for clarity
60- Bash execution for context
61- Decision points for user input
62- Next action suggestions
63
64### State-Carrying Workflow
65
66Commands that maintain state between invocations:
67
68```markdown
69---
70description: Initialize deployment workflow
71allowed-tools: Write, Bash(git:*)
72---
73
74# Initialize Deployment
75
76Creating deployment tracking file...
77
78Current branch: !`git branch --show-current`
79Latest commit: !`git log -1 --format=%H`
80
81Deployment state saved to `.claude/deployment-state.local.md`:
82
83\`\`\`markdown
84---
85initialized: true
86branch: $(git branch --show-current)
87commit: $(git log -1 --format=%H)
88timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)
89status: initialized
90---
91
92# Deployment Tracking
93
94Branch: $(git branch --show-current)
95Started: $(date)
96
97Next steps:
981. Run tests: /deploy-test
992. Build: /deploy-build
1003. Deploy: /deploy-execute
101\`\`\`
102
103State saved. Run `/deploy-test` to continue.
104```
105
106**Next command** (`/deploy-test`):
107```markdown
108---
109description: Run deployment tests
110allowed-tools: Read, Bash(npm:*)
111---
112
113Reading deployment state from `.claude/deployment-state.local.md`...
114
115Running tests: !`npm test`
116
117Updating state to 'tested'...
118
119Tests complete. Run `/deploy-build` to continue.
120```
121
122**Pattern benefits:**
123- Persistent state across commands
124- Clear workflow progression
125- Safety checkpoints
126- Resume capability
127
128### Conditional Workflow Branching
129
130Commands that adapt based on conditions:
131
132```markdown
133---
134description: Smart deployment workflow
135argument-hint: [environment]
136allowed-tools: Bash(git:*), Bash(npm:*), Read
137---
138
139# Deploy to $1
140
141## Pre-flight Checks
142
143Branch: !`git branch --show-current`
144Status: !`git status --short`
145
146**Checking conditions:**
147
1481. Branch status:
149 - If main/master: Require approval
150 - If feature branch: Warning about target
151 - If hotfix: Fast-track process
152
1532. Tests:
154 !`npm test`
155 - If tests fail: STOP - fix tests first
156 - If tests pass: Continue
157
1583. Environment:
159 - If $1 = 'production': Extra validation
160 - If $1 = 'staging': Standard process
161 - If $1 = 'dev': Minimal checks
162
163**Workflow decision:**
164Based on above, proceeding with: [determined workflow]
165
166[Conditional steps based on environment and status]
167
168Ready to deploy? (yes/no)
169```
170
171## Command Composition Patterns
172
173### Command Chaining
174
175Commands designed to work together:
176
177```markdown
178---
179description: Prepare for code review
180---
181
182# Prepare Code Review
183
184Running preparation sequence:
185
1861. Format code: /format-code
1872. Run linter: /lint-code
1883. Run tests: /test-all
1894. Generate coverage: /coverage-report
1905. Create review summary: /review-summary
191
192This is a meta-command. After completing each step above,
193I'll compile results and prepare comprehensive review materials.
194
195Starting sequence...
196```
197
198**Individual commands** are simple:
199- `/format-code` - Just formats
200- `/lint-code` - Just lints
201- `/test-all` - Just tests
202
203**Composition command** orchestrates them.
204
205### Pipeline Pattern
206
207Commands that process output from previous commands:
208
209```markdown
210---
211description: Analyze test failures
212---
213
214# Analyze Test Failures
215
216## Step 1: Get test results
217(Run /test-all first if not done)
218
219Reading test output...
220
221## Step 2: Categorize failures
222- Flaky tests (random failures)
223- Consistent failures
224- New failures vs existing
225
226## Step 3: Prioritize
227Rank by:
228- Impact (critical path vs edge case)
229- Frequency (always fails vs sometimes)
230- Effort (quick fix vs major work)
231
232## Step 4: Generate fix plan
233For each failure:
234- Root cause hypothesis
235- Suggested fix approach
236- Estimated effort
237
238Would you like me to:
2391. Fix highest priority failure
2402. Generate detailed fix plans for all
2413. Create GitHub issues for each
242```
243
244### Parallel Execution Pattern
245
246Commands that coordinate multiple simultaneous operations:
247
248```markdown
249---
250description: Run comprehensive validation
251allowed-tools: Bash(*), Read
252---
253
254# Comprehensive Validation
255
256Running validations in parallel...
257
258Starting:
259- Code quality checks
260- Security scanning
261- Dependency audit
262- Performance profiling
263
264This will take 2-3 minutes. I'll monitor all processes
265and report when complete.
266
267[Poll each process and report progress]
268
269All validations complete. Summary:
270- Quality: PASS (0 issues)
271- Security: WARN (2 minor issues)
272- Dependencies: PASS
273- Performance: PASS (baseline met)
274
275Details:
276[Collated results from all checks]
277```
278
279## Workflow State Management
280
281### Using .local.md Files
282
283Store workflow state in plugin-specific files:
284
285```markdown
286.claude/plugin-name-workflow.local.md:
287
288---
289workflow: deployment
290stage: testing
291started: 2025-01-15T10:30:00Z
292environment: staging
293branch: feature/new-api
294commit: abc123def
295tests_passed: false
296build_complete: false
297---
298
299# Deployment Workflow State
300
301Current stage: Testing
302Started: 2025-01-15 10:30 UTC
303
304Completed steps:
305- ✅ Validation
306- ✅ Branch check
307- ⏳ Testing (in progress)
308
309Pending steps:
310- Build
311- Deploy
312- Smoke tests
313```
314
315**Reading state in commands:**
316
317```markdown
318---
319description: Continue deployment workflow
320allowed-tools: Read, Write
321---
322
323Reading workflow state from .claude/plugin-name-workflow.local.md...
324
325Current stage: @.claude/plugin-name-workflow.local.md
326
327[Parse YAML frontmatter to determine next step]
328
329Next action based on state: [determined action]
330```
331
332### Workflow Recovery
333
334Handle interrupted workflows:
335
336```markdown
337---
338description: Resume deployment workflow
339allowed-tools: Read
340---
341
342# Resume Deployment
343
344Checking for interrupted workflow...
345
346State file: @.claude/plugin-name-workflow.local.md
347
348**Workflow found:**
349- Started: [timestamp]
350- Environment: [env]
351- Last completed: [step]
352
353**Recovery options:**
3541. Resume from last step
3552. Restart from beginning
3563. Abort and clean up
357
358Which would you like? (1/2/3)
359```
360
361## Workflow Coordination Patterns
362
363### Cross-Command Communication
364
365Commands that signal each other:
366
367```markdown
368---
369description: Mark feature complete
370allowed-tools: Write
371---
372
373# Mark Feature Complete
374
375Writing completion marker...
376
377Creating: .claude/feature-complete.flag
378
379This 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)
383
384Feature marked complete.
385```
386
387**Other commands check for flag:**
388
389```markdown
390---
391description: Generate release notes
392allowed-tools: Read, Bash(git:*)
393---
394
395Checking for completed features...
396
397if [ -f .claude/feature-complete.flag ]; then
398 Feature ready for release notes
399fi
400
401[Include in release notes]
402```
403
404### Workflow Locking
405
406Prevent concurrent workflow execution:
407
408```markdown
409---
410description: Start deployment
411allowed-tools: Read, Write, Bash
412---
413
414# Start Deployment
415
416Checking for active deployments...
417
418if [ -f .claude/deployment.lock ]; then
419 ERROR: Deployment already in progress
420 Started: [timestamp from lock file]
421
422 Cannot start concurrent deployment.
423 Wait for completion or run /deployment-abort
424
425 Exit.
426fi
427
428Creating deployment lock...
429
430Deployment started. Lock created.
431[Proceed with deployment]
432```
433
434**Lock cleanup:**
435
436```markdown
437---
438description: Complete deployment
439allowed-tools: Write, Bash
440---
441
442Deployment complete.
443
444Removing deployment lock...
445rm .claude/deployment.lock
446
447Ready for next deployment.
448```
449
450## Advanced Argument Handling
451
452### Optional Arguments with Defaults
453
454```markdown
455---
456description: Deploy with optional version
457argument-hint: [environment] [version]
458---
459
460Environment: ${1:-staging}
461Version: ${2:-latest}
462
463Deploying ${2:-latest} to ${1:-staging}...
464
465Note: Using defaults for missing arguments:
466- Environment defaults to 'staging'
467- Version defaults to 'latest'
468```
469
470### Argument Validation
471
472```markdown
473---
474description: Deploy to validated environment
475argument-hint: [environment]
476---
477
478Environment: $1
479
480Validating environment...
481
482valid_envs="dev staging production"
483if ! echo "$valid_envs" | grep -w "$1" > /dev/null; then
484 ERROR: Invalid environment '$1'
485 Valid options: dev, staging, production
486 Exit.
487fi
488
489Environment validated. Proceeding...
490```
491
492### Argument Transformation
493
494```markdown
495---
496description: Deploy with shorthand
497argument-hint: [env-shorthand]
498---
499
500Input: $1
501
502Expanding shorthand:
503- d/dev → development
504- s/stg → staging
505- p/prod → production
506
507case "$1" in
508 d|dev) ENV="development";;
509 s|stg) ENV="staging";;
510 p|prod) ENV="production";;
511 *) ENV="$1";;
512esac
513
514Deploying to: $ENV
515```
516
517## Error Handling in Workflows
518
519### Graceful Failure
520
521```markdown
522---
523description: Resilient deployment workflow
524---
525
526# Deployment Workflow
527
528Running steps with error handling...
529
530## Step 1: Tests
531!`npm test`
532
533if [ $? -ne 0 ]; then
534 ERROR: Tests failed
535
536 Options:
537 1. Fix tests and retry
538 2. Skip tests (NOT recommended)
539 3. Abort deployment
540
541 What would you like to do?
542
543 [Wait for user input before continuing]
544fi
545
546## Step 2: Build
547[Continue only if Step 1 succeeded]
548```
549
550### Rollback on Failure
551
552```markdown
553---
554description: Deployment with rollback
555---
556
557# Deploy with Rollback
558
559Saving current state for rollback...
560Previous version: !`current-version.sh`
561
562Deploying new version...
563
564!`deploy.sh`
565
566if [ $? -ne 0 ]; then
567 DEPLOYMENT FAILED
568
569 Initiating automatic rollback...
570 !`rollback.sh`
571
572 Rolled back to previous version.
573 Check logs for failure details.
574fi
575
576Deployment complete.
577```
578
579### Checkpoint Recovery
580
581```markdown
582---
583description: Workflow with checkpoints
584---
585
586# Multi-Stage Deployment
587
588## Checkpoint 1: Validation
589!`validate.sh`
590echo "checkpoint:validation" >> .claude/deployment-checkpoints.log
591
592## Checkpoint 2: Build
593!`build.sh`
594echo "checkpoint:build" >> .claude/deployment-checkpoints.log
595
596## Checkpoint 3: Deploy
597!`deploy.sh`
598echo "checkpoint:deploy" >> .claude/deployment-checkpoints.log
599
600If any step fails, resume with:
601/deployment-resume [last-successful-checkpoint]
602```
603
604## Best Practices
605
606### Workflow Design
607
6081. **Clear progression**: Number steps, show current position
6092. **Explicit state**: Don't rely on implicit state
6103. **User control**: Provide decision points
6114. **Error recovery**: Handle failures gracefully
6125. **Progress indication**: Show what's done, what's pending
613
614### Command Composition
615
6161. **Single responsibility**: Each command does one thing well
6172. **Composable design**: Commands work together easily
6183. **Standard interfaces**: Consistent input/output formats
6194. **Loose coupling**: Commands don't depend on each other's internals
620
621### State Management
622
6231. **Persistent state**: Use .local.md files
6242. **Atomic updates**: Write complete state files atomically
6253. **State validation**: Check state file format/completeness
6264. **Cleanup**: Remove stale state files
6275. **Documentation**: Document state file formats
628
629### Error Handling
630
6311. **Fail fast**: Detect errors early
6322. **Clear messages**: Explain what went wrong
6333. **Recovery options**: Provide clear next steps
6344. **State preservation**: Keep state for recovery
6355. **Rollback capability**: Support undoing changes
636
637## Example: Complete Deployment Workflow
638
639### Initialize Command
640
641```markdown
642---
643description: Initialize deployment
644argument-hint: [environment]
645allowed-tools: Write, Bash(git:*)
646---
647
648# Initialize Deployment to $1
649
650Creating workflow state...
651
652\`\`\`yaml
653---
654workflow: deployment
655environment: $1
656branch: !`git branch --show-current`
657commit: !`git rev-parse HEAD`
658stage: initialized
659timestamp: !`date -u +%Y-%m-%dT%H:%M:%SZ`
660---
661\`\`\`
662
663Written to .claude/deployment-state.local.md
664
665Next: Run /deployment-validate
666```
667
668### Validation Command
669
670```markdown
671---
672description: Validate deployment
673allowed-tools: Read, Bash
674---
675
676Reading state: @.claude/deployment-state.local.md
677
678Running validation...
679- Branch check: PASS
680- Tests: PASS
681- Build: PASS
682
683Updating state to 'validated'...
684
685Next: Run /deployment-execute
686```
687
688### Execution Command
689
690```markdown
691---
692description: Execute deployment
693allowed-tools: Read, Bash, Write
694---
695
696Reading state: @.claude/deployment-state.local.md
697
698Executing deployment to [environment]...
699
700!`deploy.sh [environment]`
701
702Deployment complete.
703Updating state to 'completed'...
704
705Cleanup: /deployment-cleanup
706```
707
708### Cleanup Command
709
710```markdown
711---
712description: Clean up deployment
713allowed-tools: Bash
714---
715
716Removing deployment state...
717rm .claude/deployment-state.local.md
718
719Deployment workflow complete.
720```
721
722This complete workflow demonstrates state management, sequential execution, error handling, and clean separation of concerns across multiple commands.