Code Audit Skill
This skill guides a structured, bottom-up code audit process that produces clear documentation with PlantUML diagrams.
Quick Reference
| Phase |
Action |
| 0 |
Initialize or resume audit |
| 1 |
Define scope (boundaries, aspects) |
| 2 |
Analyze components bottom-up |
| 3 |
Synthesize findings into docs/diagrams |
| 4 |
Human review and finalization |
Invocation
All audits are stored in code-audits/ relative to the current working directory.
Directory naming: code-audits/<system-title>-YYMMDD/
- Example:
code-audits/redemption-service-250106/
When invoked:
- Check
code-audits/ for existing audits with state.json
- If found, list them and offer to resume
- If starting fresh, ask for a short system title (kebab-case), then create directory
Output Directory Structure
<audit-dir>/
├── state.json # Tracks progress for resumption
├── index.md # Main audit index (created in Phase 3)
├── boundaries.md # Scope definition (created in Phase 1)
├── entry-points.md # System entry points (created in Phase 3)
├── techdebt.md # TODOs and technical debt (created in Phase 3)
├── components/ # Per-file summaries (created in Phase 2)
├── aspects/ # Cross-cutting concerns (created in Phase 3)
├── diagrams/ # PlantUML source files (created in Phase 3)
└── generated/ # Post-processed with SVGs (created in Phase 4)
State File Format
{
"version": 1,
"title": "redemption-service",
"phase": "scoping|discovery|synthesis|review|complete",
"boundaries": {
"directories": ["app/services/**"],
"files": [],
"excludes": ["**/*_test.rb", "**/*.spec.ts"]
},
"aspects": ["error-handling", "retry-patterns", "execution-contexts", "authorization"],
"components": {
"app/services/foo.rb": {
"status": "pending|in_progress|complete",
"summary_file": "components/app-services-foo.md"
}
},
"checkpoint_interval": 5,
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z"
}
Required Focus Areas
Every audit MUST document these cross-cutting concerns:
- Error Handling - How errors are caught, propagated, logged, and recovered from
- Retry Patterns - Any retry logic, backoff strategies, idempotency handling
- Execution Contexts - How code is invoked (web request, background job, scheduler, CLI, etc.)
- Authorization - Access control, permission checks, authentication requirements
- Testing Patterns - Test coverage approach, test types used, mocking strategies, what's tested vs. not
- Database Patterns - Transactions, queries, migrations, connection management, N+1 risks
- Configuration & Secrets - Environment variables, feature flags, secrets management, config loading
- Logging & Observability - Log levels, structured logging, tracing, metrics, health checks
- Concurrency & Thread Safety - Locks, async patterns, race condition risks, thread pools
- External Integrations - API clients, webhooks, third-party services, failure handling
Phase Workflow
See workflow.md for detailed instructions on each phase.
Use subagents/tasks for individual, isolated task execution to maintain efficient context.
Phase 0: Initialize/Resume
Check for existing audits in code-audits/:
- Look for directories containing
state.json
- If found, list them with their phase and progress
- Offer to resume any incomplete audit
If resuming:
- Read and parse
state.json
- Jump to the current phase
If starting fresh:
Phase 1: Scoping
Use AskUserQuestion to gather:
Boundaries: Which directories/files to include
- Accept glob patterns (e.g.,
app/services/**/*.rb)
- Can be specific files or broad directories
Excludes: What to skip
- Tests, generated files, vendor code, etc.
Additional Aspects: Beyond the 4 required ones
- Performance patterns, caching, external integrations, etc.
Then:
- Write
boundaries.md documenting the scope
- Update
state.json with boundaries and aspects
- Set phase to "discovery"
Phase 2: Discovery (Bottom-Up)
- Enumerate all files matching boundaries (respecting excludes)
- Register each in
state.json with status "pending"
- Use
TodoWrite to track progress
For each file:
- Mark "in_progress" in state
- Read and analyze the code
- Create component summary in
components/ using the template
- Mark "complete" in state
- Every N files (checkpoint_interval), pause and ask user to verify
When all components complete:
- Update phase to "synthesis"
Phase 3: Synthesis
Read all component summaries
Identify patterns across components
Create aspect documentation:
aspects/error-handling.md
aspects/retry-patterns.md
aspects/execution-contexts.md
aspects/authorization.md
aspects/testing-patterns.md
aspects/database-patterns.md
aspects/configuration-secrets.md
aspects/logging-observability.md
aspects/concurrency-thread-safety.md
aspects/external-integrations.md
- Plus any user-specified aspects
Create entry-points.md documenting:
- Where external requests enter the system (routes, endpoints, CLI)
- Background job entry points
- Scheduled task triggers
- Event/webhook handlers
- Recommended reading order for newcomers
Create techdebt.md consolidating:
- TODOs and FIXMEs found in code
- Deprecated patterns still in use
- Known issues and workarounds
- Suggested improvements from component analysis
Design PlantUML diagrams:
- Architecture overview (component relationships)
- Data flow diagrams (how data moves through system)
- Sequence diagrams (for key flows)
- State diagrams (where relevant)
Write index.md tying everything together
Update phase to "review"
Phase 4: Review
- Present audit summary to user
- Walk through each aspect
- Show diagram previews (describe what they show)
- Allow corrections/additions
- Run the render script automatically:
~/.claude/skills/audit/scripts/render-puml.sh <audit-dir>
- Mark phase as "complete"
Diagram Guidelines
Embedding in Markdown
Small diagrams can be embedded directly:
```plantuml
@startuml
Alice -> Bob: Hello
Bob -> Alice: Hi
@enduml
```
Separate Files
Larger diagrams go in diagrams/:
- Reference in markdown:

