Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install k6-docs@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin k6-docs v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install k6-docs

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/k6-docs/

Extract the ZIP to .github/skills/ in your repo. The folder name must match k6-docs for Copilot to auto-discover it.

Skill Files (21)

SKILL.md 2.8 KB
---
name: k6-docs
license: Apache-2.0
description: Write or review k6 documentation across the three k6 repositories - k6-DefinitelyTyped (TypeScript types), k6-docs (user documentation), and k6 (release notes / changelog). Applies k6 doc style conventions, generates TypeScript type definitions, drafts release notes, and validates examples by running them against k6@master. Use when working on k6 documentation, the k6 changelog, the k6 release notes, k6 API reference, k6 TypeScript types, load testing docs, or when the user asks to write, edit, or review anything in the k6, k6-docs, or k6-DefinitelyTyped repos - even if they don't explicitly say "documentation".
---

# k6 Documentation

Document or review k6 features across three repositories: k6-DefinitelyTyped (TypeScript types), k6-docs (user documentation), and k6 (release notes).

## Workflow

Pick the workflow that matches the user's intent:

- **Write documentation:** follow [references/workflows/write.md](references/workflows/write.md)
- **Review documentation:** follow [references/workflows/review.md](references/workflows/review.md)

## Quick References

- [Repository structure & feature type identification](references/repository-structure.md)
- [TypeScript patterns & troubleshooting](references/typescript-patterns.md)
- [Testing workflow with parallel subagents](references/testing-workflow.md)
- [agent-browser command reference](references/agent-browser-reference.md)
- [Troubleshooting guide](references/troubleshooting.md)

## Critical Rules

- **Never push automatically** - always ask first
- **Never chain commands with `&&` or `;`** - run each command separately (prevents failures)
- **Only document user-facing features** - not internal implementation
- **Use `1.` for every numbered list item** (not `1.`, `2.`, `3.`)
- **Test every code example** against k6@master before committing
- **No `Co-Authored-By: Claude` or AI attribution** in commits

## Validating examples (always run before committing)

Every code example in k6 documentation **and release notes** must execute cleanly against `k6@master`. The minimum loop:

```bash
# 1. cd into the k6 repo (not k6-docs or k6-DefinitelyTyped)
cd ~/path/to/k6

# 2. Make sure you're on master at the latest commit (the contract is k6@master)
#    First check for local work: if this prints anything, stop and ask the user before switching branches
git status --porcelain
git checkout master
git pull

# 3. Run each example as a separate command (no &&)
go run . run /path/to/script.js
```

If the run fails: read the error, fix the example in the source (doc or release note), re-run. Do not commit a change whose example doesn't run clean against current `master`. For the full multi-example workflow with parallel subagents, see [references/testing-workflow.md](references/testing-workflow.md).
references/
agent-browser-reference.md 3.0 KB
# agent-browser Command Reference

agent-browser is the PRIMARY tool for visual verification of documentation. Use it to catch rendering issues, broken styles, and visual problems that HTTP status checks cannot detect.

## Installation

Check if installed:
```bash
which agent-browser
```

If not installed:
```bash
npm install -g agent-browser@0.38.1
agent-browser install
```

## Navigation

- `agent-browser open <url>` - Navigate to URL
- `agent-browser back` - Go back in history
- `agent-browser reload` - Reload current page

## Inspection

- `agent-browser snapshot` - Get accessibility tree with element @refs
- `agent-browser snapshot -i` - Interactive elements only
- `agent-browser screenshot [path]` - Screenshot (add `--full` for full page)
- `agent-browser get text <selector>` - Get element text
- `agent-browser get title` - Get page title
- `agent-browser get url` - Get current URL

## Interaction

- `agent-browser click <selector|@ref>` - Click element
- `agent-browser type <selector> <text>` - Type into element
- `agent-browser scroll <up|down|left|right> [pixels]` - Scroll page
- `agent-browser wait <selector|milliseconds>` - Wait for element or time

## Selectors

Two types of selectors:

**CSS selectors:**
- `"a[href*='waitforrequest']"` - Links containing text
- `".docs-table td"` - Table cells with class
- `"h1"` - Headers

**@refs from snapshot:**
- Use `snapshot` command first to get element @refs
- Example: `@e42` references a specific element
- More reliable than CSS selectors

## Sessions

- `--session <name>` - Use isolated browser session
- Default session persists between commands

## Tips

- **Always use `--full` flag** for full-page screenshots when verifying docs
- **Use `snapshot` to find elements** before clicking (provides @refs)
- **Combine with pipes:** `agent-browser get text .title | grep "Error"` to check for issues
- Check for 404s: `agent-browser get title` should not return "404" or "Page Not Found"

## Example Verification Workflow

```bash
# Step 1: Navigate to module index
agent-browser open "http://localhost:3002/docs/k6/next/javascript-api/k6-browser/page/"

# Step 2: Verify method appears in table
agent-browser screenshot --full index-page.png

# Step 3: Navigate to method docs
agent-browser open "http://localhost:3002/docs/k6/next/javascript-api/k6-browser/page/waitforevent/"

# Step 4: Verify rendering
agent-browser screenshot --full method-page.png

# Step 5: Check related links
agent-browser snapshot > snapshot.txt
agent-browser click "a[href*='waitforrequest']"
agent-browser screenshot related-link.png

# Step 6: Verify no 404
agent-browser get title  # Should not be "404" or "Page Not Found"
```

## Fallback: curl

If agent-browser is unavailable, use `curl` as a last resort (provides no visual verification):

```bash
# Check HTTP status only
curl -s -o /dev/null -w '%{http_code}' http://localhost:3002/docs/k6/next/path/
```

**Note:** curl only verifies pages return 200 - it cannot catch rendering, styling, or visual issues.
repository-structure.md 3.7 KB
# Repository Structure Reference

## k6-DefinitelyTyped

TypeScript type definitions:

```
types/k6/
├── browser/
│   └── index.d.ts          # Browser module types (Page, Frame, Locator, etc.)
├── http/
│   └── index.d.ts          # HTTP module types
├── test/
│   └── browser.ts          # Browser type tests
│   └── http.ts             # HTTP type tests
└── index.d.ts              # Core k6 types
```

