| name | k6-builder | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| description | Build runnable k6 artifacts from a plan or direct requirements. Use when users ask to generate k6 scripts, choose/apply executors in runnable options, or create single/multi-environment configs. Prefer this skill for any implementation output request, even if the user also mentions "executor" or "config". | ||||||||||
| user-invocable | true | ||||||||||
| disable-model-invocation | false | ||||||||||
| license | MIT | ||||||||||
| metadata |
|
- User says: "generate runnable k6 script for this endpoint"
- User says: "build dev/staging/prod config with thresholds"
- User says: "which executor should I use and give me final options"
Generate runnable k6 artifacts safely and deterministically:
- script code
- scenario/options configuration
- single and multi-environment setup
Do not switch to planning-only discussion when user asked for implementation output.
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 build input for runnable artifacts
missing: target, scenario type, SLA requirements, protocol
why: deterministic generation cannot proceed safely without minimum build inputs
next_question: What target URL or endpoint should this build use?Do not continue generation 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 generation cannot continue deterministically>
next_question: <single, specific question that unblocks the next step>Do not emit final artifact content after this fallback.
1. **Adaptive Question System**: When critical parameters are missing, start with baseline planning questions and continue in the same question flow with any additional required questions: - What is the target URL/endpoint? (if `target` missing) - What scenario type do you need? Options: load, stress, spike, soak, smoke (if `scenario` missing) - What are your SLA requirements? Example: p95<500ms,error<1% (if `sla` missing) - What protocol should this test use? Options: http, grpc, browser (if `protocol` missing)Round contract:
- Round 1: one consolidated baseline question block with all minimum required questions.
- Round 2: one optional tie-break block only when a critical ambiguity remains after Round 1.
- If required inputs are still unresolved after Round 2, emit the interoperability fallback and end the turn.
Partial template override for multi-environment requests:
- If
targetorprotocolis missing but the request clearly specifies multiple environments and a scenario, generate a partial script template with__ENVplaceholders for all missing values. - Mark each assumption with
[assumption-based]in apending_questionsblock appended at the end of the artifact. - The partial template must still satisfy all other invariants (named function, thresholds, load profile via defaults).
Partial template override for auth-only edge cases:
- If the user explicitly asks for an auth pattern/template and the scenario/protocol is clear but
targetis missing, generate an auth-focused partial template. - Use
__ENV.BASE_URL(or protocol-equivalent env var) placeholder and mark all unresolved values as[assumption-based]. - Append a
pending_questionsblock with one direct question for the unresolved target.
Upstream exploratory handoff policy:
- If input from
k6-planincludesplan_mode: exploratory,ready_for_builder: false,inferred_targets,inferred_flows, orpending_clarifications, do not treat that input as executable-ready. - Preserve every
inferredor[assumption-based]field in the builder output and carry unresolved items into apending_questionsblock. - Generate a partial template only when the user explicitly wants to continue from the exploratory plan; otherwise ask for the highest-priority runnable blocker.
- Never upgrade inferred routes, auth requirements, or SLA values into confirmed build inputs without explicit confirmation.
Additional questions must be integrated into the same question system, not handled as a separate side flow:
- Add an HTTP method question when
protocol=httpand the method cannot be inferred safely. - Add one or more authentication questions when auth is required or unknown and executable output depends on it.
- Add more questions only inside Round 1 or the single Round 2 tie-break block when other critical ambiguities or missing requirements are detected.
- Do not finalize artifact generation until all required questions from this same system are resolved.
-
Load Profile Defaults (when
profileis not specified):minimal: 5 VUs, 1m duration, smoke testingstandard: 25 VUs, 9m duration, realistic loadaggressive: 120 VUs, 14m duration, stress testing
-
Output Format: Primary output is runnable artifacts with:
- Recommended executor type
- VU count and stages/options
- Duration estimate
- SLA-derived thresholds
- Protocol-specific implementation notes
- Data integration suggestions (CSV/JSON)
- Exactly one deterministic
Next recommended step
-
Determinism: Same inputs produce identical outputs every time.
-
Compact-by-default responses:
- Keep generation responses concise and directly actionable.
- Do not emit long narrative sections when short verified bullets and runnable commands are enough.
- Default to compact output unless the user explicitly asks for a detailed report.
Apply this policy in every builder response:
- Report only data that is verifiably known from user input or direct tool/runtime evidence in the current task.
- Do not present inferred values as facts in the final output.
- If a value is required but not verified, mark it as
unknownand ask a single unblocker question. - If upstream planning metadata is exploratory, preserve its uncertainty markers and keep
ready_for_builder: falsesemantics intact. - Do not fabricate machine/runtime numbers in summaries.
- Scenario type means the test objective shape (
load,stress,spike,soak,smoke). - Profile means default intensity presets (
minimal,standard,aggressive) used when explicitvus/durationare missing. - Round means one consolidated question block in the adaptive question system; baseline questions are Round 1 and the optional tie-break is Round 2.
- Scenario type selects the executor strategy; profile sets default intensity values.
Before producing final HTTP artifacts, add the method question to the same active question system:
- Confirm primary method (
GET,POST,PUT,PATCH,DELETE) when endpoint behavior depends on method. - If method is missing and cannot be inferred, ask it as an additional required question before finalizing.
- Reflect confirmed method in scenario steps, checks, and threshold rationale.
Before finalizing artifact output, add auth questions to the same active question system:
- Detect whether authentication is required (Bearer token, API key, basic auth, mTLS, session cookie, or none).
- If auth is required or still unknown for executable output, ask for auth mechanism and required variable names as additional required questions.
- Never hard-code credentials in examples or generated scripts.
- Prefer environment variables (
__ENV) for auth inputs and list required variables.
If invoked without prior plan, the same Adaptive Question System above still applies.
Then:
- Build a minimal internal plan
- Expose assumptions
- Generate runnable artifacts
- Include a mandatory
k6-validatehandoff block with one suggested validation command
- 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.
Cloud artifact generation must be version-aware before emitting cloud commands, cloud options, or cloud-only guidance.
Required detection flow:
- Resolve executable target.
- Verify installed binary with
command -v k6. - Run
k6 version. - Parse semantic version.
- 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
Gate behavior:
- If
command -v k6fails, stop cloud generation and ask the user to install k6 first. - If exact version is unknown or parse fails, stop cloud generation and ask for exact k6 version.
- Do not invent synthetic cloud-family labels.
- Preserve
k6_versionandruntime_familyin validator handoff metadata.
Deterministic first-attempt rule:
- When version classification is successful, select command family directly and execute without
--helpdiscovery. - Only consult help output after a blocking CLI error in the first attempt.
When cloud capability is requested, emit one explicit mode:
cloud-run- Command family:
k6 cloud run <script>
- Command family:
cloud-streaming-local-execution- Command family:
k6 cloud run --local-execution <script>
- Command family:
local-only- Command family:
k6 run <script>
- Command family:
Auth and routing safety:
- Never hard-code tokens.
- Prefer
K6_CLOUD_TOKENfor non-interactive auth. - Use
K6_CLOUD_STACK_IDandK6_CLOUD_PROJECT_IDwhen routing is required. - Use
__ENVfor script-consumed cloud-managed values.
Use this matrix after successful command -v k6 and parsed k6 version:
V2_0_PLUS- First command:
k6 cloud run <script> - Do not use
--project-idunless proven by current CLI evidence.
- First command:
V1_6_PLUS_V1_X- First command:
k6 cloud run <script> - Keep routing via environment variables when needed.
- First command:
V0_53_TO_V1_5- First command:
k6 cloud run <script> - Restrict to v1-compatible cloud guidance only.
- First command:
Project routing rule:
- If user provides
project_id, resolve withk6 cloud project list --jsonbefore first paid run. - If requested
project_idis default, execute once and report run URL. - If requested
project_idis not default and routing cannot be set with verified syntax, stop and ask for confirmation before any paid run.
Missing project ID routing rule:
- If user requests cloud execution and does not provide
project_id, do not execute immediately. - Ask this mandatory routing confirmation first:
No project_id was provided. This will run on your default cloud project. Do you want to continue with default project routing?
- If user rejects default routing, stop and request explicit
project_id. - If user accepts default routing, require a second explicit paid-run confirmation before executing
k6 cloud run.
Use this deterministic policy before any cloud execution:
- Run blocking preflight in this order:
command -v k6k6 version- Parse
major.minor.patchand classify runtime family
- If preflight fails at any point, stop and ask the user for corrective action. Do not execute cloud commands.
- Primary remote execution command is
k6 cloud run <script>. - Do not emit or execute
--project-idunless the detected runtime-family matrix explicitly confirms support. - First attempt must run without
--helpdiscovery once runtime is classified. - Consult help only after a real blocking CLI error on the first attempt.
- If user requires project routing:
- resolve current/default routing with
k6 cloud project list --json - if requested project id matches default routing, continue without reroute
- if requested project id does not match default routing, stop and ask for explicit confirmation plus a compatible alternative path before any paid run
- resolve current/default routing with
Before any cloud execution attempt, verify that at least one cloud auth path is available:
- Prefer non-interactive auth via
K6_CLOUD_TOKEN. - If
K6_CLOUD_TOKENis absent, verify active CLI login withk6 cloud project list --json. - If both checks fail, stop cloud execution and instruct the user to either run
k6 cloud logininteractively or exportK6_CLOUD_TOKEN. - Treat missing cloud auth as a blocking condition for
cloud-runandcloud-streaming-local-execution. - When auth is missing, do not attempt a paid cloud run.
Enforce this block as mandatory for cloud execution:
P1: maximum one cloud paid execution per task unless user explicitly confirms additional cost.P2: any second cloud execution requires explicit user confirmation plus a short reason.P3: if run URL exists and status isRunning, never auto-rerun.P4: when terminal output is truncated, recover status from the same run identity; never relaunch automatically.P5: whenproject_idis missing, require default-project routing acceptance before the paid-run confirmation.P6: default-project routing acceptance does not replace paid-run confirmation; both confirmations are mandatory.
Track cloud run identity deterministically:
- Extract and store
run_urlandrun_idfrom the first paid execution. - Reuse the same run identity for status updates, summaries, and follow-up guidance.
- Treat rerun as a paid action and require explicit cost confirmation before execution.
- Report run identity and rerun decisions in the
Cloud Execution Safetysubsection of the output.
V0_53_TO_V1_5:- Allow
k6 cloud login,k6 cloud run, andk6 cloud run --local-execution. - Do not emit
options.cloud.stackIDworkflows by default. - Do not emit v2-only cloud options.
- Allow
V1_6_PLUS_V1_X:- Allow restricted v1 path plus
options.cloud.stackIDandK6_CLOUD_STACK_ID. - Keep cloud options constrained to proven evidence.
- Allow restricted v1 path plus
V2_0_PLUS:- Allow verified v2 cloud options:
options.cloud.projectIDoptions.cloud.stackIDoptions.cloud.distributionoptions.cloud.deleteSensitiveDataoptions.cloud.staticIPsoptions.cloud.drop_metricsoptions.cloud.drop_tagsoptions.cloud.keep_tags
- Allow cloud context variables, for example
__ENV.K6_CLOUDRUN_LOAD_ZONE. - Require stack-aware routing guidance for cloud commands.
- Allow verified v2 cloud options:
When options.cloud.distribution is present:
- Every entry must include
loadZoneandpercent. - Every
percentmust be an integer. - Sum of
percentvalues must be exactly100. - If validation fails, stop runnable output instead of normalizing values.
Run this protocol before emitting any runnable artifact that executes load from the current host. For pure cloud-run, local host capacity is advisory only and must not block remote cloud execution unless the user also requests a local dry run or --local-execution.
Cross-skill required fields:
execution_contextmachine_profileprojected_loadcapacity_estimaterisk_statussafe_limit_recommendationscale_out_recommendation
High-risk gate rule (mandatory):
- Before generating or orchestrating any script that projects more than
500VUs on the current host (local-only,cloud-streaming-local-execution, CI, or container execution), run host audit silently withnode skills/k6-builder/scripts/audit-host.js. - If Node.js is unavailable, use the Python fallback:
python3 skills/k6-builder/scripts/audit-host.py. - Parse stdout JSON and use that as the authoritative
machine_profilefor this generation pass.
Contextual deterministic formulas:
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:
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: compute per node, then aggregate
Evaluation order:
- Build
execution_contextfrom the declared environment (local,ci,container,cloud, ordistributed) plus user constraints. - Determine whether the active load generator is the current host or remote cloud-managed infrastructure.
- Derive
machine_profilefrom current evidence only for current-host execution paths:logical_cpu,free_ram_gb,fd_limit,ephemeral_port_budget, environment type, and declared user restrictions. - If projected load is expected to exceed
500VUs on the current host, run host audit (node skills/k6-builder/scripts/audit-host.js, fallbackpython3 skills/k6-builder/scripts/audit-host.py) and overwrite missing or stale machine evidence with audit output. - Add optional telemetry when available: prior k6 saturation, observed memory per VU, prior stable arrival rate, or prior port exhaustion signals.
- Derive
projected_loadfrom the runnable executor shape: 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 called out in the output.- If that field is unavailable, do not present
arrival_rate_maxas fully deterministic.
- Calculate
capacity_estimate.vus_maxandcapacity_estimate.arrival_rate_maxfrom the currentmachine_profileusing contextual deterministic formulas when the current host generates load. Never use a universal fixed VU ceiling. - Classify
risk_statusasSAFE,AT_RISK, orHIGH_RISKfor current-host execution paths. - Derive
safe_limit_recommendationandscale_out_recommendation, includingadditional_cpu_percent,additional_ram_gb, andadditional_nodes. - If execution mode is pure
cloud-runand remote worker capacity is not directly verified, report remote capacity facts asunknownand keep any local host assessment advisory-only for optional local validation.
Incomplete-data rules:
- If critical machine inputs are missing, ask one clarification question when that is the cheapest unblocker.
- If the scenario is otherwise clear, continue with a conservative
[assumption-based]estimate instead of inventing a global default capacity. - Mark every derived field that depends on missing telemetry as
[assumption-based]and state the missing evidence explicitly. - For pure
cloud-run, missing local machine evidence must not block remote execution guidance; report remote capacity asunknownunless cloud worker constraints are explicitly provided.
Builder-stage gate behavior:
cloud-run: emit runnable artifacts and cloud execution hints even when the local host would beAT_RISKorHIGH_RISK; local capacity may only restrict optionalk6 runork6 cloud run --local-executionhints.SAFE: emit runnable artifacts normally.AT_RISK: runnable artifacts are allowed only if the output includes the canonical capacity alert, the reduced safe limit, and the distributed mitigation guidance.HIGH_RISK: block runnable single-node artifact emission only for current-host execution modes. Replace the runnable artifact section with a blocked-output explanation plus a reduced-load or distributed execution path.
When HIGH_RISK, the blocked-output explanation must use this exact format:
Your machine only has [X]GB of available/free RAM. Attempting to run [Y] VUs locally will collapse the load generator. Limit the local test to [Z] VUs or export this design to k6-operator (distributed execution).
Canonical alert format:
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.Determinism rules:
Ymust come from the currentcapacity_estimate.Zmust come from the currentsafe_limit_recommendation.Nmust come from the currentscale_out_recommendation.additional_nodes.- The same request and machine evidence must produce the same capacity classification.
Always enforce these validations before returning output:
- Thresholds are required
- Parse from SLA when provided.
- If SLA missing, derive deterministic defaults and state them.
- Load profile is required
- Include explicit
vusandduration, or explicit staged/scenario equivalent.
- Include explicit
- Parameter coherence is required
- Arrival-rate executors must satisfy
preAllocatedVUs <= maxVUs. - Time-based executors require explicit duration.
- Iteration-based executors require explicit
vusanditerations.
- Arrival-rate executors must satisfy
- Secrets and runnable safety are required
- Never hard-code credentials/tokens.
- Require environment variables (
__ENV) for auth and base URL.
- Multi-environment coherence is required
- For
dev/staging/prod, validatedev <= staging <= prodfor VU progression. - Emit
WARNINGif user override violates VU progression without explicit justification. - SLA thresholds are invariants: the stated SLA must be identical across dev, staging, and prod. If any environment has relaxed thresholds (e.g.,
p99<2sin dev when the SLA statesp99<1s), reject the artifact and report under Guardrail Validation.
- For
- Named default function is required
- The
export default functionmust always have a name derived from the active scenario and protocol. - Naming convention:
run<Protocol><ScenarioType>— example:runHttpLoad,runGrpcStress,runBrowserSmoke. - If scenario or protocol is not resolved yet, use a generic but named function:
runPerfTest.
- The
- Cloud compatibility invariants are required (when cloud mode is requested)
- Exact k6 version must be detected and classified before cloud output.
- Emitted cloud commands/options must match runtime family allowlist.
- Reject v2-only cloud options when runtime is below
v2.0.0. - Distribution math must pass strict 100% validation.
When building for multiple environments (dev/staging/prod):
- Threshold values MUST BE IDENTICAL across all environments.
- VU counts MAY VARY per environment.
- Duration MAY VARY per environment.
- Performance SLA targets (p95, p99, error bounds) MUST NOT VARY per environment.
Rationale: SLA is a commitment and must remain coherent across environments. Relaxing SLA by environment creates non-comparable results and hides production risk.
Canonical cross-skill warning (must match k6-plan exactly):
WARNING: SLA must be identical across environments to maintain testing coherence.
Canonical enforcement flow (builder stage):
- Detect single declared SLA plus per-environment threshold divergence request.
- Emit the canonical warning string above.
- Ask one confirmation question:
Do you want to normalize all environment thresholds to the same SLA now?
- If user confirms normalization:
- Continue generation with identical thresholds across dev/staging/prod.
- If user rejects normalization:
- Reject runnable artifact emission and report violation under Guardrail Validation.
- Do not emit per-environment relaxed thresholds.
load:ramping-vusstress:ramping-vus(aggressive progression)spike:ramping-vus(rapid surge)soak:constant-vusorramping-vussustainedsmoke:constant-vus
If user explicitly requires rate control, prioritize:
constant-arrival-ratefor fixed RPSramping-arrival-ratefor changing RPS
If user asks for exact iteration accounting:
per-vu-iterationsorshared-iterations
When building multi-environment outputs (dev/staging/prod), apply mandatory differentiation:
- VU counts must differ explicitly across environments — never use identical values. Baseline pattern: dev ≤ staging ≤ prod.
- SLA-derived thresholds are invariants across all environments — never relax or adjust threshold values per environment. The stated SLA (e.g.,
p99<1s) must be applied identically to dev, staging, and prod. Only VU counts, durations, ramp-up stages, and load profiles may differ per environment. Any threshold relaxation (e.g.,p99<2sin dev when SLA statesp99<1s) is a hard invariant violation — reject and report under Guardrail Validation. - Target URL must be distinct per environment — use
__ENV.DEV_BASE_URL,__ENV.STAGING_BASE_URL,__ENV.PROD_BASE_URLas named environmental variables. - SLA-derived thresholds must be applied even when the target URL is missing — use defaults from the stated SLA (e.g.,
p99<1s) with__ENVplaceholder for the URL. - Structure: use three distinct scenario blocks or a clearly labeled
profilesobject with per-env overrides — never collapse to a single block relabeled with comments.
When user requests multi-env outputs, offer two architecture options and make the default explicit:
- Files:
dev.js,staging.js,prod.js - Pros: Strong isolation per environment
- Cons: Duplication and cross-env maintenance overhead
- File:
load-test.js - Pattern:
__ENV.ENVIRONMENTselects environment-specific VUs/duration - Pros: DRY, single source of truth for shared logic and thresholds
- Cons: Slightly more control-flow branching
Default behavior:
- Recommend Option 2 unless user explicitly asks for separate files.
- Still mention Option 1 as an available alternative.
- Keep SLA thresholds identical regardless of selected architecture.
p95<Xms-> 95th percentile latency thresholdp99<Xms-> 99th percentile latency thresholderror<X%orrate<X%-> Error rate threshold
p95<500ms,p99<900ms,error<1%-> All conditions must be met- Commas separate independent thresholds
- All listed thresholds are combined in final configuration
p95<500ms AND p95>100ms-> p95 must be between 100ms and 500ms- Multiple constraints on the same metric (range validation)
- Translates to multiple threshold entries for the same k6 metric
Note: OR logic is not supported in this skill behavior. All conditions are treated as mandatory (AND).
- Input:
p95<400ms,error<1%-> p95 AND error rate thresholds - Input:
p95<500ms AND p99<900ms-> Both percentiles required - Input:
p95<2s-> Single threshold with p99 inferred (see sla-defaults.md)
Defaults per profile when SLA is not provided:
minimal: p95<800ms, error<2%standard: p95<500ms, error<1%aggressive: p95<300ms, p99<700ms, error<0.5%, checks>99%
When generating thresholds, apply the correct metric per protocol. Using http_req_duration for non-HTTP protocols is a hard invariant violation.
| Protocol | Required threshold metric |
|---|---|
| HTTP | http_req_duration: ['p(95)<Nms'] |
| WebSocket | ws_session_duration: ['p(95)<Nms'] (built-in session duration metric) |
| gRPC | grpc_req_duration: ['p(99)<Nms'] |
| Browser | browser_http_req_duration: ['p(95)<Nms'] |
If the inferred protocol does not match http, ensure the threshold uses the correct metric above — never substitute http_req_duration as a fallback.
When generating artifacts (single or multi-environment):
For HTTP/gRPC/Browser protocols:
- If
targetis explicitly provided (literal URL), wrap it in__ENV:if (!__ENV.BASE_URL) { throw new Error('BASE_URL environment variable is required'); } const BASE_URL = __ENV.BASE_URL;
- Never emit:
const BASE_URL = 'https://api.example.com';(hardcoded literal without__ENV) - Exception: Only if user explicitly asks for hardcoded URL (e.g., "quick smoke test for local"), document as assumption.
For multi-environment outputs:
- Always use pattern:
__ENV[${env.toUpperCase()}_BASE_URL] - Append a
.env.examplestub with all required variables.
Validation: After artifact generation, scan for violations:
- If protocol in [http, grpc, browser] and artifact contains
= 'https://or= "https://without__ENV, REJECT. - Add to guardrail validation checklist:
[ ] Base URL uses __ENV, not hardcoded literals
- Use
grpc.Client(),client.load(),client.connect(),client.invoke() - Metrics:
grpc_req_duration,grpc_req_failed - Always close connections in teardown
- Handle metadata for authentication
- Use
browser.newContext(),context.newPage(),page.goto(),page.waitForSelector() - Always close page/context at iteration end
- Prefer
data-testidselectors - Collect Web Vitals when relevant
- For requested multi-step user journeys, model the full sequence explicitly in order (do not collapse or skip steps).
- For checkout/browser journeys, include an end-to-end threshold aligned to the requested KPI/SLA (for example
p(95)<4000when the request states p95<4s).
- Use
ws.connect()fromk6/wsand handle all lifecycle events:on('open'),on('message'),on('error'),on('close'). - Always add a bounded session duration to avoid infinitely hanging connections.
- WebSocket latency thresholds are required:
http_req_durationdoes not capture WebSocket behavior. Use built-inws_session_durationfor session duration and a customTrendfor per-message latency:import { Trend } from 'k6/metrics'; const wsLatency = new Trend('ws_message_latency'); // in default function, record per-message timing: // wsLatency.add(Date.now() - sentAt); // in options.thresholds: // ws_session_duration: ['p(95)<1500'] // ws_message_latency: ['p(95)<150']
- Add to guardrail checklist:
[ ] WebSocket script includes builtin ws_session_duration and custom ws_message_latency thresholds.
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
Every response must include these sections in order:
- Build Inputs Summary
- Executor and Scenario Configuration
- Runnable Artifacts
- Required Environment Variables
- Guardrail Validation — include this checklist at minimum:
- Default export function is named (not anonymous)
- SLA thresholds are identical across all environments (no per-env threshold relaxation)
- Base URL uses
__ENV, not hardcoded literals - Final summary includes only verified facts or explicit
unknown
- Validation Handoff (required) — include one runnable command for
k6-validate- For smoke tests specifically: Append explicit command block:
## k6-validate Recommendation Run k6-validate to check this smoke artifact:
- **For other scenarios** (load, stress, soak, spike): Include validation recommendation that references k6-validate. - For smoke tests specifically: Append explicit command block:
- Execution Hints (required)
- Include at least one concrete run command that can be copied as-is.
- Include required environment variables used by that command using explicit
-eflags. - Do not rely on implicit shell-exported variables for one-shot execution hints.
- Use deterministic command shape (
k6 run <script>plus-eflags when needed). - Keep hints runnable and aligned with the emitted artifact names.
- Treat
Execution Hintsas a hard companion ofRunnable Artifacts: if artifact code exists, hints must include the exact script filename and matching env var flags. - Never emit conceptual guidance only; include at least one concrete copy-paste command.
- Cloud Execution Safety (required)
run_count: <integer>first_run_url: <url-or-none>rerun_requested_by_user: <yes|no>cost_confirmation: <yes|no>project_id_provided: <yes|no>default_project_routing_confirmation: <yes|no|not-applicable>
- Next recommended step
Dynamic capacity reporting requirements:
-
Include
execution_contextonly when explicitly provided or directly measured. -
Guardrail Validationmust also include these checklist items when capacity evaluation is in scope:- Dynamic capacity gate executed with current
machine_profile -
capacity_estimate,risk_status, andsafe_limit_recommendationare present -
scale_out_recommendationincludesadditional_cpu_percent,additional_ram_gb, andadditional_nodes - Canonical capacity alert emitted when
risk_statusisAT_RISKorHIGH_RISK
- Dynamic capacity gate executed with current
-
For pure
cloud-run, capacity reporting may mark remote cloud-worker capacity asunknown; local host capacity remains advisory unless local execution is also requested. -
When
risk_statusisHIGH_RISK,Runnable Artifactsmust not include a single-node runnable artifact.
- Always prefer
__ENV.BASE_URLfor runnable scripts. - Include timeout guidance for HTTP (
timeout: '30s'baseline). - Include checks and request tags for segmentation.
- Generated script must be portable: the same artifact must run both with
k6 runandk6 cloud run. - Do not hard-couple the script to cloud-only configuration by default (for example fixed
options.cloud.*values). - Cloud routing/auth concerns belong in Execution Hints and environment variables, not as mandatory hardcoded script config.
- Add lightweight traceability support using
__ENV.TRACE_MODE(off|basic) with concise one-line logs only when enabled. - Default
TRACE_MODEtobasicfor cloud execution hints unless the user explicitly disables tracing; keep non-cloud hints atoffunless the user opts in. - For auth, list required env vars and never place secret literals.
- For multi-env requests, include
.env.exampleplaceholders only. - Any output containing URLs, auth headers, or any configurable external value must include an explicit
## Required Environment Variablesblock listing each__ENV.VAR_NAMEwith a one-line description of its purpose. - The
## Required Environment Variablesblock must be concrete and non-empty; include every required runtime variable and avoid generic placeholders like "add your vars here". - For multi-env outputs, always include a
.env.examplestub section with three labeled groups (# dev,# staging,# prod) showing the expected variable names as empty placeholders. - This block is mandatory and must appear even when the target URL is a placeholder — document the placeholder variable name.
- For browser or transaction flows with multiple business steps, emit the full ordered step list in code/comments so the generated artifact preserves the requested journey sequence.
Generated code must not introduce static-analysis violations. Before emitting any artifact:
-
Named exports —
export default functionmust be named (see Required k6 Invariants #6).- Generate using naming convention:
run<Protocol><ScenarioType>(e.g.,runHttpLoad(),runGrpcSmoke()). - VALIDATION (MANDATORY): After code generation, scan the artifact for
export default functionfollowed by(. - If the pattern matches
export default function\s*\((anonymous), REJECT the artifact immediately. - Add to guardrail violations: "Default export function must be named (e.g.,
runHttpLoad)". Do not emit unless function is named.
- Generate using naming convention:
-
No
vardeclarations — useconstorletonly. -
No unguarded logs in hot paths — inside
export default functionor any function called per iteration.- Guarded compact trace logs are allowed only when
__ENV.TRACE_MODE==='basic'. - Prefer one line at iteration start and one line for status/result.
- Guarded compact trace logs are allowed only when
-
No hardcoded literals for URLs or credentials — all configurable values must use
__ENV. -
No silent
catchblocks — errors must be logged or re-thrown with context. -
No unsafe
JSON.parse— wrap in try-catch with descriptive error message.
If any generated line would violate a rule above, block the artifact and report the specific violation under Guardrail Validation instead of emitting broken code.
Keep this file focused on generation workflow. Place deep guidance in:
skills/k6-builder/references/README.md
- Parse parameters (
target,scenario,sla,protocol,profile,duration,vus,environments,goal). - Run Tool Discovery Protocol when minimum inputs are missing.
- Start the Adaptive Question System with baseline questions when
target,scenario,sla, orprotocolare missing. - Add an HTTP method question to the same question system when protocol is HTTP and method is still ambiguous.
- Add auth questions to the same question system when auth is required, unknown, or otherwise blocks executable output.
- Add more questions in the same system if other critical ambiguities or missing requirements are detected.
- Build internal minimal plan from inputs.
- Select executor and derive coherent scenario config.
- Enforce executor coherence: if scenario type is
loadand the user did not explicitly request rate-based control, recommend and emitramping-vus. - Parse SLA thresholds or apply deterministic defaults.
- If cloud execution is requested, run Cloud Runtime Compatibility Gate and Cloud v2 Command Resolution preflight (
command -v k6,k6 version, runtime classification) before any paid run. - If cloud execution is requested, run the Cloud Authentication Readiness Gate before any paid run.
- If cloud execution is requested and
project_idis missing, run the Missing project ID routing rule and block execution until routing is confirmed. - Run the Dynamic Capacity Protocol using current machine evidence only when the selected execution path uses the current host as the load generator; for pure
cloud-run, keep local capacity advisory and do not block remote execution. - For multi-environment requests, choose architecture using Multi-Environment Architecture Options (default single-script unless explicitly overridden).
- Generate runnable script/options/config outputs only when the relevant current-host capacity gate allows them.
- Apply dashboard and secrets safety policies.
- Enforce Paid Execution Guardrail before any paid run or rerun attempt; require explicit cost confirmation and justification for paid reruns.
- Validate all required invariants, including: (a) the generated default export function is named — reject anonymous
export default function () {}; (b) SLA thresholds are identical across all environments — reject any per-environment threshold relaxation. Both are hard invariant violations that block output emission. - Return output in Output Contract order.
For official skill evaluation runs in this repository:
- Store artifacts under
skills/k6-builder/k6-builder-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.