---
phase: 20-book-load-testing
plan: 01
type: execute
wave: 1
depends_on: []
files_modified:
  - pmcp-book/src/ch14-performance.md
autonomous: true
requirements:
  - BKLT-01
  - BKLT-02
  - BKLT-03

must_haves:
  truths:
    - "Reader can invoke `cargo pmcp loadtest run` and `cargo pmcp loadtest init` with correct flags"
    - "Reader can write a TOML config with [settings], [[scenario]], and [[stage]] blocks"
    - "Reader understands flat load (constant VUs) vs staged load (ramp-up/hold/ramp-down)"
    - "Reader understands HdrHistogram percentiles (P50/P95/P99) and coordinated omission correction"
    - "Reader can identify server breaking points from error rate spikes and latency degradation"
    - "Reader can consume JSON reports in CI/CD pipelines with GitHub Actions"
  artifacts:
    - path: "pmcp-book/src/ch14-performance.md"
      provides: "Complete load testing chapter replacing stub"
      min_lines: 600
      contains: "cargo pmcp loadtest"
  key_links:
    - from: "pmcp-book/src/ch14-performance.md"
      to: "cargo-pmcp/src/loadtest/"
      via: "Documented CLI flags, config schema, and metric names match actual source code"
      pattern: "cargo pmcp loadtest (run|init)"
---

<objective>
Write the complete Chapter 14: Performance and Load Testing for pmcp-book, replacing the current stub.

Purpose: Readers need a comprehensive reference for the `cargo pmcp loadtest` tool covering CLI usage, TOML configuration, execution modes, metrics interpretation, breaking point detection, and CI/CD integration. This chapter is the primary load testing documentation for the PMCP SDK.

Output: `pmcp-book/src/ch14-performance.md` fully written with all sections.
</objective>

<execution_context>
@./.claude/get-shit-done/workflows/execute-plan.md
@./.claude/get-shit-done/templates/summary.md
</execution_context>

<context>
@.planning/PROJECT.md
@.planning/ROADMAP.md
@.planning/STATE.md

The existing chapter is a 12-line stub. The new chapter must be written from scratch by reading the loadtest source code.

Style reference: Read `pmcp-book/src/ch15-testing.md` to match the existing book's voice, structure, and formatting conventions (section headers, code blocks, admonitions, tips, ASCII diagrams).

Source code to extract documentation from (READ THESE during execution):
- `cargo-pmcp/src/commands/loadtest/mod.rs` — CLI flag definitions (clap Subcommand enum)
- `cargo-pmcp/src/commands/loadtest/run.rs` — Run command implementation, config discovery, CLI overrides
- `cargo-pmcp/src/commands/loadtest/init.rs` — Init command, schema discovery, template generation
- `cargo-pmcp/src/loadtest/config.rs` — Full TOML config schema: Settings, ScenarioStep, Stage structs
- `cargo-pmcp/src/loadtest/engine.rs` — Engine orchestration, flat vs staged execution, VU spawning
- `cargo-pmcp/src/loadtest/metrics.rs` — HdrHistogram, coordinated omission, OperationType enum
- `cargo-pmcp/src/loadtest/breaking.rs` — Breaking point detector: rolling window, thresholds, detection conditions
- `cargo-pmcp/src/loadtest/report.rs` — JSON report schema: LoadTestReport, ReportMetrics, BreakingPointReport
- `cargo-pmcp/src/loadtest/summary.rs` — k6-style terminal output format, metric names
- `cargo-pmcp/src/loadtest/display.rs` — Live terminal display format
- `cargo-pmcp/src/loadtest/vu.rs` — Virtual user loop, per-VU sessions, backoff
- `cargo-pmcp/src/loadtest/error.rs` — Error classification types
</context>

<tasks>

<task type="auto">
  <name>Task 1: Write Ch 14 core sections — CLI, Configuration, and Execution Modes</name>
  <files>pmcp-book/src/ch14-performance.md</files>
  <action>
