From 3bb4a821de51ce04f644c5875292d489102dabb3 Mon Sep 17 00:00:00 2001 From: catlog22 Date: Mon, 2 Mar 2026 16:46:44 +0800 Subject: [PATCH] feat(skill): add team-arch-opt architecture optimization skill MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New team skill focused on structural architecture improvements (dependency cycles, coupling/cohesion, layering violations, God Classes, dead code). Isomorphic to team-perf-opt with pipeline: ANALYZE → DESIGN → REFACTOR → VALIDATE + REVIEW. Roles: coordinator, analyzer, designer, refactorer, validator, reviewer. Supports single/fan-out/independent/auto parallel modes. --- .claude/skills/team-arch-opt/SKILL.md | 474 ++++++++++++++++++ .../team-arch-opt/role-specs/analyzer.md | 80 +++ .../team-arch-opt/role-specs/designer.md | 118 +++++ .../team-arch-opt/role-specs/refactorer.md | 106 ++++ .../team-arch-opt/role-specs/reviewer.md | 116 +++++ .../team-arch-opt/role-specs/validator.md | 117 +++++ .../roles/coordinator/commands/dispatch.md | 376 ++++++++++++++ .../roles/coordinator/commands/monitor.md | 332 ++++++++++++ .../team-arch-opt/roles/coordinator/role.md | 291 +++++++++++ .../team-arch-opt/specs/team-config.json | 264 ++++++++++ .../subagents/discuss-subagent.md | 89 ++++ .../subagents/explore-subagent.md | 113 +++++ 12 files changed, 2476 insertions(+) create mode 100644 .claude/skills/team-arch-opt/SKILL.md create mode 100644 .claude/skills/team-arch-opt/role-specs/analyzer.md create mode 100644 .claude/skills/team-arch-opt/role-specs/designer.md create mode 100644 .claude/skills/team-arch-opt/role-specs/refactorer.md create mode 100644 .claude/skills/team-arch-opt/role-specs/reviewer.md create mode 100644 .claude/skills/team-arch-opt/role-specs/validator.md create mode 100644 .claude/skills/team-arch-opt/roles/coordinator/commands/dispatch.md create mode 100644 .claude/skills/team-arch-opt/roles/coordinator/commands/monitor.md create mode 100644 .claude/skills/team-arch-opt/roles/coordinator/role.md create mode 100644 .claude/skills/team-arch-opt/specs/team-config.json create mode 100644 .claude/skills/team-arch-opt/subagents/discuss-subagent.md create mode 100644 .claude/skills/team-arch-opt/subagents/explore-subagent.md diff --git a/.claude/skills/team-arch-opt/SKILL.md b/.claude/skills/team-arch-opt/SKILL.md new file mode 100644 index 00000000..598ad887 --- /dev/null +++ b/.claude/skills/team-arch-opt/SKILL.md @@ -0,0 +1,474 @@ +--- +name: team-arch-opt +description: Unified team skill for architecture optimization. Uses team-worker agent architecture with role-spec files for domain logic. Coordinator orchestrates pipeline, workers are team-worker agents. Triggers on "team arch-opt". +allowed-tools: Task, TaskCreate, TaskList, TaskGet, TaskUpdate, TeamCreate, TeamDelete, SendMessage, AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep, mcp__ace-tool__search_context +--- + +# Team Architecture Optimization + +Unified team skill: Analyze codebase architecture, identify structural issues (dependency cycles, coupling/cohesion, layering violations, God Classes, dead code), design refactoring strategies, implement changes, validate improvements, and review code quality. Built on **team-worker agent architecture** -- all worker roles share a single agent definition with role-specific Phase 2-4 loaded from markdown specs. + +## Architecture + +``` ++---------------------------------------------------+ +| Skill(skill="team-arch-opt") | +| args="" | ++-------------------+-------------------------------+ + | + Orchestration Mode (auto -> coordinator) + | + Coordinator (inline) + Phase 0-5 orchestration + | + +-------+-------+-------+-------+-------+ + v v v v v + [tw] [tw] [tw] [tw] [tw] +analyzer desig- refact- valid- review- + ner orer ator er + + Subagents (callable by workers, not team members): + [explore] [discuss] + +(tw) = team-worker agent +``` + +## Role Router + +This skill is **coordinator-only**. Workers do NOT invoke this skill -- they are spawned as `team-worker` agents directly. + +### Input Parsing + +Parse `$ARGUMENTS`. No `--role` needed -- always routes to coordinator. + +### Role Registry + +| Role | Spec | Task Prefix | Type | Inner Loop | +|------|------|-------------|------|------------| +| coordinator | [roles/coordinator/role.md](roles/coordinator/role.md) | (none) | orchestrator | - | +| analyzer | [role-specs/analyzer.md](role-specs/analyzer.md) | ANALYZE-* | orchestration | false | +| designer | [role-specs/designer.md](role-specs/designer.md) | DESIGN-* | orchestration | false | +| refactorer | [role-specs/refactorer.md](role-specs/refactorer.md) | REFACTOR-* / FIX-* | code_generation | true | +| validator | [role-specs/validator.md](role-specs/validator.md) | VALIDATE-* | validation | false | +| reviewer | [role-specs/reviewer.md](role-specs/reviewer.md) | REVIEW-* / QUALITY-* | read_only_analysis | false | + +### Subagent Registry + +| Subagent | Spec | Callable By | Purpose | +|----------|------|-------------|---------| +| explore | [subagents/explore-subagent.md](subagents/explore-subagent.md) | analyzer, refactorer | Shared codebase exploration for architecture-critical structures and dependency graphs | +| discuss | [subagents/discuss-subagent.md](subagents/discuss-subagent.md) | designer, reviewer | Multi-perspective discussion for refactoring approaches and review findings | + +### Dispatch + +Always route to coordinator. Coordinator reads `roles/coordinator/role.md` and executes its phases. + +### Orchestration Mode + +User just provides task description. + +**Invocation**: +```bash +Skill(skill="team-arch-opt", args="") # auto mode +Skill(skill="team-arch-opt", args="--parallel-mode=fan-out ") # force fan-out +Skill(skill="team-arch-opt", args='--parallel-mode=independent "target1" "target2"') # independent +Skill(skill="team-arch-opt", args="--max-branches=3 ") # limit branches +``` + +**Parallel Modes**: + +| Mode | Description | When to Use | +|------|-------------|------------| +| `auto` (default) | count <= 2 -> single, count >= 3 -> fan-out | General refactoring requests | +| `single` | Linear pipeline, no branching | Simple or tightly coupled refactorings | +| `fan-out` | Shared ANALYZE+DESIGN, then N parallel REFACTOR->VALIDATE+REVIEW branches | Multiple independent architecture issues | +| `independent` | M fully independent pipelines from analysis to review | Separate refactoring targets | + +**Lifecycle**: +``` +User provides task description + optional --parallel-mode / --max-branches + -> coordinator Phase 1-3: Parse flags -> TeamCreate -> Create task chain (mode-aware) + -> coordinator Phase 4: spawn first batch workers (background) -> STOP + -> Worker (team-worker agent) executes -> SendMessage callback -> coordinator advances + -> [auto/fan-out] CP-2.5: Design complete -> create N branch tasks -> spawn all REFACTOR-B* in parallel + -> [independent] All pipelines run in parallel from the start + -> Per-branch/pipeline fix cycles run independently + -> All branches/pipelines complete -> AGGREGATE -> Phase 5 report + completion action +``` + +**User Commands** (wake paused coordinator): + +| Command | Action | +|---------|--------| +| `check` / `status` | Output execution status graph (branch-grouped), no advancement | +| `resume` / `continue` | Check worker states, advance next step | +| `revise [feedback]` | Create revision task + cascade downstream (scoped to branch) | +| `feedback ` | Analyze feedback impact, create targeted revision chain | +| `recheck` | Re-run quality check | +| `improve [dimension]` | Auto-improve weakest dimension | + +--- + +## Command Execution Protocol + +When coordinator needs to execute a command (dispatch, monitor): + +1. **Read the command file**: `roles/coordinator/commands/.md` +2. **Follow the workflow** defined in the command file (Phase 2-4 structure) +3. **Commands are inline execution guides** -- NOT separate agents or subprocesses +4. **Execute synchronously** -- complete the command workflow before proceeding + +Example: +``` +Phase 3 needs task dispatch + -> Read roles/coordinator/commands/dispatch.md + -> Execute Phase 2 (Context Loading) + -> Execute Phase 3 (Task Chain Creation) + -> Execute Phase 4 (Validation) + -> Continue to Phase 4 +``` + +--- + +## Coordinator Spawn Template + +### v5 Worker Spawn (all roles) + +When coordinator spawns workers, use `team-worker` agent with role-spec path: + +``` +Task({ + subagent_type: "team-worker", + description: "Spawn worker", + team_name: , + name: "", + run_in_background: true, + prompt: `## Role Assignment +role: +role_spec: .claude/skills/team-arch-opt/role-specs/.md +session: +session_id: +team_name: +requirement: +inner_loop: + +Read role_spec file to load Phase 2-4 domain instructions. +Execute built-in Phase 1 (task discovery) -> role-spec Phase 2-4 -> built-in Phase 5 (report).` +}) +``` + +**Inner Loop roles** (refactorer): Set `inner_loop: true`. The team-worker agent handles the loop internally. + +**Single-task roles** (analyzer, designer, validator, reviewer): Set `inner_loop: false`. + +--- + +## Pipeline Definitions + +### Pipeline Diagrams + +**Single Mode** (linear, backward compatible): +``` +Pipeline: Single (Linear with Review-Fix Cycle) +===================================================================== +Stage 1 Stage 2 Stage 3 Stage 4 +ANALYZE-001 --> DESIGN-001 --> REFACTOR-001 --> VALIDATE-001 +[analyzer] [designer] [refactorer] [validator] + ^ | + +<--FIX-001---->+ + | REVIEW-001 + +<--------> [reviewer] + (max 3 iterations) | + COMPLETE +===================================================================== +``` + +**Fan-out Mode** (shared stages 1-2, parallel branches 3-4): +``` +Pipeline: Fan-out (N parallel refactoring branches) +===================================================================== +Stage 1 Stage 2 CP-2.5 Stage 3+4 (per branch) + (branch creation) +ANALYZE-001 --> DESIGN-001 --+-> REFACTOR-B01 --> VALIDATE-B01 + REVIEW-B01 (fix cycle) +[analyzer] [designer] | [refactorer] [validator] [reviewer] + +-> REFACTOR-B02 --> VALIDATE-B02 + REVIEW-B02 (fix cycle) + | [refactorer] [validator] [reviewer] + +-> REFACTOR-B0N --> VALIDATE-B0N + REVIEW-B0N (fix cycle) + | + AGGREGATE -> Phase 5 +===================================================================== +``` + +**Independent Mode** (M fully independent pipelines): +``` +Pipeline: Independent (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 +Pipeline C: ANALYZE-C01 --> DESIGN-C01 --> REFACTOR-C01 --> VALIDATE-C01 + REVIEW-C01 + | + AGGREGATE -> Phase 5 +===================================================================== +``` + +### Cadence Control + +**Beat model**: Event-driven, each beat = coordinator wake -> process -> spawn -> STOP. + +``` +Beat Cycle (single beat) +====================================================================== + Event Coordinator Workers +---------------------------------------------------------------------- + callback/resume --> +- handleCallback -+ + | mark completed | + | check pipeline | + +- handleSpawnNext -+ + | find ready tasks | + | spawn workers ---+--> [team-worker A] Phase 1-5 + | (parallel OK) --+--> [team-worker B] Phase 1-5 + +- STOP (idle) -----+ | + | + callback <-----------------------------------------+ + (next beat) SendMessage + TaskUpdate(completed) +====================================================================== + + Fast-Advance (skips coordinator for simple linear successors) +====================================================================== + [Worker A] Phase 5 complete + +- 1 ready task? simple successor? + | --> spawn team-worker B directly + | --> log fast_advance to message bus (coordinator syncs on next wake) + +- complex case? --> SendMessage to coordinator +====================================================================== +``` + +``` +Beat View: Architecture Optimization Pipeline +====================================================================== + Event Coordinator Workers +---------------------------------------------------------------------- + new task --> +- Phase 1-3: clarify -+ + | TeamCreate | + | create ANALYZE-001 | + +- Phase 4: spawn ------+--> [analyzer] Phase 1-5 + +- STOP (idle) ---------+ | + | + callback <----------------------------------------------+ + (analyzer done) --> +- handleCallback ------+ analyze_complete + | mark ANALYZE done | + | spawn designer ------+--> [designer] Phase 1-5 + +- STOP ----------------+ | + | + callback <----------------------------------------------+ + (designer done) --> +- handleCallback ------+ design_complete + | mark DESIGN done | + | spawn refactorer ----+--> [refactorer] Phase 1-5 + +- STOP ----------------+ | + | + callback <----------------------------------------------+ + (refactorer done)--> +- handleCallback ------+ refactor_complete + | mark REFACTOR done | + | spawn valid+reviewer-+--> [validator] Phase 1-5 + | (parallel) -------+--> [reviewer] Phase 1-5 + +- STOP ----------------+ | | + | | + callback x2 <--------------------------------------+-----------+ + --> +- handleCallback ------+ + | both done? | + | YES + pass -> Phase 5| + | NO / fail -> FIX task| + | spawn refactorer ----+--> [refactorer] FIX-001 + +- STOP or Phase 5 -----+ +====================================================================== +``` + +**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 from refactoring plan, 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 Metadata Registry + +**Single mode** (backward compatible): + +| 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 created 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} | +| VALIDATE-B{NN}-R{cycle} | validator | Retry (branch) | FIX-B{NN}-{cycle} | Re-validate after fix | +| REVIEW-B{NN}-R{cycle} | reviewer | Retry (branch) | FIX-B{NN}-{cycle} | Re-review after fix | + +**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} | +| FIX-{P}01-{cycle} | refactorer | Fix | (none) | Fix issues in pipeline {P} | + +### 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 | + +--- + +## Completion Action + +When the pipeline completes (all tasks done, coordinator Phase 5): + +``` +AskUserQuestion({ + questions: [{ + question: "Team pipeline complete. What would you like to do?", + header: "Completion", + multiSelect: false, + options: [ + { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, + { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, + { label: "Export Results", description: "Export deliverables to a specified location, then clean" } + ] + }] +}) +``` + +| Choice | Action | +|--------|--------| +| Archive & Clean | Update session status="completed" -> TeamDelete(arch-opt) -> output final summary | +| Keep Active | Update session status="paused" -> output resume instructions: `Skill(skill="team-arch-opt", args="resume")` | +| Export Results | AskUserQuestion for target path -> copy deliverables -> Archive & Clean | + +--- + +## Session Directory + +**Single mode**: +``` +.workflow// ++-- session.json # Session metadata + status + parallel_mode ++-- 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 ++-- explorations/ +| +-- cache-index.json # Shared explore cache +| +-- .md # Cached exploration results ++-- wisdom/ +| +-- patterns.md # Discovered patterns and conventions +| +-- shared-memory.json # Cross-role structured data ++-- discussions/ +| +-- DISCUSS-REFACTOR.md # Refactoring design discussion record +| +-- DISCUSS-REVIEW.md # Review discussion record +``` + +**Fan-out mode** (adds branches/ directory): +``` +.workflow// ++-- session.json # + parallel_mode, branches, fix_cycles ++-- artifacts/ +| +-- architecture-baseline.json # Shared baseline (all branches use this) +| +-- architecture-report.md # Shared architecture report +| +-- refactoring-plan.md # Shared plan with discrete REFACTOR-IDs +| +-- aggregate-results.json # Aggregated results from all branches +| +-- branches/ +| +-- B01/ +| | +-- refactoring-detail.md # Extracted REFACTOR-001 detail +| | +-- validation-results.json # Branch B01 validation +| | +-- review-report.md # Branch B01 review +| +-- B02/ +| | +-- refactoring-detail.md +| | +-- validation-results.json +| | +-- review-report.md +| +-- B0N/ ++-- explorations/ wisdom/ discussions/ # Same as single +``` + +**Independent mode** (adds pipelines/ directory): +``` +.workflow// ++-- session.json # + parallel_mode, independent_targets, fix_cycles ++-- artifacts/ +| +-- aggregate-results.json # Aggregated results from all pipelines +| +-- pipelines/ +| +-- A/ +| | +-- architecture-baseline.json +| | +-- architecture-report.md +| | +-- refactoring-plan.md +| | +-- validation-results.json +| | +-- review-report.md +| +-- B/ +| +-- architecture-baseline.json +| +-- ... ++-- explorations/ wisdom/ discussions/ # Same as single +``` + +## Session Resume + +Coordinator supports `--resume` / `--continue` for interrupted sessions: + +1. Scan session directory for sessions with status "active" or "paused" +2. Multiple matches -> AskUserQuestion for selection +3. Audit TaskList -> reconcile session state <-> task status +4. Reset in_progress -> pending (interrupted tasks) +5. Rebuild team and spawn needed workers only +6. Create missing tasks with correct blockedBy +7. Kick first executable task -> Phase 4 coordination loop + +## Shared Resources + +| Resource | Path | Usage | +|----------|------|-------| +| Architecture Baseline | [/artifacts/architecture-baseline.json](/artifacts/architecture-baseline.json) | Pre-refactoring metrics for comparison | +| Architecture Report | [/artifacts/architecture-report.md](/artifacts/architecture-report.md) | Analyzer output consumed by designer | +| Refactoring Plan | [/artifacts/refactoring-plan.md](/artifacts/refactoring-plan.md) | Designer output consumed by refactorer | +| Validation Results | [/artifacts/validation-results.json](/artifacts/validation-results.json) | Validator output consumed by reviewer | + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| Role spec file not found | Error with expected path (role-specs/.md) | +| Command file not found | Fallback to inline execution in coordinator role.md | +| Subagent spec not found | Error with expected path (subagents/-subagent.md) | +| Fast-advance orphan detected | Coordinator resets task to pending on next check | +| consensus_blocked HIGH | Coordinator creates revision task or pauses pipeline | +| team-worker agent unavailable | Error: requires .claude/agents/team-worker.md | +| Completion action timeout | Default to Keep Active | +| Analysis tool not available | Fallback to static analysis methods | +| Validation regression detected | Auto-create FIX task with regression details (scoped to branch/pipeline) | +| Review-fix cycle exceeds 3 iterations | Escalate to user with summary of remaining issues (per-branch/pipeline scope) | +| One branch REFACTOR fails | Mark that branch failed, other branches continue to completion | +| Branch scope overlap detected | Designer constrains non-overlapping target files; REFACTOR logs warning on detection | +| Shared-memory concurrent writes | Each worker writes only its own namespace key (e.g., `refactorer.B01`) | +| Branch fix cycle >= 3 | Escalate only that branch to user, other branches continue independently | +| max_branches exceeded | Coordinator truncates to top N refactorings by priority at CP-2.5 | +| Independent pipeline partial failure | Failed pipeline marked, others continue; aggregate reports partial results | diff --git a/.claude/skills/team-arch-opt/role-specs/analyzer.md b/.claude/skills/team-arch-opt/role-specs/analyzer.md new file mode 100644 index 00000000..561be243 --- /dev/null +++ b/.claude/skills/team-arch-opt/role-specs/analyzer.md @@ -0,0 +1,80 @@ +--- +prefix: ANALYZE +inner_loop: false +subagents: [explore] +message_types: + success: analyze_complete + error: error +--- + +# 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 | +| shared-memory.json | /wisdom/shared-memory.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` subagent 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 + +## Phase 4: Report Generation + +1. Write architecture baseline to `/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 `/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 `/wisdom/shared-memory.json` under `analyzer` namespace: + - Read existing -> merge `{ "analyzer": { project_type, issue_count, top_issue, scope, categories } }` -> write back diff --git a/.claude/skills/team-arch-opt/role-specs/designer.md b/.claude/skills/team-arch-opt/role-specs/designer.md new file mode 100644 index 00000000..3a9660db --- /dev/null +++ b/.claude/skills/team-arch-opt/role-specs/designer.md @@ -0,0 +1,118 @@ +--- +prefix: DESIGN +inner_loop: false +discuss_rounds: [DISCUSS-REFACTOR] +subagents: [discuss] +message_types: + success: design_complete + error: error +--- + +# 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 | /artifacts/architecture-report.md | Yes | +| Architecture baseline | /artifacts/architecture-baseline.json | Yes | +| shared-memory.json | /wisdom/shared-memory.json | Yes | +| Wisdom files | /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 shared-memory.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` subagent (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 `/artifacts/refactoring-plan.md`: + + Each refactoring MUST have a unique REFACTOR-ID and self-contained detail block: + + ```markdown + ### REFACTOR-001: + - 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/shared-memory.json` under `designer` namespace: + - Read existing -> merge -> write back: + ```json + { + "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` diff --git a/.claude/skills/team-arch-opt/role-specs/refactorer.md b/.claude/skills/team-arch-opt/role-specs/refactorer.md new file mode 100644 index 00000000..e1db48c0 --- /dev/null +++ b/.claude/skills/team-arch-opt/role-specs/refactorer.md @@ -0,0 +1,106 @@ +--- +prefix: REFACTOR +inner_loop: true +additional_prefixes: [FIX] +subagents: [explore] +message_types: + success: refactor_complete + error: error + fix: fix_required +--- + +# Code Refactorer + +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) | +| shared-memory.json | <session>/wisdom/shared-memory.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` subagent to load implementation context for target files +6. For inner loop (single mode only): load context_accumulator from prior REFACTOR/FIX tasks + +**Shared-memory namespace**: +- Single: write to `refactorer` namespace +- 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}/` diff --git a/.claude/skills/team-arch-opt/role-specs/reviewer.md b/.claude/skills/team-arch-opt/role-specs/reviewer.md new file mode 100644 index 00000000..287463e2 --- /dev/null +++ b/.claude/skills/team-arch-opt/role-specs/reviewer.md @@ -0,0 +1,116 @@ +--- +prefix: REVIEW +inner_loop: false +additional_prefixes: [QUALITY] +discuss_rounds: [DISCUSS-REVIEW] +subagents: [discuss] +message_types: + success: review_complete + error: error + fix: fix_required +--- + +# 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 | +| shared-memory.json | <session>/wisdom/shared-memory.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 shared-memory.json for scoped refactorer namespace: + - Single: `refactorer` namespace + - 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` subagent (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/shared-memory.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) diff --git a/.claude/skills/team-arch-opt/role-specs/validator.md b/.claude/skills/team-arch-opt/role-specs/validator.md new file mode 100644 index 00000000..cc5662ab --- /dev/null +++ b/.claude/skills/team-arch-opt/role-specs/validator.md @@ -0,0 +1,117 @@ +--- +prefix: VALIDATE +inner_loop: false +message_types: + success: validate_complete + error: error + fix: fix_required +--- + +# 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 | +| shared-memory.json | <session>/wisdom/shared-memory.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 shared-memory.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 shared-memory: + - Single: `refactorer` namespace + - 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/shared-memory.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 diff --git a/.claude/skills/team-arch-opt/roles/coordinator/commands/dispatch.md b/.claude/skills/team-arch-opt/roles/coordinator/commands/dispatch.md new file mode 100644 index 00000000..1e634166 --- /dev/null +++ b/.claude/skills/team-arch-opt/roles/coordinator/commands/dispatch.md @@ -0,0 +1,376 @@ +# 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>", + owner: "<role>", + 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/shared-memory.json +EXPECTED: <deliverable path> + <quality criteria> +CONSTRAINTS: <scope limits, focus areas> +--- +InnerLoop: <true|false> +BranchId: <B01|A|none>", + blockedBy: [<dependency-list>], + status: "pending" +}) +``` + +### 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/shared-memory.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", + status: "pending" +}) +``` + +**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/shared-memory.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", + blockedBy: ["ANALYZE-001"], + status: "pending" +}) +``` + +**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/shared-memory.json +EXPECTED: Modified source files + validation passing | Refactorings applied without regressions +CONSTRAINTS: Preserve existing behavior | Update all references | Follow code conventions +--- +InnerLoop: true", + blockedBy: ["DESIGN-001"], + status: "pending" +}) +``` + +**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/shared-memory.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", + blockedBy: ["REFACTOR-001"], + status: "pending" +}) +``` + +**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/shared-memory.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", + blockedBy: ["REFACTOR-001"], + status: "pending" +}) +``` + +--- + +### 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", ... }) // blockedBy: [] +TaskCreate({ subject: "DESIGN-<P>01", ... }) // blockedBy: ["ANALYZE-<P>01"] +TaskCreate({ subject: "REFACTOR-<P>01", ... }) // blockedBy: ["DESIGN-<P>01"] +TaskCreate({ subject: "VALIDATE-<P>01", ... }) // blockedBy: ["REFACTOR-<P>01"] +TaskCreate({ subject: "REVIEW-<P>01", ... }) // blockedBy: ["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/` +- Shared-memory 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/shared-memory.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", + status: "pending" +}) +``` + +--- + +### 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 `shared-memory.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_branches` if `refactoring_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/shared-memory.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}", + blockedBy: ["DESIGN-001"], + status: "pending" +}) + +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/shared-memory.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}", + blockedBy: ["REFACTOR-B{NN}"], + status: "pending" +}) + +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} shared-memory namespace + - 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/shared-memory.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}", + blockedBy: ["REFACTOR-B{NN}"], + status: "pending" +}) +``` + +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. diff --git a/.claude/skills/team-arch-opt/roles/coordinator/commands/monitor.md b/.claude/skills/team-arch-opt/roles/coordinator/commands/monitor.md new file mode 100644 index 00000000..7dfe7871 --- /dev/null +++ b/.claude/skills/team-arch-opt/roles/coordinator/commands/monitor.md @@ -0,0 +1,332 @@ +# Command: Monitor + +Handle all coordinator monitoring events: worker callbacks, status checks, pipeline advancement, and completion. Supports single, fan-out, and independent parallel modes with per-branch/pipeline tracking. + +## Phase 2: Context Loading + +| Input | Source | Required | +|-------|--------|----------| +| Session state | <session>/session.json | Yes | +| Task list | TaskList() | Yes | +| Trigger event | From Entry Router detection | Yes | +| Pipeline definition | From SKILL.md | Yes | + +1. Load session.json for current state, `parallel_mode`, `branches`, `fix_cycles` +2. Run TaskList() to get current task statuses +3. Identify trigger event type from Entry Router + +## Phase 3: Event Handlers + +### handleCallback + +Triggered when a worker sends completion message. + +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 `auto` or `fan-out`: + - Execute **CP-2.5 Branch Creation** subroutine from dispatch.md + - After branch creation, proceed to handleSpawnNext (spawns all REFACTOR-B* in parallel) + - STOP after spawning + +5. Check if checkpoint feedback is configured for this stage: + +| Completed Task | Checkpoint | Action | +|---------------|------------|--------| +| ANALYZE-001 / ANALYZE-{P}01 | CP-1 | Notify user: architecture report ready for review | +| DESIGN-001 / DESIGN-{P}01 | CP-2 | Notify user: refactoring plan ready for review | +| DESIGN-001 (auto/fan-out) | CP-2.5 | Execute branch creation, then notify user with branch count | +| VALIDATE-* or REVIEW-* | CP-3 | Check verdicts per branch (see Review-Fix Cycle below) | + +6. Proceed to handleSpawnNext + +### handleSpawnNext + +Find and spawn the next ready tasks. + +1. Scan task list for tasks where: + - Status is "pending" + - All blockedBy tasks have status "completed" + +2. For each ready task, spawn team-worker: + +``` +Task({ + 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: .claude/skills/team-arch-opt/role-specs/<role>.md +session: <session-folder> +session_id: <session-id> +team_name: arch-opt +requirement: <task-description> +inner_loop: <true|false> + +Read role_spec file to load Phase 2-4 domain instructions. +Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` +}) +``` + +3. **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-B{NN} + REVIEW-B{NN} ready | Spawn both for that branch in parallel | +| Independent | Any unblocked task | Spawn all ready tasks across all pipelines in parallel | + +4. STOP after spawning -- wait for next callback + +### Review-Fix Cycle (CP-3) + +**Per-branch/pipeline scoping**: Each branch/pipeline has its own independent fix cycle. + +#### Single Mode (unchanged) + +When both VALIDATE-001 and REVIEW-001 are completed: + +1. Read validation verdict from shared-memory (validator namespace) +2. Read review verdict from shared-memory (reviewer namespace) + +| Validate Verdict | Review Verdict | Action | +|-----------------|----------------|--------| +| PASS | APPROVE | -> handleComplete | +| 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 | + +#### Fan-out Mode (per-branch) + +When both VALIDATE-B{NN} and REVIEW-B{NN} are completed for a specific branch: + +1. Read validation verdict from `validator.B{NN}` namespace +2. Read review verdict from `reviewer.B{NN}` namespace +3. Apply same verdict matrix as single mode, but scoped to this branch only +4. **Other branches are unaffected** -- they continue independently + +#### Independent Mode (per-pipeline) + +When both VALIDATE-{P}01 and REVIEW-{P}01 are completed for a specific pipeline: + +1. Read verdicts from `validator.{P}` and `reviewer.{P}` namespaces +2. Apply same verdict matrix, scoped to this pipeline only + +#### Fix Cycle Count Tracking + +Fix cycles are tracked per branch/pipeline in `session.json`: + +```json +// Single mode +{ "fix_cycles": { "main": 0 } } + +// Fan-out mode +{ "fix_cycles": { "B01": 0, "B02": 1, "B03": 0 } } + +// Independent mode +{ "fix_cycles": { "A": 0, "B": 2 } } +``` + +| Cycle Count | Action | +|-------------|--------| +| < 3 | Create FIX task, increment cycle count for this branch/pipeline | +| >= 3 | Escalate THIS branch/pipeline to user. Other branches continue | + +#### FIX Task Creation (branched) + +**Fan-out mode**: +``` +TaskCreate({ + subject: "FIX-B{NN}-{cycle}", + description: "PURPOSE: Fix issues in branch B{NN} from review/validation | Success: All flagged issues resolved +TASK: + - Address review findings: <specific-findings> + - Fix validation failures: <specific-failures> + - Re-validate after fixes +CONTEXT: + - Session: <session-folder> + - Branch: B{NN} + - Upstream artifacts: branches/B{NN}/review-report.md, branches/B{NN}/validation-results.json + - Shared memory: <session>/wisdom/shared-memory.json (namespace: refactorer.B{NN}) +EXPECTED: Fixed source files for B{NN} only +CONSTRAINTS: Targeted fixes only | Do not touch other branches +--- +InnerLoop: false +BranchId: B{NN}", + blockedBy: [], + status: "pending" +}) +``` + +Create new VALIDATE and REVIEW with retry suffix: +- `VALIDATE-B{NN}-R{cycle}` blocked on `FIX-B{NN}-{cycle}` +- `REVIEW-B{NN}-R{cycle}` blocked on `FIX-B{NN}-{cycle}` + +**Independent mode**: +``` +TaskCreate({ + subject: "FIX-{P}01-{cycle}", + ...same pattern with pipeline prefix... + blockedBy: [], + status: "pending" +}) +``` + +Create `VALIDATE-{P}01-R{cycle}` and `REVIEW-{P}01-R{cycle}`. + +### handleCheck + +Output current pipeline status grouped by branch/pipeline. + +**Single mode** (unchanged): +``` +Pipeline Status: + [DONE] ANALYZE-001 (analyzer) -> architecture-report.md + [DONE] DESIGN-001 (designer) -> refactoring-plan.md + [RUN] REFACTOR-001 (refactorer) -> refactoring... + [WAIT] VALIDATE-001 (validator) -> blocked by REFACTOR-001 + [WAIT] REVIEW-001 (reviewer) -> blocked by REFACTOR-001 + +Fix Cycles: 0/3 +Session: <session-id> +``` + +**Fan-out mode**: +``` +Pipeline Status (fan-out, 3 branches): + Shared Stages: + [DONE] ANALYZE-001 (analyzer) -> architecture-report.md + [DONE] DESIGN-001 (designer) -> refactoring-plan.md (4 REFACTOR-IDs) + + Branch B01 (REFACTOR-001: <title>): + [RUN] REFACTOR-B01 (refactorer) -> refactoring... + [WAIT] VALIDATE-B01 (validator) -> blocked by REFACTOR-B01 + [WAIT] REVIEW-B01 (reviewer) -> blocked by REFACTOR-B01 + Fix Cycles: 0/3 + + Branch B02 (REFACTOR-002: <title>): + [DONE] REFACTOR-B02 (refactorer) -> done + [RUN] VALIDATE-B02 (validator) -> validating... + [RUN] REVIEW-B02 (reviewer) -> reviewing... + Fix Cycles: 0/3 + + Branch B03 (REFACTOR-003: <title>): + [FAIL] REFACTOR-B03 (refactorer) -> failed + Fix Cycles: 0/3 [BRANCH FAILED] + +Session: <session-id> +``` + +**Independent mode**: +``` +Pipeline Status (independent, 2 pipelines): + Pipeline A (target: refactor auth module): + [DONE] ANALYZE-A01 -> [DONE] DESIGN-A01 -> [RUN] REFACTOR-A01 -> ... + Fix Cycles: 0/3 + + Pipeline B (target: refactor API layer): + [DONE] ANALYZE-B01 -> [DONE] DESIGN-B01 -> [DONE] REFACTOR-B01 -> ... + Fix Cycles: 1/3 + +Session: <session-id> +``` + +Output status -- do NOT advance pipeline. + +### handleResume + +Resume pipeline after user pause or interruption. + +1. Audit task list for inconsistencies: + - Tasks stuck in "in_progress" -> reset to "pending" + - Tasks with completed blockers but still "pending" -> include in spawn list +2. For fan-out/independent: check each branch/pipeline independently +3. Proceed to handleSpawnNext + +### 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 | + +### handleComplete + +Triggered when all pipeline tasks are completed and no fix cycles remain. + +**Completion check varies by mode**: + +| Mode | Completion Condition | +|------|---------------------| +| Single | All 5 tasks (+ any FIX/retry tasks) have status "completed" | +| Fan-out | ALL branches have VALIDATE + REVIEW completed with PASS/APPROVE (or escalated), shared stages done | +| Independent | ALL pipelines have VALIDATE + REVIEW completed with PASS/APPROVE (or escalated) | + +**Aggregate results** before transitioning to Phase 5: + +1. For fan-out mode: collect per-branch validation results into `<session>/artifacts/aggregate-results.json`: + ```json + { + "branches": { + "B01": { "refactor_id": "REFACTOR-001", "validate_verdict": "PASS", "review_verdict": "APPROVE", "improvement": "..." }, + "B02": { "refactor_id": "REFACTOR-002", "validate_verdict": "PASS", "review_verdict": "APPROVE", "improvement": "..." }, + "B03": { "status": "failed", "reason": "REFACTOR failed" } + }, + "overall": { "total_branches": 3, "passed": 2, "failed": 1 } + } + ``` + +2. For independent mode: collect per-pipeline results similarly + +3. If any tasks not completed, return to handleSpawnNext +4. If all completed (allowing for failed branches marked as such), transition to coordinator Phase 5 + +### handleRevise + +Triggered by user "revise <TASK-ID> [feedback]" command. + +1. Parse target task ID and optional feedback +2. Detect branch/pipeline from task ID pattern +3. Create revision task with same role but updated requirements, scoped to branch +4. Set blockedBy to empty (immediate execution) +5. Cascade: create new downstream tasks within same branch only +6. Proceed to handleSpawnNext + +### handleFeedback + +Triggered by user "feedback <text>" command. + +1. Analyze feedback text to determine impact scope +2. Identify which pipeline stage, role, and branch/pipeline should handle the feedback +3. Create targeted revision task (scoped to branch if applicable) +4. Proceed to handleSpawnNext + +## Phase 4: State Persistence + +After every handler execution: + +1. Update session.json with current state (active tasks, fix cycle counts per branch, last event, resolved parallel_mode) +2. Verify task list consistency +3. STOP and wait for next event diff --git a/.claude/skills/team-arch-opt/roles/coordinator/role.md b/.claude/skills/team-arch-opt/roles/coordinator/role.md new file mode 100644 index 00000000..36e37ba4 --- /dev/null +++ b/.claude/skills/team-arch-opt/roles/coordinator/role.md @@ -0,0 +1,291 @@ +# Coordinator - Architecture Optimization Team + +**Role**: coordinator +**Type**: Orchestrator +**Team**: arch-opt + +Orchestrates the architecture optimization pipeline: manages task chains, spawns team-worker agents, handles review-fix cycles, and drives the pipeline to completion. + +## Boundaries + +### MUST + +- Use `team-worker` agent type for all worker spawns (NOT `general-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 command (dispatch, monitor): + +1. **Read the command file**: `roles/coordinator/commands/<command-name>.md` +2. **Follow the workflow** defined in the command file (Phase 2-4 structure) +3. **Commands are inline execution guides** -- NOT separate agents or subprocesses +4. **Execute synchronously** -- complete the command workflow before proceeding + +Example: +``` +Phase 3 needs task dispatch + -> Read roles/coordinator/commands/dispatch.md + -> Execute Phase 2 (Context Loading) + -> Execute Phase 3 (Task Chain Creation) + -> Execute Phase 4 (Validation) + -> Continue to Phase 4 +``` + +--- + +## Entry Router + +When coordinator is invoked, detect invocation type: + +| Detection | Condition | Handler | +|-----------|-----------|---------| +| Worker callback | Message contains role tag [analyzer], [designer], [refactorer], [validator], [reviewer] | -> handleCallback | +| Branch callback | Message contains branch tag [refactorer-B01], [validator-B02], etc. | -> handleCallback (branch-aware) | +| Pipeline callback | Message contains pipeline tag [analyzer-A], [refactorer-B], etc. | -> handleCallback (pipeline-aware) | +| Consensus blocked | Message contains "consensus_blocked" | -> handleConsensus | +| Status check | Arguments contain "check" or "status" | -> handleCheck | +| Manual resume | Arguments contain "resume" or "continue" | -> handleResume | +| Pipeline complete | All tasks have status "completed" | -> handleComplete | +| Interrupted session | Active/paused session exists | -> Phase 0 (Resume Check) | +| New session | None of above | -> Phase 1 (Requirement Clarification) | + +For callback/check/resume/complete: load `commands/monitor.md` and execute matched handler, then STOP. + +### Router Implementation + +1. **Load session context** (if exists): + - Scan `.workflow/.team/ARCH-OPT-*/team-session.json` for active/paused sessions + - If found, extract session folder path, status, and `parallel_mode` + +2. **Parse $ARGUMENTS** for detection keywords: + - Check for role name tags in message content (including branch variants like `[refactorer-B01]`) + - Check for "check", "status", "resume", "continue" keywords + - Check for "consensus_blocked" signal + +3. **Route to handler**: + - For monitor handlers: Read `commands/monitor.md`, execute matched handler, STOP + - For Phase 0: Execute Session Resume Check below + - For Phase 1: Execute Requirement Clarification below + +--- + +## Phase 0: Session Resume Check + +Triggered when an active/paused session is detected on coordinator entry. + +1. Load session.json from detected session folder +2. Audit task list: + +``` +TaskList() +``` + +3. Reconcile session state vs task status: + +| Task Status | Session Expects | Action | +|-------------|----------------|--------| +| in_progress | Should be running | Reset to pending (worker was interrupted) | +| completed | Already tracked | Skip | +| pending + unblocked | Ready to run | Include in spawn list | + +4. Rebuild team if not active: + +``` +TeamCreate({ team_name: "arch-opt" }) +``` + +5. Spawn workers for ready tasks -> Phase 4 coordination loop + +--- + +## Phase 1: Requirement Clarification + +1. Parse user 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 (from config) | + + - For `independent` mode: remaining positional arguments after flags are `independent_targets` array + - Example: `--parallel-mode=independent "refactor auth" "refactor API"` -> targets = ["refactor auth", "refactor API"] + +3. Identify architecture optimization target: + +| Signal | Target | +|--------|--------| +| Specific file/module mentioned | Scoped refactoring | +| "coupling", "dependency", "structure", generic | Full architecture analysis | +| Specific issue mentioned (cycles, God Class, duplication) | Targeted issue resolution | +| Multiple quoted targets (independent mode) | Per-target scoped refactoring | + +4. If target is unclear, ask for clarification: + +``` +AskUserQuestion({ + questions: [{ + question: "What should I analyze and refactor? Provide a target scope or describe the architecture issue.", + header: "Scope" + }] +}) +``` + +5. Record refactoring requirement with scope, target issues, parallel_mode, and max_branches + +--- + +## Phase 2: Session & Team Setup + +1. Create session directory: + +``` +Bash("mkdir -p .workflow/<session-id>/artifacts .workflow/<session-id>/explorations .workflow/<session-id>/wisdom .workflow/<session-id>/discussions") +``` + + For independent mode, also create pipeline subdirectories: +``` +// For each target in independent_targets +Bash("mkdir -p .workflow/<session-id>/artifacts/pipelines/A .workflow/<session-id>/artifacts/pipelines/B ...") +``` + +2. Write session.json with extended fields: + +```json +{ + "status": "active", + "team_name": "arch-opt", + "requirement": "<requirement>", + "timestamp": "<ISO-8601>", + "parallel_mode": "<auto|single|fan-out|independent>", + "max_branches": 5, + "branches": [], + "independent_targets": [], + "fix_cycles": {} +} +``` + + - `parallel_mode`: from Phase 1 parsing (default: "auto") + - `max_branches`: from Phase 1 parsing (default: 5) + - `branches`: populated at CP-2.5 for fan-out mode (e.g., ["B01", "B02", "B03"]) + - `independent_targets`: populated for independent mode (e.g., ["refactor auth", "refactor API"]) + - `fix_cycles`: populated per-branch/pipeline as fix cycles occur + +3. Initialize shared-memory.json: + +``` +Write("<session>/wisdom/shared-memory.json", { "session_id": "<session-id>", "requirement": "<requirement>", "parallel_mode": "<mode>" }) +``` + +4. Create team: + +``` +TeamCreate({ team_name: "arch-opt" }) +``` + +--- + +## Phase 3: Task Chain Creation + +Execute `commands/dispatch.md` inline (Command Execution Protocol): + +1. Read `roles/coordinator/commands/dispatch.md` +2. Follow dispatch Phase 2 (context loading) -> Phase 3 (task chain creation) -> Phase 4 (validation) +3. Result: all pipeline tasks created with correct blockedBy dependencies + +--- + +## Phase 4: Spawn & Coordination Loop + +### Initial Spawn + +Find first unblocked task and spawn its worker: + +``` +Task({ + subagent_type: "team-worker", + description: "Spawn analyzer worker", + team_name: "arch-opt", + name: "analyzer", + run_in_background: true, + prompt: `## Role Assignment +role: analyzer +role_spec: .claude/skills/team-arch-opt/role-specs/analyzer.md +session: <session-folder> +session_id: <session-id> +team_name: arch-opt +requirement: <requirement> +inner_loop: false + +Read role_spec file to load Phase 2-4 domain instructions. +Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.` +}) +``` + +**STOP** after spawning. Wait for worker callback. + +### Coordination (via monitor.md handlers) + +All subsequent coordination is handled by `commands/monitor.md` handlers triggered by worker callbacks: + +- handleCallback -> mark task done -> check pipeline -> handleSpawnNext +- handleSpawnNext -> find ready tasks -> spawn team-worker agents -> STOP +- handleComplete -> all done -> Phase 5 + +--- + +## 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 from validation results + +5. **Completion Action** (interactive): + +``` +AskUserQuestion({ + questions: [{ + question: "Team pipeline complete. What would you like to do?", + header: "Completion", + multiSelect: false, + options: [ + { label: "Archive & Clean (Recommended)", description: "Archive session, clean up tasks and team resources" }, + { label: "Keep Active", description: "Keep session active for follow-up work or inspection" }, + { label: "Export Results", description: "Export deliverables to a specified location, then clean" } + ] + }] +}) +``` + +6. Handle user choice: + +| Choice | Steps | +|--------|-------| +| Archive & Clean | TaskList -> verify all completed -> update session status="completed" -> TeamDelete("arch-opt") -> output final summary with artifact paths | +| Keep Active | Update session status="paused" -> output: "Session paused. Resume with: Skill(skill='team-arch-opt', args='resume')" | +| Export Results | AskUserQuestion for target directory -> copy all artifacts -> Archive & Clean flow | diff --git a/.claude/skills/team-arch-opt/specs/team-config.json b/.claude/skills/team-arch-opt/specs/team-config.json new file mode 100644 index 00000000..a2f4c21c --- /dev/null +++ b/.claude/skills/team-arch-opt/specs/team-config.json @@ -0,0 +1,264 @@ +{ + "version": "5.0.0", + "team_name": "arch-opt", + "team_display_name": "Architecture Optimization", + "skill_name": "team-arch-opt", + "skill_path": ".claude/skills/team-arch-opt/", + "worker_agent": "team-worker", + "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": "role-specs/analyzer.md", + "inner_loop": false, + "frontmatter": { + "prefix": "ANALYZE", + "inner_loop": false, + "additional_prefixes": [], + "discuss_rounds": [], + "subagents": ["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": "role-specs/designer.md", + "inner_loop": false, + "frontmatter": { + "prefix": "DESIGN", + "inner_loop": false, + "additional_prefixes": [], + "discuss_rounds": ["DISCUSS-REFACTOR"], + "subagents": ["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": "role-specs/refactorer.md", + "inner_loop": true, + "frontmatter": { + "prefix": "REFACTOR", + "inner_loop": true, + "additional_prefixes": ["FIX"], + "discuss_rounds": [], + "subagents": ["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": "role-specs/validator.md", + "inner_loop": false, + "frontmatter": { + "prefix": "VALIDATE", + "inner_loop": false, + "additional_prefixes": [], + "discuss_rounds": [], + "subagents": [], + "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": "role-specs/reviewer.md", + "inner_loop": false, + "frontmatter": { + "prefix": "REVIEW", + "inner_loop": false, + "additional_prefixes": ["QUALITY"], + "discuss_rounds": ["DISCUSS-REVIEW"], + "subagents": ["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" + }, + + "subagents": [ + { + "name": "explore", + "agent_type": "cli-explore-agent", + "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", + "agent_type": "cli-discuss-agent", + "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}" + } + } +} diff --git a/.claude/skills/team-arch-opt/subagents/discuss-subagent.md b/.claude/skills/team-arch-opt/subagents/discuss-subagent.md new file mode 100644 index 00000000..1e7a590f --- /dev/null +++ b/.claude/skills/team-arch-opt/subagents/discuss-subagent.md @@ -0,0 +1,89 @@ +# Discuss Subagent + +Multi-perspective discussion for evaluating refactoring strategies and reviewing code change quality. Used by designer (DISCUSS-REFACTOR) and reviewer (DISCUSS-REVIEW) when complex trade-offs require multi-angle analysis. + +## Design Rationale + +Complex refactoring decisions (e.g., choosing between dependency inversion vs mediator pattern to break a cycle) and nuanced code review findings (e.g., evaluating whether a temporary coupling increase is acceptable) benefit from structured multi-perspective analysis. This subagent provides that analysis inline without spawning additional team members. + +## Invocation + +Called by designer, reviewer after their primary analysis when complexity warrants multi-perspective evaluation: + +``` +Task({ + subagent_type: "cli-discuss-agent", + run_in_background: false, + description: "Discuss <round-id>: <topic> for architecture optimization", + prompt: `Conduct a multi-perspective discussion on the following topic. + +Round: <round-id> +Topic: <discussion-topic> +Session: <session-folder> + +Context: +<relevant-context-from-calling-role> + +Perspectives to consider: +- Architecture impact: Will this actually improve the target structural metric? +- Risk assessment: What could break? Dangling references? Behavioral changes? Migration risk? +- Maintainability: Is the refactored code more understandable and maintainable? +- Alternative approaches: Are there simpler or safer ways to achieve the same structural improvement? + +Evaluate trade-offs and provide a structured recommendation with: +- Consensus verdict: proceed / revise / escalate +- Confidence level: high / medium / low +- Key trade-offs identified +- Recommended approach with rationale +- Dissenting perspectives (if any)` +}) +``` + +## Round Configuration + +| Round | Artifact | Parameters | Calling Role | +|-------|----------|------------|-------------| +| DISCUSS-REFACTOR | <session>/discussions/DISCUSS-REFACTOR.md | Refactoring strategy trade-offs | designer | +| DISCUSS-REVIEW | <session>/discussions/DISCUSS-REVIEW.md | Code review finding validation | reviewer | + +## Integration with Calling Role + +The calling role is responsible for: + +1. **Before calling**: Complete primary analysis, identify the specific trade-off or finding needing discussion +2. **Calling**: Invoke subagent with round ID, topic, and relevant context +3. **After calling**: + +| Result | Action | +|--------|--------| +| consensus_reached (proceed) | Incorporate recommendation into output, continue | +| consensus_reached (revise) | Adjust findings/strategy based on discussion insights | +| consensus_blocked (HIGH) | Report to coordinator via message with severity | +| consensus_blocked (MEDIUM) | Include in output with recommendation for revision | +| consensus_blocked (LOW) | Note in output, proceed with original assessment | + +## Output Schema + +```json +{ + "round_id": "<DISCUSS-REFACTOR|DISCUSS-REVIEW>", + "topic": "<discussion-topic>", + "verdict": "<proceed|revise|escalate>", + "confidence": "<high|medium|low>", + "trade_offs": [ + { "dimension": "<architecture|risk|maintainability>", "pro": "<benefit>", "con": "<cost>" } + ], + "recommendation": "<recommended-approach>", + "rationale": "<reasoning>", + "dissenting_views": ["<alternative-perspective>"] +} +``` + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| Single perspective analysis fails | Continue with partial perspectives | +| All analyses fail | Return basic recommendation from calling role's primary analysis | +| Artifact not found | Return error immediately | +| Discussion inconclusive | Return "revise" verdict with low confidence | diff --git a/.claude/skills/team-arch-opt/subagents/explore-subagent.md b/.claude/skills/team-arch-opt/subagents/explore-subagent.md new file mode 100644 index 00000000..87d8c79a --- /dev/null +++ b/.claude/skills/team-arch-opt/subagents/explore-subagent.md @@ -0,0 +1,113 @@ +# Explore Subagent + +Shared codebase exploration for discovering architecture-critical structures, dependency graphs, module boundaries, and layer organization. Results are cached to avoid redundant exploration across analyzer and refactorer roles. + +## Design Rationale + +Codebase exploration is a read-only operation shared between analyzer (mapping structural issues) and refactorer (understanding implementation context). Caching explorations avoids redundant work when refactorer re-explores structures the analyzer already mapped. + +## Invocation + +Called by analyzer, refactorer after needing codebase context for architecture analysis or implementation: + +``` +Task({ + subagent_type: "cli-explore-agent", + run_in_background: false, + description: "Explore codebase for architecture-critical structures in <target-scope>", + prompt: `Explore the codebase to identify architecture-critical structures. + +Target scope: <target-scope> +Session: <session-folder> +Focus: <exploration-focus> + +Tasks: +1. Map the module structure, entry points, and layer boundaries within scope +2. Build dependency graph (import/require relationships between modules) +3. Identify architectural patterns (layering, dependency injection, event-driven, plugin architecture) +4. Note any existing abstractions, interfaces, and module boundaries +5. List key files with their roles, layer assignment, and dependency relationships + +Output a structured exploration report with: +- Module map (key files, their relationships, and layer assignments) +- Dependency graph (directed edges between modules, cycle indicators) +- Layer structure (identified layers and their boundaries) +- Existing architectural patterns found +- Architecture-relevant configuration (path aliases, barrel exports, module boundaries)` +}) +``` + +## Cache Mechanism + +### Cache Index Schema + +`<session-folder>/explorations/cache-index.json`: + +```json +{ + "entries": [ + { + "key": "<scope-hash>", + "scope": "<target-scope>", + "focus": "<exploration-focus>", + "timestamp": "<ISO-8601>", + "result_file": "<hash>.md" + } + ] +} +``` + +### Cache Lookup Rules + +| Condition | Action | +|-----------|--------| +| Exact scope+focus match exists | Return cached result from <hash>.md | +| No match | Execute subagent, cache result to <hash>.md, update index | +| Cache file missing but index has entry | Remove stale entry, re-execute | +| Cache older than current session | Use cached (explorations are stable within session) | + +## Integration with Calling Role + +The calling role is responsible for: + +1. **Before calling**: Determine target scope and exploration focus +2. **Calling**: Check cache first, invoke subagent only on cache miss +3. **After calling**: + +| Result | Action | +|--------|--------| +| Exploration successful | Use findings to inform analysis/implementation | +| Exploration partial | Use available findings, note gaps | +| Exploration failed | Proceed without exploration context, use direct file reading | + +## Output Schema + +```json +{ + "scope": "<target-scope>", + "module_map": [ + { "file": "<path>", "role": "<description>", "layer": "<presentation|domain|data|infra>", "dependency_graph": { "imports": ["<path>"], "imported_by": ["<path>"] } } + ], + "dependency_graph": { + "nodes": ["<module-path>"], + "edges": [{ "from": "<path>", "to": "<path>", "type": "<import|re-export|dynamic>" }], + "cycles": [["<path-a>", "<path-b>", "<path-a>"]] + }, + "layer_structure": [ + { "layer": "<name>", "modules": ["<path>"], "violations": ["<description>"] } + ], + "existing_patterns": [ + { "type": "<pattern>", "location": "<file:line>", "description": "<what>" } + ], + "investigation_targets": ["<file-or-pattern>"] +} +``` + +## Error Handling + +| Scenario | Resolution | +|----------|------------| +| Single exploration angle fails | Continue with partial results | +| All exploration fails | Return basic result from direct file listing | +| Target scope not found | Return error immediately | +| Cache corrupt | Clear cache-index.json, re-execute |