---
description: Generate a k6 load test suite from a provided OpenAPI or Swagger specification
argument-hint: "<spec-path-or-url> [output-dir] [scope]"
---

Generate a complete, runnable k6 load test suite from the OpenAPI/Swagger specification at `$1`, guided by the k6 skills in this package. Default output directory is `${2:-tests/k6/}` and default scope is `${3:-all}` (all suitable operations, or a tag/path filter like `Users` or `/users`).

## Step 1 — Load the k6 skills

Before writing any code, use `read` to load the SKILL.md files (follow their reference files when relevant):

- **generating-tests-from-openapi** — primary; drives the whole workflow (spec parsing, auth mapping, request body generation).
- **designing-test-scenarios** — always; for executors, load profiles, and thresholds per endpoint type.
- **generating-api-load-tests** — always; for idiomatic HTTP script patterns (headers, params, checks, data handling).
- **analyzing-test-results** — always; to interpret the validation run.

Load these additional skills only when the condition applies:

- **operating-k6-in-ci-cd** — the user asks for a CI pipeline snippet alongside the tests.
- **testing-resilience** — the user asks for fault injection during the load tests.

## Step 2 — Load and validate the spec

- If `$1` is a URL, download it with `curl -sSL`; if it is a local file, read it directly.
- Support both **OpenAPI 3.x** (`openapi:` key, `servers`, `components.securitySchemes`) and **Swagger 2.0** (`swagger: '2.0'`, `basePath`/`host`, `securityDefinitions`) — normalize Swagger 2.0 structures to their OpenAPI 3 equivalents while parsing.
- Support both YAML and JSON. If the file fails to parse, stop and report the exact error instead of guessing.
- Note the API title, version, base URL (`servers[0].url` or `host + basePath`), and whether a base URL is missing (then require it via `__ENV.BASE_URL` and say so).

## Step 3 — Parse the spec per the skill

Follow the *generating-tests-from-openapi* skill workflow and extract:

- All paths and operations (method, `operationId`, `tags`, parameters, request bodies, response codes).
- **Security analysis (prerequisite)**: global `security`, per-operation overrides, and public endpoints (`security: []`); map schemes per the skill's auth-mapping reference (OAuth2 flows, API key, Bearer/Basic, OpenID Connect).
- Request body schemas, resolving `$ref`s to `components`/`definitions`, and building example values from the skill's schema→example table (prefer `example`/`default` values from the spec when present).

## Step 4 — Confirm the scope

- Apply `$3` (default `all`): filter to the requested tag or path prefix if given.
- By default **exclude**: deprecated operations, destructive operations (`DELETE`, and state-destroying `PUT`/`POST` like reset endpoints), and health/doc endpoints unless trivial — but list everything excluded and let the user re-include any.
- If the API has many tags, propose one script per tag under the output directory; otherwise a single script organized with `group()`s by tag (per the skill's Step 5 pattern).

## Step 5 — Design the load profile

Use the *designing-test-scenarios* skill:

- Pick executors and load levels per endpoint characteristic (per the OpenAPI skill's Step 6): read-heavy GETs get higher rates, writes get lower rates, admin endpoints are excluded or isolated.
- Set sensible default thresholds (e.g. `http_req_failed: ['rate<0.01']`, `http_req_duration: ['p(95)<500']`) and let the user override with their SLAs.
- Confirm the target environment: default `BASE_URL` from the spec's `servers`, but **warn and require explicit confirmation before running against any production URL**.

## Step 6 — Generate the test suite

Following the *generating-tests-from-openapi* script structure (and *generating-api-load-tests* patterns):

- All config via `__ENV` with defaults (`BASE_URL`, auth credentials, scenario tuning); never hardcode secrets.
- `setup()` implementing the required auth flow from the security analysis (token fetch, API key injection) — pass tokens to the default function via the setup data argument.
- `export const options` with the designed scenarios and thresholds.
- Default function with one `group()` per API tag; each operation tagged `{ name: '<operationId>' }` and wrapped in `check`s for the documented success status code (200/201/etc. from the spec).
- **Chain dependent operations** where the spec implies it (e.g. POST `/users` → use the created `id` in GET `/users/{id}` → DELETE it in cleanup), so writes are self-cleaning and don't pollute the target.
- Request bodies built from the schema example values; override placeholders like `test@example.com` are fine for load tests.
- Realistic `sleep(1)` think time between operations.
- If CI was requested, add the pipeline snippet per *operating-k6-in-ci-cd*; if resilience was requested, follow *testing-resilience* for the fault-injection wrapper.

## Step 7 — Validate and analyze

- Run `k6 inspect` on each generated script to confirm they parse and options export correctly.
- With the user's explicit permission (non-production target preferred), run a short smoke validation, e.g. `k6 run --iterations 2 <script>` per script or on one representative script.
- If a run was executed, apply the *analyzing-test-results* skill to interpret threshold pass/fail, percentiles, and error rates.
- Report results and suggested next steps (tuning VUs, per-endpoint scenarios, soak runs).

## Rules

- Only target APIs the user owns or has explicit authorization to load test; never run against production without explicit confirmation.
- Never echo, log, or persist credentials; read auth secrets exclusively from `__ENV`.
- Do not overwrite existing test files; pick new file names if targets exist.
- Do not invent endpoints or fields that are not in the spec; if something is ambiguous (missing base URL, circular `$ref`, unresolved schema), ask or state the assumption explicitly.
- Keep generated scripts idiomatic k6 (init context, options export, groups, checks, tags); no dead code.

After generating, summarize:
- The spec (title, version, OpenAPI/Swagger format), base URL, and number of operations covered vs. excluded.
- The auth scheme detected and how it was implemented in `setup()`.
- The scenarios/thresholds designed per endpoint type and why.
- Output file path(s), required env variables, and how to run them.
- Validation/analysis results from any executed run.
- Which k6 skills were loaded and how each shaped the result.
