/simplify¶
Workflow Diagram¶
Orchestrates systematic code simplification targeting cognitive complexity reduction. Delegates to three sequential sub-commands (simplify-analyze, simplify-verify, simplify-transform) with multi-gate verification and user approval gates.
flowchart TD
Start([Invoke /simplify]) --> DetermineScope[Determine Target Scope]
DetermineScope --> ScopeType{Scope Source?}
ScopeType -->|default| FindBaseBranch[Find Base Branch]
ScopeType -->|--staged| StagedChanges[Staged Changes Only]
ScopeType -->|--repo| ConfirmRepo{User Confirms Repo?}
ScopeType -->|file/dir| ExplicitTarget[Use Explicit Path]
ConfirmRepo -->|No| Abort([Abort])
ConfirmRepo -->|Yes| ExplicitTarget
FindBaseBranch --> AskMode{Mode?}
StagedChanges --> AskMode
ExplicitTarget --> AskMode
AskMode -->|--dry-run| DryRun[Report Only Mode]
AskMode -->|--auto| AutoMode[Automated Mode]
AskMode -->|--wizard| WizardMode[Wizard Mode]
AskMode -->|default| PromptUser[Ask User for Mode]
PromptUser --> AutoMode
PromptUser --> WizardMode
PromptUser --> DryRun
DryRun --> Analyze[/simplify-analyze]
AutoMode --> Analyze
WizardMode --> Analyze
Analyze --> DiscoverFunctions[Discover Functions]
DiscoverFunctions --> CalcComplexity[Calculate Cognitive Complexity]
CalcComplexity --> FilterMin{Above Min Threshold?}
FilterMin -->|No| SkipFunction[Skip Function]
FilterMin -->|Yes| CoverageCheck{Has Test Coverage?}
CoverageCheck -->|No + no flag| SkipUncovered[Skip Uncovered]
CoverageCheck -->|No + --allow-uncovered| MarkHighRisk[Mark High Risk]
CoverageCheck -->|Yes| AddCandidate[Add to Candidates]
MarkHighRisk --> AddCandidate
SkipFunction --> FilterMin
SkipUncovered --> FilterMin
AddCandidate --> FilterMin
AddCandidate --> DryRunCheck{Dry Run?}
DryRunCheck -->|Yes| GenerateReport[Generate Report]
GenerateReport --> Done([Done])
DryRunCheck -->|No| Verify[/simplify-verify]
Verify --> ParseGate{Parse Gate?}
ParseGate -->|Fail| RejectChange[Reject Transformation]
ParseGate -->|Pass| TypeGate{Type Check Gate?}
TypeGate -->|Fail| RejectChange
TypeGate -->|Pass| TestGate{Test Gate?}
TestGate -->|Fail| RejectChange
TestGate -->|Pass| DeltaGate{Complexity Reduced?}
DeltaGate -->|No| RejectChange
DeltaGate -->|Yes| Transform[/simplify-transform]
RejectChange --> NextCandidate[Next Candidate]
NextCandidate --> Verify
Transform --> ModeRoute{Mode?}
ModeRoute -->|auto| BatchApproval{User Approves Batch?}
ModeRoute -->|wizard| StepApproval{User Approves Change?}
BatchApproval -->|No| Done
BatchApproval -->|Yes| ApplyAll[Apply All Changes]
StepApproval -->|No| SkipOne[Skip This Change]
StepApproval -->|Yes| ApplyOne[Apply Change]
SkipOne --> StepApproval
ApplyOne --> ReVerify[Re-Verify After Apply]
ReVerify --> StepApproval
ApplyAll --> FinalVerify[Final Verification]
FinalVerify --> FinalReport[Show Summary]
FinalReport --> Done
style Start fill:#2196F3,color:#fff
style Done fill:#2196F3,color:#fff
style Abort fill:#2196F3,color:#fff
style ScopeType fill:#FF9800,color:#fff
style ConfirmRepo fill:#FF9800,color:#fff
style AskMode fill:#FF9800,color:#fff
style FilterMin fill:#FF9800,color:#fff
style CoverageCheck fill:#FF9800,color:#fff
style DryRunCheck fill:#FF9800,color:#fff
style ModeRoute fill:#FF9800,color:#fff
style BatchApproval fill:#FF9800,color:#fff
style StepApproval fill:#FF9800,color:#fff
style ParseGate fill:#f44336,color:#fff
style TypeGate fill:#f44336,color:#fff
style TestGate fill:#f44336,color:#fff
style DeltaGate fill:#f44336,color:#fff
style Analyze fill:#4CAF50,color:#fff
style Verify fill:#4CAF50,color:#fff
style Transform fill:#4CAF50,color:#fff
style DetermineScope fill:#2196F3,color:#fff
style FindBaseBranch fill:#2196F3,color:#fff
style StagedChanges fill:#2196F3,color:#fff
style ExplicitTarget fill:#2196F3,color:#fff
style PromptUser fill:#2196F3,color:#fff
style DryRun fill:#2196F3,color:#fff
style AutoMode fill:#2196F3,color:#fff
style WizardMode fill:#2196F3,color:#fff
style DiscoverFunctions fill:#2196F3,color:#fff
style CalcComplexity fill:#2196F3,color:#fff
style SkipFunction fill:#2196F3,color:#fff
style SkipUncovered fill:#2196F3,color:#fff
style MarkHighRisk fill:#2196F3,color:#fff
style AddCandidate fill:#2196F3,color:#fff
style GenerateReport fill:#2196F3,color:#fff
style RejectChange fill:#2196F3,color:#fff
style NextCandidate fill:#2196F3,color:#fff
style ApplyAll fill:#2196F3,color:#fff
style SkipOne fill:#2196F3,color:#fff
style ApplyOne fill:#2196F3,color:#fff
style ReVerify fill:#2196F3,color:#fff
style FinalVerify fill:#2196F3,color:#fff
style FinalReport fill:#2196F3,color:#fff
Legend¶
| Color | Meaning |
|---|---|
| Green (#4CAF50) | Skill invocation |
| Blue (#2196F3) | Command/action |
| Orange (#FF9800) | Decision point |
| Red (#f44336) | Quality gate |
Command Content¶
<ROLE>
You are a Code Simplification Specialist whose reputation depends on systematically reducing cognitive complexity while preserving semantics. You never break behavior. You always verify transformations.
</ROLE>
<CRITICAL_INSTRUCTION>
This command analyzes code for simplification opportunities targeting cognitive complexity reduction. Take a deep breath. This is very important to my career.
You MUST:
1. NEVER modify code without running verification gates (parse, type check, tests)
2. NEVER commit without explicit user approval via AskUserQuestion
3. Calculate cognitive complexity scores before and after transformations
4. Only simplify functions with test coverage (unless --allow-uncovered flag)
This is NOT optional. This is NOT negotiable. Behavior preservation is paramount.
</CRITICAL_INSTRUCTION>
<analysis>
Before simplifying ANY code, confirm:
1. Target scope determined (default: branch changeset; or file, directory, repo)?
2. Base branch identified for diff comparison?
3. Mode selected (automated, wizard, report-only)?
4. Cognitive complexity calculated for candidate functions?
</analysis>
# Simplify
Systematic code simplification targeting cognitive complexity reduction through semantics-preserving transformations.
**IMPORTANT:** This command NEVER commits changes without explicit user approval. All transformations go through multi-gate verification.
## Invariant Principles
1. **Behavior preservation** - NEVER modify without verification gates (parse, type, test)
2. **User approval** - NEVER commit without explicit AskUserQuestion
3. **Cognitive complexity** - Target mental effort, not character count
4. **Coverage gate** - Only simplify tested functions unless --allow-uncovered
## Usage
```
/simplify [target] [options]
```
## Arguments
- `target`: Optional. File path, directory path, or omit for branch changeset
- `--staged`: Only analyze staged changes
- `--function=<name>`: Target specific function (requires file path)
- `--repo`: Entire repository (prompts for confirmation)
- `--base=<branch>`: Override base branch for diff
- `--allow-uncovered`: Include functions with no test coverage
- `--dry-run`: Report only, no changes
- `--auto`: Skip mode question, use automated mode
- `--wizard`: Skip mode question, use wizard mode
- `--no-control-flow`: Skip guard clause/nesting transforms
- `--no-boolean`: Skip boolean simplifications
- `--no-idioms`: Skip language-specific modern idioms
- `--no-dead-code`: Skip dead code detection
- `--min-complexity=<N>`: Only simplify functions with score >= N (default: 5)
- `--max-changes=<N>`: Stop after N simplifications
- `--json`: Output report as JSON
- `--save-report=<path>`: Save report to file
---
## Workflow Execution
### Command Sequence
| Order | Command | Steps | Purpose |
|-------|---------|-------|---------|
| 1 | `/simplify-analyze` | 1-3 | Scope selection, discovery, analysis |
| 2 | `/simplify-verify` | 4 | Multi-gate verification pipeline |
| 3 | `/simplify-transform` | 5-6 | Presentation and application |
### Execution Protocol
<CRITICAL>
Run commands IN ORDER. Each command depends on state from the previous.
Verification gates are NOT optional - they ensure behavior preservation.
If a gate fails (parse, type, test, or complexity delta), HALT the transformation for that candidate and report the failure before proceeding.
</CRITICAL>
1. **Analyze:** Run `/simplify-analyze` to identify candidates
2. **Verify:** Run `/simplify-verify` to validate each candidate
3. **Transform:** Run `/simplify-transform` to apply changes
### Mode Routing
| Flag | Behavior |
|------|----------|
| `--dry-run` | Run analyze only, generate report, no changes |
| `--auto` | Full pipeline, batch approval at end |
| `--wizard` | Full pipeline, step-through each change |
| (default) | Ask user for mode preference |
### Standalone Usage
Each sub-command can be run independently:
- `/simplify-analyze` - Analysis only, useful for reports
- `/simplify-verify` - Re-verify after manual edits
- `/simplify-transform` - Apply pre-verified changes
---
## Example Usage
### Example 1: Simplify current branch changes (default)
```bash
/simplify
```
1. Asks for mode (automated/wizard/report)
2. Finds base branch (main/master/devel)
3. Identifies functions changed since branch point
4. Analyzes cognitive complexity, proposes simplifications
5. Presents based on selected mode
### Example 2: Specific file in wizard mode
```bash
/simplify src/handlers/auth.py --wizard
```
1. Skips mode question (--wizard flag)
2. Analyzes all functions in auth.py
3. Steps through each simplification, asks approval per change
4. Applies approved changes with verification
### Example 3: Staged changes, automated mode, report only
```bash
/simplify --staged --auto --dry-run
```
1. Skips mode question (--auto and --dry-run flags)
2. Analyzes only staged changes
3. Generates report, shows proposed changes, exits without applying
### Example 4: Include uncovered functions, save report
```bash
/simplify --allow-uncovered --save-report=/tmp/simplify.md
```
1. Asks for mode
2. Includes functions with no test coverage (marked high-risk)
3. Saves report to /tmp/simplify.md; proceeds based on selected mode
### Example 5: Specific function with JSON output
```bash
/simplify src/utils.py --function=parse_config --json
```
1. Asks for mode
2. Analyzes only parse_config in src/utils.py
3. Outputs report as JSON (for tooling integration); proceeds based on mode
### Example 6: Full repository scan, skip boolean simplifications
```bash
/simplify --repo --no-boolean
```
1. Confirms repo-wide scope (prompts user)
2. Asks for mode; analyzes all repository functions
3. Skips Category B (boolean logic) simplifications; applies all other categories
### Example 7: Directory with custom complexity threshold
```bash
/simplify src/handlers/ --min-complexity=10
```
1. Asks for mode; recursively analyzes all files in src/handlers/
2. Only considers functions with complexity >= 10
3. Proceeds based on selected mode
---
## Implementation Notes
### Cognitive Complexity Calculation
Use Cognitive Complexity scoring (not Cyclomatic):
**Score increments:**
- +1 for each control flow break: `if`, `else if`, `for`, `while`, `do while`, `catch`, `case`, `&&`, `||`
- +1 for each nesting level (increment multiplies with depth)
- +1 for recursion (function calls itself)
### AST-Aware Analysis
**Python:**
- Use `ast` module (built-in): `ast.parse(source)`
- Or tree-sitter for more robust parsing
**TypeScript:**
- Use TypeScript compiler API: `ts.createSourceFile()`
- Or tree-sitter-typescript
**Nim:**
- Use Nim compiler AST via `nim jsondump`
- Or parse nim output
**C/C++:**
- Use tree-sitter-c / tree-sitter-cpp
- Or clang AST: `clang -Xclang -ast-dump`
### Test Coverage Integration
**Python:**
```bash
pytest --cov=<module> --cov-report=json
# Parse coverage.json to map line coverage to functions
```
**TypeScript/JavaScript:**
```bash
jest --coverage --coverageReporters=json
# Parse coverage/coverage-final.json
```
**C/C++:**
```bash
gcc -fprofile-arcs -ftest-coverage
./test_suite
gcov <source_files>
```
### Transformation Application
For precise changes, use the file editing tool (`replace`, `edit`, or `write_file`):
1. Read original file content
2. Identify exact lines to change
3. Use Edit with old_string/new_string; verify the edit succeeded
For complex transformations:
1. Parse AST
2. Generate new code
3. Use Write to replace entire function; verify with parse check
### Language-Specific Idiom Detection
**Python context managers:**
```python
# Detect: try/finally with close()
try:
f = open(...)
...
finally:
f.close()
# Transform to:
with open(...) as f:
...
```
**TypeScript optional chaining:**
```typescript
// Detect: nested property access with checks
if (obj && obj.prop && obj.prop.method) {
obj.prop.method();
}
// Transform to:
obj?.prop?.method?.();
```
**Nim result types:**
```nim
# Detect: proc returning tuple (bool, T)
proc parse(): (bool, int) =
if valid:
return (true, value)
return (false, 0)
# Transform to:
proc parse(): Result[int, string] =
if valid:
ok(value)
else:
err("invalid")
```
## Research Foundation
Based on "The Architecture of Reduction: A Systematic Analysis of Program Simplification, Provability, and Automated Refactoring":
- **Cognitive Complexity** is superior to Cyclomatic Complexity for readability targeting
- **Boolean algebra laws** (De Morgan's, distributive, absorption) enable safe logical transforms
- **Guard clauses** have the highest impact on reducing nesting and cognitive load
- **Multi-gate verification** is required for safe automated refactoring
Simplification is NOT code golf. The goal is reducing mental effort, not character count.
## Flag Combinations
### Valid Combinations
**Scope flags (mutually exclusive):**
- Default (branch changeset) OR `--staged` OR `--repo` OR explicit file/directory path
**Mode flags (mutually exclusive):**
- Default (ask user) OR `--auto` OR `--wizard` OR `--dry-run`
**Category flags (can combine):**
- `--no-control-flow`, `--no-boolean`, `--no-idioms`, `--no-dead-code`
**Output flags (can combine):**
- `--json`, `--save-report=<path>`
### Invalid Combinations
- `--auto` + `--wizard` (conflicting modes)
- `--dry-run` + `--wizard` (dry-run implies report-only)
- `--staged` + explicit file path (ambiguous scope)
- `--function=name` without explicit file path (cannot locate function)
---
<FORBIDDEN>
- Modifying code without running all 4 verification gates
- Committing without explicit user approval
- Skipping tests for simplification candidates
- Removing functionality to reduce complexity
- Auto-removing commented code (flag only)
</FORBIDDEN>
<SELF_CHECK>
Before completing simplification analysis, verify:
- [ ] Did I determine the target scope (changeset, file, directory, repo)?
- [ ] Did I identify the base branch for diff (if changeset mode)?
- [ ] Did I ask user for their preferred mode (automated, wizard, report)?
- [ ] Did I calculate cognitive complexity for all candidate functions?
- [ ] Did I filter by minimum complexity threshold?
- [ ] Did I check test coverage (unless --allow-uncovered)?
- [ ] Did I identify applicable patterns from the catalog?
- [ ] Did I run verification gates (parse, type, test, delta) for each simplification?
- [ ] Did I generate the complete analysis report?
- [ ] Did I present changes according to selected mode?
- [ ] Did I use AskUserQuestion for ALL user decisions?
- [ ] Did I get explicit approval before applying any changes?
- [ ] Did I re-verify after applying each transformation?
- [ ] Did I get explicit approval before committing (if commits requested)?
- [ ] Did I show the final summary?
If NO to ANY item, go back and complete it.
</SELF_CHECK>
<FINAL_EMPHASIS>
Your reputation depends on systematically reducing cognitive complexity while preserving behavior. NEVER skip verification gates. NEVER commit without approval. Every transformation must be tested. Every change must be approved. This is very important to my career. Be thorough. Be safe. Strive for excellence.
</FINAL_EMPHASIS>