Deep Analysis Workflow
Execute a structured exploration + synthesis workflow using hub-and-spoke coordination. The lead performs rapid reconnaissance to generate dynamic focus areas, composes a team plan for review, workers explore independently, and a synthesizer merges findings with shell-powered investigation.
This skill can be invoked standalone or loaded by other skills as a reusable building block. Approval behavior is configurable.
Settings Check
Goal: Determine whether the team plan requires user approval before execution.
Read settings file:
- Check configuration for
deep-analysis.direct-invocation-approval (default: true)
- Check configuration for
deep-analysis.invocation-by-skill-approval (default: false)
- If settings are missing or malformed, use defaults
Determine invocation mode:
- Direct invocation: The user invoked deep-analysis directly, or it is running standalone
- Skill-invoked: Another skill (e.g., codebase-analysis, feature-dev, docs-manager) loaded and is executing this workflow
Resolve settings:
- If settings were found, use them as-is
- If settings are missing, use defaults
- If settings are malformed, warn the user and use defaults
Set REQUIRE_APPROVAL:
- If direct invocation: use
direct-invocation-approval value (default: true)
- If skill-invoked: use
invocation-by-skill-approval value (default: false)
Parse session settings:
- Check configuration for
deep-analysis.cache-ttl-hours (default: 24). Number of hours before exploration cache expires. Set to 0 to disable caching entirely.
- Check configuration for
deep-analysis.enable-checkpointing (default: true). Whether to write session checkpoints at phase boundaries.
- Check configuration for
deep-analysis.enable-progress-indicators (default: true). Whether to display phase progress messages.
Set behavioral flags:
CACHE_TTL = value of cache-ttl-hours (default: 24)
ENABLE_CHECKPOINTING = value of enable-checkpointing (default: true)
ENABLE_PROGRESS = value of enable-progress-indicators (default: true)
Phase 0: Session Setup
Goal: Check for cached exploration results, detect interrupted sessions, and initialize the session directory.
Skip this phase entirely if CACHE_TTL = 0 AND ENABLE_CHECKPOINTING = false.
Step 1: Exploration Cache Check
If CACHE_TTL > 0:
- Check if
.claude/sessions/exploration-cache/manifest.md exists
- If found, read the manifest and verify:
analysis_context matches the current analysis context (or is a superset)
codebase_path matches the current working directory
timestamp is within CACHE_TTL hours of now
- Config files referenced in
config_checksum haven't been modified since the cache was written (check mod-times of package.json, tsconfig.json, pyproject.toml, etc.)
- If cache is valid:
- Skill-invoked mode: Auto-accept the cache. Set
CACHE_HIT = true. Read cached synthesis.md and recon_summary.md. Skip to Phase 6 step 2 (present/return results).
- Direct invocation: Prompt the user to choose:
- Use cached results -- Set
CACHE_HIT = true, skip to Phase 6 step 2
- Refresh analysis -- Set
CACHE_HIT = false, proceed normally
- If cache is invalid or absent: Set
CACHE_HIT = false
Step 2: Interrupted Session Check
If ENABLE_CHECKPOINTING = true:
- Check if
.claude/sessions/__da_live__/checkpoint.md exists
- If found, read the checkpoint to determine
last_completed_phase
- Prompt the user to choose:
- Resume from Phase [N+1] -- Load checkpoint state, proceed from the interrupted phase (see Session Recovery in Error Handling)
- Start fresh -- Archive the interrupted session to
.claude/sessions/da-interrupted-{timestamp}/ and proceed normally
- If not found: proceed normally
Step 3: Initialize Session Directory
If ENABLE_CHECKPOINTING = true AND CACHE_HIT = false:
- Create
.claude/sessions/__da_live__/ directory
- Write
checkpoint.md:## Deep Analysis Session
- **analysis_context**: [context from arguments or caller]
- **codebase_path**: [current working directory]
- **started**: [ISO timestamp]
- **current_phase**: 0
- **status**: initialized
- Write
progress.md:## Deep Analysis Progress
- **Phase**: 0 of 6
- **Status**: Session initialized
### Phase Log
- [timestamp] Phase 0: Session initialized
Phase 1: Reconnaissance & Planning
Goal: Perform codebase reconnaissance, generate dynamic focus areas, and compose a team plan.
Determine analysis context:
- Accept the following inputs: an analysis context or focus area describing the exploration goal
- If no inputs and this skill was loaded by another skill, use the calling skill's context
- If no inputs and standalone invocation, set context to "general codebase understanding"
- Set
PATH = current working directory
- Inform the user: "Exploring codebase at:
PATH" with the analysis context
Rapid codebase reconnaissance:
Search for files and read contents to quickly map the codebase structure. This should take 1-2 minutes, not deep investigation.
- Directory structure: Search for files matching
*/ pattern to understand the project layout
- Language and framework detection: Read config files (
package.json, tsconfig.json, pyproject.toml, Cargo.toml, go.mod, etc.) to identify primary language(s) and framework(s)
- File distribution: Search for files matching patterns like
src/**/*.ts, **/*.py to gauge the size and shape of different areas
- Key documentation: Read
README.md, CLAUDE.md, or similar docs if they exist for project context
- For feature-focused analysis: Search file contents for feature-related terms (function names, component names, route paths) to find hotspot directories
- For general analysis: Identify the 3-5 largest or most architecturally significant directories
Fallback: If reconnaissance fails (empty project, unusual structure, errors), use the static focus area templates from Step 3b.
Generate dynamic focus areas:
Based on reconnaissance findings, create focus areas tailored to the actual codebase. Default to 3 focus areas, but adjust based on codebase size and complexity (2 for small projects, up to 4 for large ones).
a) Dynamic focus areas (default):
Each focus area should include:
- Label: Short description (e.g., "API layer in src/api/")
- Directories: Specific directories to explore
- Starting files: 2-3 key files to read first
- Search terms: Patterns to find related code
- Complexity estimate: Low/Medium/High based on file count and apparent structure
For feature-focused analysis, focus areas should track the feature's actual footprint:
Example:
Focus 1: "API routes and middleware in src/api/ and src/middleware/" (auth-related endpoints, request handling)
Focus 2: "React components in src/pages/profile/ and src/components/user/" (UI layer for user profiles)
Focus 3: "Data models and services in src/db/ and src/services/" (persistence and business logic)
For general analysis, focus areas should map to the codebase's actual structure:
Example:
Focus 1: "Next.js app layer in apps/web/src/" (pages, components, app router)
Focus 2: "Shared library in packages/core/src/" (utilities, types, shared logic)
Focus 3: "CLI and tooling in packages/cli/" (commands, configuration, build)
b) Static fallback focus areas (only if recon failed):
For feature-focused analysis:
Focus 1: Explore entry points and user-facing code related to the context
Focus 2: Explore data models, schemas, and storage related to the context
Focus 3: Explore utilities, helpers, and shared infrastructure
For general codebase understanding:
Focus 1: Explore application structure, entry points, and core logic
Focus 2: Explore configuration, infrastructure, and shared utilities
Focus 3: Explore shared utilities, patterns, and cross-cutting concerns
Compose the team plan:
Assemble a structured plan document from the reconnaissance and focus area findings:
## Team Plan: Deep Analysis
### Analysis Context
[context from Step 1]
### Reconnaissance Summary
- **Project:** [name/type]
- **Primary language/framework:** [detected]
- **Codebase size:** [file counts, key directories]
- **Key observations:** [2-3 bullets]
### Focus Areas
#### Focus Area 1: [Label]
- **Directories:** [list]
- **Starting files:** [2-3 files]
- **Search patterns:** [patterns]
- **Complexity:** [Low/Medium/High]
- **Assigned to:** explorer-1
#### Focus Area 2: [Label]
- **Directories:** [list]
- **Starting files:** [2-3 files]
- **Search patterns:** [patterns]
- **Complexity:** [Low/Medium/High]
- **Assigned to:** explorer-2
[... repeated for each focus area]
### Agent Composition
| Role | Count | Purpose |
|------|-------|---------|
| Explorer | [N] | Independent focus area exploration |
| Synthesizer | 1 | Merge findings, deep investigation |
### Task Dependencies
- Exploration Tasks 1-[N]: parallel (no dependencies)
- Synthesis Task: blocked by all exploration tasks
Checkpoint (if ENABLE_CHECKPOINTING = true):
- Update
.claude/sessions/__da_live__/checkpoint.md: set current_phase: 1
- Write
.claude/sessions/__da_live__/team_plan.md with the full team plan from Step 4
- Write
.claude/sessions/__da_live__/recon_summary.md with reconnaissance findings from Step 2
- Append to
progress.md: [timestamp] Phase 1: Reconnaissance complete -- [N] focus areas identified
Phase 2: Review & Approval
Goal: Present the team plan for user review and approval before allocating resources.
If REQUIRE_APPROVAL = false
Skip to Phase 3 with a brief note: "Auto-approving team plan (skill-invoked mode). Proceeding with [N] explorers and 1 synthesizer."
If REQUIRE_APPROVAL = true
Present the team plan to the user (output the plan from Phase 1 Step 4), then prompt the user to choose:
- Approve -- Proceed to Phase 3 as-is
- Modify -- User describes changes (adjust focus areas, add/remove explorers, change scope)
- Regenerate -- Re-run reconnaissance with user feedback
If "Modify" (up to 3 cycles):
- Ask what to change
- Apply modifications to the team plan (adjust focus areas, agent count, scope)
- Re-present the updated plan for approval
- If 3 modification cycles are exhausted, offer "Approve current plan" or "Abort analysis"
If "Regenerate" (up to 2 cycles):
- Ask for feedback/new direction
- Return to Phase 1 Step 2 with the user's feedback incorporated
- Re-compose and re-present the team plan
- If 2 regeneration cycles are exhausted, offer "Approve current plan" or "Abort analysis"
Checkpoint (if ENABLE_CHECKPOINTING = true):
- Update
.claude/sessions/__da_live__/checkpoint.md: set current_phase: 2, record approval_mode (approved/auto-approved)
- Append to
progress.md: [timestamp] Phase 2: Plan approved (mode: [approval_mode])
Phase 3: Team Assembly
Goal: Create the team, delegate tasks, and assign work using the approved plan.
Create the team named deep-analysis-{timestamp} with description: "Deep analysis of [analysis context]"
Delegate exploration to independent workers based on the approved plan:
Create tasks:
- Exploration Task per focus area: Subject: "Explore: [Focus area label]", Description: detailed exploration instructions including directories, starting files, search terms, and complexity estimate
- Synthesis Task: Subject: "Synthesize and evaluate exploration findings", Description: "Merge and synthesize findings from all exploration tasks into a unified analysis. Investigate gaps using shell commands (git history, dependency trees). Evaluate completeness before finalizing."
- The synthesis task is blocked by all exploration tasks
Assign exploration tasks (with status guard):
For each exploration task, apply the following status-guarded assignment:
- Check the task's current status and owner
- Only assign if status is
pending AND owner is empty
- If already assigned or completed: log "Task [ID] already [status], skipping" and move on
- Set the owner to the corresponding explorer
- Send the explorer the task details: "Your exploration task [ID] is assigned. Focus area: [label]. Directories: [list]. Starting files: [list]. Search patterns: [list]. Begin exploration now."
Never re-assign a completed or in-progress task.
Checkpoint (if ENABLE_CHECKPOINTING = true):
- Update
.claude/sessions/__da_live__/checkpoint.md: set current_phase: 3, record team_name, explorer_names (list), task_ids (map of explorer to task ID), synthesis_task_id
- Append to
progress.md: [timestamp] Phase 3: Team assembled -- [N] explorers, 1 synthesizer
Phase 4: Focused Exploration
Goal: Workers explore their assigned areas independently.
Monitoring Loop
After assigning exploration tasks, monitor progress with status-aware tracking:
- When an explorer goes idle or sends a message, check their task status
- If task is
completed: Record the explorer's findings. If ENABLE_CHECKPOINTING = true, write explorer-{N}-findings.md to .claude/sessions/__da_live__/ and update checkpoint.
- If task is
in_progress: The explorer is still working -- do NOT re-send the assignment
- If task is
pending and owner is set: The explorer received the assignment but hasn't started yet -- wait, do NOT re-send
- If task is
pending and owner is empty: Assignment may have been lost -- re-assign using the status guard from Phase 3 step 4
Never re-assign a completed or in-progress task. This is the primary duplicate prevention mechanism.
- Workers explore their assigned focus areas independently -- no cross-worker messaging
- Workers can respond to follow-up questions from the synthesizer
- Each worker marks its task as completed when done
- You (the lead) receive idle notifications as workers finish
- Wait for all exploration tasks to be marked complete before proceeding to Phase 5
Phase 5: Evaluation and Synthesis
Goal: Verify exploration completeness, launch synthesis with deep investigation.
Step 1: Structural Completeness Check
This is a structural check, not a quality assessment:
- Verify all exploration tasks are completed
- Check that each worker produced a report with content (review the messages/reports received)
- If a worker failed completely (empty or error output):
- Create a follow-up exploration task targeting the gap
- Assign it to an idle worker
- Add the new task as a blocker for the synthesis task
- Wait for the follow-up task to complete
- If all produced content: proceed immediately to Step 2
Step 2: Launch Synthesis
Assign the synthesis task to the synthesizer
Send the synthesizer the exploration context and recon findings:
"All exploration tasks are complete. Your synthesis task is now assigned.
Analysis context: [analysis context]
Codebase path: [PATH]
Recon findings from planning phase:
- Project structure: [brief summary of directory layout]
- Primary language/framework: [what was detected]
- Key areas identified: [the focus areas and why they were chosen]
The workers are: [list of explorer names from the approved plan]. You can message them with follow-up questions if you find conflicts or gaps in their findings.
You have shell access for deep investigation -- use it for git history analysis, dependency trees, static analysis, or any investigation that file reading and searching can't handle.
Read the completed exploration tasks to access their reports, then synthesize into a unified analysis. Evaluate completeness before finalizing."
Wait for the synthesizer to mark the synthesis task as completed
Checkpoint (if ENABLE_CHECKPOINTING = true):
- Update
.claude/sessions/__da_live__/checkpoint.md: set current_phase: 5
- Write
.claude/sessions/__da_live__/synthesis.md with the synthesis results
- Append to
progress.md: [timestamp] Phase 5: Synthesis complete
Phase 6: Completion + Cleanup
Goal: Collect results, present to user, and tear down the team.
Collect synthesis output:
- The synthesizer's findings are in the messages it sent and/or the task completion output
- Read the synthesis results
Write exploration cache (if CACHE_TTL > 0):
Present or return results:
- Standalone invocation: Present the synthesized analysis to the user. The results remain in conversation memory for follow-up questions.
- Loaded by another skill: The synthesis is complete. Control returns to the calling workflow -- do not present a standalone summary.
Tear down the team:
Notify all spawned workers that the analysis is complete and release resources.
Archive session and cleanup team:
- If
ENABLE_CHECKPOINTING = true: Move .claude/sessions/__da_live__/ to .claude/sessions/da-{timestamp}/
- Remove the team and its task list
Error Handling
Settings Check Failure
- If settings exist but are malformed: warn the user ("Settings file found but could not parse deep-analysis settings -- using defaults") and proceed with default approval values.
Planning Phase Failure
- If reconnaissance fails (errors, empty results, unusual structure): fall back to static focus area templates (Step 3b)
- If the codebase appears empty: inform the user and ask how to proceed
Approval Phase Failure
- If maximum modification cycles (3) or regeneration cycles (2) are reached without approval, prompt the user to choose:
- Approve current plan -- Proceed with the latest version of the plan
- Abort analysis -- Cancel the analysis entirely
Partial Worker Failure
- If one worker fails: create a follow-up task targeting the missed focus area, assign to an idle worker, add as blocker for synthesis
- If two workers fail: attempt follow-ups, but if they also fail, instruct the synthesizer to work with partial results
- If all workers fail: inform the user and offer to retry or abort
Synthesizer Failure
- If the synthesizer fails: present the raw exploration results to the user directly
- Offer to retry synthesis or let the user work with partial results
General Failures
If any phase fails:
- Explain what went wrong
- Ask the user how to proceed:
- Retry the phase
- Continue with partial results
- Abort the analysis
Session Recovery
When resuming from an interrupted session (detected in Phase 0 Step 2), use the following per-phase strategy:
| Interrupted At |
Recovery Strategy |
| Phase 1 |
Restart from Phase 1 (reconnaissance is fast, ~1-2 min) |
| Phase 2 |
Load saved team_plan.md from session dir, re-present for approval |
| Phase 3 |
Load approved plan from checkpoint, restart team assembly |
| Phase 4 |
Read completed explorer-{N}-findings.md files from session dir. Only spawn and assign explorers whose findings files are missing. Add existing findings to synthesizer context. |
| Phase 5 |
Load all explorer findings from session dir. Spawn a fresh synthesizer and launch synthesis with the persisted findings. |
| Phase 6 |
Load synthesis.md from session dir. Proceed directly to present/return results and cleanup. |
Recovery procedure:
- Read
checkpoint.md to determine last_completed_phase and session state (team_name, explorer_names, task_ids)
- Load any persisted artifacts from the session directory (team_plan, explorer findings, synthesis)
- Resume from Phase
last_completed_phase + 1 using the loaded state
- For Phase 4 recovery: compare persisted
explorer-{N}-findings.md files against expected explorer list to determine which explorers still need to run
Agent Coordination
- The lead (you) acts as the planner: performs recon, composes the team plan, handles approval, assigns work
- Workers explore independently -- no cross-worker messaging (hub-and-spoke topology)
- The synthesizer can ask workers follow-up questions to resolve conflicts and fill gaps
- The synthesizer has shell access for deep investigation (git history, dependency trees, static analysis)
- Wait for task dependencies to resolve before proceeding
- Handle agent failures gracefully -- continue with partial results
- Agent count and focus area details come from the approved plan, not hardcoded values
Integration Notes
What this component does: Orchestrates a multi-agent codebase exploration and synthesis workflow. A lead agent performs reconnaissance, plans focus areas, delegates exploration to independent workers, and coordinates a synthesizer to merge findings into a unified analysis.
Capabilities needed:
- File operations (read, write, search by pattern, search by content)
- Shell execution (for session management directories)
- Sub-agent delegation (spawn N explorer workers + 1 synthesizer)
- Task/message coordination between agents
- User interaction (approval prompts, cache/resume choices)
Adaptation guidance:
- The hub-and-spoke pattern requires a way to spawn independent worker agents and a synthesizer agent. Map to your platform's agent delegation mechanism.
- Task status tracking (pending/in_progress/completed) with ownership is required for the status-guard duplicate prevention. If your platform lacks this, implement equivalent coordination logic.
- Session checkpointing writes to
.claude/sessions/ -- adapt the directory to your platform's session storage.
- The before_action hook (see hooks/) auto-approves file writes to session directories. Adapt to your platform's permission model.
Configurable parameters:
deep-analysis.direct-invocation-approval (default: true)
deep-analysis.invocation-by-skill-approval (default: false)
deep-analysis.cache-ttl-hours (default: 24)
deep-analysis.enable-checkpointing (default: true)
deep-analysis.enable-progress-indicators (default: true)
1---2name: deep-analysis-103description: Deep exploration and synthesis workflow using dynamic planning and hub-and-spoke coordination. Use when asked for "deep analysis", "deep understanding", "analyze codebase", "explore and analyze", or "investigate codebase".4---5
6# Deep Analysis Workflow
7
8Execute a structured exploration + synthesis workflow using hub-and-spoke coordination. The lead performs rapid reconnaissance to generate dynamic focus areas, composes a team plan for review, workers explore independently, and a synthesizer merges findings with shell-powered investigation.
9
10This skill can be invoked standalone or loaded by other skills as a reusable building block. Approval behavior is configurable.
11
12## Settings Check
13
14**Goal:** Determine whether the team plan requires user approval before execution.
15
161. **Read settings file:**
17 - Check configuration for `deep-analysis.direct-invocation-approval` (default: `true`)
18 - Check configuration for `deep-analysis.invocation-by-skill-approval` (default: `false`)
19 - If settings are missing or malformed, use defaults
20
212. **Determine invocation mode:**
22 - **Direct invocation:** The user invoked deep-analysis directly, or it is running standalone
23 - **Skill-invoked:** Another skill (e.g., codebase-analysis, feature-dev, docs-manager) loaded and is executing this workflow
24
253. **Resolve settings:**
26 - If settings were found, use them as-is
27 - If settings are missing, use defaults
28 - If settings are malformed, warn the user and use defaults
29
304. **Set `REQUIRE_APPROVAL`:**
31 - If direct invocation: use `direct-invocation-approval` value (default: `true`)
32 - If skill-invoked: use `invocation-by-skill-approval` value (default: `false`)
33
345. **Parse session settings:**
35 - Check configuration for `deep-analysis.cache-ttl-hours` (default: `24`). Number of hours before exploration cache expires. Set to `0` to disable caching entirely.
36 - Check configuration for `deep-analysis.enable-checkpointing` (default: `true`). Whether to write session checkpoints at phase boundaries.
37 - Check configuration for `deep-analysis.enable-progress-indicators` (default: `true`). Whether to display phase progress messages.
38
396. **Set behavioral flags:**
40 - `CACHE_TTL` = value of `cache-ttl-hours` (default: `24`)
41 - `ENABLE_CHECKPOINTING` = value of `enable-checkpointing` (default: `true`)
42 - `ENABLE_PROGRESS` = value of `enable-progress-indicators` (default: `true`)
43
44---
45
46## Phase 0: Session Setup
47
48**Goal:** Check for cached exploration results, detect interrupted sessions, and initialize the session directory.
49
50> Skip this phase entirely if `CACHE_TTL = 0` AND `ENABLE_CHECKPOINTING = false`.
51
52### Step 1: Exploration Cache Check
53
54If `CACHE_TTL > 0`:
55
561. Check if `.claude/sessions/exploration-cache/manifest.md` exists
572. If found, read the manifest and verify:
58 - `analysis_context` matches the current analysis context (or is a superset)
59 - `codebase_path` matches the current working directory
60 - `timestamp` is within `CACHE_TTL` hours of now
61 - Config files referenced in `config_checksum` haven't been modified since the cache was written (check mod-times of `package.json`, `tsconfig.json`, `pyproject.toml`, etc.)
623. **If cache is valid:**
63 - **Skill-invoked mode:** Auto-accept the cache. Set `CACHE_HIT = true`. Read cached `synthesis.md` and `recon_summary.md`. Skip to Phase 6 step 2 (present/return results).
64 - **Direct invocation:** Prompt the user to choose:
65 - **Use cached results** -- Set `CACHE_HIT = true`, skip to Phase 6 step 2
66 - **Refresh analysis** -- Set `CACHE_HIT = false`, proceed normally
674. **If cache is invalid or absent:** Set `CACHE_HIT = false`
68
69### Step 2: Interrupted Session Check
70
71If `ENABLE_CHECKPOINTING = true`:
72
731. Check if `.claude/sessions/__da_live__/checkpoint.md` exists
742. If found, read the checkpoint to determine `last_completed_phase`
753. Prompt the user to choose:
76 - **Resume from Phase [N+1]** -- Load checkpoint state, proceed from the interrupted phase (see Session Recovery in Error Handling)
77 - **Start fresh** -- Archive the interrupted session to `.claude/sessions/da-interrupted-{timestamp}/` and proceed normally
784. If not found: proceed normally
79
80### Step 3: Initialize Session Directory
81
82If `ENABLE_CHECKPOINTING = true` AND `CACHE_HIT = false`:
83
841. Create `.claude/sessions/__da_live__/` directory
852. Write `checkpoint.md`:
86 ```markdown
87 ## Deep Analysis Session
88 - **analysis_context**: [context from arguments or caller]
89 - **codebase_path**: [current working directory]
90 - **started**: [ISO timestamp]
91 - **current_phase**: 0
92 - **status**: initialized
93 ```
943. Write `progress.md`:
95 ```markdown
96 ## Deep Analysis Progress
97 - **Phase**: 0 of 6
98 - **Status**: Session initialized
99
100 ### Phase Log
101 - [timestamp] Phase 0: Session initialized
102 ```
103
104---
105
106## Phase 1: Reconnaissance & Planning
107
108**Goal:** Perform codebase reconnaissance, generate dynamic focus areas, and compose a team plan.
109
1101. **Determine analysis context:**
111 - Accept the following inputs: an analysis context or focus area describing the exploration goal
112 - If no inputs and this skill was loaded by another skill, use the calling skill's context
113 - If no inputs and standalone invocation, set context to "general codebase understanding"
114 - Set `PATH = current working directory`
115 - Inform the user: "Exploring codebase at: `PATH`" with the analysis context
116
1172. **Rapid codebase reconnaissance:**
118 Search for files and read contents to quickly map the codebase structure. This should take 1-2 minutes, not deep investigation.
119
120 - **Directory structure:** Search for files matching `*/` pattern to understand the project layout
121 - **Language and framework detection:** Read config files (`package.json`, `tsconfig.json`, `pyproject.toml`, `Cargo.toml`, `go.mod`, etc.) to identify primary language(s) and framework(s)
122 - **File distribution:** Search for files matching patterns like `src/**/*.ts`, `**/*.py` to gauge the size and shape of different areas
123 - **Key documentation:** Read `README.md`, `CLAUDE.md`, or similar docs if they exist for project context
124 - **For feature-focused analysis:** Search file contents for feature-related terms (function names, component names, route paths) to find hotspot directories
125 - **For general analysis:** Identify the 3-5 largest or most architecturally significant directories
126
127 **Fallback:** If reconnaissance fails (empty project, unusual structure, errors), use the static focus area templates from Step 3b.
128
1293. **Generate dynamic focus areas:**
130
131 Based on reconnaissance findings, create focus areas tailored to the actual codebase. Default to 3 focus areas, but adjust based on codebase size and complexity (2 for small projects, up to 4 for large ones).
132
133 **a) Dynamic focus areas (default):**
134
135 Each focus area should include:
136 - **Label:** Short description (e.g., "API layer in src/api/")
137 - **Directories:** Specific directories to explore
138 - **Starting files:** 2-3 key files to read first
139 - **Search terms:** Patterns to find related code
140 - **Complexity estimate:** Low/Medium/High based on file count and apparent structure
141
142 For feature-focused analysis, focus areas should track the feature's actual footprint:
143 ```
144 Example:
145 Focus 1: "API routes and middleware in src/api/ and src/middleware/" (auth-related endpoints, request handling)
146 Focus 2: "React components in src/pages/profile/ and src/components/user/" (UI layer for user profiles)
147 Focus 3: "Data models and services in src/db/ and src/services/" (persistence and business logic)
148 ```
149
150 For general analysis, focus areas should map to the codebase's actual structure:
151 ```
152 Example:
153 Focus 1: "Next.js app layer in apps/web/src/" (pages, components, app router)
154 Focus 2: "Shared library in packages/core/src/" (utilities, types, shared logic)
155 Focus 3: "CLI and tooling in packages/cli/" (commands, configuration, build)
156 ```
157
158 **b) Static fallback focus areas** (only if recon failed):
159
160 For feature-focused analysis:
161 ```
162 Focus 1: Explore entry points and user-facing code related to the context
163 Focus 2: Explore data models, schemas, and storage related to the context
164 Focus 3: Explore utilities, helpers, and shared infrastructure
165 ```
166
167 For general codebase understanding:
168 ```
169 Focus 1: Explore application structure, entry points, and core logic
170 Focus 2: Explore configuration, infrastructure, and shared utilities
171 Focus 3: Explore shared utilities, patterns, and cross-cutting concerns
172 ```
173
1744. **Compose the team plan:**
175
176 Assemble a structured plan document from the reconnaissance and focus area findings:
177
178 ```markdown
179 ## Team Plan: Deep Analysis
180
181 ### Analysis Context
182 [context from Step 1]
183
184 ### Reconnaissance Summary
185 - **Project:** [name/type]
186 - **Primary language/framework:** [detected]
187 - **Codebase size:** [file counts, key directories]
188 - **Key observations:** [2-3 bullets]
189
190 ### Focus Areas
191
192 #### Focus Area 1: [Label]
193 - **Directories:** [list]
194 - **Starting files:** [2-3 files]
195 - **Search patterns:** [patterns]
196 - **Complexity:** [Low/Medium/High]
197 - **Assigned to:** explorer-1
198
199 #### Focus Area 2: [Label]
200 - **Directories:** [list]
201 - **Starting files:** [2-3 files]
202 - **Search patterns:** [patterns]
203 - **Complexity:** [Low/Medium/High]
204 - **Assigned to:** explorer-2
205
206 [... repeated for each focus area]
207
208 ### Agent Composition
209 | Role | Count | Purpose |
210 |------|-------|---------|
211 | Explorer | [N] | Independent focus area exploration |
212 | Synthesizer | 1 | Merge findings, deep investigation |
213
214 ### Task Dependencies
215 - Exploration Tasks 1-[N]: parallel (no dependencies)
216 - Synthesis Task: blocked by all exploration tasks
217 ```
218
2195. **Checkpoint** (if `ENABLE_CHECKPOINTING = true`):
220 - Update `.claude/sessions/__da_live__/checkpoint.md`: set `current_phase: 1`
221 - Write `.claude/sessions/__da_live__/team_plan.md` with the full team plan from Step 4
222 - Write `.claude/sessions/__da_live__/recon_summary.md` with reconnaissance findings from Step 2
223 - Append to `progress.md`: `[timestamp] Phase 1: Reconnaissance complete -- [N] focus areas identified`
224
225---
226
227## Phase 2: Review & Approval
228
229**Goal:** Present the team plan for user review and approval before allocating resources.
230
231### If `REQUIRE_APPROVAL = false`
232
233Skip to Phase 3 with a brief note: "Auto-approving team plan (skill-invoked mode). Proceeding with [N] explorers and 1 synthesizer."
234
235### If `REQUIRE_APPROVAL = true`
236
2371. **Present the team plan** to the user (output the plan from Phase 1 Step 4), then prompt the user to choose:
238 - **Approve** -- Proceed to Phase 3 as-is
239 - **Modify** -- User describes changes (adjust focus areas, add/remove explorers, change scope)
240 - **Regenerate** -- Re-run reconnaissance with user feedback
241
2422. **If "Modify"** (up to 3 cycles):
243 - Ask what to change
244 - Apply modifications to the team plan (adjust focus areas, agent count, scope)
245 - Re-present the updated plan for approval
246 - If 3 modification cycles are exhausted, offer "Approve current plan" or "Abort analysis"
247
2483. **If "Regenerate"** (up to 2 cycles):
249 - Ask for feedback/new direction
250 - Return to Phase 1 Step 2 with the user's feedback incorporated
251 - Re-compose and re-present the team plan
252 - If 2 regeneration cycles are exhausted, offer "Approve current plan" or "Abort analysis"
253
2544. **Checkpoint** (if `ENABLE_CHECKPOINTING = true`):
255 - Update `.claude/sessions/__da_live__/checkpoint.md`: set `current_phase: 2`, record `approval_mode` (approved/auto-approved)
256 - Append to `progress.md`: `[timestamp] Phase 2: Plan approved (mode: [approval_mode])`
257
258---
259
260## Phase 3: Team Assembly
261
262**Goal:** Create the team, delegate tasks, and assign work using the approved plan.
263
2641. **Create the team** named `deep-analysis-{timestamp}` with description: "Deep analysis of [analysis context]"
265
2662. **Delegate exploration to independent workers** based on the approved plan:
267
268 - **N explorers** (one per focus area) -- using the **code-explorer** agent definition
269 - Named: `explorer-1`, `explorer-2`, ... `explorer-N`
270 - Prompt each with: "You are part of a deep analysis team. Wait for your task assignment. The codebase is at: [PATH]. Analysis context: [context]"
271
272 - **1 synthesizer** -- using the **code-synthesizer** agent definition
273 - Named: `synthesizer`
274 - Prompt with: "You are the synthesizer for a deep analysis team. You have shell access for git history, dependency analysis, and static analysis. Wait for your task assignment. The codebase is at: [PATH]. Analysis context: [context]"
275
2763. **Create tasks:**
277
278 - **Exploration Task per focus area:** Subject: "Explore: [Focus area label]", Description: detailed exploration instructions including directories, starting files, search terms, and complexity estimate
279 - **Synthesis Task:** Subject: "Synthesize and evaluate exploration findings", Description: "Merge and synthesize findings from all exploration tasks into a unified analysis. Investigate gaps using shell commands (git history, dependency trees). Evaluate completeness before finalizing."
280 - The synthesis task is blocked by all exploration tasks
281
2824. **Assign exploration tasks (with status guard):**
283
284 For each exploration task, apply the following status-guarded assignment:
285
286 1. Check the task's current status and owner
287 2. **Only assign if** status is `pending` AND owner is empty
288 3. If already assigned or completed: log "Task [ID] already [status], skipping" and move on
289 4. Set the owner to the corresponding explorer
290 5. Send the explorer the task details: "Your exploration task [ID] is assigned. Focus area: [label]. Directories: [list]. Starting files: [list]. Search patterns: [list]. Begin exploration now."
291
292 **Never re-assign a completed or in-progress task.**
293
2945. **Checkpoint** (if `ENABLE_CHECKPOINTING = true`):
295 - Update `.claude/sessions/__da_live__/checkpoint.md`: set `current_phase: 3`, record `team_name`, `explorer_names` (list), `task_ids` (map of explorer to task ID), `synthesis_task_id`
296 - Append to `progress.md`: `[timestamp] Phase 3: Team assembled -- [N] explorers, 1 synthesizer`
297
298---
299
300## Phase 4: Focused Exploration
301
302**Goal:** Workers explore their assigned areas independently.
303
304### Monitoring Loop
305
306After assigning exploration tasks, monitor progress with status-aware tracking:
307
3081. When an explorer goes idle or sends a message, check their task status
3092. **If task is `completed`**: Record the explorer's findings. If `ENABLE_CHECKPOINTING = true`, write `explorer-{N}-findings.md` to `.claude/sessions/__da_live__/` and update checkpoint.
3103. **If task is `in_progress`**: The explorer is still working -- do NOT re-send the assignment
3114. **If task is `pending` and owner is set**: The explorer received the assignment but hasn't started yet -- wait, do NOT re-send
3125. **If task is `pending` and owner is empty**: Assignment may have been lost -- re-assign using the status guard from Phase 3 step 4
313
314**Never re-assign a completed or in-progress task.** This is the primary duplicate prevention mechanism.
315
316- Workers explore their assigned focus areas independently -- no cross-worker messaging
317- Workers can respond to follow-up questions from the synthesizer
318- Each worker marks its task as completed when done
319- You (the lead) receive idle notifications as workers finish
320- **Wait for all exploration tasks to be marked complete** before proceeding to Phase 5
321
322---
323
324## Phase 5: Evaluation and Synthesis
325
326**Goal:** Verify exploration completeness, launch synthesis with deep investigation.
327
328### Step 1: Structural Completeness Check
329
330This is a structural check, not a quality assessment:
331
3321. Verify all exploration tasks are completed
3332. Check that each worker produced a report with content (review the messages/reports received)
3343. **If a worker failed completely** (empty or error output):
335 - Create a follow-up exploration task targeting the gap
336 - Assign it to an idle worker
337 - Add the new task as a blocker for the synthesis task
338 - Wait for the follow-up task to complete
3394. **If all produced content**: proceed immediately to Step 2
340
341### Step 2: Launch Synthesis
342
3431. Assign the synthesis task to the synthesizer
3442. Send the synthesizer the exploration context and recon findings:
345 "All exploration tasks are complete. Your synthesis task is now assigned.
346
347 Analysis context: [analysis context]
348 Codebase path: [PATH]
349
350 Recon findings from planning phase:
351 - Project structure: [brief summary of directory layout]
352 - Primary language/framework: [what was detected]
353 - Key areas identified: [the focus areas and why they were chosen]
354
355 The workers are: [list of explorer names from the approved plan]. You can message them with follow-up questions if you find conflicts or gaps in their findings.
356
357 You have shell access for deep investigation -- use it for git history analysis, dependency trees, static analysis, or any investigation that file reading and searching can't handle.
358
359 Read the completed exploration tasks to access their reports, then synthesize into a unified analysis. Evaluate completeness before finalizing."
3603. Wait for the synthesizer to mark the synthesis task as completed
361
3624. **Checkpoint** (if `ENABLE_CHECKPOINTING = true`):
363 - Update `.claude/sessions/__da_live__/checkpoint.md`: set `current_phase: 5`
364 - Write `.claude/sessions/__da_live__/synthesis.md` with the synthesis results
365 - Append to `progress.md`: `[timestamp] Phase 5: Synthesis complete`
366
367---
368
369## Phase 6: Completion + Cleanup
370
371**Goal:** Collect results, present to user, and tear down the team.
372
3731. **Collect synthesis output:**
374 - The synthesizer's findings are in the messages it sent and/or the task completion output
375 - Read the synthesis results
376
3772. **Write exploration cache** (if `CACHE_TTL > 0`):
378 - Create `.claude/sessions/exploration-cache/` directory (overwrite if exists)
379 - Write `manifest.md`:
380 ```markdown
381 ## Exploration Cache Manifest
382 - **analysis_context**: [the analysis context used]
383 - **codebase_path**: [current working directory]
384 - **timestamp**: [ISO timestamp]
385 - **config_checksum**: [comma-separated list of config files and their mod-times]
386 - **ttl_hours**: [CACHE_TTL value]
387 - **explorer_count**: [N]
388 ```
389 - Write `synthesis.md` with the full synthesis output
390 - Write `recon_summary.md` with the Phase 1 reconnaissance findings
391 - Write `explorer-{N}-findings.md` for each explorer's findings (if not already persisted from Phase 4 checkpoints)
392
3933. **Present or return results:**
394 - **Standalone invocation:** Present the synthesized analysis to the user. The results remain in conversation memory for follow-up questions.
395 - **Loaded by another skill:** The synthesis is complete. Control returns to the calling workflow -- do not present a standalone summary.
396
3974. **Tear down the team:**
398 Notify all spawned workers that the analysis is complete and release resources.
399
4005. **Archive session and cleanup team:**
401 - If `ENABLE_CHECKPOINTING = true`: Move `.claude/sessions/__da_live__/` to `.claude/sessions/da-{timestamp}/`
402 - Remove the team and its task list
403
404---
405
406## Error Handling
407
408### Settings Check Failure
409- If settings exist but are malformed: warn the user ("Settings file found but could not parse deep-analysis settings -- using defaults") and proceed with default approval values.
410
411### Planning Phase Failure
412- If reconnaissance fails (errors, empty results, unusual structure): fall back to static focus area templates (Step 3b)
413- If the codebase appears empty: inform the user and ask how to proceed
414
415### Approval Phase Failure
416- If maximum modification cycles (3) or regeneration cycles (2) are reached without approval, prompt the user to choose:
417 - **Approve current plan** -- Proceed with the latest version of the plan
418 - **Abort analysis** -- Cancel the analysis entirely
419
420### Partial Worker Failure
421- If one worker fails: create a follow-up task targeting the missed focus area, assign to an idle worker, add as blocker for synthesis
422- If two workers fail: attempt follow-ups, but if they also fail, instruct the synthesizer to work with partial results
423- If all workers fail: inform the user and offer to retry or abort
424
425### Synthesizer Failure
426- If the synthesizer fails: present the raw exploration results to the user directly
427- Offer to retry synthesis or let the user work with partial results
428
429### General Failures
430If any phase fails:
4311. Explain what went wrong
4322. Ask the user how to proceed:
433 - Retry the phase
434 - Continue with partial results
435 - Abort the analysis
436
437### Session Recovery
438
439When resuming from an interrupted session (detected in Phase 0 Step 2), use the following per-phase strategy:
440
441| Interrupted At | Recovery Strategy |
442|----------------|-------------------|
443| **Phase 1** | Restart from Phase 1 (reconnaissance is fast, ~1-2 min) |
444| **Phase 2** | Load saved `team_plan.md` from session dir, re-present for approval |
445| **Phase 3** | Load approved plan from checkpoint, restart team assembly |
446| **Phase 4** | Read completed `explorer-{N}-findings.md` files from session dir. Only spawn and assign explorers whose findings files are missing. Add existing findings to synthesizer context. |
447| **Phase 5** | Load all explorer findings from session dir. Spawn a fresh synthesizer and launch synthesis with the persisted findings. |
448| **Phase 6** | Load `synthesis.md` from session dir. Proceed directly to present/return results and cleanup. |
449
450**Recovery procedure:**
4511. Read `checkpoint.md` to determine `last_completed_phase` and session state (team_name, explorer_names, task_ids)
4522. Load any persisted artifacts from the session directory (team_plan, explorer findings, synthesis)
4533. Resume from Phase `last_completed_phase + 1` using the loaded state
4544. For Phase 4 recovery: compare persisted `explorer-{N}-findings.md` files against expected explorer list to determine which explorers still need to run
455
456---
457
458## Agent Coordination
459
460- The lead (you) acts as the planner: performs recon, composes the team plan, handles approval, assigns work
461- Workers explore independently -- no cross-worker messaging (hub-and-spoke topology)
462- The synthesizer can ask workers follow-up questions to resolve conflicts and fill gaps
463- The synthesizer has shell access for deep investigation (git history, dependency trees, static analysis)
464- Wait for task dependencies to resolve before proceeding
465- Handle agent failures gracefully -- continue with partial results
466- Agent count and focus area details come from the approved plan, not hardcoded values
467
468---
469
470## Integration Notes
471
472**What this component does:** Orchestrates a multi-agent codebase exploration and synthesis workflow. A lead agent performs reconnaissance, plans focus areas, delegates exploration to independent workers, and coordinates a synthesizer to merge findings into a unified analysis.
473
474**Capabilities needed:**
475- File operations (read, write, search by pattern, search by content)
476- Shell execution (for session management directories)
477- Sub-agent delegation (spawn N explorer workers + 1 synthesizer)
478- Task/message coordination between agents
479- User interaction (approval prompts, cache/resume choices)
480
481**Adaptation guidance:**
482- The hub-and-spoke pattern requires a way to spawn independent worker agents and a synthesizer agent. Map to your platform's agent delegation mechanism.
483- Task status tracking (pending/in_progress/completed) with ownership is required for the status-guard duplicate prevention. If your platform lacks this, implement equivalent coordination logic.
484- Session checkpointing writes to `.claude/sessions/` -- adapt the directory to your platform's session storage.
485- The before_action hook (see hooks/) auto-approves file writes to session directories. Adapt to your platform's permission model.
486
487**Configurable parameters:**
488- `deep-analysis.direct-invocation-approval` (default: `true`)
489- `deep-analysis.invocation-by-skill-approval` (default: `false`)
490- `deep-analysis.cache-ttl-hours` (default: `24`)
491- `deep-analysis.enable-checkpointing` (default: `true`)
492- `deep-analysis.enable-progress-indicators` (default: `true`)