## k6-docs

User-facing documentation:

```
docs/sources/k6/
├── next/                           # Upcoming release docs
│   └── javascript-api/
│       ├── k6-http/                # HTTP module docs
│       ├── k6-browser/             # Browser module docs
│       │   ├── page/
│       │   ├── frame/
│       │   ├── locator/
│       │   └── browsercontext/
│       ├── k6-grpc/                # gRPC module docs
│       └── k6-ws/                  # WebSocket docs
└── v1.X.x/                         # Released version docs
```

## k6

Main repository:

```
k6/
├── release notes/
│   └── v{VERSION}.md       # Release changelog
├── internal/js/modules/k6/
│   ├── http/               # HTTP module implementation
│   ├── browser/            # Browser module implementation
│   └── ...
└── lib/options.go          # Core k6 options
```

## Feature Type Mapping

| Type           | Example                          | Docs Location                       | Types Location              |
| -------------- | -------------------------------- | ----------------------------------- | --------------------------- |
| Core k6        | `check()`, `group()`, options    | `javascript-api/k6/` or `using-k6/` | `types/k6/index.d.ts`       |
| HTTP module    | `http.get()`, `http.batch()`     | `javascript-api/k6-http/`           | `types/k6/http/index.d.ts`  |
| Browser module | `page.click()`, `locator.fill()` | `javascript-api/k6-browser/`        | `types/k6/browser/index.d.ts` |
| gRPC module    | `grpc.Client`, `grpc.connect()`  | `javascript-api/k6-grpc/`           | `types/k6/grpc/index.d.ts`  |
| WebSocket      | `ws.connect()`                   | `javascript-api/k6-ws/`             | `types/k6/ws/index.d.ts`    |
| Experimental   | Redis, timers                    | `javascript-api/k6-experimental/`   | Various                     |
| CLI feature    | New flags, commands              | `using-k6/` or `misc/`              | N/A                         |

## How to Identify Feature Type

Use these three methods to determine which module a feature belongs to:

### Method 1: From PR/Commit Files

Look at which files are modified in the k6 repository:

- `internal/js/modules/k6/http/` → HTTP module
- `internal/js/modules/k6/browser/` → Browser module
- `internal/js/modules/k6/grpc/` → gRPC module
- `internal/js/modules/k6/ws/` → WebSocket module
- `lib/options.go` → Core k6 options
- `cmd/` → CLI features

### Method 2: From Feature Name

The method or class name often indicates the module:

- `page.waitForEvent` → Browser module (Page class)
- `http.asyncRequest` → HTTP module
- `--env` flag → CLI/Core feature
- `grpc.Client` → gRPC module

### Method 3: From Import Statement

Check the import statement in example code:

- `import { browser }` from `'k6/browser'` → Browser module
- `import http from 'k6/http'` → HTTP module
- `import { check } from 'k6'` → Core k6
- `import grpc from 'k6/grpc'` → gRPC module
- `import ws from 'k6/ws'` → WebSocket module

## Method tables in `_index.md`

It is **generally recommended** that method/API tables in `_index.md` files (e.g. in `javascript-api/k6-browser/page/`, `javascript-api/k6-http/`, or any module) be **sorted alphabetically** by method or API name. When adding a new method, add its row in the correct alphabetical position and create the corresponding method doc.
subagent-prompts.md 3.4 KB
# Subagent Review Prompts

Use these prompts when launching parallel review agents via Task tool.

## TypeScript Review Subagent

```
Review TypeScript definitions for [FEATURE_NAME].

Branch: [BRANCH_NAME]
Locate k6-DefinitelyTyped repository in current directory or subdirectories.

1. Checkout the branch:
   cd k6-DefinitelyTyped
   git checkout [BRANCH_NAME]

2. Check what changed:
   git log main..HEAD --oneline
   git diff main --stat

3. Read the changed type definition files in types/k6/

4. Review against checklist in references/review-checklists.md (TypeScript section)

5. Run tests:
   pnpm install -w --filter "{./types/k6}..."
   pnpm test k6

6. Report findings:
   ## TypeScript Review: [FEATURE_NAME]
   **Status:** PASS / ISSUES FOUND
   **Commits:** [list]
   **Files Changed:** [list]
   **Checklist Results:** [each item with PASS/FAIL]
   **Test Results:** [pass/fail with details]
   **Issues Found:** [list]
   **Recommendations:** [list]
```

## Documentation Review Subagent

```
Review user documentation for [FEATURE_NAME].

Branch: [BRANCH_NAME]
Local server: http://localhost:3002
Locate k6-docs repository in current directory or subdirectories.

1. Checkout the branch:
   cd k6-docs
   git checkout [BRANCH_NAME]

2. Check what changed:
   git log main..HEAD --oneline
   git diff main --stat

3. Validate ALL added links with ${CLAUDE_PLUGIN_ROOT}/skills/k6-docs/scripts/validate_links.sh

4. Visual verification with agent-browser (or curl fallback):
   agent-browser open "http://localhost:3002/docs/k6/next/javascript-api/[module]/[method]/"
   agent-browser screenshot --full method-page.png

   Verify page loads, parameters table, code highlighting, links, breadcrumbs

5. Read each changed documentation file and review against checklist in references/review-checklists.md (User Documentation section)

6. Check _index.md was updated

7. Test examples with k6@master:
   Extract runnable examples (skip <!-- md-k6:skip --> blocks)
   For each example:
   - Write to /tmp/k6-test-<name>-<N>.js
   - Run: cd k6
   - Run: go run . run /tmp/k6-test-<name>-<N>.js
   - Report: SUCCESS or FAILURE with output
   - Clean up temp file

   CRITICAL: You MUST actually execute code examples.
   If ALL examples have skip markers: Status is ⚠️ UNTESTED (NOT ✅ PASS)

8. Report findings:
   ## Documentation Review: [FEATURE_NAME]
   **Status:** PASS / ISSUES FOUND
   **Commits:** [list]
   **Files Changed:** [list]
   **Visual Verification:** [results]
   **Link Validation:** [total/passed/failed with broken links list]
   **Example Tests:** [total/passed/failed/skipped with failures]
   **Content Checklist:** [each item]
   **Issues Found:** [list]
   **Recommendations:** [list]
```

