Codebase Analysis Workflow
Execute a structured 3-phase codebase analysis workflow to gather insights.
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 arguments are provided, use them as the analysis context
- If no arguments, 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:
- Load and follow the deep-analysis skill 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 content 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:
- Follow the technical-diagrams skill conventions
- Use Mermaid diagrams in the Architecture Overview and Relationship Map sections
Structure the report using the report template below
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.
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 (multiple selections allowed):
- 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
- Ask the user to confirm or customize the file path
Step 2a-2: Generate and save the report
- Generate the full structured report using the Phase 2 analysis findings and the report template
- Write the report to the confirmed path
- Confirm the file was saved
Action: Save Custom Report
Step 2b-1: Gather report requirements
- Ask 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
- Ask 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
- Write the report to 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 (multiple selections allowed):
- 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 ask: "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 using appropriate edit or write operations.
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 format documented 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 (multiple selections allowed)
- 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 worker with context: the item title, severity, description, the relevant report section text, and any files or components mentioned. The architect designs the fix and returns a proposal.
- Complex (needs investigation): Delegate to a code-explorer worker with context: the item title, description, suspected files/components, and what needs investigation. The explorer investigates and returns findings for you to formulate a fix proposal.
- If a 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 an edit or write operation 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. See that 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 |
{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 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.
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.
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}
### Medium Severity
2. **{Title}** -- _{Source: Recommendations}_
{Brief description and rationale}
### Low Severity
3. **{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 should cite which challenge it addresses. 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
- If no challenge link is present, 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
Complex -- Architectural (Delegate to code-architect)
- Requires refactoring across multiple files
- Introduces or changes a pattern
- Affects system architecture
- 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
| 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
#### {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.}
**Rationale:**
{Why this approach was chosen. Reference the original finding.}
Summary Format
## Actionable Insights Summary
### Items Addressed
| # | Item | Severity | Files Modified |
|---|------|----------|----------------|
| 1 | {Title} | High | file1.ts, file2.ts |
### Items Skipped
| # | Item | Severity | Reason |
|---|------|----------|--------|
| 2 | {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 Processing Guidelines
- Only extract items with concrete, actionable fixes -- skip vague observations
- Deduplication: Merge items targeting the same file/component, with significant keyword overlap, or where one subsumes the other. Keep the higher severity.
- Present items in severity order so the user sees the most impactful items first
- Conflict detection: Before starting fixes, scan for same-file modifications, contradictory changes, or ordering dependencies. If conflicts are detected, present them and suggest a processing order.
- Maximum 3 revision cycles per item when user selects "Modify"
Integration Notes
What this component does: Orchestrates a full codebase analysis workflow -- from deep exploration through structured reporting to actionable insight remediation -- with user interaction at key decision points.
Capabilities needed: File reading, file writing, file editing, file searching (by name pattern and content), command-line execution, multi-agent orchestration (via deep-analysis dependency), user interaction prompts
Adaptation guidance: The reporting templates and actionable insights flow are platform-agnostic. The deep-analysis dependency handles all agent orchestration. Adapt file write/edit operations to your platform's file system API.
Configurable parameters: Inherits deep-analysis settings (cache-ttl-hours, checkpointing, progress indicators). Report output path is user-configurable at runtime.
1---2name: codebase-analysis-43description: 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
10## Phase Overview
11
121. **Deep Analysis** -- Explore and synthesize codebase findings via the deep-analysis skill
132. **Reporting** -- Present structured analysis to the user
143. **Post-Analysis Actions** -- Save, document, or retain analysis insights
15
16---
17
18## Phase 1: Deep Analysis
19
20**Goal:** Explore the codebase and synthesize findings.
21
221. **Determine analysis context:**
23 - If arguments are provided, use them as the analysis context
24 - If no arguments, set context to "general codebase understanding"
25
262. **Check for cached results:**
27 - Check if `.agents/sessions/exploration-cache/manifest.md` exists
28 - 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)
29 - **If cache is valid**, prompt the user to choose:
30 - **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.
31 - **Run fresh analysis** -- Remove the cache manifest file, set `CACHE_HIT = false`, and proceed to step 3
32 - **If no valid cache**: set `CACHE_HIT = false` and proceed to step 3
33
343. **Run deep-analysis workflow:**
35 - Load and follow the deep-analysis skill workflow
36 - Pass the analysis context from step 1
37 - This handles reconnaissance, team planning, approval (auto-approved when skill-invoked), team creation, parallel exploration (code-explorer agents), and synthesis (code-synthesizer agent)
38 - After completion, set `CACHE_TIMESTAMP = null` (fresh results, no prior cache)
39
404. **Verify results and capture metadata:**
41 - Ensure the synthesis covers the analysis context adequately
42 - If critical gaps remain, search for files and content to fill them directly
43 - 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)
44
45---
46
47## Phase 2: Reporting
48
49**Goal:** Present a structured analysis to the user.
50
511. **Load diagram guidance:**
52 - Follow the technical-diagrams skill conventions
53 - Use Mermaid diagrams in the Architecture Overview and Relationship Map sections
54
552. **Structure the report using the report template below**
56
573. **Present the analysis:**
58 Structure the report with these sections:
59 - **Executive Summary** -- Lead with the most important finding
60 - **Architecture Overview** -- How the codebase is structured
61 - **Tech Stack** -- Core technologies, frameworks, and tools detected
62 - **Critical Files** -- The 5-10 most important files with details
63 - **Patterns & Conventions** -- Recurring patterns and coding conventions
64 - **Relationship Map** -- How components connect to each other
65 - **Challenges & Risks** -- Technical risks and complexity hotspots
66 - **Recommendations** -- Actionable next steps, each citing the challenge it addresses
67 - **Analysis Methodology** -- Agents used, cache status, scope, and duration
68
694. Proceed immediately to Phase 3.
70
71---
72
73## Phase 3: Post-Analysis Actions
74
75**Goal:** Let the user save, document, or retain analysis insights from the report through a multi-step interactive flow.
76
77### Step 1: Select actions
78
79Prompt the user to choose (multiple selections allowed):
80
81- **Save Codebase Analysis Report** -- Write the structured report to a markdown file
82- **Save a custom report** -- Generate a report tailored to your specific goals (you'll provide instructions next)
83- **Update project documentation** -- Add/update README.md, CLAUDE.md, or AGENTS.md with analysis insights
84- **Keep a condensed summary in memory** -- Retain a quick-reference summary in conversation context
85
86If the user selects no actions, the workflow is complete. Thank the user and end.
87
88### Step 2: Execute selected actions
89
90Process selected actions in the following fixed order. Complete all sub-steps for each action before moving to the next.
91
92#### Action: Save Codebase Analysis Report
93
94**Step 2a-1: Prompt for file location**
95
96- Check if an `internal/docs/` directory exists in the project root
97 - If yes, suggest default path: `internal/docs/codebase-analysis-report-{YYYY-MM-DD}.md`
98 - If no, suggest default path: `codebase-analysis-report-{YYYY-MM-DD}.md` in the project root
99- Ask the user to confirm or customize the file path
100
101**Step 2a-2: Generate and save the report**
102
103- Generate the full structured report using the Phase 2 analysis findings and the report template
104- Write the report to the confirmed path
105- Confirm the file was saved
106
107#### Action: Save Custom Report
108
109**Step 2b-1: Gather report requirements**
110
111- Ask 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
112
113**Step 2b-2: Prompt for file location**
114
115- Check if an `internal/docs/` directory exists in the project root
116 - If yes, suggest default path: `internal/docs/custom-report-{YYYY-MM-DD}.md`
117 - If no, suggest default path: `custom-report-{YYYY-MM-DD}.md` in the project root
118- Ask the user to confirm or customize the file path
119
120**Step 2b-3: Generate and save the custom report**
121
122- 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
123- Write the report to the confirmed path
124- Confirm the file was saved
125
126#### Action: Update Project Documentation
127
128**Step 2c-1: Select documentation files and gather directions**
129
130Prompt the user to choose (multiple selections allowed):
131
132- **README.md** -- Add architecture, structure, and tech stack information
133- **CLAUDE.md** -- Add patterns, conventions, critical files, and architectural decisions
134- **AGENTS.md** -- Add agent descriptions, capabilities, and coordination patterns
135
136Then ask: "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)."
137
138**Step 2c-2: Generate and approve documentation drafts**
139
140For each selected file, read the existing file and generate a draft based on the user's directions and Phase 2 analysis data:
141
142- **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.
143- **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.
144- **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.
145
146Present **all drafts together** in a single output, clearly labeled by file. Then prompt the user to choose:
147
148- **Apply all** -- Apply all drafted updates
149- **Modify** -- Specify which file(s) to revise and what to change (max 3 revision cycles, then must Apply or Skip)
150- **Skip all** -- Skip all documentation updates
151
152If approved, apply updates using appropriate edit or write operations.
153
154#### Action: Keep Insights in Memory
155
156- Present a condensed **Codebase Quick Reference** inline in the conversation:
157 - **Architecture** -- 1-2 sentence summary of how the codebase is structured
158 - **Key Files** -- 3-5 most critical files with one-line descriptions
159 - **Conventions** -- Important patterns and naming conventions
160 - **Tech Stack** -- Core technologies and frameworks
161 - **Watch Out For** -- Top risks or complexity hotspots
162- No file is written -- this summary stays in conversation context for reference during the session
163
164### Step 3: Actionable Insights Follow-up
165
166**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.
167
168Prompt the user to choose:
169- **Address actionable insights** -- Fix challenges and implement recommendations from the report
170- **Skip** -- No further action needed
171
172If the user selects "Skip", proceed to Step 4.
173
174If the user selects "Address actionable insights":
175
176**Step 3a: Extract actionable items from the report**
177
178Parse the Phase 2 report (in conversation context) to extract items from:
179- **Challenges & Risks** table rows -- title from Challenge column, severity from Severity column, description from Impact column
180- **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.
181- **Other findings** with concrete fixes -- default to Low severity
182
183If no actionable items are found, inform the user and skip to Step 4.
184
185**Step 3b: Present severity-ranked item list**
186
187- Use the actionable insights format documented below
188- Present items sorted High to Medium to Low, each showing:
189 - Title
190 - Severity (High / Medium / Low)
191 - Source section (Challenges & Risks, Recommendations, or Other)
192 - Brief description
193- Prompt the user to select which items to address (multiple selections allowed)
194- If no items selected, skip to Step 4
195
196**Step 3c: Process each selected item in priority order (High to Medium to Low)**
197
198For each item:
199
2001. **Assess complexity:**
201 - **Simple** -- Single file, clear fix, localized change
202 - **Complex** -- Multi-file, architectural impact, requires investigation
203
2042. **Plan the fix:**
205 - Simple: Read the target file, propose changes directly
206 - Complex (architectural): Delegate to a code-architect worker with context: the item title, severity, description, the relevant report section text, and any files or components mentioned. The architect designs the fix and returns a proposal.
207 - Complex (needs investigation): Delegate to a code-explorer worker with context: the item title, description, suspected files/components, and what needs investigation. The explorer investigates and returns findings for you to formulate a fix proposal.
208 - If a delegation fails, fall back to direct investigation using file reading and searching, and propose a simpler fix based on available information.
209
2103. **Present proposal:** Show files to modify, specific changes, and rationale
211
2124. **User approval:** Prompt the user to choose:
213 - **Apply** -- Execute changes, confirm success
214 - **Skip** -- Record the skip, move to next item
215 - **Modify** -- User describes adjustments, re-propose the fix (max 3 revision cycles, then must Apply or Skip)
216
217**Step 3d: Summarize results**
218
219Present a summary covering:
220- Items addressed (with list of files modified per item)
221- Items skipped
222- Total files modified table
223
224### Step 4: Complete the workflow
225
226Summarize which actions were executed and confirm the workflow is complete.
227
228---
229
230## Error Handling
231
232### General
233
234If any phase fails:
2351. Explain what went wrong
2362. Ask the user how to proceed:
237 - Retry the phase
238 - Skip to next phase (with partial results)
239 - Abort the workflow
240
241### Documentation Update Failures (Step 2c)
242
243If an edit or write operation fails when applying documentation updates:
2441. Retry the operation once
2452. If still failing, present the drafted content to the user inline and suggest they apply it manually
2463. Continue with the remaining selected files
247
248### Agent Delegation Failures (Step 3c)
249
250If a code-architect or code-explorer delegation fails during actionable insight processing:
2511. Fall back to direct investigation using file reading and searching
2522. Propose a simpler fix based on available information
2533. If the item is too complex to address without agent assistance, inform the user and offer to skip
254
255---
256
257## Agent Coordination
258
259Exploration 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. See that skill for team setup, approval flow, and failure handling details.
260
261---
262
263## Report Template
264
265Use this template when presenting analysis findings in Phase 2.
266
267```markdown
268# Codebase Analysis Report
269
270**Analysis Context**: {What was analyzed and why}
271**Codebase Path**: {Path analyzed}
272**Date**: {YYYY-MM-DD}
273
274{If the report exceeds approximately 100 lines, add a **Table of Contents** here linking to each major section.}
275
276---
277
278## Executive Summary
279
280{Lead with the most important finding. 2-3 sentences covering: what was analyzed, the key architectural insight, and the primary recommendation or risk.}
281
282---
283
284## Architecture Overview
285
286{2-3 paragraphs describing:}
287- How the codebase is structured (layers, modules, boundaries)
288- The design philosophy and architectural style
289- Key architectural decisions and their rationale
290
291{Include a Mermaid architecture diagram (flowchart or C4 Context) showing the major layers/components. Use classDef with color:#000 for all node styles.}
292
293---
294
295## Tech Stack
296
297| Category | Technology | Version (if detected) | Role |
298|----------|-----------|----------------------|------|
299| Language | {e.g., TypeScript} | {e.g., 5.x} | Primary language |
300| Framework | {e.g., Next.js} | {e.g., 16} | Web framework |
301
302{Include only technologies actually detected in config files or code. Omit categories that don't apply.}
303
304---
305
306## Critical Files
307
308{Limit to 5-10 most important files}
309
310| File | Purpose | Relevance |
311|------|---------|-----------|
312| path/to/file | Brief description | High/Medium |
313
314### File Details
315
316#### path/to/critical-file
317- **Key exports**: What this file provides to others
318- **Core logic**: What it does
319- **Connections**: What depends on it and what it depends on
320
321---
322
323## Patterns & Conventions
324
325### Code Patterns
326- **Pattern**: Description and where it's used
327
328### Naming Conventions
329- **Convention**: Description and examples
330
331### Project Structure
332- **Organization**: How files and directories are organized
333
334---
335
336## Relationship Map
337
338{Describe how key components connect -- limit to 15-20 most significant connections. Use Mermaid flowcharts for both data flows and dependency maps.}
339
340---
341
342## Challenges & Risks
343
344| Challenge | Severity | Impact |
345|-----------|----------|--------|
346| {Description} | High/Medium/Low | {What could go wrong} |
347
348---
349
350## Recommendations
351
3521. **{Recommendation}** _(addresses: {Challenge name})_: {Brief rationale}
3532. **{Recommendation}** _(addresses: {Challenge name})_: {Brief rationale}
354
355---
356
357## Analysis Methodology
358
359- **Exploration agents**: {Number} agents with focus areas: {list}
360- **Synthesis**: Findings merged and critical files read in depth
361- **Scope**: {What was included and what was intentionally excluded}
362- **Cache status**: {Fresh analysis / Cached results from YYYY-MM-DD}
363- **Config files detected**: {List of config files found during reconnaissance}
364- **Gap-filling**: {Whether direct investigation was needed after synthesis, and what areas were filled}
365```
366
367### Section Guidelines
368
369#### Executive Summary
370- Lead with the most important finding, not a generic overview
371- Keep to 2-3 sentences maximum
372- Include at least one actionable insight
373
374#### Critical Files
375- Limit to 5-10 files -- these should be the files someone must understand
376- Include both the "what" (purpose) and "why" (relevance to analysis context)
377- File Details should cover exports, logic, and connections
378
379#### Patterns & Conventions
380- Only include patterns that are consistently applied (not one-off occurrences)
381- Note deviations from patterns -- these are often more interesting than the patterns themselves
382
383#### Relationship Map
384- Focus on the most important connections, not an exhaustive dependency graph
385- Use directional language (calls, depends on, triggers, reads from)
386- Highlight any circular dependencies or unexpected couplings
387- **Depth**: Include 2-3 levels of dependency depth
388- **Format**: Use Mermaid flowcharts. Apply `classDef` with `color:#000` for readability.
389- **Scope limit**: Cap at 15-20 connections.
390
391#### Challenges & Risks
392- Rate severity based on likelihood and impact combined
393- Include specific details, not vague warnings
394- Focus on challenges relevant to the analysis context
395
396#### Recommendations
397- Make recommendations actionable -- "consider" is weaker than "use X for Y"
398- **Cite source challenge**: Each recommendation must reference the specific challenge it addresses using the format: _(addresses: {Challenge name})_
399- Limit to 3-5 recommendations to maintain focus
400
401### Adapting the Template
402
403#### For Feature-Focused Analysis
404- Emphasize integration points and files that would need modification
405- Include a "Feature Implementation Context" section before Recommendations
406- Focus Challenges on implementation risks
407
408#### For General Codebase Understanding
409- Broader Architecture Overview with layer descriptions
410- More extensive Patterns & Conventions section
411- Focus Recommendations on areas for improvement or further investigation
412
413#### For Debugging/Investigation
414- Emphasize the execution path and data flow
415- Include a "Relevant Execution Paths" section
416- Focus Critical Files on the suspected problem area
417
418---
419
420## Actionable Insights Template
421
422Use this format when presenting and processing actionable items in Phase 3.
423
424### Item List Format
425
426Present extracted items grouped by severity, highest first:
427
428```markdown
429### High Severity
430
4311. **{Title}** -- _{Source: Challenges & Risks}_
432 {Brief description of the issue and its impact}
433
434### Medium Severity
435
4362. **{Title}** -- _{Source: Recommendations}_
437 {Brief description and rationale}
438
439### Low Severity
440
4413. **{Title}** -- _{Source: Other Findings}_
442 {Brief description}
443```
444
445### Severity Assignment Guidelines
446
447#### From Challenges & Risks Table
448- Use the **Severity** column value directly (High, Medium, or Low)
449- Title comes from the **Challenge** column
450- Description comes from the **Impact** column
451
452#### From Recommendations Section
453- Each recommendation should cite which challenge it addresses. Use this citation to inherit severity:
454 - Recommendation cites a **High** challenge: assign **High**
455 - Recommendation cites a **Medium** challenge: assign **Medium**
456 - Recommendation cites a **Low** challenge: assign **Low**
457- If a recommendation addresses multiple challenges, use the highest severity
458- If no challenge link is present, infer from context or default to **Medium**
459
460#### From Other Findings
461- Default to **Low** unless the finding explicitly describes a critical issue
462- Only include findings that have a concrete, implementable fix
463
464### Complexity Assessment Criteria
465
466#### Simple (No agent needed)
467- Single file change
468- Clear, localized fix (rename, add validation, fix import, update config)
469- No architectural impact
470- Change is self-contained
471
472#### Complex -- Architectural (Delegate to code-architect)
473- Requires refactoring across multiple files
474- Introduces or changes a pattern
475- Affects system architecture
476- Requires design decisions about approach
477
478#### Complex -- Investigation Needed (Delegate to code-explorer)
479- Root cause is unclear or needs tracing through the codebase
480- Multiple potential locations for the fix
481- Requires understanding current behavior before proposing changes
482- Dependencies or side effects need mapping
483
484#### Effort Estimates
485
486| Complexity | Typical Effort | Description |
487|-----------|---------------|-------------|
488| Simple | Low (~minutes) | Single targeted change, clear fix |
489| Complex -- Architectural | Medium-High (~30min-1hr+) | Multi-file refactoring, design decisions |
490| Complex -- Investigation | Medium (~15-30min) + varies | Investigation phase + fix implementation |
491
492### Change Proposal Format
493
494```markdown
495#### {Item Title} ({Severity})
496
497**Complexity:** Simple / Complex (architectural) / Complex (investigation)
498**Effort:** Low (~minutes) / Medium (~30min) / High (~1hr+)
499
500**Files to modify:**
501| File | Change Type |
502|------|-------------|
503| path/to/file | Edit / Create / Delete |
504
505**Proposed changes:**
506{Description of what will change and why.}
507
508**Rationale:**
509{Why this approach was chosen. Reference the original finding.}
510```
511
512### Summary Format
513
514```markdown
515## Actionable Insights Summary
516
517### Items Addressed
518| # | Item | Severity | Files Modified |
519|---|------|----------|----------------|
520| 1 | {Title} | High | file1.ts, file2.ts |
521
522### Items Skipped
523| # | Item | Severity | Reason |
524|---|------|----------|--------|
525| 2 | {Title} | Low | User skipped |
526
527### Files Modified
528| File | Changes |
529|------|---------|
530| path/to/file | {Brief description of change} |
531
532**Total:** {N} items addressed, {M} items skipped, {P} files modified
533```
534
535### Item Processing Guidelines
536
537- Only extract items with concrete, actionable fixes -- skip vague observations
538- **Deduplication**: Merge items targeting the same file/component, with significant keyword overlap, or where one subsumes the other. Keep the higher severity.
539- Present items in severity order so the user sees the most impactful items first
540- **Conflict detection**: Before starting fixes, scan for same-file modifications, contradictory changes, or ordering dependencies. If conflicts are detected, present them and suggest a processing order.
541- Maximum 3 revision cycles per item when user selects "Modify"
542
543---
544
545## Integration Notes
546**What this component does:** Orchestrates a full codebase analysis workflow -- from deep exploration through structured reporting to actionable insight remediation -- with user interaction at key decision points.
547**Capabilities needed:** File reading, file writing, file editing, file searching (by name pattern and content), command-line execution, multi-agent orchestration (via deep-analysis dependency), user interaction prompts
548**Adaptation guidance:** The reporting templates and actionable insights flow are platform-agnostic. The deep-analysis dependency handles all agent orchestration. Adapt file write/edit operations to your platform's file system API.
549**Configurable parameters:** Inherits deep-analysis settings (cache-ttl-hours, checkpointing, progress indicators). Report output path is user-configurable at runtime.