
Team Arch Opt
- 35 installs
- 2.1k repo stars
- Updated June 18, 2026
- catlog22/claude-code-workflow
Support for team-arch-opt
About
Provides workflow support for team-arch-opt. Solo builders use this to streamline development.
- team-arch-opt
Team Arch Opt by the numbers
- 35 all-time installs (skills.sh)
- Ranked #1,773 of 3,282 Productivity & Planning 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 team-arch-optAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 35 |
|---|---|
| repo stars | ★ 2.1k |
| Last updated | June 18, 2026 |
| Repository | catlog22/claude-code-workflow ↗ |
What it does
Support for team-arch-opt
Files
Team Architecture Optimization
Orchestrate multi-agent architecture optimization: analyze codebase → design refactoring plan → implement changes → validate improvements → review code quality.
Architecture
Skill(skill="team-arch-opt", args="task description")
|
SKILL.md (this file) = Router
|
+--------------+--------------+
| |
no --role flag --role <name>
| |
Coordinator Worker
roles/coordinator/role.md roles/<name>/role.md
|
+-- analyze → dispatch → spawn workers → STOP
|
+-------+-------+-------+-------+
v v v v v
[analyzer][designer][refactorer][validator][reviewer]Role Registry
| Role | Path | Prefix | Inner Loop |
|---|---|---|---|
| coordinator | roles/coordinator/role.md | — | — |
| analyzer | roles/analyzer/role.md | ANALYZE-* | false |
| designer | roles/designer/role.md | DESIGN-* | false |
| refactorer | roles/refactorer/role.md | REFACTOR-, FIX- | true |
| validator | roles/validator/role.md | VALIDATE-* | false |
| reviewer | roles/reviewer/role.md | REVIEW-, QUALITY- | false |
Role Router
Parse $ARGUMENTS:
- Has
--role <name>→ Readroles/<name>/role.md, execute Phase 2-4 - No
--role→@roles/coordinator/role.md, execute entry router
Shared Constants
- Session prefix:
TAO - Session path:
.workflow/.team/TAO-<slug>-<date>/ - CLI tools:
ccw cli --mode analysis(read-only),ccw cli --mode write(modifications) - Message bus:
mcp__ccw-tools__team_msg(session_id=<session-id>, ...)
Worker Spawn Template
Coordinator spawns workers using this template:
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker",
team_name: "arch-opt",
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: <skill_root>/roles/<role>/role.md
session: <session-folder>
session_id: <session-id>
team_name: arch-opt
requirement: <task-description>
inner_loop: <true|false>
## Progress Milestones
session_id: <session-id>
Report progress via team_msg at natural phase boundaries (context loaded -> core work done -> verification).
Report blockers immediately via team_msg type="blocker".
Report completion via team_msg type="task_complete" after final SendMessage.
Read role_spec file (@<skill_root>/roles/<role>/role.md) to load Phase 2-4 domain instructions.
Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).`
})Inner Loop roles (refactorer): Set inner_loop dynamically — true for single mode, false for fan-out/independent (parallel branches). Single-task roles (analyzer, designer, validator, reviewer): Set inner_loop: false.
User Commands
| Command | Action |
|---|---|
check / status | View execution status graph (branch-grouped), no advancement |
resume / continue | Check worker states, advance next step |
revise <TASK-ID> [feedback] | Revise specific task + cascade downstream |
feedback <text> | Analyze feedback impact, create targeted revision chain |
recheck | Re-run quality check |
improve [dimension] | Auto-improve weakest dimension |
Session Directory
.workflow/.team/TAO-<slug>-<date>/
├── session.json # Session metadata + status + parallel_mode
├── task-analysis.json # Coordinator analyze output
├── artifacts/
│ ├── architecture-baseline.json # Analyzer: pre-refactoring metrics
│ ├── architecture-report.md # Analyzer: ranked structural issue findings
│ ├── refactoring-plan.md # Designer: prioritized refactoring plan
│ ├── validation-results.json # Validator: post-refactoring validation
│ ├── review-report.md # Reviewer: code review findings
│ ├── aggregate-results.json # Fan-out/independent: aggregated results
│ ├── branches/ # Fan-out mode branch artifacts
│ │ └── B{NN}/
│ │ ├── refactoring-detail.md
│ │ ├── validation-results.json
│ │ └── review-report.md
│ └── pipelines/ # Independent mode pipeline artifacts
│ └── {P}/
│ └── ...
├── explorations/
│ ├── cache-index.json # Shared explore cache
│ └── <hash>.md
├── wisdom/
│ └── patterns.md # Discovered patterns and conventions
├── discussions/
│ ├── DISCUSS-REFACTOR.md
│ └── DISCUSS-REVIEW.md
└── .msg/
├── messages.jsonl # Message bus log
└── meta.json # Session state + cross-role stateSpecs Reference
- specs/pipelines.md — Pipeline definitions, task registry, parallel modes
Error Handling
| Scenario | Resolution |
|---|---|
| Unknown command | Error with available command list |
| Role not found | Error with role registry |
| CLI tool fails | Worker fallback to direct implementation |
| Fast-advance conflict | Coordinator reconciles on next callback |
| Completion action fails | Default to Keep Active |
| consensus_blocked HIGH | Coordinator creates revision task or pauses pipeline |
| Branch fix cycle >= 3 | Escalate only that branch to user, others continue |
| max_branches exceeded | Coordinator truncates to top N at CP-2.5 |
Architecture Analyzer
Analyze codebase architecture to identify structural issues: dependency cycles, coupling/cohesion problems, layering violations, God Classes, code duplication, dead code, and API surface bloat. Produce quantified baseline metrics and a ranked architecture report.
Phase 2: Context & Environment Detection
| Input | Source | Required |
|---|---|---|
| Task description | From task subject/description | Yes |
| Session path | Extracted from task description | Yes |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | No |
1. Extract session path and target scope from task description 2. Detect project type by scanning for framework markers:
| Signal File | Project Type | Analysis Focus |
|---|---|---|
| package.json + React/Vue/Angular | Frontend | Component tree, prop drilling, state management, barrel exports |
| package.json + Express/Fastify/NestJS | Backend Node | Service layer boundaries, middleware chains, DB access patterns |
| Cargo.toml / go.mod / pom.xml | Native/JVM Backend | Module boundaries, trait/interface usage, dependency injection |
| Mixed framework markers | Full-stack / Monorepo | Cross-package dependencies, shared types, API contracts |
| CLI entry / bin/ directory | CLI Tool | Command structure, plugin architecture, configuration layering |
| No detection | Generic | All architecture dimensions |
3. Use explore CLI tool to map module structure, dependency graph, and layer boundaries within target scope 4. Detect available analysis tools (linters, dependency analyzers, build tools)
Phase 3: Architecture Analysis
Execute analysis based on detected project type:
Dependency analysis:
- Build import/require graph across modules
- Detect circular dependencies (direct and transitive cycles)
- Identify layering violations (e.g., UI importing from data layer, utils importing from domain)
- Calculate fan-in/fan-out per module (high fan-out = fragile hub, high fan-in = tightly coupled)
Structural analysis:
- Identify God Classes / God Modules (> 500 LOC, > 10 public methods, too many responsibilities)
- Calculate coupling metrics (afferent/efferent coupling per module)
- Calculate cohesion metrics (LCOM -- Lack of Cohesion of Methods)
- Detect code duplication (repeated logic blocks, copy-paste patterns)
- Identify missing abstractions (repeated conditionals, switch-on-type patterns)
API surface analysis:
- Count exported symbols per module (export bloat detection)
- Identify dead exports (exported but never imported elsewhere)
- Detect dead code (unreachable functions, unused variables, orphan files)
- Check for pattern inconsistencies (mixed naming conventions, inconsistent error handling)
All project types:
- Collect quantified architecture baseline metrics (dependency count, cycle count, coupling scores, LOC distribution)
- Rank top 3-7 architecture issues by severity (Critical / High / Medium)
- Record evidence: file paths, line numbers, measured values
Tech Profile Scan
After analysis, scan findings for context-aware trigger signals (based on detected codebase characteristics):
1. Check dependency analysis → signals (sql_detected, auth_detected, ml_detected) 2. Check structural analysis → risk signals (perf_sensitive, legacy_patterns, scaling_concern) 3. Include tech_profile in Phase 5 state_update data
Phase 4: Report Generation
1. Write architecture baseline to <session>/artifacts/architecture-baseline.json:
- Module count, dependency count, cycle count, average coupling, average cohesion
- God Class candidates with LOC and method count
- Dead code file count, dead export count
- Timestamp and project type details
2. Write architecture report to <session>/artifacts/architecture-report.md:
- Ranked list of architecture issues with severity, location (file:line or module), measured impact
- Issue categories: CYCLE, COUPLING, COHESION, GOD_CLASS, DUPLICATION, LAYER_VIOLATION, DEAD_CODE, API_BLOAT
- Evidence summary per issue
- Detected project type and analysis methods used
3. Update <session>/wisdom/.msg/meta.json under analyzer namespace:
- Read existing -> merge
{ "analyzer": { project_type, issue_count, top_issue, scope, categories } }-> write back
Analyze Task
Parse user task -> detect architecture capabilities -> build dependency graph -> design roles.
CONSTRAINT: Text-level analysis only. NO source code reading, NO codebase exploration.
Signal Detection
| Keywords | Capability | Prefix |
|---|---|---|
| analyze, scan, audit, map, identify | analyzer | ANALYZE |
| design, plan, strategy, refactoring-plan | designer | DESIGN |
| refactor, implement, fix, apply | refactorer | REFACTOR |
| validate, build, test, verify, compile | validator | VALIDATE |
| review, audit-code, quality, check-code | reviewer | REVIEW |
Dependency Graph
Natural ordering tiers:
- Tier 0: analyzer (knowledge gathering -- no dependencies)
- Tier 1: designer (requires analyzer output)
- Tier 2: refactorer (requires designer output)
- Tier 3: validator, reviewer (validation requires refactored artifacts, can run in parallel)
Complexity Scoring
| Factor | Points |
|---|---|
| Per capability | +1 |
| Cross-domain refactoring | +2 |
| Parallel branches requested | +1 per branch |
| Serial depth > 3 | +1 |
| Multiple targets (independent mode) | +2 |
Results: 1-3 Low, 4-6 Medium, 7+ High
Role Minimization
- Cap at 5 roles
- Merge overlapping capabilities
- Absorb trivial single-step roles
Output
Write <session>/task-analysis.json:
{
"task_description": "<original>",
"pipeline_type": "<single|fan-out|independent|auto>",
"capabilities": [{ "name": "<cap>", "prefix": "<PREFIX>", "keywords": ["..."] }],
"dependency_graph": { "<TASK-ID>": { "role": "<role>", "blockedBy": ["..."], "priority": "P0|P1|P2" } },
"roles": [{ "name": "<role>", "prefix": "<PREFIX>", "inner_loop": false }],
"complexity": { "score": 0, "level": "Low|Medium|High" },
"parallel_mode": "<auto|single|fan-out|independent>",
"max_branches": 5
}Command: Dispatch
Create the architecture optimization task chain with correct dependencies and structured task descriptions. Supports single, fan-out, independent, and auto parallel modes.
Phase 2: Context Loading
| Input | Source | Required |
|---|---|---|
| User requirement | From coordinator Phase 1 | Yes |
| Session folder | From coordinator Phase 2 | Yes |
| Pipeline definition | From SKILL.md Pipeline Definitions | Yes |
| Parallel mode | From session.json parallel_mode | Yes |
| Max branches | From session.json max_branches | Yes |
| Independent targets | From session.json independent_targets (independent mode only) | Conditional |
1. Load user requirement and refactoring scope from session.json 2. Load pipeline stage definitions from SKILL.md Task Metadata Registry 3. Read parallel_mode and max_branches from session.json 4. For independent mode: read independent_targets array from session.json
Phase 3: Task Chain Creation (Mode-Branched)
Task Description Template
Every task description uses structured format for clarity:
TaskCreate({
subject: "<TASK-ID>",
description: "PURPOSE: <what this task achieves> | Success: <measurable completion criteria>
TASK:
- <step 1: specific action>
- <step 2: specific action>
- <step 3: specific action>
CONTEXT:
- Session: <session-folder>
- Scope: <refactoring-scope>
- Branch: <branch-id or 'none'>
- Upstream artifacts: <artifact-1>, <artifact-2>
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: <deliverable path> + <quality criteria>
CONSTRAINTS: <scope limits, focus areas>
---
InnerLoop: <true|false>
BranchId: <B01|A|none>"
})
TaskUpdate({ taskId: "<TASK-ID>", addBlockedBy: [<dependency-list>], owner: "<role>" })Mode Router
| Mode | Action |
|---|---|
single | Create 5 tasks (ANALYZE → DESIGN → REFACTOR → VALIDATE + REVIEW) -- unchanged from linear pipeline |
auto | Create ANALYZE-001 + DESIGN-001 only. Defer branch creation to CP-2.5 after design completes |
fan-out | Create ANALYZE-001 + DESIGN-001 only. Defer branch creation to CP-2.5 after design completes |
independent | Create M complete pipelines immediately (one per target) |
---
Single Mode Task Chain
Create tasks in dependency order (backward compatible, unchanged):
ANALYZE-001 (analyzer, Stage 1):
TaskCreate({
subject: "ANALYZE-001",
description: "PURPOSE: Analyze codebase architecture to identify structural issues | Success: Baseline metrics captured, top 3-7 issues ranked by severity
TASK:
- Detect project type and available analysis tools
- Execute analysis across relevant dimensions (dependencies, coupling, cohesion, layering, duplication, dead code)
- Collect baseline metrics and rank architecture issues by severity
CONTEXT:
- Session: <session-folder>
- Scope: <refactoring-scope>
- Branch: none
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: <session>/artifacts/architecture-baseline.json + <session>/artifacts/architecture-report.md | Quantified metrics with evidence
CONSTRAINTS: Focus on <refactoring-scope> | Analyze before any changes
---
InnerLoop: false"
})
TaskUpdate({ taskId: "ANALYZE-001", owner: "analyzer" })DESIGN-001 (designer, Stage 2):
TaskCreate({
subject: "DESIGN-001",
description: "PURPOSE: Design prioritized refactoring plan from architecture analysis | Success: Actionable plan with measurable success criteria per refactoring
TASK:
- Analyze architecture report and baseline metrics
- Select refactoring strategies per issue type
- Prioritize by impact/effort ratio, define success criteria
- Each refactoring MUST have a unique REFACTOR-ID (REFACTOR-001, REFACTOR-002, ...) with non-overlapping target files
CONTEXT:
- Session: <session-folder>
- Scope: <refactoring-scope>
- Branch: none
- Upstream artifacts: architecture-baseline.json, architecture-report.md
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: <session>/artifacts/refactoring-plan.md | Priority-ordered with structural improvement targets, discrete REFACTOR-IDs
CONSTRAINTS: Focus on highest-impact refactorings | Risk assessment required | Non-overlapping file targets per REFACTOR-ID
---
InnerLoop: false"
})
TaskUpdate({ taskId: "DESIGN-001", addBlockedBy: ["ANALYZE-001"], owner: "designer" })REFACTOR-001 (refactorer, Stage 3):
TaskCreate({
subject: "REFACTOR-001",
description: "PURPOSE: Implement refactoring changes per design plan | Success: All planned refactorings applied, code compiles, existing tests pass
TASK:
- Load refactoring plan and identify target files
- Apply refactorings in priority order (P0 first)
- Update all import references for moved/renamed modules
- Validate changes compile and pass existing tests
CONTEXT:
- Session: <session-folder>
- Scope: <refactoring-scope>
- Branch: none
- Upstream artifacts: refactoring-plan.md
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: Modified source files + validation passing | Refactorings applied without regressions
CONSTRAINTS: Preserve existing behavior | Update all references | Follow code conventions
---
InnerLoop: true"
})
TaskUpdate({ taskId: "REFACTOR-001", addBlockedBy: ["DESIGN-001"], owner: "refactorer" })VALIDATE-001 (validator, Stage 4 - parallel):
TaskCreate({
subject: "VALIDATE-001",
description: "PURPOSE: Validate refactoring results against baseline | Success: Build passes, tests pass, no metric regressions, API compatible
TASK:
- Load architecture baseline and plan success criteria
- Run build validation (compilation, type checking)
- Run test validation (existing test suite)
- Compare dependency metrics against baseline
- Verify API compatibility (no dangling references)
CONTEXT:
- Session: <session-folder>
- Scope: <refactoring-scope>
- Branch: none
- Upstream artifacts: architecture-baseline.json, refactoring-plan.md
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: <session>/artifacts/validation-results.json | Per-dimension validation with verdicts
CONSTRAINTS: Must compare against baseline | Flag any regressions or broken imports
---
InnerLoop: false"
})
TaskUpdate({ taskId: "VALIDATE-001", addBlockedBy: ["REFACTOR-001"], owner: "validator" })REVIEW-001 (reviewer, Stage 4 - parallel):
TaskCreate({
subject: "REVIEW-001",
description: "PURPOSE: Review refactoring code for correctness, pattern consistency, and migration safety | Success: All dimensions reviewed, verdict issued
TASK:
- Load modified files and refactoring plan
- Review across 5 dimensions: correctness, pattern consistency, completeness, migration safety, best practices
- Issue verdict: APPROVE, REVISE, or REJECT with actionable feedback
CONTEXT:
- Session: <session-folder>
- Scope: <refactoring-scope>
- Branch: none
- Upstream artifacts: refactoring-plan.md, validation-results.json (if available)
- Shared memory: <session>/wisdom/.msg/meta.json
EXPECTED: <session>/artifacts/review-report.md | Per-dimension findings with severity
CONSTRAINTS: Focus on refactoring changes only | Provide specific file:line references
---
InnerLoop: false"
})
TaskUpdate({ taskId: "REVIEW-001", addBlockedBy: ["REFACTOR-001"], owner: "reviewer" })---
Auto / Fan-out Mode Task Chain (Deferred Branching)
For auto and fan-out modes, create only shared stages now. Branch tasks are created at CP-2.5 after DESIGN-001 completes.
Create ANALYZE-001 and DESIGN-001 with same templates as single mode above.
Do NOT create REFACTOR/VALIDATE/REVIEW tasks yet. They are created by the CP-2.5 Branch Creation subroutine in monitor.md.
---
Independent Mode Task Chain
For independent mode, create M complete pipelines -- one per target in independent_targets array.
Pipeline prefix chars: A, B, C, D, E, F, G, H, I, J (from config pipeline_prefix_chars).
For each target index i (0-based), with prefix char P = pipeline_prefix_chars[i]:
// Create session subdirectory for this pipeline
Bash("mkdir -p <session>/artifacts/pipelines/<P>")
TaskCreate({ subject: "ANALYZE-<P>01", ... })
TaskCreate({ subject: "DESIGN-<P>01", ... })
TaskUpdate({ taskId: "DESIGN-<P>01", addBlockedBy: ["ANALYZE-<P>01"] })
TaskCreate({ subject: "REFACTOR-<P>01", ... })
TaskUpdate({ taskId: "REFACTOR-<P>01", addBlockedBy: ["DESIGN-<P>01"] })
TaskCreate({ subject: "VALIDATE-<P>01", ... })
TaskUpdate({ taskId: "VALIDATE-<P>01", addBlockedBy: ["REFACTOR-<P>01"] })
TaskCreate({ subject: "REVIEW-<P>01", ... })
TaskUpdate({ taskId: "REVIEW-<P>01", addBlockedBy: ["REFACTOR-<P>01"] })Task descriptions follow same template as single mode, with additions:
Pipeline: <P>in CONTEXT- Artifact paths use
<session>/artifacts/pipelines/<P>/instead of<session>/artifacts/ - Meta.json namespace uses
<role>.<P>(e.g.,analyzer.A,refactorer.B) - Each pipeline's scope is its specific target from
independent_targets[i]
Example for pipeline A with target "refactor auth module":
TaskCreate({
subject: "ANALYZE-A01",
description: "PURPOSE: Analyze auth module architecture | Success: Auth module structural issues identified
TASK:
- Detect project type and available analysis tools
- Execute architecture analysis focused on auth module
- Collect baseline metrics and rank auth module issues
CONTEXT:
- Session: <session-folder>
- Scope: refactor auth module
- Pipeline: A
- Shared memory: <session>/wisdom/.msg/meta.json (namespace: analyzer.A)
EXPECTED: <session>/artifacts/pipelines/A/architecture-baseline.json + architecture-report.md
CONSTRAINTS: Focus on auth module scope
---
InnerLoop: false
PipelineId: A"
})
TaskUpdate({ taskId: "ANALYZE-A01", owner: "analyzer" })---
CP-2.5: Branch Creation Subroutine
Triggered by: monitor.md handleCallback when DESIGN-001 completes in auto or fan-out mode.
Procedure:
1. Read <session>/artifacts/refactoring-plan.md to count REFACTOR-IDs 2. Read .msg/meta.json -> designer.refactoring_count 3. Auto mode decision:
| Refactoring Count | Decision |
|---|---|
| count <= 2 | Switch to single mode -- create REFACTOR-001, VALIDATE-001, REVIEW-001 (standard single pipeline) |
| count >= 3 | Switch to fan-out mode -- create branch tasks below |
4. Update session.json with resolved parallel_mode (auto -> single or fan-out)
5. Fan-out branch creation (when count >= 3 or forced fan-out):
- Truncate to
max_branchesifrefactoring_count > max_branches(keep top N by priority) - For each refactoring
i(1-indexed), branch ID =B{NN}where NN = zero-padded i:
// Create branch artifact directory
Bash("mkdir -p <session>/artifacts/branches/B{NN}")
// Extract single REFACTOR detail to branch
Write("<session>/artifacts/branches/B{NN}/refactoring-detail.md",
extracted REFACTOR-{NNN} block from refactoring-plan.md)6. Create branch tasks for each branch B{NN}:
TaskCreate({
subject: "REFACTOR-B{NN}",
description: "PURPOSE: Implement refactoring REFACTOR-{NNN} | Success: Single refactoring applied, compiles, tests pass
TASK:
- Load refactoring detail from branches/B{NN}/refactoring-detail.md
- Apply this single refactoring to target files
- Update all import references for moved/renamed modules
- Validate changes compile and pass existing tests
CONTEXT:
- Session: <session-folder>
- Branch: B{NN}
- Upstream artifacts: branches/B{NN}/refactoring-detail.md
- Shared memory: <session>/wisdom/.msg/meta.json (namespace: refactorer.B{NN})
EXPECTED: Modified source files for REFACTOR-{NNN} only
CONSTRAINTS: Only implement this branch's refactoring | Do not touch files outside REFACTOR-{NNN} scope
---
InnerLoop: false
BranchId: B{NN}"
})
TaskUpdate({ taskId: "REFACTOR-B{NN}", addBlockedBy: ["DESIGN-001"], owner: "refactorer" })
TaskCreate({
subject: "VALIDATE-B{NN}",
description: "PURPOSE: Validate branch B{NN} refactoring | Success: REFACTOR-{NNN} passes build, tests, and metric checks
TASK:
- Load architecture baseline and REFACTOR-{NNN} success criteria
- Validate build, tests, dependency metrics, and API compatibility
- Compare against baseline, check for regressions
CONTEXT:
- Session: <session-folder>
- Branch: B{NN}
- Upstream artifacts: architecture-baseline.json, branches/B{NN}/refactoring-detail.md
- Shared memory: <session>/wisdom/.msg/meta.json (namespace: validator.B{NN})
EXPECTED: <session>/artifacts/branches/B{NN}/validation-results.json
CONSTRAINTS: Only validate this branch's changes
---
InnerLoop: false
BranchId: B{NN}"
})
TaskUpdate({ taskId: "VALIDATE-B{NN}", addBlockedBy: ["REFACTOR-B{NN}"], owner: "validator" })
TaskCreate({
subject: "REVIEW-B{NN}",
description: "PURPOSE: Review branch B{NN} refactoring code | Success: Code quality verified for REFACTOR-{NNN}
TASK:
- Load modified files from refactorer.B{NN} namespace in .msg/meta.json
- Review across 5 dimensions for this branch's changes only
- Issue verdict: APPROVE, REVISE, or REJECT
CONTEXT:
- Session: <session-folder>
- Branch: B{NN}
- Upstream artifacts: branches/B{NN}/refactoring-detail.md
- Shared memory: <session>/wisdom/.msg/meta.json (namespace: reviewer.B{NN})
EXPECTED: <session>/artifacts/branches/B{NN}/review-report.md
CONSTRAINTS: Only review this branch's changes
---
InnerLoop: false
BranchId: B{NN}"
})
TaskUpdate({ taskId: "REVIEW-B{NN}", addBlockedBy: ["REFACTOR-B{NN}"], owner: "reviewer" })7. Update session.json:
branches: array of branch IDs (["B01", "B02", ...])fix_cycles: object keyed by branch ID, all initialized to 0
---
Phase 4: Validation
Verify task chain integrity:
| Check | Method | Expected |
|---|---|---|
| Task count correct | TaskList count | single: 5, auto/fan-out: 2 (pre-CP-2.5), independent: 5*M |
| Dependencies correct | Trace dependency graph | Acyclic, correct blockedBy |
| No circular dependencies | Trace dependency graph | Acyclic |
| Task IDs use correct prefixes | Pattern check | Match naming rules per mode |
| Structured descriptions complete | Each has PURPOSE/TASK/CONTEXT/EXPECTED/CONSTRAINTS | All present |
| Branch/Pipeline IDs consistent | Cross-check with session.json | Match |
Naming Rules Summary
| Mode | Stage 3 | Stage 4 | Fix |
|---|---|---|---|
| Single | REFACTOR-001 | VALIDATE-001, REVIEW-001 | FIX-001, FIX-002 |
| Fan-out | REFACTOR-B01 | VALIDATE-B01, REVIEW-B01 | FIX-B01-1, FIX-B01-2 |
| Independent | REFACTOR-A01 | VALIDATE-A01, REVIEW-A01 | FIX-A01-1, FIX-A01-2 |
If validation fails, fix the specific task and re-validate.
Monitor Pipeline
Event-driven pipeline coordination. Beat model: coordinator wake -> process -> spawn -> STOP.
Constants
- SPAWN_MODE: background
- ONE_STEP_PER_INVOCATION: true
- FAST_ADVANCE_AWARE: true
- WORKER_AGENT: team-worker
Handler Router
| Source | Handler |
|---|---|
| Message contains [analyzer], [designer], [refactorer], [validator], [reviewer] | handleCallback |
| Message contains branch tag [refactorer-B01], etc. | handleCallback (branch-aware) |
| Message contains pipeline tag [analyzer-A], etc. | handleCallback (pipeline-aware) |
| "consensus_blocked" | handleConsensus |
| "capability_gap" | handleAdapt |
| "check" or "status" | handleCheck |
| "resume" or "continue" | handleResume |
| All tasks completed | handleComplete |
| Default | handleSpawnNext |
handleCallback
Worker completed. Process and advance.
1. Parse message to identify role, task ID, and branch/pipeline label:
| Message Pattern | Branch Detection |
|---|---|
[refactorer-B01] or task ID REFACTOR-B01 | Branch B01 (fan-out) |
[analyzer-A] or task ID ANALYZE-A01 | Pipeline A (independent) |
[analyzer] or task ID ANALYZE-001 | No branch (single) |
2. Mark task as completed: TaskUpdate({ taskId: "<task-id>", status: "completed" }) 3. Record completion in session state 4. CP-2.5 check (auto/fan-out mode only):
- If completed task is DESIGN-001 AND parallel_mode is
autoorfan-out: - Execute CP-2.5 Branch Creation from dispatch.md
- After branch creation, proceed to handleSpawnNext (spawns all REFACTOR-B* in parallel)
- STOP after spawning
5. Check stage checkpoints:
| Completed Task | Checkpoint | Action |
|---|---|---|
| ANALYZE-001 / ANALYZE-{P}01 | CP-1 | Notify user: architecture report ready |
| DESIGN-001 / DESIGN-{P}01 | CP-2 | Notify user: refactoring plan ready |
| DESIGN-001 (auto/fan-out) | CP-2.5 | Execute branch creation, notify with branch count |
| VALIDATE- or REVIEW- | CP-3 | Check verdicts per branch (see Review-Fix Cycle) |
6. Proceed to handleSpawnNext
handleCheck
Read-only status report, then STOP.
Worker Progress (from message bus):
Before generating status output, read worker milestones:
const progressMsgs = mcp__ccw-tools__team_msg({
operation: "list", session_id: sessionId, type: "progress", last: 50
})
const blockerMsgs = mcp__ccw-tools__team_msg({
operation: "list", session_id: sessionId, type: "blocker", last: 10
})
// Aggregate latest milestone per task
const taskProgress = {}
for (const msg of (progressMsgs.result?.messages || [])) {
const tid = msg.data?.task_id
if (tid && (!taskProgress[tid] || msg.ts > taskProgress[tid].ts)) {
taskProgress[tid] = { phase: msg.data.phase, pct: msg.data.progress_pct, ts: msg.ts }
}
}Include in status output:
- Per-worker latest milestone (phase + progress_pct) next to task status
- Active blockers section (if any blockerMsgs found)
Output (single mode):
[coordinator] Pipeline Status
[coordinator] Progress: <done>/<total> (<pct>%)
[coordinator] Active: <workers with elapsed time>
[coordinator] Ready: <pending tasks with resolved deps>
[coordinator] Commands: 'resume' to advance | 'check' to refreshFan-out mode adds per-branch grouping. Independent mode adds per-pipeline grouping.
handleResume
1. Audit task list: Tasks stuck in "in_progress" -> reset to "pending" 2. For fan-out/independent: check each branch/pipeline independently 3. Proceed to handleSpawnNext
handleSpawnNext
Find ready tasks, spawn workers, STOP.
1. Collect: completedSubjects, inProgressSubjects, readySubjects 2. No ready + work in progress -> report waiting, STOP 3. No ready + nothing in progress -> handleComplete 4. Has ready -> for each: a. Check inner_loop: parse task description InnerLoop: field (NOT role.md default)
- InnerLoop: true AND same-role worker already active -> skip (worker picks up)
- InnerLoop: false OR no active same-role worker -> spawn new worker
b. TaskUpdate -> in_progress c. team_msg log -> task_unblocked d. Spawn team-worker (see SKILL.md Spawn Template):
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker for <task-id>",
team_name: "arch-opt",
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: ~ or <project>/.claude/skills/team-arch-opt/roles/<role>/role.md
session: <session-folder>
session_id: <session-id>
team_name: arch-opt
requirement: <task-description>
inner_loop: <true|false>
## Progress Milestones
session_id: <session-id>
Report progress via team_msg at natural phase boundaries (context loaded -> core work done -> verification).
Report blockers immediately via team_msg type="blocker".
Report completion via team_msg type="task_complete" after final SendMessage.
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).`
})e. Add to active_workers 5. Parallel spawn rules by mode:
| Mode | Scenario | Spawn Behavior |
|---|---|---|
| Single | Stage 4 ready | Spawn VALIDATE-001 + REVIEW-001 in parallel |
| Fan-out (CP-2.5 done) | All REFACTOR-B* unblocked | Spawn ALL REFACTOR-B* in parallel |
| Fan-out (REFACTOR-B{NN} done) | VALIDATE + REVIEW ready | Spawn both for that branch in parallel |
| Independent | Any unblocked task | Spawn all ready tasks across all pipelines in parallel |
6. Update session, output summary, STOP
Review-Fix Cycle (CP-3)
Per-branch/pipeline scoping: Each branch/pipeline has its own independent fix cycle.
When both VALIDATE- and REVIEW- are completed for a branch/pipeline:
1. Read validation verdict from scoped meta.json namespace 2. Read review verdict from scoped meta.json namespace
| Validate Verdict | Review Verdict | Action |
|---|---|---|
| PASS | APPROVE | -> handleComplete check |
| PASS | REVISE | Create FIX task with review feedback |
| FAIL | APPROVE | Create FIX task with validation feedback |
| FAIL | REVISE/REJECT | Create FIX task with combined feedback |
| Any | REJECT | Create FIX task + flag for designer re-evaluation |
Fix cycle tracking per branch in session.json fix_cycles:
- < 3: Create FIX task, increment cycle count
- >= 3: Escalate THIS branch to user. Other branches continue
handleComplete
Pipeline done. Generate report and completion action.
Completion check by mode:
| Mode | Completion Condition |
|---|---|
| Single | All 5 tasks (+ any FIX/retry tasks) completed |
| Fan-out | ALL branches have VALIDATE + REVIEW completed (or escalated), shared stages done |
| Independent | ALL pipelines have VALIDATE + REVIEW completed (or escalated) |
1. For fan-out/independent: aggregate per-branch/pipeline results to <session>/artifacts/aggregate-results.json 2. If any tasks not completed, return to handleSpawnNext 3. If all completed -> transition to coordinator Phase 5
handleConsensus
Handle consensus_blocked signals from discuss rounds.
| Severity | Action |
|---|---|
| HIGH | Pause pipeline (or branch), notify user with findings summary |
| MEDIUM | Create revision task for the blocked role (scoped to branch if applicable) |
| LOW | Log finding, continue pipeline |
handleAdapt
Capability gap reported mid-pipeline.
1. Parse gap description 2. Check if existing role covers it -> redirect 3. Role count < 5 -> generate dynamic role-spec in <session>/role-specs/ 4. Create new task, spawn worker 5. Role count >= 5 -> merge or pause
Fast-Advance Reconciliation
On every coordinator wake: 1. Read team_msg entries with type="fast_advance" 2. Sync active_workers with spawned successors 3. No duplicate spawns
Coordinator
Orchestrate team-arch-opt: analyze -> dispatch -> spawn -> monitor -> report.
Identity
- Name: coordinator | Tag: [coordinator]
- Responsibility: Analyze task -> Create team -> Dispatch tasks -> Monitor progress -> Report results
Boundaries
MUST
- Use
team-workeragent type for all worker spawns (NOTgeneral-purpose) - Follow Command Execution Protocol for dispatch and monitor commands
- Respect pipeline stage dependencies (blockedBy)
- Stop after spawning workers -- wait for callbacks
- Handle review-fix cycles with max 3 iterations
- Execute completion action in Phase 5
MUST NOT
- Implement domain logic (analyzing, refactoring, reviewing) -- workers handle this
- Spawn workers without creating tasks first
- Skip checkpoints when configured
- Force-advance pipeline past failed review/validation
- Modify source code directly -- delegate to refactorer worker
Command Execution Protocol
When coordinator needs to execute a specific phase: 1. Read commands/<command>.md 2. Follow the workflow defined in the command 3. Commands are inline execution guides, NOT separate agents 4. Execute synchronously, complete before proceeding
Entry Router
| Detection | Condition | Handler |
|---|---|---|
| Worker callback | Message contains [analyzer], [designer], [refactorer], [validator], [reviewer] | -> handleCallback (monitor.md) |
| Branch callback | Message contains [refactorer-B01], [validator-B02], etc. | -> handleCallback branch-aware (monitor.md) |
| Pipeline callback | Message contains [analyzer-A], [refactorer-B], etc. | -> handleCallback pipeline-aware (monitor.md) |
| Consensus blocked | Message contains "consensus_blocked" | -> handleConsensus (monitor.md) |
| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) |
| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) |
| Capability gap | Message contains "capability_gap" | -> handleAdapt (monitor.md) |
| Pipeline complete | All tasks completed | -> handleComplete (monitor.md) |
| Interrupted session | Active session in .workflow/.team/TAO-* | -> Phase 0 |
| New session | None of above | -> Phase 1 |
For callback/check/resume/consensus/adapt/complete: load @commands/monitor.md, execute handler, STOP.
Phase 0: Session Resume Check
1. Scan .workflow/.team/TAO-*/session.json for active/paused sessions 2. No sessions -> Phase 1 3. Single session -> reconcile (audit TaskList, reset in_progress->pending, rebuild team, kick first ready task) 4. Multiple -> AskUserQuestion for selection
Phase 1: Requirement Clarification
TEXT-LEVEL ONLY. No source code reading.
1. Parse task description from $ARGUMENTS 2. Parse parallel mode flags:
| Flag | Value | Default |
|---|---|---|
--parallel-mode | single, fan-out, independent, auto | auto |
--max-branches | integer 1-10 | 5 |
3. Identify architecture optimization target:
| Signal | Target |
|---|---|
| Specific file/module mentioned | Scoped refactoring |
| "coupling", "dependency", "structure", generic | Full architecture analysis |
| Specific issue (cycles, God Class, duplication) | Targeted issue resolution |
| Multiple quoted targets (independent mode) | Per-target scoped refactoring |
4. If target is unclear, AskUserQuestion for scope clarification 5. Record requirement with scope, target issues, parallel_mode, max_branches
Phase 2: Create Team + Initialize Session
1. Resolve workspace paths (MUST do first):
project_root= result ofBash({ command: "pwd" })skill_root=<project_root>/.claude/skills/team-arch-opt
2. Generate session ID: TAO-<slug>-<date> 3. Create session folder structure 4. TeamCreate with team name arch-opt 5. Write session.json with parallel_mode, max_branches, branches, independent_targets, fix_cycles 6. Initialize meta.json via team_msg state_update:
mcp__ccw-tools__team_msg({
operation: "log", session_id: "<id>", from: "coordinator",
type: "state_update", summary: "Session initialized",
data: { pipeline_mode: "<mode>", pipeline_stages: ["analyzer","designer","refactorer","validator","reviewer"], team_name: "arch-opt" }
})7. Write session.json
Phase 3: Create Task Chain
Delegate to @commands/dispatch.md: 1. Read dependency graph and parallel mode from session.json 2. Topological sort tasks 3. Create tasks via TaskCreate, then set dependencies via TaskUpdate({ addBlockedBy }) 4. Update session.json with task count
Phase 4: Spawn-and-Stop
Delegate to @commands/monitor.md#handleSpawnNext: 1. Find ready tasks (pending + blockedBy resolved) 2. Spawn team-worker agents (see SKILL.md Spawn Template) 3. Output status summary 4. STOP
Phase 5: Report + Completion Action
1. Load session state -> count completed tasks, calculate duration 2. List deliverables:
| Deliverable | Path |
|---|---|
| Architecture Baseline | <session>/artifacts/architecture-baseline.json |
| Architecture Report | <session>/artifacts/architecture-report.md |
| Refactoring Plan | <session>/artifacts/refactoring-plan.md |
| Validation Results | <session>/artifacts/validation-results.json |
| Review Report | <session>/artifacts/review-report.md |
3. Include discussion summaries if discuss rounds were used 4. Output pipeline summary: task count, duration, improvement metrics
5. Execute completion action per session.completion_action:
- interactive -> AskUserQuestion (Archive/Keep/Export)
- auto_archive -> Archive & Clean (status=completed, TeamDelete)
- auto_keep -> Keep Active (status=paused)
Error Handling
| Error | Resolution |
|---|---|
| Task too vague | AskUserQuestion for clarification |
| Session corruption | Attempt recovery, fallback to manual |
| Worker crash | Reset task to pending, respawn |
| Dependency cycle | Detect in analysis, halt |
| Role limit exceeded | Merge overlapping roles |
Refactoring Designer
Analyze architecture reports and baseline metrics to design a prioritized refactoring plan with concrete strategies, expected structural improvements, and risk assessments.
Phase 2: Analysis Loading
| Input | Source | Required |
|---|---|---|
| Architecture report | <session>/artifacts/architecture-report.md | Yes |
| Architecture baseline | <session>/artifacts/architecture-baseline.json | Yes |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
| Wisdom files | <session>/wisdom/patterns.md | No |
1. Extract session path from task description 2. Read architecture report -- extract ranked issue list with severities and categories 3. Read architecture baseline -- extract current structural metrics 4. Load .msg/meta.json for analyzer findings (project_type, scope) 5. Assess overall refactoring complexity:
| Issue Count | Severity Mix | Complexity |
|---|---|---|
| 1-2 | All Medium | Low |
| 2-3 | Mix of High/Medium | Medium |
| 3+ or any Critical | Any Critical present | High |
Phase 3: Strategy Formulation
For each architecture issue, select refactoring approach by type:
| Issue Type | Strategies | Risk Level |
|---|---|---|
| Circular dependency | Interface extraction, dependency inversion, mediator pattern | High |
| God Class/Module | SRP decomposition, extract class/module, delegate pattern | High |
| Layering violation | Move to correct layer, introduce Facade, add anti-corruption layer | Medium |
| Code duplication | Extract shared utility/base class, template method pattern | Low |
| High coupling | Introduce interface/abstraction, dependency injection, event-driven | Medium |
| API bloat / dead exports | Privatize internals, re-export only public API, barrel file cleanup | Low |
| Dead code | Safe removal with reference verification | Low |
| Missing abstraction | Extract interface/type, introduce strategy/factory pattern | Medium |
Prioritize refactorings by impact/effort ratio:
| Priority | Criteria |
|---|---|
| P0 (Critical) | High impact + Low effort -- quick wins (dead code removal, simple moves) |
| P1 (High) | High impact + Medium effort (cycle breaking, layer fixes) |
| P2 (Medium) | Medium impact + Low effort (duplication extraction) |
| P3 (Low) | Low impact or High effort -- defer (large God Class decomposition) |
If complexity is High, invoke discuss CLI tool (DISCUSS-REFACTOR round) to evaluate trade-offs between competing strategies before finalizing the plan.
Define measurable success criteria per refactoring (target metric improvement or structural change).
Phase 4: Plan Output
1. Write refactoring plan to <session>/artifacts/refactoring-plan.md:
Each refactoring MUST have a unique REFACTOR-ID and self-contained detail block:
### REFACTOR-001: <title>
- Priority: P0
- Target issue: <issue from report>
- Issue type: <CYCLE|COUPLING|GOD_CLASS|DUPLICATION|LAYER_VIOLATION|DEAD_CODE|API_BLOAT>
- Target files: <file-list>
- Strategy: <selected approach>
- Expected improvement: <metric> by <description>
- Risk level: <Low/Medium/High>
- Success criteria: <specific structural change to verify>
- Implementation guidance:
1. <step 1>
2. <step 2>
3. <step 3>
### REFACTOR-002: <title>
...Requirements:
- Each REFACTOR-ID is sequentially numbered (REFACTOR-001, REFACTOR-002, ...)
- Each refactoring must be non-overlapping in target files (no two REFACTOR-IDs modify the same file unless explicitly noted with conflict resolution)
- Implementation guidance must be self-contained -- a branch refactorer should be able to work from a single REFACTOR block without reading others
2. Update <session>/wisdom/.msg/meta.json under designer namespace:
- Read existing -> merge -> write back:
{
"designer": {
"complexity": "<Low|Medium|High>",
"refactoring_count": 4,
"priorities": ["P0", "P0", "P1", "P2"],
"discuss_used": false,
"refactorings": [
{
"id": "REFACTOR-001",
"title": "<title>",
"issue_type": "<CYCLE|COUPLING|...>",
"priority": "P0",
"target_files": ["src/a.ts", "src/b.ts"],
"expected_improvement": "<metric> by <description>",
"success_criteria": "<threshold>"
}
]
}
}3. If DISCUSS-REFACTOR was triggered, record discussion summary in <session>/discussions/DISCUSS-REFACTOR.md
Code Refactorer
inner_loop: dynamic — Dispatch sets per-task:truefor single mode (one REFACTOR task with iterative fix cycles),falsefor fan-out/independent modes (REFACTOR-B01..N run as separate parallel workers). When false, each branch gets its own worker.
Implement architecture refactoring changes following the design plan. For FIX tasks, apply targeted corrections based on review/validation feedback.
Modes
| Mode | Task Prefix | Trigger | Focus |
|---|---|---|---|
| Refactor | REFACTOR | Design plan ready | Apply refactorings per plan priority |
| Fix | FIX | Review/validation feedback | Targeted fixes for identified issues |
Phase 2: Plan & Context Loading
| Input | Source | Required |
|---|---|---|
| Refactoring plan | <session>/artifacts/refactoring-plan.md | Yes (REFACTOR, no branch) |
| Branch refactoring detail | <session>/artifacts/branches/B{NN}/refactoring-detail.md | Yes (REFACTOR with branch) |
| Pipeline refactoring plan | <session>/artifacts/pipelines/{P}/refactoring-plan.md | Yes (REFACTOR with pipeline) |
| Review/validation feedback | From task description | Yes (FIX) |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
| Wisdom files | <session>/wisdom/patterns.md | No |
| Context accumulator | From prior REFACTOR/FIX tasks | Yes (inner loop) |
1. Extract session path and task mode (REFACTOR or FIX) from task description 2. Detect branch/pipeline context from task description:
| Task Description Field | Value | Context |
|---|---|---|
BranchId: B{NN} | Present | Fan-out branch -- load single refactoring detail |
PipelineId: {P} | Present | Independent pipeline -- load pipeline-scoped plan |
| Neither present | - | Single mode -- load full refactoring plan |
3. Load refactoring context by mode:
- Single mode (no branch): Read
<session>/artifacts/refactoring-plan.md-- extract ALL priority-ordered changes - Fan-out branch: Read
<session>/artifacts/branches/B{NN}/refactoring-detail.md-- extract ONLY this branch's refactoring (single REFACTOR-ID) - Independent pipeline: Read
<session>/artifacts/pipelines/{P}/refactoring-plan.md-- extract this pipeline's plan
4. For FIX: parse review/validation feedback for specific issues to address 5. Use explore CLI tool to load implementation context for target files 6. For inner loop (single mode only): load context_accumulator from prior REFACTOR/FIX tasks
Meta.json namespace:
- Single: write to
refactorernamespace - Fan-out: write to
refactorer.B{NN}namespace - Independent: write to
refactorer.{P}namespace
Phase 3: Code Implementation
Implementation backend selection:
| Backend | Condition | Method |
|---|---|---|
| CLI | Multi-file refactoring with clear plan | ccw cli --tool gemini --mode write |
| Direct | Single-file changes or targeted fixes | Inline Edit/Write tools |
For REFACTOR tasks:
- Single mode: Apply refactorings in plan priority order (P0 first, then P1, etc.)
- Fan-out branch: Apply ONLY this branch's single refactoring (from refactoring-detail.md)
- Independent pipeline: Apply this pipeline's refactorings in priority order
- Follow implementation guidance from plan (target files, patterns)
- Preserve existing behavior -- refactoring must not change functionality
- Update ALL import references when moving/renaming modules
- Update ALL test files that reference moved/renamed symbols
For FIX tasks:
- Read specific issues from review/validation feedback
- Apply targeted corrections to flagged code locations
- Verify the fix addresses the exact concern raised
General rules:
- Make minimal, focused changes per refactoring
- Add comments only where refactoring logic is non-obvious
- Preserve existing code style and conventions
- Verify no dangling imports after module moves
Phase 4: Self-Validation
| Check | Method | Pass Criteria |
|---|---|---|
| Syntax | IDE diagnostics or build check | No new errors |
| File integrity | Verify all planned files exist and are modified | All present |
| Import integrity | Verify no broken imports after moves | All imports resolve |
| Acceptance | Match refactoring plan success criteria | All structural changes applied |
| No regression | Run existing tests if available | No new failures |
If validation fails, attempt auto-fix (max 2 attempts) before reporting error.
Append to context_accumulator for next REFACTOR/FIX task (single/inner-loop mode only):
- Files modified, refactorings applied, validation results
- Any discovered patterns or caveats for subsequent iterations
Branch output paths:
- Single: write artifacts to
<session>/artifacts/ - Fan-out: write artifacts to
<session>/artifacts/branches/B{NN}/ - Independent: write artifacts to
<session>/artifacts/pipelines/{P}/
Architecture Reviewer
Review refactoring code changes for correctness, pattern consistency, completeness, migration safety, and adherence to best practices. Provide structured verdicts with actionable feedback.
Phase 2: Context Loading
| Input | Source | Required |
|---|---|---|
| Refactoring code changes | From REFACTOR task artifacts / git diff | Yes |
| Refactoring plan / detail | Varies by mode (see below) | Yes |
| Validation results | Varies by mode (see below) | No |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
1. Extract session path from task description 2. Detect branch/pipeline context from task description:
| Task Description Field | Value | Context |
|---|---|---|
BranchId: B{NN} | Present | Fan-out branch -- review only this branch's changes |
PipelineId: {P} | Present | Independent pipeline -- review pipeline-scoped changes |
| Neither present | - | Single mode -- review all refactoring changes |
3. Load refactoring context by mode:
- Single: Read
<session>/artifacts/refactoring-plan.md - Fan-out branch: Read
<session>/artifacts/branches/B{NN}/refactoring-detail.md - Independent: Read
<session>/artifacts/pipelines/{P}/refactoring-plan.md
4. Load .msg/meta.json for scoped refactorer namespace:
- Single:
refactorernamespace - Fan-out:
refactorer.B{NN}namespace - Independent:
refactorer.{P}namespace
5. Identify changed files from refactorer context -- read ONLY files modified by this branch/pipeline 6. If validation results available, read from scoped path:
- Single:
<session>/artifacts/validation-results.json - Fan-out:
<session>/artifacts/branches/B{NN}/validation-results.json - Independent:
<session>/artifacts/pipelines/{P}/validation-results.json
Phase 3: Multi-Dimension Review
Analyze refactoring changes across five dimensions:
| Dimension | Focus | Severity |
|---|---|---|
| Correctness | No behavior changes, all references updated, no dangling imports | Critical |
| Pattern consistency | Follows existing patterns, naming consistent, language-idiomatic | High |
| Completeness | All related code updated (imports, tests, config, documentation) | High |
| Migration safety | No dangling references, backward compatible, public API preserved | Critical |
| Best practices | Clean Architecture / SOLID principles, appropriate abstraction level | Medium |
Per-dimension review process:
- Scan modified files for patterns matching each dimension
- Record findings with severity (Critical / High / Medium / Low)
- Include specific file:line references and suggested fixes
Correctness checks:
- Verify moved code preserves original behavior (no logic changes mixed with structural changes)
- Check all import/require statements updated to new paths
- Verify no orphaned files left behind after moves
Pattern consistency checks:
- New module names follow existing naming conventions
- Extracted interfaces/classes use consistent patterns with existing codebase
- File organization matches project conventions (e.g., index files, barrel exports)
Completeness checks:
- All test files updated for moved/renamed modules
- Configuration files updated if needed (e.g., path aliases, build configs)
- Type definitions updated for extracted interfaces
Migration safety checks:
- Public API surface unchanged (same exports available to consumers)
- No circular dependencies introduced by the refactoring
- Re-exports in place if module paths changed for backward compatibility
Best practices checks:
- Extracted modules have clear single responsibility
- Dependency direction follows layer conventions (dependencies flow inward)
- Appropriate abstraction level (not over-engineered, not under-abstracted)
If any Critical findings detected, invoke discuss CLI tool (DISCUSS-REVIEW round) to validate the assessment before issuing verdict.
Phase 4: Verdict & Feedback
Classify overall verdict based on findings:
| Verdict | Condition | Action |
|---|---|---|
| APPROVE | No Critical or High findings | Send review_complete |
| REVISE | Has High findings, no Critical | Send fix_required with detailed feedback |
| REJECT | Has Critical findings or fundamental approach flaw | Send fix_required + flag for designer escalation |
1. Write review report to scoped output path:
- Single:
<session>/artifacts/review-report.md - Fan-out:
<session>/artifacts/branches/B{NN}/review-report.md - Independent:
<session>/artifacts/pipelines/{P}/review-report.md - Content: Per-dimension findings with severity, file:line, description; Overall verdict with rationale; Specific fix instructions for REVISE/REJECT verdicts
2. Update <session>/wisdom/.msg/meta.json under scoped namespace:
- Single: merge
{ "reviewer": { verdict, finding_count, critical_count, dimensions_reviewed } } - Fan-out: merge
{ "reviewer.B{NN}": { verdict, finding_count, critical_count, dimensions_reviewed } } - Independent: merge
{ "reviewer.{P}": { verdict, finding_count, critical_count, dimensions_reviewed } }
3. If DISCUSS-REVIEW was triggered, record discussion summary in <session>/discussions/DISCUSS-REVIEW.md (or DISCUSS-REVIEW-B{NN}.md for branch-scoped discussions)
Architecture Validator
Validate refactoring changes by running build checks, test suites, dependency metric comparisons, and API compatibility verification. Ensure refactoring improves architecture without breaking functionality.
Phase 2: Environment & Baseline Loading
| Input | Source | Required |
|---|---|---|
| Architecture baseline | <session>/artifacts/architecture-baseline.json (shared) | Yes |
| Refactoring plan / detail | Varies by mode (see below) | Yes |
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
1. Extract session path from task description 2. Detect branch/pipeline context from task description:
| Task Description Field | Value | Context |
|---|---|---|
BranchId: B{NN} | Present | Fan-out branch -- validate only this branch's changes |
PipelineId: {P} | Present | Independent pipeline -- use pipeline-scoped baseline |
| Neither present | - | Single mode -- full validation |
3. Load architecture baseline:
- Single / Fan-out: Read
<session>/artifacts/architecture-baseline.json(shared baseline) - Independent: Read
<session>/artifacts/pipelines/{P}/architecture-baseline.json
4. Load refactoring context:
- Single: Read
<session>/artifacts/refactoring-plan.md-- all success criteria - Fan-out branch: Read
<session>/artifacts/branches/B{NN}/refactoring-detail.md-- only this branch's criteria - Independent: Read
<session>/artifacts/pipelines/{P}/refactoring-plan.md
5. Load .msg/meta.json for project type and refactoring scope 6. Detect available validation tools from project:
| Signal | Validation Tool | Method |
|---|---|---|
| package.json + tsc | TypeScript compiler | Type-check entire project |
| package.json + vitest/jest | Test runner | Run existing test suite |
| package.json + eslint | Linter | Run lint checks for import/export issues |
| Cargo.toml | Rust compiler | cargo check + cargo test |
| go.mod | Go tools | go build + go test |
| Makefile with test target | Custom tests | make test |
| No tooling detected | Manual validation | File existence + import grep checks |
7. Get changed files scope from .msg/meta.json:
- Single:
refactorernamespace - Fan-out:
refactorer.B{NN}namespace - Independent:
refactorer.{P}namespace
Phase 3: Validation Execution
Run validations across four dimensions:
Build validation:
- Compile/type-check the project -- zero new errors allowed
- Verify all moved/renamed files are correctly referenced
- Check for missing imports or unresolved modules
Test validation:
- Run existing test suite -- all previously passing tests must still pass
- Identify any tests that need updating due to module moves (update, don't skip)
- Check for test file imports that reference old paths
Dependency metric validation:
- Recalculate architecture metrics post-refactoring
- Compare coupling scores against baseline (must improve or stay neutral)
- Verify no new circular dependencies introduced
- Check cohesion metrics for affected modules
API compatibility validation:
- Verify public API signatures are preserved (exported function/class/type names)
- Check for dangling references (imports pointing to removed/moved files)
- Verify no new dead exports introduced by the refactoring
- Check that re-exports maintain backward compatibility where needed
Branch-scoped validation (fan-out mode):
- Only validate metrics relevant to this branch's refactoring (from refactoring-detail.md)
- Still check for regressions across all metrics (not just branch-specific ones)
Phase 4: Result Analysis
Compare against baseline and plan criteria:
| Metric | Threshold | Verdict |
|---|---|---|
| Build passes | Zero compilation errors | PASS |
| All tests pass | No new test failures | PASS |
| Coupling improved or neutral | No metric degradation > 5% | PASS |
| No new cycles introduced | Cycle count <= baseline | PASS |
| All plan success criteria met | Every criterion satisfied | PASS |
| Partial improvement | Some metrics improved, none degraded | WARN |
| Build fails | Compilation errors detected | FAIL -> fix_required |
| Test failures | Previously passing tests now fail | FAIL -> fix_required |
| New cycles introduced | Cycle count > baseline | FAIL -> fix_required |
| Dangling references | Unresolved imports detected | FAIL -> fix_required |
1. Write validation results to output path:
- Single:
<session>/artifacts/validation-results.json - Fan-out:
<session>/artifacts/branches/B{NN}/validation-results.json - Independent:
<session>/artifacts/pipelines/{P}/validation-results.json - Content: Per-dimension: name, baseline value, current value, improvement/regression, verdict; Overall verdict: PASS / WARN / FAIL; Failure details (if any)
2. Update <session>/wisdom/.msg/meta.json under scoped namespace:
- Single: merge
{ "validator": { verdict, improvements, regressions, build_pass, test_pass } } - Fan-out: merge
{ "validator.B{NN}": { verdict, improvements, regressions, build_pass, test_pass } } - Independent: merge
{ "validator.{P}": { verdict, improvements, regressions, build_pass, test_pass } }
3. If verdict is FAIL, include detailed feedback in message for FIX task creation:
- Which validations failed, specific errors, suggested investigation areas
Pipeline Definitions — team-arch-opt
Available Pipelines
Single Mode (Linear)
ANALYZE-001 → DESIGN-001 → REFACTOR-001 → VALIDATE-001 + REVIEW-001
[analyzer] [designer] [refactorer] [validator] [reviewer]
^ |
+<-- FIX-001 ----+
(max 3 iterations)Fan-out Mode (Shared Stages + Parallel Branches)
ANALYZE-001 → DESIGN-001 --+→ REFACTOR-B01 → VALIDATE-B01 + REVIEW-B01
[analyzer] [designer] | [refactorer] [validator] [reviewer]
+→ REFACTOR-B02 → VALIDATE-B02 + REVIEW-B02
+→ REFACTOR-B0N → VALIDATE-B0N + REVIEW-B0N
|
AGGREGATE → Phase 5Branch tasks created at CP-2.5 after DESIGN-001 completes.
Independent Mode (M Complete Pipelines)
Pipeline A: ANALYZE-A01 → DESIGN-A01 → REFACTOR-A01 → VALIDATE-A01 + REVIEW-A01
Pipeline B: ANALYZE-B01 → DESIGN-B01 → REFACTOR-B01 → VALIDATE-B01 + REVIEW-B01
... |
AGGREGATE → Phase 5Auto Mode
Auto-detects based on refactoring count at CP-2.5:
- count <= 2 → switch to single mode
- count >= 3 → switch to fan-out mode
Task Metadata Registry
Single Mode
| Task ID | Role | Phase | Dependencies | Description |
|---|---|---|---|---|
| ANALYZE-001 | analyzer | Stage 1 | (none) | Analyze architecture, identify structural issues |
| DESIGN-001 | designer | Stage 2 | ANALYZE-001 | Design refactoring plan from architecture report |
| REFACTOR-001 | refactorer | Stage 3 | DESIGN-001 | Implement highest-priority refactorings |
| VALIDATE-001 | validator | Stage 4 | REFACTOR-001 | Validate build, tests, metrics, API compatibility |
| REVIEW-001 | reviewer | Stage 4 | REFACTOR-001 | Review refactoring code for correctness |
| FIX-001 | refactorer | Stage 3 (cycle) | REVIEW-001 or VALIDATE-001 | Fix issues found in review/validation |
Fan-out Mode (Branch Tasks at CP-2.5)
| Task ID | Role | Phase | Dependencies | Description |
|---|---|---|---|---|
| ANALYZE-001 | analyzer | Stage 1 (shared) | (none) | Analyze architecture |
| DESIGN-001 | designer | Stage 2 (shared) | ANALYZE-001 | Design plan with discrete REFACTOR-IDs |
| REFACTOR-B{NN} | refactorer | Stage 3 (branch) | DESIGN-001 | Implement REFACTOR-{NNN} only |
| VALIDATE-B{NN} | validator | Stage 4 (branch) | REFACTOR-B{NN} | Validate branch B{NN} |
| REVIEW-B{NN} | reviewer | Stage 4 (branch) | REFACTOR-B{NN} | Review branch B{NN} |
| FIX-B{NN}-{cycle} | refactorer | Fix (branch) | (none) | Fix issues in branch B{NN} |
Independent Mode
| Task ID | Role | Phase | Dependencies | Description |
|---|---|---|---|---|
| ANALYZE-{P}01 | analyzer | Stage 1 | (none) | Analyze for pipeline {P} target |
| DESIGN-{P}01 | designer | Stage 2 | ANALYZE-{P}01 | Design for pipeline {P} |
| REFACTOR-{P}01 | refactorer | Stage 3 | DESIGN-{P}01 | Implement pipeline {P} refactorings |
| VALIDATE-{P}01 | validator | Stage 4 | REFACTOR-{P}01 | Validate pipeline {P} |
| REVIEW-{P}01 | reviewer | Stage 4 | REFACTOR-{P}01 | Review pipeline {P} |
Checkpoints
| Checkpoint | Trigger | Location | Behavior |
|---|---|---|---|
| CP-1 | ANALYZE-001 complete | After Stage 1 | User reviews architecture report, can refine scope |
| CP-2 | DESIGN-001 complete | After Stage 2 | User reviews refactoring plan, can adjust priorities |
| CP-2.5 | DESIGN-001 complete (auto/fan-out) | After Stage 2 | Auto-create N branch tasks, spawn all REFACTOR-B* in parallel |
| CP-3 | REVIEW/VALIDATE fail | Stage 4 (per-branch) | Auto-create FIX task for that branch only (max 3x per branch) |
| CP-4 | All tasks/branches complete | Phase 5 | Aggregate results, interactive completion action |
Task Naming Rules
| Mode | Stage 3 | Stage 4 | Fix | Retry |
|---|---|---|---|---|
| Single | REFACTOR-001 | VALIDATE-001, REVIEW-001 | FIX-001 | VALIDATE-001-R1, REVIEW-001-R1 |
| Fan-out | REFACTOR-B01 | VALIDATE-B01, REVIEW-B01 | FIX-B01-1 | VALIDATE-B01-R1, REVIEW-B01-R1 |
| Independent | REFACTOR-A01 | VALIDATE-A01, REVIEW-A01 | FIX-A01-1 | VALIDATE-A01-R1, REVIEW-A01-R1 |
Parallel Mode Invocation
Skill(skill="team-arch-opt", args="<task-description>") # auto mode
Skill(skill="team-arch-opt", args="--parallel-mode=fan-out <task-description>") # force fan-out
Skill(skill="team-arch-opt", args='--parallel-mode=independent "target1" "target2"') # independent
Skill(skill="team-arch-opt", args="--max-branches=3 <task-description>") # limit branches{
"version": "5.0.0",
"team_name": "arch-opt",
"team_display_name": "Architecture Optimization",
"skill_name": "team-arch-opt",
"skill_path": "~ or <project>/.claude/skills/team-arch-opt/",
"pipeline_type": "Linear with Review-Fix Cycle (Parallel-Capable)",
"completion_action": "interactive",
"has_inline_discuss": true,
"has_shared_explore": true,
"has_checkpoint_feedback": true,
"has_session_resume": true,
"roles": [
{
"name": "coordinator",
"type": "orchestrator",
"description": "Orchestrates architecture optimization pipeline, manages task chains, handles review-fix cycles",
"spec_path": "roles/coordinator/role.md",
"tools": ["Task", "TaskCreate", "TaskList", "TaskGet", "TaskUpdate", "TeamCreate", "TeamDelete", "SendMessage", "AskUserQuestion", "Read", "Write", "Bash", "Glob", "Grep"]
},
{
"name": "analyzer",
"type": "orchestration",
"description": "Analyzes architecture: dependency graphs, coupling/cohesion, layering violations, God Classes, dead code",
"role_spec": "roles/analyzer/role.md",
"inner_loop": false,
"frontmatter": {
"prefix": "ANALYZE",
"inner_loop": false,
"additional_prefixes": [],
"discuss_rounds": [],
"cli_tools": ["explore"],
"message_types": {
"success": "analyze_complete",
"error": "error"
}
},
"weight": 1,
"tools": ["Read", "Bash", "Glob", "Grep", "Task", "mcp__ace-tool__search_context"]
},
{
"name": "designer",
"type": "orchestration",
"description": "Designs refactoring strategies from architecture analysis, produces prioritized refactoring plan with discrete REFACTOR-IDs",
"role_spec": "roles/designer/role.md",
"inner_loop": false,
"frontmatter": {
"prefix": "DESIGN",
"inner_loop": false,
"additional_prefixes": [],
"discuss_rounds": ["DISCUSS-REFACTOR"],
"cli_tools": ["discuss"],
"message_types": {
"success": "design_complete",
"error": "error"
}
},
"weight": 2,
"tools": ["Read", "Bash", "Glob", "Grep", "Task", "mcp__ace-tool__search_context"]
},
{
"name": "refactorer",
"type": "code_generation",
"description": "Implements architecture refactoring changes following the design plan",
"role_spec": "roles/refactorer/role.md",
"inner_loop": "dynamic",
"frontmatter": {
"prefix": "REFACTOR",
"inner_loop": "dynamic",
"additional_prefixes": ["FIX"],
"discuss_rounds": [],
"cli_tools": ["explore"],
"message_types": {
"success": "refactor_complete",
"error": "error",
"fix": "fix_required"
}
},
"weight": 3,
"tools": ["Read", "Write", "Edit", "Bash", "Glob", "Grep", "Task", "mcp__ace-tool__search_context"]
},
{
"name": "validator",
"type": "validation",
"description": "Validates refactoring: build checks, test suites, dependency metrics, API compatibility",
"role_spec": "roles/validator/role.md",
"inner_loop": false,
"frontmatter": {
"prefix": "VALIDATE",
"inner_loop": false,
"additional_prefixes": [],
"discuss_rounds": [],
"cli_tools": [],
"message_types": {
"success": "validate_complete",
"error": "error",
"fix": "fix_required"
}
},
"weight": 4,
"tools": ["Read", "Bash", "Glob", "Grep", "Task"]
},
{
"name": "reviewer",
"type": "read_only_analysis",
"description": "Reviews refactoring code for correctness, pattern consistency, completeness, migration safety, and best practices",
"role_spec": "roles/reviewer/role.md",
"inner_loop": false,
"frontmatter": {
"prefix": "REVIEW",
"inner_loop": false,
"additional_prefixes": ["QUALITY"],
"discuss_rounds": ["DISCUSS-REVIEW"],
"cli_tools": ["discuss"],
"message_types": {
"success": "review_complete",
"error": "error",
"fix": "fix_required"
}
},
"weight": 4,
"tools": ["Read", "Bash", "Glob", "Grep", "Task", "mcp__ace-tool__search_context"]
}
],
"parallel_config": {
"modes": ["single", "fan-out", "independent", "auto"],
"default_mode": "auto",
"max_branches": 5,
"auto_mode_rules": {
"single": "refactoring_count <= 2",
"fan-out": "refactoring_count >= 3"
}
},
"pipeline": {
"stages": [
{
"stage": 1,
"name": "Architecture Analysis",
"roles": ["analyzer"],
"blockedBy": [],
"fast_advance": true
},
{
"stage": 2,
"name": "Refactoring Design",
"roles": ["designer"],
"blockedBy": ["ANALYZE"],
"fast_advance": true
},
{
"stage": 3,
"name": "Code Refactoring",
"roles": ["refactorer"],
"blockedBy": ["DESIGN"],
"fast_advance": false
},
{
"stage": 4,
"name": "Validate & Review",
"roles": ["validator", "reviewer"],
"blockedBy": ["REFACTOR"],
"fast_advance": false,
"parallel": true,
"review_fix_cycle": {
"trigger": "REVIEW or VALIDATE finds issues",
"target_stage": 3,
"max_iterations": 3
}
}
],
"parallel_pipelines": {
"fan-out": {
"shared_stages": [1, 2],
"branch_stages": [3, 4],
"branch_prefix": "B",
"review_fix_cycle": {
"scope": "per_branch",
"max_iterations": 3
}
},
"independent": {
"pipeline_prefix_chars": "ABCDEFGHIJ",
"review_fix_cycle": {
"scope": "per_pipeline",
"max_iterations": 3
}
}
},
"diagram": "See pipeline-diagram section"
},
"cli_tools": [
{
"name": "explore",
"implementation": "ccw cli with analysis mode",
"callable_by": ["analyzer", "refactorer"],
"purpose": "Shared codebase exploration for architecture-critical structures, dependency graphs, and module boundaries",
"has_cache": true,
"cache_domain": "explorations"
},
{
"name": "discuss",
"implementation": "ccw cli with analysis mode",
"callable_by": ["designer", "reviewer"],
"purpose": "Multi-perspective discussion for refactoring approaches and review findings",
"has_cache": false
}
],
"shared_resources": [
{
"name": "Architecture Baseline",
"path": "<session>/artifacts/architecture-baseline.json",
"usage": "Pre-refactoring architecture metrics for comparison",
"scope": "shared (fan-out) / per-pipeline (independent)"
},
{
"name": "Architecture Report",
"path": "<session>/artifacts/architecture-report.md",
"usage": "Analyzer output consumed by designer",
"scope": "shared (fan-out) / per-pipeline (independent)"
},
{
"name": "Refactoring Plan",
"path": "<session>/artifacts/refactoring-plan.md",
"usage": "Designer output consumed by refactorer",
"scope": "shared (fan-out) / per-pipeline (independent)"
},
{
"name": "Validation Results",
"path": "<session>/artifacts/validation-results.json",
"usage": "Validator output consumed by reviewer",
"scope": "per-branch (fan-out) / per-pipeline (independent)"
}
],
"shared_memory_namespacing": {
"single": {
"analyzer": "analyzer",
"designer": "designer",
"refactorer": "refactorer",
"validator": "validator",
"reviewer": "reviewer"
},
"fan-out": {
"analyzer": "analyzer",
"designer": "designer",
"refactorer": "refactorer.B{NN}",
"validator": "validator.B{NN}",
"reviewer": "reviewer.B{NN}"
},
"independent": {
"analyzer": "analyzer.{P}",
"designer": "designer.{P}",
"refactorer": "refactorer.{P}",
"validator": "validator.{P}",
"reviewer": "reviewer.{P}"
}
}
}