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 shell-powered investigation.
This skill can be invoked standalone or loaded by other skills as a reusable building block. Approval behavior is configurable.
Accept the following inputs:
- analysis-context (optional): The focus area, feature, or question to analyze. Defaults to "general codebase understanding" if not provided.
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 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 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 analysis-context input is provided, use it as the analysis context (feature area, question, or general exploration goal)
- If no input and this skill was loaded by another skill, use the calling skill's context
- If no input 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:
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: Search 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:** [search patterns]
- **Complexity:** [Low/Medium/High]
- **Assigned to:** explorer-1
#### Focus Area 2: [Label]
- **Directories:** [list]
- **Starting files:** [2-3 files]
- **Search patterns:** [search 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: Assemble a team of agents, create tasks, and assign work using the approved plan.
If ENABLE_PROGRESS = true: Display "[Phase 3/6] Team Assembly — Creating team and assigning agents..."
Assemble the team:
- Create a team named
deep-analysis-{timestamp} (e.g., deep-analysis-1707300000)
- Description: "Deep analysis of [analysis context]"
Delegate to teammates:
Based on the approved plan, assign teammates:
Track sub-tasks:
Create a task for each work item 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 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
- Communicate the task details to the explorer:
"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
- The lead receives 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
Communicate the exploration context and recon findings to the synthesizer:
"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 command 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 disband 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.
Archive session and disband the team:
- If
ENABLE_CHECKPOINTING = true: Move .agents/sessions/__da_live__/ to .agents/sessions/da-{timestamp}/
- Disband the team and its task list
Error Handling
Settings Check Failure
- If
.agents/agent-alchemy.local.md 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 assign explorers whose findings files are missing. Add existing findings to synthesizer context. |
| Phase 5 |
Load all explorer findings from session dir. Start 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 command 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 using hub-and-spoke coordination with dynamic planning, caching, and session recovery.
Capabilities needed:
- File reading, file search, and content search (for reconnaissance)
- Shell command execution (for the synthesizer's deep investigation)
- Agent/sub-task spawning (to create explorer and synthesizer workers)
- Inter-agent messaging (hub-and-spoke communication)
- Task tracking (to manage exploration and synthesis tasks)
- File writing (for session checkpoints and cache)
Adaptation guidance:
- This skill originally spawned code-explorer (sonnet-tier) and code-synthesizer (opus-tier) as sub-agents via a team/task system. In the target harness, adapt to whatever agent spawning or background task mechanism is available.
- The hub-and-spoke pattern means the lead coordinates all workers; workers never communicate with each other directly.
- If the target harness doesn't support agent teams, this workflow can be serialized: run each exploration focus area sequentially, then run synthesis on the collected findings.
- Session checkpointing writes to
.agents/sessions/ — adapt the path to the target harness's session storage.
Configurable parameters:
deep-analysis.direct-invocation-approval — Whether to require plan approval when invoked directly (default: true)
deep-analysis.invocation-by-skill-approval — Whether to require approval when loaded by another skill (default: false)
deep-analysis.cache-ttl-hours — Hours before exploration cache expires; 0 disables caching (default: 24)
deep-analysis.enable-checkpointing — Write session checkpoints at phase boundaries for recovery (default: true)
deep-analysis.enable-progress-indicators — Display progress messages during execution (default: true)
1---2name: deep-analysis-163description: 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 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
12Accept the following inputs:
13- **analysis-context** (optional): The focus area, feature, or question to analyze. Defaults to "general codebase understanding" if not provided.
14
15## Settings Check
16
17**Goal:** Determine whether the team plan requires user approval before execution.
18
191. **Read settings file:**
20 - Check if `.agents/agent-alchemy.local.md` exists
21 - If it exists, read it and look for a `deep-analysis` section with nested settings:
22 ```markdown
23 - **deep-analysis**:
24 - **direct-invocation-approval**: true
25 - **invocation-by-skill-approval**: false
26 ```
27 - If the file does not exist or is malformed, use defaults (see step 4)
28
292. **Determine invocation mode:**
30 - **Direct invocation:** The user invoked deep-analysis directly, or it is running standalone
31 - **Skill-invoked:** Another skill (e.g., codebase-analysis, feature-dev, docs-manager) loaded and is executing this workflow
32
333. **Resolve settings:**
34 - If settings were found, use them as-is
35 - If the file is missing or the `deep-analysis` section is absent, use defaults:
36 - `direct-invocation-approval`: `true`
37 - `invocation-by-skill-approval`: `false`
38 - If the file exists but is malformed (unparseable), warn the user and use defaults
39
404. **Set `REQUIRE_APPROVAL`:**
41 - If direct invocation: use `direct-invocation-approval` value (default: `true`)
42 - If skill-invoked: use `invocation-by-skill-approval` value (default: `false`)
43
445. **Parse session settings** (also under the `deep-analysis` section):
45 ```markdown
46 - **deep-analysis**:
47 - **cache-ttl-hours**: 24
48 - **enable-checkpointing**: true
49 - **enable-progress-indicators**: true
50 ```
51 - `cache-ttl-hours`: Number of hours before exploration cache expires. Default: `24`. Set to `0` to disable caching entirely.
52 - `enable-checkpointing`: Whether to write session checkpoints at phase boundaries. Default: `true`.
53 - `enable-progress-indicators`: Whether to display `[Phase N/6]` progress messages. Default: `true`.
54
556. **Set behavioral flags:**
56 - `CACHE_TTL` = value of `cache-ttl-hours` (default: `24`)
57 - `ENABLE_CHECKPOINTING` = value of `enable-checkpointing` (default: `true`)
58 - `ENABLE_PROGRESS` = value of `enable-progress-indicators` (default: `true`)
59
60---
61
62## Phase 0: Session Setup
63
64**Goal:** Check for cached exploration results, detect interrupted sessions, and initialize the session directory.
65
66> Skip this phase entirely if `CACHE_TTL = 0` AND `ENABLE_CHECKPOINTING = false`.
67
68### Step 1: Exploration Cache Check
69
70If `CACHE_TTL > 0`:
71
721. Check if `.agents/sessions/exploration-cache/manifest.md` exists
732. If found, read the manifest and verify:
74 - `analysis_context` matches the current analysis context (or is a superset)
75 - `codebase_path` matches the current working directory
76 - `timestamp` is within `CACHE_TTL` hours of now
77 - 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.)
783. **If cache is valid:**
79 - **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).
80 - **Direct invocation:** Prompt the user to choose:
81 - **"Use cached results"** — Set `CACHE_HIT = true`, skip to Phase 6 step 2
82 - **"Refresh analysis"** — Set `CACHE_HIT = false`, proceed normally
834. **If cache is invalid or absent:** Set `CACHE_HIT = false`
84
85### Step 2: Interrupted Session Check
86
87If `ENABLE_CHECKPOINTING = true`:
88
891. Check if `.agents/sessions/__da_live__/checkpoint.md` exists
902. If found, read the checkpoint to determine `last_completed_phase`
913. Prompt the user to choose:
92 - **"Resume from Phase [N+1]"** — Load checkpoint state, proceed from the interrupted phase (see Session Recovery in Error Handling)
93 - **"Start fresh"** — Archive the interrupted session to `.agents/sessions/da-interrupted-{timestamp}/` and proceed normally
944. If not found: proceed normally
95
96### Step 3: Initialize Session Directory
97
98If `ENABLE_CHECKPOINTING = true` AND `CACHE_HIT = false`:
99
1001. Create `.agents/sessions/__da_live__/` directory
1012. Write `checkpoint.md`:
102 ```markdown
103 ## Deep Analysis Session
104 - **analysis_context**: [context from arguments or caller]
105 - **codebase_path**: [current working directory]
106 - **started**: [ISO timestamp]
107 - **current_phase**: 0
108 - **status**: initialized
109 ```
1103. Write `progress.md`:
111 ```markdown
112 ## Deep Analysis Progress
113 - **Phase**: 0 of 6
114 - **Status**: Session initialized
115
116 ### Phase Log
117 - [timestamp] Phase 0: Session initialized
118 ```
119
120---
121
122## Phase 1: Reconnaissance & Planning
123
124**Goal:** Perform codebase reconnaissance, generate dynamic focus areas, and compose a team plan.
125
126> If `ENABLE_PROGRESS = true`: Display "**[Phase 1/6] Reconnaissance & Planning** — Mapping codebase structure..."
127
1281. **Determine analysis context:**
129 - If analysis-context input is provided, use it as the analysis context (feature area, question, or general exploration goal)
130 - If no input and this skill was loaded by another skill, use the calling skill's context
131 - If no input and standalone invocation, set context to "general codebase understanding"
132 - Set `PATH = current working directory`
133 - Inform the user: "Exploring codebase at: `PATH`" with the analysis context
134
1352. **Rapid codebase reconnaissance:**
136 Quickly map the codebase structure. This should take 1-2 minutes, not deep investigation.
137
138 - **Directory structure:** Search for top-level directories (e.g., `*/` pattern) to understand the project layout
139 - **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)
140 - **File distribution:** Search for files matching patterns like `src/**/*.ts`, `**/*.py` to gauge the size and shape of different areas
141 - **Key documentation:** Read `README.md`, `CLAUDE.md`, or similar docs if they exist for project context
142 - **For feature-focused analysis:** Search file contents for feature-related terms (function names, component names, route paths) to find hotspot directories
143 - **For general analysis:** Identify the 3-5 largest or most architecturally significant directories
144
145 **Fallback:** If reconnaissance fails (empty project, unusual structure, errors), use the static focus area templates from Step 3b.
146
1473. **Generate dynamic focus areas:**
148
149 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).
150
151 **a) Dynamic focus areas (default):**
152
153 Each focus area should include:
154 - **Label:** Short description (e.g., "API layer in src/api/")
155 - **Directories:** Specific directories to explore
156 - **Starting files:** 2-3 key files to read first
157 - **Search terms:** Search patterns to find related code
158 - **Complexity estimate:** Low/Medium/High based on file count and apparent structure
159
160 For feature-focused analysis, focus areas should track the feature's actual footprint:
161 ```
162 Example:
163 Focus 1: "API routes and middleware in src/api/ and src/middleware/" (auth-related endpoints, request handling)
164 Focus 2: "React components in src/pages/profile/ and src/components/user/" (UI layer for user profiles)
165 Focus 3: "Data models and services in src/db/ and src/services/" (persistence and business logic)
166 ```
167
168 For general analysis, focus areas should map to the codebase's actual structure:
169 ```
170 Example:
171 Focus 1: "Next.js app layer in apps/web/src/" (pages, components, app router)
172 Focus 2: "Shared library in packages/core/src/" (utilities, types, shared logic)
173 Focus 3: "CLI and tooling in packages/cli/" (commands, configuration, build)
174 ```
175
176 **b) Static fallback focus areas** (only if recon failed):
177
178 For feature-focused analysis:
179 ```
180 Focus 1: Explore entry points and user-facing code related to the context
181 Focus 2: Explore data models, schemas, and storage related to the context
182 Focus 3: Explore utilities, helpers, and shared infrastructure
183 ```
184
185 For general codebase understanding:
186 ```
187 Focus 1: Explore application structure, entry points, and core logic
188 Focus 2: Explore configuration, infrastructure, and shared utilities
189 Focus 3: Explore shared utilities, patterns, and cross-cutting concerns
190 ```
191
1924. **Compose the team plan:**
193
194 Assemble a structured plan document from the reconnaissance and focus area findings:
195
196 ```markdown
197 ## Team Plan: Deep Analysis
198
199 ### Analysis Context
200 [context from Step 1]
201
202 ### Reconnaissance Summary
203 - **Project:** [name/type]
204 - **Primary language/framework:** [detected]
205 - **Codebase size:** [file counts, key directories]
206 - **Key observations:** [2-3 bullets]
207
208 ### Focus Areas
209
210 #### Focus Area 1: [Label]
211 - **Directories:** [list]
212 - **Starting files:** [2-3 files]
213 - **Search patterns:** [search patterns]
214 - **Complexity:** [Low/Medium/High]
215 - **Assigned to:** explorer-1
216
217 #### Focus Area 2: [Label]
218 - **Directories:** [list]
219 - **Starting files:** [2-3 files]
220 - **Search patterns:** [search patterns]
221 - **Complexity:** [Low/Medium/High]
222 - **Assigned to:** explorer-2
223
224 [... repeated for each focus area]
225
226 ### Agent Composition
227 | Role | Count | Purpose |
228 |------|-------|---------|
229 | Explorer | [N] | Independent focus area exploration |
230 | Synthesizer | 1 | Merge findings, deep investigation |
231
232 ### Task Dependencies
233 - Exploration Tasks 1-[N]: parallel (no dependencies)
234 - Synthesis Task: blocked by all exploration tasks
235 ```
236
2375. **Checkpoint** (if `ENABLE_CHECKPOINTING = true`):
238 - Update `.agents/sessions/__da_live__/checkpoint.md`: set `current_phase: 1`
239 - Write `.agents/sessions/__da_live__/team_plan.md` with the full team plan from Step 4
240 - Write `.agents/sessions/__da_live__/recon_summary.md` with reconnaissance findings from Step 2
241 - Append to `progress.md`: `[timestamp] Phase 1: Reconnaissance complete — [N] focus areas identified`
242
243---
244
245## Phase 2: Review & Approval
246
247**Goal:** Present the team plan for user review and approval before allocating resources.
248
249> If `ENABLE_PROGRESS = true`: Display "**[Phase 2/6] Review & Approval** — Presenting team plan..."
250
251### If `REQUIRE_APPROVAL = false`
252
253Skip to Phase 3 with a brief note: "Auto-approving team plan (skill-invoked mode). Proceeding with [N] explorers and 1 synthesizer."
254
255### If `REQUIRE_APPROVAL = true`
256
2571. **Present the team plan** to the user (output the plan from Phase 1 Step 4), then prompt the user to choose:
258 - **"Approve"** — Proceed to Phase 3 as-is
259 - **"Modify"** — User describes changes (adjust focus areas, add/remove explorers, change scope)
260 - **"Regenerate"** — Re-run reconnaissance with user feedback
261
2622. **If "Modify"** (up to 3 cycles):
263 - Ask what to change
264 - Apply modifications to the team plan (adjust focus areas, agent count, scope)
265 - Re-present the updated plan for approval
266 - If 3 modification cycles are exhausted, offer "Approve current plan" or "Abort analysis"
267
2683. **If "Regenerate"** (up to 2 cycles):
269 - Ask for feedback/new direction
270 - Return to Phase 1 Step 2 with the user's feedback incorporated
271 - Re-compose and re-present the team plan
272 - If 2 regeneration cycles are exhausted, offer "Approve current plan" or "Abort analysis"
273
2744. **Checkpoint** (if `ENABLE_CHECKPOINTING = true`):
275 - Update `.agents/sessions/__da_live__/checkpoint.md`: set `current_phase: 2`, record `approval_mode` (approved/auto-approved)
276 - Append to `progress.md`: `[timestamp] Phase 2: Plan approved (mode: [approval_mode])`
277
278---
279
280## Phase 3: Team Assembly
281
282**Goal:** Assemble a team of agents, create tasks, and assign work using the approved plan.
283
284> If `ENABLE_PROGRESS = true`: Display "**[Phase 3/6] Team Assembly** — Creating team and assigning agents..."
285
2861. **Assemble the team:**
287 - Create a team named `deep-analysis-{timestamp}` (e.g., `deep-analysis-1707300000`)
288 - Description: "Deep analysis of [analysis context]"
289
2902. **Delegate to teammates:**
291 Based on the approved plan, assign teammates:
292
293 - **N explorers** (one per focus area) — using the **code-explorer** skill
294 - Named: `explorer-1`, `explorer-2`, ... `explorer-N`
295 - Prompt each with: "You are part of a deep analysis team. Wait for your task assignment. The codebase is at: [PATH]. Analysis context: [context]"
296
297 - **1 synthesizer** — using the **code-synthesizer** skill
298 - Named: `synthesizer`
299 - Prompt with: "You are the synthesizer for a deep analysis team. You have shell command access for git history, dependency analysis, and static analysis. Wait for your task assignment. The codebase is at: [PATH]. Analysis context: [context]"
300
3013. **Track sub-tasks:**
302 Create a task for each work item based on the approved plan's focus areas:
303
304 - **Exploration Task per focus area:** Subject: "Explore: [Focus area label]", Description: detailed exploration instructions including directories, starting files, search terms, and complexity estimate
305 - **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."
306 - The synthesis task is blocked by all exploration tasks
307
3084. **Assign exploration tasks (with status guard):**
309
310 For each exploration task, apply the following status-guarded assignment:
311
312 1. Check the task's current status and owner
313 2. **Only assign if** status is `pending` AND owner is empty
314 3. If already assigned or completed: log "Task [ID] already [status], skipping" and move on
315 4. Set the owner to the corresponding explorer
316 5. Communicate the task details to the explorer:
317 "Your exploration task [ID] is assigned. Focus area: [label]. Directories: [list]. Starting files: [list]. Search patterns: [list]. Begin exploration now."
318
319 **Never re-assign a completed or in-progress task.**
320
3215. **Checkpoint** (if `ENABLE_CHECKPOINTING = true`):
322 - 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`
323 - Append to `progress.md`: `[timestamp] Phase 3: Team assembled — [N] explorers, 1 synthesizer`
324
325---
326
327## Phase 4: Focused Exploration
328
329**Goal:** Workers explore their assigned areas independently.
330
331> If `ENABLE_PROGRESS = true`: Display "**[Phase 4/6] Focused Exploration** — 0/[N] explorers complete"
332
333### Monitoring Loop
334
335After assigning exploration tasks, monitor progress with status-aware tracking:
336
3371. When an explorer goes idle or sends a message, check their task status
3382. **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.
3393. **If task is `in_progress`**: The explorer is still working — do NOT re-send the assignment
3404. **If task is `pending` and owner is set**: The explorer received the assignment but hasn't started yet — wait, do NOT re-send
3415. **If task is `pending` and owner is empty**: Assignment may have been lost — re-assign using the status guard from Phase 3 step 4
342
343**Never re-assign a completed or in-progress task.** This is the primary duplicate prevention mechanism.
344
345If `ENABLE_PROGRESS = true`: Update the progress display as explorers complete: "**[Phase 4/6] Focused Exploration** — [completed]/[N] explorers complete"
346
347- Workers explore their assigned focus areas independently — no cross-worker messaging
348- Workers can respond to follow-up questions from the synthesizer
349- Each worker marks its task as completed when done
350- The lead receives idle notifications as workers finish
351- **Wait for all exploration tasks to be marked complete** before proceeding to Phase 5
352
353---
354
355## Phase 5: Evaluation and Synthesis
356
357**Goal:** Verify exploration completeness, launch synthesis with deep investigation.
358
359> If `ENABLE_PROGRESS = true`: Display "**[Phase 5/6] Synthesis** — Merging findings and investigating gaps..."
360
361### Step 1: Structural Completeness Check
362
363This is a structural check, not a quality assessment:
364
3651. Verify all exploration tasks are completed
3662. Check that each worker produced a report with content (review the messages/reports received)
3673. **If a worker failed completely** (empty or error output):
368 - Create a follow-up exploration task targeting the gap
369 - Assign it to an idle worker
370 - Add the new task to the synthesis task's blocked-by list
371 - Wait for the follow-up task to complete
3724. **If all produced content**: proceed immediately to Step 2
373
374### Step 2: Launch Synthesis
375
3761. Assign the synthesis task to the synthesizer
3772. Communicate the exploration context and recon findings to the synthesizer:
378 "All exploration tasks are complete. Your synthesis task is now assigned.
379
380 Analysis context: [analysis context]
381 Codebase path: [PATH]
382
383 Recon findings from planning phase:
384 - Project structure: [brief summary of directory layout]
385 - Primary language/framework: [what was detected]
386 - Key areas identified: [the focus areas and why they were chosen]
387
388 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.
389
390 You have shell command 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.
391
392 Read the completed exploration tasks to access their reports, then synthesize into a unified analysis. Evaluate completeness before finalizing."
3933. Wait for the synthesizer to mark the synthesis task as completed
394
3954. **Checkpoint** (if `ENABLE_CHECKPOINTING = true`):
396 - Update `.agents/sessions/__da_live__/checkpoint.md`: set `current_phase: 5`
397 - Write `.agents/sessions/__da_live__/synthesis.md` with the synthesis results
398 - Append to `progress.md`: `[timestamp] Phase 5: Synthesis complete`
399
400---
401
402## Phase 6: Completion + Cleanup
403
404**Goal:** Collect results, present to user, and disband the team.
405
406> If `ENABLE_PROGRESS = true`: Display "**[Phase 6/6] Completion** — Collecting results and cleaning up..."
407
4081. **Collect synthesis output:**
409 - The synthesizer's findings are in the messages it sent and/or the task completion output
410 - Read the synthesis results
411
4122. **Write exploration cache** (if `CACHE_TTL > 0`):
413 - Create `.agents/sessions/exploration-cache/` directory (overwrite if exists)
414 - Write `manifest.md`:
415 ```markdown
416 ## Exploration Cache Manifest
417 - **analysis_context**: [the analysis context used]
418 - **codebase_path**: [current working directory]
419 - **timestamp**: [ISO timestamp]
420 - **config_checksum**: [comma-separated list of config files and their mod-times]
421 - **ttl_hours**: [CACHE_TTL value]
422 - **explorer_count**: [N]
423 ```
424 - Write `synthesis.md` with the full synthesis output
425 - Write `recon_summary.md` with the Phase 1 reconnaissance findings
426 - Write `explorer-{N}-findings.md` for each explorer's findings (if not already persisted from Phase 4 checkpoints)
427
4283. **Present or return results:**
429 - **Standalone invocation:** Present the synthesized analysis to the user. The results remain in conversation memory for follow-up questions.
430 - **Loaded by another skill:** The synthesis is complete. Control returns to the calling workflow — do not present a standalone summary.
431
4324. **Archive session and disband the team:**
433 - If `ENABLE_CHECKPOINTING = true`: Move `.agents/sessions/__da_live__/` to `.agents/sessions/da-{timestamp}/`
434 - Disband the team and its task list
435
436---
437
438## Error Handling
439
440### Settings Check Failure
441- If `.agents/agent-alchemy.local.md` 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.
442
443### Planning Phase Failure
444- If reconnaissance fails (errors, empty results, unusual structure): fall back to static focus area templates (Step 3b)
445- If the codebase appears empty: inform the user and ask how to proceed
446
447### Approval Phase Failure
448- If maximum modification cycles (3) or regeneration cycles (2) are reached without approval, prompt the user to choose:
449 - **"Approve current plan"** — Proceed with the latest version of the plan
450 - **"Abort analysis"** — Cancel the analysis entirely
451
452### Partial Worker Failure
453- 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
454- If two workers fail: attempt follow-ups, but if they also fail, instruct the synthesizer to work with partial results
455- If all workers fail: inform the user and offer to retry or abort
456
457### Synthesizer Failure
458- If the synthesizer fails: present the raw exploration results to the user directly
459- Offer to retry synthesis or let the user work with partial results
460
461### General Failures
462If any phase fails:
4631. Explain what went wrong
4642. Ask the user how to proceed:
465 - Retry the phase
466 - Continue with partial results
467 - Abort the analysis
468
469### Session Recovery
470
471When resuming from an interrupted session (detected in Phase 0 Step 2), use the following per-phase strategy:
472
473| Interrupted At | Recovery Strategy |
474|----------------|-------------------|
475| **Phase 1** | Restart from Phase 1 (reconnaissance is fast, ~1-2 min) |
476| **Phase 2** | Load saved `team_plan.md` from session dir, re-present for approval |
477| **Phase 3** | Load approved plan from checkpoint, restart team assembly |
478| **Phase 4** | Read completed `explorer-{N}-findings.md` files from session dir. Only assign explorers whose findings files are missing. Add existing findings to synthesizer context. |
479| **Phase 5** | Load all explorer findings from session dir. Start a fresh synthesizer and launch synthesis with the persisted findings. |
480| **Phase 6** | Load `synthesis.md` from session dir. Proceed directly to present/return results and cleanup. |
481
482**Recovery procedure:**
4831. Read `checkpoint.md` to determine `last_completed_phase` and session state (team_name, explorer_names, task_ids)
4842. Load any persisted artifacts from the session directory (team_plan, explorer findings, synthesis)
4853. Resume from Phase `last_completed_phase + 1` using the loaded state
4864. For Phase 4 recovery: compare persisted `explorer-{N}-findings.md` files against expected explorer list to determine which explorers still need to run
487
488---
489
490## Agent Coordination
491
492- The lead (you) acts as the planner: performs recon, composes the team plan, handles approval, assigns work
493- Workers explore independently — no cross-worker messaging (hub-and-spoke topology)
494- The synthesizer can ask workers follow-up questions to resolve conflicts and fill gaps
495- The synthesizer has shell command access for deep investigation (git history, dependency trees, static analysis)
496- Wait for task dependencies to resolve before proceeding
497- Handle agent failures gracefully — continue with partial results
498- Agent count and focus area details come from the approved plan, not hardcoded values
499
500## Integration Notes
501
502**What this component does:** Orchestrates a multi-agent codebase exploration and synthesis workflow using hub-and-spoke coordination with dynamic planning, caching, and session recovery.
503
504**Capabilities needed:**
505- File reading, file search, and content search (for reconnaissance)
506- Shell command execution (for the synthesizer's deep investigation)
507- Agent/sub-task spawning (to create explorer and synthesizer workers)
508- Inter-agent messaging (hub-and-spoke communication)
509- Task tracking (to manage exploration and synthesis tasks)
510- File writing (for session checkpoints and cache)
511
512**Adaptation guidance:**
513- This skill originally spawned **code-explorer** (sonnet-tier) and **code-synthesizer** (opus-tier) as sub-agents via a team/task system. In the target harness, adapt to whatever agent spawning or background task mechanism is available.
514- The hub-and-spoke pattern means the lead coordinates all workers; workers never communicate with each other directly.
515- If the target harness doesn't support agent teams, this workflow can be serialized: run each exploration focus area sequentially, then run synthesis on the collected findings.
516- Session checkpointing writes to `.agents/sessions/` — adapt the path to the target harness's session storage.
517
518**Configurable parameters:**
519- `deep-analysis.direct-invocation-approval` — Whether to require plan approval when invoked directly (default: true)
520- `deep-analysis.invocation-by-skill-approval` — Whether to require approval when loaded by another skill (default: false)
521- `deep-analysis.cache-ttl-hours` — Hours before exploration cache expires; 0 disables caching (default: 24)
522- `deep-analysis.enable-checkpointing` — Write session checkpoints at phase boundaries for recovery (default: true)
523- `deep-analysis.enable-progress-indicators` — Display progress messages during execution (default: true)