
Team Perf Opt
- 38 installs
- 2.1k repo stars
- Updated June 18, 2026
- catlog22/claude-code-workflow
Support for team-perf-opt
About
Provides workflow support for team-perf-opt. Solo builders use this to streamline development.
- team-perf-opt
Team Perf Opt by the numbers
- 38 all-time installs (skills.sh)
- Ranked #1,739 of 3,282 Productivity & Planning skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/catlog22/claude-code-workflow --skill team-perf-optAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 38 |
|---|---|
| repo stars | ★ 2.1k |
| Last updated | June 18, 2026 |
| Repository | catlog22/claude-code-workflow ↗ |
What it does
Support for team-perf-opt
Files
Team Performance Optimization
Profile application performance, identify bottlenecks, design optimization strategies, implement changes, benchmark improvements, and review code quality.
Architecture
Skill(skill="team-perf-opt", args="<task-description>")
|
SKILL.md (this file) = Router
|
+--------------+--------------+
| |
no --role flag --role <name>
| |
Coordinator Worker
roles/coordinator/role.md roles/<name>/role.md
|
+-- analyze -> dispatch -> spawn workers -> STOP
|
+-------+-------+-------+-------+-------+
v v v v v
[profiler] [strategist] [optimizer] [benchmarker] [reviewer]
(team-worker agents)
Pipeline (Single mode):
PROFILE-001 -> STRATEGY-001 -> IMPL-001 -> BENCH-001 + REVIEW-001 (fix cycle)
Pipeline (Fan-out mode):
PROFILE-001 -> STRATEGY-001 -> [IMPL-B01..N](parallel) -> BENCH+REVIEW per branch
Pipeline (Independent mode):
[Pipeline A: PROFILE-A->STRATEGY-A->IMPL-A->BENCH-A+REVIEW-A]
[Pipeline B: PROFILE-B->STRATEGY-B->IMPL-B->BENCH-B+REVIEW-B] (parallel)Role Registry
| Role | Path | Prefix | Inner Loop |
|---|---|---|---|
| coordinator | roles/coordinator/role.md | — | — |
| profiler | roles/profiler/role.md | PROFILE-* | false |
| strategist | roles/strategist/role.md | STRATEGY-* | false |
| optimizer | roles/optimizer/role.md | IMPL-, FIX- | true |
| benchmarker | roles/benchmarker/role.md | BENCH-* | false |
| reviewer | roles/reviewer/role.md | REVIEW-, QUALITY- | false |
Role Router
Parse $ARGUMENTS:
- Has
--role <name>→ Readroles/<name>/role.md, execute Phase 2-4 - No
--role→@roles/coordinator/role.md, execute entry router
Shared Constants
- Session prefix:
PERF-OPT - Session path:
.workflow/.team/PERF-OPT-<slug>-<date>/ - Team name:
perf-opt - CLI tools:
ccw cli --mode analysis(read-only),ccw cli --mode write(modifications) - Message bus:
mcp__ccw-tools__team_msg(session_id=<session-id>, ...)
Worker Spawn Template
Coordinator spawns workers using this template:
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker",
team_name: "perf-opt",
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: <skill_root>/roles/<role>/role.md
session: <session-folder>
session_id: <session-id>
team_name: perf-opt
requirement: <task-description>
inner_loop: <true|false>
## Progress Milestones
session_id: <session-id>
Report progress via team_msg at natural phase boundaries (context loaded -> core work done -> verification).
Report blockers immediately via team_msg type="blocker".
Report completion via team_msg type="task_complete" after final SendMessage.
Read role_spec file (@<skill_root>/roles/<role>/role.md) to load Phase 2-4 domain instructions.
Execute built-in Phase 1 (task discovery) -> role Phase 2-4 -> built-in Phase 5 (report).`
})Inner Loop roles (optimizer): Set inner_loop dynamically — true for single mode, false for fan-out/independent (parallel branches). Single-task roles (profiler, strategist, benchmarker, reviewer): Set inner_loop: false.
User Commands
| Command | Action |
|---|---|
check / status | Output execution status graph (branch-grouped), no advancement |
resume / continue | Check worker states, advance next step |
revise <TASK-ID> [feedback] | Create revision task + cascade downstream (scoped to branch) |
feedback <text> | Analyze feedback impact, create targeted revision chain |
recheck | Re-run quality check |
improve [dimension] | Auto-improve weakest dimension |
Session Directory
.workflow/.team/PERF-OPT-<slug>-<date>/
+-- session.json # Session metadata + status + parallel_mode
+-- artifacts/
| +-- baseline-metrics.json # Profiler: before-optimization metrics
| +-- bottleneck-report.md # Profiler: ranked bottleneck findings
| +-- optimization-plan.md # Strategist: prioritized optimization plan
| +-- benchmark-results.json # Benchmarker: after-optimization metrics
| +-- review-report.md # Reviewer: code review findings
| +-- branches/B01/... # Fan-out branch artifacts
| +-- pipelines/A/... # Independent pipeline artifacts
+-- explorations/ # Shared explore cache
+-- wisdom/patterns.md # Discovered patterns and conventions
+-- discussions/ # Discussion records
+-- .msg/messages.jsonl # Team message bus
+-- .msg/meta.json # Session metadataCompletion Action
When the pipeline completes:
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" }
]
}]
})Specs Reference
- specs/pipelines.md — Pipeline definitions and task registry
- specs/team-config.json — Team configuration
Error Handling
| Scenario | Resolution |
|---|---|
| Unknown --role value | Error with role registry list |
| Role file not found | Error with expected path (roles/{name}/role.md) |
| Profiling tool not available | Fallback to static analysis methods |
| Benchmark regression detected | Auto-create FIX task with regression details |
| Review-fix cycle exceeds 3 iterations | Escalate to user |
| One branch IMPL fails | Mark that branch failed, other branches continue |
| Fast-advance conflict | Coordinator reconciles on next callback |
| Completion action fails | Default to Keep Active |
Performance Benchmarker
Run benchmarks comparing before/after optimization metrics. Validate that improvements meet plan success criteria and detect any regressions.
Phase 2: Environment & Baseline Loading
| Input | Source | Required |
|---|---|---|
| Baseline metrics | <session>/artifacts/baseline-metrics.json (shared) | Yes |
| Optimization plan / detail | Varies by mode (see below) | Yes |
| .msg/meta.json | <session>/.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 -- benchmark only this branch's metrics |
PipelineId: {P} | Present | Independent pipeline -- use pipeline-scoped baseline |
| Neither present | - | Single mode -- full benchmark |
3. Load baseline metrics:
- Single / Fan-out: Read
<session>/artifacts/baseline-metrics.json(shared baseline) - Independent: Read
<session>/artifacts/pipelines/{P}/baseline-metrics.json
4. Load optimization context:
- Single: Read
<session>/artifacts/optimization-plan.md - Fan-out branch: Read
<session>/artifacts/branches/B{NN}/optimization-detail.md - Independent: Read
<session>/artifacts/pipelines/{P}/optimization-plan.md
5. Load .msg/meta.json for project type and optimization scope 6. Detect available benchmark tools from project:
| Signal | Benchmark Tool | Method |
|---|---|---|
| package.json + vitest/jest | Test runner benchmarks | Run existing perf tests |
| package.json + webpack/vite | Bundle analysis | Compare build output sizes |
| Cargo.toml + criterion | Rust benchmarks | cargo bench |
| go.mod | Go benchmarks | go test -bench |
| Makefile with bench target | Custom benchmarks | make bench |
| No tooling detected | Manual measurement | Timed execution via Bash |
7. Get changed files scope from shared-memory (optimizer namespace, scoped by branch/pipeline)
Phase 3: Benchmark Execution
Run benchmarks matching detected project type:
Frontend benchmarks: Compare bundle size, render performance, dependency weight changes.
Backend benchmarks: Measure endpoint response times, memory usage under load, database query improvements.
CLI / Library benchmarks: Execution time, memory peak, throughput under sustained load.
All project types:
- Run existing test suite to verify no regressions
- Collect post-optimization metrics matching baseline format
- Calculate improvement percentages per metric
Branch-scoped benchmarking (fan-out mode):
- Only benchmark metrics relevant to this branch's optimization
- Still check for regressions across all metrics
Phase 4: Result Analysis
Compare against baseline and plan criteria:
| Metric | Threshold | Verdict |
|---|---|---|
| Target improvement vs baseline | Meets plan success criteria | PASS |
| No regression in unrelated metrics | < 5% degradation allowed | PASS |
| All plan success criteria met | Every criterion satisfied | PASS |
| Improvement below target | > 50% of target achieved | WARN |
| Regression detected | Any unrelated metric degrades > 5% | FAIL -> fix_required |
| Plan criteria not met | Any criterion not satisfied | FAIL -> fix_required |
1. Write benchmark results to output path (scoped by branch/pipeline/single) 2. Update <session>/.msg/meta.json under scoped namespace 3. If verdict is FAIL, include detailed feedback in message for FIX task creation
Analyze Task - Performance Optimization
Parse optimization request -> detect parallel mode -> determine scope -> design pipeline structure.
CONSTRAINT: Text-level analysis only. NO source code reading, NO codebase exploration.
Signal Detection
Parallel Mode Detection
| Flag | Value | Pipeline Shape |
|---|---|---|
--parallel-mode=single | explicit | Single linear pipeline |
--parallel-mode=fan-out | explicit | Shared profile+strategy, N parallel IMPL branches |
--parallel-mode=independent | explicit | M fully independent pipelines |
--parallel-mode=auto or absent | default | Auto-detect from bottleneck count at CP-2.5 |
auto with count <= 2 | auto-resolved | single mode |
auto with count >= 3 | auto-resolved | fan-out mode |
Scope Detection
| Signal | Target |
|---|---|
| Specific file/module mentioned | Scoped optimization |
| "slow", "performance", generic | Full application profiling |
| Specific metric mentioned (FCP, memory, startup) | Targeted metric optimization |
| Multiple quoted targets (independent mode) | Per-target scoped optimization |
Optimization Keywords
| Keywords | Capability |
|---|---|
| profile, bottleneck, slow, benchmark | profiler |
| optimize, improve, reduce, speed | optimizer |
| strategy, plan, prioritize | strategist |
| verify, test, validate | benchmarker |
| review, audit, quality | reviewer |
Output
Coordinator state from this command (used by dispatch.md):
{
"parallel_mode": "<auto|single|fan-out|independent>",
"max_branches": 5,
"optimization_targets": ["<target1>", "<target2>"],
"independent_targets": [],
"scope": "<specific|full-app|targeted>",
"target_metrics": ["<metric1>", "<metric2>"]
}Pipeline Structure by Mode
| Mode | Stages |
|---|---|
| single | PROFILE-001 -> STRATEGY-001 -> IMPL-001 -> BENCH-001 + REVIEW-001 |
| fan-out | PROFILE-001 -> STRATEGY-001 -> [IMPL-B01..N in parallel] -> BENCH+REVIEW per branch |
| independent | N complete pipelines (PROFILE+STRATEGY+IMPL+BENCH+REVIEW) in parallel |
| auto | Decided at CP-2.5 after STRATEGY-001 completes based on bottleneck count |
Command: Dispatch
Create the performance 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 optimization scope from session.json 2. Load pipeline stage definitions from SKILL.md Task Metadata Registry 3. Read parallel_mode and max_branches from session.json 4. For independent mode: read independent_targets array from session.json
Phase 3: Task Chain Creation (Mode-Branched)
Task Description Template
Every task description uses structured format for clarity:
TaskCreate({
subject: "<TASK-ID>",
description: "PURPOSE: <what this task achieves> | Success: <measurable completion criteria>
TASK:
- <step 1: specific action>
- <step 2: specific action>
- <step 3: specific action>
CONTEXT:
- Session: <session-folder>
- Scope: <optimization-scope>
- Branch: <branch-id or 'none'>
- Upstream artifacts: <artifact-1>, <artifact-2>
- Shared memory: <session>/.msg/meta.json
EXPECTED: <deliverable path> + <quality criteria>
CONSTRAINTS: <scope limits, focus areas>
---
InnerLoop: <true|false>
BranchId: <B01|A|none>",
status: "pending"
})
TaskUpdate({ taskId: "<TASK-ID>", addBlockedBy: [<dependency-list>], owner: "<role>" })Mode Router
| Mode | Action |
|---|---|
single | Create 5 tasks (PROFILE → STRATEGY → IMPL → BENCH + REVIEW) -- unchanged from linear pipeline |
auto | Create PROFILE-001 + STRATEGY-001 only. Defer branch creation to CP-2.5 after strategy completes |
fan-out | Create PROFILE-001 + STRATEGY-001 only. Defer branch creation to CP-2.5 after strategy completes |
independent | Create M complete pipelines immediately (one per target) |
---
Single Mode Task Chain
Create tasks in dependency order (backward compatible, unchanged):
PROFILE-001 (profiler, Stage 1):
TaskCreate({
subject: "PROFILE-001",
description: "PURPOSE: Profile application performance to identify bottlenecks | Success: Baseline metrics captured, top 3-5 bottlenecks ranked by severity
TASK:
- Detect project type and available profiling tools
- Execute profiling across relevant dimensions (CPU, memory, I/O, network, rendering)
- Collect baseline metrics and rank bottlenecks by severity
CONTEXT:
- Session: <session-folder>
- Scope: <optimization-scope>
- Branch: none
- Shared memory: <session>/.msg/meta.json
EXPECTED: <session>/artifacts/baseline-metrics.json + <session>/artifacts/bottleneck-report.md | Quantified metrics with evidence
CONSTRAINTS: Focus on <optimization-scope> | Profile before any changes
---
InnerLoop: false",
status: "pending"
})STRATEGY-001 (strategist, Stage 2):
TaskCreate({
subject: "STRATEGY-001",
description: "PURPOSE: Design prioritized optimization plan from bottleneck analysis | Success: Actionable plan with measurable success criteria per optimization
TASK:
- Analyze bottleneck report and baseline metrics
- Select optimization strategies per bottleneck type
- Prioritize by impact/effort ratio, define success criteria
- Each optimization MUST have a unique OPT-ID (OPT-001, OPT-002, ...) with non-overlapping target files
CONTEXT:
- Session: <session-folder>
- Scope: <optimization-scope>
- Branch: none
- Upstream artifacts: baseline-metrics.json, bottleneck-report.md
- Shared memory: <session>/.msg/meta.json
EXPECTED: <session>/artifacts/optimization-plan.md | Priority-ordered with improvement targets, discrete OPT-IDs
CONSTRAINTS: Focus on highest-impact optimizations | Risk assessment required | Non-overlapping file targets per OPT-ID
---
InnerLoop: false",
status: "pending"
})
TaskUpdate({ taskId: "STRATEGY-001", addBlockedBy: ["PROFILE-001"] })IMPL-001 (optimizer, Stage 3):
TaskCreate({
subject: "IMPL-001",
description: "PURPOSE: Implement optimization changes per strategy plan | Success: All planned optimizations applied, code compiles, existing tests pass
TASK:
- Load optimization plan and identify target files
- Apply optimizations in priority order (P0 first)
- Validate changes compile and pass existing tests
CONTEXT:
- Session: <session-folder>
- Scope: <optimization-scope>
- Branch: none
- Upstream artifacts: optimization-plan.md
- Shared memory: <session>/.msg/meta.json
EXPECTED: Modified source files + validation passing | Optimizations applied without regressions
CONSTRAINTS: Preserve existing behavior | Minimal changes per optimization | Follow code conventions
---
InnerLoop: true",
status: "pending"
})
TaskUpdate({ taskId: "IMPL-001", addBlockedBy: ["STRATEGY-001"] })BENCH-001 (benchmarker, Stage 4 - parallel):
TaskCreate({
subject: "BENCH-001",
description: "PURPOSE: Benchmark optimization results against baseline | Success: All plan success criteria met, no regressions detected
TASK:
- Load baseline metrics and plan success criteria
- Run benchmarks matching project type
- Compare before/after metrics, calculate improvements
CONTEXT:
- Session: <session-folder>
- Scope: <optimization-scope>
- Branch: none
- Upstream artifacts: baseline-metrics.json, optimization-plan.md
- Shared memory: <session>/.msg/meta.json
EXPECTED: <session>/artifacts/benchmark-results.json | Per-metric comparison with verdicts
CONSTRAINTS: Must compare against baseline | Flag any regressions
---
InnerLoop: false",
status: "pending"
})
TaskUpdate({ taskId: "BENCH-001", addBlockedBy: ["IMPL-001"] })REVIEW-001 (reviewer, Stage 4 - parallel):
TaskCreate({
subject: "REVIEW-001",
description: "PURPOSE: Review optimization code for correctness, side effects, and regression risks | Success: All dimensions reviewed, verdict issued
TASK:
- Load modified files and optimization plan
- Review across 5 dimensions: correctness, side effects, maintainability, regression risk, best practices
- Issue verdict: APPROVE, REVISE, or REJECT with actionable feedback
CONTEXT:
- Session: <session-folder>
- Scope: <optimization-scope>
- Branch: none
- Upstream artifacts: optimization-plan.md, benchmark-results.json (if available)
- Shared memory: <session>/.msg/meta.json
EXPECTED: <session>/artifacts/review-report.md | Per-dimension findings with severity
CONSTRAINTS: Focus on optimization changes only | Provide specific file:line references
---
InnerLoop: false",
status: "pending"
})
TaskUpdate({ taskId: "REVIEW-001", addBlockedBy: ["IMPL-001"] })---
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 STRATEGY-001 completes.
Create PROFILE-001 and STRATEGY-001 with same templates as single mode above.
Do NOT create IMPL/BENCH/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: "PROFILE-<P>01", ... })
TaskCreate({ subject: "STRATEGY-<P>01", ... })
TaskCreate({ subject: "IMPL-<P>01", ... })
TaskCreate({ subject: "BENCH-<P>01", ... })
TaskCreate({ subject: "REVIEW-<P>01", ... })
// Then set dependencies via TaskUpdate:
TaskUpdate({ taskId: "STRATEGY-<P>01", addBlockedBy: ["PROFILE-<P>01"] })
TaskUpdate({ taskId: "IMPL-<P>01", addBlockedBy: ["STRATEGY-<P>01"] })
TaskUpdate({ taskId: "BENCH-<P>01", addBlockedBy: ["IMPL-<P>01"] })
TaskUpdate({ taskId: "REVIEW-<P>01", addBlockedBy: ["IMPL-<P>01"] })Task descriptions follow same template as single mode, with additions:
Branch: <P>in CONTEXT- Artifact paths use
<session>/artifacts/pipelines/<P>/instead of<session>/artifacts/ - Shared-memory namespace uses
<role>.<P>(e.g.,profiler.A,optimizer.B) - Each pipeline's scope is its specific target from
independent_targets[i]
Example for pipeline A with target "optimize rendering":
TaskCreate({
subject: "PROFILE-A01",
description: "PURPOSE: Profile rendering performance | Success: Rendering bottlenecks identified
TASK:
- Detect project type and available profiling tools
- Execute profiling focused on rendering performance
- Collect baseline metrics and rank rendering bottlenecks
CONTEXT:
- Session: <session-folder>
- Scope: optimize rendering
- Pipeline: A
- Shared memory: <session>/.msg/meta.json (namespace: profiler.A)
EXPECTED: <session>/artifacts/pipelines/A/baseline-metrics.json + bottleneck-report.md
CONSTRAINTS: Focus on rendering scope
---
InnerLoop: false
PipelineId: A",
status: "pending"
})---
CP-2.5: Branch Creation Subroutine
Triggered by: monitor.md handleCallback when STRATEGY-001 completes in auto or fan-out mode.
Procedure:
1. Read <session>/artifacts/optimization-plan.md to count OPT-IDs 2. Read .msg/meta.json -> strategist.optimization_count 3. Auto mode decision:
| Optimization Count | Decision |
|---|---|
| count <= 2 | Switch to single mode -- create IMPL-001, BENCH-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_branchesifoptimization_count > max_branches(keep top N by priority) - For each optimization
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 OPT detail to branch
Write("<session>/artifacts/branches/B{NN}/optimization-detail.md",
extracted OPT-{NNN} block from optimization-plan.md)6. Create branch tasks for each branch B{NN}:
TaskCreate({
subject: "IMPL-B{NN}",
description: "PURPOSE: Implement optimization OPT-{NNN} | Success: Single optimization applied, compiles, tests pass
TASK:
- Load optimization detail from branches/B{NN}/optimization-detail.md
- Apply this single optimization to target files
- Validate changes compile and pass existing tests
CONTEXT:
- Session: <session-folder>
- Branch: B{NN}
- Upstream artifacts: branches/B{NN}/optimization-detail.md
- Shared memory: <session>/.msg/meta.json (namespace: optimizer.B{NN})
EXPECTED: Modified source files for OPT-{NNN} only
CONSTRAINTS: Only implement this branch's optimization | Do not touch files outside OPT-{NNN} scope
---
InnerLoop: false
BranchId: B{NN}",
status: "pending"
})
TaskUpdate({ taskId: "IMPL-B{NN}", addBlockedBy: ["STRATEGY-001"] })
TaskCreate({
subject: "BENCH-B{NN}",
description: "PURPOSE: Benchmark branch B{NN} optimization | Success: OPT-{NNN} metrics meet success criteria
TASK:
- Load baseline metrics and OPT-{NNN} success criteria
- Benchmark only metrics relevant to this optimization
- Compare against baseline, calculate improvement
CONTEXT:
- Session: <session-folder>
- Branch: B{NN}
- Upstream artifacts: baseline-metrics.json, branches/B{NN}/optimization-detail.md
- Shared memory: <session>/.msg/meta.json (namespace: benchmarker.B{NN})
EXPECTED: <session>/artifacts/branches/B{NN}/benchmark-results.json
CONSTRAINTS: Only benchmark this branch's metrics
---
InnerLoop: false
BranchId: B{NN}",
status: "pending"
})
TaskUpdate({ taskId: "BENCH-B{NN}", addBlockedBy: ["IMPL-B{NN}"] })
TaskCreate({
subject: "REVIEW-B{NN}",
description: "PURPOSE: Review branch B{NN} optimization code | Success: Code quality verified for OPT-{NNN}
TASK:
- Load modified files from optimizer.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}/optimization-detail.md
- Shared memory: <session>/.msg/meta.json (namespace: reviewer.B{NN})
EXPECTED: <session>/artifacts/branches/B{NN}/review-report.md
CONSTRAINTS: Only review this branch's changes
---
InnerLoop: false
BranchId: B{NN}",
status: "pending"
})
TaskUpdate({ taskId: "REVIEW-B{NN}", addBlockedBy: ["IMPL-B{NN}"] })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 addBlockedBy |
| 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 | IMPL-001 | BENCH-001, REVIEW-001 | FIX-001, FIX-002 |
| Fan-out | IMPL-B01 | BENCH-B01, REVIEW-B01 | FIX-B01-1, FIX-B01-2 |
| Independent | IMPL-A01 | BENCH-A01, REVIEW-A01 | FIX-A01-1, FIX-A01-2 |
If validation fails, fix the specific task and re-validate.
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 |
|---|---|
[optimizer-B01] or task ID IMPL-B01 | Branch B01 (fan-out) |
[profiler-A] or task ID PROFILE-A01 | Pipeline A (independent) |
[profiler] or task ID PROFILE-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 STRATEGY-001 AND
parallel_modeisautoorfan-out: - Execute CP-2.5 Branch Creation subroutine from dispatch.md
- After branch creation, proceed to handleSpawnNext (spawns all IMPL-B* in parallel)
- STOP after spawning
5. Check if checkpoint feedback is configured for this stage:
| Completed Task | Checkpoint | Action |
|---|---|---|
| PROFILE-001 / PROFILE-{P}01 | CP-1 | Notify user: bottleneck report ready for review |
| STRATEGY-001 / STRATEGY-{P}01 | CP-2 | Notify user: optimization plan ready for review |
| STRATEGY-001 (auto/fan-out) | CP-2.5 | Execute branch creation, then notify user with branch count |
| BENCH- 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:
Agent({
subagent_type: "team-worker",
description: "Spawn <role> worker for <task-id>",
team_name: "perf-opt",
name: "<role>",
run_in_background: true,
prompt: `## Role Assignment
role: <role>
role_spec: ~ or <project>/.claude/skills/team-perf-opt/roles/<role>/role.md
session: <session-folder>
session_id: <session-id>
team_name: perf-opt
requirement: <task-description>
inner_loop: <true|false>
## Progress Milestones
session_id: <session-id>
Report progress via team_msg at natural phase boundaries (context loaded -> core work done -> verification).
Report blockers immediately via team_msg type="blocker".
Report completion via team_msg type="task_complete" after final SendMessage.
Read role_spec file to load Phase 2-4 domain instructions.
Execute built-in Phase 1 -> role-spec Phase 2-4 -> built-in Phase 5.`
})3. Parallel spawn rules by mode:
| Mode | Scenario | Spawn Behavior |
|---|---|---|
| Single | Stage 4 ready | Spawn BENCH-001 + REVIEW-001 in parallel |
| Fan-out (CP-2.5 done) | All IMPL-B* unblocked | Spawn ALL IMPL-B* in parallel |
| Fan-out (IMPL-B{NN} done) | BENCH-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 BENCH-001 and REVIEW-001 are completed:
1. Read benchmark verdict from shared-memory (benchmarker namespace) 2. Read review verdict from shared-memory (reviewer namespace)
| Bench Verdict | Review Verdict | Action |
|---|---|---|
| PASS | APPROVE | -> handleComplete |
| PASS | REVISE | Create FIX task with review feedback |
| FAIL | APPROVE | Create FIX task with benchmark feedback |
| FAIL | REVISE/REJECT | Create FIX task with combined feedback |
| Any | REJECT | Create FIX task + flag for strategist re-evaluation |
Fan-out Mode (per-branch)
When both BENCH-B{NN} and REVIEW-B{NN} are completed for a specific branch:
1. Read benchmark verdict from benchmarker.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 BENCH-{P}01 and REVIEW-{P}01 are completed for a specific pipeline:
1. Read verdicts from benchmarker.{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:
// 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/benchmark | Success: All flagged issues resolved
TASK:
- Address review findings: <specific-findings>
- Fix benchmark regressions: <specific-regressions>
- Re-validate after fixes
CONTEXT:
- Session: <session-folder>
- Branch: B{NN}
- Upstream artifacts: branches/B{NN}/review-report.md, branches/B{NN}/benchmark-results.json
- Shared memory: <session>/.msg/meta.json (namespace: optimizer.B{NN})
EXPECTED: Fixed source files for B{NN} only
CONSTRAINTS: Targeted fixes only | Do not touch other branches
---
InnerLoop: false
BranchId: B{NN}",
status: "pending"
})Create new BENCH and REVIEW with retry suffix:
BENCH-B{NN}-R{cycle}blocked onFIX-B{NN}-{cycle}REVIEW-B{NN}-R{cycle}blocked onFIX-B{NN}-{cycle}
Independent mode:
TaskCreate({
subject: "FIX-{P}01-{cycle}",
...same pattern with pipeline prefix...
status: "pending"
})Create BENCH-{P}01-R{cycle} and REVIEW-{P}01-R{cycle}.
handleCheck
Output current pipeline status grouped by branch/pipeline.
Worker Progress (from message bus):
Before generating status output, read worker milestones:
const progressMsgs = mcp__ccw-tools__team_msg({
operation: "list", session_id: sessionId, type: "progress", last: 50
})
const blockerMsgs = mcp__ccw-tools__team_msg({
operation: "list", session_id: sessionId, type: "blocker", last: 10
})
// Aggregate latest milestone per task
const taskProgress = {}
for (const msg of (progressMsgs.result?.messages || [])) {
const tid = msg.data?.task_id
if (tid && (!taskProgress[tid] || msg.ts > taskProgress[tid].ts)) {
taskProgress[tid] = { phase: msg.data.phase, pct: msg.data.progress_pct, ts: msg.ts }
}
}Include in status output:
- Per-worker latest milestone (phase + progress_pct) next to task status
- Active blockers section (if any blockerMsgs found)
Single mode (unchanged):
Pipeline Status:
[DONE] PROFILE-001 (profiler) -> bottleneck-report.md
[DONE] STRATEGY-001 (strategist) -> optimization-plan.md
[RUN] IMPL-001 (optimizer) -> implementing...
[WAIT] BENCH-001 (benchmarker) -> blocked by IMPL-001
[WAIT] REVIEW-001 (reviewer) -> blocked by IMPL-001
Fix Cycles: 0/3
Session: <session-id>Fan-out mode:
Pipeline Status (fan-out, 3 branches):
Shared Stages:
[DONE] PROFILE-001 (profiler) -> bottleneck-report.md
[DONE] STRATEGY-001 (strategist) -> optimization-plan.md (4 OPT-IDs)
Branch B01 (OPT-001: <title>):
[RUN] IMPL-B01 (optimizer) -> implementing...
[WAIT] BENCH-B01 (benchmarker) -> blocked by IMPL-B01
[WAIT] REVIEW-B01 (reviewer) -> blocked by IMPL-B01
Fix Cycles: 0/3
Branch B02 (OPT-002: <title>):
[DONE] IMPL-B02 (optimizer) -> done
[RUN] BENCH-B02 (benchmarker) -> benchmarking...
[RUN] REVIEW-B02 (reviewer) -> reviewing...
Fix Cycles: 0/3
Branch B03 (OPT-003: <title>):
[FAIL] IMPL-B03 (optimizer) -> failed
Fix Cycles: 0/3 [BRANCH FAILED]
Session: <session-id>Independent mode:
Pipeline Status (independent, 2 pipelines):
Pipeline A (target: optimize rendering):
[DONE] PROFILE-A01 -> [DONE] STRATEGY-A01 -> [RUN] IMPL-A01 -> ...
Fix Cycles: 0/3
Pipeline B (target: optimize API):
[DONE] PROFILE-B01 -> [DONE] STRATEGY-B01 -> [DONE] IMPL-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 BENCH + REVIEW completed with PASS/APPROVE (or escalated), shared stages done |
| Independent | ALL pipelines have BENCH + REVIEW completed with PASS/APPROVE (or escalated) |
Aggregate results before transitioning to Phase 5:
1. For fan-out mode: collect per-branch benchmark results into <session>/artifacts/aggregate-results.json:
{
"branches": {
"B01": { "opt_id": "OPT-001", "bench_verdict": "PASS", "review_verdict": "APPROVE", "improvement": "..." },
"B02": { "opt_id": "OPT-002", "bench_verdict": "PASS", "review_verdict": "APPROVE", "improvement": "..." },
"B03": { "status": "failed", "reason": "IMPL 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. Skip addBlockedBy (no dependencies, 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
Coordinator - Performance Optimization Team
Role: coordinator Type: Orchestrator Team: perf-opt
Orchestrates the performance optimization pipeline: manages task chains, spawns team-worker agents, handles review-fix cycles, and drives the pipeline to completion.
Boundaries
MUST
- Use
team-workeragent type for all worker spawns (NOTgeneral-purpose) - Follow Command Execution Protocol for dispatch and monitor commands
- Respect pipeline stage dependencies (blockedBy)
- Stop after spawning workers -- wait for callbacks
- Handle review-fix cycles with max 3 iterations per branch
- Execute completion action in Phase 5
MUST NOT
- Implement domain logic (profiling, optimizing, reviewing) -- workers handle this
- Spawn workers without creating tasks first
- Skip checkpoints when configured
- Force-advance pipeline past failed review/benchmark
- Modify source code directly -- delegate to optimizer 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
---
Entry Router
When coordinator is invoked, detect invocation type:
| Detection | Condition | Handler |
|---|---|---|
| Worker callback | Message contains role tag [profiler], [strategist], [optimizer], [benchmarker], [reviewer] | -> handleCallback (monitor.md) |
| Branch callback | Message contains branch tag [optimizer-B01], [benchmarker-B02], etc. | -> handleCallback branch-aware (monitor.md) |
| Pipeline callback | Message contains pipeline tag [profiler-A], [optimizer-B], etc. | -> handleCallback pipeline-aware (monitor.md) |
| Consensus blocked | Message contains "consensus_blocked" | -> handleConsensus (monitor.md) |
| Status check | Arguments contain "check" or "status" | -> handleCheck (monitor.md) |
| Manual resume | Arguments contain "resume" or "continue" | -> handleResume (monitor.md) |
| Pipeline complete | All tasks have status "completed" | -> handleComplete (monitor.md) |
| Interrupted session | Active/paused session exists | -> Phase 0 |
| New session | None of above | -> Phase 1 |
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/PERF-OPT-*/.msg/meta.jsonfor active/paused sessions - If found, extract session folder path, status, and
parallel_mode
2. Parse $ARGUMENTS for detection keywords
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 (reset in_progress to pending, rebuild team) 4. 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: --parallel-mode (auto/single/fan-out/independent), --max-branches 3. Identify optimization target (specific file, full app, or multiple independent targets) 4. If target is unclear, AskUserQuestion for scope clarification 5. Record optimization requirement with scope, target metrics, parallel_mode, max_branches
---
Phase 2: Session & Team Setup
1. Resolve workspace paths (MUST do first):
project_root= result ofBash({ command: "pwd" })skill_root=<project_root>/.claude/skills/team-perf-opt
2. Create session directory with artifacts/, explorations/, wisdom/, discussions/ subdirs 3. Write session.json with extended fields (parallel_mode, max_branches, branches, fix_cycles) 4. Initialize meta.json with pipeline metadata via team_msg 5. Call TeamCreate({ team_name: "perf-opt" })
---
Phase 3: Create Task Chain
Execute @commands/dispatch.md inline (Command Execution Protocol).
---
Phase 4: Spawn & Coordination Loop
Initial Spawn
Find first unblocked task and spawn its worker using SKILL.md Worker Spawn Template with:
role_spec: <skill_root>/roles/<role>/role.mdteam_name: perf-opt
STOP after spawning. Wait for worker callback.
Coordination (via monitor.md handlers)
All subsequent coordination handled by @commands/monitor.md.
---
Phase 5: Report + Completion Action
1. Load session state -> count completed tasks, calculate duration 2. List deliverables (baseline-metrics.json, bottleneck-report.md, optimization-plan.md, benchmark-results.json, review-report.md) 3. Output pipeline summary with improvement metrics from benchmark results 4. Execute completion action per SKILL.md Completion Action section
---
Error Handling
| Scenario | Resolution |
|---|---|
| Teammate unresponsive | Send follow-up, 2x -> respawn |
| Profiling tool not available | Fallback to static analysis methods |
| Benchmark regression detected | Auto-create FIX task with regression details |
| Review-fix cycle exceeds 3 iterations | Escalate to user with summary of remaining issues |
| One branch IMPL fails | Mark that branch failed, other branches continue |
| max_branches exceeded | Truncate to top N optimizations by priority at CP-2.5 |
Code Optimizer
inner_loop: dynamic — Dispatch sets per-task:truefor single mode (one IMPL task with iterative fix cycles),falsefor fan-out/independent modes (IMPL-B01..N run as separate parallel workers). When false, each branch gets its own worker.
Implement optimization changes following the strategy plan. For FIX tasks, apply targeted corrections based on review/benchmark feedback.
Modes
| Mode | Task Prefix | Trigger | Focus |
|---|---|---|---|
| Implement | IMPL | Strategy plan ready | Apply optimizations per plan priority |
| Fix | FIX | Review/bench feedback | Targeted fixes for identified issues |
Phase 2: Plan & Context Loading
| Input | Source | Required |
|---|---|---|
| Optimization plan | <session>/artifacts/optimization-plan.md | Yes (IMPL, no branch) |
| Branch optimization detail | <session>/artifacts/branches/B{NN}/optimization-detail.md | Yes (IMPL with branch) |
| Pipeline optimization plan | <session>/artifacts/pipelines/{P}/optimization-plan.md | Yes (IMPL with pipeline) |
| Review/bench feedback | From task description | Yes (FIX) |
| .msg/meta.json | <session>/.msg/meta.json | Yes |
| Wisdom files | <session>/wisdom/patterns.md | No |
| Context accumulator | From prior IMPL/FIX tasks | Yes (inner loop) |
1. Extract session path and task mode (IMPL 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 optimization detail |
PipelineId: {P} | Present | Independent pipeline -- load pipeline-scoped plan |
| Neither present | - | Single mode -- load full optimization plan |
3. Load optimization context by mode:
- Single mode: Read
<session>/artifacts/optimization-plan.md - Fan-out branch: Read
<session>/artifacts/branches/B{NN}/optimization-detail.md - Independent pipeline: Read
<session>/artifacts/pipelines/{P}/optimization-plan.md
4. For FIX: parse review/benchmark feedback for specific issues to address 5. Use ACE search or CLI tools to load implementation context for target files 6. For inner loop (single mode only): load context_accumulator from prior IMPL/FIX tasks
Phase 3: Code Implementation
Implementation backend selection:
| Backend | Condition | Method |
|---|---|---|
| CLI | Multi-file optimization with clear plan | ccw cli --tool gemini --mode write |
| Direct | Single-file changes or targeted fixes | Inline Edit/Write tools |
For IMPL tasks:
- Single mode: Apply optimizations in plan priority order (P0 first, then P1, etc.)
- Fan-out branch: Apply ONLY this branch's single optimization
- Independent pipeline: Apply this pipeline's optimizations in priority order
- Follow implementation guidance from plan (target files, patterns)
- Preserve existing behavior -- optimization must not break functionality
For FIX tasks:
- Read specific issues from review/benchmark feedback
- Apply targeted corrections to flagged code locations
- Verify the fix addresses the exact concern raised
General rules:
- Make minimal, focused changes per optimization
- Add comments only where optimization logic is non-obvious
- Preserve existing code style and conventions
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 |
| Acceptance | Match optimization plan success criteria | All target metrics addressed |
| 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 IMPL/FIX task (single/inner-loop mode only):
- Files modified, optimizations 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}/
Performance Profiler
Profile application performance to identify CPU, memory, I/O, network, and rendering bottlenecks. Produce quantified baseline metrics and a ranked bottleneck 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>/.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 | Profiling Focus |
|---|---|---|
| package.json + React/Vue/Angular | Frontend | Render time, bundle size, FCP/LCP/CLS |
| package.json + Express/Fastify/NestJS | Backend Node | CPU hotspots, memory, DB queries |
| Cargo.toml / go.mod / pom.xml | Native/JVM Backend | CPU, memory, GC tuning |
| Mixed framework markers | Full-stack | Split into FE + BE profiling passes |
| CLI entry / bin/ directory | CLI Tool | Startup time, throughput, memory peak |
| No detection | Generic | All profiling dimensions |
3. Use ACE search or CLI tools to map performance-critical code paths within target scope 4. Detect available profiling tools (test runners, benchmark harnesses, linting tools)
Phase 3: Performance Profiling
Execute profiling based on detected project type:
Frontend profiling:
- Analyze bundle size and dependency weight via build output
- Identify render-blocking resources and heavy components
- Check for unnecessary re-renders, large DOM trees, unoptimized assets
Backend profiling:
- Trace hot code paths via execution analysis or instrumented runs
- Identify slow database queries, N+1 patterns, missing indexes
- Check memory allocation patterns and potential leaks
CLI / Library profiling:
- Measure startup time and critical path latency
- Profile throughput under representative workloads
- Identify memory peaks and allocation churn
All project types:
- Collect quantified baseline metrics (timing, memory, throughput)
- Rank top 3-5 bottlenecks by severity (Critical / High / Medium)
- Record evidence: file paths, line numbers, measured values
Tech Profile Scan
After profiling, scan findings for context-aware trigger signals (based on detected codebase characteristics):
1. Check profiling results → signals (perf_sensitive, scaling_concern, concurrency_issue) 2. Check code patterns found → risk signals (sql_detected, realtime_detected) 3. Include tech_profile in Phase 5 state_update data
Phase 4: Report Generation
1. Write baseline metrics to <session>/artifacts/baseline-metrics.json:
- Key metric names, measured values, units, measurement method
- Timestamp and environment details
2. Write bottleneck report to <session>/artifacts/bottleneck-report.md:
- Ranked list of bottlenecks with severity, location (file:line), measured impact
- Evidence summary per bottleneck
- Detected project type and profiling methods used
3. Update <session>/.msg/meta.json under profiler namespace:
- Read existing -> merge
{ "profiler": { project_type, bottleneck_count, top_bottleneck, scope } }-> write back
Optimization Reviewer
Review optimization code changes for correctness, side effects, regression risks, and adherence to best practices. Provide structured verdicts with actionable feedback.
Phase 2: Context Loading
| Input | Source | Required |
|---|---|---|
| Optimization code changes | From IMPL task artifacts / git diff | Yes |
| Optimization plan / detail | Varies by mode (see below) | Yes |
| Benchmark results | Varies by mode (see below) | No |
| .msg/meta.json | <session>/.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 optimization changes |
3. Load optimization context by mode:
- Single: Read
<session>/artifacts/optimization-plan.md - Fan-out branch: Read
<session>/artifacts/branches/B{NN}/optimization-detail.md - Independent: Read
<session>/artifacts/pipelines/{P}/optimization-plan.md
4. Load .msg/meta.json for scoped optimizer namespace 5. Identify changed files from optimizer context -- read ONLY files modified by this branch/pipeline 6. If benchmark results available, read from scoped path
Phase 3: Multi-Dimension Review
Analyze optimization changes across five dimensions:
| Dimension | Focus | Severity |
|---|---|---|
| Correctness | Logic errors, off-by-one, race conditions, null safety | Critical |
| Side effects | Unintended behavior changes, API contract breaks, data loss | Critical |
| Maintainability | Code clarity, complexity increase, naming, documentation | High |
| Regression risk | Impact on unrelated code paths, implicit dependencies | High |
| Best practices | Idiomatic patterns, framework conventions, optimization anti-patterns | 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
If any Critical findings detected, use CLI tools for multi-perspective validation (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 strategist escalation |
1. Write review report to scoped output path (single/fan-out/independent) 2. Update <session>/.msg/meta.json under scoped namespace 3. If DISCUSS-REVIEW was triggered, record discussion summary in discussions directory
Optimization Strategist
Analyze bottleneck reports and baseline metrics to design a prioritized optimization plan with concrete strategies, expected improvements, and risk assessments.
Phase 2: Analysis Loading
| Input | Source | Required |
|---|---|---|
| Bottleneck report | <session>/artifacts/bottleneck-report.md | Yes |
| Baseline metrics | <session>/artifacts/baseline-metrics.json | Yes |
| .msg/meta.json | <session>/.msg/meta.json | Yes |
| Wisdom files | <session>/wisdom/patterns.md | No |
1. Extract session path from task description 2. Read bottleneck report -- extract ranked bottleneck list with severities 3. Read baseline metrics -- extract current performance numbers 4. Load .msg/meta.json for profiler findings (project_type, scope) 5. Assess overall optimization complexity:
| Bottleneck 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 bottleneck, select optimization approach by type:
| Bottleneck Type | Strategies | Risk Level |
|---|---|---|
| CPU hotspot | Algorithm optimization, memoization, caching, worker threads | Medium |
| Memory leak/bloat | Pool reuse, lazy initialization, WeakRef, scope cleanup | High |
| I/O bound | Batching, async pipelines, streaming, connection pooling | Medium |
| Network latency | Request coalescing, compression, CDN, prefetching | Low |
| Rendering | Virtualization, memoization, CSS containment, code splitting | Medium |
| Database | Index optimization, query rewriting, caching layer, denormalization | High |
Prioritize optimizations by impact/effort ratio:
| Priority | Criteria |
|---|---|
| P0 (Critical) | High impact + Low effort -- quick wins |
| P1 (High) | High impact + Medium effort |
| P2 (Medium) | Medium impact + Low effort |
| P3 (Low) | Low impact or High effort -- defer |
If complexity is High, use CLI tools for multi-perspective analysis (DISCUSS-OPT round) to evaluate trade-offs between competing strategies before finalizing the plan.
Define measurable success criteria per optimization (target metric value or improvement %).
Phase 4: Plan Output
1. Write optimization plan to <session>/artifacts/optimization-plan.md:
Each optimization MUST have a unique OPT-ID and self-contained detail block:
### OPT-001: <title>
- Priority: P0
- Target bottleneck: <bottleneck from report>
- Target files: <file-list>
- Strategy: <selected approach>
- Expected improvement: <metric> by <X%>
- Risk level: <Low/Medium/High>
- Success criteria: <specific threshold to verify>
- Implementation guidance:
1. <step 1>
2. <step 2>
3. <step 3>
### OPT-002: <title>
...Requirements:
- Each OPT-ID is sequentially numbered (OPT-001, OPT-002, ...)
- Each optimization must be non-overlapping in target files
- Implementation guidance must be self-contained
2. Update <session>/.msg/meta.json under strategist namespace:
- Read existing -> merge -> write back with optimization metadata
3. If DISCUSS-OPT was triggered, record discussion summary in <session>/discussions/DISCUSS-OPT.md
Pipeline Definitions — Team Performance Optimization
Pipeline Modes
Single Mode (Linear with Review-Fix Cycle)
Stage 1 Stage 2 Stage 3 Stage 4
PROFILE-001 --> STRATEGY-001 --> IMPL-001 --> BENCH-001
[profiler] [strategist] [optimizer] [benchmarker]
^ |
+<--FIX-001---->+
| REVIEW-001
+<--------> [reviewer]
(max 3 iterations)Fan-out Mode (Shared stages 1-2, parallel branches 3-4)
Stage 1 Stage 2 CP-2.5 Stage 3+4 (per branch)
PROFILE-001 --> STRATEGY-001 --+-> IMPL-B01 --> BENCH-B01 + REVIEW-B01 (fix cycle)
+-> IMPL-B02 --> BENCH-B02 + REVIEW-B02 (fix cycle)
+-> IMPL-B0N --> BENCH-B0N + REVIEW-B0N (fix cycle)
|
AGGREGATE -> Phase 5Independent Mode (M fully independent pipelines)
Pipeline A: PROFILE-A01 --> STRATEGY-A01 --> IMPL-A01 --> BENCH-A01 + REVIEW-A01
Pipeline B: PROFILE-B01 --> STRATEGY-B01 --> IMPL-B01 --> BENCH-B01 + REVIEW-B01
|
AGGREGATE -> Phase 5Task Metadata Registry (Single Mode)
| Task ID | Role | Phase | Dependencies | Description |
|---|---|---|---|---|
| PROFILE-001 | profiler | Stage 1 | (none) | Profile application, identify bottlenecks |
| STRATEGY-001 | strategist | Stage 2 | PROFILE-001 | Design optimization plan from bottleneck report |
| IMPL-001 | optimizer | Stage 3 | STRATEGY-001 | Implement highest-priority optimizations |
| BENCH-001 | benchmarker | Stage 4 | IMPL-001 | Run benchmarks, compare vs baseline |
| REVIEW-001 | reviewer | Stage 4 | IMPL-001 | Review optimization code for correctness |
| FIX-001 | optimizer | Stage 3 (cycle) | REVIEW-001 or BENCH-001 | Fix issues found in review/benchmark |
Checkpoints
| Checkpoint | Trigger | Behavior |
|---|---|---|
| CP-1 | PROFILE-001 complete | User reviews bottleneck report, can refine scope |
| CP-2 | STRATEGY-001 complete | User reviews optimization plan, can adjust priorities |
| CP-2.5 | STRATEGY-001 complete (auto/fan-out) | Auto-create N branch tasks, spawn all IMPL-B* in parallel |
| CP-3 | REVIEW/BENCH fail | Auto-create FIX task for that branch only (max 3x per branch) |
| CP-4 | All tasks/branches complete | Aggregate results, interactive completion action |
Task Naming Rules
| Mode | Stage 3 | Stage 4 | Fix | Retry |
|---|---|---|---|---|
| Single | IMPL-001 | BENCH-001, REVIEW-001 | FIX-001 | BENCH-001-R1, REVIEW-001-R1 |
| Fan-out | IMPL-B01 | BENCH-B01, REVIEW-B01 | FIX-B01-1 | BENCH-B01-R1, REVIEW-B01-R1 |
| Independent | IMPL-A01 | BENCH-A01, REVIEW-A01 | FIX-A01-1 | BENCH-A01-R1, REVIEW-A01-R1 |
{
"version": "5.0.0",
"team_name": "perf-opt",
"team_display_name": "Performance Optimization",
"skill_name": "team-perf-opt",
"skill_path": "~ or <project>/.claude/skills/team-perf-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 performance 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": "profiler",
"type": "orchestration",
"description": "Profiles application performance, identifies CPU/memory/IO/network/rendering bottlenecks",
"role_spec": "roles/profiler/role.md",
"inner_loop": false,
"frontmatter": {
"prefix": "PROFILE",
"inner_loop": false,
"additional_prefixes": [],
"discuss_rounds": [],
"delegates_to": [],
"message_types": {
"success": "profile_complete",
"error": "error"
}
},
"weight": 1,
"tools": ["Read", "Bash", "Glob", "Grep", "Task", "mcp__ace-tool__search_context"]
},
{
"name": "strategist",
"type": "orchestration",
"description": "Analyzes bottleneck reports, designs prioritized optimization plans with concrete strategies",
"role_spec": "roles/strategist/role.md",
"inner_loop": false,
"frontmatter": {
"prefix": "STRATEGY",
"inner_loop": false,
"additional_prefixes": [],
"discuss_rounds": ["DISCUSS-OPT"],
"delegates_to": [],
"message_types": {
"success": "strategy_complete",
"error": "error"
}
},
"weight": 2,
"tools": ["Read", "Bash", "Glob", "Grep", "Task", "mcp__ace-tool__search_context"]
},
{
"name": "optimizer",
"type": "code_generation",
"description": "Implements optimization changes following the strategy plan",
"role_spec": "roles/optimizer/role.md",
"inner_loop": "dynamic",
"frontmatter": {
"prefix": "IMPL",
"inner_loop": "dynamic",
"additional_prefixes": ["FIX"],
"discuss_rounds": [],
"delegates_to": [],
"message_types": {
"success": "impl_complete",
"error": "error",
"fix": "fix_required"
}
},
"weight": 3,
"tools": ["Read", "Write", "Edit", "Bash", "Glob", "Grep", "Task", "mcp__ace-tool__search_context"]
},
{
"name": "benchmarker",
"type": "validation",
"description": "Runs benchmarks, compares before/after metrics, validates performance improvements",
"role_spec": "roles/benchmarker/role.md",
"inner_loop": false,
"frontmatter": {
"prefix": "BENCH",
"inner_loop": false,
"additional_prefixes": [],
"discuss_rounds": [],
"delegates_to": [],
"message_types": {
"success": "bench_complete",
"error": "error",
"fix": "fix_required"
}
},
"weight": 4,
"tools": ["Read", "Bash", "Glob", "Grep", "Task"]
},
{
"name": "reviewer",
"type": "read_only_analysis",
"description": "Reviews optimization code for correctness, side effects, and regression risks",
"role_spec": "roles/reviewer/role.md",
"inner_loop": false,
"frontmatter": {
"prefix": "REVIEW",
"inner_loop": false,
"additional_prefixes": ["QUALITY"],
"discuss_rounds": ["DISCUSS-REVIEW"],
"delegates_to": [],
"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": "optimization_count <= 2",
"fan-out": "optimization_count >= 3"
}
},
"pipeline": {
"stages": [
{
"stage": 1,
"name": "Performance Profiling",
"roles": ["profiler"],
"blockedBy": [],
"fast_advance": true
},
{
"stage": 2,
"name": "Optimization Strategy",
"roles": ["strategist"],
"blockedBy": ["PROFILE"],
"fast_advance": true
},
{
"stage": 3,
"name": "Code Optimization",
"roles": ["optimizer"],
"blockedBy": ["STRATEGY"],
"fast_advance": false
},
{
"stage": 4,
"name": "Benchmark & Review",
"roles": ["benchmarker", "reviewer"],
"blockedBy": ["IMPL"],
"fast_advance": false,
"parallel": true,
"review_fix_cycle": {
"trigger": "REVIEW or BENCH 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"
},
"shared_resources": [
{
"name": "Performance Baseline",
"path": "<session>/artifacts/baseline-metrics.json",
"usage": "Before-optimization metrics for comparison",
"scope": "shared (fan-out) / per-pipeline (independent)"
},
{
"name": "Bottleneck Report",
"path": "<session>/artifacts/bottleneck-report.md",
"usage": "Profiler output consumed by strategist",
"scope": "shared (fan-out) / per-pipeline (independent)"
},
{
"name": "Optimization Plan",
"path": "<session>/artifacts/optimization-plan.md",
"usage": "Strategist output consumed by optimizer",
"scope": "shared (fan-out) / per-pipeline (independent)"
},
{
"name": "Benchmark Results",
"path": "<session>/artifacts/benchmark-results.json",
"usage": "Benchmarker output consumed by reviewer",
"scope": "per-branch (fan-out) / per-pipeline (independent)"
}
],
"shared_memory_namespacing": {
"single": {
"profiler": "profiler",
"strategist": "strategist",
"optimizer": "optimizer",
"benchmarker": "benchmarker",
"reviewer": "reviewer"
},
"fan-out": {
"profiler": "profiler",
"strategist": "strategist",
"optimizer": "optimizer.B{NN}",
"benchmarker": "benchmarker.B{NN}",
"reviewer": "reviewer.B{NN}"
},
"independent": {
"profiler": "profiler.{P}",
"strategist": "strategist.{P}",
"optimizer": "optimizer.{P}",
"benchmarker": "benchmarker.{P}",
"reviewer": "reviewer.{P}"
}
}
}