## Release Notes Review Subagent

```
Review release notes for [FEATURE_NAME].

Branch: [BRANCH_NAME]
Locate k6 repository in current directory or subdirectories.

1. Checkout the branch:
   cd k6
   git fetch origin [BRANCH_NAME]
   git checkout [BRANCH_NAME]

2. Check what changed:
   git log origin/[BRANCH_NAME]..HEAD --oneline
   OR: git diff origin/[BRANCH_NAME] -- "release notes/"

3. Read the release notes file (release notes/v*.md)

4. Review against checklist in references/review-checklists.md (Release Notes section)

5. Report findings:
   ## Release Notes Review: [FEATURE_NAME]
   **Status:** PASS / ISSUES FOUND
   **Commits:** [list]
   **File Changed:** [release notes file]
   **Checklist Results:** [each item]
   **Issues Found:** [list]
   **Recommendations:** [list]
```
testing-workflow.md 2.3 KB
# Testing Workflow for k6 Examples

**REQUIRED:** All code examples in documentation and release notes must be tested with k6@master using `go run . run script.js`.

## Testing Loop

Follow this loop until 100% of examples pass:

1. Extract runnable examples (skip blocks with `<!-- md-k6:skip -->` comment)
1. Set up dependencies if needed (test servers, mock APIs, etc.)
1. Launch parallel subagents to test each example (one Task per example in single message)
1. If failures: launch fix subagent → update docs → re-test ALL examples
1. Repeat until 100% pass

## Testing Subagent Template

Use this template for each example test subagent (Bash subagent type):

```
Test example <N>: <brief description>

1. Write code to /tmp/k6-test-<name>-<N>.js
2. Run: cd /path/to/k6
3. Run: go run . run /tmp/k6-test-<name>-<N>.js
4. Report: SUCCESS or FAILURE with exit code and full output
5. Clean up temp file
```

## Fix Subagent Template

When examples fail, use this template (general-purpose subagent):

```
Fix failing examples: [list failures with errors]

1. Analyze failures (API errors, missing imports, timing issues, etc.)
2. Update docs: docs/sources/k6/next/javascript-api/[...]/[method].md
3. Report changes made

allowed-tools: Read, Edit, Grep, Glob
```

## Parallel Launch Pattern

**IMPORTANT:** Launch all test subagents IN PARALLEL using the Task tool.

Send a **SINGLE message** with MULTIPLE Task tool calls to run them simultaneously:

```
Message structure:
- Text explaining what you're testing
- [Invoke Task tool: Test example 1]
- [Invoke Task tool: Test example 2]
- [Invoke Task tool: Test example 3]
- ...
```

This runs tests concurrently instead of waiting for each to finish sequentially.

## After All Examples Fail/Pass

If ALL examples have `<!-- md-k6:skip -->` markers:
- Status is ⚠️ **UNTESTED** (NOT ✅ PASS)
- Flag this as a concern: "No examples were actually tested"
- Question whether skip markers are appropriate
- This is NOT a success - nothing was verified

Do NOT use ✅ or report PASS/SUCCESS/VERIFIED unless you actually ran `go run . run` and it succeeded.

## Prerequisites

k6 repository must be on `master` branch for testing:
```bash
cd /path/to/k6
git status --porcelain  # must print nothing; otherwise stop and ask the user before switching branches
git checkout master
git pull origin master
```
troubleshooting.md 4.7 KB
# Troubleshooting Guide

Common issues and solutions when documenting k6 features.

## TypeScript Module Resolution

### Error: `Cannot find module 'k6/browser'`

**Cause:** You likely used `npm install` instead of `pnpm install`. The k6-DefinitelyTyped workspace requires pnpm to create proper symlinks for module resolution.

**Fix:**
```bash
cd k6-DefinitelyTyped
pnpm install -w --filter "{./types/k6}..."
```

The first command creates a symlink for `@types/k6` in `node_modules`, which is required for TypeScript module resolution during tests.

### Error: `dtslint is not found`

**Cause:** Missing workspace dependencies.

**Fix:**
```bash
cd k6-DefinitelyTyped
pnpm install -w --filter "{./types/k6}..."
```

Ensure you're using the `--filter` flag to install workspace dependencies correctly.

### Pre-existing Test Failures

**Issue:** The test suite shows errors unrelated to your changes.

**Context:** The k6-DefinitelyTyped test suite may have pre-existing failures. This is normal.

**Action:** Focus on ensuring your NEW types don't introduce ADDITIONAL errors. Compare test output before and after your changes.

## Locating Documentation Files

When testing documentation, files may not be on the current branch.

### Step 1: Check Local Branches

```bash
# Search for branches matching the feature name
git branch | grep -i <feature-name>

# Example:
git branch | grep -i waitforevent
```

### Step 2: Check Remote Branches

If not found locally:

```bash
# Fetch all remote branch info
git fetch --all

# Search remote branches
git branch -r | grep -i <feature-name>

# Example:
git branch -r | grep -i waitforevent
```

### Step 3: Checkout the Branch

Once found:

```bash
# For remote branches, fetch and create local branch in one command
git fetch origin <branch-name>:<branch-name>
git checkout <branch-name>

# Example:
git fetch origin add/page-waitForEvent:add/page-waitForEvent
git checkout add/page-waitForEvent
```

**⚠️ Common Mistake:** Don't run `git checkout origin/branch-name` directly. It creates a detached HEAD state. Always use the fetch command above to create a local tracking branch.

### Step 4: Checkout from PR Number

If given a PR number, use GitHub CLI:

```bash
gh pr checkout <PR_NUMBER>
```

This automatically creates the local branch and checks it out.

### Step 5: Verify Files

After checkout, confirm the documentation files exist:

```bash
# List all changed files in this branch vs main
git diff main --name-only
```

## Link Validation Issues

### Link Returns 404

**Common causes:**

1. **Wrong casing:** `consolemessage` vs `console-message`
1. **Missing hyphens:** `browsercontext` vs `browser-context`
1. **Wrong path structure:** Check actual file/folder names in docs directory

