Deep Analysis Workflow
Execute a structured exploration + synthesis workflow using agent teams with 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 command-line 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:
Determine invocation mode:
- Direct invocation: The user invoked deep-analysis directly, or you are running this skill 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 the file is missing or the
deep-analysis section is absent, use defaults:
direct-invocation-approval: true
invocation-by-skill-approval: false
- If the file exists but is malformed (unparseable), 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 (also under the deep-analysis section):
- **deep-analysis**:
- **cache-ttl-hours**: 24
- **enable-checkpointing**: true
- **enable-progress-indicators**: true
cache-ttl-hours: Number of hours before exploration cache expires. Default: 24. Set to 0 to disable caching entirely.
enable-checkpointing: Whether to write session checkpoints at phase boundaries. Default: true.
enable-progress-indicators: Whether to display [Phase N/6] progress messages. Default: true.
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
.agents/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
.agents/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
.agents/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
.agents/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.
If ENABLE_PROGRESS = true: Display "[Phase 1/6] Reconnaissance & Planning -- Mapping codebase structure..."
Determine analysis context:
- If arguments are provided, use them as the analysis context (feature area, question, or general exploration goal)
- If no arguments and this skill was loaded by another skill, use the calling skill's context
- If no arguments 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 scan content to quickly map the codebase structure. This should take 1-2 minutes, not deep investigation.
- Directory structure: Search for top-level directories (e.g.,
*/ 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
.agents/sessions/__da_live__/checkpoint.md: set current_phase: 1
- Write
.agents/sessions/__da_live__/team_plan.md with the full team plan from Step 4
- Write
.agents/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 ENABLE_PROGRESS = true: Display "[Phase 2/6] Review & Approval -- Presenting team plan..."
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
.agents/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, spawn agents, create tasks, and assign work using the approved plan.
If ENABLE_PROGRESS = true: Display "[Phase 3/6] Team Assembly -- Creating team and spawning agents..."
Create the team:
- Create a team named
deep-analysis-{timestamp} (e.g., deep-analysis-1707300000)
- Description: "Deep analysis of [analysis context]"
Spawn teammates:
Delegate work to agents based on the approved plan:
Create tasks:
Create a task for each unit of work based on the approved plan's focus areas:
- 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 command-line tools (git history, dependency trees). Evaluate completeness before finalizing."
- The synthesis task is blocked by all exploration task IDs
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 a message with 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
.agents/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.
If ENABLE_PROGRESS = true: Display "[Phase 4/6] Focused Exploration -- 0/[N] explorers complete"
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 .agents/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.
If ENABLE_PROGRESS = true: Update the progress display as explorers complete: "[Phase 4/6] Focused Exploration -- [completed]/[N] explorers complete"
- 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.
If ENABLE_PROGRESS = true: Display "[Phase 5/6] Synthesis -- Merging findings and investigating gaps..."
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 to the synthesis task's blocked-by list
- 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 a message with 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 command-line 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
.agents/sessions/__da_live__/checkpoint.md: set current_phase: 5
- Write
.agents/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.
If ENABLE_PROGRESS = true: Display "[Phase 6/6] Completion -- Collecting results and cleaning up..."
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.
Shutdown teammates:
Send shutdown requests to all spawned teammates (iterate over the actual agents from the approved plan):
- Shut down each explorer
- Shut down the synthesizer
Archive session and cleanup team:
- If
ENABLE_CHECKPOINTING = true: Move .agents/sessions/__da_live__/ to .agents/sessions/da-{timestamp}/
- Delete the team and its task list
Error Handling
Settings Check Failure
- If the settings file exists but is malformed or the
deep-analysis section is unparseable: 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 to synthesis blocked-by list
- 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 command-line 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
When delegating to teammates:
- Use a high-reasoning model for the synthesizer
- Use a lightweight/fast model for workers
- Always associate agents with the team
Integration Notes
What this component does: Orchestrates a multi-agent hub-and-spoke codebase exploration workflow -- a lead performs reconnaissance and planning, N explorer workers investigate focus areas in parallel, and a synthesizer merges findings with deep investigation capabilities.
Capabilities needed: File reading, file searching (by name pattern and content), command-line execution, multi-agent orchestration (team creation, task management, inter-agent messaging), user interaction prompts
Adaptation guidance: The core workflow (recon, plan, explore, synthesize) is platform-agnostic. Adapt the team/task management primitives to your platform's agent orchestration API. Session checkpointing writes to .agents/sessions/ and can be adapted to any persistent storage.
Configurable parameters: direct-invocation-approval (default: true), invocation-by-skill-approval (default: false), cache-ttl-hours (default: 24), enable-checkpointing (default: true), enable-progress-indicators (default: true)
1---2name: deep-analysis-43description: Deep exploration and synthesis workflow using agent teams with 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 agent teams with 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 command-line 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 a `deep-analysis` section with nested settings:
18 ```markdown
19 - **deep-analysis**:
20 - **direct-invocation-approval**: true
21 - **invocation-by-skill-approval**: false
22 ```
23 - If the file does not exist or is malformed, use defaults (see step 4)
24
252. **Determine invocation mode:**
26 - **Direct invocation:** The user invoked deep-analysis directly, or you are running this skill standalone
27 - **Skill-invoked:** Another skill (e.g., codebase-analysis, feature-dev, docs-manager) loaded and is executing this workflow
28
293. **Resolve settings:**
30 - If settings were found, use them as-is
31 - If the file is missing or the `deep-analysis` section is absent, use defaults:
32 - `direct-invocation-approval`: `true`
33 - `invocation-by-skill-approval`: `false`
34 - If the file exists but is malformed (unparseable), warn the user and use defaults
35
364. **Set `REQUIRE_APPROVAL`:**
37 - If direct invocation: use `direct-invocation-approval` value (default: `true`)
38 - If skill-invoked: use `invocation-by-skill-approval` value (default: `false`)
39
405. **Parse session settings** (also under the `deep-analysis` section):
41 ```markdown
42 - **deep-analysis**:
43 - **cache-ttl-hours**: 24
44 - **enable-checkpointing**: true
45 - **enable-progress-indicators**: true
46 ```
47 - `cache-ttl-hours`: Number of hours before exploration cache expires. Default: `24`. Set to `0` to disable caching entirely.
48 - `enable-checkpointing`: Whether to write session checkpoints at phase boundaries. Default: `true`.
49 - `enable-progress-indicators`: Whether to display `[Phase N/6]` progress messages. Default: `true`.
50
516. **Set behavioral flags:**
52 - `CACHE_TTL` = value of `cache-ttl-hours` (default: `24`)
53 - `ENABLE_CHECKPOINTING` = value of `enable-checkpointing` (default: `true`)
54 - `ENABLE_PROGRESS` = value of `enable-progress-indicators` (default: `true`)
55
56---
57
58## Phase 0: Session Setup
59
60**Goal:** Check for cached exploration results, detect interrupted sessions, and initialize the session directory.
61
62> Skip this phase entirely if `CACHE_TTL = 0` AND `ENABLE_CHECKPOINTING = false`.
63
64### Step 1: Exploration Cache Check
65
66If `CACHE_TTL > 0`:
67
681. Check if `.agents/sessions/exploration-cache/manifest.md` exists
692. If found, read the manifest and verify:
70 - `analysis_context` matches the current analysis context (or is a superset)
71 - `codebase_path` matches the current working directory
72 - `timestamp` is within `CACHE_TTL` hours of now
73 - 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.)
743. **If cache is valid:**
75 - **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).
76 - **Direct invocation:** Prompt the user to choose:
77 - **Use cached results** -- Set `CACHE_HIT = true`, skip to Phase 6 step 2
78 - **Refresh analysis** -- Set `CACHE_HIT = false`, proceed normally
794. **If cache is invalid or absent:** Set `CACHE_HIT = false`
80
81### Step 2: Interrupted Session Check
82
83If `ENABLE_CHECKPOINTING = true`:
84
851. Check if `.agents/sessions/__da_live__/checkpoint.md` exists
862. If found, read the checkpoint to determine `last_completed_phase`
873. Prompt the user to choose:
88 - **Resume from Phase [N+1]** -- Load checkpoint state, proceed from the interrupted phase (see Session Recovery in Error Handling)
89 - **Start fresh** -- Archive the interrupted session to `.agents/sessions/da-interrupted-{timestamp}/` and proceed normally
904. If not found: proceed normally
91
92### Step 3: Initialize Session Directory
93
94If `ENABLE_CHECKPOINTING = true` AND `CACHE_HIT = false`:
95
961. Create `.agents/sessions/__da_live__/` directory
972. Write `checkpoint.md`:
98 ```markdown
99 ## Deep Analysis Session
100 - **analysis_context**: [context from arguments or caller]
101 - **codebase_path**: [current working directory]
102 - **started**: [ISO timestamp]
103 - **current_phase**: 0
104 - **status**: initialized
105 ```
1063. Write `progress.md`:
107 ```markdown
108 ## Deep Analysis Progress
109 - **Phase**: 0 of 6
110 - **Status**: Session initialized
111
112 ### Phase Log
113 - [timestamp] Phase 0: Session initialized
114 ```
115
116---
117
118## Phase 1: Reconnaissance & Planning
119
120**Goal:** Perform codebase reconnaissance, generate dynamic focus areas, and compose a team plan.
121
122> If `ENABLE_PROGRESS = true`: Display "[Phase 1/6] Reconnaissance & Planning -- Mapping codebase structure..."
123
1241. **Determine analysis context:**
125 - If arguments are provided, use them as the analysis context (feature area, question, or general exploration goal)
126 - If no arguments and this skill was loaded by another skill, use the calling skill's context
127 - If no arguments and standalone invocation, set context to "general codebase understanding"
128 - Set `PATH = current working directory`
129 - Inform the user: "Exploring codebase at: `PATH`" with the analysis context
130
1312. **Rapid codebase reconnaissance:**
132 Search for files and scan content to quickly map the codebase structure. This should take 1-2 minutes, not deep investigation.
133
134 - **Directory structure:** Search for top-level directories (e.g., `*/` pattern) to understand the project layout
135 - **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)
136 - **File distribution:** Search for files matching patterns like `src/**/*.ts`, `**/*.py` to gauge the size and shape of different areas
137 - **Key documentation:** Read `README.md`, `CLAUDE.md`, or similar docs if they exist for project context
138 - **For feature-focused analysis:** Search file contents for feature-related terms (function names, component names, route paths) to find hotspot directories
139 - **For general analysis:** Identify the 3-5 largest or most architecturally significant directories
140
141 **Fallback:** If reconnaissance fails (empty project, unusual structure, errors), use the static focus area templates from Step 3b.
142
1433. **Generate dynamic focus areas:**
144
145 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).
146
147 **a) Dynamic focus areas (default):**
148
149 Each focus area should include:
150 - **Label:** Short description (e.g., "API layer in src/api/")
151 - **Directories:** Specific directories to explore
152 - **Starting files:** 2-3 key files to read first
153 - **Search terms:** Patterns to find related code
154 - **Complexity estimate:** Low/Medium/High based on file count and apparent structure
155
156 For feature-focused analysis, focus areas should track the feature's actual footprint:
157 ```
158 Example:
159 Focus 1: "API routes and middleware in src/api/ and src/middleware/" (auth-related endpoints, request handling)
160 Focus 2: "React components in src/pages/profile/ and src/components/user/" (UI layer for user profiles)
161 Focus 3: "Data models and services in src/db/ and src/services/" (persistence and business logic)
162 ```
163
164 For general analysis, focus areas should map to the codebase's actual structure:
165 ```
166 Example:
167 Focus 1: "Next.js app layer in apps/web/src/" (pages, components, app router)
168 Focus 2: "Shared library in packages/core/src/" (utilities, types, shared logic)
169 Focus 3: "CLI and tooling in packages/cli/" (commands, configuration, build)
170 ```
171
172 **b) Static fallback focus areas** (only if recon failed):
173
174 For feature-focused analysis:
175 ```
176 Focus 1: Explore entry points and user-facing code related to the context
177 Focus 2: Explore data models, schemas, and storage related to the context
178 Focus 3: Explore utilities, helpers, and shared infrastructure
179 ```
180
181 For general codebase understanding:
182 ```
183 Focus 1: Explore application structure, entry points, and core logic
184 Focus 2: Explore configuration, infrastructure, and shared utilities
185 Focus 3: Explore shared utilities, patterns, and cross-cutting concerns
186 ```
187
1884. **Compose the team plan:**
189
190 Assemble a structured plan document from the reconnaissance and focus area findings:
191
192 ```markdown
193 ## Team Plan: Deep Analysis
194
195 ### Analysis Context
196 [context from Step 1]
197
198 ### Reconnaissance Summary
199 - **Project:** [name/type]
200 - **Primary language/framework:** [detected]
201 - **Codebase size:** [file counts, key directories]
202 - **Key observations:** [2-3 bullets]
203
204 ### Focus Areas
205
206 #### Focus Area 1: [Label]
207 - **Directories:** [list]
208 - **Starting files:** [2-3 files]
209 - **Search patterns:** [patterns]
210 - **Complexity:** [Low/Medium/High]
211 - **Assigned to:** explorer-1
212
213 #### Focus Area 2: [Label]
214 - **Directories:** [list]
215 - **Starting files:** [2-3 files]
216 - **Search patterns:** [patterns]
217 - **Complexity:** [Low/Medium/High]
218 - **Assigned to:** explorer-2
219
220 [... repeated for each focus area]
221
222 ### Agent Composition
223 | Role | Count | Purpose |
224 |------|-------|---------|
225 | Explorer | [N] | Independent focus area exploration |
226 | Synthesizer | 1 | Merge findings, deep investigation |
227
228 ### Task Dependencies
229 - Exploration Tasks 1-[N]: parallel (no dependencies)
230 - Synthesis Task: blocked by all exploration tasks
231 ```
232
2335. **Checkpoint** (if `ENABLE_CHECKPOINTING = true`):
234 - Update `.agents/sessions/__da_live__/checkpoint.md`: set `current_phase: 1`
235 - Write `.agents/sessions/__da_live__/team_plan.md` with the full team plan from Step 4
236 - Write `.agents/sessions/__da_live__/recon_summary.md` with reconnaissance findings from Step 2
237 - Append to `progress.md`: `[timestamp] Phase 1: Reconnaissance complete -- [N] focus areas identified`
238
239---
240
241## Phase 2: Review & Approval
242
243**Goal:** Present the team plan for user review and approval before allocating resources.
244
245> If `ENABLE_PROGRESS = true`: Display "[Phase 2/6] Review & Approval -- Presenting team plan..."
246
247### If `REQUIRE_APPROVAL = false`
248
249Skip to Phase 3 with a brief note: "Auto-approving team plan (skill-invoked mode). Proceeding with [N] explorers and 1 synthesizer."
250
251### If `REQUIRE_APPROVAL = true`
252
2531. **Present the team plan** to the user (output the plan from Phase 1 Step 4), then prompt the user to choose:
254 - **Approve** -- Proceed to Phase 3 as-is
255 - **Modify** -- User describes changes (adjust focus areas, add/remove explorers, change scope)
256 - **Regenerate** -- Re-run reconnaissance with user feedback
257
2582. **If "Modify"** (up to 3 cycles):
259 - Ask what to change
260 - Apply modifications to the team plan (adjust focus areas, agent count, scope)
261 - Re-present the updated plan for approval
262 - If 3 modification cycles are exhausted, offer "Approve current plan" or "Abort analysis"
263
2643. **If "Regenerate"** (up to 2 cycles):
265 - Ask for feedback/new direction
266 - Return to Phase 1 Step 2 with the user's feedback incorporated
267 - Re-compose and re-present the team plan
268 - If 2 regeneration cycles are exhausted, offer "Approve current plan" or "Abort analysis"
269
2704. **Checkpoint** (if `ENABLE_CHECKPOINTING = true`):
271 - Update `.agents/sessions/__da_live__/checkpoint.md`: set `current_phase: 2`, record `approval_mode` (approved/auto-approved)
272 - Append to `progress.md`: `[timestamp] Phase 2: Plan approved (mode: [approval_mode])`
273
274---
275
276## Phase 3: Team Assembly
277
278**Goal:** Create the team, spawn agents, create tasks, and assign work using the approved plan.
279
280> If `ENABLE_PROGRESS = true`: Display "[Phase 3/6] Team Assembly -- Creating team and spawning agents..."
281
2821. **Create the team:**
283 - Create a team named `deep-analysis-{timestamp}` (e.g., `deep-analysis-1707300000`)
284 - Description: "Deep analysis of [analysis context]"
285
2862. **Spawn teammates:**
287 Delegate work to agents based on the approved plan:
288
289 - **N explorers** (one per focus area) -- use code-explorer agent type (lightweight/fast model recommended)
290 - Named: `explorer-1`, `explorer-2`, ... `explorer-N`
291 - Instruct each with: "You are part of a deep analysis team. Wait for your task assignment. The codebase is at: [PATH]. Analysis context: [context]"
292
293 - **1 synthesizer** -- use code-synthesizer agent type (high-reasoning model recommended)
294 - Named: `synthesizer`
295 - Instruct with: "You are the synthesizer for a deep analysis team. You have command-line access for git history, dependency analysis, and static analysis. Wait for your task assignment. The codebase is at: [PATH]. Analysis context: [context]"
296
2973. **Create tasks:**
298 Create a task for each unit of work based on the approved plan's focus areas:
299
300 - **Exploration Task per focus area:** Subject: "Explore: [Focus area label]", Description: detailed exploration instructions including directories, starting files, search terms, and complexity estimate
301 - **Synthesis Task:** Subject: "Synthesize and evaluate exploration findings", Description: "Merge and synthesize findings from all exploration tasks into a unified analysis. Investigate gaps using command-line tools (git history, dependency trees). Evaluate completeness before finalizing."
302 - The synthesis task is blocked by all exploration task IDs
303
3044. **Assign exploration tasks (with status guard):**
305
306 For each exploration task, apply the following status-guarded assignment:
307
308 1. Check the task's current status and owner
309 2. **Only assign if** status is `pending` AND owner is empty
310 3. If already assigned or completed: log "Task [ID] already [status], skipping" and move on
311 4. Set the owner to the corresponding explorer
312 5. Send the explorer a message with the task details:
313 "Your exploration task [ID] is assigned. Focus area: [label]. Directories: [list]. Starting files: [list]. Search patterns: [list]. Begin exploration now."
314
315 **Never re-assign a completed or in-progress task.**
316
3175. **Checkpoint** (if `ENABLE_CHECKPOINTING = true`):
318 - Update `.agents/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`
319 - Append to `progress.md`: `[timestamp] Phase 3: Team assembled -- [N] explorers, 1 synthesizer`
320
321---
322
323## Phase 4: Focused Exploration
324
325**Goal:** Workers explore their assigned areas independently.
326
327> If `ENABLE_PROGRESS = true`: Display "[Phase 4/6] Focused Exploration -- 0/[N] explorers complete"
328
329### Monitoring Loop
330
331After assigning exploration tasks, monitor progress with status-aware tracking:
332
3331. When an explorer goes idle or sends a message, check their task status
3342. **If task is `completed`**: Record the explorer's findings. If `ENABLE_CHECKPOINTING = true`, write `explorer-{N}-findings.md` to `.agents/sessions/__da_live__/` and update checkpoint.
3353. **If task is `in_progress`**: The explorer is still working -- do NOT re-send the assignment
3364. **If task is `pending` and owner is set**: The explorer received the assignment but hasn't started yet -- wait, do NOT re-send
3375. **If task is `pending` and owner is empty**: Assignment may have been lost -- re-assign using the status guard from Phase 3 step 4
338
339**Never re-assign a completed or in-progress task.** This is the primary duplicate prevention mechanism.
340
341If `ENABLE_PROGRESS = true`: Update the progress display as explorers complete: "[Phase 4/6] Focused Exploration -- [completed]/[N] explorers complete"
342
343- Workers explore their assigned focus areas independently -- no cross-worker messaging
344- Workers can respond to follow-up questions from the synthesizer
345- Each worker marks its task as completed when done
346- You (the lead) receive idle notifications as workers finish
347- **Wait for all exploration tasks to be marked complete** before proceeding to Phase 5
348
349---
350
351## Phase 5: Evaluation and Synthesis
352
353**Goal:** Verify exploration completeness, launch synthesis with deep investigation.
354
355> If `ENABLE_PROGRESS = true`: Display "[Phase 5/6] Synthesis -- Merging findings and investigating gaps..."
356
357### Step 1: Structural Completeness Check
358
359This is a structural check, not a quality assessment:
360
3611. Verify all exploration tasks are completed
3622. Check that each worker produced a report with content (review the messages/reports received)
3633. **If a worker failed completely** (empty or error output):
364 - Create a follow-up exploration task targeting the gap
365 - Assign it to an idle worker
366 - Add the new task to the synthesis task's blocked-by list
367 - Wait for the follow-up task to complete
3684. **If all produced content**: proceed immediately to Step 2
369
370### Step 2: Launch Synthesis
371
3721. Assign the synthesis task to the synthesizer
3732. Send the synthesizer a message with exploration context and recon findings:
374 "All exploration tasks are complete. Your synthesis task is now assigned.
375
376 Analysis context: [analysis context]
377 Codebase path: [PATH]
378
379 Recon findings from planning phase:
380 - Project structure: [brief summary of directory layout]
381 - Primary language/framework: [what was detected]
382 - Key areas identified: [the focus areas and why they were chosen]
383
384 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.
385
386 You have command-line 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.
387
388 Read the completed exploration tasks to access their reports, then synthesize into a unified analysis. Evaluate completeness before finalizing."
3893. Wait for the synthesizer to mark the synthesis task as completed
390
3914. **Checkpoint** (if `ENABLE_CHECKPOINTING = true`):
392 - Update `.agents/sessions/__da_live__/checkpoint.md`: set `current_phase: 5`
393 - Write `.agents/sessions/__da_live__/synthesis.md` with the synthesis results
394 - Append to `progress.md`: `[timestamp] Phase 5: Synthesis complete`
395
396---
397
398## Phase 6: Completion + Cleanup
399
400**Goal:** Collect results, present to user, and tear down the team.
401
402> If `ENABLE_PROGRESS = true`: Display "[Phase 6/6] Completion -- Collecting results and cleaning up..."
403
4041. **Collect synthesis output:**
405 - The synthesizer's findings are in the messages it sent and/or the task completion output
406 - Read the synthesis results
407
4082. **Write exploration cache** (if `CACHE_TTL > 0`):
409 - Create `.agents/sessions/exploration-cache/` directory (overwrite if exists)
410 - Write `manifest.md`:
411 ```markdown
412 ## Exploration Cache Manifest
413 - **analysis_context**: [the analysis context used]
414 - **codebase_path**: [current working directory]
415 - **timestamp**: [ISO timestamp]
416 - **config_checksum**: [comma-separated list of config files and their mod-times]
417 - **ttl_hours**: [CACHE_TTL value]
418 - **explorer_count**: [N]
419 ```
420 - Write `synthesis.md` with the full synthesis output
421 - Write `recon_summary.md` with the Phase 1 reconnaissance findings
422 - Write `explorer-{N}-findings.md` for each explorer's findings (if not already persisted from Phase 4 checkpoints)
423
4243. **Present or return results:**
425 - **Standalone invocation:** Present the synthesized analysis to the user. The results remain in conversation memory for follow-up questions.
426 - **Loaded by another skill:** The synthesis is complete. Control returns to the calling workflow -- do not present a standalone summary.
427
4284. **Shutdown teammates:**
429 Send shutdown requests to all spawned teammates (iterate over the actual agents from the approved plan):
430 - Shut down each explorer
431 - Shut down the synthesizer
432
4335. **Archive session and cleanup team:**
434 - If `ENABLE_CHECKPOINTING = true`: Move `.agents/sessions/__da_live__/` to `.agents/sessions/da-{timestamp}/`
435 - Delete the team and its task list
436
437---
438
439## Error Handling
440
441### Settings Check Failure
442- If the settings file exists but is malformed or the `deep-analysis` section is unparseable: warn the user ("Settings file found but could not parse deep-analysis settings -- using defaults") and proceed with default approval values.
443
444### Planning Phase Failure
445- If reconnaissance fails (errors, empty results, unusual structure): fall back to static focus area templates (Step 3b)
446- If the codebase appears empty: inform the user and ask how to proceed
447
448### Approval Phase Failure
449- If maximum modification cycles (3) or regeneration cycles (2) are reached without approval, prompt the user to choose:
450 - **Approve current plan** -- Proceed with the latest version of the plan
451 - **Abort analysis** -- Cancel the analysis entirely
452
453### Partial Worker Failure
454- If one worker fails: create a follow-up task targeting the missed focus area, assign to an idle worker, add to synthesis blocked-by list
455- If two workers fail: attempt follow-ups, but if they also fail, instruct the synthesizer to work with partial results
456- If all workers fail: inform the user and offer to retry or abort
457
458### Synthesizer Failure
459- If the synthesizer fails: present the raw exploration results to the user directly
460- Offer to retry synthesis or let the user work with partial results
461
462### General Failures
463If any phase fails:
4641. Explain what went wrong
4652. Ask the user how to proceed:
466 - Retry the phase
467 - Continue with partial results
468 - Abort the analysis
469
470### Session Recovery
471
472When resuming from an interrupted session (detected in Phase 0 Step 2), use the following per-phase strategy:
473
474| Interrupted At | Recovery Strategy |
475|----------------|-------------------|
476| **Phase 1** | Restart from Phase 1 (reconnaissance is fast, ~1-2 min) |
477| **Phase 2** | Load saved `team_plan.md` from session dir, re-present for approval |
478| **Phase 3** | Load approved plan from checkpoint, restart team assembly |
479| **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. |
480| **Phase 5** | Load all explorer findings from session dir. Spawn a fresh synthesizer and launch synthesis with the persisted findings. |
481| **Phase 6** | Load `synthesis.md` from session dir. Proceed directly to present/return results and cleanup. |
482
483**Recovery procedure:**
4841. Read `checkpoint.md` to determine `last_completed_phase` and session state (team_name, explorer_names, task_ids)
4852. Load any persisted artifacts from the session directory (team_plan, explorer findings, synthesis)
4863. Resume from Phase `last_completed_phase + 1` using the loaded state
4874. For Phase 4 recovery: compare persisted `explorer-{N}-findings.md` files against expected explorer list to determine which explorers still need to run
488
489---
490
491## Agent Coordination
492
493- The lead (you) acts as the planner: performs recon, composes the team plan, handles approval, assigns work
494- Workers explore independently -- no cross-worker messaging (hub-and-spoke topology)
495- The synthesizer can ask workers follow-up questions to resolve conflicts and fill gaps
496- The synthesizer has command-line access for deep investigation (git history, dependency trees, static analysis)
497- Wait for task dependencies to resolve before proceeding
498- Handle agent failures gracefully -- continue with partial results
499- Agent count and focus area details come from the approved plan, not hardcoded values
500
501When delegating to teammates:
502- Use a high-reasoning model for the synthesizer
503- Use a lightweight/fast model for workers
504- Always associate agents with the team
505
506---
507
508## Integration Notes
509**What this component does:** Orchestrates a multi-agent hub-and-spoke codebase exploration workflow -- a lead performs reconnaissance and planning, N explorer workers investigate focus areas in parallel, and a synthesizer merges findings with deep investigation capabilities.
510**Capabilities needed:** File reading, file searching (by name pattern and content), command-line execution, multi-agent orchestration (team creation, task management, inter-agent messaging), user interaction prompts
511**Adaptation guidance:** The core workflow (recon, plan, explore, synthesize) is platform-agnostic. Adapt the team/task management primitives to your platform's agent orchestration API. Session checkpointing writes to `.agents/sessions/` and can be adapted to any persistent storage.
512**Configurable parameters:** `direct-invocation-approval` (default: true), `invocation-by-skill-approval` (default: false), `cache-ttl-hours` (default: 24), `enable-checkpointing` (default: true), `enable-progress-indicators` (default: true)