Supported Types
@startuml / @enduml - class, sequence, activity, component
@startmindmap / @endmindmap - hierarchical views
@startwbs / @endwbs - work breakdown structures
@startjson / @endjson - data structure visualization
Valid Colors
PlantUML only supports specific color names. Use these valid colors:
| Category |
Valid Colors |
| Basic |
Red, Green, Blue, Yellow, Orange, Purple, Pink, Cyan, Magenta, White, Black, Gray |
| Light |
LightBlue, LightGreen, LightYellow, LightGray, LightPink, LightCyan, LightCoral, LightSalmon |
| Purple variants |
Lavender, Plum, Violet, Orchid, MediumPurple, DarkViolet, Indigo, Thistle |
| Other |
Aqua, Beige, Coral, Crimson, Gold, Khaki, Lime, Maroon, Navy, Olive, Silver, Teal, Tomato |
Invalid colors to avoid: LightPurple, LightOrange, LightRed (use alternatives above)
You can also use hex codes: #E6E6FA (lavender), #DDA0DD (plum), #EE82EE (violet)
Templates
Use templates from templates/ directory for consistency:
templates/index.md - Main audit index
templates/component.md - Per-file component summary
templates/aspect.md - Cross-cutting concern documentation
templates/entry-points.md - System entry points documentation
templates/techdebt.md - Technical debt tracking
Render Script
The scripts/render-puml.sh script:
- Uses Docker (
plantuml/plantuml image)
- Converts
.puml files to SVG
- Processes markdown files to replace plantuml blocks/references with SVG
- Outputs to
generated/ directory
Usage:
~/.claude/skills/audit/scripts/render-puml.sh /path/to/audit
1---2name: code-audit3description: Perform a human-assisted code audit. Use when asked to audit, review architecture, document a codebase, or create technical documentation with diagrams.4---56# Code Audit Skill78This skill guides a structured, bottom-up code audit process that produces clear documentation with PlantUML diagrams.910## Quick Reference1112| Phase | Action |13|-------|--------|14| 0 | Initialize or resume audit |15| 1 | Define scope (boundaries, aspects) |16| 2 | Analyze components bottom-up |17| 3 | Synthesize findings into docs/diagrams |18| 4 | Human review and finalization |1920## Invocation2122All audits are stored in `code-audits/` relative to the current working directory.2324**Directory naming**: `code-audits/<system-title>-YYMMDD/`25- Example: `code-audits/redemption-service-250106/`2627When invoked:281. Check `code-audits/` for existing audits with `state.json`292. If found, list them and offer to resume303. If starting fresh, ask for a short system title (kebab-case), then create directory3132## Output Directory Structure3334```35<audit-dir>/36├── state.json # Tracks progress for resumption37├── index.md # Main audit index (created in Phase 3)38├── boundaries.md # Scope definition (created in Phase 1)39├── entry-points.md # System entry points (created in Phase 3)40├── techdebt.md # TODOs and technical debt (created in Phase 3)41├── components/ # Per-file summaries (created in Phase 2)42├── aspects/ # Cross-cutting concerns (created in Phase 3)43├── diagrams/ # PlantUML source files (created in Phase 3)44└── generated/ # Post-processed with SVGs (created in Phase 4)45```4647## State File Format4849```json50{51 "version": 1,52 "title": "redemption-service",53 "phase": "scoping|discovery|synthesis|review|complete",54 "boundaries": {55 "directories": ["app/services/**"],56 "files": [],57 "excludes": ["**/*_test.rb", "**/*.spec.ts"]58 },59 "aspects": ["error-handling", "retry-patterns", "execution-contexts", "authorization"],60 "components": {61 "app/services/foo.rb": {62 "status": "pending|in_progress|complete",63 "summary_file": "components/app-services-foo.md"64 }65 },66 "checkpoint_interval": 5,67 "created_at": "2024-01-01T00:00:00Z",68 "updated_at": "2024-01-01T00:00:00Z"69}70```7172## Required Focus Areas7374Every audit MUST document these cross-cutting concerns:75761. **Error Handling** - How errors are caught, propagated, logged, and recovered from772. **Retry Patterns** - Any retry logic, backoff strategies, idempotency handling783. **Execution Contexts** - How code is invoked (web request, background job, scheduler, CLI, etc.)794. **Authorization** - Access control, permission checks, authentication requirements805. **Testing Patterns** - Test coverage approach, test types used, mocking strategies, what's tested vs. not816. **Database Patterns** - Transactions, queries, migrations, connection management, N+1 risks827. **Configuration & Secrets** - Environment variables, feature flags, secrets management, config loading838. **Logging & Observability** - Log levels, structured logging, tracing, metrics, health checks849. **Concurrency & Thread Safety** - Locks, async patterns, race condition risks, thread pools8510. **External Integrations** - API clients, webhooks, third-party services, failure handling8687## Phase Workflow8889See `workflow.md` for detailed instructions on each phase. 90Use subagents/tasks for individual, isolated task execution to maintain efficient context.9192### Phase 0: Initialize/Resume93941. Check for existing audits in `code-audits/`:95 - Look for directories containing `state.json`96 - If found, list them with their phase and progress97 - Offer to resume any incomplete audit98992. If resuming:100 - Read and parse `state.json`101 - Jump to the current phase1021033. If starting fresh:104 - Ask for a short system title (kebab-case, e.g., "redemption-service")105 - Generate directory name: `code-audits/<title>-YYMMDD/`106 - Create directory structure:107 ```108 mkdir -p code-audits/<title>-YYMMDD/{components,aspects,diagrams,generated}109 ```110 - Initialize `state.json` with phase="scoping"111 - Proceed to Phase 1112113### Phase 1: Scoping114115Use `AskUserQuestion` to gather:1161171. **Boundaries**: Which directories/files to include118 - Accept glob patterns (e.g., `app/services/**/*.rb`)119 - Can be specific files or broad directories1201212. **Excludes**: What to skip122 - Tests, generated files, vendor code, etc.1231243. **Additional Aspects**: Beyond the 4 required ones125 - Performance patterns, caching, external integrations, etc.126127Then:128- Write `boundaries.md` documenting the scope129- Update `state.json` with boundaries and aspects130- Set phase to "discovery"131132### Phase 2: Discovery (Bottom-Up)1331341. Enumerate all files matching boundaries (respecting excludes)1352. Register each in `state.json` with status "pending"1363. Use `TodoWrite` to track progress137138For each file:1391. Mark "in_progress" in state1402. Read and analyze the code1413. Create component summary in `components/` using the template1424. Mark "complete" in state1435. Every N files (checkpoint_interval), pause and ask user to verify144145When all components complete:146- Update phase to "synthesis"147148### Phase 3: Synthesis1491501. Read all component summaries1512. Identify patterns across components1523. Create aspect documentation:153 - `aspects/error-handling.md`154 - `aspects/retry-patterns.md`155 - `aspects/execution-contexts.md`156 - `aspects/authorization.md`157 - `aspects/testing-patterns.md`158 - `aspects/database-patterns.md`159 - `aspects/configuration-secrets.md`160 - `aspects/logging-observability.md`161 - `aspects/concurrency-thread-safety.md`162 - `aspects/external-integrations.md`163 - Plus any user-specified aspects1641654. Create `entry-points.md` documenting:166 - Where external requests enter the system (routes, endpoints, CLI)167 - Background job entry points168 - Scheduled task triggers169 - Event/webhook handlers170 - Recommended reading order for newcomers1711725. Create `techdebt.md` consolidating:173 - TODOs and FIXMEs found in code174 - Deprecated patterns still in use175 - Known issues and workarounds176 - Suggested improvements from component analysis1771786. Design PlantUML diagrams:179 - Architecture overview (component relationships)180 - Data flow diagrams (how data moves through system)181 - Sequence diagrams (for key flows)182 - State diagrams (where relevant)1831847. Write `index.md` tying everything together1851868. Update phase to "review"187188### Phase 4: Review1891901. Present audit summary to user1912. Walk through each aspect1923. Show diagram previews (describe what they show)1934. Allow corrections/additions1945. Run the render script automatically:195 ```bash196 ~/.claude/skills/audit/scripts/render-puml.sh <audit-dir>197 ```1986. Mark phase as "complete"199200## Diagram Guidelines201202### Embedding in Markdown203204Small diagrams can be embedded directly:205206~~~markdown207```plantuml208@startuml209Alice -> Bob: Hello210Bob -> Alice: Hi211@enduml212```213~~~214215### Separate Files216217Larger diagrams go in `diagrams/`:218- Reference in markdown: ``219220### Supported Types221222- `@startuml` / `@enduml` - class, sequence, activity, component223- `@startmindmap` / `@endmindmap` - hierarchical views224- `@startwbs` / `@endwbs` - work breakdown structures225- `@startjson` / `@endjson` - data structure visualization226227### Valid Colors228229PlantUML only supports specific color names. Use these valid colors:230231| Category | Valid Colors |232|----------|--------------|233| Basic | Red, Green, Blue, Yellow, Orange, Purple, Pink, Cyan, Magenta, White, Black, Gray |234| Light | LightBlue, LightGreen, LightYellow, LightGray, LightPink, LightCyan, LightCoral, LightSalmon |235| Purple variants | Lavender, Plum, Violet, Orchid, MediumPurple, DarkViolet, Indigo, Thistle |236| Other | Aqua, Beige, Coral, Crimson, Gold, Khaki, Lime, Maroon, Navy, Olive, Silver, Teal, Tomato |237238**Invalid colors to avoid**: LightPurple, LightOrange, LightRed (use alternatives above)239240You can also use hex codes: `#E6E6FA` (lavender), `#DDA0DD` (plum), `#EE82EE` (violet)241242## Templates243244Use templates from `templates/` directory for consistency:245- `templates/index.md` - Main audit index246- `templates/component.md` - Per-file component summary247- `templates/aspect.md` - Cross-cutting concern documentation248- `templates/entry-points.md` - System entry points documentation249- `templates/techdebt.md` - Technical debt tracking250251## Render Script252253The `scripts/render-puml.sh` script:254- Uses Docker (`plantuml/plantuml` image)255- Converts `.puml` files to SVG256- Processes markdown files to replace plantuml blocks/references with SVG257- Outputs to `generated/` directory258259Usage:260```bash261~/.claude/skills/audit/scripts/render-puml.sh /path/to/audit262```