**Fix:**
```bash
# Check the actual file name in the docs
ls -la docs/sources/k6/next/javascript-api/k6-browser/

# Compare with your link path
```

### Can't Extract Links from Diff

**Issue:** The git diff + grep pipeline isn't finding links.

**Debug:**
```bash
# Step-by-step debugging
cd k6-docs

# 1. Check diff has content
git diff main -- docs/sources/k6/next/ | head -20

# 2. Check for added lines
git diff main -- docs/sources/k6/next/ | grep '^\+' | head -20

# 3. Check for URLs
git diff main -- docs/sources/k6/next/ | grep '^\+' | grep 'grafana.com'
```

## agent-browser Issues

### Installation Fails

If `npm install -g agent-browser@0.38.1` fails, check Node.js version:

```bash
node --version  # Should be 18.x or higher
```

Update Node.js if needed, then retry installation.

### Browser Not Installed

After installing agent-browser, install the browser:

```bash
agent-browser install
```

This downloads Chromium for agent-browser to use.

### Command Not Found After Install

Check PATH includes npm global bin directory:

```bash
npm config get prefix
# Should show a directory in your PATH
```

Add to PATH if needed (add to ~/.bashrc or ~/.zshrc):
```bash
export PATH="$(npm config get prefix)/bin:$PATH"
```

## k6 Testing Issues

### Error: `k6: command not found` when running `go run . run`

**Issue:** You're not in the k6 repository directory.

**Fix:**
```bash
# Navigate to k6 repo first
cd /path/to/k6

# Then run the command
go run . run /tmp/test-script.js
```

### Examples Work Locally But Not in Docs

**Issue:** Example has environment-specific code (hardcoded paths, local servers).

**Fix:** Ensure examples use:
- Generic URLs (use `https://quickpizza.grafana.com/` for HTTP examples)
- No hardcoded file paths
- No dependencies on local services unless documented

### k6 Branch Issues

**Issue:** Testing with wrong k6 version.

**Verify:**
```bash
cd /path/to/k6
git branch  # Should show * master
git status  # Should be clean or only local uncommitted changes
```

**IMPORTANT:** k6 must be on `master` branch for testing examples with new features.
typescript-patterns.md 4.2 KB
# TypeScript Definition Patterns

## Basic Method Signature

```typescript
/**
 * Brief description of what the method does.
 *
 * Additional context about when/why to use it.
 *
 * @example
 * ```js
 * // Example showing basic usage
 * const result = page.methodName('arg1');
 * ```
 *
 * @param paramName Description of the parameter.
 * @param options Options to use.
 */
methodName(
    paramName: string | RegExp,
    options?: {
        /** Description of option property. */
        timeout?: number;
    },
): Promise<ReturnType>;
```

## Method Overloads

For methods with different return types based on parameters:

```typescript
// Overload for string input
parse(input: string): ParsedString;

// Overload for buffer input
parse(input: ArrayBuffer): ParsedBuffer;

// Generic overload
parse(input: string | ArrayBuffer): ParsedString | ParsedBuffer;
```

## Browser Event Overloads

Event-based methods need per-event overloads for type safety:

```typescript
// Overload for 'console' event
waitForEvent(
    event: "console",
    optionsOrPredicate?: ((msg: ConsoleMessage) => boolean) | {
        predicate?: (msg: ConsoleMessage) => boolean;
        timeout?: number;
    },
): Promise<ConsoleMessage>;

// Overload for 'request' event
waitForEvent(
    event: "request",
    optionsOrPredicate?: ((req: Request) => boolean) | {
        predicate?: (req: Request) => boolean;
        timeout?: number;
    },
): Promise<Request>;
```

### When to Use Event Overloads

**Rule:** If a method accepts an event name string as the first parameter, create one overload per supported event.

**Why:** Each event type has its own return type (ConsoleMessage vs. Request vs. Response), so TypeScript needs explicit overloads to provide accurate type information.

**How to add a new event:**

1. Copy an existing overload
1. Change the event string literal: `"console"` → `"dialog"`
1. Update the parameter type in predicate: `ConsoleMessage` → `Dialog`
1. Update the return type: `Promise<ConsoleMessage>` → `Promise<Dialog>`

Example adding 'dialog' event:
```typescript
// Overload for 'dialog' event
waitForEvent(
    event: "dialog",
    optionsOrPredicate?: ((dialog: Dialog) => boolean) | {
        predicate?: (dialog: Dialog) => boolean;
        timeout?: number;
    },
): Promise<Dialog>;
```

**Note:** The `optionsOrPredicate` union type (function OR object) is a Playwright pattern that k6-browser mirrors.

## Type Tests

In `types/k6/test/<module>.ts`:

```typescript
// @ts-expect-error - Tests that required parameters are enforced
page.methodName();

// $ExpectType Promise<ReturnType>
page.methodName("argument");

// $ExpectType Promise<ReturnType>
page.methodName("argument", { timeout: 10000 });
```

Test patterns:
- `// @ts-expect-error` - Verifies TypeScript errors on invalid calls
- `// $ExpectType <Type>` - Verifies the return type

## Testing TypeScript Definitions

**IMPORTANT:** Use `pnpm` (not `npm`) to install dependencies. The k6-DefinitelyTyped workspace requires pnpm to create proper symlinks for module resolution.

```bash
cd k6-DefinitelyTyped
pnpm install -w --filter "{./types/k6}..."
pnpm test k6
```

Or use `${CLAUDE_PLUGIN_ROOT}/skills/k6-docs/scripts/test_typescript.sh`

The first command creates a symlink for `@types/k6` in `node_modules`, which is required for TypeScript module resolution to work during tests.

## Troubleshooting

### Error: `Cannot find module 'k6/browser'`

**Cause:** You likely used `npm install` instead of `pnpm install`.

**Fix:**
```bash
cd k6-DefinitelyTyped
pnpm install -w --filter "{./types/k6}..."
```

### Error: `dtslint is not found`

**Cause:** Missing workspace dependencies.

**Fix:**
```bash
cd k6-DefinitelyTyped
pnpm install -w --filter "{./types/k6}..."
```

