nav-simplify
Simplify and refine code for clarity, consistency, and maintainability while preserving all functionality. Focuses on recently modified code. Auto-invoke after implementation skills or on-demand.
What this skill does
# Navigator Code Simplification Skill
Simplify recently modified code for clarity, consistency, and maintainability while preserving exact functionality. Based on Anthropic's internal code-simplifier pattern.
## Core Principle
**Clarity over brevity. Functionality preserved absolutely.**
You are an expert code simplification specialist. Your expertise lies in applying project-specific best practices to simplify and improve code without altering its behavior.
## When to Invoke
**Auto-invoke after**:
- `backend-endpoint` skill completes
- `frontend-component` skill completes
- `database-migration` skill completes
- Any implementation task with code changes
**Manual invoke when user says**:
- "simplify this code"
- "review for clarity"
- "clean up recent changes"
- "refactor for readability"
- "simplify modified files"
**DO NOT invoke if**:
- No code was modified (docs-only changes)
- User explicitly says "skip simplification"
- Files are configuration only (JSON, YAML)
## Execution Steps
### Step 1: Identify Modified Code
**Option A: Git-based detection (preferred)**
```bash
# Get files modified in current session/commits
git diff --name-only HEAD~3 -- '*.ts' '*.tsx' '*.js' '*.jsx' '*.py' '*.go' '*.rs' 2>/dev/null || \
git diff --name-only --cached -- '*.ts' '*.tsx' '*.js' '*.jsx' '*.py' '*.go' '*.rs' 2>/dev/null || \
git diff --name-only -- '*.ts' '*.tsx' '*.js' '*.jsx' '*.py' '*.go' '*.rs'
```
**Option B: User-specified scope**
If user mentions specific files or directories, use those instead.
**Option C: Recent conversation context**
Analyze conversation for files that were written/edited in this session.
### Step 2: Load Simplification Configuration
Check for project-specific configuration:
```bash
if [ -f ".agent/.nav-config.json" ]; then
python3 -c "import json; c=json.load(open('.agent/.nav-config.json')); s=c.get('simplification',{}); print('auto_apply=' + str(s.get('auto_apply', False)).lower()); print('enabled=' + str(s.get('enabled', True)).lower())"
fi
```
Default configuration:
```json
{
"simplification": {
"enabled": true,
"trigger": "post-implementation",
"scope": "modified",
"model": "opus",
"skip_patterns": ["*.test.*", "*.spec.*", "*.md", "*.json", "*.yaml"],
"max_file_size": 50000,
"auto_apply": false,
"preserve_comments": true
}
}
```
#### Autonomous context check (CRITICAL)
After loading config, determine the invocation mode:
**Autonomous** (no human in the loop):
- Invoked from `nav-loop` VERIFY or COMPLETE phase
- Invoked from `nav-workflow` COMPLETE phase
- `NAV_AUTONOMOUS=1` env var set
- Triggered by autonomous-completion protocol
**Interactive** (human reviewing):
- Direct user request ("simplify this code")
- Mid-implementation manual invocation
**Decision matrix**:
| `auto_apply` | Context | Action |
|---|---|---|
| `true` | autonomous | Apply directly (Step 7 silent) |
| `true` | interactive | Apply directly, show summary |
| `false` | autonomous | **SKIP simplification entirely** — emit warning, return to caller. Never pause an autonomous flow waiting for approval. |
| `false` | interactive | Show diff per file, prompt for approval |
When skipping in autonomous-mode-with-false, emit:
```
⚠️ nav-simplify skipped: auto_apply=false but invoked autonomously.
To enable: set simplification.auto_apply=true in .agent/.nav-config.json
To disable cleanly: set simplification.enabled=false
```
### Step 3: Read Project Standards
**Load from CLAUDE.md** (required):
```
Read(file_path: "CLAUDE.md")
```
Extract coding standards:
- Preferred patterns (function vs arrow, explicit returns)
- Naming conventions
- Import ordering
- Error handling patterns
- Framework-specific guidelines
### Step 4: Analyze Each File
For each modified file, analyze for simplification opportunities:
**Complexity Indicators** (look for):
- Deep nesting (> 3 levels)
- Long functions (> 50 lines)
- Redundant code patterns
- Unclear variable names
- Nested ternary operators
- Over-abstraction
- Dead code
- Inconsistent patterns
**Run analysis**:
```bash
PLUGIN_DIR="${CLAUDE_PLUGIN_ROOT:-$HOME/.claude/plugins/cache/navigator-marketplace/navigator}"
[ -d "$PLUGIN_DIR" ] || PLUGIN_DIR="$HOME/.claude/plugins/marketplaces/navigator-marketplace"
# Pass --scoring roi to enable cost/benefit gating (default: complexity,
# legacy behavior).
python3 "$PLUGIN_DIR/skills/nav-simplify/scripts/code_analyzer.py" --file "$file" --scoring roi
```
### Step 4.5: ROI Gate (when scoring.mode = "roi")
If `simplification.scoring.mode` is `"roi"` in `.agent/.nav-config.json` (or `--scoring roi` was passed), the analyzer emits `benefit_score`, `cost_score`, `roi_score`, and a `gate_action` field. Honor the gate:
| `gate_action` | Behavior |
|---|---|
| `skip` | Skip this file. Emit a one-line reason with ROI math. Continue to next file. |
| `suggest` | Force interactive mode for this file regardless of `auto_apply`. Show diff + reason. |
| `apply` | Proceed with Step 5+ as normal (honor `auto_apply`). |
**Skip emission format**:
```
⏭️ {file} — low ROI (B={B}/10, C={C}/10, ROI={R}). Skipping.
{reason}
```
`{reason}` summarizes the dominant cost factor (e.g., "stable file (412 days), 8 import references" or "below skip_below threshold").
**Mode is opt-in.** When `scoring.mode == "complexity"` (default), Step 4.5 is a no-op and behavior is unchanged from prior versions.
### Step 5: Apply Simplification Rules
**Anthropic Simplification Rules**:
1. **Preserve Functionality**: Never change what the code does - only how it does it. All original features, outputs, and behaviors must remain intact.
2. **Apply Project Standards**: Follow CLAUDE.md coding standards:
- Use ES modules with proper import sorting
- Prefer `function` keyword over arrow functions (if project standard)
- Use explicit return type annotations
- Follow proper React/Vue component patterns
- Use proper error handling patterns
- Maintain consistent naming conventions
3. **Enhance Clarity**:
- Reduce unnecessary complexity and nesting
- Eliminate redundant code and abstractions
- Improve readability through clear names
- Consolidate related logic
- Remove unnecessary comments that describe obvious code
- **AVOID nested ternary operators** - use switch/if-else
- **Choose clarity over brevity** - explicit > compact
4. **Maintain Balance** - Avoid over-simplification that could:
- Reduce code clarity or maintainability
- Create overly clever solutions
- Combine too many concerns
- Remove helpful abstractions
- Prioritize "fewer lines" over readability
- Make code harder to debug or extend
### Step 6: Generate Simplified Code
For each file with improvements:
1. Read current file content
2. Apply simplification rules
3. Verify functionality unchanged (logic review)
4. Generate diff or replacement
**Output format**:
```
📝 Simplifying: {filename}
Changes:
- [Line X] Flattened nested ternary to switch statement
- [Line Y] Extracted repeated logic to helper function
- [Line Z] Renamed `x` to `userCount` for clarity
Diff:
```diff
- const result = a ? (b ? c : d) : e;
+ let result;
+ if (a && b) {
+ result = c;
+ } else if (a) {
+ result = d;
+ } else {
+ result = e;
+ }
```
```
### Step 7: Apply Changes
Branch on the decision matrix from Step 2:
**Autonomous + `auto_apply: false`**: skip entirely, emit the warning, return.
**Autonomous + `auto_apply: true`**: apply each change directly with `Edit()`. Do not prompt.
**Interactive + `auto_apply: true`**: apply directly, show summary at end.
**Interactive + `auto_apply: false`**: show diff per file, prompt `Apply this change? [y/N]`, apply only on yes.
When applying:
```
Edit(
file_path: "{file}",
old_string: "{original}",
new_string: "{simplified}"
)
```
### Step 8: Generate Summary
```
╔══════════════════════════════════════════════════════╗
║ ║
║ 🧹 Code SiRelated in Data & Analytics
clawarr-suite
IncludedComprehensive management for self-hosted media stacks (Sonarr, Radarr, Lidarr, Readarr, Prowlarr, Bazarr, Overseerr, Plex, Tautulli, SABnzbd, Recyclarr, Unpackerr, Notifiarr, Maintainerr, Kometa, FlareSolverr). Deep library exploration, analytics, dashboard generation, content management, request handling, subtitle management, indexer control, download monitoring, quality profile sync, library cleanup automation, notification routing, collection/overlay management, and media tracker integration (Trakt, Letterboxd, Simkl).
querying-soql
IncludedSOQL query generation, optimization, and analysis with 100-point scoring. Use this skill when the user needs SOQL/SOSL authoring or optimization: natural-language-to-query generation, relationship queries, aggregates, query-plan analysis, and performance or safety improvements for Salesforce queries. TRIGGER when: user writes, optimizes, or debugs SOQL/SOSL queries, touches .soql files, or asks about relationship queries, aggregates, or query performance. DO NOT TRIGGER when: bulk data operations (use handling-sf-data), Apex DML logic (use generating-apex), or report/dashboard queries.
app-store-optimization
IncludedApp Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklists, and tracking ranking changes.
habit-flow
IncludedAI-powered atomic habit tracker with natural language logging, streak tracking, smart reminders, and coaching. Use for creating habits, logging completions naturally ("I meditated today"), viewing progress, and getting personalized coaching.
app-store-optimization
IncludedApp Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklists, and tracking ranking changes.
visualizing-data
IncludedBuilds dashboards, reports, and data-driven interfaces requiring charts, graphs, or visual analytics. Provides systematic framework for selecting appropriate visualizations based on data characteristics and analytical purpose. Includes 24+ visualization types organized by purpose (trends, comparisons, distributions, relationships, flows, hierarchies, geospatial), accessibility patterns (WCAG 2.1 AA compliance), colorblind-safe palettes, and performance optimization strategies. Use when creating visualizations, choosing chart types, displaying data graphically, or designing data interfaces.