mirror of
https://github.com/catlog22/Claude-Code-Workflow.git
synced 2026-03-25 19:48:33 +08:00
feat: migrate all codex team skills from spawn_agents_on_csv to spawn_agent + wait_agent architecture
- Delete 21 old team skill directories using CSV-wave pipeline pattern (~100+ files) - Delete old team-lifecycle (v3) and team-planex-v2 - Create generic team-worker.toml and team-supervisor.toml (replacing tlv4-specific TOMLs) - Convert 19 team skills from Claude Code format (Agent/SendMessage/TaskCreate) to Codex format (spawn_agent/wait_agent/tasks.json/request_user_input) - Update team-lifecycle-v4 to use generic agent types (team_worker/team_supervisor) - Convert all coordinator role files: dispatch.md, monitor.md, role.md - Convert all worker role files: remove run_in_background, fix Bash syntax - Convert all specs/pipelines.md references - Final state: 20 team skills, 217 .md files, zero Claude Code API residuals Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
78
.codex/skills/team-arch-opt/roles/analyzer/role.md
Normal file
78
.codex/skills/team-arch-opt/roles/analyzer/role.md
Normal file
@@ -0,0 +1,78 @@
|
||||
---
|
||||
role: analyzer
|
||||
prefix: ANALYZE
|
||||
inner_loop: false
|
||||
message_types: [state_update]
|
||||
---
|
||||
|
||||
# Architecture Analyzer
|
||||
|
||||
Analyze codebase architecture to identify structural issues: dependency cycles, coupling/cohesion problems, layering violations, God Classes, code duplication, dead code, and API surface bloat. Produce quantified baseline metrics and a ranked architecture report.
|
||||
|
||||
## Phase 2: Context & Environment Detection
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Task description | From task subject/description | Yes |
|
||||
| Session path | Extracted from task description | Yes |
|
||||
| .msg/meta.json | <session>/wisdom/.msg/meta.json | No |
|
||||
|
||||
1. Extract session path and target scope from task description
|
||||
2. Detect project type by scanning for framework markers:
|
||||
|
||||
| Signal File | Project Type | Analysis Focus |
|
||||
|-------------|-------------|----------------|
|
||||
| package.json + React/Vue/Angular | Frontend | Component tree, prop drilling, state management, barrel exports |
|
||||
| package.json + Express/Fastify/NestJS | Backend Node | Service layer boundaries, middleware chains, DB access patterns |
|
||||
| Cargo.toml / go.mod / pom.xml | Native/JVM Backend | Module boundaries, trait/interface usage, dependency injection |
|
||||
| Mixed framework markers | Full-stack / Monorepo | Cross-package dependencies, shared types, API contracts |
|
||||
| CLI entry / bin/ directory | CLI Tool | Command structure, plugin architecture, configuration layering |
|
||||
| No detection | Generic | All architecture dimensions |
|
||||
|
||||
3. Use `explore` CLI tool to map module structure, dependency graph, and layer boundaries within target scope
|
||||
4. Detect available analysis tools (linters, dependency analyzers, build tools)
|
||||
|
||||
## Phase 3: Architecture Analysis
|
||||
|
||||
Execute analysis based on detected project type:
|
||||
|
||||
**Dependency analysis**:
|
||||
- Build import/require graph across modules
|
||||
- Detect circular dependencies (direct and transitive cycles)
|
||||
- Identify layering violations (e.g., UI importing from data layer, utils importing from domain)
|
||||
- Calculate fan-in/fan-out per module (high fan-out = fragile hub, high fan-in = tightly coupled)
|
||||
|
||||
**Structural analysis**:
|
||||
- Identify God Classes / God Modules (> 500 LOC, > 10 public methods, too many responsibilities)
|
||||
- Calculate coupling metrics (afferent/efferent coupling per module)
|
||||
- Calculate cohesion metrics (LCOM -- Lack of Cohesion of Methods)
|
||||
- Detect code duplication (repeated logic blocks, copy-paste patterns)
|
||||
- Identify missing abstractions (repeated conditionals, switch-on-type patterns)
|
||||
|
||||
**API surface analysis**:
|
||||
- Count exported symbols per module (export bloat detection)
|
||||
- Identify dead exports (exported but never imported elsewhere)
|
||||
- Detect dead code (unreachable functions, unused variables, orphan files)
|
||||
- Check for pattern inconsistencies (mixed naming conventions, inconsistent error handling)
|
||||
|
||||
**All project types**:
|
||||
- Collect quantified architecture baseline metrics (dependency count, cycle count, coupling scores, LOC distribution)
|
||||
- Rank top 3-7 architecture issues by severity (Critical / High / Medium)
|
||||
- Record evidence: file paths, line numbers, measured values
|
||||
|
||||
## Phase 4: Report Generation
|
||||
|
||||
1. Write architecture baseline to `<session>/artifacts/architecture-baseline.json`:
|
||||
- Module count, dependency count, cycle count, average coupling, average cohesion
|
||||
- God Class candidates with LOC and method count
|
||||
- Dead code file count, dead export count
|
||||
- Timestamp and project type details
|
||||
|
||||
2. Write architecture report to `<session>/artifacts/architecture-report.md`:
|
||||
- Ranked list of architecture issues with severity, location (file:line or module), measured impact
|
||||
- Issue categories: CYCLE, COUPLING, COHESION, GOD_CLASS, DUPLICATION, LAYER_VIOLATION, DEAD_CODE, API_BLOAT
|
||||
- Evidence summary per issue
|
||||
- Detected project type and analysis methods used
|
||||
|
||||
3. Update `<session>/wisdom/.msg/meta.json` under `analyzer` namespace:
|
||||
- Read existing -> merge `{ "analyzer": { project_type, issue_count, top_issue, scope, categories } }` -> write back
|
||||
@@ -0,0 +1,57 @@
|
||||
# Analyze Task
|
||||
|
||||
Parse user task -> detect architecture capabilities -> build dependency graph -> design roles.
|
||||
|
||||
**CONSTRAINT**: Text-level analysis only. NO source code reading, NO codebase exploration.
|
||||
|
||||
## Signal Detection
|
||||
|
||||
| Keywords | Capability | Prefix |
|
||||
|----------|------------|--------|
|
||||
| analyze, scan, audit, map, identify | analyzer | ANALYZE |
|
||||
| design, plan, strategy, refactoring-plan | designer | DESIGN |
|
||||
| refactor, implement, fix, apply | refactorer | REFACTOR |
|
||||
| validate, build, test, verify, compile | validator | VALIDATE |
|
||||
| review, audit-code, quality, check-code | reviewer | REVIEW |
|
||||
|
||||
## Dependency Graph
|
||||
|
||||
Natural ordering tiers:
|
||||
- Tier 0: analyzer (knowledge gathering -- no dependencies)
|
||||
- Tier 1: designer (requires analyzer output)
|
||||
- Tier 2: refactorer (requires designer output)
|
||||
- Tier 3: validator, reviewer (validation requires refactored artifacts, can run in parallel)
|
||||
|
||||
## Complexity Scoring
|
||||
|
||||
| Factor | Points |
|
||||
|--------|--------|
|
||||
| Per capability | +1 |
|
||||
| Cross-domain refactoring | +2 |
|
||||
| Parallel branches requested | +1 per branch |
|
||||
| Serial depth > 3 | +1 |
|
||||
| Multiple targets (independent mode) | +2 |
|
||||
|
||||
Results: 1-3 Low, 4-6 Medium, 7+ High
|
||||
|
||||
## Role Minimization
|
||||
|
||||
- Cap at 5 roles
|
||||
- Merge overlapping capabilities
|
||||
- Absorb trivial single-step roles
|
||||
|
||||
## Output
|
||||
|
||||
Write <session>/task-analysis.json:
|
||||
```json
|
||||
{
|
||||
"task_description": "<original>",
|
||||
"pipeline_type": "<single|fan-out|independent|auto>",
|
||||
"capabilities": [{ "name": "<cap>", "prefix": "<PREFIX>", "keywords": ["..."] }],
|
||||
"dependency_graph": { "<TASK-ID>": { "role": "<role>", "blockedBy": ["..."], "priority": "P0|P1|P2" } },
|
||||
"roles": [{ "name": "<role>", "prefix": "<PREFIX>", "inner_loop": false }],
|
||||
"complexity": { "score": 0, "level": "Low|Medium|High" },
|
||||
"parallel_mode": "<auto|single|fan-out|independent>",
|
||||
"max_branches": 5
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,287 @@
|
||||
# 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 tasks.json `parallel_mode` | Yes |
|
||||
| Max branches | From tasks.json `max_branches` | Yes |
|
||||
| Independent targets | From tasks.json `independent_targets` (independent mode only) | Conditional |
|
||||
|
||||
1. Load user requirement and refactoring scope from tasks.json
|
||||
2. Load pipeline stage definitions from SKILL.md Task Metadata Registry
|
||||
3. Read `parallel_mode` and `max_branches` from tasks.json
|
||||
4. For `independent` mode: read `independent_targets` array from tasks.json
|
||||
|
||||
## Phase 3: Task Chain Creation (Mode-Branched)
|
||||
|
||||
### Task Entry Template
|
||||
|
||||
Every task in tasks.json `tasks` object uses structured format:
|
||||
|
||||
```json
|
||||
{
|
||||
"<TASK-ID>": {
|
||||
"title": "<concise title>",
|
||||
"description": "PURPOSE: <what this task achieves> | Success: <measurable completion criteria>\nTASK:\n - <step 1: specific action>\n - <step 2: specific action>\n - <step 3: specific action>\nCONTEXT:\n - Session: <session-folder>\n - Scope: <refactoring-scope>\n - Branch: <branch-id or 'none'>\n - Upstream artifacts: <artifact-1>, <artifact-2>\n - Shared memory: <session>/wisdom/.msg/meta.json\nEXPECTED: <deliverable path> + <quality criteria>\nCONSTRAINTS: <scope limits, focus areas>\n---\nInnerLoop: <true|false>\nBranchId: <B01|A|none>",
|
||||
"role": "<role-name>",
|
||||
"prefix": "<PREFIX>",
|
||||
"deps": ["<upstream-task-id>"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 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):
|
||||
```json
|
||||
{
|
||||
"ANALYZE-001": {
|
||||
"title": "Analyze codebase architecture",
|
||||
"description": "PURPOSE: Analyze codebase architecture to identify structural issues | Success: Baseline metrics captured, top 3-7 issues ranked by severity\nTASK:\n - Detect project type and available analysis tools\n - Execute analysis across relevant dimensions (dependencies, coupling, cohesion, layering, duplication, dead code)\n - Collect baseline metrics and rank architecture issues by severity\nCONTEXT:\n - Session: <session-folder>\n - Scope: <refactoring-scope>\n - Branch: none\n - Shared memory: <session>/wisdom/.msg/meta.json\nEXPECTED: <session>/artifacts/architecture-baseline.json + <session>/artifacts/architecture-report.md | Quantified metrics with evidence\nCONSTRAINTS: Focus on <refactoring-scope> | Analyze before any changes\n---\nInnerLoop: false",
|
||||
"role": "analyzer",
|
||||
"prefix": "ANALYZE",
|
||||
"deps": [],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**DESIGN-001** (designer, Stage 2):
|
||||
```json
|
||||
{
|
||||
"DESIGN-001": {
|
||||
"title": "Design prioritized refactoring plan",
|
||||
"description": "PURPOSE: Design prioritized refactoring plan from architecture analysis | Success: Actionable plan with measurable success criteria per refactoring\nTASK:\n - Analyze architecture report and baseline metrics\n - Select refactoring strategies per issue type\n - Prioritize by impact/effort ratio, define success criteria\n - Each refactoring MUST have a unique REFACTOR-ID (REFACTOR-001, REFACTOR-002, ...) with non-overlapping target files\nCONTEXT:\n - Session: <session-folder>\n - Scope: <refactoring-scope>\n - Branch: none\n - Upstream artifacts: architecture-baseline.json, architecture-report.md\n - Shared memory: <session>/wisdom/.msg/meta.json\nEXPECTED: <session>/artifacts/refactoring-plan.md | Priority-ordered with structural improvement targets, discrete REFACTOR-IDs\nCONSTRAINTS: Focus on highest-impact refactorings | Risk assessment required | Non-overlapping file targets per REFACTOR-ID\n---\nInnerLoop: false",
|
||||
"role": "designer",
|
||||
"prefix": "DESIGN",
|
||||
"deps": ["ANALYZE-001"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**REFACTOR-001** (refactorer, Stage 3):
|
||||
```json
|
||||
{
|
||||
"REFACTOR-001": {
|
||||
"title": "Implement refactoring changes per design plan",
|
||||
"description": "PURPOSE: Implement refactoring changes per design plan | Success: All planned refactorings applied, code compiles, existing tests pass\nTASK:\n - Load refactoring plan and identify target files\n - Apply refactorings in priority order (P0 first)\n - Update all import references for moved/renamed modules\n - Validate changes compile and pass existing tests\nCONTEXT:\n - Session: <session-folder>\n - Scope: <refactoring-scope>\n - Branch: none\n - Upstream artifacts: refactoring-plan.md\n - Shared memory: <session>/wisdom/.msg/meta.json\nEXPECTED: Modified source files + validation passing | Refactorings applied without regressions\nCONSTRAINTS: Preserve existing behavior | Update all references | Follow code conventions\n---\nInnerLoop: true",
|
||||
"role": "refactorer",
|
||||
"prefix": "REFACTOR",
|
||||
"deps": ["DESIGN-001"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**VALIDATE-001** (validator, Stage 4 - parallel):
|
||||
```json
|
||||
{
|
||||
"VALIDATE-001": {
|
||||
"title": "Validate refactoring results against baseline",
|
||||
"description": "PURPOSE: Validate refactoring results against baseline | Success: Build passes, tests pass, no metric regressions, API compatible\nTASK:\n - Load architecture baseline and plan success criteria\n - Run build validation (compilation, type checking)\n - Run test validation (existing test suite)\n - Compare dependency metrics against baseline\n - Verify API compatibility (no dangling references)\nCONTEXT:\n - Session: <session-folder>\n - Scope: <refactoring-scope>\n - Branch: none\n - Upstream artifacts: architecture-baseline.json, refactoring-plan.md\n - Shared memory: <session>/wisdom/.msg/meta.json\nEXPECTED: <session>/artifacts/validation-results.json | Per-dimension validation with verdicts\nCONSTRAINTS: Must compare against baseline | Flag any regressions or broken imports\n---\nInnerLoop: false",
|
||||
"role": "validator",
|
||||
"prefix": "VALIDATE",
|
||||
"deps": ["REFACTOR-001"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**REVIEW-001** (reviewer, Stage 4 - parallel):
|
||||
```json
|
||||
{
|
||||
"REVIEW-001": {
|
||||
"title": "Review refactoring code for correctness and quality",
|
||||
"description": "PURPOSE: Review refactoring code for correctness, pattern consistency, and migration safety | Success: All dimensions reviewed, verdict issued\nTASK:\n - Load modified files and refactoring plan\n - Review across 5 dimensions: correctness, pattern consistency, completeness, migration safety, best practices\n - Issue verdict: APPROVE, REVISE, or REJECT with actionable feedback\nCONTEXT:\n - Session: <session-folder>\n - Scope: <refactoring-scope>\n - Branch: none\n - Upstream artifacts: refactoring-plan.md, validation-results.json (if available)\n - Shared memory: <session>/wisdom/.msg/meta.json\nEXPECTED: <session>/artifacts/review-report.md | Per-dimension findings with severity\nCONSTRAINTS: Focus on refactoring changes only | Provide specific file:line references\n---\nInnerLoop: false",
|
||||
"role": "reviewer",
|
||||
"prefix": "REVIEW",
|
||||
"deps": ["REFACTOR-001"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 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]`:
|
||||
|
||||
```javascript
|
||||
// Create session subdirectory for this pipeline
|
||||
Bash("mkdir -p <session>/artifacts/pipelines/<P>")
|
||||
|
||||
// Add pipeline tasks to tasks.json:
|
||||
state.tasks["ANALYZE-<P>01"] = { title: "...", role: "analyzer", prefix: "ANALYZE", deps: [], ... }
|
||||
state.tasks["DESIGN-<P>01"] = { title: "...", role: "designer", prefix: "DESIGN", deps: ["ANALYZE-<P>01"], ... }
|
||||
state.tasks["REFACTOR-<P>01"] = { title: "...", role: "refactorer", prefix: "REFACTOR", deps: ["DESIGN-<P>01"], ... }
|
||||
state.tasks["VALIDATE-<P>01"] = { title: "...", role: "validator", prefix: "VALIDATE", deps: ["REFACTOR-<P>01"], ... }
|
||||
state.tasks["REVIEW-<P>01"] = { title: "...", role: "reviewer", prefix: "REVIEW", deps: ["REFACTOR-<P>01"], ... }
|
||||
```
|
||||
|
||||
Task descriptions follow same template as single mode, with additions:
|
||||
- `Pipeline: <P>` in CONTEXT
|
||||
- Artifact paths use `<session>/artifacts/pipelines/<P>/` instead of `<session>/artifacts/`
|
||||
- Meta.json namespace uses `<role>.<P>` (e.g., `analyzer.A`, `refactorer.B`)
|
||||
- Each pipeline's scope is its specific target from `independent_targets[i]`
|
||||
|
||||
Example for pipeline A with target "refactor auth module":
|
||||
```json
|
||||
{
|
||||
"ANALYZE-A01": {
|
||||
"title": "Analyze auth module architecture",
|
||||
"description": "PURPOSE: Analyze auth module architecture | Success: Auth module structural issues identified\nTASK:\n - Detect project type and available analysis tools\n - Execute architecture analysis focused on auth module\n - Collect baseline metrics and rank auth module issues\nCONTEXT:\n - Session: <session-folder>\n - Scope: refactor auth module\n - Pipeline: A\n - Shared memory: <session>/wisdom/.msg/meta.json (namespace: analyzer.A)\nEXPECTED: <session>/artifacts/pipelines/A/architecture-baseline.json + architecture-report.md\nCONSTRAINTS: Focus on auth module scope\n---\nInnerLoop: false\nPipelineId: A",
|
||||
"role": "analyzer",
|
||||
"prefix": "ANALYZE",
|
||||
"deps": [],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### CP-2.5: Branch Creation Subroutine
|
||||
|
||||
**Triggered by**: monitor.md handleSpawnNext when DESIGN-001 completes in `auto` or `fan-out` mode.
|
||||
|
||||
**Procedure**:
|
||||
|
||||
1. Read `<session>/artifacts/refactoring-plan.md` to count REFACTOR-IDs
|
||||
2. Read `.msg/meta.json` -> `designer.refactoring_count`
|
||||
3. **Auto mode decision**:
|
||||
|
||||
| Refactoring Count | Decision |
|
||||
|-------------------|----------|
|
||||
| count <= 2 | Switch to `single` mode -- add REFACTOR-001, VALIDATE-001, REVIEW-001 to tasks.json (standard single pipeline) |
|
||||
| count >= 3 | Switch to `fan-out` mode -- add branch tasks below |
|
||||
|
||||
4. Update tasks.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:
|
||||
|
||||
```javascript
|
||||
// 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. Add branch tasks to tasks.json for each branch B{NN}:
|
||||
|
||||
```json
|
||||
{
|
||||
"REFACTOR-B{NN}": {
|
||||
"title": "Implement refactoring REFACTOR-{NNN}",
|
||||
"description": "PURPOSE: Implement refactoring REFACTOR-{NNN} | Success: Single refactoring applied, compiles, tests pass\nTASK:\n - Load refactoring detail from branches/B{NN}/refactoring-detail.md\n - Apply this single refactoring to target files\n - Update all import references for moved/renamed modules\n - Validate changes compile and pass existing tests\nCONTEXT:\n - Session: <session-folder>\n - Branch: B{NN}\n - Upstream artifacts: branches/B{NN}/refactoring-detail.md\n - Shared memory: <session>/wisdom/.msg/meta.json (namespace: refactorer.B{NN})\nEXPECTED: Modified source files for REFACTOR-{NNN} only\nCONSTRAINTS: Only implement this branch's refactoring | Do not touch files outside REFACTOR-{NNN} scope\n---\nInnerLoop: false\nBranchId: B{NN}",
|
||||
"role": "refactorer",
|
||||
"prefix": "REFACTOR",
|
||||
"deps": ["DESIGN-001"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
},
|
||||
"VALIDATE-B{NN}": {
|
||||
"title": "Validate branch B{NN} refactoring",
|
||||
"description": "PURPOSE: Validate branch B{NN} refactoring | Success: REFACTOR-{NNN} passes build, tests, and metric checks\nTASK:\n - Load architecture baseline and REFACTOR-{NNN} success criteria\n - Validate build, tests, dependency metrics, and API compatibility\n - Compare against baseline, check for regressions\nCONTEXT:\n - Session: <session-folder>\n - Branch: B{NN}\n - Upstream artifacts: architecture-baseline.json, branches/B{NN}/refactoring-detail.md\n - Shared memory: <session>/wisdom/.msg/meta.json (namespace: validator.B{NN})\nEXPECTED: <session>/artifacts/branches/B{NN}/validation-results.json\nCONSTRAINTS: Only validate this branch's changes\n---\nInnerLoop: false\nBranchId: B{NN}",
|
||||
"role": "validator",
|
||||
"prefix": "VALIDATE",
|
||||
"deps": ["REFACTOR-B{NN}"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
},
|
||||
"REVIEW-B{NN}": {
|
||||
"title": "Review branch B{NN} refactoring code",
|
||||
"description": "PURPOSE: Review branch B{NN} refactoring code | Success: Code quality verified for REFACTOR-{NNN}\nTASK:\n - Load modified files from refactorer.B{NN} namespace in .msg/meta.json\n - Review across 5 dimensions for this branch's changes only\n - Issue verdict: APPROVE, REVISE, or REJECT\nCONTEXT:\n - Session: <session-folder>\n - Branch: B{NN}\n - Upstream artifacts: branches/B{NN}/refactoring-detail.md\n - Shared memory: <session>/wisdom/.msg/meta.json (namespace: reviewer.B{NN})\nEXPECTED: <session>/artifacts/branches/B{NN}/review-report.md\nCONSTRAINTS: Only review this branch's changes\n---\nInnerLoop: false\nBranchId: B{NN}",
|
||||
"role": "reviewer",
|
||||
"prefix": "REVIEW",
|
||||
"deps": ["REFACTOR-B{NN}"],
|
||||
"status": "pending",
|
||||
"findings": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
7. Update tasks.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 | tasks.json task count | single: 5, auto/fan-out: 2 (pre-CP-2.5), independent: 5*M |
|
||||
| Dependencies correct | Trace dependency graph | Acyclic, correct deps |
|
||||
| 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 tasks.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.
|
||||
@@ -0,0 +1,204 @@
|
||||
# Monitor Pipeline
|
||||
|
||||
Synchronous pipeline coordination using spawn_agent + wait_agent.
|
||||
|
||||
## Constants
|
||||
|
||||
- WORKER_AGENT: team_worker
|
||||
- ONE_STEP_PER_INVOCATION: false (synchronous wait loop)
|
||||
- FAST_ADVANCE_AWARE: true
|
||||
|
||||
## Handler Router
|
||||
|
||||
| Source | Handler |
|
||||
|--------|---------|
|
||||
| Message contains branch tag [refactorer-B01], etc. | handleSpawnNext (branch-aware) |
|
||||
| Message contains pipeline tag [analyzer-A], etc. | handleSpawnNext (pipeline-aware) |
|
||||
| "consensus_blocked" | handleConsensus |
|
||||
| "capability_gap" | handleAdapt |
|
||||
| "check" or "status" | handleCheck |
|
||||
| "resume" or "continue" | handleResume |
|
||||
| All tasks completed | handleComplete |
|
||||
| Default | handleSpawnNext |
|
||||
|
||||
## handleCheck
|
||||
|
||||
Read-only status report from tasks.json, then STOP.
|
||||
|
||||
1. Read tasks.json
|
||||
2. Count tasks by status (pending, in_progress, completed, failed)
|
||||
|
||||
Output (single mode):
|
||||
```
|
||||
[coordinator] Pipeline Status
|
||||
[coordinator] Progress: <done>/<total> (<pct>%)
|
||||
[coordinator] Active agents: <list from active_agents>
|
||||
[coordinator] Ready: <pending tasks with resolved deps>
|
||||
[coordinator] Commands: 'resume' to advance | 'check' to refresh
|
||||
```
|
||||
|
||||
Fan-out mode adds per-branch grouping. Independent mode adds per-pipeline grouping.
|
||||
|
||||
## handleResume
|
||||
|
||||
1. Read tasks.json, check active_agents
|
||||
2. No active agents -> handleSpawnNext
|
||||
3. Has active agents -> check each status
|
||||
4. Proceed to handleSpawnNext
|
||||
|
||||
## handleSpawnNext
|
||||
|
||||
Find ready tasks, spawn workers, wait for completion, process results.
|
||||
|
||||
1. Read tasks.json
|
||||
2. Collect: completedTasks, inProgressTasks, readyTasks (pending + all deps completed)
|
||||
3. No ready + nothing in progress -> handleComplete
|
||||
4. No ready + work in progress -> report waiting, STOP
|
||||
5. Has ready -> for each:
|
||||
a. Check if inner loop role with active worker -> skip (worker picks up)
|
||||
b. Update task status in tasks.json -> in_progress
|
||||
c. team_msg log -> task_unblocked
|
||||
d. **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 from dispatch.md
|
||||
- After branch creation, re-collect readyTasks (spawns all REFACTOR-B* in parallel)
|
||||
|
||||
### Spawn Workers
|
||||
|
||||
For each ready task:
|
||||
|
||||
```javascript
|
||||
// 1) Update status in tasks.json
|
||||
state.tasks[taskId].status = 'in_progress'
|
||||
|
||||
// 2) Spawn worker
|
||||
const agentId = spawn_agent({
|
||||
agent_type: "team_worker",
|
||||
items: [
|
||||
{ type: "text", text: `## Role Assignment
|
||||
role: ${task.role}
|
||||
role_spec: ${skillRoot}/roles/${task.role}/role.md
|
||||
session: ${sessionFolder}
|
||||
session_id: ${sessionId}
|
||||
team_name: arch-opt
|
||||
requirement: ${task.description}
|
||||
inner_loop: ${task.role === 'refactorer'}` },
|
||||
|
||||
{ type: "text", text: `Read role_spec file (${skillRoot}/roles/${task.role}/role.md) to load Phase 2-4 domain instructions.
|
||||
Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).` },
|
||||
|
||||
{ type: "text", text: `## Task Context
|
||||
task_id: ${taskId}
|
||||
title: ${task.title}
|
||||
description: ${task.description}` },
|
||||
|
||||
{ type: "text", text: `## Upstream Context\n${prevContext}` }
|
||||
]
|
||||
})
|
||||
|
||||
// 3) Track agent
|
||||
state.active_agents[taskId] = { agentId, role: task.role, started_at: now }
|
||||
```
|
||||
|
||||
6. Parallel spawn rules by mode:
|
||||
|
||||
| Mode | Scenario | Spawn Behavior |
|
||||
|------|----------|---------------|
|
||||
| Single | Stage 4 ready | Spawn VALIDATE-001 + REVIEW-001 in parallel |
|
||||
| Fan-out (CP-2.5 done) | All REFACTOR-B* unblocked | Spawn ALL REFACTOR-B* in parallel |
|
||||
| Fan-out (REFACTOR-B{NN} done) | VALIDATE + REVIEW ready | Spawn both for that branch in parallel |
|
||||
| Independent | Any unblocked task | Spawn all ready tasks across all pipelines in parallel |
|
||||
|
||||
### Wait and Process Results
|
||||
|
||||
After spawning all ready tasks:
|
||||
|
||||
```javascript
|
||||
// 4) Batch wait for all spawned workers
|
||||
const agentIds = Object.values(state.active_agents).map(a => a.agentId)
|
||||
wait_agent({ ids: agentIds, timeout_ms: 900000 })
|
||||
|
||||
// 5) Collect results
|
||||
for (const [taskId, agent] of Object.entries(state.active_agents)) {
|
||||
state.tasks[taskId].status = 'completed'
|
||||
close_agent({ id: agent.agentId })
|
||||
delete state.active_agents[taskId]
|
||||
}
|
||||
```
|
||||
|
||||
### Persist and Loop
|
||||
|
||||
After processing all results:
|
||||
1. Write updated tasks.json
|
||||
2. Check stage checkpoints (CP-1, CP-2, CP-2.5, CP-3)
|
||||
3. Check if more tasks are now ready (deps newly resolved)
|
||||
4. If yes -> loop back to step 1 of handleSpawnNext
|
||||
5. If no more ready and all done -> handleComplete
|
||||
6. If no more ready but some still blocked -> report status, STOP
|
||||
|
||||
## Review-Fix Cycle (CP-3)
|
||||
|
||||
**Per-branch/pipeline scoping**: Each branch/pipeline has its own independent fix cycle.
|
||||
|
||||
When both VALIDATE-* and REVIEW-* are completed for a branch/pipeline:
|
||||
|
||||
1. Read validation verdict from scoped meta.json namespace
|
||||
2. Read review verdict from scoped meta.json namespace
|
||||
|
||||
| Validate Verdict | Review Verdict | Action |
|
||||
|-----------------|----------------|--------|
|
||||
| PASS | APPROVE | -> handleComplete check |
|
||||
| PASS | REVISE | Create FIX task in tasks.json with review feedback |
|
||||
| FAIL | APPROVE | Create FIX task in tasks.json with validation feedback |
|
||||
| FAIL | REVISE/REJECT | Create FIX task in tasks.json with combined feedback |
|
||||
| Any | REJECT | Create FIX task in tasks.json + flag for designer re-evaluation |
|
||||
|
||||
Fix cycle tracking per branch in tasks.json `fix_cycles`:
|
||||
- < 3: Add FIX task to tasks.json, increment cycle count
|
||||
- >= 3: Escalate THIS branch to user. Other branches continue
|
||||
|
||||
## handleComplete
|
||||
|
||||
Pipeline done. Generate report and completion action.
|
||||
|
||||
Completion check by mode:
|
||||
| Mode | Completion Condition |
|
||||
|------|---------------------|
|
||||
| Single | All 5 tasks (+ any FIX/retry tasks) completed |
|
||||
| Fan-out | ALL branches have VALIDATE + REVIEW completed (or escalated), shared stages done |
|
||||
| Independent | ALL pipelines have VALIDATE + REVIEW completed (or escalated) |
|
||||
|
||||
1. For fan-out/independent: aggregate per-branch/pipeline results to `<session>/artifacts/aggregate-results.json`
|
||||
2. If any tasks not completed, return to handleSpawnNext
|
||||
3. If all completed -> transition to coordinator Phase 5
|
||||
4. Execute completion action per tasks.json completion_action:
|
||||
- interactive -> request_user_input (Archive/Keep/Export)
|
||||
- auto_archive -> Archive & Clean (rm -rf session folder)
|
||||
- auto_keep -> Keep Active (status=paused)
|
||||
|
||||
## handleConsensus
|
||||
|
||||
Handle consensus_blocked signals from discuss rounds.
|
||||
|
||||
| Severity | Action |
|
||||
|----------|--------|
|
||||
| HIGH | Pause pipeline (or branch), notify user with findings summary |
|
||||
| MEDIUM | Add revision task to tasks.json for the blocked role (scoped to branch if applicable) |
|
||||
| LOW | Log finding, continue pipeline |
|
||||
|
||||
## handleAdapt
|
||||
|
||||
Capability gap reported mid-pipeline.
|
||||
|
||||
1. Parse gap description
|
||||
2. Check if existing role covers it -> redirect
|
||||
3. Role count < 5 -> generate dynamic role-spec in <session>/role-specs/
|
||||
4. Add new task to tasks.json, spawn worker via spawn_agent + wait_agent
|
||||
5. Role count >= 5 -> merge or pause
|
||||
|
||||
## Fast-Advance Reconciliation
|
||||
|
||||
On every coordinator wake:
|
||||
1. Read team_msg entries with type="fast_advance"
|
||||
2. Sync active_agents with spawned successors
|
||||
3. No duplicate spawns
|
||||
162
.codex/skills/team-arch-opt/roles/coordinator/role.md
Normal file
162
.codex/skills/team-arch-opt/roles/coordinator/role.md
Normal file
@@ -0,0 +1,162 @@
|
||||
# Coordinator
|
||||
|
||||
Orchestrate team-arch-opt: analyze -> dispatch -> spawn -> monitor -> report.
|
||||
|
||||
## Identity
|
||||
- Name: coordinator | Tag: [coordinator]
|
||||
- Responsibility: Analyze task -> Create session -> Dispatch tasks -> Monitor progress -> Report results
|
||||
|
||||
## Boundaries
|
||||
|
||||
### MUST
|
||||
- Spawn workers via `spawn_agent({ agent_type: "team_worker" })` and wait via `wait_agent`
|
||||
- Follow Command Execution Protocol for dispatch and monitor commands
|
||||
- Respect pipeline stage dependencies (deps)
|
||||
- Handle review-fix cycles with max 3 iterations
|
||||
- Execute completion action in Phase 5
|
||||
|
||||
### MUST NOT
|
||||
- Implement domain logic (analyzing, refactoring, reviewing) -- workers handle this
|
||||
- Spawn workers without creating tasks first
|
||||
- Skip checkpoints when configured
|
||||
- Force-advance pipeline past failed review/validation
|
||||
- Modify source code directly -- delegate to refactorer worker
|
||||
|
||||
## Command Execution Protocol
|
||||
|
||||
When coordinator needs to execute a specific phase:
|
||||
1. Read `commands/<command>.md`
|
||||
2. Follow the workflow defined in the command
|
||||
3. Commands are inline execution guides, NOT separate agents
|
||||
4. Execute synchronously, complete before proceeding
|
||||
|
||||
## Entry Router
|
||||
|
||||
| Detection | Condition | Handler |
|
||||
|-----------|-----------|---------|
|
||||
| Status check | Args contain "check" or "status" | -> handleCheck (monitor.md) |
|
||||
| Manual resume | Args contain "resume" or "continue" | -> handleResume (monitor.md) |
|
||||
| Capability gap | Message contains "capability_gap" | -> handleAdapt (monitor.md) |
|
||||
| Pipeline complete | All tasks completed | -> handleComplete (monitor.md) |
|
||||
| Interrupted session | Active session in .workflow/.team/TAO-* | -> Phase 0 |
|
||||
| New session | None of above | -> Phase 1 |
|
||||
|
||||
For check/resume/adapt/complete: load @commands/monitor.md, execute handler, STOP.
|
||||
|
||||
## Phase 0: Session Resume Check
|
||||
|
||||
1. Scan `.workflow/.team/TAO-*/tasks.json` for active/paused sessions
|
||||
2. No sessions -> Phase 1
|
||||
3. Single session -> reconcile:
|
||||
a. Read tasks.json, reset in_progress -> pending
|
||||
b. Rebuild active_agents map
|
||||
c. Kick first ready task via handleSpawnNext
|
||||
4. Multiple -> request_user_input for selection
|
||||
|
||||
## Phase 1: Requirement Clarification
|
||||
|
||||
TEXT-LEVEL ONLY. No source code reading.
|
||||
|
||||
1. Parse task description from $ARGUMENTS
|
||||
2. Parse parallel mode flags:
|
||||
|
||||
| Flag | Value | Default |
|
||||
|------|-------|---------|
|
||||
| `--parallel-mode` | `single`, `fan-out`, `independent`, `auto` | `auto` |
|
||||
| `--max-branches` | integer 1-10 | 5 |
|
||||
|
||||
3. Identify architecture optimization target:
|
||||
|
||||
| Signal | Target |
|
||||
|--------|--------|
|
||||
| Specific file/module mentioned | Scoped refactoring |
|
||||
| "coupling", "dependency", "structure", generic | Full architecture analysis |
|
||||
| Specific issue (cycles, God Class, duplication) | Targeted issue resolution |
|
||||
| Multiple quoted targets (independent mode) | Per-target scoped refactoring |
|
||||
|
||||
4. If target is unclear, request_user_input for scope clarification
|
||||
5. Record requirement with scope, target issues, parallel_mode, max_branches
|
||||
|
||||
## Phase 2: Create Session + Initialize
|
||||
|
||||
1. Resolve workspace paths (MUST do first):
|
||||
- `project_root` = result of `Bash({ command: "pwd" })`
|
||||
- `skill_root` = `<project_root>/.codex/skills/team-arch-opt`
|
||||
2. Generate session ID: `TAO-<slug>-<date>`
|
||||
3. Create session folder structure:
|
||||
```bash
|
||||
mkdir -p .workflow/.team/${SESSION_ID}/{artifacts,artifacts/branches,artifacts/pipelines,wisdom,wisdom/.msg}
|
||||
```
|
||||
4. Initialize meta.json via team_msg state_update:
|
||||
```
|
||||
mcp__ccw-tools__team_msg({
|
||||
operation: "log", session_id: "<id>", from: "coordinator",
|
||||
type: "state_update", summary: "Session initialized",
|
||||
data: { pipeline_mode: "<mode>", pipeline_stages: ["analyzer","designer","refactorer","validator","reviewer"], team_name: "arch-opt" }
|
||||
})
|
||||
```
|
||||
5. Write initial tasks.json:
|
||||
```json
|
||||
{
|
||||
"session_id": "<id>",
|
||||
"pipeline": "<parallel_mode>",
|
||||
"requirement": "<original requirement>",
|
||||
"created_at": "<ISO timestamp>",
|
||||
"parallel_mode": "<single|fan-out|independent|auto>",
|
||||
"max_branches": 5,
|
||||
"branches": [],
|
||||
"independent_targets": [],
|
||||
"fix_cycles": {},
|
||||
"completed_waves": [],
|
||||
"active_agents": {},
|
||||
"tasks": {}
|
||||
}
|
||||
```
|
||||
|
||||
## Phase 3: Create Task Chain
|
||||
|
||||
Delegate to @commands/dispatch.md:
|
||||
1. Read dependency graph and parallel mode from tasks.json
|
||||
2. Topological sort tasks
|
||||
3. Write tasks to tasks.json with deps arrays
|
||||
4. Update tasks.json metadata (total count)
|
||||
|
||||
## Phase 4: Spawn-and-Wait
|
||||
|
||||
Delegate to @commands/monitor.md#handleSpawnNext:
|
||||
1. Find ready tasks (pending + deps resolved)
|
||||
2. Spawn team_worker agents via spawn_agent
|
||||
3. Wait for completion via wait_agent
|
||||
4. Process results, advance pipeline
|
||||
5. Repeat until all waves complete or pipeline blocked
|
||||
|
||||
## Phase 5: Report + Completion Action
|
||||
|
||||
1. Load session state -> count completed tasks, calculate duration
|
||||
2. List deliverables:
|
||||
|
||||
| Deliverable | Path |
|
||||
|-------------|------|
|
||||
| Architecture Baseline | <session>/artifacts/architecture-baseline.json |
|
||||
| Architecture Report | <session>/artifacts/architecture-report.md |
|
||||
| Refactoring Plan | <session>/artifacts/refactoring-plan.md |
|
||||
| Validation Results | <session>/artifacts/validation-results.json |
|
||||
| Review Report | <session>/artifacts/review-report.md |
|
||||
|
||||
3. Include discussion summaries if discuss rounds were used
|
||||
4. Output pipeline summary: task count, duration, improvement metrics
|
||||
|
||||
5. Execute completion action per tasks.json completion_action:
|
||||
- interactive -> request_user_input (Archive/Keep/Export)
|
||||
- auto_archive -> Archive & Clean (rm -rf session folder)
|
||||
- auto_keep -> Keep Active (status=paused)
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Resolution |
|
||||
|-------|------------|
|
||||
| Task too vague | request_user_input for clarification |
|
||||
| Session corruption | Attempt recovery, fallback to manual |
|
||||
| Worker crash | Reset task to pending in tasks.json, respawn via spawn_agent |
|
||||
| Dependency cycle | Detect in analysis, halt |
|
||||
| Role limit exceeded | Merge overlapping roles |
|
||||
115
.codex/skills/team-arch-opt/roles/designer/role.md
Normal file
115
.codex/skills/team-arch-opt/roles/designer/role.md
Normal file
@@ -0,0 +1,115 @@
|
||||
---
|
||||
role: designer
|
||||
prefix: DESIGN
|
||||
inner_loop: false
|
||||
message_types: [state_update]
|
||||
---
|
||||
|
||||
# Refactoring Designer
|
||||
|
||||
Analyze architecture reports and baseline metrics to design a prioritized refactoring plan with concrete strategies, expected structural improvements, and risk assessments.
|
||||
|
||||
## Phase 2: Analysis Loading
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Architecture report | <session>/artifacts/architecture-report.md | Yes |
|
||||
| Architecture baseline | <session>/artifacts/architecture-baseline.json | Yes |
|
||||
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
|
||||
| Wisdom files | <session>/wisdom/patterns.md | No |
|
||||
|
||||
1. Extract session path from task description
|
||||
2. Read architecture report -- extract ranked issue list with severities and categories
|
||||
3. Read architecture baseline -- extract current structural metrics
|
||||
4. Load .msg/meta.json for analyzer findings (project_type, scope)
|
||||
5. Assess overall refactoring complexity:
|
||||
|
||||
| Issue Count | Severity Mix | Complexity |
|
||||
|-------------|-------------|------------|
|
||||
| 1-2 | All Medium | Low |
|
||||
| 2-3 | Mix of High/Medium | Medium |
|
||||
| 3+ or any Critical | Any Critical present | High |
|
||||
|
||||
## Phase 3: Strategy Formulation
|
||||
|
||||
For each architecture issue, select refactoring approach by type:
|
||||
|
||||
| Issue Type | Strategies | Risk Level |
|
||||
|------------|-----------|------------|
|
||||
| Circular dependency | Interface extraction, dependency inversion, mediator pattern | High |
|
||||
| God Class/Module | SRP decomposition, extract class/module, delegate pattern | High |
|
||||
| Layering violation | Move to correct layer, introduce Facade, add anti-corruption layer | Medium |
|
||||
| Code duplication | Extract shared utility/base class, template method pattern | Low |
|
||||
| High coupling | Introduce interface/abstraction, dependency injection, event-driven | Medium |
|
||||
| API bloat / dead exports | Privatize internals, re-export only public API, barrel file cleanup | Low |
|
||||
| Dead code | Safe removal with reference verification | Low |
|
||||
| Missing abstraction | Extract interface/type, introduce strategy/factory pattern | Medium |
|
||||
|
||||
Prioritize refactorings by impact/effort ratio:
|
||||
|
||||
| Priority | Criteria |
|
||||
|----------|----------|
|
||||
| P0 (Critical) | High impact + Low effort -- quick wins (dead code removal, simple moves) |
|
||||
| P1 (High) | High impact + Medium effort (cycle breaking, layer fixes) |
|
||||
| P2 (Medium) | Medium impact + Low effort (duplication extraction) |
|
||||
| P3 (Low) | Low impact or High effort -- defer (large God Class decomposition) |
|
||||
|
||||
If complexity is High, invoke `discuss` CLI tool (DISCUSS-REFACTOR round) to evaluate trade-offs between competing strategies before finalizing the plan.
|
||||
|
||||
Define measurable success criteria per refactoring (target metric improvement or structural change).
|
||||
|
||||
## Phase 4: Plan Output
|
||||
|
||||
1. Write refactoring plan to `<session>/artifacts/refactoring-plan.md`:
|
||||
|
||||
Each refactoring MUST have a unique REFACTOR-ID and self-contained detail block:
|
||||
|
||||
```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/.msg/meta.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`
|
||||
102
.codex/skills/team-arch-opt/roles/refactorer/role.md
Normal file
102
.codex/skills/team-arch-opt/roles/refactorer/role.md
Normal file
@@ -0,0 +1,102 @@
|
||||
---
|
||||
role: refactorer
|
||||
prefix: REFACTOR
|
||||
inner_loop: true
|
||||
message_types: [state_update]
|
||||
---
|
||||
|
||||
# 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) |
|
||||
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
|
||||
| Wisdom files | <session>/wisdom/patterns.md | No |
|
||||
| Context accumulator | From prior REFACTOR/FIX tasks | Yes (inner loop) |
|
||||
|
||||
1. Extract session path and task mode (REFACTOR or FIX) from task description
|
||||
2. **Detect branch/pipeline context** from task description:
|
||||
|
||||
| Task Description Field | Value | Context |
|
||||
|----------------------|-------|---------|
|
||||
| `BranchId: B{NN}` | Present | Fan-out branch -- load single refactoring detail |
|
||||
| `PipelineId: {P}` | Present | Independent pipeline -- load pipeline-scoped plan |
|
||||
| Neither present | - | Single mode -- load full refactoring plan |
|
||||
|
||||
3. **Load refactoring context by mode**:
|
||||
- **Single mode (no branch)**: Read `<session>/artifacts/refactoring-plan.md` -- extract ALL priority-ordered changes
|
||||
- **Fan-out branch**: Read `<session>/artifacts/branches/B{NN}/refactoring-detail.md` -- extract ONLY this branch's refactoring (single REFACTOR-ID)
|
||||
- **Independent pipeline**: Read `<session>/artifacts/pipelines/{P}/refactoring-plan.md` -- extract this pipeline's plan
|
||||
|
||||
4. For FIX: parse review/validation feedback for specific issues to address
|
||||
5. Use `explore` CLI tool to load implementation context for target files
|
||||
6. For inner loop (single mode only): load context_accumulator from prior REFACTOR/FIX tasks
|
||||
|
||||
**Meta.json namespace**:
|
||||
- Single: write to `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}/`
|
||||
111
.codex/skills/team-arch-opt/roles/reviewer/role.md
Normal file
111
.codex/skills/team-arch-opt/roles/reviewer/role.md
Normal file
@@ -0,0 +1,111 @@
|
||||
---
|
||||
role: reviewer
|
||||
prefix: REVIEW
|
||||
inner_loop: false
|
||||
message_types: [state_update]
|
||||
---
|
||||
|
||||
# Architecture Reviewer
|
||||
|
||||
Review refactoring code changes for correctness, pattern consistency, completeness, migration safety, and adherence to best practices. Provide structured verdicts with actionable feedback.
|
||||
|
||||
## Phase 2: Context Loading
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Refactoring code changes | From REFACTOR task artifacts / git diff | Yes |
|
||||
| Refactoring plan / detail | Varies by mode (see below) | Yes |
|
||||
| Validation results | Varies by mode (see below) | No |
|
||||
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
|
||||
|
||||
1. Extract session path from task description
|
||||
2. **Detect branch/pipeline context** from task description:
|
||||
|
||||
| Task Description Field | Value | Context |
|
||||
|----------------------|-------|---------|
|
||||
| `BranchId: B{NN}` | Present | Fan-out branch -- review only this branch's changes |
|
||||
| `PipelineId: {P}` | Present | Independent pipeline -- review pipeline-scoped changes |
|
||||
| Neither present | - | Single mode -- review all refactoring changes |
|
||||
|
||||
3. **Load refactoring context by mode**:
|
||||
- Single: Read `<session>/artifacts/refactoring-plan.md`
|
||||
- Fan-out branch: Read `<session>/artifacts/branches/B{NN}/refactoring-detail.md`
|
||||
- Independent: Read `<session>/artifacts/pipelines/{P}/refactoring-plan.md`
|
||||
|
||||
4. Load .msg/meta.json for scoped refactorer namespace:
|
||||
- Single: `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` CLI tool (DISCUSS-REVIEW round) to validate the assessment before issuing verdict.
|
||||
|
||||
## Phase 4: Verdict & Feedback
|
||||
|
||||
Classify overall verdict based on findings:
|
||||
|
||||
| Verdict | Condition | Action |
|
||||
|---------|-----------|--------|
|
||||
| APPROVE | No Critical or High findings | Send review_complete |
|
||||
| REVISE | Has High findings, no Critical | Send fix_required with detailed feedback |
|
||||
| REJECT | Has Critical findings or fundamental approach flaw | Send fix_required + flag for designer escalation |
|
||||
|
||||
1. Write review report to scoped output path:
|
||||
- Single: `<session>/artifacts/review-report.md`
|
||||
- Fan-out: `<session>/artifacts/branches/B{NN}/review-report.md`
|
||||
- Independent: `<session>/artifacts/pipelines/{P}/review-report.md`
|
||||
- Content: Per-dimension findings with severity, file:line, description; Overall verdict with rationale; Specific fix instructions for REVISE/REJECT verdicts
|
||||
|
||||
2. Update `<session>/wisdom/.msg/meta.json` under scoped namespace:
|
||||
- Single: merge `{ "reviewer": { verdict, finding_count, critical_count, dimensions_reviewed } }`
|
||||
- Fan-out: merge `{ "reviewer.B{NN}": { verdict, finding_count, critical_count, dimensions_reviewed } }`
|
||||
- Independent: merge `{ "reviewer.{P}": { verdict, finding_count, critical_count, dimensions_reviewed } }`
|
||||
|
||||
3. If DISCUSS-REVIEW was triggered, record discussion summary in `<session>/discussions/DISCUSS-REVIEW.md` (or `DISCUSS-REVIEW-B{NN}.md` for branch-scoped discussions)
|
||||
115
.codex/skills/team-arch-opt/roles/validator/role.md
Normal file
115
.codex/skills/team-arch-opt/roles/validator/role.md
Normal file
@@ -0,0 +1,115 @@
|
||||
---
|
||||
role: validator
|
||||
prefix: VALIDATE
|
||||
inner_loop: false
|
||||
message_types: [state_update]
|
||||
---
|
||||
|
||||
# Architecture Validator
|
||||
|
||||
Validate refactoring changes by running build checks, test suites, dependency metric comparisons, and API compatibility verification. Ensure refactoring improves architecture without breaking functionality.
|
||||
|
||||
## Phase 2: Environment & Baseline Loading
|
||||
|
||||
| Input | Source | Required |
|
||||
|-------|--------|----------|
|
||||
| Architecture baseline | <session>/artifacts/architecture-baseline.json (shared) | Yes |
|
||||
| Refactoring plan / detail | Varies by mode (see below) | Yes |
|
||||
| .msg/meta.json | <session>/wisdom/.msg/meta.json | Yes |
|
||||
|
||||
1. Extract session path from task description
|
||||
2. **Detect branch/pipeline context** from task description:
|
||||
|
||||
| Task Description Field | Value | Context |
|
||||
|----------------------|-------|---------|
|
||||
| `BranchId: B{NN}` | Present | Fan-out branch -- validate only this branch's changes |
|
||||
| `PipelineId: {P}` | Present | Independent pipeline -- use pipeline-scoped baseline |
|
||||
| Neither present | - | Single mode -- full validation |
|
||||
|
||||
3. **Load architecture baseline**:
|
||||
- Single / Fan-out: Read `<session>/artifacts/architecture-baseline.json` (shared baseline)
|
||||
- Independent: Read `<session>/artifacts/pipelines/{P}/architecture-baseline.json`
|
||||
|
||||
4. **Load refactoring context**:
|
||||
- Single: Read `<session>/artifacts/refactoring-plan.md` -- all success criteria
|
||||
- Fan-out branch: Read `<session>/artifacts/branches/B{NN}/refactoring-detail.md` -- only this branch's criteria
|
||||
- Independent: Read `<session>/artifacts/pipelines/{P}/refactoring-plan.md`
|
||||
|
||||
5. Load .msg/meta.json for project type and refactoring scope
|
||||
6. Detect available validation tools from project:
|
||||
|
||||
| Signal | Validation Tool | Method |
|
||||
|--------|----------------|--------|
|
||||
| package.json + tsc | TypeScript compiler | Type-check entire project |
|
||||
| package.json + vitest/jest | Test runner | Run existing test suite |
|
||||
| package.json + eslint | Linter | Run lint checks for import/export issues |
|
||||
| Cargo.toml | Rust compiler | cargo check + cargo test |
|
||||
| go.mod | Go tools | go build + go test |
|
||||
| Makefile with test target | Custom tests | make test |
|
||||
| No tooling detected | Manual validation | File existence + import grep checks |
|
||||
|
||||
7. Get changed files scope from .msg/meta.json:
|
||||
- Single: `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/.msg/meta.json` under scoped namespace:
|
||||
- Single: merge `{ "validator": { verdict, improvements, regressions, build_pass, test_pass } }`
|
||||
- Fan-out: merge `{ "validator.B{NN}": { verdict, improvements, regressions, build_pass, test_pass } }`
|
||||
- Independent: merge `{ "validator.{P}": { verdict, improvements, regressions, build_pass, test_pass } }`
|
||||
|
||||
3. If verdict is FAIL, include detailed feedback in message for FIX task creation:
|
||||
- Which validations failed, specific errors, suggested investigation areas
|
||||
Reference in New Issue
Block a user