Ensure you're using the `--filter` flag with the workspace flag `-w`.

### Pre-existing Test Failures

**Context:** The test suite may have pre-existing failures unrelated to your changes.

**Action:** Focus on ensuring your NEW types don't introduce ADDITIONAL errors. Compare test output before and after your changes.

See [Troubleshooting guide](troubleshooting.md) for more help.

## Formatting

Format files with dprint:

```bash
pnpm dprint fmt types/k6/
```

Or use `${CLAUDE_PLUGIN_ROOT}/skills/k6-docs/scripts/format_typescript.sh`
references/checklists/
documentation.md 4.1 KB
# User Documentation Checklist

## Front Matter

- [ ] title matches method signature format
- [ ] description is accurate

## Parameters Table

- [ ] All parameters documented with Type, Default, Description
- [ ] Required params marked as "Required."

## Returns Section

- [ ] Return type is accurate
- [ ] Description is clear

## Examples

**REQUIRED:** Test ALL examples with k6@master. See [Testing workflow](../testing-workflow.md) for complete procedure.

```bash
# Extract example from docs
# Write to /tmp/test-example.js
# Then run:
cd /path/to/k6
go run . run /tmp/test-example.js
```

**Checklist:**
- [ ] Code is complete and runnable
- [ ] Includes proper imports
- [ ] Non-runnable code has `<!-- md-k6:skip -->` comment
- [ ] All runnable examples tested with k6@master
- [ ] All examples pass without errors
- [ ] Examples use generic URLs (not localhost or hardcoded paths)

## Best Practices

- [ ] Uses 1. for ALL numbered list items (not 1., 2., 3.)
- [ ] Helpful and actionable

## Related Section

- [ ] Links sorted ALPHABETICALLY
- [ ] Bidirectional links exist (if A links to B, B links to A)

## Links

**REQUIRED:** Validate ALL added links using this procedure:

### Step 1: Extract Links from Changes

```bash
cd k6-docs
git diff main -- docs/sources/k6/next/ | grep '^\+' | grep -oE 'https://grafana\.com/docs/k6/<K6_VERSION>/[^)\"]+' | sed 's/<K6_VERSION>/next/g' | sort -u
```

This extracts only YOUR added links, not pre-existing ones.

### Step 2: Check Each Link

For each URL from step 1, replace `https://grafana.com` with `http://localhost:3002` and verify:

```bash
# Check multiple links at once
for url in \
  "/docs/k6/next/javascript-api/k6-browser/page/waitforevent/" \
  "/docs/k6/next/javascript-api/k6-browser/request/"
do
  echo "$(curl -s -o /dev/null -w '%{http_code}' http://localhost:3002$url) $url"
done
```

All links must return `200`. Any `404` is a broken link that must be fixed.

### Step 3: Fix Broken Links

Common link issues:
- **Wrong casing:** `consolemessage` vs `console-message`
- **Missing hyphens:** `browsercontext` vs `browser-context`
- **Wrong path:** Check actual file/folder names in docs directory

### Step 4: Re-validate After Fixes

Run validation again to ensure all links return `200`.

**Checklist:**
- [ ] All links extracted with git diff pipeline
- [ ] Each link checked with curl against localhost:3002
- [ ] All links return 200 (no 404s)
- [ ] Broken links fixed and re-validated

## Visual Verification

**REQUIRED:** Use agent-browser to verify rendering. Screenshots catch issues HTTP 200 status cannot detect.

When reviewing screenshots, verify ALL seven criteria:

1. **No 404 errors** - Page content renders, not an error page
1. **Parameters table** - All columns visible (Parameter, Type, Default, Description)
1. **Code blocks** - Syntax highlighting applied (colored keywords)
1. **Navigation** - Breadcrumbs show correct path (e.g., "k6 > JavaScript API > k6-browser > Page > waitForEvent")
1. **Related links section** - Links are styled and clickable
1. **No broken images** - All images load properly
1. **Proper formatting** - Headers, lists, and tables render correctly

**Commands:**
```bash
# Take full-page screenshot (ALWAYS use --full flag for docs)
agent-browser screenshot --full page.png

# Check page title (should not be "404")
agent-browser get title

# Verify related links work
agent-browser snapshot  # Get @refs
agent-browser click "@e42"  # Click link by @ref
```

See [agent-browser reference](../agent-browser-reference.md) for complete command list.

**Checklist:**
- [ ] Method appears in module's API index table (screenshot verified)
- [ ] Method documentation page loads without 404 (screenshot verified)
- [ ] Parameters table renders with all columns (screenshot verified)
- [ ] Code examples render with syntax highlighting (screenshot verified)
- [ ] Related links are clickable and load correct pages (click and screenshot each)
- [ ] Navigation breadcrumbs are correct (screenshot verified)
- [ ] No broken images or formatting issues (screenshot verified)

## Index

- [ ] _index.md updated with new method entry
- [ ] New method row is in **alphabetical order** in the method table
release-notes.md 0.8 KB
# Release Notes Checklist

## Feature Section

- [ ] Heading format: ### \`feature.name\` [#PR](url)
- [ ] Introduction explains what and why
- [ ] Code example is practical and runnable
- [ ] Links to full documentation
- [ ] Mentions related features if applicable

## Writing Style

- [ ] Leads with user value, not technical details
- [ ] Uses active voice
- [ ] No typos or grammatical errors
- [ ] Proper punctuation (especially commas)
- [ ] Uses 1. for all numbered lists

## External Contributors

- [ ] If applicable, thanked with @username
- [ ] Check PR commits against team list in [references/k6-team-members.md](references/k6-team-members.md)

## Code Examples

- [ ] Do NOT require `<!-- md-k6:skip -->` markers in release notes
- [ ] Should be validated when tested
typescript.md 0.7 KB
# TypeScript Definitions Checklist

## Type Definitions

- [ ] JSDoc comments: Clear description, @example with code, @param descriptions
- [ ] Method signature: Correct parameter types, return type, optional params marked with ?
- [ ] Overloads: If method has different return types, are overloads defined?
- [ ] Consistency: Matches style of existing methods in same interface

## Type Tests (in types/k6/test/)