Read the following source files to extract accurate details:
- `cargo-pmcp/src/commands/loadtest/mod.rs` for CLI flags and subcommand structure
- `cargo-pmcp/src/commands/loadtest/run.rs` for config discovery logic and CLI overrides
- `cargo-pmcp/src/commands/loadtest/init.rs` for init command and schema discovery
- `cargo-pmcp/src/loadtest/config.rs` for full TOML config schema (Settings, ScenarioStep, Stage)
- `cargo-pmcp/src/loadtest/engine.rs` for flat vs staged execution modes
- `cargo-pmcp/src/loadtest/vu.rs` for VU management details
- `cargo-pmcp/src/loadtest/display.rs` for live terminal display format

Also read `pmcp-book/src/ch15-testing.md` (first ~100 lines) for style reference.

Write `pmcp-book/src/ch14-performance.md` with these sections:

**1. Chapter Introduction** (## Introduction)
- Why load testing matters for MCP servers (many servers, few clients — same framing as Ch 15)
- What `cargo pmcp loadtest` provides: k6-inspired engine purpose-built for MCP
- Overview of what the chapter covers

**2. Quick Start** (## Quick Start)
- Minimal 3-step workflow: `loadtest init` -> edit config -> `loadtest run`
- Show a complete working example end-to-end in < 30 lines of terminal + TOML
- Include expected terminal output showing the k6-style live display format

**3. CLI Reference** (## CLI Reference)
- `cargo pmcp loadtest run <URL>` with ALL flags from the clap enum:
  - `--config <PATH>` (default: auto-discover .pmcp/loadtest.toml)
  - `--vus <N>` (overrides config)
  - `--duration <SECS>` (overrides config)
  - `--iterations <N>` (overrides config, first-limit-wins with duration)
  - `--no-report` (disable JSON output)
  - `--no-color` (disable colored terminal output)
- `cargo pmcp loadtest init [URL]` with flags:
  - `--force` (overwrite existing config)
  - Optional URL for server schema discovery (connects to discover tools/resources/prompts)
- Show example commands for common use cases

**4. Configuration Reference** (## Configuration Reference)
- Full TOML schema documentation with `[settings]` block:
  - `virtual_users` — concurrent VU count
  - `duration_secs` — test duration
  - `timeout_ms` — per-request timeout
  - `expected_interval_ms` — coordinated omission correction interval (default: 100ms)
- `[[scenario]]` blocks with all three MCP operation types:
  - `type = "tools/call"` with `weight`, `tool`, `arguments` fields
  - `type = "resources/read"` with `weight`, `uri` fields
  - `type = "prompts/get"` with `weight`, `prompt`, `arguments` fields
- Weight-based proportional scheduling explanation (e.g., 60/30/10 = 60% tools, 30% resources, 10% prompts)
- Complete annotated example config with mixed operations

**5. Execution Modes** (## Execution Modes)
- **Flat Load** (### Flat Load): All VUs start immediately, constant load for `duration_secs`
  - Config example (no `[[stage]]` blocks)
  - When to use: baseline performance, soak testing, simple scenarios
- **Staged Load** (### Staged Load): Multi-phase profiles with `[[stage]]` blocks
  - `target_vus` and `duration_secs` per stage, linear ramp between stages
  - When stages are present, `settings.virtual_users` is ignored (warn behavior)
  - Config example showing ramp-up -> hold -> ramp-down pattern
  - When to use: capacity planning, breaking point detection, realistic traffic patterns
- ASCII diagram showing VU count over time for a staged profile (similar to k6 docs)

**6. Schema Discovery with `loadtest init`** (## Schema Discovery)
- How `loadtest init <URL>` connects to a running server
- Discovers available tools, resources, and prompts via MCP protocol
- Generates a populated TOML config with real tool names from the server
- Fallback: generates default template if server is unreachable
- Show before/after: default template vs discovered template

Write the file with these sections. Leave a clear `<!-- CONTINUED IN TASK 2 -->` comment at the end. The file should be well-structured mdBook-compatible markdown.

IMPORTANT: Extract ALL details from source code — do not guess CLI flags, config field names, or behavior. Every flag, field, and behavior documented must match the actual Rust source.
  </action>
  <verify>
    <automated>grep -c "## " pmcp-book/src/ch14-performance.md | xargs test 5 -le</automated>
    Verify the file has at least 5 major sections (## headers), contains "cargo pmcp loadtest run", "cargo pmcp loadtest init", "[settings]", "[[scenario]]", "[[stage]]", "tools/call", "resources/read", "prompts/get".
    Run: grep -E "(cargo pmcp loadtest|\\[settings\\]|\\[\\[scenario\\]\\]|\\[\\[stage\\]\\]|tools/call|resources/read|prompts/get)" pmcp-book/src/ch14-performance.md | wc -l
    Should return 10+.
  </verify>
  <done>
    Ch 14 contains complete documentation for CLI usage (all flags from source), TOML configuration (all fields from config.rs), flat and staged execution modes, and schema discovery. All details extracted from actual source code, not invented.
  </done>
</task>

<task type="auto">
  <name>Task 2: Write Ch 14 metrics, breaking point, and CI/CD sections</name>
  <files>pmcp-book/src/ch14-performance.md</files>
  <action>
Read the following source files to extract accurate details:
- `cargo-pmcp/src/loadtest/metrics.rs` for HdrHistogram usage, coordinated omission, OperationType enum, MetricsSnapshot fields
- `cargo-pmcp/src/loadtest/breaking.rs` for breaking point detection: rolling window algorithm, thresholds (ERROR_RATE_ABSOLUTE_THRESHOLD=0.10, ERROR_RATE_RELATIVE_MULTIPLIER=2.0, P99_RELATIVE_MULTIPLIER=3.0), detection conditions, self-calibrating baseline
- `cargo-pmcp/src/loadtest/report.rs` for JSON report schema: LoadTestReport fields (schema_version, timestamp, target_url, duration_secs, config, metrics, errors, per_tool, breaking_point), ReportMetrics, LatencyMetrics, ToolReportMetrics, BreakingPointReport
- `cargo-pmcp/src/loadtest/summary.rs` for k6-style output format and metric names (mcp_req_duration, mcp_req_success_count, etc.)
- `cargo-pmcp/src/loadtest/error.rs` for error classification types

Remove the `<!-- CONTINUED IN TASK 2 -->` comment from the file and append these sections:

**7. Understanding Metrics** (## Understanding Metrics)
- **HdrHistogram** (### HdrHistogram): What it is, why it's better than averages for latency
  - Percentile breakdown: P50 (median, typical), P95 (tail), P99 (worst-case for most users)
  - Millisecond resolution
  - Separate success and error histograms (error spikes don't pollute success percentiles)
- **Coordinated Omission Correction** (### Coordinated Omission Correction):
  - What coordinated omission is (measurement bias when stalled system stops measuring)
  - How `record_correct()` fixes it (fills synthetic samples for missed intervals)
  - `expected_interval_ms` config field (default 100ms) — what to set it to
  - Why this matters: without correction, P99 during stalls is UNDERREPORTED
- **Terminal Output** (### Terminal Output):
  - k6-style summary format showing all metric names: mcp_req_duration, mcp_req_success_count, mcp_req_error_count, mcp_req_error_rate, mcp_req_throughput, mcp_req_total, mcp_req_elapsed
  - Include the ASCII art header format from summary.rs
  - Error classification breakdown section
  - Per-operation type tracking (tools/call, resources/read, prompts/get, initialize)

**8. Breaking Point Detection** (## Breaking Point Detection)
- Self-calibrating rolling window approach (no hardcoded absolute thresholds)
  - Window splits in half: recent vs baseline
  - Default window size: 10 samples at 2-second intervals = 20 seconds of history
- Detection triggers when EITHER condition is met:
  1. Error rate spike: recent error rate > 10% absolute AND > 2x baseline rate
  2. Latency degradation: recent P99 > 3x baseline P99
- Report-and-continue semantics (detection fires once, test continues)
- How to use with staged load for capacity planning
  - Example: ramp from 10 to 100 VUs, observe where breaking point fires
- Show example terminal warning and JSON report breaking_point section

**9. JSON Reports** (## JSON Reports)
- Report location: `.pmcp/reports/` directory
- Schema version field (currently "1.1") for parser compatibility
- Full JSON structure with annotated example showing:
  - `schema_version`, `timestamp`, `target_url`, `duration_secs`
  - `config` block (resolved config with CLI overrides)
  - `metrics` block: total_requests, success_count, error_count, error_rate, throughput_rps, latency (p50/p95/p99 for both success and error), operation_counts, operation_errors
  - `per_tool` block: per-tool latency (p50/p95/p99/min/max/mean), per-tool errors
  - `breaking_point` block: detected, vus, reason, detail, timestamp
  - `errors` block: counts by classification type
- `--no-report` flag to disable

**10. CI/CD Integration** (## CI/CD Integration)
- Using JSON reports for automated quality gates
- Example: parse report with `jq` to extract P99 and error rate
- Example: fail CI if P99 > threshold or error rate > threshold
- Complete GitHub Actions workflow example:
  1. Build MCP server
  2. Start server in background
  3. Run `cargo pmcp loadtest init <URL>` for schema discovery
  4. Run `cargo pmcp loadtest run <URL>` with appropriate flags
  5. Parse JSON report for pass/fail
  6. Upload report as artifact
  7. Stop server
- Tips: use `--no-color` in CI, use `--no-report` if only checking exit code

**11. Best Practices** (## Best Practices)
- Start with `loadtest init` for schema discovery
- Use flat load for baselines, staged for capacity planning
- Set `expected_interval_ms` to match your server's expected response time
- Test in an environment similar to production
- Use breaking point detection with staged ramp-up to find limits
- Store configs in version control alongside server code
- Include load tests in CI to prevent performance regressions

**12. Summary** (## Summary)
- Key takeaways (bulleted list matching Ch 15's style)
- Next steps pointing to Ch 15 for functional testing

IMPORTANT: Extract ALL metric names, field names, threshold values, and report schema fields from actual source code. The JSON report example must match the `LoadTestReport` struct in report.rs exactly.
  </action>
  <verify>
    <automated>wc -l pmcp-book/src/ch14-performance.md | awk '{if ($1 >= 600) print "PASS: "$1" lines"; else print "FAIL: only "$1" lines, need 600+"; exit ($1 < 600)}'</automated>
    Also verify key content:
    Run: grep -cE "(HdrHistogram|coordinated omission|breaking.point|schema_version|GitHub Actions|mcp_req_)" pmcp-book/src/ch14-performance.md
    Should return 10+ matches confirming all major topics are covered.
  </verify>
  <done>
    Ch 14 is complete with metrics explanation (HdrHistogram, coordinated omission, percentiles), breaking point detection (rolling window, thresholds, self-calibrating), JSON report schema (all fields from report.rs), CI/CD integration (GitHub Actions workflow), and best practices. All values match source code.
  </done>
</task>

</tasks>

<verification>
1. `pmcp-book/src/ch14-performance.md` exists and is > 600 lines
2. Chapter covers all BKLT requirements:
   - BKLT-01: CLI, TOML config, scenarios, flat + staged modes
   - BKLT-02: HdrHistogram, breaking point, coordinated omission, interpretation
   - BKLT-03: CI/CD integration, JSON reports, GitHub Actions
3. All CLI flags match `cargo-pmcp/src/commands/loadtest/mod.rs`
4. All config fields match `cargo-pmcp/src/loadtest/config.rs`
5. All metric names match `cargo-pmcp/src/loadtest/summary.rs`
6. JSON report schema matches `cargo-pmcp/src/loadtest/report.rs`
7. Breaking point thresholds match `cargo-pmcp/src/loadtest/breaking.rs`
8. `mdbook build pmcp-book` succeeds (no broken links or syntax errors)
</verification>

<success_criteria>
- Ch 14 is a comprehensive, production-quality chapter that a reader can use as the sole reference for `cargo pmcp loadtest`
- Every CLI flag, config option, metric name, and report field is accurate to the source code
- Code examples are complete and copy-pasteable
- Writing style matches Ch 15 (section headers, code blocks, tips, ASCII diagrams)
</success_criteria>

<output>
After completion, create `.planning/phases/20-book-load-testing/20-01-SUMMARY.md`
</output>
