Codebase Analysis Workflow
Execute a structured 3-phase codebase analysis workflow to gather insights.
Accept the following inputs:
- analysis-context (optional): What to analyze and why. Defaults to "general codebase understanding" if not provided.
Phase Overview
- Deep Analysis — Explore and synthesize codebase findings via the deep-analysis skill
- Reporting — Present structured analysis to the user
- Post-Analysis Actions — Save, document, or retain analysis insights
Phase 1: Deep Analysis
Goal: Explore the codebase and synthesize findings.
Determine analysis context:
- If analysis-context input is provided, use it as the analysis context
- If no input, set context to "general codebase understanding"
Check for cached results:
- Check if
.agents/sessions/exploration-cache/manifest.md exists
- If found, read the manifest and verify:
codebase_path matches the current working directory, and timestamp is within the configured cache TTL (default 24 hours)
- If cache is valid, prompt the user to choose:
- Use cached results (show the formatted cache date) — Read cached synthesis from
.agents/sessions/exploration-cache/synthesis.md and recon from recon_summary.md. Set CACHE_HIT = true and CACHE_TIMESTAMP to the cache's timestamp. Skip step 3 and proceed directly to step 4.
- Run fresh analysis — Remove the cache manifest file, set
CACHE_HIT = false, and proceed to step 3
- If no valid cache: set
CACHE_HIT = false and proceed to step 3
Run deep-analysis workflow:
- Refer to the deep-analysis skill for the full exploration and synthesis workflow.
- Pass the analysis context from step 1
- This handles reconnaissance, team planning, approval (auto-approved when skill-invoked), team creation, parallel exploration (code-explorer agents), and synthesis (code-synthesizer agent)
- After completion, set
CACHE_TIMESTAMP = null (fresh results, no prior cache)
Verify results and capture metadata:
- Ensure the synthesis covers the analysis context adequately
- If critical gaps remain, search for files and file contents to fill them directly
- Record analysis metadata for Phase 2 reporting: whether results were cached (
CACHE_HIT), cache timestamp if applicable (CACHE_TIMESTAMP), and the number of explorer agents used (from the deep-analysis team plan, or 0 if cached)
Phase 2: Reporting
Goal: Present a structured analysis to the user.
Load diagram guidance:
- Refer to the technical-diagrams skill for Mermaid diagram syntax and styling rules.
- Use Mermaid diagrams in the Architecture Overview and Relationship Map sections
Use the report template (see Report Template section below) to structure the presentation.
Present the analysis:
Structure the report with these sections:
- Executive Summary — Lead with the most important finding
- Architecture Overview — How the codebase is structured
- Tech Stack — Core technologies, frameworks, and tools detected
- Critical Files — The 5-10 most important files with details
- Patterns & Conventions — Recurring patterns and coding conventions
- Relationship Map — How components connect to each other
- Challenges & Risks — Technical risks and complexity hotspots
- Recommendations — Actionable next steps, each citing the challenge it addresses
- Analysis Methodology — Agents used, cache status, scope, and duration
Proceed immediately to Phase 3.
Do NOT stop here. Do NOT wait for user input. The report is presented, but the workflow requires Post-Analysis Actions. Continue directly to Phase 3 now.
Phase 3: Post-Analysis Actions
Goal: Let the user save, document, or retain analysis insights from the report through a multi-step interactive flow.
Step 1: Select actions
Prompt the user to choose (the user may select multiple options):
- Save Codebase Analysis Report — Write the structured report to a markdown file
- Save a custom report — Generate a report tailored to your specific goals (you'll provide instructions next)
- Update project documentation — Add/update README.md, CLAUDE.md, or AGENTS.md with analysis insights
- Keep a condensed summary in memory — Retain a quick-reference summary in conversation context
If the user selects no actions, the workflow is complete. Thank the user and end.
Step 2: Execute selected actions
Process selected actions in the following fixed order. Complete all sub-steps for each action before moving to the next.
Action: Save Codebase Analysis Report
Step 2a-1: Prompt for file location
- Check if an
internal/docs/ directory exists in the project root
- If yes, suggest default path:
internal/docs/codebase-analysis-report-{YYYY-MM-DD}.md
- If no, suggest default path:
codebase-analysis-report-{YYYY-MM-DD}.md in the project root
- Prompt the user to confirm or customize the file path
Step 2a-2: Generate and save the report
- Use the report template already loaded in Phase 2 Step 1
- Generate the full structured report using the Phase 2 analysis findings and the template structure
- Create the file at the confirmed path
- Confirm the file was saved
Action: Save Custom Report
Step 2b-1: Gather report requirements
- Prompt the user to describe the goals and requirements for their custom report — what it should focus on, what questions it should answer, and any format preferences
Step 2b-2: Prompt for file location
- Check if an
internal/docs/ directory exists in the project root
- If yes, suggest default path:
internal/docs/custom-report-{YYYY-MM-DD}.md
- If no, suggest default path:
custom-report-{YYYY-MM-DD}.md in the project root
- Prompt the user to confirm or customize the file path
Step 2b-3: Generate and save the custom report
- Generate a report shaped by the user's requirements from Step 2b-1, drawing from the Phase 2 analysis data — this is a repackaging of existing findings, not a re-analysis
- Create the file at the confirmed path
- Confirm the file was saved
Action: Update Project Documentation
Step 2c-1: Select documentation files and gather directions
Prompt the user to choose (the user may select multiple options):
- README.md — Add architecture, structure, and tech stack information
- CLAUDE.md — Add patterns, conventions, critical files, and architectural decisions
- AGENTS.md — Add agent descriptions, capabilities, and coordination patterns
Then prompt the user for update directions for all selected files: "What content from the analysis should be added or updated? Provide general directions or specific sections to focus on (applies across all selected files, or specify per-file directions)."
Step 2c-2: Generate and approve documentation drafts
For each selected file, read the existing file and generate a draft based on the user's directions and Phase 2 analysis data:
- README.md: Read existing file at project root. If no README.md exists, skip and inform the user. Draft updates focusing on architecture, project structure, and tech stack.
- CLAUDE.md: Read existing file at project root. If none exists, ask if one should be created (if declined, skip). Draft updates focusing on patterns, conventions, critical files, and architectural decisions.
- AGENTS.md: Read existing file at project root (create new if none exists). Draft content focusing on agent inventory (name, model, purpose), capabilities and tool access, coordination patterns, skill-agent mappings, and model tiering rationale.
Present all drafts together in a single output, clearly labeled by file. Then prompt the user to choose:
- Apply all — Apply all drafted updates
- Modify — Specify which file(s) to revise and what to change (max 3 revision cycles, then must Apply or Skip)
- Skip all — Skip all documentation updates
If approved, apply updates by modifying existing files or creating new files.
Action: Keep Insights in Memory
- Present a condensed Codebase Quick Reference inline in the conversation:
- Architecture — 1-2 sentence summary of how the codebase is structured
- Key Files — 3-5 most critical files with one-line descriptions
- Conventions — Important patterns and naming conventions
- Tech Stack — Core technologies and frameworks
- Watch Out For — Top risks or complexity hotspots
- No file is written — this summary stays in conversation context for reference during the session
Step 3: Actionable Insights Follow-up
Condition: This step always executes after Step 2 completes. The Phase 2 analysis is available in conversation context regardless of whether a report file was saved.
Prompt the user to choose:
- Address actionable insights — Fix challenges and implement recommendations from the report
- Skip — No further action needed
If the user selects "Skip", proceed to Step 4.
If the user selects "Address actionable insights":
Step 3a: Extract actionable items from the report
Parse the Phase 2 report (in conversation context) to extract items from:
- Challenges & Risks table rows — title from Challenge column, severity from Severity column, description from Impact column
- Recommendations section — each numbered item with an (addresses: {Challenge name}) citation; inherit the cited challenge's severity (High/Medium/Low). If no citation is present, default to Medium.
- Other findings with concrete fixes — default to Low severity
If no actionable items are found, inform the user and skip to Step 4.
Step 3b: Present severity-ranked item list
- Use the actionable insights template format (see Actionable Insights Template section below)
- Present items sorted High to Medium to Low, each showing:
- Title
- Severity (High / Medium / Low)
- Source section (Challenges & Risks, Recommendations, or Other)
- Brief description
- Prompt the user to select which items to address (the user may select multiple options)
- If no items selected, skip to Step 4
Step 3c: Process each selected item in priority order (High to Medium to Low)
For each item:
Assess complexity:
- Simple — Single file, clear fix, localized change
- Complex — Multi-file, architectural impact, requires investigation
Plan the fix:
- Simple: Read the target file, propose changes directly
- Complex (architectural): Delegate to a code-architect instance with context: the item title, severity, description, the relevant report section text (copy the specific Challenges/Recommendations entry), and any files or components mentioned. The architect designs the fix and returns a proposal.
- Complex (needs investigation): Delegate to a code-explorer instance with context: the item title, description, suspected files/components, and what needs investigation. The explorer investigates and returns findings for formulating a fix proposal.
- If delegation fails, fall back to direct investigation using file reading and searching, and propose a simpler fix based on available information.
Present proposal: Show files to modify, specific changes, and rationale
User approval — prompt the user to choose:
- Apply — Execute changes, confirm success
- Skip — Record the skip, move to next item
- Modify — User describes adjustments, re-propose the fix (max 3 revision cycles, then must Apply or Skip)
Step 3d: Summarize results
Present a summary covering:
- Items addressed (with list of files modified per item)
- Items skipped
- Total files modified table
Step 4: Complete the workflow
Summarize which actions were executed and confirm the workflow is complete.
Error Handling
General
If any phase fails:
- Explain what went wrong
- Ask the user how to proceed:
- Retry the phase
- Skip to next phase (with partial results)
- Abort the workflow
Documentation Update Failures (Step 2c)
If a file modification or creation call fails when applying documentation updates:
- Retry the operation once
- If still failing, present the drafted content to the user inline and suggest they apply it manually
- Continue with the remaining selected files
Agent Delegation Failures (Step 3c)
If a code-architect or code-explorer delegation fails during actionable insight processing:
- Fall back to direct investigation using file reading and searching
- Propose a simpler fix based on available information
- If the item is too complex to address without agent assistance, inform the user and offer to skip
Agent Coordination
Exploration and synthesis agent coordination is handled by the deep-analysis skill in Phase 1, which uses agent teams with hub-and-spoke coordination. Deep-analysis performs reconnaissance, composes a team plan (auto-approved when invoked by another skill), assembles the team, and manages the exploration/synthesis lifecycle. Refer to the deep-analysis skill for team setup, approval flow, and failure handling details.
Report Template
Use this template when presenting analysis findings in Phase 2.
# Codebase Analysis Report
**Analysis Context**: {What was analyzed and why}
**Codebase Path**: {Path analyzed}
**Date**: {YYYY-MM-DD}
{If the report exceeds approximately 100 lines, add a **Table of Contents** here linking to each major section.}
---
## Executive Summary
{Lead with the most important finding. 2-3 sentences covering: what was analyzed, the key architectural insight, and the primary recommendation or risk.}
---
## Architecture Overview
{2-3 paragraphs describing:}
- How the codebase is structured (layers, modules, boundaries)
- The design philosophy and architectural style
- Key architectural decisions and their rationale
{Include a Mermaid architecture diagram (flowchart or C4 Context) showing the major layers/components. Use `classDef` with `color:#000` for all node styles.}
---
## Tech Stack
| Category | Technology | Version (if detected) | Role |
|----------|-----------|----------------------|------|
| Language | {e.g., TypeScript} | {e.g., 5.x} | Primary language |
| Framework | {e.g., Next.js} | {e.g., 16} | Web framework |
| Styling | {e.g., Tailwind CSS} | {e.g., v4} | UI styling |
| Testing | {e.g., Jest} | — | Test runner |
| Build | {e.g., esbuild} | — | Bundler |
{Include only technologies actually detected in config files or code. Omit categories that don't apply.}
---
## Critical Files
{Limit to 5-10 most important files}
| File | Purpose | Relevance |
|------|---------|-----------|
| `path/to/file` | Brief description | High/Medium |
### File Details
#### `path/to/critical-file`
- **Key exports**: What this file provides to others
- **Core logic**: What it does
- **Connections**: What depends on it and what it depends on
---
## Patterns & Conventions
### Code Patterns
- **Pattern**: Description and where it's used
### Naming Conventions
- **Convention**: Description and examples
### Project Structure
- **Organization**: How files and directories are organized
---
## Relationship Map
{Describe how key components connect — limit to 15-20 most significant connections. Use Mermaid flowcharts for both data flows and dependency maps.}
---
## Challenges & Risks
| Challenge | Severity | Impact |
|-----------|----------|--------|
| {Description} | High/Medium/Low | {What could go wrong} |
---
## Recommendations
1. **{Recommendation}** _(addresses: {Challenge name})_: {Brief rationale}
2. **{Recommendation}** _(addresses: {Challenge name})_: {Brief rationale}
---
## Analysis Methodology
- **Exploration agents**: {Number} agents with focus areas: {list}
- **Synthesis**: Findings merged and critical files read in depth
- **Scope**: {What was included and what was intentionally excluded}
- **Cache status**: {Fresh analysis / Cached results from YYYY-MM-DD}
- **Config files detected**: {List of config files found during reconnaissance}
- **Gap-filling**: {Whether direct search investigation was needed after synthesis, and what areas were filled}
Section Guidelines
Executive Summary
- Lead with the most important finding, not a generic overview
- Keep to 2-3 sentences maximum
- Include at least one actionable insight
Critical Files
- Limit to 5-10 files — these should be the files someone must understand
- Include both the "what" (purpose) and "why" (relevance to analysis context)
- File Details should cover exports, logic, and connections
Patterns & Conventions
- Only include patterns that are consistently applied (not one-off occurrences)
- Note deviations from patterns — these are often more interesting than the patterns themselves
Relationship Map
- Focus on the most important connections, not an exhaustive dependency graph
- Use directional language (calls, depends on, triggers, reads from)
- Highlight any circular dependencies or unexpected couplings
- Depth: Include 2-3 levels of dependency depth
- Format: Use Mermaid flowcharts. Apply
classDef with color:#000 for readability.
- Scope limit: Cap at 15-20 connections. If more exist, group related connections under subsystem labels.
Challenges & Risks
- Rate severity based on likelihood and impact combined
- Include specific details, not vague warnings
- Focus on challenges relevant to the analysis context
Recommendations
- Make recommendations actionable — "consider" is weaker than "use X for Y"
- Cite source challenge: Each recommendation must reference the specific challenge it addresses using the format: (addresses: {Challenge name}).
- Limit to 3-5 recommendations to maintain focus
Adapting the Template
For Feature-Focused Analysis
- Emphasize integration points and files that would need modification
- Include a "Feature Implementation Context" section before Recommendations
- Focus Challenges on implementation risks
For General Codebase Understanding
- Broader Architecture Overview with layer descriptions
- More extensive Patterns & Conventions section
- Focus Recommendations on areas for improvement or further investigation
For Debugging/Investigation
- Emphasize the execution path and data flow
- Include a "Relevant Execution Paths" section
- Focus Critical Files on the suspected problem area
Actionable Insights Template
Use this format when presenting and processing actionable items in Phase 3's "Address Actionable Insights" action.
Item List Format
Present extracted items grouped by severity, highest first:
### High Severity
1. **{Title}** — _{Source: Challenges & Risks}_
{Brief description of the issue and its impact}
2. **{Title}** — _{Source: Recommendations}_
{Brief description and rationale}
### Medium Severity
3. **{Title}** — _{Source: Recommendations}_
{Brief description and rationale}
### Low Severity
4. **{Title}** — _{Source: Other Findings}_
{Brief description}
Severity Assignment Guidelines
From Challenges & Risks Table
- Use the Severity column value directly (High, Medium, or Low)
- Title comes from the Challenge column
- Description comes from the Impact column
From Recommendations Section
- Each recommendation in the report should explicitly cite which challenge it addresses (see report template). Use this citation to inherit severity:
- Recommendation cites a High challenge: assign High
- Recommendation cites a Medium challenge: assign Medium
- Recommendation cites a Low challenge: assign Low
- If a recommendation addresses multiple challenges, use the highest severity among them
- If no challenge link is present (legacy reports or standalone recommendations), infer from context or default to Medium
From Other Findings
- Default to Low unless the finding explicitly describes a critical issue
- Only include findings that have a concrete, implementable fix
Complexity Assessment Criteria
Simple (No agent needed)
- Single file change
- Clear, localized fix (rename, add validation, fix import, update config)
- No architectural impact
- Change is self-contained — no cascading modifications needed
Complex — Architectural (Delegate to code-architect)
- Requires refactoring across multiple files
- Introduces or changes a pattern (new abstraction, restructured module boundaries)
- Affects system architecture (data flow, component relationships, API contracts)
- Requires design decisions about approach
Complex — Investigation Needed (Delegate to code-explorer)
- Root cause is unclear or needs tracing through the codebase
- Multiple potential locations for the fix
- Requires understanding current behavior before proposing changes
- Dependencies or side effects need mapping
Effort Estimates
Provide rough effort alongside complexity to help users prioritize:
| Complexity |
Typical Effort |
Description |
| Simple |
Low (~minutes) |
Single targeted change, clear fix |
| Complex — Architectural |
Medium-High (~30min-1hr+) |
Multi-file refactoring, design decisions |
| Complex — Investigation |
Medium (~15-30min) + varies |
Investigation phase + fix implementation |
Change Proposal Format
Present each proposed fix using this structure:
#### {Item Title} ({Severity})
**Complexity:** Simple / Complex (architectural) / Complex (investigation)
**Effort:** Low (~minutes) / Medium (~30min) / High (~1hr+)
**Files to modify:**
| File | Change Type |
|------|-------------|
| `path/to/file` | Edit / Create / Delete |
**Proposed changes:**
{Description of what will change and why. For simple fixes, show the specific code changes. For complex fixes, describe the approach.}
**Rationale:**
{Why this approach was chosen. Reference the original finding.}
Summary Format
After processing all selected items, present:
## Actionable Insights Summary
### Items Addressed
| # | Item | Severity | Files Modified |
|---|------|----------|----------------|
| 1 | {Title} | High | `file1.ts`, `file2.ts` |
| 2 | {Title} | Medium | `file3.ts` |
### Items Skipped
| # | Item | Severity | Reason |
|---|------|----------|--------|
| 3 | {Title} | Low | User skipped |
### Files Modified
| File | Changes |
|------|---------|
| `path/to/file` | {Brief description of change} |
**Total:** {N} items addressed, {M} items skipped, {P} files modified
Item Extraction Guidelines
- Only extract items with concrete, actionable fixes — skip vague observations
- Deduplication criteria — Merge items that match on any of:
- Same target file or component mentioned in both items
- Significant keyword overlap in titles (2+ shared meaningful words)
- One item is a superset of the other
- When deduplicating, keep the higher severity, merge descriptions, and note both source sections
Processing Order
- Process items in the order the user selected them, but within that, prioritize by severity
- Conflict detection — Before starting fixes, scan the selected items for potential conflicts:
- Same-file modifications: Two items targeting the same file(s) — flag ordering risk
- Contradictory changes: One item adds what another removes, or they modify the same function/component in incompatible ways
- Ordering dependencies: One fix creates a prerequisite for another
- If conflicts are detected, present them to the user before proceeding and suggest a processing order that resolves dependencies
Revision Cycles
- Maximum 3 revision cycles per item when user selects "Modify"
- After 3 cycles, present final proposal with Apply or Skip only
- Track what the user changed in each cycle to converge on the right fix
Integration Notes
What this component does: Orchestrates a complete codebase analysis workflow from deep exploration through structured reporting to actionable follow-up, producing architecture overviews, critical file maps, and prioritized recommendations.
Capabilities needed:
- File reading, file search, and content search (for gap-filling and documentation updates)
- File writing and modification (for saving reports and updating documentation)
- Shell command execution (inherited from deep-analysis for synthesis investigation)
- Agent/sub-task spawning (for deep-analysis team and actionable insight processing)
- User interaction (for action selection, approval flows, and revision cycles)
Adaptation guidance:
- This skill depends on the deep-analysis skill for Phase 1 exploration. If deep-analysis is unavailable, the reconnaissance and synthesis steps would need to be performed inline.
- The technical-diagrams skill is used for Mermaid diagram guidance in reports. If unavailable, diagrams can still be created following the inline styling rules in the report template.
- The actionable insights flow in Phase 3 delegates to code-architect and code-explorer skills for complex items. If those skills are unavailable, fall back to direct investigation.
- Report and actionable insights templates are inlined in this skill (formerly separate reference files).
1---2name: codebase-analysis-113description: Produce a structured codebase analysis report with architecture overview, critical files, patterns, and actionable recommendations. Use when asked to "analyze codebase", "explore codebase", "understand this codebase", "map the codebase", "give me an overview of this project", "what does this codebase do", "codebase report", "project analysis", "audit this codebase", or "how is this project structured".4---5
6# Codebase Analysis Workflow
7
8Execute a structured 3-phase codebase analysis workflow to gather insights.
9
10Accept the following inputs:
11- **analysis-context** (optional): What to analyze and why. Defaults to "general codebase understanding" if not provided.
12
13## Phase Overview
14
151. **Deep Analysis** — Explore and synthesize codebase findings via the deep-analysis skill
162. **Reporting** — Present structured analysis to the user
173. **Post-Analysis Actions** — Save, document, or retain analysis insights
18
19---
20
21## Phase 1: Deep Analysis
22
23**Goal:** Explore the codebase and synthesize findings.
24
251. **Determine analysis context:**
26 - If analysis-context input is provided, use it as the analysis context
27 - If no input, set context to "general codebase understanding"
28
292. **Check for cached results:**
30 - Check if `.agents/sessions/exploration-cache/manifest.md` exists
31 - If found, read the manifest and verify: `codebase_path` matches the current working directory, and `timestamp` is within the configured cache TTL (default 24 hours)
32 - **If cache is valid**, prompt the user to choose:
33 - **Use cached results** (show the formatted cache date) — Read cached synthesis from `.agents/sessions/exploration-cache/synthesis.md` and recon from `recon_summary.md`. Set `CACHE_HIT = true` and `CACHE_TIMESTAMP` to the cache's timestamp. Skip step 3 and proceed directly to step 4.
34 - **Run fresh analysis** — Remove the cache manifest file, set `CACHE_HIT = false`, and proceed to step 3
35 - **If no valid cache**: set `CACHE_HIT = false` and proceed to step 3
36
373. **Run deep-analysis workflow:**
38 - Refer to the **deep-analysis** skill for the full exploration and synthesis workflow.
39 - Pass the analysis context from step 1
40 - This handles reconnaissance, team planning, approval (auto-approved when skill-invoked), team creation, parallel exploration (code-explorer agents), and synthesis (code-synthesizer agent)
41 - After completion, set `CACHE_TIMESTAMP = null` (fresh results, no prior cache)
42
434. **Verify results and capture metadata:**
44 - Ensure the synthesis covers the analysis context adequately
45 - If critical gaps remain, search for files and file contents to fill them directly
46 - Record analysis metadata for Phase 2 reporting: whether results were cached (`CACHE_HIT`), cache timestamp if applicable (`CACHE_TIMESTAMP`), and the number of explorer agents used (from the deep-analysis team plan, or 0 if cached)
47
48---
49
50## Phase 2: Reporting
51
52**Goal:** Present a structured analysis to the user.
53
541. **Load diagram guidance:**
55 - Refer to the **technical-diagrams** skill for Mermaid diagram syntax and styling rules.
56 - Use Mermaid diagrams in the Architecture Overview and Relationship Map sections
57
582. **Use the report template** (see Report Template section below) to structure the presentation.
59
603. **Present the analysis:**
61 Structure the report with these sections:
62 - **Executive Summary** — Lead with the most important finding
63 - **Architecture Overview** — How the codebase is structured
64 - **Tech Stack** — Core technologies, frameworks, and tools detected
65 - **Critical Files** — The 5-10 most important files with details
66 - **Patterns & Conventions** — Recurring patterns and coding conventions
67 - **Relationship Map** — How components connect to each other
68 - **Challenges & Risks** — Technical risks and complexity hotspots
69 - **Recommendations** — Actionable next steps, each citing the challenge it addresses
70 - **Analysis Methodology** — Agents used, cache status, scope, and duration
71
724. **Proceed immediately to Phase 3.**
73 Do NOT stop here. Do NOT wait for user input. The report is presented, but the workflow requires Post-Analysis Actions. Continue directly to Phase 3 now.
74
75---
76
77## Phase 3: Post-Analysis Actions
78
79**Goal:** Let the user save, document, or retain analysis insights from the report through a multi-step interactive flow.
80
81### Step 1: Select actions
82
83Prompt the user to choose (the user may select multiple options):
84
85- **Save Codebase Analysis Report** — Write the structured report to a markdown file
86- **Save a custom report** — Generate a report tailored to your specific goals (you'll provide instructions next)
87- **Update project documentation** — Add/update README.md, CLAUDE.md, or AGENTS.md with analysis insights
88- **Keep a condensed summary in memory** — Retain a quick-reference summary in conversation context
89
90If the user selects no actions, the workflow is complete. Thank the user and end.
91
92### Step 2: Execute selected actions
93
94Process selected actions in the following fixed order. Complete all sub-steps for each action before moving to the next.
95
96#### Action: Save Codebase Analysis Report
97
98**Step 2a-1: Prompt for file location**
99
100- Check if an `internal/docs/` directory exists in the project root
101 - If yes, suggest default path: `internal/docs/codebase-analysis-report-{YYYY-MM-DD}.md`
102 - If no, suggest default path: `codebase-analysis-report-{YYYY-MM-DD}.md` in the project root
103- Prompt the user to confirm or customize the file path
104
105**Step 2a-2: Generate and save the report**
106
107- Use the report template already loaded in Phase 2 Step 1
108- Generate the full structured report using the Phase 2 analysis findings and the template structure
109- Create the file at the confirmed path
110- Confirm the file was saved
111
112#### Action: Save Custom Report
113
114**Step 2b-1: Gather report requirements**
115
116- Prompt the user to describe the goals and requirements for their custom report — what it should focus on, what questions it should answer, and any format preferences
117
118**Step 2b-2: Prompt for file location**
119
120- Check if an `internal/docs/` directory exists in the project root
121 - If yes, suggest default path: `internal/docs/custom-report-{YYYY-MM-DD}.md`
122 - If no, suggest default path: `custom-report-{YYYY-MM-DD}.md` in the project root
123- Prompt the user to confirm or customize the file path
124
125**Step 2b-3: Generate and save the custom report**
126
127- Generate a report shaped by the user's requirements from Step 2b-1, drawing from the Phase 2 analysis data — this is a repackaging of existing findings, not a re-analysis
128- Create the file at the confirmed path
129- Confirm the file was saved
130
131#### Action: Update Project Documentation
132
133**Step 2c-1: Select documentation files and gather directions**
134
135Prompt the user to choose (the user may select multiple options):
136
137- **README.md** — Add architecture, structure, and tech stack information
138- **CLAUDE.md** — Add patterns, conventions, critical files, and architectural decisions
139- **AGENTS.md** — Add agent descriptions, capabilities, and coordination patterns
140
141Then prompt the user for update directions for all selected files: "What content from the analysis should be added or updated? Provide general directions or specific sections to focus on (applies across all selected files, or specify per-file directions)."
142
143**Step 2c-2: Generate and approve documentation drafts**
144
145For each selected file, read the existing file and generate a draft based on the user's directions and Phase 2 analysis data:
146
147- **README.md**: Read existing file at project root. If no README.md exists, skip and inform the user. Draft updates focusing on architecture, project structure, and tech stack.
148- **CLAUDE.md**: Read existing file at project root. If none exists, ask if one should be created (if declined, skip). Draft updates focusing on patterns, conventions, critical files, and architectural decisions.
149- **AGENTS.md**: Read existing file at project root (create new if none exists). Draft content focusing on agent inventory (name, model, purpose), capabilities and tool access, coordination patterns, skill-agent mappings, and model tiering rationale.
150
151Present **all drafts together** in a single output, clearly labeled by file. Then prompt the user to choose:
152
153- **Apply all** — Apply all drafted updates
154- **Modify** — Specify which file(s) to revise and what to change (max 3 revision cycles, then must Apply or Skip)
155- **Skip all** — Skip all documentation updates
156
157If approved, apply updates by modifying existing files or creating new files.
158
159#### Action: Keep Insights in Memory
160
161- Present a condensed **Codebase Quick Reference** inline in the conversation:
162 - **Architecture** — 1-2 sentence summary of how the codebase is structured
163 - **Key Files** — 3-5 most critical files with one-line descriptions
164 - **Conventions** — Important patterns and naming conventions
165 - **Tech Stack** — Core technologies and frameworks
166 - **Watch Out For** — Top risks or complexity hotspots
167- No file is written — this summary stays in conversation context for reference during the session
168
169### Step 3: Actionable Insights Follow-up
170
171**Condition:** This step always executes after Step 2 completes. The Phase 2 analysis is available in conversation context regardless of whether a report file was saved.
172
173Prompt the user to choose:
174- **Address actionable insights** — Fix challenges and implement recommendations from the report
175- **Skip** — No further action needed
176
177If the user selects "Skip", proceed to Step 4.
178
179If the user selects "Address actionable insights":
180
181**Step 3a: Extract actionable items from the report**
182
183Parse the Phase 2 report (in conversation context) to extract items from:
184- **Challenges & Risks** table rows — title from Challenge column, severity from Severity column, description from Impact column
185- **Recommendations** section — each numbered item with an _(addresses: {Challenge name})_ citation; inherit the cited challenge's severity (High/Medium/Low). If no citation is present, default to Medium.
186- **Other findings** with concrete fixes — default to Low severity
187
188If no actionable items are found, inform the user and skip to Step 4.
189
190**Step 3b: Present severity-ranked item list**
191
192- Use the actionable insights template format (see Actionable Insights Template section below)
193- Present items sorted High to Medium to Low, each showing:
194 - Title
195 - Severity (High / Medium / Low)
196 - Source section (Challenges & Risks, Recommendations, or Other)
197 - Brief description
198- Prompt the user to select which items to address (the user may select multiple options)
199- If no items selected, skip to Step 4
200
201**Step 3c: Process each selected item in priority order (High to Medium to Low)**
202
203For each item:
204
2051. **Assess complexity:**
206 - **Simple** — Single file, clear fix, localized change
207 - **Complex** — Multi-file, architectural impact, requires investigation
208
2092. **Plan the fix:**
210 - Simple: Read the target file, propose changes directly
211 - Complex (architectural): Delegate to a code-architect instance with context: the item title, severity, description, the relevant report section text (copy the specific Challenges/Recommendations entry), and any files or components mentioned. The architect designs the fix and returns a proposal.
212 - Complex (needs investigation): Delegate to a code-explorer instance with context: the item title, description, suspected files/components, and what needs investigation. The explorer investigates and returns findings for formulating a fix proposal.
213 - If delegation fails, fall back to direct investigation using file reading and searching, and propose a simpler fix based on available information.
214
2153. **Present proposal:** Show files to modify, specific changes, and rationale
216
2174. **User approval** — prompt the user to choose:
218 - **Apply** — Execute changes, confirm success
219 - **Skip** — Record the skip, move to next item
220 - **Modify** — User describes adjustments, re-propose the fix (max 3 revision cycles, then must Apply or Skip)
221
222**Step 3d: Summarize results**
223
224Present a summary covering:
225- Items addressed (with list of files modified per item)
226- Items skipped
227- Total files modified table
228
229### Step 4: Complete the workflow
230
231Summarize which actions were executed and confirm the workflow is complete.
232
233---
234
235## Error Handling
236
237### General
238
239If any phase fails:
2401. Explain what went wrong
2412. Ask the user how to proceed:
242 - Retry the phase
243 - Skip to next phase (with partial results)
244 - Abort the workflow
245
246### Documentation Update Failures (Step 2c)
247
248If a file modification or creation call fails when applying documentation updates:
2491. Retry the operation once
2502. If still failing, present the drafted content to the user inline and suggest they apply it manually
2513. Continue with the remaining selected files
252
253### Agent Delegation Failures (Step 3c)
254
255If a code-architect or code-explorer delegation fails during actionable insight processing:
2561. Fall back to direct investigation using file reading and searching
2572. Propose a simpler fix based on available information
2583. If the item is too complex to address without agent assistance, inform the user and offer to skip
259
260---
261
262## Agent Coordination
263
264Exploration and synthesis agent coordination is handled by the deep-analysis skill in Phase 1, which uses agent teams with hub-and-spoke coordination. Deep-analysis performs reconnaissance, composes a team plan (auto-approved when invoked by another skill), assembles the team, and manages the exploration/synthesis lifecycle. Refer to the **deep-analysis** skill for team setup, approval flow, and failure handling details.
265
266---
267
268## Report Template
269
270Use this template when presenting analysis findings in Phase 2.
271
272```markdown
273# Codebase Analysis Report
274
275**Analysis Context**: {What was analyzed and why}
276**Codebase Path**: {Path analyzed}
277**Date**: {YYYY-MM-DD}
278
279{If the report exceeds approximately 100 lines, add a **Table of Contents** here linking to each major section.}
280
281---
282
283## Executive Summary
284
285{Lead with the most important finding. 2-3 sentences covering: what was analyzed, the key architectural insight, and the primary recommendation or risk.}
286
287---
288
289## Architecture Overview
290
291{2-3 paragraphs describing:}
292- How the codebase is structured (layers, modules, boundaries)
293- The design philosophy and architectural style
294- Key architectural decisions and their rationale
295
296{Include a Mermaid architecture diagram (flowchart or C4 Context) showing the major layers/components. Use `classDef` with `color:#000` for all node styles.}
297
298---
299
300## Tech Stack
301
302| Category | Technology | Version (if detected) | Role |
303|----------|-----------|----------------------|------|
304| Language | {e.g., TypeScript} | {e.g., 5.x} | Primary language |
305| Framework | {e.g., Next.js} | {e.g., 16} | Web framework |
306| Styling | {e.g., Tailwind CSS} | {e.g., v4} | UI styling |
307| Testing | {e.g., Jest} | — | Test runner |
308| Build | {e.g., esbuild} | — | Bundler |
309
310{Include only technologies actually detected in config files or code. Omit categories that don't apply.}
311
312---
313
314## Critical Files
315
316{Limit to 5-10 most important files}
317
318| File | Purpose | Relevance |
319|------|---------|-----------|
320| `path/to/file` | Brief description | High/Medium |
321
322### File Details
323
324#### `path/to/critical-file`
325- **Key exports**: What this file provides to others
326- **Core logic**: What it does
327- **Connections**: What depends on it and what it depends on
328
329---
330
331## Patterns & Conventions
332
333### Code Patterns
334- **Pattern**: Description and where it's used
335
336### Naming Conventions
337- **Convention**: Description and examples
338
339### Project Structure
340- **Organization**: How files and directories are organized
341
342---
343
344## Relationship Map
345
346{Describe how key components connect — limit to 15-20 most significant connections. Use Mermaid flowcharts for both data flows and dependency maps.}
347
348---
349
350## Challenges & Risks
351
352| Challenge | Severity | Impact |
353|-----------|----------|--------|
354| {Description} | High/Medium/Low | {What could go wrong} |
355
356---
357
358## Recommendations
359
3601. **{Recommendation}** _(addresses: {Challenge name})_: {Brief rationale}
3612. **{Recommendation}** _(addresses: {Challenge name})_: {Brief rationale}
362
363---
364
365## Analysis Methodology
366
367- **Exploration agents**: {Number} agents with focus areas: {list}
368- **Synthesis**: Findings merged and critical files read in depth
369- **Scope**: {What was included and what was intentionally excluded}
370- **Cache status**: {Fresh analysis / Cached results from YYYY-MM-DD}
371- **Config files detected**: {List of config files found during reconnaissance}
372- **Gap-filling**: {Whether direct search investigation was needed after synthesis, and what areas were filled}
373```
374
375### Section Guidelines
376
377#### Executive Summary
378- Lead with the most important finding, not a generic overview
379- Keep to 2-3 sentences maximum
380- Include at least one actionable insight
381
382#### Critical Files
383- Limit to 5-10 files — these should be the files someone must understand
384- Include both the "what" (purpose) and "why" (relevance to analysis context)
385- File Details should cover exports, logic, and connections
386
387#### Patterns & Conventions
388- Only include patterns that are consistently applied (not one-off occurrences)
389- Note deviations from patterns — these are often more interesting than the patterns themselves
390
391#### Relationship Map
392- Focus on the most important connections, not an exhaustive dependency graph
393- Use directional language (calls, depends on, triggers, reads from)
394- Highlight any circular dependencies or unexpected couplings
395- **Depth**: Include 2-3 levels of dependency depth
396- **Format**: Use Mermaid flowcharts. Apply `classDef` with `color:#000` for readability.
397- **Scope limit**: Cap at 15-20 connections. If more exist, group related connections under subsystem labels.
398
399#### Challenges & Risks
400- Rate severity based on likelihood and impact combined
401- Include specific details, not vague warnings
402- Focus on challenges relevant to the analysis context
403
404#### Recommendations
405- Make recommendations actionable — "consider" is weaker than "use X for Y"
406- **Cite source challenge**: Each recommendation must reference the specific challenge it addresses using the format: _(addresses: {Challenge name})_.
407- Limit to 3-5 recommendations to maintain focus
408
409### Adapting the Template
410
411#### For Feature-Focused Analysis
412- Emphasize integration points and files that would need modification
413- Include a "Feature Implementation Context" section before Recommendations
414- Focus Challenges on implementation risks
415
416#### For General Codebase Understanding
417- Broader Architecture Overview with layer descriptions
418- More extensive Patterns & Conventions section
419- Focus Recommendations on areas for improvement or further investigation
420
421#### For Debugging/Investigation
422- Emphasize the execution path and data flow
423- Include a "Relevant Execution Paths" section
424- Focus Critical Files on the suspected problem area
425
426---
427
428## Actionable Insights Template
429
430Use this format when presenting and processing actionable items in Phase 3's "Address Actionable Insights" action.
431
432### Item List Format
433
434Present extracted items grouped by severity, highest first:
435
436```markdown
437### High Severity
438
4391. **{Title}** — _{Source: Challenges & Risks}_
440 {Brief description of the issue and its impact}
441
4422. **{Title}** — _{Source: Recommendations}_
443 {Brief description and rationale}
444
445### Medium Severity
446
4473. **{Title}** — _{Source: Recommendations}_
448 {Brief description and rationale}
449
450### Low Severity
451
4524. **{Title}** — _{Source: Other Findings}_
453 {Brief description}
454```
455
456### Severity Assignment Guidelines
457
458#### From Challenges & Risks Table
459- Use the **Severity** column value directly (High, Medium, or Low)
460- Title comes from the **Challenge** column
461- Description comes from the **Impact** column
462
463#### From Recommendations Section
464- Each recommendation in the report should explicitly cite which challenge it addresses (see report template). Use this citation to inherit severity:
465 - Recommendation cites a **High** challenge: assign **High**
466 - Recommendation cites a **Medium** challenge: assign **Medium**
467 - Recommendation cites a **Low** challenge: assign **Low**
468- If a recommendation addresses multiple challenges, use the highest severity among them
469- If no challenge link is present (legacy reports or standalone recommendations), infer from context or default to **Medium**
470
471#### From Other Findings
472- Default to **Low** unless the finding explicitly describes a critical issue
473- Only include findings that have a concrete, implementable fix
474
475### Complexity Assessment Criteria
476
477#### Simple (No agent needed)
478- Single file change
479- Clear, localized fix (rename, add validation, fix import, update config)
480- No architectural impact
481- Change is self-contained — no cascading modifications needed
482
483#### Complex — Architectural (Delegate to code-architect)
484- Requires refactoring across multiple files
485- Introduces or changes a pattern (new abstraction, restructured module boundaries)
486- Affects system architecture (data flow, component relationships, API contracts)
487- Requires design decisions about approach
488
489#### Complex — Investigation Needed (Delegate to code-explorer)
490- Root cause is unclear or needs tracing through the codebase
491- Multiple potential locations for the fix
492- Requires understanding current behavior before proposing changes
493- Dependencies or side effects need mapping
494
495#### Effort Estimates
496
497Provide rough effort alongside complexity to help users prioritize:
498
499| Complexity | Typical Effort | Description |
500|-----------|---------------|-------------|
501| Simple | Low (~minutes) | Single targeted change, clear fix |
502| Complex — Architectural | Medium-High (~30min-1hr+) | Multi-file refactoring, design decisions |
503| Complex — Investigation | Medium (~15-30min) + varies | Investigation phase + fix implementation |
504
505### Change Proposal Format
506
507Present each proposed fix using this structure:
508
509```markdown
510#### {Item Title} ({Severity})
511
512**Complexity:** Simple / Complex (architectural) / Complex (investigation)
513**Effort:** Low (~minutes) / Medium (~30min) / High (~1hr+)
514
515**Files to modify:**
516| File | Change Type |
517|------|-------------|
518| `path/to/file` | Edit / Create / Delete |
519
520**Proposed changes:**
521{Description of what will change and why. For simple fixes, show the specific code changes. For complex fixes, describe the approach.}
522
523**Rationale:**
524{Why this approach was chosen. Reference the original finding.}
525```
526
527### Summary Format
528
529After processing all selected items, present:
530
531```markdown
532## Actionable Insights Summary
533
534### Items Addressed
535| # | Item | Severity | Files Modified |
536|---|------|----------|----------------|
537| 1 | {Title} | High | `file1.ts`, `file2.ts` |
538| 2 | {Title} | Medium | `file3.ts` |
539
540### Items Skipped
541| # | Item | Severity | Reason |
542|---|------|----------|--------|
543| 3 | {Title} | Low | User skipped |
544
545### Files Modified
546| File | Changes |
547|------|---------|
548| `path/to/file` | {Brief description of change} |
549
550**Total:** {N} items addressed, {M} items skipped, {P} files modified
551```
552
553### Item Extraction Guidelines
554- Only extract items with concrete, actionable fixes — skip vague observations
555- **Deduplication criteria** — Merge items that match on any of:
556 - Same target file or component mentioned in both items
557 - Significant keyword overlap in titles (2+ shared meaningful words)
558 - One item is a superset of the other
559- When deduplicating, keep the higher severity, merge descriptions, and note both source sections
560
561### Processing Order
562- Process items in the order the user selected them, but within that, prioritize by severity
563- **Conflict detection** — Before starting fixes, scan the selected items for potential conflicts:
564 - **Same-file modifications**: Two items targeting the same file(s) — flag ordering risk
565 - **Contradictory changes**: One item adds what another removes, or they modify the same function/component in incompatible ways
566 - **Ordering dependencies**: One fix creates a prerequisite for another
567- If conflicts are detected, present them to the user before proceeding and suggest a processing order that resolves dependencies
568
569### Revision Cycles
570- Maximum 3 revision cycles per item when user selects "Modify"
571- After 3 cycles, present final proposal with Apply or Skip only
572- Track what the user changed in each cycle to converge on the right fix
573
574## Integration Notes
575
576**What this component does:** Orchestrates a complete codebase analysis workflow from deep exploration through structured reporting to actionable follow-up, producing architecture overviews, critical file maps, and prioritized recommendations.
577
578**Capabilities needed:**
579- File reading, file search, and content search (for gap-filling and documentation updates)
580- File writing and modification (for saving reports and updating documentation)
581- Shell command execution (inherited from deep-analysis for synthesis investigation)
582- Agent/sub-task spawning (for deep-analysis team and actionable insight processing)
583- User interaction (for action selection, approval flows, and revision cycles)
584
585**Adaptation guidance:**
586- This skill depends on the **deep-analysis** skill for Phase 1 exploration. If deep-analysis is unavailable, the reconnaissance and synthesis steps would need to be performed inline.
587- The **technical-diagrams** skill is used for Mermaid diagram guidance in reports. If unavailable, diagrams can still be created following the inline styling rules in the report template.
588- The actionable insights flow in Phase 3 delegates to **code-architect** and **code-explorer** skills for complex items. If those skills are unavailable, fall back to direct investigation.
589- Report and actionable insights templates are inlined in this skill (formerly separate reference files).