- [ ] Coverage: All method signatures tested
- [ ] @ts-expect-error: Tests for invalid calls
- [ ] $ExpectType: Return types verified for each overload

## Testing

Run each command separately:
1. `pnpm install -w --filter "{./types/k6}..."`
2. `pnpm test k6`

Pre-existing failures may exist - focus on new types not introducing errors
references/templates/
documentation.md 3.1 KB
# User Documentation Template

## Front Matter

```yaml
---
title: 'methodName(param[, options])'
description: 'Module: class.methodName(param[, options]) method'
---
```

## Content Structure

```markdown
# methodName(param[, options])

Brief description of what the method does and when to use it.

| Parameter       | Type   | Default | Description                             |
| --------------- | ------ | ------- | --------------------------------------- |
| param           | string | -       | Required. Description of the parameter. |
| options         | object | `null`  |                                         |
| options.timeout | number | `30000` | Maximum time in milliseconds.           |

### Returns

| Type                | Description                              |
| ------------------- | ---------------------------------------- |
| Promise<ReturnType> | A Promise that fulfills with the result. |

### Examples

#### Example Title

\`\`\`javascript
import http from 'k6/http';
import { check } from 'k6';

export default function () {
  // Example code here
}
\`\`\`

### Best practices

1. **Practice title**: Description of the practice.

### Related

- [Related method](link) - Brief description
```

## Browser Module Example Template

```javascript
import { browser } from 'k6/browser';
import { check } from 'k6';

export const options = {
  scenarios: {
    ui: {
      executor: 'shared-iterations',
      options: {
        browser: {
          type: 'chromium',
        },
      },
    },
  },
};

export default async function () {
  const page = await browser.newPage();

  try {
    // Example code here
  } finally {
    await page.close();
  }
}
```

## Cross-Linking Guidelines

Always add bidirectional links between related methods in the `### Related` section:

1. **Identify related methods**: Methods that work together, handle similar events, or serve complementary purposes
1. **Bidirectional links**: If page A links to page B, page B should link back to page A
1. **Sort alphabetically**: Always list related links in alphabetical order
1. **Group related changes**: When adding cross-links, commit all related files together
1. **Descriptive link text**: Include brief descriptions explaining the relationship

Example (properly sorted):
```markdown
### Related

- [page.on()](link) - Subscribe to page events
- [page.waitForEvent()](link) - Wait for page events with predicate functions
- [page.waitForLoadState()](link) - Wait for load states
- [page.waitForNavigation()](link) - Wait for navigation events
```

## Formatting Rules

1. **Numbered lists**: Always use `1.` for every item (Markdown auto-numbers):
   ```markdown
   <!-- CORRECT -->
   1. First item
   1. Second item
   1. Third item
   ```

1. **Punctuation**: Pay attention to comma placement in compound sentences

1. **Consistency**: Match the formatting style of existing documentation

## Code Validation

- All JavaScript snippets are validated by ESLint
- Use comments to control validation:
  - `<!-- md-k6:skip -->` - Skip snippet execution
  - `<!-- eslint-skip -->` - Skip ESLint validation
  - `<!-- md-k6:nofail -->` - Allow errors in execution
release-notes.md 0.8 KB
# Release Notes Template

```markdown
### `feature.name` [#PR](https://github.com/grafana/k6/pull/PR)

Introduction paragraph explaining what the feature is and why it matters.

Additional context about when to use it and what problem it solves.

The method supports [specific capabilities]:

\`\`\`javascript
import http from 'k6/http';

export default function () {
  // Example showing feature usage
  const response = http.get('https://quickpizza.grafana.com/');
}
\`\`\`

This complements existing [related features](links) by providing [specific benefit].
```

## Important Notes

- Release note examples do NOT require `<!-- md-k6:skip -->` markers
- All examples should be practical and runnable
- Lead with user value, not technical implementation details
- Use active voice and clear language
- Thank external contributors with their @username
references/workflows/
review.md 2.7 KB
# Review Documentation Workflow

Validate k6 documentation across three repositories in parallel using specialized review agents.

## Prerequisites

**agent-browser for visual verification:**
- Run `${CLAUDE_PLUGIN_ROOT}/skills/k6-docs/scripts/check_agent_browser.sh` to install if needed
- See [agent-browser reference](../agent-browser-reference.md) for command list
- Fallback: Use `curl` for HTTP status checks only (no visual verification)

**Local docs server must be running:**
- Automatically confirm `npm start` running in k6-docs at http://localhost:3002, or ask user to start it

**k6 repository on master branch:**
- Required for testing examples: `cd /path/to/k6`, confirm `git status --porcelain` prints nothing (otherwise stop and ask the user), then `git checkout master`

## Initial Setup

Ask user for branch names (or pull from PR if applicable):
- k6-docs branch (e.g., `add/page-waitForEvent`)
- k6-DefinitelyTyped branch (e.g., `add/page-waitForEvent`)
- k6 release branch (e.g., `release-1.5.0` or `release-v1.5.0`)

## Workflow

Launch THREE review agents IN PARALLEL using Task tool in a SINGLE message.

Use prompts from [Subagent prompts](../subagent-prompts.md):
1. TypeScript Review - Validates type definitions and tests using [TypeScript checklist](../checklists/typescript.md)
2. Documentation Review - Validates user docs, links, and examples using [Documentation checklist](../checklists/documentation.md)
3. Release Notes Review - Validates release notes content using [Release notes checklist](../checklists/release-notes.md)

Each agent checks out specified branch and reports structured findings.

## Critical Rules

- **Never chain commands** with `&&` or `;` - run separately (prevents failures)
- **MUST execute code examples:** Use [Testing workflow](../testing-workflow.md) with parallel subagents
- **MUST validate links:** Use git diff + grep + curl pipeline (see [Documentation checklist](../checklists/documentation.md))
- **MUST visual verify:** Use agent-browser for screenshots (see [agent-browser reference](../agent-browser-reference.md))
- **If ALL examples have skip markers:** Report ⚠️ UNTESTED, not ✅ PASS - nothing was verified
- **Pre-existing failures:** Focus on ensuring NEW changes don't add errors (see [Troubleshooting](../troubleshooting.md))

