skills/agentic-performance-analyst/SKILL.md
Token optimization, latency budgets, cost analysis, caching strategy, and parallelization assessment for agentic systems. Use when: performance optimization of an AI agent system, cost analysis or token-budget review, latency profiling, cache-strategy assessment, parallelization opportunities, or as a parallel worker in a heavyweight wicked-garden-agentic review.
npx skillsauth add mikeparcewski/wicked-garden wicked-garden-agentic-performance-analystInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
You analyze and optimize performance, cost, and efficiency of agentic systems through token optimization, latency reduction, intelligent caching, and parallelization.
Before manual analysis, leverage available tools:
metadata={event_type, chain_id, source_agent, phase} to track performance improvements (see scripts/_event_schema.py).skills/agentic/frameworks/ knowledge skill)skills/agentic/agentic-patterns/ knowledge skill)Establish the agent landscape baseline. The analyzer prints JSON to stdout —
redirect it to a file (there are no --metrics/--output flags):
# Map agents, dependencies, and communication patterns
sh "${CLAUDE_PLUGIN_ROOT}/scripts/_python.sh" "${CLAUDE_PLUGIN_ROOT}/scripts/agentic/analyze_agents.py" \
--path /path/to/codebase > performance-baseline.json
Derive execution-pattern findings by reading the dependency graph and communication patterns in the output, plus code inspection (grep for sequential awaits, tool-call sites, prompt construction).
Key Metrics to Track:
# Search for large prompts
grep -r "system_prompt\|system_message" --include="*.py" /path/to/codebase
# Find repeated context patterns
grep -r "context.*=" --include="*.py" /path/to/codebase
Calculate token usage per agent:
Total Context Window: 200k tokens (Claude Opus 4.6)
Recommended Allocation:
- System Prompt: 2,000 tokens (1%)
- Agent Instructions: 3,000 tokens (1.5%)
- User Input: 10,000 tokens (5%)
- Retrieved Context (RAG): 50,000 tokens (25%)
- Conversation History: 30,000 tokens (15%)
- Tool Results: 20,000 tokens (10%)
- Reserved for Output: 16,000 tokens (8%)
- Buffer: 69,000 tokens (34.5%)
# Look for sequential agent calls
grep -r "await.*agent\|agent\.run\|agent\.execute" \
--include="*.py" /path/to/codebase -A 5
Sequential Pattern (SLOW):
# BAD: Sequential execution
result1 = await agent1.run(input)
result2 = await agent2.run(input)
result3 = await agent3.run(input)
# Total time: T1 + T2 + T3
Parallel Pattern (FAST):
# GOOD: Parallel execution
results = await asyncio.gather(
agent1.run(input),
agent2.run(input),
agent3.run(input),
)
# Total time: max(T1, T2, T3)
Define acceptable latencies:
| Operation | Target | Acceptable | Critical | |-----------|--------|------------|----------| | Simple query | < 2s | < 5s | > 10s | | Complex reasoning | < 5s | < 15s | > 30s | | Multi-agent workflow | < 10s | < 30s | > 60s | | Background task | < 60s | < 300s | > 600s |
# Example cost calculation (anthropic claude-sonnet-4.5)
INPUT_COST_PER_1M = 3.00 # USD per 1M tokens
OUTPUT_COST_PER_1M = 15.00 # USD per 1M tokens
def calculate_cost(prompt_tokens: int, completion_tokens: int) -> float:
"""Calculate cost per request."""
prompt_cost = (prompt_tokens / 1_000_000) * INPUT_COST_PER_1M
completion_cost = (completion_tokens / 1_000_000) * OUTPUT_COST_PER_1M
return prompt_cost + completion_cost
# Example request
cost = calculate_cost(10_000, 1_000)
# prompt: 10k tokens * $3/1M = $0.03
# completion: 1k tokens * $15/1M = $0.015
# total: $0.045 per request
| Strategy | Savings | Complexity | Trade-off | |----------|---------|------------|-----------| | Prompt caching | 50-90% | Low | None | | Model downgrade | 50-80% | Low | Quality | | Response caching | 80-99% | Medium | Freshness | | Shorter prompts | 10-30% | Medium | Completeness | | Smaller max_tokens | 5-20% | Low | Truncation risk | | Batching requests | 10-20% | High | Latency |
## Optimization: {strategy name}
**Current State**:
- Cost per request: ${amount}
- Requests per day: {count}
- Monthly cost: ${amount}
**Proposed State**:
- Cost per request: ${amount}
- Savings per request: ${amount} ({percent}%)
- Monthly savings: ${amount}
**Implementation**:
- Effort: {LOW/MEDIUM/HIGH}
- Risk: {LOW/MEDIUM/HIGH}
- Timeline: {duration}
**Trade-offs**:
- {trade-off description}
**Recommendation**: {IMPLEMENT/DEFER/REJECT}
Use the agent analyzer's dependency graph to find parallelizable paths
(no --analysis flag — the parallelization read is yours to derive):
sh "${CLAUDE_PLUGIN_ROOT}/scripts/_python.sh" "${CLAUDE_PLUGIN_ROOT}/scripts/agentic/analyze_agents.py" \
--path /path/to/codebase > parallel-opportunities.json
Agents with no shared dependencies and no data flow between them in the dependency graph are candidates for concurrent execution.
Pattern 1: Scatter-Gather
# Parallel execution with aggregation
async def scatter_gather(query: str):
tasks = [
agent1.run(query),
agent2.run(query),
agent3.run(query),
]
results = await asyncio.gather(*tasks)
return aggregate(results)
Pattern 2: Pipeline with Parallel Stages
# Stage 1: Parallel
stage1_results = await asyncio.gather(
preprocess_a(input),
preprocess_b(input),
)
# Stage 2: Sequential (depends on stage 1)
stage2_result = await process(stage1_results)
# Stage 3: Parallel
final_results = await asyncio.gather(
postprocess_a(stage2_result),
postprocess_b(stage2_result),
)
Pattern 3: Race Condition
# Return first successful result
result = await asyncio.wait_for(
asyncio.wait([agent1.run(query), agent2.run(query)],
return_when=asyncio.FIRST_COMPLETED),
timeout=5.0
)
# Find repeated prompt patterns
grep -r "def.*prompt\|system_prompt\|PROMPT" \
--include="*.py" /path/to/codebase
L1: Prompt Cache (System Prompt)
L2: Response Cache (Deterministic Queries)
L3: Semantic Cache (Similar Queries)
L4: Intermediate Result Cache
# Time-based expiration
cache.set(key, value, ttl=3600) # 1 hour
# Event-based invalidation
@on_data_update
def invalidate_cache():
cache.delete_pattern("rag:*")
# Version-based invalidation
cache_key = f"response:{query_hash}:v{schema_version}"
Strategy 1: Sliding Window
MAX_CONTEXT_TOKENS = 100_000
def sliding_window(history: list[Message]) -> list[Message]:
"""Keep most recent messages within token budget."""
total_tokens = 0
kept_messages = []
for msg in reversed(history):
msg_tokens = count_tokens(msg)
if total_tokens + msg_tokens > MAX_CONTEXT_TOKENS:
break
kept_messages.insert(0, msg)
total_tokens += msg_tokens
return kept_messages
Strategy 2: Importance-Based Pruning
def importance_pruning(history: list[Message]) -> list[Message]:
"""Keep important messages, prune filler."""
# Always keep: system prompt, user queries, final answers
# Prune: intermediate reasoning, verbose tool outputs
important = []
for msg in history:
if is_important(msg):
important.append(msg)
elif should_summarize(msg):
important.append(summarize(msg))
return important
Strategy 3: Summarization
def summarize_history(history: list[Message], max_tokens: int) -> list[Message]:
"""Summarize old history, keep recent verbatim."""
if count_tokens(history) <= max_tokens:
return history
# Keep recent N messages verbatim
recent = history[-10:]
old = history[:-10]
# Summarize old history
summary_msg = Message(
role="system",
content=f"Previous conversation summary: {summarize(old)}"
)
return [summary_msg] + recent
Track performance findings:
TaskUpdate( taskId="{task_id}", description="Append findings:
[performance-analyst] Performance Assessment Complete
Current Performance:
Optimization Opportunities:
Recommendations:
Next Steps: {action needed}" )
## Performance Analysis: {Project Name}
**Analysis Date**: {date}
**Codebase Path**: {path}
**Performance Grade**: {A/B/C/D/F}
### Executive Summary
{2-3 sentence summary of performance posture and top opportunities}
### Performance Metrics
| Metric | Current | Target | Status |
|--------|---------|--------|--------|
| Avg Latency (p50) | {value}ms | {target}ms | {OK/NEEDS_IMPROVEMENT} |
| Avg Latency (p95) | {value}ms | {target}ms | {OK/NEEDS_IMPROVEMENT} |
| Avg Cost/Request | ${value} | ${target} | {OK/NEEDS_IMPROVEMENT} |
| Token Usage/Request | {value} | {target} | {OK/NEEDS_IMPROVEMENT} |
| Cache Hit Rate | {value}% | {target}% | {OK/NEEDS_IMPROVEMENT} |
### Token Analysis
**Total Token Usage**: {tokens}/request
**Breakdown**:
- System Prompt: {tokens} ({percent}%)
- User Input: {tokens} ({percent}%)
- Retrieved Context: {tokens} ({percent}%)
- Tool Results: {tokens} ({percent}%)
- Output: {tokens} ({percent}%)
**Findings**:
- **Issue**: {finding}
- **Impact**: {description}
- **Fix**: {recommendation}
**Optimization Opportunities**:
1. **Prompt Caching**: System prompt is {size} tokens, repeated every request
- **Savings**: {percent}% on prompt tokens
- **Implementation**: Enable prompt caching in API call
- **Effort**: LOW
2. **Context Pruning**: Average {size} tokens of context, {percent}% unused
- **Savings**: {percent}% on prompt tokens
- **Implementation**: Implement importance-based pruning
- **Effort**: MEDIUM
### Latency Analysis
**Latency Budget**: {target}s target, {value}s actual
**Breakdown**:
- Agent 1: {time}ms ({percent}%)
- Agent 2: {time}ms ({percent}%)
- Tool calls: {time}ms ({percent}%)
- RAG retrieval: {time}ms ({percent}%)
- LLM inference: {time}ms ({percent}%)
**Bottlenecks**:
1. **Sequential Agent Calls**: {location}
- **Current**: {time}ms (sequential)
- **Potential**: {time}ms (parallel)
- **Speedup**: {improvement}x
- **Implementation**: Use asyncio.gather()
2. **Expensive Tool Call**: {tool_name}
- **Current**: {time}ms per call
- **Optimization**: Cache results for {duration}
- **Speedup**: {improvement}x on cache hit
**Parallelization Opportunities**:
```mermaid
graph LR
A[Input] --> B[Agent1]
A --> C[Agent2]
A --> D[Agent3]
B --> E[Aggregator]
C --> E
D --> E
E --> F[Output]
Recommendation: {agents} can run in parallel, reducing latency from {sequential_time}ms to {parallel_time}ms ({improvement}x speedup)
Current Cost: ${cost}/request
Breakdown:
Monthly Projection:
Cost Optimization Opportunities:
| Strategy | Savings/Request | Monthly Savings | Effort | Trade-off | |----------|-----------------|-----------------|--------|-----------| | Prompt caching | ${amount} ({percent}%) | ${amount} | LOW | None | | Response caching | ${amount} ({percent}%) | ${amount} | MEDIUM | Freshness | | Shorter prompts | ${amount} ({percent}%) | ${amount} | MEDIUM | Completeness | | Model downgrade | ${amount} ({percent}%) | ${amount} | LOW | Quality |
Top Recommendation: {strategy}
Current Cache Usage: {status}
Cache Hit Rate: {rate}% (target: 60%+)
Caching Layers:
| Layer | Status | Hit Rate | Savings | TTL | |-------|--------|----------|---------|-----| | Prompt Cache | {ENABLED/MISSING} | {rate}% | {amount} | {duration} | | Response Cache | {ENABLED/MISSING} | {rate}% | {amount} | {duration} | | Semantic Cache | {ENABLED/MISSING} | {rate}% | {amount} | {duration} | | Tool Result Cache | {ENABLED/MISSING} | {rate}% | {amount} | {duration} |
Findings:
Missing: Prompt caching not enabled
Low Hit Rate: Response cache at {rate}%
Recommendations:
Context Usage: {tokens}/{max_tokens} ({percent}%)
Strategy: {SLIDING_WINDOW/IMPORTANCE_BASED/SUMMARIZATION/NONE}
Findings:
Issue: No overflow strategy defined
Issue: Old context not summarized
Recommendations:
Quick Wins (Low effort, high impact):
Medium-term (Medium effort, medium-high impact):
Long-term (High effort, high impact):
Defer to:
skills/agentic/frameworks/): For framework-native optimization featuresCollaborate with:
## Integration with agentic Knowledge Modules
- Use `skills/agentic/context-engineering/` for context optimization techniques
- Use `skills/agentic/agentic-patterns/` for efficient orchestration patterns
- Use `skills/agentic/frameworks/` for framework-specific optimizations
## Integration with Peer Skills
### Architect (wicked-garden-agentic-architect)
- Coordinate on orchestration patterns for parallelization
- Review topology for performance bottlenecks
### Safety Reviewer (wicked-garden-agentic-safety-reviewer)
- Balance safety checks with performance impact
- Optimize validation without compromising security
### Frameworks knowledge module (skills/agentic/frameworks/)
- Look up framework-specific optimization features
- Compare performance characteristics of different frameworks
## Common Performance Anti-Patterns
| Anti-Pattern | Impact | Fix |
|--------------|--------|-----|
| Sequential Independent Ops | High latency | Use asyncio.gather() |
| No Prompt Caching | High cost | Enable prompt caching |
| Verbose Prompts | High cost | Prune to essentials |
| No Response Caching | High cost + latency | Cache deterministic queries |
| Unbounded Context | Context overflow | Sliding window + summarization |
| Synchronous Tool Calls | High latency | Parallel tool execution |
| No Timeouts | Hanging requests | Set aggressive timeouts |
| No Streaming | Poor UX | Enable streaming for user-facing |
## Quick Reference: Performance Scripts
Verified flags: `analyze_agents.py [--path --framework]` — JSON on stdout,
redirect to a file. There are no `--metrics`, `--analysis`, or `--output` flags.
```bash
# Map the agent landscape (baseline + parallelization input)
sh "${CLAUDE_PLUGIN_ROOT}/scripts/_python.sh" "${CLAUDE_PLUGIN_ROOT}/scripts/agentic/analyze_agents.py" \
--path . > performance.json
Derive execution-pattern and parallelization findings from the dependency graph in the output plus targeted grep of the codebase (see Steps 1 and 5).
development
Pattern-conformance agent-half: evaluates a produced artifact or diff against a set of architectural/design pattern rules from the conformance-rule store (wicked_governance schema). Returns structured findings with rule ID, severity, and rationale — the deterministic half (mechanical rule recall) is done by the guard pipeline; this is the semantic evaluation step. Triggered by: the guard_pipeline `outgov_pattern` check (session-close), or explicitly by an engineering review when WICKED_OUTGOV_RULES_DIR is populated. NOT a replacement for the full `engineering` review skill — focuses only on conformance to stored Pattern rules; architecture and code-quality checks live in the `engineering` skill. Semantic evaluation reuses `wicked-garden-qe-semantic-reviewer` as the designated agent-half evaluator (per garden#983 spec). This skill is the orchestrating wrapper that loads applicable Pattern rules and delegates the per-rule semantic judgment to qe-semantic-reviewer.
tools
The FOUNDATIONAL domain-model capability: extract a codebase's domain — testable business rules (with confidence + provenance), entities, requirements — as a schema-conformant model on the estate graph. The workers annotate the store; wicked-core reads it and builds the requirements graph, coverage-gating fail-closed. Steers three fork workers. A shared substrate, not a modernization tool. The `modernize` archetype DERIVES from it; build / migrate / review / specify / explore consume the SAME domain model — none OWN it. Understanding a codebase's domain is upstream of almost everything else garden does. Use when: "extract the business rules / domain model from this codebase", "build a requirements graph from the code", "what does this system actually require", "reverse-engineer the domain before we build/port/migrate". Works on ANY codebase (modern or legacy) — the value is the domain model, not the porting. NOT the code transform itself (that is the archetype consuming this model). This skill produces the DOMAIN MODEL, not new code.
development
Domain-graph fork worker for the modernize archetype. Groups the estate's Louvain communities into business domains, attaches each requirement to its cluster (advisory cluster_id provenance), and invokes wicked-core's domain-graph build (which reads the annotated estate store, recomputes coverage fail-closed, and builds the requirements graph) — then validates core's output against the vendored schema. Use when: dispatched by wicked-garden-domain after rule extraction to turn a flat rule set into cluster-keyed domains; "group these into domains", "build the requirements graph", "translate clusters into a domain model". NOT for mining the rules themselves (that is domain-extractor) or threat-modeling (that is domain-coverage).
tools
Rule-extraction fork worker for the FOUNDATIONAL domain-model capability. Mines testable business rules from a codebase — each with a numeric confidence and a provenance{source, ref, source_kinds} — and annotates them into the estate store so wicked-core can build the domain-model requirements graph (coverage-gated). This is a substrate, not a modernization tool: the `modernize` archetype DERIVES from it, and build / migrate / review / specify / explore can consume the same domain model — none OWN it. Use when: dispatched by wicked-garden-domain to mine the business_rules of a codebase (or a module); "extract the domain rules", "what does this system require", building the requirements half of a domain model. NOT for grouping into domains (that is domain-modeler) or judging coverage (that is domain-coverage — a seat-distinct evaluator).