| name | k6-validate | ||||
|---|---|---|---|---|---|
| description | Validate k6 scripts against structural, performance, and reliability standards. Use when users ask to validate a k6 script, review k6 test quality, or detect anti-patterns before execution. | ||||
| user-invocable | true | ||||
| disable-model-invocation | false | ||||
| license | MIT | ||||
| metadata |
|
- User says: "find issues in my k6 scenario"
- User says: "check if my thresholds and load profile are correct"
At the beginning of the workflow, detect and use interaction tools in this order:
- If
AskUserQuestionexists, use it for required inputs. - Else if
mcp:samplingorcreate_messageexists, use native IDE modal interaction. - Else if
confirm_actionexists, use it for critical confirmations. - Else emit the exact fallback and end the turn:
> [?] MISSING REQUIREMENT: Missing script path or validation scope
missing: script path, validation scope
why: deterministic validation report cannot run without target and scope
next_question: Which script should be validated?Do not continue validation after fallback.
When fallback is required, always use this portable payload shape:
> [?] MISSING REQUIREMENT: <short missing requirement summary>
missing: <comma-separated missing fields>
why: <why validation cannot continue deterministically>
next_question: <single, specific question that unblocks the next step>Do not emit final validation findings after this fallback.
- Report only findings supported by direct script evidence, explicit user context, or direct runtime/tool evidence.
- Do not state inferred conditions as facts in
Validation Summary. - If a required fact cannot be verified, mark it
unknownand include a single unblocker question inScope and Assumptions. - Keep language compact and action-oriented; avoid narrative repetition.
- If user language is explicit, answer in that language.
- If language is not explicit, default to English.
- Keep command names, k6 metric keys, and code identifiers in English.
When a target artifact declares cloud execution, validator must enforce version-safe behavior.
Required runtime classification for cloud checks:
- Parse or receive exact k6 version from context/handoff.
- Classify runtime family deterministically:
V0_53_TO_V1_5for>=0.53.0and<1.6.0V1_6_PLUS_V1_Xfor>=1.6.0and<2.0.0V2_0_PLUSfor>=2.0.0
Validation rules:
- Reject artifacts claiming v2 cloud behavior when runtime family is below
v2.0.0. - Verify cloud auth/routing variables when cloud mode is declared:
K6_CLOUD_TOKENK6_CLOUD_STACK_IDwhen stack routing is requiredK6_CLOUD_PROJECT_IDwhen project routing is required
- Flag hard-coded tokens as
ERROR. - Flag undocumented cloud options/flags as
ERROR. - Enforce cloud option allowlist parity with builder:
options.cloud.projectIDoptions.cloud.stackIDoptions.cloud.distributionoptions.cloud.deleteSensitiveDataoptions.cloud.staticIPsoptions.cloud.drop_metricsoptions.cloud.drop_tagsoptions.cloud.keep_tags
- Validate cloud distribution entries:
- every entry includes
loadZoneandpercent percentvalues are integers- total percent equals
100
- every entry includes
When validating cloud execution guidance or run procedures, enforce cost/idempotency guardrails:
- Flag
ERRORif output proposes more than one cloud execution without explicit user confirmation. - Flag
ERRORif output proposes rerun while an existing run URL is present withRunningstatus. - Flag
ERRORif output uses truncated terminal output as a reason to relaunch instead of checking the same run identity. - Require
Cloud Execution Safetyevidence:run_countfirst_run_urlrerun_requested_by_usercost_confirmation
- Flag
ERRORwhen rerun is requested by user butcost_confirmationis missing orno. - Flag
WARNINGwhen cloud mode is declared but run identity (run_url/run_id) is not traceable.
- Scenario type means the test objective shape (
load,stress,spike,soak,smoke) used to select executor intent. - Profile means the expected intensity preset (
minimal,standard,aggressive) used to evaluate whethervus,duration, and thresholds fit the intended load level. - Recommended profile in validation references is advisory mapping from scenario type to default intensity, not a replacement for explicit user-provided values.
- When both scenario type and profile are provided, validate executor fit against scenario type first and threshold/load intensity fit against profile second.
Apply deterministic recommendation:
- CI/headless:
K6_WEB_DASHBOARD=false - Local browser troubleshooting:
K6_WEB_DASHBOARD=true - Local non-browser: default
K6_WEB_DASHBOARD=falseunless explicit opt-in - Otherwise default
false
Audit this protocol whenever the input is an executable k6 artifact, a runnable plan, or a validation request that includes capacity claims. For pure cloud-run, missing local host capacity evidence must not by itself fail validation unless the artifact also claims local execution capacity.
Cross-skill required fields:
execution_contextmachine_profileprojected_loadcapacity_estimaterisk_statussafe_limit_recommendationscale_out_recommendation
High-risk gate audit expectation:
- If projected load exceeds
500VUs on the current host, validation must expect evidence that host audit was executed before generation (node skills/k6-validate/scripts/audit-host.js, orpython3 skills/k6-validate/scripts/audit-host.pywhen Node.js is unavailable). - Missing pre-generation audit evidence for
>500VU current-host scenarios is a validation failure for executable artifacts.
Contextual deterministic formulas (audit target):
vus_max = (logical_cpu * cpu_factor) + (free_ram_gb * ram_factor)arrival_rate_max = floor(vus_max / max(projected_load.expected_iteration_duration_seconds, 1))
Default context factors to validate:
local:cpu_factor=50,ram_factor=10ci:cpu_factor=30,ram_factor=6container:cpu_factor=25,ram_factor=5cloud:cpu_factor=60,ram_factor=12distributed: per-node estimate aggregated
Validation expectations:
execution_contextmust identify whether the run islocal,ci,container,cloud, ordistributed, and whether the active load generator is current-host or remote cloud-managed.machine_profilemust reflect current evidence when the current host generates load:logical_cpu,free_ram_gb,fd_limit,ephemeral_port_budget, environment type, and declared user restrictions.projected_loadmust reflect the actual executor shape being reviewed: target VUs, arrival rate, duration, stages, andexpected_iteration_duration_secondsfor arrival-rate executors.projected_load.expected_iteration_duration_secondsmust come from explicit user input, prior measured telemetry, or a conservative[assumption-based]estimate.- If that field is missing, validation must treat
arrival_rate_maxas non-deterministic and report the gap.
capacity_estimate.vus_maxandcapacity_estimate.arrival_rate_maxmust be tied to the currentmachine_profile, not to a universal fixed threshold.risk_statusmust be coherent with the numeric relationship betweenprojected_loadandcapacity_estimate.safe_limit_recommendationandscale_out_recommendationmust includeadditional_cpu_percent,additional_ram_gb, andadditional_nodeswhen risk is present.- For
projected_load.target_vus > 500on the current host, pre-generation host audit evidence must be present and consistent withmachine_profile. - For pure
cloud-run, remote cloud-worker capacity may remainunknown; local host capacity is advisory unless the artifact also includes local execution guidance.
Required formula checks:
- VU-driven:
additional_nodes = ceil(projected_load.target_vus / capacity_estimate.vus_max) - 1 - Rate-driven:
additional_nodes = ceil(projected_load.target_arrival_rate / capacity_estimate.arrival_rate_max) - 1 - Clamp
additional_nodesat0minimum.
Canonical alert requirement when risk exists:
LOAD GENERATOR CAPACITY ALERT
Risk Detected: The requested scenario ([X] VUs) exceeds the load generator operating limit ([Y] VUs).
Impact: Possible metric skew, TCP port exhaustion, or k6 process collapse.
Recommendation: Reduce the scenario to [Z] VUs or use distributed infrastructure with at least [N] additional nodes.Incomplete-data rules:
- If a field is missing, accept a conservative
[assumption-based]substitute only when the missing evidence is called out explicitly. - If executable output claims
SAFEwithout enough machine evidence, report that as a validation failure. - If executable output claims
AT_RISKorHIGH_RISKwith incomplete machine evidence, report that the risk assessment is unreliable until missing evidence is provided. - If runtime latency indicates overload (for example heavy tail growth, timeout spikes, or saturation signals), warn about potential coordinated omission even when pre-generation capacity evidence exists.
- For pure
cloud-run, do not fail validation solely because local machine evidence is absent; fail only when the artifact incorrectly presents local-capacity facts as verified or blocks remote execution on local limits.
-
Performance Best Practices:
- Sleep between iterations (avoid tight loops); if missing, report at least
WARNING - Checks implemented for assertions; if absent, report
WARNING - Timeouts set on requests
- Tagged requests for metric segmentation; if missing for multi-endpoint flows, report
WARNING - Profile/load-context clarity present (scenario type and expected profile intensity are inferable); if missing, report
WARNING - Capacity-assessment clarity present for executable or near-executable outputs; if missing, report at least
WARNING - Runtime-risk awareness present: when high latency tail or error bursts appear, include a coordinated-omission caution tied to runtime stress vs agent-time audit.
- Sleep between iterations (avoid tight loops); if missing, report at least
-
Protocol-Specific:
- HTTP: timeouts set, checks included
- gRPC: connections properly closed
- gRPC: flag
client.connect()outsidedefault function,setup(), orteardown()asWARNING(connection lifecycle leakage risk) - Browser: page/context closure in all execution paths (success, catch, finally, and early return paths)
- WebSocket: socket lifecycle hygiene (
on('open'),on('error'), graceful close path, and bounded session duration) - Browser: if page/context closure is missing in any iteration path, report
WARNING - Browser lifecycle path analysis is mandatory:
- Track each
newPage()/newContext()creation. - Evaluate all exits after creation (normal completion,
return,throw, catch branches). - If any path lacks corresponding
.close(), emitWARNINGwith path evidence. - Prefer
try/finallyremediation inSuggested Fixes.
- Track each
-
Anti-Patterns to Flag:
- Hard-coded credentials
- Hard-coded production URLs (for example
https://api.prod...) in runnable scripts without__ENVcontrol - Insecure hard-coded environment defaults/fallbacks in runnable scripts (without
__ENVfallback) - Unbounded loops
- Synchronous waits without reason
- Silent
catchblocks that swallow errors - Unsafe parsing without guarded failure handling
- Quality violations mapped to static-analysis concerns (including S7726-class findings)
- Anonymous default export function —
export default function() {}without a name is a quality violation. Flag asWARNING: "Default export function should be named for traceability and debuggability. Example:export default function runLoad() {}". The naming convention isrun<ScenarioType>orrun<Protocol><ScenarioType>.
When the artifact or upstream handoff is explicitly exploratory or provisional (plan_mode: exploratory, ready_for_builder: false, pending_clarifications, or pervasive [assumption-based] markers):
- Keep security, lifecycle hygiene, cloud compatibility, and cloud paid execution guardrails as hard gates.
- Treat missing confirmed thresholds, incomplete load-profile confirmation, or missing current-host capacity evidence as
WARNINGinstead ofERRORonly when the provisional state is explicit and the unresolved evidence is called out clearly. - Do not issue
PASSfor provisional artifacts; the highest allowed status isWARNuntil runnable blockers are resolved. - In
Scope and Assumptions, list the provisional markers exactly as they appear in the artifact or handoff. - In
Next Step, prioritize the first clarification required to convert the artifact into a final runnable candidate.
Always enforce these validations as mandatory checks:
- Thresholds are required
- Flag as error when thresholds are missing.
- If user provides explicit SLA values in the validation prompt/context, compare thresholds against that SLA.
- Flag as warning when thresholds exist but are more lax than stated SLA.
- For multi-environment artifacts with one declared SLA, threshold divergence across environments is
ERRORbecause it violates cross-env SLA coherence expected byk6-builder.
- Load profile is required
- Flag as error when no explicit load profile exists.
- Require explicit
vusanddurationfor time-based cases, or clear equivalent (stages,iterations+vus) for scenario-based definitions.
- Parameter coherence is required
- If arrival-rate parameters exist, validate
preAllocatedVUs <= maxVUs. - If staged scenarios exist, validate non-empty stages with explicit duration per stage.
- If arrival-rate parameters exist, validate
- Secrets and runnable safety are required
- Flag hard-coded credentials/tokens as error.
- Flag insecure runnable defaults for secrets as error or warning based on impact.
- Flag hard-coded production URLs without
__ENVcontrol as at leastWARNING(elevate toERRORwhen credentials or sensitive paths are coupled).
- Lifecycle hygiene is required
- Browser scripts must close
page/contextin all execution paths. - gRPC scripts must show connect/invoke/close lifecycle consistency.
- WebSocket scripts must include open/message/error/close handling and an explicit bounded lifetime.
- Browser scripts must close
- Dynamic capacity assessment is required for executable outputs
- Flag as error when
execution_context,machine_profile,projected_load, orcapacity_estimateis missing without explicit[assumption-based]justification for current-host execution artifacts. - Flag as error when
risk_statuscontradicts the numeric comparison between projected load and current capacity. - Flag as error when
AT_RISKorHIGH_RISKoutputs omit the canonical capacity alert. - Flag as error when
additional_nodesdoes not match the required formula for VU-driven or rate-driven execution. - Flag as warning when additional CPU or RAM guidance is omitted for
AT_RISKorHIGH_RISKoutputs. - For pure
cloud-run, treat remote capacity asunknownunless verified cloud-worker evidence exists; local capacity becomes advisory-only.
- Flag as error when
- Cloud compatibility is required for cloud artifacts
- Flag as error when cloud runtime family is unknown for cloud artifact claims.
- Flag as error when cloud options exceed the runtime-family allowlist.
- Flag as error when cloud distribution math is invalid.
- Flag as error when cloud mode is declared without explicit auth path (
K6_CLOUD_TOKENork6 cloud loginguidance).
- Cloud paid execution guardrail compliance is required when cloud runs are present
- Flag as error when multiple paid cloud runs are proposed without explicit user confirmation.
- Flag as error when rerun is proposed despite an existing running run URL.
- Flag as error when rerun is proposed for truncated output instead of same-run status recovery.
- Flag as error when
Cloud Execution Safetyevidence is missing for cloud run flows.
ERROR: mandatory invariant failures, hard safety/security violations, or incoherent capacity math.WARNING: quality/performance hygiene gaps that do not invalidate core correctness.INFO: optional non-blocking improvements.- Every finding row must carry exactly one severity label from
ERROR,WARNING, orINFO. - A report may contain one, two, or three severity levels depending on findings; do not force all three levels to appear.
Every validation response must include these sections in order:
Output artifact requirements:
- Use a single stable output artifact name:
validation-report.md. - Use Markdown as the required output format.
- Use exactly these H2 section headers in this order — no sections may be added, removed, reordered, or renamed:
## Validation Summary## Scope and Assumptions## Mandatory Invariant Results## Detailed Findings## Suggested Fixes## Next Step
## Validation Summarymust always begin with a status badge on its own line:**Status: PASS**,**Status: WARN**, or**Status: FAIL**.## Mandatory Invariant Resultsmust include a checklist item for each invariant fromRequired k6 Invariants, even if the result is ✅ pass.## Detailed Findingsmust group entries by severity in this order: 🔴 CRITICAL (ERROR) → 🟡 WARNING → ℹ️ INFO.- In each severity group, sort by impact first, then line order.
- Every reported finding must include exactly one valid severity label (
ERROR,WARNING, orINFO). - Do not require all three severity levels to appear in the same report.
- For dynamic-capacity audits with missing machine evidence in
AT_RISK/HIGH_RISKoutputs, include the termunreliableexplicitly in the relevant finding text. ## Suggested Fixesmust include a compact fix-priority matrix with counts and estimated time-to-fix per severity.
Output budget:
- Sections
Validation Summary+Mandatory Invariant Results+Detailed Findingscombined must target ≤ 600 tokens total. - Use a compact findings table with these columns:
#·Severity·Finding·Recommended Fix(one-liner max). - Keep
Validation Summaryto verified facts only; unresolved items must beunknown. - Extended explanations, code examples, and multi-step remediation instructions belong exclusively in
Suggested Fixes. Each fix should include:issue: The problem detectedseverity: ERROR, WARNING, or INFOevidence: Code snippet or line reference showing the issuefix_snippet: Executable corrected code (when applicable)estimated_time: short estimate (for example~5 min)
- Do not repeat finding descriptions between
Detailed FindingsandSuggested Fixes—Detailed Findingsidentifies;Suggested Fixesremediates. - Token budget rule: If combined findings exceed token budget, deprioritize INFO-level findings; ERROR and WARNING must always be reported.
- Compactness rule: If section content is already actionable, do not add explanatory filler.
For common anti-patterns, point to skills/k6-validate/references/remediation-playbooks.md and include the matching playbook name.
Findings table format:
| # | Severity | Finding | Recommended Fix |
|---|---|---|---|
| 1 | ERROR | Missing thresholds | Add thresholds block to options |
| 2 | WARNING | Anonymous default function | Rename to export default function runLoad() |
Under the table, include this compact template:
### 🔴 CRITICAL (Fix Immediately)
- <highest-impact findings only>
### 🟡 WARNING (Fix Soon)
- <quality/perf risks>
### ℹ️ INFO (Optional)
- <non-blocking improvements>In Suggested Fixes, append:
## Fix Priority Matrix
| Priority | Category | Count | Estimated Time |
|---|---|---:|---|
| 🔴 CRITICAL | Security/Safety/Correctness | <n> | <total> |
| 🟡 WARNING | Quality/Performance | <n> | <total> |
| ℹ️ INFO | Best Practice | <n> | <total> |Keep this file focused on validation workflow. Place deep guidance in:
skills/k6-validate/references/README.md
- Parse validation target (
script) and optional context (protocol,sla, scenario type, profile). - Run Tool Discovery Protocol if required input is missing.
- Validate syntax and structure.
- Validate performance best practices and protocol-specific rules.
- Enforce required threshold, load-profile, and lifecycle-hygiene invariants.
- Audit the Dynamic Capacity Protocol and verify formula coherence when current-host capacity claims are present or required, including mandatory pre-generation host-audit evidence for current-host projected loads above 500 VUs.
- Audit Cloud Compatibility Validation: version-family match, cloud allowlist, auth/routing completeness, blocking login readiness, and distribution math.
- Audit Cloud Paid Execution Compliance: single paid run policy, rerun confirmation, same-run recovery, and
Cloud Execution Safetytraceability. - If explicit SLA is present, compare script thresholds against the declared SLA and emit
WARNINGfor more lax thresholds. - For browser scripts, run path-based closure analysis for
page/contextresources and flag any non-closed path. - Run quality-hardening checks (silent catch, unsafe parse, static-analysis signals, hard-coded production URLs, missing checks/sleep/tags).
- Reference remediation playbooks for every fixable finding that matches a known anti-pattern.
- Return deterministic report in
validation-report.mdusing Markdown and the Output Contract section order.
For official skill evaluation runs in this repository:
- Store artifacts under
skills/k6-validate/k6-validate-workspace/iteration-N/. - Keep each run isolated inside its own
iteration-Ndirectory. - Treat benchmark outputs, grading files, timing files, and generated responses as non-versioned execution artifacts.