feat(skill): add team-arch-opt architecture optimization skill

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.
This commit is contained in:
catlog22
2026-03-02 16:46:44 +08:00
parent d346d48ba2
commit 3bb4a821de
12 changed files with 2476 additions and 0 deletions

View File

@@ -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 | <session>/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 `<session>/artifacts/architecture-baseline.json`:
- Module count, dependency count, cycle count, average coupling, average cohesion
- God Class candidates with LOC and method count
- Dead code file count, dead export count
- Timestamp and project type details
2. Write architecture report to `<session>/artifacts/architecture-report.md`:
- Ranked list of architecture issues with severity, location (file:line or module), measured impact
- Issue categories: CYCLE, COUPLING, COHESION, GOD_CLASS, DUPLICATION, LAYER_VIOLATION, DEAD_CODE, API_BLOAT
- Evidence summary per issue
- Detected project type and analysis methods used
3. Update `<session>/wisdom/shared-memory.json` under `analyzer` namespace:
- Read existing -> merge `{ "analyzer": { project_type, issue_count, top_issue, scope, categories } }` -> write back

View File

@@ -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 | <session>/artifacts/architecture-report.md | Yes |
| Architecture baseline | <session>/artifacts/architecture-baseline.json | Yes |
| shared-memory.json | <session>/wisdom/shared-memory.json | Yes |
| Wisdom files | <session>/wisdom/patterns.md | No |
1. Extract session path from task description
2. Read architecture report -- extract ranked issue list with severities and categories
3. Read architecture baseline -- extract current structural metrics
4. Load 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 `<session>/artifacts/refactoring-plan.md`:
Each refactoring MUST have a unique REFACTOR-ID and self-contained detail block:
```markdown
### REFACTOR-001: <title>
- Priority: P0
- Target issue: <issue from report>
- Issue type: <CYCLE|COUPLING|GOD_CLASS|DUPLICATION|LAYER_VIOLATION|DEAD_CODE|API_BLOAT>
- Target files: <file-list>
- Strategy: <selected approach>
- Expected improvement: <metric> by <description>
- Risk level: <Low/Medium/High>
- Success criteria: <specific structural change to verify>
- Implementation guidance:
1. <step 1>
2. <step 2>
3. <step 3>
### REFACTOR-002: <title>
...
```
Requirements:
- Each REFACTOR-ID is sequentially numbered (REFACTOR-001, REFACTOR-002, ...)
- Each refactoring must be **non-overlapping** in target files (no two REFACTOR-IDs modify the same file unless explicitly noted with conflict resolution)
- Implementation guidance must be self-contained -- a branch refactorer should be able to work from a single REFACTOR block without reading others
2. Update `<session>/wisdom/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`

View File

@@ -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}/`

View File

@@ -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)

View File

@@ -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