## Final Report Format

After all three subagents complete:

```
# Documentation Review Summary: [FEATURE_NAME]

## Overall Status: [PASS / ISSUES FOUND]

## TypeScript Definitions
[Subagent 1 results]

## User Documentation
[Subagent 2 results]

## Release Notes
[Subagent 3 results]

## Action Items
1. [Required fixes]
2. [Recommended improvements]

## Ready to Merge?
[YES - all checks pass / NO - issues must be fixed first]
```

If issues found, ask user if they want you to fix them.
write.md 5.4 KB
# Write Documentation Workflow

Document k6 features across three repositories: k6-DefinitelyTyped (TypeScript types), k6-docs (user documentation), and k6 (release notes).

## Before Starting

Ask the user for clarification if not already specified:

1. **PR or branch?** - Is there a PR number to fetch with `gh pr checkout <PR>`, or should you check out a branch directly?
1. **Which release?** - What milestone/version is this for? (e.g., `v1.5.0`)
   - Release branches are named `release-X.X.0` or `release-vX.X.0`
   - This format is used in both k6 and k6-DefinitelyTyped repositories
   - If documenting from a PR, **use the PR's milestone when it exists** to decide which doc version(s) get the change.
1. **Repository paths?** - Where are the repositories located? Auto-detect from `pwd` or ask user.

## Setup

- Determine absolute paths to repos before running commands
- For PR number: First `cd /absolute/path/to/repo`, then `gh pr checkout <PR>` (separate commands)
- For branch name: Use `${CLAUDE_PLUGIN_ROOT}/skills/k6-docs/scripts/find_branch.sh`
- k6 must be on `master` branch for testing examples
- Never chain commands with `&&` or `;` - run separately

## Workflow

Create tasks for each documentation type requested, and handle them using parallel subagents.

## 1. User Documentation (k6-docs)

**Base branch:** `main` (k6-docs always branches from main, targeting `docs/sources/k6/next/` for upcoming releases)

**Branch name:** `add/<feature-name>` (e.g., `add/page-waitForEvent`)

Steps:
1. Create `docs/sources/k6/next/javascript-api/<module>/<feature>.md`
1. Use [User documentation template](../templates/documentation.md)
1. Update `docs/sources/k6/next/javascript-api/<module>/_index.md` table
1. Add bidirectional cross-links to related methods (alphabetically sorted)

**Test (REQUIRED):**
```bash
# Start local server
cd k6-docs
npm install
npm start  # Runs at http://localhost:3002
```

Then follow [Documentation checklist](../checklists/documentation.md):
- Validate ALL links (git diff + grep + curl pipeline)
- Visual verification with agent-browser
- Test ALL examples with k6@master (see [Testing workflow](../testing-workflow.md))

**Commit format:**
```
docs: add <module>.<feature> documentation

Adds documentation for <brief description>.

Related: grafana/k6#<PR_NUMBER>
```

Example: `docs: add browser.page.waitForEvent documentation`

**Note:** `Related: grafana/k6#1234` format creates bidirectional GitHub links between repositories.

## 2. TypeScript Definitions (k6-DefinitelyTyped)

**Base branch:** `release-X.X.0` (TypeScript branches from release branch because types are published per k6 version)

**Branch name:** `add/<feature-name>` (e.g., `add/page-waitForEvent`)

Steps:
1. Identify the interface (Page, HTTP, etc.) - see [Repository structure guide](../repository-structure.md)
1. Add method signature to `types/k6/<module>/index.d.ts` - see [TypeScript patterns](../typescript-patterns.md)
1. Add type tests to `types/k6/test/<module>.ts`
1. Format: `${CLAUDE_PLUGIN_ROOT}/skills/k6-docs/scripts/format_typescript.sh`

**Test (REQUIRED):**
```bash
cd k6-DefinitelyTyped
pnpm install -w --filter "{./types/k6}..."
pnpm test k6
```

See [TypeScript checklist](../checklists/typescript.md) for full validation.

**Commit format:**
```
<module>: add TypeScript definitions for <feature>

<Brief description of what was added>

Related: grafana/k6#<PR_NUMBER>
```

Example: `browser: add TypeScript definitions for page.waitForEvent`

### Using Playwright Documentation as Reference

**For browser module only:** k6-browser's API is based on Playwright. Always reference official Playwright documentation to ensure API signatures, parameters, and patterns match established conventions.

```bash
# Search for Playwright documentation
WebSearch: "playwright page.waitForEvent documentation"

# Fetch specific Playwright docs page
WebFetch: url="https://playwright.dev/docs/api/class-page#page-wait-for-event"
         prompt="Explain the page.waitForEvent method parameters and usage"
```

**Note:** k6-browser may have slight differences from Playwright (e.g., different default timeouts, missing features). Always verify the actual k6 implementation, but use Playwright docs as your baseline reference.

## 3. Release Notes (k6)

**Branch:** `release-X.X.0` or `release-vX.X.0` (same repository, use existing release branch)

Steps:
1. Edit `release notes/v{VERSION}.md`
1. Use [Release notes template](../templates/release-notes.md)
1. Check PR commits for external contributors - see [k6 team members list](../k6-team-members.md)
   - Follow the 3-step identification process
   - Remember: Git shows real names, not GitHub handles
   - If team list is outdated, run `${CLAUDE_PLUGIN_ROOT}/skills/k6-docs/scripts/update_team_members.sh` to refresh
1. Thank external contributors: `Thanks, @username for your contribution! 🎉`

**Test examples (REQUIRED):**

Release note examples do NOT need `<!-- md-k6:skip -->` markers (they demonstrate features, not runnable tests). However, you should still verify they're syntactically correct and follow k6 patterns.

**Commit format:**
```
release notes: add <feature> to vX.X.0

Documents the new <feature> that allows <brief description>.

Related: #<PR_NUMBER>
```

Example: `release notes: add page.waitForEvent to v1.5.0`

**Note:** `Related: #1234` format (without repo prefix) because this is in the same repository as the PR.

## Verification

