
Review Cycle
- 66 installs
- 2.1k repo stars
- Updated June 18, 2026
- catlog22/claude-code-workflow
Review code and ensure quality standards
About
Automates code review and quality checks for review-cycle. Teams use this to enforce standards and catch issues early.
- Code quality
- Automated review
Review Cycle by the numbers
- 66 all-time installs (skills.sh)
- Ranked #528 of 1,352 Code Review & Quality skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/catlog22/claude-code-workflow --skill review-cycleAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 66 |
|---|---|
| repo stars | ★ 2.1k |
| Last updated | June 18, 2026 |
| Repository | catlog22/claude-code-workflow ↗ |
What it does
Review code and ensure quality standards
Files
Review Cycle
Unified code review orchestrator with mode-based routing. Detects input type and dispatches to the appropriate execution phase.
Architecture Overview
┌──────────────────────────────────────────────────────────┐
│ Review Cycle Orchestrator (SKILL.md) │
│ → Parse input → Detect mode → Read phase doc → Execute │
└───────────────────────────┬──────────────────────────────┘
│
┌─────────────────┼─────────────────┐
↓ ↓ ↓
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ session │ │ module │ │ fix │
│ (git changes│ │(path pattern│ │(export file │
│ review) │ │ review) │ │ auto-fix) │
└─────────────┘ └─────────────┘ └─────────────┘
phases/ phases/ phases/
review-session.md review-module.md review-fix.mdAuto Mode Detection
// ★ 统一 auto mode 检测:-y/--yes 从 $ARGUMENTS 或 ccw 传播
const autoYes = /\b(-y|--yes)\b/.test($ARGUMENTS)When autoYes is true, skip all interactive confirmations and use defaults throughout the review cycle phases.
Mode Detection
function detectMode(args) {
if (args.includes('--fix')) return 'fix';
if (args.match(/\*|\.ts|\.js|\.py|\.vue|\.jsx|\.tsx|src\/|lib\//)) return 'module';
if (args.match(/^WFS-/) || args.trim() === '') return 'session';
return 'session'; // default
}| Input Pattern | Detected Mode | Phase Doc |
|---|---|---|
src/auth/** | module | phases/review-module.md |
src/auth/**,src/payment/** | module | phases/review-module.md |
WFS-payment-integration | session | phases/review-session.md |
| _(empty)_ | session | phases/review-session.md |
--fix .review/ | fix | phases/review-fix.md |
--fix --resume | fix | phases/review-fix.md |
Usage
Skill(skill="review-cycle", args="src/auth/**") # Module mode
Skill(skill="review-cycle", args="src/auth/** --dimensions=security,architecture") # Module + custom dims
Skill(skill="review-cycle", args="WFS-payment-integration") # Session mode
Skill(skill="review-cycle", args="") # Session: auto-detect
Skill(skill="review-cycle", args="--fix .workflow/active/WFS-123/.review/") # Fix mode
Skill(skill="review-cycle", args="--fix --resume") # Fix: resume
Skill(skill="review-cycle", args="-y src/auth/**") # Auto mode (skip confirmations)
# Common flags (all modes):
--dimensions=dim1,dim2,... Custom dimensions (default: all 7)
--max-iterations=N Max deep-dive iterations (default: 3)
# Fix-only flags:
--fix Enter fix pipeline
--resume Resume interrupted fix session
--batch-size=N Findings per planning batch (default: 5)
--max-iterations=N Max retry per finding (default: 3)Execution Flow
1. Parse $ARGUMENTS → extract mode + flags
2. Detect mode (session | module | fix)
3. Read corresponding phase doc:
- session → Read phases/review-session.md → execute
- module → Read phases/review-module.md → execute
- fix → Read phases/review-fix.md → execute
4. Phase doc contains full execution detail (5 phases for review, 4+1 phases for fix)Phase Reference Documents (read on-demand based on detected mode):
| Mode | Document | Source | Description |
|---|---|---|---|
| session | phases/review-session.md | review-session-cycle.md | Session-based review: git changes → 7-dimension parallel analysis → aggregation → deep-dive → completion |
| module | phases/review-module.md | review-module-cycle.md | Module-based review: path patterns → 7-dimension parallel analysis → aggregation → deep-dive → completion |
| fix | phases/review-fix.md | review-cycle-fix.md | Automated fix: export file → intelligent batching → parallel planning → execution → completion |
Project Context
Run ccw spec load --category review for review standards, checklists, and approval gates.
Core Rules
1. Mode Detection First: Parse input to determine session/module/fix mode before anything else 2. Progressive Loading: Read ONLY the phase doc for the detected mode, not all three 3. Full Delegation: Once mode is detected, the phase doc owns the entire execution flow 4. Auto-Continue: Phase docs contain their own multi-phase execution (Phase 1-5 or Phase 1-4+5) 5. DO NOT STOP: Continuous execution until all internal phases within the phase doc complete
Error Handling
| Error | Action |
|---|---|
| Cannot determine mode from input | AskUserQuestion to clarify intent |
| Phase doc not found | Error and exit with file path |
| Invalid flags for mode | Warn and continue with defaults |
Related Commands
# View review/fix progress dashboard
ccw view
# Workflow pipeline
# Step 1: Review
Skill(skill="review-cycle", args="src/auth/**")
# Step 2: Fix (after review complete)
Skill(skill="review-cycle", args="--fix .workflow/active/WFS-{session-id}/.review/")Workflow Review-Cycle-Fix Command
Quick Start
# Fix from exported findings file (session-based path)
/workflow:review-cycle-fix .workflow/active/WFS-123/.review/fix-export-1706184622000.json
# Fix from review directory (auto-discovers latest export)
/workflow:review-cycle-fix .workflow/active/WFS-123/.review/
# Resume interrupted fix session
/workflow:review-cycle-fix --resume
# Custom max retry attempts per finding
/workflow:review-cycle-fix .workflow/active/WFS-123/.review/ --max-iterations=5
# Custom batch size for parallel planning (default: 5 findings per batch)
/workflow:review-cycle-fix .workflow/active/WFS-123/.review/ --batch-size=3Fix Source: Exported findings from review cycle dashboard Output Directory: {review-dir}/fixes/{fix-session-id}/ (within session .review/) Default Max Iterations: 3 (per finding, adjustable) Default Batch Size: 5 (findings per planning batch, adjustable) Max Parallel Agents: 10 (concurrent planning agents) CLI Tools: @cli-planning-agent (planning), @cli-execute-agent (fixing)
What & Why
Core Concept
Automated fix orchestrator with parallel planning architecture: Multiple AI agents analyze findings concurrently in batches, then coordinate parallel/serial execution. Generates fix timeline with intelligent grouping and dependency analysis, executes fixes with conservative test verification.
Fix Process:
- Batching Phase (1.5): Orchestrator groups findings by file+dimension similarity, creates batches
- Planning Phase (2): Up to 10 agents plan batches in parallel, generate partial plans, orchestrator aggregates
- Execution Phase (3): Main orchestrator coordinates agents per aggregated timeline stages
- Parallel Efficiency: Customizable batch size (default: 5), MAX_PARALLEL=10 agents
- No rigid structure: Adapts to task requirements, not bound to fixed JSON format
vs Manual Fixing:
- Manual: Developer reviews findings one-by-one, fixes sequentially
- Automated: AI groups related issues, multiple agents plan in parallel, executes in optimal parallel/serial order with automatic test verification
Value Proposition
1. Parallel Planning: Multiple agents analyze findings concurrently, reducing planning time for large batches (10+ findings) 2. Intelligent Batching: Semantic similarity grouping ensures related findings are analyzed together 3. Multi-stage Coordination: Supports complex parallel + serial execution with cross-batch dependency management 4. Conservative Safety: Mandatory test verification with automatic rollback on failure 5. Resume Support: Checkpoint-based recovery for interrupted sessions
Orchestrator Boundary (CRITICAL)
- ONLY command for automated review finding fixes
- Manages: Intelligent batching (Phase 1.5), parallel planning coordination (launch N agents), plan aggregation, stage-based execution, agent scheduling, progress tracking
- Delegates: Batch planning to @cli-planning-agent, fix execution to @cli-execute-agent
Execution Flow
Phase 1: Discovery & Initialization
└─ Validate export file, create fix session structure, initialize state files
Phase 1.5: Intelligent Grouping & Batching
├─ Analyze findings metadata (file, dimension, severity)
├─ Group by semantic similarity (file proximity + dimension affinity)
├─ Create batches respecting --batch-size (default: 5)
└─ Output: Finding batches for parallel planning
Phase 2: Parallel Planning Coordination (@cli-planning-agent × N)
├─ Launch MAX_PARALLEL planning agents concurrently (default: 10)
├─ Each agent processes one batch:
│ ├─ Analyze findings for patterns and dependencies
│ ├─ Group by file + dimension + root cause similarity
│ ├─ Determine execution strategy (parallel/serial/hybrid)
│ ├─ Generate fix timeline with stages
│ └─ Output: partial-plan-{batch-id}.json
├─ Collect results from all agents
└─ Aggregate: Merge partial plans → fix-plan.json (resolve cross-batch dependencies)
Phase 3: Execution Orchestration (Stage-based)
For each timeline stage:
├─ Load groups for this stage
├─ If parallel: Launch all group agents simultaneously
├─ If serial: Execute groups sequentially
├─ Each agent:
│ ├─ Analyze code context
│ ├─ Apply fix per strategy
│ ├─ Run affected tests
│ ├─ On test failure: Rollback, retry up to max_iterations
│ └─ On success: Commit, update fix-progress-{N}.json
└─ Advance to next stage
Phase 4: Completion & Aggregation
└─ Aggregate results → Generate fix-summary.md → Update history → Output summary
Phase 5: Session Completion (Optional)
└─ If all fixes successful → Prompt to complete workflow sessionAgent Roles
| Agent | Responsibility |
|---|---|
| Orchestrator | Input validation, session management, intelligent batching (Phase 1.5), parallel planning coordination (launch N agents), plan aggregation (merge partial plans, resolve cross-batch dependencies), stage-based execution scheduling, progress tracking, result aggregation |
| @cli-planning-agent | Batch findings analysis, intelligent grouping (file+dimension+root cause), execution strategy determination (parallel/serial/hybrid), timeline generation with dependency mapping, partial plan output |
| @cli-execute-agent | Fix execution per group, code context analysis, Edit tool operations, test verification, git rollback on failure, completion JSON generation |
Enhanced Features
1. Parallel Planning Architecture
Batch Processing Strategy:
| Phase | Agent Count | Input | Output | Purpose |
|---|---|---|---|---|
| Batching (1.5) | Orchestrator | All findings | Finding batches | Semantic grouping by file+dimension, respecting --batch-size |
| Planning (2) | N agents (≤10) | 1 batch each | partial-plan-{batch-id}.json | Analyze batch in parallel, generate execution groups and timeline |
| Aggregation (2) | Orchestrator | All partial plans | fix-plan.json | Merge timelines, resolve cross-batch dependencies |
| Execution (3) | M agents (dynamic) | 1 group each | fix-progress-{N}.json | Execute fixes per aggregated plan with test verification |
Benefits:
- Speed: N agents plan concurrently, reducing planning time for large batches
- Scalability: MAX_PARALLEL=10 prevents resource exhaustion
- Flexibility: Batch size customizable via --batch-size (default: 5)
- Isolation: Each planning agent focuses on related findings (semantic grouping)
- Reusable: Aggregated plan can be re-executed without re-planning
2. Intelligent Grouping Strategy
Three-Level Grouping:
// Level 1: Primary grouping by file + dimension
{file: "auth.ts", dimension: "security"} → Group A
{file: "auth.ts", dimension: "quality"} → Group B
{file: "query-builder.ts", dimension: "security"} → Group C
// Level 2: Secondary grouping by root cause similarity
Group A findings → Semantic similarity analysis (threshold 0.7)
→ Sub-group A1: "missing-input-validation" (findings 1, 2)
→ Sub-group A2: "insecure-crypto" (finding 3)
// Level 3: Dependency analysis
Sub-group A1 creates validation utilities
Sub-group C4 depends on those utilities
→ A1 must execute before C4 (serial stage dependency)Similarity Computation:
- Combine:
description + recommendation + category - Vectorize: TF-IDF or LLM embedding
- Cluster: Greedy algorithm with cosine similarity > 0.7
3. Execution Strategy Determination
Strategy Types:
| Strategy | When to Use | Stage Structure |
|---|---|---|
| Parallel | All groups independent, different files | Single stage, all groups in parallel |
| Serial | Strong dependencies, shared resources | Multiple stages, one group per stage |
| Hybrid | Mixed dependencies | Multiple stages, parallel within stages |
Dependency Detection:
- Shared file modifications
- Utility creation + usage patterns
- Test dependency chains
- Risk level clustering (high-risk groups isolated)
4. Conservative Test Verification
Test Strategy (per fix):
// 1. Identify affected tests
const testPattern = identifyTestPattern(finding.file);
// e.g., "tests/auth/**/*.test.*" for src/auth/service.ts
// 2. Run tests
const result = await runTests(testPattern);
// 3. Evaluate
if (result.passRate < 100%) {
// Rollback
await gitCheckout(finding.file);
// Retry with failure context
if (attempts < maxIterations) {
const fixContext = analyzeFailure(result.stderr);
regenerateFix(finding, fixContext);
retry();
} else {
markFailed(finding.id);
}
} else {
// Commit
await gitCommit(`Fix: ${finding.title} [${finding.id}]`);
markFixed(finding.id);
}Pass Criteria: 100% test pass rate (no partial fixes)
Core Responsibilities
Orchestrator
Phase 1: Discovery & Initialization
- Input validation: Check export file exists and is valid JSON
- Auto-discovery: If review-dir provided, find latest
*-fix-export.json - Session creation: Generate fix-session-id (
fix-{timestamp}) - Directory structure: Create
{review-dir}/fixes/{fix-session-id}/with subdirectories - State files: Initialize active-fix-session.json (session marker)
- TodoWrite initialization: Set up 5-phase tracking (including Phase 1.5)
Phase 1.5: Intelligent Grouping & Batching
- Load all findings metadata (id, file, dimension, severity, title)
- Semantic similarity analysis:
- Primary: Group by file proximity (same file or related modules)
- Secondary: Group by dimension affinity (same review dimension)
- Tertiary: Analyze title/description similarity (root cause clustering)
- Create batches respecting --batch-size (default: 5 findings per batch)
- Balance workload: Distribute high-severity findings across batches
- Output: Array of finding batches for parallel planning
Phase 2: Parallel Planning Coordination
- Determine concurrency: MIN(batch_count, MAX_PARALLEL=10)
- For each batch chunk (≤10 batches):
- Launch all agents in parallel with run_in_background=true
- Pass batch findings + project context + batch_id to each agent
- Each agent outputs: partial-plan-{batch-id}.json
- Collect results via TaskOutput (blocking until all complete)
- Aggregate partial plans:
- Merge execution groups (renumber group_ids sequentially: G1, G2, ...)
- Merge timelines (detect cross-batch dependencies, adjust stages)
- Resolve conflicts (same file in multiple batches → serialize)
- Generate final fix-plan.json with aggregated metadata
- TodoWrite update: Mark planning complete, start execution
Phase 3: Execution Orchestration
- Load fix-plan.json timeline stages
- For each stage:
- If parallel mode: Launch all group agents via
Promise.all() - If serial mode: Execute groups sequentially with
await - Assign agent IDs (agents update their fix-progress-{N}.json)
- Handle agent failures gracefully (mark group as failed, continue)
- Advance to next stage only when current stage complete
Phase 4: Completion & Aggregation
- Collect final status from all fix-progress-{N}.json files
- Generate fix-summary.md with timeline and results
- Update fix-history.json with new session entry
- Remove active-fix-session.json
- TodoWrite completion: Mark all phases done
- Output summary to user
Phase 5: Session Completion (Optional)
- If all findings fixed successfully (no failures):
- Prompt user: "All fixes complete. Complete workflow session? [Y/n]"
- If confirmed: Execute
/workflow:session:completeto archive session with lessons learned - If partial success (some failures):
- Output: "Some findings failed. Review fix-summary.md before completing session."
- Do NOT auto-complete session
Output File Structure
.workflow/active/WFS-{session-id}/.review/
├── fix-export-{timestamp}.json # Exported findings (input)
└── fixes/{fix-session-id}/
├── partial-plan-1.json # Batch 1 partial plan (planning agent 1 output)
├── partial-plan-2.json # Batch 2 partial plan (planning agent 2 output)
├── partial-plan-N.json # Batch N partial plan (planning agent N output)
├── fix-plan.json # Aggregated execution plan (orchestrator merges partials)
├── fix-progress-1.json # Group 1 progress (planning agent init → agent updates)
├── fix-progress-2.json # Group 2 progress (planning agent init → agent updates)
├── fix-progress-3.json # Group 3 progress (planning agent init → agent updates)
├── fix-summary.md # Final report (orchestrator generates)
├── active-fix-session.json # Active session marker
└── fix-history.json # All sessions historyFile Producers:
- Orchestrator: Batches findings (Phase 1.5), aggregates partial plans →
fix-plan.json(Phase 2), launches parallel planning agents - Planning Agents (N): Each outputs
partial-plan-{batch-id}.json+ initializesfix-progress-*.jsonfor assigned groups - Execution Agents (M): Update assigned
fix-progress-{N}.jsonin real-time
Agent Invocation Template
Phase 1.5: Intelligent Batching (Orchestrator):
// Load findings
const findings = JSON.parse(Read(exportFile));
const batchSize = flags.batchSize || 5;
// Semantic similarity analysis: group by file+dimension
const batches = [];
const grouped = new Map(); // key: "${file}:${dimension}"
for (const finding of findings) {
const key = `${finding.file || 'unknown'}:${finding.dimension || 'general'}`;
if (!grouped.has(key)) grouped.set(key, []);
grouped.get(key).push(finding);
}
// Create batches respecting batchSize
for (const [key, group] of grouped) {
while (group.length > 0) {
const batch = group.splice(0, batchSize);
batches.push({
batch_id: batches.length + 1,
findings: batch,
metadata: { primary_file: batch[0].file, primary_dimension: batch[0].dimension }
});
}
}
console.log(`Created ${batches.length} batches (${batchSize} findings per batch)`);Phase 2: Parallel Planning (Orchestrator launches N agents):
const MAX_PARALLEL = 10;
const partialPlans = [];
// Process batches in chunks of MAX_PARALLEL
for (let i = 0; i < batches.length; i += MAX_PARALLEL) {
const chunk = batches.slice(i, i + MAX_PARALLEL);
const taskIds = [];
// Launch agents in parallel (run_in_background=true)
for (const batch of chunk) {
const taskId = Agent({
subagent_type: "cli-planning-agent",
run_in_background: true,
description: `Plan batch ${batch.batch_id}: ${batch.findings.length} findings`,
prompt: planningPrompt(batch) // See Planning Agent template below
});
taskIds.push({ taskId, batch });
}
console.log(`Launched ${taskIds.length} planning agents...`);
// Collect results from this chunk (blocking)
for (const { taskId, batch } of taskIds) {
const result = TaskOutput({ task_id: taskId, block: true });
const partialPlan = JSON.parse(Read(`${sessionDir}/partial-plan-${batch.batch_id}.json`));
partialPlans.push(partialPlan);
updateTodo(`Batch ${batch.batch_id}`, 'completed');
}
}
// Aggregate partial plans → fix-plan.json
let groupCounter = 1;
const groupIdMap = new Map();
for (const partial of partialPlans) {
for (const group of partial.groups) {
const newGroupId = `G${groupCounter}`;
groupIdMap.set(`${partial.batch_id}:${group.group_id}`, newGroupId);
aggregatedPlan.groups.push({ ...group, group_id: newGroupId, progress_file: `fix-progress-${groupCounter}.json` });
groupCounter++;
}
}
// Merge timelines, resolve cross-batch conflicts (shared files → serialize)
let stageCounter = 1;
for (const partial of partialPlans) {
for (const stage of partial.timeline) {
aggregatedPlan.timeline.push({
...stage, stage_id: stageCounter,
groups: stage.groups.map(gid => groupIdMap.get(`${partial.batch_id}:${gid}`))
});
stageCounter++;
}
}
// Write aggregated plan + initialize progress files
Write(`${sessionDir}/fix-plan.json`, JSON.stringify(aggregatedPlan, null, 2));
for (let i = 1; i <= aggregatedPlan.groups.length; i++) {
Write(`${sessionDir}/fix-progress-${i}.json`, JSON.stringify(initProgressFile(aggregatedPlan.groups[i-1]), null, 2));
}Planning Agent (Batch Mode - Partial Plan Only):
Agent({
subagent_type: "cli-planning-agent",
run_in_background: true,
description: `Plan batch ${batch.batch_id}: ${batch.findings.length} findings`,
prompt: `
## Task Objective
Analyze code review findings in batch ${batch.batch_id} and generate **partial** execution plan.
## Input Data
Review Session: ${reviewId}
Fix Session ID: ${fixSessionId}
Batch ID: ${batch.batch_id}
Batch Findings: ${batch.findings.length}
Findings:
${JSON.stringify(batch.findings, null, 2)}
Project Context:
- Structure: ${projectStructure}
- Test Framework: ${testFramework}
- Git Status: ${gitStatus}
## Output Requirements
### 1. partial-plan-${batch.batch_id}.json
Generate partial execution plan with structure:
{
"batch_id": ${batch.batch_id},
"groups": [...], // Groups created from batch findings (use local IDs: G1, G2, ...)
"timeline": [...], // Local timeline for this batch only
"metadata": {
"findings_count": ${batch.findings.length},
"groups_count": N,
"created_at": "ISO-8601-timestamp"
}
}
**Key Generation Rules**:
- **Groups**: Create groups with local IDs (G1, G2, ...) using intelligent grouping (file+dimension+root cause)
- **Timeline**: Define stages for this batch only (local dependencies within batch)
- **Progress Files**: DO NOT generate fix-progress-*.json here (orchestrator handles after aggregation)
## Analysis Requirements
### Intelligent Grouping Strategy
Group findings using these criteria (in priority order):
1. **File Proximity**: Findings in same file or related files
2. **Dimension Affinity**: Same dimension (security, performance, etc.)
3. **Root Cause Similarity**: Similar underlying issues
4. **Fix Approach Commonality**: Can be fixed with similar approach
**Grouping Guidelines**:
- Optimal group size: 2-5 findings per group
- Avoid cross-cutting concerns in same group
- Consider test isolation (different test suites → different groups)
- Balance workload across groups for parallel execution
### Execution Strategy Determination (Local Only)
**Parallel Mode**: Use when groups are independent, no shared files
**Serial Mode**: Use when groups have dependencies or shared resources
**Hybrid Mode**: Use for mixed dependency graphs (recommended for most cases)
**Dependency Analysis**:
- Identify shared files between groups
- Detect test dependency chains
- Evaluate risk of concurrent modifications
### Risk Assessment
For each group, evaluate:
- **Complexity**: Based on code structure, file size, existing tests
- **Impact Scope**: Number of files affected, API surface changes
- **Rollback Feasibility**: Ease of reverting changes if tests fail
### Test Strategy
For each group, determine:
- **Test Pattern**: Glob pattern matching affected tests
- **Pass Criteria**: All tests must pass (100% pass rate)
- **Test Command**: Infer from project (package.json, pytest.ini, etc.)
## Output Files
Write to ${sessionDir}:
- ./partial-plan-${batch.batch_id}.json
## Quality Checklist
Before finalizing outputs:
- ✅ All batch findings assigned to exactly one group
- ✅ Group dependencies (within batch) correctly identified
- ✅ Timeline stages respect local dependencies
- ✅ Test patterns are valid and specific
- ✅ Risk assessments are realistic
`
})Execution Agent (per group):
Agent({
subagent_type: "cli-execute-agent",
description: `Fix ${group.findings.length} issues: ${group.group_name}`,
prompt: `
## Task Objective
Execute fixes for code review findings in group ${group.group_id}. Update progress file in real-time with flow control tracking.
## Assignment
- Group ID: ${group.group_id}
- Group Name: ${group.group_name}
- Progress File: ${sessionDir}/${group.progress_file}
- Findings Count: ${group.findings.length}
- Max Iterations: ${maxIterations} (per finding)
## Fix Strategy
${JSON.stringify(group.fix_strategy, null, 2)}
## Risk Assessment
${JSON.stringify(group.risk_assessment, null, 2)}
## Execution Flow
### Initialization (Before Starting)
1. Read ${group.progress_file} to load initial state
2. Update progress file:
- assigned_agent: "${agentId}"
- status: "in-progress"
- started_at: Current ISO 8601 timestamp
- last_update: Current ISO 8601 timestamp
3. Write updated state back to ${group.progress_file}
### Main Execution Loop
For EACH finding in ${group.progress_file}.findings:
#### Step 1: Analyze Context
**Before Step**:
- Update finding: status→"in-progress", started_at→now()
- Update current_finding: Populate with finding details, status→"analyzing", action→"Reading file and understanding code structure"
- Update phase→"analyzing"
- Update flow_control: Add "analyze_context" step to implementation_approach (status→"in-progress"), set current_step→"analyze_context"
- Update last_update→now(), write to ${group.progress_file}
**Action**:
- Read file: finding.file
- Understand code structure around line: finding.line
- Analyze surrounding context (imports, dependencies, related functions)
- Review recommendations: finding.recommendations
**After Step**:
- Update flow_control: Mark "analyze_context" step as "completed" with completed_at→now()
- Update last_update→now(), write to ${group.progress_file}
#### Step 2: Apply Fix
**Before Step**:
- Update current_finding: status→"fixing", action→"Applying code changes per recommendations"
- Update phase→"fixing"
- Update flow_control: Add "apply_fix" step to implementation_approach (status→"in-progress"), set current_step→"apply_fix"
- Update last_update→now(), write to ${group.progress_file}
**Action**:
- Use Edit tool to implement code changes per finding.recommendations
- Follow fix_strategy.approach
- Maintain code style and existing patterns
**After Step**:
- Update flow_control: Mark "apply_fix" step as "completed" with completed_at→now()
- Update last_update→now(), write to ${group.progress_file}
#### Step 3: Test Verification
**Before Step**:
- Update current_finding: status→"testing", action→"Running test suite to verify fix"
- Update phase→"testing"
- Update flow_control: Add "run_tests" step to implementation_approach (status→"in-progress"), set current_step→"run_tests"
- Update last_update→now(), write to ${group.progress_file}
**Action**:
- Run tests using fix_strategy.test_pattern
- Require 100% pass rate
- Capture test output
**On Test Failure**:
- Git rollback: \`git checkout -- \${finding.file}\`
- Increment finding.attempts
- Update flow_control: Mark "run_tests" step as "failed" with completed_at→now()
- Update errors: Add entry (finding_id, error_type→"test_failure", message, timestamp)
- If finding.attempts < ${maxIterations}:
- Reset flow_control: implementation_approach→[], current_step→null
- Retry from Step 1
- Else:
- Update finding: status→"completed", result→"failed", error_message→"Max iterations reached", completed_at→now()
- Update summary counts, move to next finding
**On Test Success**:
- Update flow_control: Mark "run_tests" step as "completed" with completed_at→now()
- Update last_update→now(), write to ${group.progress_file}
- Proceed to Step 4
#### Step 4: Commit Changes
**Before Step**:
- Update current_finding: status→"committing", action→"Creating git commit for successful fix"
- Update phase→"committing"
- Update flow_control: Add "commit_changes" step to implementation_approach (status→"in-progress"), set current_step→"commit_changes"
- Update last_update→now(), write to ${group.progress_file}
**Action**:
- Git commit: \`git commit -m "fix(${finding.dimension}): ${finding.title} [${finding.id}]"\`
- Capture commit hash
**After Step**:
- Update finding: status→"completed", result→"fixed", commit_hash→<captured>, test_passed→true, completed_at→now()
- Update flow_control: Mark "commit_changes" step as "completed" with completed_at→now()
- Update last_update→now(), write to ${group.progress_file}
#### After Each Finding
- Update summary: Recalculate counts (pending/in_progress/fixed/failed) and percent_complete
- If all findings completed: Clear current_finding, reset flow_control
- Update last_update→now(), write to ${group.progress_file}
### Final Completion
When all findings processed:
- Update status→"completed", phase→"done", summary.percent_complete→100.0
- Update last_update→now(), write final state to ${group.progress_file}
## Critical Requirements
### Progress File Updates
- **MUST update after every significant action** (before/after each step)
- **Always maintain complete structure** - never write partial updates
- **Use ISO 8601 timestamps** - e.g., "2025-01-25T14:36:00Z"
### Flow Control Format
Follow action-planning-agent flow_control.implementation_approach format:
- step: Identifier (e.g., "analyze_context", "apply_fix")
- action: Human-readable description
- status: "pending" | "in-progress" | "completed" | "failed"
- started_at: ISO 8601 timestamp or null
- completed_at: ISO 8601 timestamp or null
### Error Handling
- Capture all errors in errors[] array
- Never leave progress file in invalid state
- Always write complete updates, never partial
- On unrecoverable error: Mark group as failed, preserve state
## Test Patterns
Use fix_strategy.test_pattern to run affected tests:
- Pattern: ${group.fix_strategy.test_pattern}
- Command: Infer from project (npm test, pytest, etc.)
- Pass Criteria: 100% pass rate required
`
})Error Handling
Batching Failures (Phase 1.5):
- Invalid findings data → Abort with error message
- Empty batches after grouping → Warn and skip empty batches
Planning Failures (Phase 2):
- Planning agent timeout → Mark batch as failed, continue with other batches
- Partial plan missing → Skip batch, warn user
- Agent crash → Collect available partial plans, proceed with aggregation
- All agents fail → Abort entire fix session with error
- Aggregation conflicts → Apply conflict resolution (serialize conflicting groups)
Execution Failures (Phase 3):
- Agent crash → Mark group as failed, continue with other groups
- Test command not found → Skip test verification, warn user
- Git operations fail → Abort with error, preserve state
Rollback Scenarios:
- Test failure after fix → Automatic
git checkoutrollback - Max iterations reached → Leave file unchanged, mark as failed
- Unrecoverable error → Rollback entire group, save checkpoint
TodoWrite Structure
Initialization (after Phase 1.5 batching):
TodoWrite({
todos: [
{content: "Phase 1: Discovery & Initialization", status: "completed", activeForm: "Discovering"},
{content: "Phase 1.5: Intelligent Batching", status: "completed", activeForm: "Batching"},
{content: "Phase 2: Parallel Planning", status: "in_progress", activeForm: "Planning"},
{content: " → Batch 1: 4 findings (auth.ts:security)", status: "pending", activeForm: "Planning batch 1"},
{content: " → Batch 2: 3 findings (query.ts:security)", status: "pending", activeForm: "Planning batch 2"},
{content: " → Batch 3: 2 findings (config.ts:quality)", status: "pending", activeForm: "Planning batch 3"},
{content: "Phase 3: Execution", status: "pending", activeForm: "Executing"},
{content: "Phase 4: Completion", status: "pending", activeForm: "Completing"}
]
});During Planning (parallel agents running):
TodoWrite({
todos: [
{content: "Phase 1: Discovery & Initialization", status: "completed", activeForm: "Discovering"},
{content: "Phase 1.5: Intelligent Batching", status: "completed", activeForm: "Batching"},
{content: "Phase 2: Parallel Planning", status: "in_progress", activeForm: "Planning"},
{content: " → Batch 1: 4 findings (auth.ts:security)", status: "completed", activeForm: "Planning batch 1"},
{content: " → Batch 2: 3 findings (query.ts:security)", status: "in_progress", activeForm: "Planning batch 2"},
{content: " → Batch 3: 2 findings (config.ts:quality)", status: "in_progress", activeForm: "Planning batch 3"},
{content: "Phase 3: Execution", status: "pending", activeForm: "Executing"},
{content: "Phase 4: Completion", status: "pending", activeForm: "Completing"}
]
});During Execution:
TodoWrite({
todos: [
{content: "Phase 1: Discovery & Initialization", status: "completed", activeForm: "Discovering"},
{content: "Phase 1.5: Intelligent Batching", status: "completed", activeForm: "Batching"},
{content: "Phase 2: Parallel Planning (3 batches → 5 groups)", status: "completed", activeForm: "Planning"},
{content: "Phase 3: Execution", status: "in_progress", activeForm: "Executing"},
{content: " → Stage 1: Parallel execution (3 groups)", status: "completed", activeForm: "Executing stage 1"},
{content: " • Group G1: Auth validation (2 findings)", status: "completed", activeForm: "Fixing G1"},
{content: " • Group G2: Query security (3 findings)", status: "completed", activeForm: "Fixing G2"},
{content: " • Group G3: Config quality (1 finding)", status: "completed", activeForm: "Fixing G3"},
{content: " → Stage 2: Serial execution (1 group)", status: "in_progress", activeForm: "Executing stage 2"},
{content: " • Group G4: Dependent fixes (2 findings)", status: "in_progress", activeForm: "Fixing G4"},
{content: "Phase 4: Completion", status: "pending", activeForm: "Completing"}
]
});Update Rules:
- Add batch items dynamically during Phase 1.5
- Mark batch items completed as parallel agents return results
- Add stage/group items dynamically after Phase 2 plan aggregation
- Mark completed immediately after each group finishes
- Update parent phase status when all child items complete
Post-Completion Expansion
Auto-sync: 执行 /workflow:session:sync -y "{summary}" 更新 specs/*.md + project-tech。
完成后询问用户是否扩展为issue(test/enhance/refactor/doc),选中项调用 /issue:new "{summary} - {dimension}"
Best Practices
1. Leverage Parallel Planning: For 10+ findings, parallel batching significantly reduces planning time 2. Tune Batch Size: Use --batch-size to control granularity (smaller batches = more parallelism, larger = better grouping context) 3. Conservative Approach: Test verification is mandatory - no fixes kept without passing tests 4. Parallel Efficiency: MAX_PARALLEL=10 for planning agents, 3 concurrent execution agents per stage 5. Resume Support: Fix sessions can resume from checkpoints after interruption 6. Manual Review: Always review failed fixes manually - may require architectural changes 7. Incremental Fixing: Start with small batches (5-10 findings) before large-scale fixes
Related Commands
View Fix Progress
Use ccw view to open the workflow dashboard in browser:
ccw viewWorkflow Review-Module-Cycle Command
Quick Start
# Review specific module (all 7 dimensions)
/workflow:review-module-cycle src/auth/**
# Review multiple modules
/workflow:review-module-cycle src/auth/**,src/payment/**
# Review with custom dimensions
/workflow:review-module-cycle src/payment/** --dimensions=security,architecture,quality
# Review specific files
/workflow:review-module-cycle src/payment/processor.ts,src/payment/validator.tsReview Scope: Specified modules/files only (independent of git history) Session Requirement: Auto-creates workflow session via /workflow:session:start Output Directory: .workflow/active/WFS-{session-id}/.review/ (session-based) Default Dimensions: Security, Architecture, Quality, Action-Items, Performance, Maintainability, Best-Practices Max Iterations: 3 (adjustable via --max-iterations) Default Iterations: 1 (deep-dive runs once; use --max-iterations=0 to skip) CLI Tools: Gemini → Qwen → Codex (fallback chain)
What & Why
Core Concept
Independent multi-dimensional code review orchestrator with hybrid parallel-iterative execution for comprehensive quality assessment of specific modules or files.
Review Scope:
- Module-based: Reviews specified file patterns (e.g.,
src/auth/**,*.ts) - Session-integrated: Runs within workflow session context for unified tracking
- Output location:
.review/subdirectory within active session
vs Session Review:
- Session Review (
review-session-cycle): Reviews git changes within a workflow session - Module Review (
review-module-cycle): Reviews any specified code paths, regardless of git history - Common output: Both use same
.review/directory structure within session
Value Proposition
1. Module-Focused Review: Target specific code areas independent of git history 2. Session-Integrated: Review results tracked within workflow session for unified management 3. Comprehensive Coverage: Same 7 specialized dimensions as session review 4. Intelligent Prioritization: Automatic identification of critical issues and cross-cutting concerns 5. Unified Archive: Review results archived with session for historical reference
Orchestrator Boundary (CRITICAL)
- ONLY command for independent multi-dimensional module review
- Manages: dimension coordination, aggregation, iteration control, progress tracking
- Delegates: Code exploration and analysis to @cli-explore-agent, dimension-specific reviews via Deep Scan mode
How It Works
Execution Flow
Phase 1: Discovery & Initialization
└─ Resolve file patterns, validate paths, initialize state, create output structure
Phase 2: Parallel Reviews (for each dimension)
├─ Launch 7 review agents simultaneously
├─ Each executes CLI analysis via Gemini/Qwen on specified files
├─ Generate dimension JSON + markdown reports
└─ Update review-progress.json
Phase 3: Aggregation
├─ Load all dimension JSON files
├─ Calculate severity distribution (critical/high/medium/low)
├─ Identify cross-cutting concerns (files in 3+ dimensions)
└─ Decision:
├─ Critical findings OR high > 5 OR critical files → Phase 4 (Iterate)
└─ Else → Phase 5 (Complete)
Phase 4: Iterative Deep-Dive (optional)
├─ Select critical findings (max 5 per iteration)
├─ Launch deep-dive agents for root cause analysis
├─ Generate remediation plans with impact assessment
├─ Re-assess severity based on analysis
└─ Loop until no critical findings OR max iterations
Phase 5: Completion
└─ Finalize review-progress.jsonAgent Roles
| Agent | Responsibility |
|---|---|
| Orchestrator | Phase control, path resolution, state management, aggregation logic, iteration control |
| @cli-explore-agent (Review) | Execute dimension-specific code analysis via Deep Scan mode, generate findings JSON with dual-source strategy (Bash + Gemini), create structured analysis reports |
| @cli-explore-agent (Deep-dive) | Focused root cause analysis using dependency mapping, remediation planning with architectural insights, impact assessment, severity re-assessment |
Enhanced Features
1. Review Dimensions Configuration
7 Specialized Dimensions with priority-based allocation:
| Dimension | Template | Priority | Timeout |
|---|---|---|---|
| Security | 03-assess-security-risks.txt | 1 (Critical) | 60min |
| Architecture | 02-review-architecture.txt | 2 (High) | 60min |
| Quality | 02-review-code-quality.txt | 3 (Medium) | 40min |
| Action-Items | 02-analyze-code-patterns.txt | 2 (High) | 40min |
| Performance | 03-analyze-performance.txt | 3 (Medium) | 60min |
| Maintainability | 02-review-code-quality.txt* | 3 (Medium) | 40min |
| Best-Practices | 03-review-quality-standards.txt | 3 (Medium) | 40min |
*Custom focus: "Assess technical debt and maintainability"
Category Definitions by Dimension:
const CATEGORIES = {
security: ['injection', 'authentication', 'authorization', 'encryption', 'input-validation', 'access-control', 'data-exposure'],
architecture: ['coupling', 'cohesion', 'layering', 'dependency', 'pattern-violation', 'scalability', 'separation-of-concerns'],
quality: ['code-smell', 'duplication', 'complexity', 'naming', 'error-handling', 'testability', 'readability'],
'action-items': ['requirement-coverage', 'acceptance-criteria', 'documentation', 'deployment-readiness', 'missing-functionality'],
performance: ['n-plus-one', 'inefficient-query', 'memory-leak', 'blocking-operation', 'caching', 'resource-usage'],
maintainability: ['technical-debt', 'magic-number', 'long-method', 'large-class', 'dead-code', 'commented-code'],
'best-practices': ['convention-violation', 'anti-pattern', 'deprecated-api', 'missing-validation', 'inconsistent-style']
};2. Path Pattern Resolution
Syntax Rules:
- All paths are relative from project root (e.g.,
src/auth/**not/src/auth/**) - Multiple patterns: comma-separated, no spaces (e.g.,
src/auth/**,src/payment/**) - Glob and specific files can be mixed (e.g.,
src/auth/**,src/config.ts)
Supported Patterns:
| Pattern Type | Example | Description |
|---|---|---|
| Glob directory | src/auth/** | All files under src/auth/ |
| Glob with extension | src/**/*.ts | All .ts files under src/ |
| Specific file | src/payment/processor.ts | Single file |
| Multiple patterns | src/auth/**,src/payment/** | Comma-separated (no spaces) |
Resolution Process: 1. Parse input pattern (split by comma, trim whitespace) 2. Expand glob patterns to file list via find command 3. Validate all files exist and are readable 4. Error if pattern matches 0 files 5. Store resolved file list in review-state.json
3. Aggregation Logic
Cross-Cutting Concern Detection: 1. Files appearing in 3+ dimensions = Critical Files 2. Same issue pattern across dimensions = Systemic Issue 3. Severity clustering in specific files = Hotspots
Deep-Dive Selection Criteria:
- All critical severity findings (priority 1)
- Top 3 high-severity findings in critical files (priority 2)
- Max 5 findings per iteration (prevent overwhelm)
4. Severity Assessment
Severity Levels:
- Critical: Security vulnerabilities, data corruption risks, system-wide failures, authentication/authorization bypass
- High: Feature degradation, performance bottlenecks, architecture violations, significant technical debt
- Medium: Code smells, minor performance issues, style inconsistencies, maintainability concerns
- Low: Documentation gaps, minor refactoring opportunities, cosmetic issues
Iteration Trigger:
- Critical findings > 0 OR
- High findings > 5 OR
- Critical files count > 0
Core Responsibilities
Orchestrator
Phase 1: Discovery & Initialization
Step 1: Session Creation
// Create workflow session for this review (type: review)
Skill(skill="workflow:session:start", args="--type review \"Code review for [target_pattern]\"")
// Parse output
const sessionId = output.match(/SESSION_ID: (WFS-[^\s]+)/)[1];Step 2: Path Resolution & Validation
# Expand glob pattern to file list (relative paths from project root)
find . -path "./src/auth/**" -type f | sed 's|^\./||'
# Validate files exist and are readable
for file in ${resolvedFiles[@]}; do
test -r "$file" || error "File not readable: $file"
done- Parse and expand file patterns (glob support):
src/auth/**→ actual file list - Validation: Ensure all specified files exist and are readable
- Store as relative paths from project root (e.g.,
src/auth/service.ts) - Agents construct absolute paths dynamically during execution
Step 3: Output Directory Setup
- Output directory:
.workflow/active/${sessionId}/.review/ - Create directory structure:
mkdir -p ${sessionDir}/.review/{dimensions,iterations,reports}Step 4: Initialize Review State
- State initialization: Create
review-state.jsonwith metadata, dimensions, max_iterations, resolved_files (merged metadata + state) - Progress tracking: Create
review-progress.jsonfor progress tracking
Step 5: TodoWrite Initialization
- Set up progress tracking with hierarchical structure
- Mark Phase 1 completed, Phase 2 in_progress
Phase 2: Parallel Review Coordination
- Launch 7 @cli-explore-agent instances simultaneously (Deep Scan mode)
- Pass dimension-specific context (template, timeout, custom focus, target files)
- Monitor completion via review-progress.json updates
- TodoWrite updates: Mark dimensions as completed
- CLI tool fallback: Gemini → Qwen → Codex (on error/timeout)
Phase 3: Aggregation
- Load all dimension JSON files from dimensions/
- Calculate severity distribution: Count by critical/high/medium/low
- Identify cross-cutting concerns: Files in 3+ dimensions
- Select deep-dive findings: Critical + high in critical files (max 5)
- Decision logic: Iterate if critical > 0 OR high > 5 OR critical files exist
- Update review-state.json with aggregation results
Phase 4: Iteration Control
- Check iteration count < max_iterations (default 3)
- Launch deep-dive agents for selected findings
- Collect remediation plans and re-assessed severities
- Update severity distribution based on re-assessments
- Record iteration in review-state.json
- Loop back to aggregation if still have critical/high findings
Phase 5: Completion
- Finalize review-progress.json with completion statistics
- Update review-state.json with completion_time and phase=complete
- TodoWrite completion: Mark all tasks done
Output File Structure
.workflow/active/WFS-{session-id}/.review/
├── review-state.json # Orchestrator state machine (includes metadata)
├── review-progress.json # Real-time progress for dashboard
├── dimensions/ # Per-dimension results
│ ├── security.json
│ ├── architecture.json
│ ├── quality.json
│ ├── action-items.json
│ ├── performance.json
│ ├── maintainability.json
│ └── best-practices.json
├── iterations/ # Deep-dive results
│ ├── iteration-1-finding-{uuid}.json
│ └── iteration-2-finding-{uuid}.json
└── reports/ # Human-readable reports
├── security-analysis.md
├── security-cli-output.txt
├── deep-dive-1-{uuid}.md
└── ...Session Context:
.workflow/active/WFS-{session-id}/
├── workflow-session.json
├── IMPL_PLAN.md
├── TODO_LIST.md
├── .task/
├── .summaries/
└── .review/ # Review results (this command)
└── (structure above)Review State JSON
Purpose: Unified state machine and metadata (merged from metadata + state)
{
"review_id": "review-20250125-143022",
"review_type": "module",
"session_id": "WFS-auth-system",
"metadata": {
"created_at": "2025-01-25T14:30:22Z",
"target_pattern": "src/auth/**",
"resolved_files": [
"src/auth/service.ts",
"src/auth/validator.ts",
"src/auth/middleware.ts"
],
"dimensions": ["security", "architecture", "quality", "action-items", "performance", "maintainability", "best-practices"],
"max_iterations": 3
},
"phase": "parallel|aggregate|iterate|complete",
"current_iteration": 1,
"dimensions_reviewed": ["security", "architecture", "quality", "action-items", "performance", "maintainability", "best-practices"],
"selected_strategy": "comprehensive",
"next_action": "execute_parallel_reviews|aggregate_findings|execute_deep_dive|generate_final_report|complete",
"severity_distribution": {
"critical": 2,
"high": 5,
"medium": 12,
"low": 8
},
"critical_files": [...],
"iterations": [...],
"completion_criteria": {...}
}Review Progress JSON
Purpose: Real-time dashboard updates via polling
{
"review_id": "review-20250125-143022",
"last_update": "2025-01-25T14:35:10Z",
"phase": "parallel|aggregate|iterate|complete",
"current_iteration": 1,
"progress": {
"parallel_review": {
"total_dimensions": 7,
"completed": 5,
"in_progress": 2,
"percent_complete": 71
},
"deep_dive": {
"total_findings": 6,
"analyzed": 2,
"in_progress": 1,
"percent_complete": 33
}
},
"agent_status": [
{
"agent_type": "review-agent",
"dimension": "security",
"status": "completed",
"started_at": "2025-01-25T14:30:00Z",
"completed_at": "2025-01-25T15:15:00Z",
"duration_ms": 2700000
},
{
"agent_type": "deep-dive-agent",
"finding_id": "sec-001-uuid",
"status": "in_progress",
"started_at": "2025-01-25T14:32:00Z"
}
],
"estimated_completion": "2025-01-25T16:00:00Z"
}Agent Output Schemas
Agent-produced JSON files follow standardized schemas:
1. Dimension Results (cli-explore-agent output from parallel reviews)
- Schema:
~/.ccw/workflows/cli-templates/schemas/review-dimension-results-schema.json - Output:
{output-dir}/dimensions/{dimension}.json - Contains: findings array, summary statistics, cross_references
2. Deep-Dive Results (cli-explore-agent output from iterations)
- Schema:
~/.ccw/workflows/cli-templates/schemas/review-deep-dive-results-schema.json - Output:
{output-dir}/iterations/iteration-{N}-finding-{uuid}.json - Contains: root_cause, remediation_plan, impact_assessment, reassessed_severity
Agent Invocation Template
Review Agent (parallel execution, 7 instances):
Task(
subagent_type="cli-explore-agent",
run_in_background=false,
description=`Execute ${dimension} review analysis via Deep Scan`,
prompt=`
## Task Objective
Conduct comprehensive ${dimension} code exploration and analysis using Deep Scan mode (Bash + Gemini dual-source strategy) for specified module files
## Analysis Mode Selection
Use **Deep Scan mode** for this review:
- Phase 1: Bash structural scan for standard patterns (classes, functions, imports)
- Phase 2: Gemini semantic analysis for design intent, non-standard patterns, ${dimension}-specific concerns
- Phase 3: Synthesis with attribution (bash-discovered vs gemini-discovered findings)
## MANDATORY FIRST STEPS (Execute by Agent)
**You (cli-explore-agent) MUST execute these steps in order:**
1. Read review state: ${reviewStateJsonPath}
2. Get target files: Read resolved_files from review-state.json
3. Validate file access: bash(ls -la ${targetFiles.join(' ')})
4. Execute: cat ~/.ccw/workflows/cli-templates/schemas/review-dimension-results-schema.json (get output schema reference)
5. Read: .workflow/project-tech.json (technology stack and architecture context)
6. Read: .workflow/specs/*.md (user-defined constraints and conventions to validate against)
## Review Context
- Review Type: module (independent)
- Review Dimension: ${dimension}
- Review ID: ${reviewId}
- Target Pattern: ${targetPattern}
- Resolved Files: ${resolvedFiles.length} files
- Output Directory: ${outputDir}
## CLI Configuration
- Tool Priority: gemini → qwen → codex (fallback chain)
- Custom Focus: ${customFocus || 'Standard dimension analysis'}
- Mode: analysis (READ-ONLY)
- Context Pattern: ${targetFiles.map(f => `@${f}`).join(' ')}
## Expected Deliverables
**Schema Reference**: Schema obtained in MANDATORY FIRST STEPS step 4, follow schema exactly
1. Dimension Results JSON: ${outputDir}/dimensions/${dimension}.json
**⚠️ CRITICAL JSON STRUCTURE REQUIREMENTS**:
Root structure MUST be array: \`[{ ... }]\` NOT \`{ ... }\`
Required top-level fields:
- dimension, review_id, analysis_timestamp (NOT timestamp/analyzed_at)
- cli_tool_used (gemini|qwen|codex), model, analysis_duration_ms
- summary (FLAT structure), findings, cross_references
Summary MUST be FLAT (NOT nested by_severity):
\`{ "total_findings": N, "critical": N, "high": N, "medium": N, "low": N, "files_analyzed": N, "lines_reviewed": N }\`
Finding required fields:
- id: format \`{dim}-{seq}-{uuid8}\` e.g., \`sec-001-a1b2c3d4\` (lowercase)
- severity: lowercase only (critical|high|medium|low)
- snippet (NOT code_snippet), impact (NOT exploit_scenario)
- metadata, iteration (0), status (pending_remediation), cross_references
2. Analysis Report: ${outputDir}/reports/${dimension}-analysis.md
- Human-readable summary with recommendations
- Grouped by severity: critical → high → medium → low
- Include file:line references for all findings
3. CLI Output Log: ${outputDir}/reports/${dimension}-cli-output.txt
- Raw CLI tool output for debugging
- Include full analysis text
## Dimension-Specific Guidance
${getDimensionGuidance(dimension)}
## Success Criteria
- [ ] Schema obtained via cat review-dimension-results-schema.json
- [ ] All target files analyzed for ${dimension} concerns
- [ ] All findings include file:line references with code snippets
- [ ] Severity assessment follows established criteria (see reference)
- [ ] Recommendations are actionable with code examples
- [ ] JSON output follows schema exactly
- [ ] Report is comprehensive and well-organized
`
)Deep-Dive Agent (iteration execution):
Task(
subagent_type="cli-explore-agent",
run_in_background=false,
description=`Deep-dive analysis for critical finding: ${findingTitle} via Dependency Map + Deep Scan`,
prompt=`
## Task Objective
Perform focused root cause analysis using Dependency Map mode (for impact analysis) + Deep Scan mode (for semantic understanding) to generate comprehensive remediation plan for critical ${dimension} issue
## Analysis Mode Selection
Use **Dependency Map mode** first to understand dependencies:
- Build dependency graph around ${file} to identify affected components
- Detect circular dependencies or tight coupling related to this finding
- Calculate change risk scores for remediation impact
Then apply **Deep Scan mode** for semantic analysis:
- Understand design intent and architectural context
- Identify non-standard patterns or implicit dependencies
- Extract remediation insights from code structure
## Finding Context
- Finding ID: ${findingId}
- Original Dimension: ${dimension}
- Title: ${findingTitle}
- File: ${file}:${line}
- Severity: ${severity}
- Category: ${category}
- Original Description: ${description}
- Iteration: ${iteration}
## MANDATORY FIRST STEPS (Execute by Agent)
**You (cli-explore-agent) MUST execute these steps in order:**
1. Read original finding: ${dimensionJsonPath}
2. Read affected file: ${file}
3. Identify related code: bash(grep -r "import.*${basename(file)}" ${projectDir}/src --include="*.ts")
4. Read test files: bash(find ${projectDir}/tests -name "*${basename(file, '.ts')}*" -type f)
5. Execute: cat ~/.ccw/workflows/cli-templates/schemas/review-deep-dive-results-schema.json (get output schema reference)
6. Read: .workflow/project-tech.json (technology stack and architecture context)
7. Read: .workflow/specs/*.md (user-defined constraints for remediation compliance)
## CLI Configuration
- Tool Priority: gemini → qwen → codex
- Template: ~/.ccw/workflows/cli-templates/prompts/analysis/01-diagnose-bug-root-cause.txt
- Mode: analysis (READ-ONLY)
## Expected Deliverables
**Schema Reference**: Schema obtained in MANDATORY FIRST STEPS step 5, follow schema exactly
1. Deep-Dive Results JSON: ${outputDir}/iterations/iteration-${iteration}-finding-${findingId}.json
**⚠️ CRITICAL JSON STRUCTURE REQUIREMENTS**:
Root structure MUST be array: \`[{ ... }]\` NOT \`{ ... }\`
Required top-level fields:
- finding_id, dimension, iteration, analysis_timestamp
- cli_tool_used, model, analysis_duration_ms
- original_finding, root_cause, remediation_plan
- impact_assessment, reassessed_severity, confidence_score, cross_references
All nested objects must follow schema exactly - read schema for field names
2. Analysis Report: ${outputDir}/reports/deep-dive-${iteration}-${findingId}.md
- Detailed root cause analysis
- Step-by-step remediation plan
- Impact assessment and rollback strategy
## Success Criteria
- [ ] Schema obtained via cat review-deep-dive-results-schema.json
- [ ] Root cause clearly identified with supporting evidence
- [ ] Remediation plan is step-by-step actionable with exact file:line references
- [ ] Each step includes specific commands and validation tests
- [ ] Impact fully assessed (files, tests, breaking changes, dependencies)
- [ ] Severity re-evaluation justified with evidence
- [ ] Confidence score accurately reflects certainty of analysis
- [ ] JSON output follows schema exactly
- [ ] References include project-specific and external documentation
`
)Dimension Guidance Reference
function getDimensionGuidance(dimension) {
const guidance = {
security: `
Focus Areas:
- Input validation and sanitization
- Authentication and authorization mechanisms
- Data encryption (at-rest and in-transit)
- SQL/NoSQL injection vulnerabilities
- XSS, CSRF, and other web vulnerabilities
- Sensitive data exposure
- Access control and privilege escalation
Severity Criteria:
- Critical: Authentication bypass, SQL injection, RCE, sensitive data exposure
- High: Missing authorization checks, weak encryption, exposed secrets
- Medium: Missing input validation, insecure defaults, weak password policies
- Low: Security headers missing, verbose error messages, outdated dependencies
`,
architecture: `
Focus Areas:
- Layering and separation of concerns
- Coupling and cohesion
- Design pattern adherence
- Dependency management
- Scalability and extensibility
- Module boundaries
- API design consistency
Severity Criteria:
- Critical: Circular dependencies, god objects, tight coupling across layers
- High: Violated architectural principles, scalability bottlenecks
- Medium: Missing abstractions, inconsistent patterns, suboptimal design
- Low: Minor coupling issues, documentation gaps, naming inconsistencies
`,
quality: `
Focus Areas:
- Code duplication
- Complexity (cyclomatic, cognitive)
- Naming conventions
- Error handling patterns
- Code readability
- Comment quality
- Dead code
Severity Criteria:
- Critical: Severe complexity (CC > 20), massive duplication (>50 lines)
- High: High complexity (CC > 10), significant duplication, poor error handling
- Medium: Moderate complexity (CC > 5), naming issues, code smells
- Low: Minor duplication, documentation gaps, cosmetic issues
`,
'action-items': `
Focus Areas:
- Requirements coverage verification
- Acceptance criteria met
- Documentation completeness
- Deployment readiness
- Missing functionality
- Test coverage gaps
- Configuration management
Severity Criteria:
- Critical: Core requirements not met, deployment blockers
- High: Significant functionality missing, acceptance criteria not met
- Medium: Minor requirements gaps, documentation incomplete
- Low: Nice-to-have features missing, minor documentation gaps
`,
performance: `
Focus Areas:
- N+1 query problems
- Inefficient algorithms (O(n²) where O(n log n) possible)
- Memory leaks
- Blocking operations on main thread
- Missing caching opportunities
- Resource usage (CPU, memory, network)
- Database query optimization
Severity Criteria:
- Critical: Memory leaks, O(n²) in hot path, blocking main thread
- High: N+1 queries, missing indexes, inefficient algorithms
- Medium: Suboptimal caching, unnecessary computations, lazy loading issues
- Low: Minor optimization opportunities, redundant operations
`,
maintainability: `
Focus Areas:
- Technical debt indicators
- Magic numbers and hardcoded values
- Long methods (>50 lines)
- Large classes (>500 lines)
- Dead code and commented code
- Code documentation
- Test coverage
Severity Criteria:
- Critical: Massive methods (>200 lines), severe technical debt blocking changes
- High: Large methods (>100 lines), significant dead code, undocumented complex logic
- Medium: Magic numbers, moderate technical debt, missing tests
- Low: Minor refactoring opportunities, cosmetic improvements
`,
'best-practices': `
Focus Areas:
- Framework conventions adherence
- Language idioms
- Anti-patterns
- Deprecated API usage
- Coding standards compliance
- Error handling patterns
- Logging and monitoring
Severity Criteria:
- Critical: Severe anti-patterns, deprecated APIs with security risks
- High: Major convention violations, poor error handling, missing logging
- Medium: Minor anti-patterns, style inconsistencies, suboptimal patterns
- Low: Cosmetic style issues, minor convention deviations
`
};
return guidance[dimension] || 'Standard code review analysis';
}Completion Conditions
Full Success:
- All dimensions reviewed
- Critical findings = 0
- High findings ≤ 5
- Action: Generate final report, mark phase=complete
Partial Success:
- All dimensions reviewed
- Max iterations reached
- Still have critical/high findings
- Action: Generate report with warnings, recommend follow-up
Error Handling
Phase-Level Error Matrix:
| Phase | Error | Blocking? | Action |
|---|---|---|---|
| Phase 1 | Invalid path pattern | Yes | Error and exit |
| Phase 1 | No files matched | Yes | Error and exit |
| Phase 1 | Files not readable | Yes | Error and exit |
| Phase 2 | Single dimension fails | No | Log warning, continue other dimensions |
| Phase 2 | All dimensions fail | Yes | Error and exit |
| Phase 3 | Missing dimension JSON | No | Skip in aggregation, log warning |
| Phase 4 | Deep-dive agent fails | No | Skip finding, continue others |
| Phase 4 | Max iterations reached | No | Generate partial report |
CLI Fallback Chain: Gemini → Qwen → Codex → degraded mode
Fallback Triggers: 1. HTTP 429, 5xx errors, connection timeout 2. Invalid JSON output (parse error, missing required fields) 3. Low confidence score < 0.4 4. Analysis too brief (< 100 words in report)
Fallback Behavior:
- On trigger: Retry with next tool in chain
- After Codex fails: Enter degraded mode (skip analysis, log error)
- Degraded mode: Continue workflow with available results
TodoWrite Structure
TodoWrite({
todos: [
{ content: "Phase 1: Discovery & Initialization", status: "completed", activeForm: "Initializing" },
{ content: "Phase 2: Parallel Reviews (7 dimensions)", status: "in_progress", activeForm: "Reviewing" },
{ content: " → Security review", status: "in_progress", activeForm: "Analyzing security" },
// ... other dimensions as sub-items
{ content: "Phase 3: Aggregation", status: "pending", activeForm: "Aggregating" },
{ content: "Phase 4: Deep-dive", status: "pending", activeForm: "Deep-diving" },
{ content: "Phase 5: Completion", status: "pending", activeForm: "Completing" }
]
});Best Practices
1. Start Specific: Begin with focused module patterns for faster results 2. Expand Gradually: Add more modules based on initial findings 3. Use Glob Wisely: src/auth/** is more efficient than src/** with lots of irrelevant files 4. Trust Aggregation Logic: Auto-selection based on proven heuristics 5. Monitor Logs: Check reports/ directory for CLI analysis insights
Related Commands
View Review Progress
Use ccw view to open the review dashboard in browser:
ccw viewAutomated Fix Workflow
After completing a module review, use the generated findings JSON for automated fixing:
# Step 1: Complete review (this command)
/workflow:review-module-cycle src/auth/**
# Step 2: Run automated fixes using dimension findings
/workflow:review-cycle-fix .workflow/active/WFS-{session-id}/.review/See review-cycle skill (fix phase) for automated fixing with smart grouping, parallel execution, and test verification.
Workflow Review-Session-Cycle Command
Quick Start
# Execute comprehensive session review (all 7 dimensions)
/workflow:review-session-cycle
# Review specific session with custom dimensions
/workflow:review-session-cycle WFS-payment-integration --dimensions=security,architecture,quality
# Specify session and iteration limit
/workflow:review-session-cycle WFS-payment-integration --max-iterations=5Review Scope: Git changes from session creation to present (via git log --since) Session Requirement: Requires active or completed workflow session Output Directory: .workflow/active/WFS-{session-id}/.review/ (session-based) Default Dimensions: Security, Architecture, Quality, Action-Items, Performance, Maintainability, Best-Practices Max Iterations: 3 (adjustable via --max-iterations) Default Iterations: 1 (deep-dive runs once; use --max-iterations=0 to skip) CLI Tools: Gemini → Qwen → Codex (fallback chain)
What & Why
Core Concept
Session-based multi-dimensional code review orchestrator with hybrid parallel-iterative execution for comprehensive quality assessment of git changes within a workflow session.
Review Scope:
- Session-based: Reviews only files changed during the workflow session (via
git log --since="${sessionCreatedAt}") - For independent module review: Use
review-cycleskill command instead
vs Standard Review:
- Standard: Sequential manual reviews → Inconsistent coverage → Missed cross-cutting concerns
- Review-Session-Cycle: Parallel automated analysis → Aggregate findings → Deep-dive critical issues → Comprehensive coverage
Value Proposition
1. Comprehensive Coverage: 7 specialized dimensions analyze all quality aspects simultaneously 2. Intelligent Prioritization: Automatic identification of critical issues and cross-cutting concerns 3. Actionable Insights: Deep-dive iterations provide step-by-step remediation plans
Orchestrator Boundary (CRITICAL)
- ONLY command for comprehensive multi-dimensional review
- Manages: dimension coordination, aggregation, iteration control, progress tracking
- Delegates: Code exploration and analysis to @cli-explore-agent, dimension-specific reviews via Deep Scan mode
How It Works
Execution Flow (Simplified)
Phase 1: Discovery & Initialization
└─ Validate session, initialize state, create output structure
Phase 2: Parallel Reviews (for each dimension)
├─ Launch 7 review agents simultaneously
├─ Each executes CLI analysis via Gemini/Qwen
├─ Generate dimension JSON + markdown reports
└─ Update review-progress.json
Phase 3: Aggregation
├─ Load all dimension JSON files
├─ Calculate severity distribution (critical/high/medium/low)
├─ Identify cross-cutting concerns (files in 3+ dimensions)
└─ Decision:
├─ Critical findings OR high > 5 OR critical files → Phase 4 (Iterate)
└─ Else → Phase 5 (Complete)
Phase 4: Iterative Deep-Dive (optional)
├─ Select critical findings (max 5 per iteration)
├─ Launch deep-dive agents for root cause analysis
├─ Generate remediation plans with impact assessment
├─ Re-assess severity based on analysis
└─ Loop until no critical findings OR max iterations
Phase 5: Completion
└─ Finalize review-progress.jsonAgent Roles
| Agent | Responsibility |
|---|---|
| Orchestrator | Phase control, session discovery, state management, aggregation logic, iteration control |
| @cli-explore-agent (Review) | Execute dimension-specific code analysis via Deep Scan mode, generate findings JSON with dual-source strategy (Bash + Gemini), create structured analysis reports |
| @cli-explore-agent (Deep-dive) | Focused root cause analysis using dependency mapping, remediation planning with architectural insights, impact assessment, severity re-assessment |
Enhanced Features
1. Review Dimensions Configuration
7 Specialized Dimensions with priority-based allocation:
| Dimension | Template | Priority | Timeout |
|---|---|---|---|
| Security | 03-assess-security-risks.txt | 1 (Critical) | 60min |
| Architecture | 02-review-architecture.txt | 2 (High) | 60min |
| Quality | 02-review-code-quality.txt | 3 (Medium) | 40min |
| Action-Items | 02-analyze-code-patterns.txt | 2 (High) | 40min |
| Performance | 03-analyze-performance.txt | 3 (Medium) | 60min |
| Maintainability | 02-review-code-quality.txt* | 3 (Medium) | 40min |
| Best-Practices | 03-review-quality-standards.txt | 3 (Medium) | 40min |
*Custom focus: "Assess technical debt and maintainability"
Category Definitions by Dimension:
const CATEGORIES = {
security: ['injection', 'authentication', 'authorization', 'encryption', 'input-validation', 'access-control', 'data-exposure'],
architecture: ['coupling', 'cohesion', 'layering', 'dependency', 'pattern-violation', 'scalability', 'separation-of-concerns'],
quality: ['code-smell', 'duplication', 'complexity', 'naming', 'error-handling', 'testability', 'readability'],
'action-items': ['requirement-coverage', 'acceptance-criteria', 'documentation', 'deployment-readiness', 'missing-functionality'],
performance: ['n-plus-one', 'inefficient-query', 'memory-leak', 'blocking-operation', 'caching', 'resource-usage'],
maintainability: ['technical-debt', 'magic-number', 'long-method', 'large-class', 'dead-code', 'commented-code'],
'best-practices': ['convention-violation', 'anti-pattern', 'deprecated-api', 'missing-validation', 'inconsistent-style']
};2. Aggregation Logic
Cross-Cutting Concern Detection: 1. Files appearing in 3+ dimensions = Critical Files 2. Same issue pattern across dimensions = Systemic Issue 3. Severity clustering in specific files = Hotspots
Deep-Dive Selection Criteria:
- All critical severity findings (priority 1)
- Top 3 high-severity findings in critical files (priority 2)
- Max 5 findings per iteration (prevent overwhelm)
3. Severity Assessment
Severity Levels:
- Critical: Security vulnerabilities, data corruption risks, system-wide failures, authentication/authorization bypass
- High: Feature degradation, performance bottlenecks, architecture violations, significant technical debt
- Medium: Code smells, minor performance issues, style inconsistencies, maintainability concerns
- Low: Documentation gaps, minor refactoring opportunities, cosmetic issues
Iteration Trigger:
- Critical findings > 0 OR
- High findings > 5 OR
- Critical files count > 0
Core Responsibilities
Orchestrator
Phase 1: Discovery & Initialization
Step 1: Session Discovery
// If session ID not provided, auto-detect
if (!providedSessionId) {
// Check for active sessions
const activeSessions = Glob('.workflow/active/WFS-*');
if (activeSessions.length === 1) {
sessionId = activeSessions[0].match(/WFS-[^/]+/)[0];
} else if (activeSessions.length > 1) {
// List sessions and prompt user
error("Multiple active sessions found. Please specify session ID.");
} else {
error("No active session found. Create session first with /workflow:session:start");
}
} else {
sessionId = providedSessionId;
}
// Validate session exists
Bash(`test -d .workflow/active/${sessionId} && echo "EXISTS"`);Step 2: Session Validation
- Ensure session has implementation artifacts (check
.summaries/or.task/directory) - Extract session creation timestamp from
workflow-session.json - Use timestamp for git log filtering:
git log --since="${sessionCreatedAt}"
Step 3: Changed Files Detection
# Get files changed since session creation
git log --since="${sessionCreatedAt}" --name-only --pretty=format: | sort -uStep 4: Output Directory Setup
- Output directory:
.workflow/active/${sessionId}/.review/ - Create directory structure:
mkdir -p ${sessionDir}/.review/{dimensions,iterations,reports}Step 5: Initialize Review State
- State initialization: Create
review-state.jsonwith metadata, dimensions, max_iterations (merged metadata + state) - Progress tracking: Create
review-progress.jsonfor progress tracking
Step 6: TodoWrite Initialization
- Set up progress tracking with hierarchical structure
- Mark Phase 1 completed, Phase 2 in_progress
Phase 2: Parallel Review Coordination
- Launch 7 @cli-explore-agent instances simultaneously (Deep Scan mode)
- Pass dimension-specific context (template, timeout, custom focus)
- Monitor completion via review-progress.json updates
- TodoWrite updates: Mark dimensions as completed
- CLI tool fallback: Gemini → Qwen → Codex (on error/timeout)
Phase 3: Aggregation
- Load all dimension JSON files from dimensions/
- Calculate severity distribution: Count by critical/high/medium/low
- Identify cross-cutting concerns: Files in 3+ dimensions
- Select deep-dive findings: Critical + high in critical files (max 5)
- Decision logic: Iterate if critical > 0 OR high > 5 OR critical files exist
- Update review-state.json with aggregation results
Phase 4: Iteration Control
- Check iteration count < max_iterations (default 3)
- Launch deep-dive agents for selected findings
- Collect remediation plans and re-assessed severities
- Update severity distribution based on re-assessments
- Record iteration in review-state.json
- Loop back to aggregation if still have critical/high findings
Phase 5: Completion
- Finalize review-progress.json with completion statistics
- Update review-state.json with completion_time and phase=complete
- TodoWrite completion: Mark all tasks done
Session File Structure
.workflow/active/WFS-{session-id}/.review/
├── review-state.json # Orchestrator state machine (includes metadata)
├── review-progress.json # Real-time progress for dashboard
├── dimensions/ # Per-dimension results
│ ├── security.json
│ ├── architecture.json
│ ├── quality.json
│ ├── action-items.json
│ ├── performance.json
│ ├── maintainability.json
│ └── best-practices.json
├── iterations/ # Deep-dive results
│ ├── iteration-1-finding-{uuid}.json
│ └── iteration-2-finding-{uuid}.json
└── reports/ # Human-readable reports
├── security-analysis.md
├── security-cli-output.txt
├── deep-dive-1-{uuid}.md
└── ...Session Context:
.workflow/active/WFS-{session-id}/
├── workflow-session.json
├── IMPL_PLAN.md
├── TODO_LIST.md
├── .task/
├── .summaries/
└── .review/ # Review results (this command)
└── (structure above)Review State JSON
Purpose: Unified state machine and metadata (merged from metadata + state)
{
"session_id": "WFS-payment-integration",
"review_id": "review-20250125-143022",
"review_type": "session",
"metadata": {
"created_at": "2025-01-25T14:30:22Z",
"git_changes": {
"commit_range": "abc123..def456",
"files_changed": 15,
"insertions": 342,
"deletions": 128
},
"dimensions": ["security", "architecture", "quality", "action-items", "performance", "maintainability", "best-practices"],
"max_iterations": 3
},
"phase": "parallel|aggregate|iterate|complete",
"current_iteration": 1,
"dimensions_reviewed": ["security", "architecture", "quality", "action-items", "performance", "maintainability", "best-practices"],
"selected_strategy": "comprehensive",
"next_action": "execute_parallel_reviews|aggregate_findings|execute_deep_dive|generate_final_report|complete",
"severity_distribution": {
"critical": 2,
"high": 5,
"medium": 12,
"low": 8
},
"critical_files": [
{
"file": "src/payment/processor.ts",
"finding_count": 5,
"dimensions": ["security", "architecture", "quality"]
}
],
"iterations": [
{
"iteration": 1,
"findings_analyzed": ["uuid-1", "uuid-2"],
"findings_resolved": 1,
"findings_escalated": 1,
"severity_change": {
"before": {"critical": 2, "high": 5, "medium": 12, "low": 8},
"after": {"critical": 1, "high": 6, "medium": 12, "low": 8}
},
"timestamp": "2025-01-25T14:30:00Z"
}
],
"completion_criteria": {
"target": "no_critical_findings_and_high_under_5",
"current_status": "in_progress",
"estimated_completion": "2 iterations remaining"
}
}Field Descriptions:
phase: Current execution phase (state machine pointer)current_iteration: Iteration counter (used for max check)next_action: Next step orchestrator should executeseverity_distribution: Aggregated counts across all dimensionscritical_files: Files appearing in 3+ dimensions with metadataiterations[]: Historical log for trend analysis
Review Progress JSON
Purpose: Real-time dashboard updates via polling
{
"review_id": "review-20250125-143022",
"last_update": "2025-01-25T14:35:10Z",
"phase": "parallel|aggregate|iterate|complete",
"current_iteration": 1,
"progress": {
"parallel_review": {
"total_dimensions": 7,
"completed": 5,
"in_progress": 2,
"percent_complete": 71
},
"deep_dive": {
"total_findings": 6,
"analyzed": 2,
"in_progress": 1,
"percent_complete": 33
}
},
"agent_status": [
{
"agent_type": "review-agent",
"dimension": "security",
"status": "completed",
"started_at": "2025-01-25T14:30:00Z",
"completed_at": "2025-01-25T15:15:00Z",
"duration_ms": 2700000
},
{
"agent_type": "deep-dive-agent",
"finding_id": "sec-001-uuid",
"status": "in_progress",
"started_at": "2025-01-25T14:32:00Z"
}
],
"estimated_completion": "2025-01-25T16:00:00Z"
}Agent Output Schemas
Agent-produced JSON files follow standardized schemas:
1. Dimension Results (cli-explore-agent output from parallel reviews)
- Schema:
~/.ccw/workflows/cli-templates/schemas/review-dimension-results-schema.json - Output:
.review-cycle/dimensions/{dimension}.json - Contains: findings array, summary statistics, cross_references
2. Deep-Dive Results (cli-explore-agent output from iterations)
- Schema:
~/.ccw/workflows/cli-templates/schemas/review-deep-dive-results-schema.json - Output:
.review-cycle/iterations/iteration-{N}-finding-{uuid}.json - Contains: root_cause, remediation_plan, impact_assessment, reassessed_severity
Agent Invocation Template
Review Agent (parallel execution, 7 instances):
Task(
subagent_type="cli-explore-agent",
run_in_background=false,
description=`Execute ${dimension} review analysis via Deep Scan`,
prompt=`
## Task Objective
Conduct comprehensive ${dimension} code exploration and analysis using Deep Scan mode (Bash + Gemini dual-source strategy) for completed implementation in session ${sessionId}
## Analysis Mode Selection
Use **Deep Scan mode** for this review:
- Phase 1: Bash structural scan for standard patterns (classes, functions, imports)
- Phase 2: Gemini semantic analysis for design intent, non-standard patterns, ${dimension}-specific concerns
- Phase 3: Synthesis with attribution (bash-discovered vs gemini-discovered findings)
## MANDATORY FIRST STEPS (Execute by Agent)
**You (cli-explore-agent) MUST execute these steps in order:**
1. Read session metadata: ${sessionMetadataPath}
2. Read completed task summaries: bash(find ${summariesDir} -name "IMPL-*.md" -type f)
3. Get changed files: bash(cd ${workflowDir} && git log --since="${sessionCreatedAt}" --name-only --pretty=format: | sort -u)
4. Read review state: ${reviewStateJsonPath}
5. Execute: cat ~/.ccw/workflows/cli-templates/schemas/review-dimension-results-schema.json (get output schema reference)
6. Read: .workflow/project-tech.json (technology stack and architecture context)
7. Read: .workflow/specs/*.md (user-defined constraints and conventions to validate against)
## Session Context
- Session ID: ${sessionId}
- Review Dimension: ${dimension}
- Review ID: ${reviewId}
- Implementation Phase: Complete (all tests passing)
- Output Directory: ${outputDir}
## CLI Configuration
- Tool Priority: gemini → qwen → codex (fallback chain)
- Template: ~/.ccw/workflows/cli-templates/prompts/analysis/${dimensionTemplate}
- Custom Focus: ${customFocus || 'Standard dimension analysis'}
- Timeout: ${timeout}ms
- Mode: analysis (READ-ONLY)
## Expected Deliverables
**Schema Reference**: Schema obtained in MANDATORY FIRST STEPS step 5, follow schema exactly
1. Dimension Results JSON: ${outputDir}/dimensions/${dimension}.json
**⚠️ CRITICAL JSON STRUCTURE REQUIREMENTS**:
Root structure MUST be array: \`[{ ... }]\` NOT \`{ ... }\`
Required top-level fields:
- dimension, review_id, analysis_timestamp (NOT timestamp/analyzed_at)
- cli_tool_used (gemini|qwen|codex), model, analysis_duration_ms
- summary (FLAT structure), findings, cross_references
Summary MUST be FLAT (NOT nested by_severity):
\`{ "total_findings": N, "critical": N, "high": N, "medium": N, "low": N, "files_analyzed": N, "lines_reviewed": N }\`
Finding required fields:
- id: format \`{dim}-{seq}-{uuid8}\` e.g., \`sec-001-a1b2c3d4\` (lowercase)
- severity: lowercase only (critical|high|medium|low)
- snippet (NOT code_snippet), impact (NOT exploit_scenario)
- metadata, iteration (0), status (pending_remediation), cross_references
2. Analysis Report: ${outputDir}/reports/${dimension}-analysis.md
- Human-readable summary with recommendations
- Grouped by severity: critical → high → medium → low
- Include file:line references for all findings
3. CLI Output Log: ${outputDir}/reports/${dimension}-cli-output.txt
- Raw CLI tool output for debugging
- Include full analysis text
## Dimension-Specific Guidance
${getDimensionGuidance(dimension)}
## Success Criteria
- [ ] Schema obtained via cat review-dimension-results-schema.json
- [ ] All changed files analyzed for ${dimension} concerns
- [ ] All findings include file:line references with code snippets
- [ ] Severity assessment follows established criteria (see reference)
- [ ] Recommendations are actionable with code examples
- [ ] JSON output follows schema exactly
- [ ] Report is comprehensive and well-organized
`
)Deep-Dive Agent (iteration execution):
Task(
subagent_type="cli-explore-agent",
run_in_background=false,
description=`Deep-dive analysis for critical finding: ${findingTitle} via Dependency Map + Deep Scan`,
prompt=`
## Task Objective
Perform focused root cause analysis using Dependency Map mode (for impact analysis) + Deep Scan mode (for semantic understanding) to generate comprehensive remediation plan for critical ${dimension} issue
## Analysis Mode Selection
Use **Dependency Map mode** first to understand dependencies:
- Build dependency graph around ${file} to identify affected components
- Detect circular dependencies or tight coupling related to this finding
- Calculate change risk scores for remediation impact
Then apply **Deep Scan mode** for semantic analysis:
- Understand design intent and architectural context
- Identify non-standard patterns or implicit dependencies
- Extract remediation insights from code structure
## Finding Context
- Finding ID: ${findingId}
- Original Dimension: ${dimension}
- Title: ${findingTitle}
- File: ${file}:${line}
- Severity: ${severity}
- Category: ${category}
- Original Description: ${description}
- Iteration: ${iteration}
## MANDATORY FIRST STEPS (Execute by Agent)
**You (cli-explore-agent) MUST execute these steps in order:**
1. Read original finding: ${dimensionJsonPath}
2. Read affected file: ${file}
3. Identify related code: bash(grep -r "import.*${basename(file)}" ${workflowDir}/src --include="*.ts")
4. Read test files: bash(find ${workflowDir}/tests -name "*${basename(file, '.ts')}*" -type f)
5. Execute: cat ~/.ccw/workflows/cli-templates/schemas/review-deep-dive-results-schema.json (get output schema reference)
6. Read: .workflow/project-tech.json (technology stack and architecture context)
7. Read: .workflow/specs/*.md (user-defined constraints for remediation compliance)
## CLI Configuration
- Tool Priority: gemini → qwen → codex
- Template: ~/.ccw/workflows/cli-templates/prompts/analysis/01-diagnose-bug-root-cause.txt
- Timeout: 2400000ms (40 minutes)
- Mode: analysis (READ-ONLY)
## Expected Deliverables
**Schema Reference**: Schema obtained in MANDATORY FIRST STEPS step 5, follow schema exactly
1. Deep-Dive Results JSON: ${outputDir}/iterations/iteration-${iteration}-finding-${findingId}.json
**⚠️ CRITICAL JSON STRUCTURE REQUIREMENTS**:
Root structure MUST be array: \`[{ ... }]\` NOT \`{ ... }\`
Required top-level fields:
- finding_id, dimension, iteration, analysis_timestamp
- cli_tool_used, model, analysis_duration_ms
- original_finding, root_cause, remediation_plan
- impact_assessment, reassessed_severity, confidence_score, cross_references
All nested objects must follow schema exactly - read schema for field names
2. Analysis Report: ${outputDir}/reports/deep-dive-${iteration}-${findingId}.md
- Detailed root cause analysis
- Step-by-step remediation plan
- Impact assessment and rollback strategy
## Success Criteria
- [ ] Schema obtained via cat review-deep-dive-results-schema.json
- [ ] Root cause clearly identified with supporting evidence
- [ ] Remediation plan is step-by-step actionable with exact file:line references
- [ ] Each step includes specific commands and validation tests
- [ ] Impact fully assessed (files, tests, breaking changes, dependencies)
- [ ] Severity re-evaluation justified with evidence
- [ ] Confidence score accurately reflects certainty of analysis
- [ ] JSON output follows schema exactly
- [ ] References include project-specific and external documentation
`
)Dimension Guidance Reference
function getDimensionGuidance(dimension) {
const guidance = {
security: `
Focus Areas:
- Input validation and sanitization
- Authentication and authorization mechanisms
- Data encryption (at-rest and in-transit)
- SQL/NoSQL injection vulnerabilities
- XSS, CSRF, and other web vulnerabilities
- Sensitive data exposure
- Access control and privilege escalation
Severity Criteria:
- Critical: Authentication bypass, SQL injection, RCE, sensitive data exposure
- High: Missing authorization checks, weak encryption, exposed secrets
- Medium: Missing input validation, insecure defaults, weak password policies
- Low: Security headers missing, verbose error messages, outdated dependencies
`,
architecture: `
Focus Areas:
- Layering and separation of concerns
- Coupling and cohesion
- Design pattern adherence
- Dependency management
- Scalability and extensibility
- Module boundaries
- API design consistency
Severity Criteria:
- Critical: Circular dependencies, god objects, tight coupling across layers
- High: Violated architectural principles, scalability bottlenecks
- Medium: Missing abstractions, inconsistent patterns, suboptimal design
- Low: Minor coupling issues, documentation gaps, naming inconsistencies
`,
quality: `
Focus Areas:
- Code duplication
- Complexity (cyclomatic, cognitive)
- Naming conventions
- Error handling patterns
- Code readability
- Comment quality
- Dead code
Severity Criteria:
- Critical: Severe complexity (CC > 20), massive duplication (>50 lines)
- High: High complexity (CC > 10), significant duplication, poor error handling
- Medium: Moderate complexity (CC > 5), naming issues, code smells
- Low: Minor duplication, documentation gaps, cosmetic issues
`,
'action-items': `
Focus Areas:
- Requirements coverage verification
- Acceptance criteria met
- Documentation completeness
- Deployment readiness
- Missing functionality
- Test coverage gaps
- Configuration management
Severity Criteria:
- Critical: Core requirements not met, deployment blockers
- High: Significant functionality missing, acceptance criteria not met
- Medium: Minor requirements gaps, documentation incomplete
- Low: Nice-to-have features missing, minor documentation gaps
`,
performance: `
Focus Areas:
- N+1 query problems
- Inefficient algorithms (O(n²) where O(n log n) possible)
- Memory leaks
- Blocking operations on main thread
- Missing caching opportunities
- Resource usage (CPU, memory, network)
- Database query optimization
Severity Criteria:
- Critical: Memory leaks, O(n²) in hot path, blocking main thread
- High: N+1 queries, missing indexes, inefficient algorithms
- Medium: Suboptimal caching, unnecessary computations, lazy loading issues
- Low: Minor optimization opportunities, redundant operations
`,
maintainability: `
Focus Areas:
- Technical debt indicators
- Magic numbers and hardcoded values
- Long methods (>50 lines)
- Large classes (>500 lines)
- Dead code and commented code
- Code documentation
- Test coverage
Severity Criteria:
- Critical: Massive methods (>200 lines), severe technical debt blocking changes
- High: Large methods (>100 lines), significant dead code, undocumented complex logic
- Medium: Magic numbers, moderate technical debt, missing tests
- Low: Minor refactoring opportunities, cosmetic improvements
`,
'best-practices': `
Focus Areas:
- Framework conventions adherence
- Language idioms
- Anti-patterns
- Deprecated API usage
- Coding standards compliance
- Error handling patterns
- Logging and monitoring
Severity Criteria:
- Critical: Severe anti-patterns, deprecated APIs with security risks
- High: Major convention violations, poor error handling, missing logging
- Medium: Minor anti-patterns, style inconsistencies, suboptimal patterns
- Low: Cosmetic style issues, minor convention deviations
`
};
return guidance[dimension] || 'Standard code review analysis';
}Completion Conditions
Full Success:
- All dimensions reviewed
- Critical findings = 0
- High findings ≤ 5
- Action: Generate final report, mark phase=complete
Partial Success:
- All dimensions reviewed
- Max iterations reached
- Still have critical/high findings
- Action: Generate report with warnings, recommend follow-up
Error Handling
Phase-Level Error Matrix:
| Phase | Error | Blocking? | Action |
|---|---|---|---|
| Phase 1 | Session not found | Yes | Error and exit |
| Phase 1 | No completed tasks | Yes | Error and exit |
| Phase 1 | No changed files | Yes | Error and exit |
| Phase 2 | Single dimension fails | No | Log warning, continue other dimensions |
| Phase 2 | All dimensions fail | Yes | Error and exit |
| Phase 3 | Missing dimension JSON | No | Skip in aggregation, log warning |
| Phase 4 | Deep-dive agent fails | No | Skip finding, continue others |
| Phase 4 | Max iterations reached | No | Generate partial report |
CLI Fallback Chain: Gemini → Qwen → Codex → degraded mode
Fallback Triggers: 1. HTTP 429, 5xx errors, connection timeout 2. Invalid JSON output (parse error, missing required fields) 3. Low confidence score < 0.4 4. Analysis too brief (< 100 words in report)
Fallback Behavior:
- On trigger: Retry with next tool in chain
- After Codex fails: Enter degraded mode (skip analysis, log error)
- Degraded mode: Continue workflow with available results
TodoWrite Structure
TodoWrite({
todos: [
{ content: "Phase 1: Discovery & Initialization", status: "completed", activeForm: "Initializing" },
{ content: "Phase 2: Parallel Reviews (7 dimensions)", status: "in_progress", activeForm: "Reviewing" },
{ content: " → Security review", status: "in_progress", activeForm: "Analyzing security" },
// ... other dimensions as sub-items
{ content: "Phase 3: Aggregation", status: "pending", activeForm: "Aggregating" },
{ content: "Phase 4: Deep-dive", status: "pending", activeForm: "Deep-diving" },
{ content: "Phase 5: Completion", status: "pending", activeForm: "Completing" }
]
});Best Practices
1. Default Settings Work: 7 dimensions + 3 iterations sufficient for most cases 2. Parallel Execution: ~60 minutes for full initial review (7 dimensions) 3. Trust Aggregation Logic: Auto-selection based on proven heuristics 4. Monitor Logs: Check reports/ directory for CLI analysis insights
Related Commands
View Review Progress
Use ccw view to open the review dashboard in browser:
ccw viewAutomated Fix Workflow
After completing a review, use the generated findings JSON for automated fixing:
# Step 1: Complete review (this command)
/workflow:review-session-cycle
# Step 2: Run automated fixes using dimension findings
/workflow:review-cycle-fix .workflow/active/WFS-{session-id}/.review/See review-cycle skill (fix phase) for automated fixing with smart grouping, parallel execution, and test verification.