After completing all three, use [Review workflow](review.md) to validate the work.
scripts/
check_agent_browser.sh 0.5 KB
#!/usr/bin/env bash
# Check if agent-browser is installed and install if needed
# Usage: check_agent_browser.sh

if command -v agent-browser &> /dev/null; then
    echo "✓ agent-browser is installed"
    exit 0
fi

echo "agent-browser not found. Install it? (y/n)"
read -r REPLY

if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "Installing agent-browser..."
    npm install -g agent-browser@0.38.1
    agent-browser install
    echo "✓ agent-browser installed"
else
    echo "Skipping agent-browser installation"
    exit 0
fi
fetch_pr.sh 0.2 KB
#!/usr/bin/env bash
# Fetch and checkout a PR in the current repository
# Usage: fetch_pr.sh <PR_NUMBER>

if [ -z "$1" ]; then
    echo "Usage: $0 <PR_NUMBER>"
    exit 1
fi

gh pr checkout "$1"
find_branch.sh 0.9 KB
#!/usr/bin/env bash
# Find and checkout a branch by feature name
# Usage: find_branch.sh <feature-name>

if [ -z "$1" ]; then
    echo "Usage: $0 <feature-name>"
    exit 1
fi

FEATURE="$1"

if [ -n "$(git status --porcelain)" ]; then
    echo "Error: working tree has uncommitted changes; commit or stash them before switching branches." >&2
    exit 1
fi

echo "Searching local branches..."
LOCAL_BRANCH=$(git branch | grep -iF "$FEATURE" | head -1 | tr -d ' *')

if [ -n "$LOCAL_BRANCH" ]; then
    echo "Found local branch: $LOCAL_BRANCH"
    git checkout "$LOCAL_BRANCH"
    exit 0
fi

echo "Searching remote branches..."
git fetch --all
REMOTE_BRANCH=$(git branch -r | grep -iF "$FEATURE" | head -1 | sed 's/.*origin\///' | tr -d ' ')

if [ -n "$REMOTE_BRANCH" ]; then
    echo "Found remote branch: $REMOTE_BRANCH"
    git fetch origin "$REMOTE_BRANCH:$REMOTE_BRANCH"
    git checkout "$REMOTE_BRANCH"
    exit 0
fi

echo "No branch found for: $FEATURE"
exit 1
format_typescript.sh 0.2 KB
#!/usr/bin/env bash
# Format TypeScript definitions using dprint
# Usage: format_typescript.sh [path_to_k6_DefinitelyTyped]

REPO_PATH="${1:-.}"
cd "$REPO_PATH" || exit 1

echo "Formatting TypeScript files..."
pnpm dprint fmt types/k6/
test_typescript.sh 0.3 KB
#!/usr/bin/env bash
# Test TypeScript definitions in k6-DefinitelyTyped
# Usage: test_typescript.sh [path_to_k6_DefinitelyTyped]

REPO_PATH="${1:-.}"
cd "$REPO_PATH" || exit 1

echo "Installing dependencies..."
pnpm install -w --filter "{./types/k6}..."

echo "Running TypeScript tests..."
pnpm test k6
update_team_members.sh 1.4 KB
#!/usr/bin/env bash
# Update k6 team members list from GitHub API
# Usage: update_team_members.sh [output-file]

set -e

# Resolve default output file relative to the skill directory (one level above scripts/)
if [ -n "$1" ]; then
    OUTPUT_FILE="$1"
else
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
    OUTPUT_FILE="${SCRIPT_DIR}/references/k6-team-members.md"
fi

echo "Fetching k6 team members from GitHub..."

# Fetch all members of grafana/k6 repository collaborators with push+ access
# This gets people who have write/admin access to the k6 repo
MEMBERS=$(gh api repos/grafana/k6/collaborators \
    --paginate \
    --slurp \
    --jq '[.[][] | select(.permissions.push == true or .permissions.admin == true) | {login: .login, name: .name}] | sort_by(.login | ascii_downcase)')

# Start building the markdown file
cat > "$OUTPUT_FILE" <<'EOF'
# Grafana k6 Team Members

Do NOT thank these people as external contributors in release notes:

| GitHub Handle          | Name                    |
| ---------------------- | ----------------------- |
EOF

# Add each member to the table
echo "$MEMBERS" | jq -r '.[] | "| \(.login) | \(.name // .login) |"' >> "$OUTPUT_FILE"

echo ""
echo "✓ Updated $OUTPUT_FILE with $(echo "$MEMBERS" | jq 'length') team members"

# Show a preview
echo ""
echo "Preview (first 10 members):"
head -15 "$OUTPUT_FILE" | tail -10
validate_links.sh 1.1 KB
#!/usr/bin/env bash
# Validate all documentation links in k6-docs branch
# Usage: validate_links.sh <docs-repo-path>

if [ -z "$1" ]; then
    echo "Usage: $0 <docs-repo-path>"
    exit 1
fi

DOCS_PATH="$1"
cd "$DOCS_PATH" || exit 1

echo "Extracting new links from git diff..."
LINKS=$(git diff main -- docs/sources/k6/next/ | grep '^\+' | grep -oE 'https://grafana\.com/docs/k6/<K6_VERSION>/[^)\"]+' | sed 's/<K6_VERSION>/next/g' | sort -u)

if [ -z "$LINKS" ]; then
    echo "No new links found"
    exit 0
fi

echo "Checking links against local server (http://localhost:3002)..."
echo ""

FAILED=0
PASSED=0

while IFS= read -r link; do
    # Convert grafana.com link to localhost
    LOCAL_URL=$(echo "$link" | sed 's|https://grafana.com|http://localhost:3002|')

    STATUS=$(curl --connect-timeout 5 --max-time 10 -s -o /dev/null -w '%{http_code}' "$LOCAL_URL")

    if [ "$STATUS" = "200" ]; then
        echo "✓ $LOCAL_URL"
        ((PASSED++))
    else
        echo "✗ $LOCAL_URL (HTTP $STATUS)"
        ((FAILED++))
    fi
done <<< "$LINKS"

echo ""
echo "Results: $PASSED passed, $FAILED failed"

if [ $FAILED -gt 0 ]; then
    exit 1
fi

exit 0

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/grafana/skills/blob/main/LICENSE