{"name": "payload", "version": "0.1.0", "hash": "sha256:ded818ed0719f4270dd30517c877de7fb8342b3cb522017e7f6012d50b983275", "files": {"ABSORB_REPORT.md": "# Absorb report: payload\n\n- **Source:** https://github.com/payloadcms/payload at `7f2d2ff2e69c`\n- **Licence:** MIT\n- **Project names searched for:** payloadcms_payload, payload, payload-monorepo\n\n## What was absorbed\n\n| Piece | Kind | Class | Project names | Project paths |\n|---|---|---|---|---|\n| audit-dependencies | skill | mixed |  | packages/plugin-sentry, tools/releaser, tools/scripts |\n| generate-translations | skill | mixed | payload ×5 | packages/ui, packages/payload, packages/next, packages/translations/src/languages/en.ts, packages/translations/src/clientKeys.ts, tools/scripts, tools/scripts/package.json |\n| payload-accessibility | skill | mixed | payload ×9 | test/a11y/e2e.spec.ts, test/a11y/WCAG.audit.spec.ts, test/a11y/screen-reader.spec.ts, test/a11y/helpers.ts |\n| record-pr-demo | skill | mixed | payload ×47 |  |\n| triage-ci-flake | skill | mixed | payload ×4 | test/admin/e2e/list-view/e2e.spec.ts, test/plugin-import-export/e2e.spec.ts, test/i18n/e2e.spec.ts |\n| ui4 | skill | mixed | payload ×5 | packages/ui/src/icons, packages/ui/src/icons/Chevron/index.tsx, packages/ui/src/css, packages/ui/src/css/spacing.css, packages/ui/src/css/colors.css, packages/ui/src/css/typography.css, packages/ui/src/css/radius.css, test/v4/collections, test/v4, packages/ui/src/elements/Button/index.css, test/fields/collections |\n| ui4-convert-tests | skill | mixed | payload ×9 | packages/ui/src, test/__helpers/e2e, test/query-presets/e2e.spec.ts, test |\n| ui4-review | skill | mixed |  | packages/ui/src/css/elevations.css |\n| analyze-issue | command | mechanics |  |  |\n| respond-to-discussion-features | command | mixed | payload ×6 |  |\n| triage | command | mechanics |  |  |\n| hooks/post-write-format.sh | hook-file | mechanics |  |  |\n| PostToolUse [Write] | hook | mechanics |  |  |\n| permission rules | permissions | mechanics |  |  |\n| playwright | mcp-server | mechanics |  |  |\n| payload | mcp-server | mechanics |  |  |\n\n## Needs review before sharing\n\nThese pieces mention the project by name or lean on its files. Move those facts into configuration, or keep the piece out of a shared starter.\n\n- **audit-dependencies** (skill): paths packages/plugin-sentry, tools/releaser, tools/scripts\n- **generate-translations** (skill): names payload; paths packages/ui, packages/payload, packages/next, packages/translations/src/languages/en.ts, packages/translations/src/clientKeys.ts, tools/scripts, tools/scripts/package.json\n- **payload-accessibility** (skill): names payload; paths test/a11y/e2e.spec.ts, test/a11y/WCAG.audit.spec.ts, test/a11y/screen-reader.spec.ts, test/a11y/helpers.ts\n- **record-pr-demo** (skill): names payload\n- **triage-ci-flake** (skill): names payload; paths test/admin/e2e/list-view/e2e.spec.ts, test/plugin-import-export/e2e.spec.ts, test/i18n/e2e.spec.ts\n- **ui4** (skill): names payload; paths packages/ui/src/icons, packages/ui/src/icons/Chevron/index.tsx, packages/ui/src/css, packages/ui/src/css/spacing.css, packages/ui/src/css/colors.css, packages/ui/src/css/typography.css, packages/ui/src/css/radius.css, test/v4/collections, test/v4, packages/ui/src/elements/Button/index.css, test/fields/collections\n- **ui4-convert-tests** (skill): names payload; paths packages/ui/src, test/__helpers/e2e, test/query-presets/e2e.spec.ts, test\n- **ui4-review** (skill): paths packages/ui/src/css/elevations.css\n- **respond-to-discussion-features** (command): names payload\n- **analyze-issue**: was a slash command; now a skill\n- **respond-to-discussion-features**: was a slash command; now a skill\n- **triage**: was a slash command; now a skill\n\n## Not absorbed\n\n- instruction files (AGENTS.md): they describe the project, so they stay with it. Pass --with-instructions to absorb them for review\n- `enableAllProjectMcpServers` in .claude/settings.json: a Claude Code setting, not part of the harness mechanics\n- `enabledMcpjsonServers` in .claude/settings.json: a Claude Code setting, not part of the harness mechanics\n- `enabledPlugins` in .claude/settings.json: a Claude Code setting, not part of the harness mechanics\n- `extraKnownMarketplaces` in .claude/settings.json: a Claude Code setting, not part of the harness mechanics\n- `skillOverrides` in .claude/settings.json: a Claude Code setting, not part of the harness mechanics\n\n## Self-test\n\nNo case could be generated.\n1 hook(s) were absorbed. A hook that guards something is only proven once a case shows it blocking: add `block` and `allow` cases for each, then run `baudrier selftest`.\n", "ATTRIBUTION.md": "# Attribution: payload\n\nThis harness was absorbed from https://github.com/payloadcms/payload at commit `7f2d2ff2e69ce84f544db38985272092aa39fb7e` on 2026-11-26 with `baudrier absorb`.\n\n- **Licence:** MIT. Licence and notice files kept unchanged in this folder: `LICENSE.md`.\n- **Credit:** every file listed below is the work of the source repository's authors. Files were copied unchanged, except that hook commands name their folder as `${HARNESS_HOOKS}` and slash commands were wrapped as skills.\n\n## Absorbed files\n\n- `skills/audit-dependencies/SKILL.md` (skill)\n- `skills/audit-dependencies/agents/openai.yaml` (skill)\n- `skills/generate-translations/SKILL.md` (skill)\n- `skills/payload-accessibility/SKILL.md` (skill)\n- `skills/payload-accessibility/references/change-assessment.md` (skill)\n- `skills/payload-accessibility/references/testing.md` (skill)\n- `skills/payload-accessibility/references/wcag-2.2-aa.md` (skill)\n- `skills/record-pr-demo/SKILL.md` (skill)\n- `skills/record-pr-demo/references/publishing.md` (skill)\n- `skills/record-pr-demo/references/recording-jobs.md` (skill)\n- `skills/record-pr-demo/references/recording.md` (skill)\n- `skills/record-pr-demo/references/window-chrome.md` (skill)\n- `skills/record-pr-demo/scripts/WindowChrome/index.mjs` (skill)\n- `skills/record-pr-demo/scripts/WindowChrome/sidebar.mjs` (skill)\n- `skills/record-pr-demo/scripts/accessibility-demo.mjs` (skill)\n- `skills/record-pr-demo/scripts/accessibility-demo.test.mjs` (skill)\n- `skills/record-pr-demo/scripts/annotation-demo.mjs` (skill)\n- `skills/record-pr-demo/scripts/annotation-demo.test.mjs` (skill)\n- `skills/record-pr-demo/scripts/capture-demo.mjs` (skill)\n- `skills/record-pr-demo/scripts/capture-demo.test.mjs` (skill)\n- `skills/record-pr-demo/scripts/circle-demo.test.mjs` (skill)\n- `skills/record-pr-demo/scripts/convert-demo.mjs` (skill)\n- `skills/record-pr-demo/scripts/convert-demo.test.mjs` (skill)\n- `skills/record-pr-demo/scripts/keyboard-demo.mjs` (skill)\n- `skills/record-pr-demo/scripts/keyboard-demo.test.mjs` (skill)\n- `skills/record-pr-demo/scripts/prepare-demo.mjs` (skill)\n- `skills/record-pr-demo/scripts/prepare-demo.test.mjs` (skill)\n- `skills/record-pr-demo/scripts/presentation-demo.mjs` (skill)\n- `skills/record-pr-demo/scripts/presentation-demo.test.mjs` (skill)\n- `skills/record-pr-demo/scripts/preview-chrome.mjs` (skill)\n- `skills/record-pr-demo/scripts/preview-chrome.test.mjs` (skill)\n- `skills/record-pr-demo/scripts/preview/accessibility-application.html` (skill)\n- `skills/record-pr-demo/scripts/preview/application.html` (skill)\n- `skills/record-pr-demo/scripts/preview/index.html` (skill)\n- `skills/record-pr-demo/scripts/preview/index.mjs` (skill)\n- `skills/record-pr-demo/scripts/record-demo.mjs` (skill)\n- `skills/record-pr-demo/scripts/record-demo.test.mjs` (skill)\n- `skills/record-pr-demo/scripts/recording-job.mjs` (skill)\n- `skills/record-pr-demo/scripts/recording-job.test.mjs` (skill)\n- `skills/record-pr-demo/scripts/scroll-demo.mjs` (skill)\n- `skills/record-pr-demo/scripts/scroll-demo.test.mjs` (skill)\n- `skills/record-pr-demo/scripts/sidebar-layout.test.mjs` (skill)\n- `skills/record-pr-demo/scripts/window-chrome.test.mjs` (skill)\n- `skills/triage-ci-flake/SKILL.md` (skill)\n- `skills/triage-ci-flake/agents/openai.yaml` (skill)\n- `skills/ui4/SKILL.md` (skill)\n- `skills/ui4-convert-tests/SKILL.md` (skill)\n- `skills/ui4-review/SKILL.md` (skill)\n- `skills/analyze-issue/SKILL.md` (command)\n- `skills/respond-to-discussion-features/SKILL.md` (command)\n- `skills/triage/SKILL.md` (command)\n- `hooks/post-write-format.sh` (hook-file)\n", "LICENSE.md": "MIT License\n\nCopyright (c) 2018-2026 Payload CMS, LLC <info@payloadcms.com>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", "harness.yaml": "$schema: https://harnessprotocol.io/schema/v1/harness.schema.json\nversion: '1'\nkind: profile\nmetadata:\n  name: payload\n  description: 'How the Payload repository runs its agents: format on write, triage\n    commands for issues and CI flakes, and review skills.'\n  version: 0.1.0\n  license: MIT\nskills:\n- name: audit-dependencies\n  source: ./skills/audit-dependencies\n- name: generate-translations\n  source: ./skills/generate-translations\n- name: payload-accessibility\n  source: ./skills/payload-accessibility\n- name: record-pr-demo\n  source: ./skills/record-pr-demo\n- name: triage-ci-flake\n  source: ./skills/triage-ci-flake\n- name: ui4\n  source: ./skills/ui4\n- name: ui4-convert-tests\n  source: ./skills/ui4-convert-tests\n- name: ui4-review\n  source: ./skills/ui4-review\n- name: analyze-issue\n  source: ./skills/analyze-issue\n- name: respond-to-discussion-features\n  source: ./skills/respond-to-discussion-features\n- name: triage\n  source: ./skills/triage\nx-hooks:\n  runtime: claude-code\n  files: ./hooks\n  handlers:\n  - event: PostToolUse\n    matcher: Write\n    command: ${HARNESS_HOOKS}/post-write-format.sh\npermissions:\n  tools:\n    allow:\n    - Bash(gh issue view:*)\n    - Bash(gh pr view:*)\n    - Bash(gh release view:*)\n    - Bash(gh run list:*)\n    - Bash(gh run view:*)\n    - Bash(git branch:*)\n    - Bash(git describe:*)\n    - Bash(git diff:*)\n    - Bash(git log:*)\n    - Bash(git ls-files:*)\n    - Bash(git remote:*)\n    - Bash(git rev-parse:*)\n    - Bash(git show:*)\n    - Bash(git status)\n    - Bash(pnpm --version)\n    - Bash(pnpm audit:*)\n    - Bash(pnpm install)\n    - Bash(pnpm list:*)\n    - Bash(pnpm run:*)\n    - Bash(pnpm turbo:*)\n    - Bash(pnpm view:*)\n    - Bash(pnpm why:*)\n    - Bash(pwd)\n    - Bash(which:*)\n    - Skill(superpowers:brainstorming)\n    - Skill(superpowers:executing-plans)\n    - Skill(superpowers:requesting-code-review)\n    - Skill(superpowers:subagent-driven-development)\n    - Skill(superpowers:systematic-debugging)\n    - Skill(superpowers:testing-anti-patterns)\n    - Skill(superpowers:using-git-worktrees)\n    - Skill(superpowers:writing-plans)\n    - Skill(superpowers:writing-skills)\n    - WebFetch(domain:docs.aws.amazon.com)\n    - WebFetch(domain:docs.claude.com)\n    - WebFetch(domain:github.com)\n    - WebFetch(domain:payloadcms.com)\n    - WebFetch(domain:pure.md)\n    - WebFetch(domain:raw.githubusercontent.com)\n    - WebFetch(domain:www.anthropic.com)\n    - WebFetch(domain:www.npmjs.com)\n    - WebSearch\nmcp-servers:\n  playwright:\n    transport: stdio\n    command: pnpm\n    args:\n    - dlx\n    - '@playwright/mcp@latest'\n    - --caps=vision,verify,tracing,devtools\n    - --isolated\n    - --headless\n    - --browser\n    - chromium\n  payload:\n    transport: streamable-http\n    url: http://localhost:3000/api/mcp?overrideAccess=true\nx-origin:\n  repository: https://github.com/payloadcms/payload\n  commit: 7f2d2ff2e69ce84f544db38985272092aa39fb7e\n  license: MIT\n  license_basis: detected\n  license_files:\n  - LICENSE.md\n  absorbed_at: '2026-11-26'\n", "hooks/post-write-format.sh": "#!/bin/bash\n\n# Post-write hook to format files after creating\n# This is the bash equivalent of lint-staged in package.json\n\n# To test this file directly via cli:\n# echo '{\"tool_input\": {\"file_path\": \"path/to/your/file\"}}' | .claude/hooks/post-write-format.sh\n\n# Read JSON from stdin and extract file path\nFILE=$(jq -r '.tool_input.file_path' 2>/dev/null)\n\nif [ -z \"$FILE\" ] || [ \"$FILE\" = \"null\" ]; then\n  exit 0\nfi\n\n# Check if file exists\nif [ ! -f \"$FILE\" ]; then\n  exit 0\nfi\n\n# Format based on file type\ncase \"$FILE\" in\n  *.cjs|*.css|*.cts|*.graphql|*.html|*.json|*.jsonc|*.mjs|*.mts|*.scss|*.toml|*.yaml|*.yml|*/.swcrc)\n    pnpm oxfmt \"$FILE\" >/dev/null 2>&1\n    ;;\n  *.md|*.mdx)\n    pnpm oxfmt \"$FILE\" >/dev/null 2>&1\n    if command -v markdownlint >/dev/null 2>&1; then\n      markdownlint -i node_modules \"$FILE\" >/dev/null 2>&1\n    fi\n    ;;\n  *.js|*.jsx|*.ts|*.tsx)\n    pnpm oxlint --fix --no-error-on-unmatched-pattern \"$FILE\" >/dev/null 2>&1\n    pnpm oxfmt \"$FILE\" >/dev/null 2>&1\n    ;;\nesac\n\nexit 0\n", "skills/analyze-issue/SKILL.md": "---\nname: analyze-issue\ndescription: Analyze a GitHub issue and create a resolution plan\nargument-hint: <issue-number-or-url>\n---\n\nDeep-dive on the GitHub issue provided in $ARGUMENTS. Find the problem and generate a plan. Do not write code. Explain the problem clearly and propose a comprehensive plan to solve it.\n\nPROMPT for the issue number or URL if not provided, and stop here.\n\nSteps:\n\n1. Fetch issue data using: `gh issue view $ARGUMENTS --json author,title,number,body,comments,labels`\n2. Parse the JSON response to extract:\n   - Title and number\n   - Description (body)\n   - All comments with authors\n   - Labels\n3. Format the issue context clearly\n4. Review the issue context and details\n5. Examine the relevant parts of the codebase. Analyze the code thoroughly until you have a solid understanding of how it works.\n6. Explain the issue in detail, including the problem and its root cause. There is no guarantee the issue is valid, so be critical and thorough in your analysis.\n7. Create a comprehensive plan to solve the issue. The plan should include:\n   - Required code changes\n   - Potential impacts on other parts of the system\n   - Necessary tests to be written or updated\n   - Documentation updates\n   - Performance considerations\n   - Security implications\n   - Backwards compatibility (if applicable)\n   - Include the reference link to the source issue and any related discussions\n8. Think deeply about all aspects of the task. Consider edge cases, potential challenges, and best practices for addressing the issue.\n\n**IMPORTANT: ONLY CREATE A PLAN. DO NOT WRITE ANY CODE.** Your task is to create a thorough, comprehensive strategy for understanding and resolving the issue.\n", "skills/audit-dependencies/SKILL.md": "---\nname: audit-dependencies\ndescription: Use when fixing dependency vulnerabilities, running pnpm audit, or when the audit-dependencies CI check fails\n---\n\n# Audit Dependencies\n\n## Overview\n\nFix dependency vulnerabilities reported by `.github/workflows/audit-dependencies.sh`. Prefer fixes in this order: direct dependency bump > lockfile update > pnpm override. Every override requires justification for why simpler approaches aren't feasible.\n\n## Core Workflow\n\n```dot\ndigraph audit {\n    \"Run audit script\" [shape=box];\n    \"Group by package\" [shape=box];\n    \"Trace dependency chain\" [shape=box];\n    \"Can bump direct dep?\" [shape=diamond];\n    \"Research breaking changes\" [shape=box];\n    \"Breaking changes acceptable?\" [shape=diamond];\n    \"Apply direct bump\" [shape=box];\n    \"Is version pinned or ranged?\" [shape=diamond];\n    \"Lockfile update\" [shape=box];\n    \"Apply pnpm override\" [shape=box];\n    \"More packages?\" [shape=diamond];\n    \"Present plan to user\" [shape=box];\n    \"Install and verify\" [shape=box];\n    \"Build and verify\" [shape=box];\n    \"Commit and create PR\" [shape=box];\n\n    \"Run audit script\" -> \"Group by package\";\n    \"Group by package\" -> \"Trace dependency chain\";\n    \"Trace dependency chain\" -> \"Can bump direct dep?\";\n    \"Can bump direct dep?\" -> \"Research breaking changes\" [label=\"yes\"];\n    \"Can bump direct dep?\" -> \"Is version pinned or ranged?\" [label=\"no\"];\n    \"Research breaking changes\" -> \"Breaking changes acceptable?\";\n    \"Breaking changes acceptable?\" -> \"Apply direct bump\" [label=\"yes\"];\n    \"Breaking changes acceptable?\" -> \"Is version pinned or ranged?\" [label=\"no\"];\n    \"Is version pinned or ranged?\" -> \"Lockfile update\" [label=\"ranged - fix is in range\"];\n    \"Is version pinned or ranged?\" -> \"Apply pnpm override\" [label=\"pinned - explain why\"];\n    \"Apply direct bump\" -> \"More packages?\";\n    \"Lockfile update\" -> \"More packages?\";\n    \"Apply pnpm override\" -> \"More packages?\";\n    \"More packages?\" -> \"Trace dependency chain\" [label=\"yes\"];\n    \"More packages?\" -> \"Present plan to user\" [label=\"no\"];\n    \"Present plan to user\" -> \"Install and verify\";\n    \"Install and verify\" -> \"Build and verify\";\n    \"Build and verify\" -> \"Commit and create PR\";\n}\n```\n\n## Step-by-Step\n\n### 1. Run the Audit Script\n\n```bash\n./.github/workflows/audit-dependencies.sh $ARGUMENTS\n```\n\n`$ARGUMENTS` is the severity passed to the skill (defaults to `high` if omitted). The script runs `pnpm audit --prod --json` and filters for actionable vulnerabilities (those with a patched version available). `high` includes `critical`.\n\nParse the output to build a deduplicated list of vulnerable packages with:\n\n- Package name and current version\n- Fixed version requirement\n- Full dependency chain (e.g., `packages/plugin-sentry > @sentry/nextjs > rollup`)\n\n### 2. For Each Vulnerable Package\n\n#### Trace the dependency chain\n\nIdentify whether the vulnerable package is:\n\n- **Direct dependency**: Listed in a workspace package's `package.json`\n- **Transitive dependency**: Pulled in by another package\n\n#### Try direct bump first\n\nFor transitive deps, walk up the chain to find the nearest package you control:\n\n1. Check if bumping the **parent package** resolves the vulnerability\n   - `pnpm view <parent>@latest dependencies.<vulnerable-pkg>`\n   - Check intermediate versions too (the fix may exist in a minor bump)\n2. If the parent bump resolves it, research breaking changes:\n   - Check changelogs/release notes\n   - Search GitHub issues for compatibility problems\n   - Review the API surface used in this repo (read the source files)\n   - Check if the version range crosses a major version boundary\n3. Present findings to user with risk assessment\n\n**Parallelize research**: When multiple packages need breaking change analysis, dispatch parallel agents (one per package) to research simultaneously.\n\n#### Check if a lockfile update is sufficient\n\nBefore reaching for an override, check whether the parent's version specifier is **pinned** (exact version like `3.10.3`) or **ranged** (like `^2.3.1`, `~4.0.3`):\n\n```bash\npnpm view <parent> dependencies.<vulnerable-pkg>\n```\n\nIf the range already includes the fixed version, a lockfile update is all that's needed:\n\n```bash\npnpm update <vulnerable-pkg> --recursive\n```\n\nNo `package.json` changes required — the lockfile was just stale.\n\n#### Fall back to override only when justified\n\nAdd a pnpm override in root `package.json` only when:\n\n- The parent pins an exact version that doesn't satisfy the fix\n- No version of the parent package fixes the vulnerability\n- The parent bump has high breaking change risk (major API changes, no test coverage, requires code changes across many files)\n- The user explicitly decides to defer the parent bump to a separate PR\n\nOverride format: `\"<parent>><vulnerable-pkg>\": \"^<fixed-version>\"`\n\n**Override syntax rules:**\n\n- Use `^` ranges, not `>=`. `>=` can cross major versions and cause unexpected resolutions (e.g., `\"picomatch\": \">=2.3.2\"` can resolve to 4.x).\n- pnpm only supports single-level parent scoping: `\"parent>pkg\"` works, `\"grandparent>parent>pkg\"` does not.\n- pnpm does not support version selectors in override keys: `\"pkg@^2\"` does not work.\n- If the same vulnerable package appears through many transitive paths, a global override may be needed. Be careful that it doesn't affect unrelated consumers on a different major version — use parent-scoped overrides when the package spans multiple major versions across the tree.\n- pnpm only honors `overrides` in the root workspace `package.json`. Overrides in workspace packages are ignored.\n\nBefore adding any override, verify the target version exists:\n\n```bash\npnpm view <pkg>@<version> version\n```\n\n### 3. Present Plan to User\n\nBefore applying fixes, present a summary table to the user showing each vulnerability, the proposed fix strategy (direct bump / lockfile update / override), and justification. Get confirmation before proceeding.\n\n### 4. Apply Fixes\n\n- Edit `package.json` files for direct bumps\n- Run `pnpm update <pkg> --recursive` for lockfile-only fixes\n- Edit root `package.json` `pnpm.overrides` for overrides (keep alphabetical)\n- If a direct bump changes behavior, update consuming code (e.g., adding `allowOverwrite: true` when an API default changes)\n\n### 5. Install and Verify\n\n```bash\npnpm install\n```\n\nIf install fails due to native build errors (e.g., `better-sqlite3`), fall back to:\n\n```bash\npnpm install --ignore-scripts\n```\n\nThen re-run the audit script with the same severity:\n\n```bash\n./.github/workflows/audit-dependencies.sh $ARGUMENTS\n```\n\nThe audit script must exit 0. If vulnerabilities remain, check for additional instances of the same dependency in other workspace packages.\n\n### 6. Build and Verify\n\n```bash\npnpm run build:core\n```\n\nFor packages with changed dependencies, also run their specific build:\n\n```bash\npnpm run build:<package-name>\n```\n\n### 7. Look Up CVEs\n\nFor each fixed vulnerability, find the GitHub Security Advisory (GHSA):\n\n- Check `https://github.com/<org>/<repo>/security/advisories` for each package\n- Search the web for `<package-name> GHSA <fixed-version>`\n- Record: GHSA ID, CVE ID, severity, one-line description\n- Prefer GHSA links (`https://github.com/advisories/GHSA-xxxx-xxxx-xxxx`) over NVD links\n\n**Parallelize CVE lookups**: Dispatch parallel agents to search for CVEs across all packages simultaneously.\n\n### 8. Commit and Create PR\n\nCommit with conventional commit format:\n\n```\nfix(deps): resolve $ARGUMENTS severity audit vulnerabilities\n```\n\nCreate PR using `gh pr create` with this body structure:\n\n```markdown\n# Overview\n\n[What the PR fixes, mention `pnpm audit --prod`]\n\n## Key Changes\n\n- **[Package name] in [workspace path]**\n  - [old version] → [new version]. Fixes [GHSA-xxxx-xxxx-xxxx](https://github.com/advisories/GHSA-xxxx-xxxx-xxxx) ([description]).\n  - [Why this approach: direct bump because X / lockfile update because Y / override because Z]\n  - [Any code changes required by the bump]\n\n## Design Decisions\n\n[Why direct bumps were preferred, justification for any remaining overrides]\n```\n\n## Common Mistakes\n\n| Mistake                                           | Fix                                                                                                                                                         |\n| ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Jumping straight to overrides                     | Check: can you bump the parent? If not, does the semver range already allow the fix (lockfile update)? Only then override.                                  |\n| Using `>=` in override ranges                     | Use `^` to stay within the same major version. `>=2.3.2` can resolve to 4.x.                                                                                |\n| Not checking pinned vs ranged                     | `pnpm view <parent> dependencies.<pkg>` — if ranged and the fix is in range, just `pnpm update`.                                                            |\n| Nested override scoping (`a>b>c`)                 | pnpm only supports single-level: `\"parent>pkg\"`. For deeper chains, override the direct parent or use a global override.                                    |\n| Version selectors in override keys (`pkg@^2`)     | Not supported by pnpm. Use parent-scoped or global overrides instead.                                                                                       |\n| Global override affecting multiple major versions | `\"picomatch\": \">=4.0.4\"` forces all picomatch to 4.x, breaking consumers that need 2.x. Scope overrides to the parent when a package spans multiple majors. |\n| Not checking all workspace packages               | Same dep may appear in multiple `package.json` files (e.g., `changelogen` in both `tools/releaser` and `tools/scripts`)                                     |\n| Overriding with a nonexistent version             | Verify the target version exists with `pnpm view` before installing                                                                                         |\n| Not falling back to `--ignore-scripts`            | Pre-existing native build failures block `pnpm install`; use `--ignore-scripts` to get lockfile updated                                                     |\n| Missing code changes for breaking bumps           | If a bump changes API defaults, update the calling code                                                                                                     |\n| Forgetting advisory links in PR                   | Always look up and include GHSA links for each vulnerability                                                                                                |\n| Applying fixes without user confirmation          | Present the full plan (strategy per vuln + justification) and get confirmation before making changes                                                        |\n", "skills/audit-dependencies/agents/openai.yaml": "policy:\n  allow_implicit_invocation: false\n", "skills/generate-translations/SKILL.md": "---\nname: generate-translations\ndescription: Use when new translation keys are added to packages to generate new translations strings\nallowed-tools: Write, Bash(date:*), Bash(mkdir -p *)\n---\n\n# Translation Generation Guide\n\nPayload has two separate translation systems:\n\n1. **Core Translations** - for core Payload packages (packages/ui, packages/payload, packages/next)\n2. **Plugin Translations** - for plugins (packages/plugin-\\*)\n\n## Table of Contents\n\n- [1. Core Translations](#1-core-translations)\n- [2. Plugin Translations](#2-plugin-translations)\n  - [Scaffolding New Plugin Translations](#scaffolding-new-plugin-translations)\n- [Important Notes](#important-notes)\n\n---\n\n## 1. Core Translations\n\n**When to use:** Adding translations to core Payload packages (packages/ui, packages/payload, packages/next)\n\n### Steps:\n\n1. **Add the English translation** to `packages/translations/src/languages/en.ts`\n\n   - Add your new key/value to the appropriate section (e.g., `authentication`, `general`, `fields`, etc.)\n   - Use nested objects for organization\n   - Example:\n     ```typescript\n     export const enTranslations = {\n       authentication: {\n         // ... existing keys\n         newFeature: 'New Feature Text',\n       },\n     }\n     ```\n\n2. **Add client key** (if needed for client-side usage) to `packages/translations/src/clientKeys.ts`\n\n   - Add the translation key path using colon notation\n   - Example: `'authentication:newFeature'`\n   - Client keys are used for translations that need to be available in the browser\n\n3. **Generate translations for all languages**\n   - Change directory: `cd tools/scripts`\n   - Run: `pnpm generateTranslations:core`\n   - This auto-translates your new English keys to all other supported languages\n\n---\n\n## 2. Plugin Translations\n\n**When to use:** Adding translations to any plugin package (packages/plugin-\\*)\n\n### Steps:\n\n1. **Verify plugin has translations folder**\n\n   - Check if `packages/plugin-{name}/src/translations` exists\n   - If it doesn't exist, see \"Scaffolding New Plugin Translations\" below\n\n2. **Add the English translation** to the plugin's `packages/plugin-{name}/src/translations/languages/en.ts`\n\n   - Plugin translations are namespaced under the plugin name\n   - Example for plugin-multi-tenant:\n     ```typescript\n     export const enTranslations = {\n       'plugin-multi-tenant': {\n         'new-feature-label': 'New Feature',\n       },\n     }\n     ```\n\n3. **Generate translations for all languages**\n   - Change directory: `cd tools/scripts`\n   - Run the plugin-specific script: `pnpm generateTranslations:plugin-{name}`\n   - Examples:\n     - `pnpm generateTranslations:plugin-multi-tenant`\n     - `pnpm generateTranslations:plugin-ecommerce`\n     - `pnpm generateTranslations:plugin-import-export`\n\n### Scaffolding New Plugin Translations\n\nIf a plugin doesn't have a translations folder yet, **ask the user if they want to scaffold one**.\n\n#### Structure to create:\n\n```\npackages/plugin-{name}/src/translations/\n├── index.ts\n├── types.ts\n└── languages/\n    ├── en.ts\n    ├── es.ts\n    └── ... (all other language files)\n```\n\n#### Files to create:\n\n1. **types.ts** - Define the plugin's translation types\n2. **index.ts** - Export all translations and re-export types\n3. **languages/en.ts** - English translations (the source for generation)\n4. **languages/\\*.ts** - Other language files (initially empty, will be generated)\n\n#### Generation script to create:\n\n1. Create `tools/scripts/src/generateTranslations/plugin-{name}.ts`\n\n   - Use `plugin-multi-tenant.ts` as a template\n   - Update the import paths to point to the new plugin\n   - Update the targetFolder path\n\n2. Add script to `tools/scripts/package.json`:\n   ```json\n   \"generateTranslations:plugin-{name}\": \"node --no-deprecation --import @swc-node/register/esm-register src/generateTranslations/plugin-{name}.ts\"\n   ```\n\n---\n\n## Important Notes\n\n- All translation generation requires `OPENAI_KEY` environment variable to be set\n- The generation scripts use OpenAI to translate from English to other languages\n- Always add translations to English first - it's the source of truth\n- **Core translations**: Client keys are only needed for translations used in the browser/admin UI\n- **Plugin translations**: Automatically namespaced under the plugin name to avoid conflicts\n", "skills/payload-accessibility/SKILL.md": "---\nname: payload-accessibility\ndescription: Use when building or assessing Payload UI, changing styles, content, interactions, focus, keyboard behavior or semantics, or working on accessibility tests or WCAG/VPAT evidence.\n---\n\n# Payload Accessibility\n\nAssess accessibility from design through verification. Limit conclusions to the behavior and states evaluated.\n\n## On-demand check\n\nInvoke in chat, with optional `check`:\n\n```text\n$payload-accessibility my current UI changes\n$payload-accessibility check content branching on origin/feat/content-branching\n```\n\nScope may be a feature, paths, PR or branch comparison; omitted scope means current local changes. Report the actual revision and comparison. Never silently substitute another branch or older implementation.\n\nA standalone invocation, with or without `check`, is assessment-only: inspect code, run relevant existing checks and exercise the UI with local test data as needed. Do not edit implementation or tests. Report findings, evidence, proposed fixes and verification gaps, then wait for approval.\n\nAfter approval, make the approved fixes and regression tests locally; continue editing and verifying within that scope without further approval. Report each original finding as passing, failing or unverified, with evidence. Wait for approval before any commit or push. Fix approval does not authorise committing or publishing. Follow the user's explicit scope and instructions.\n\nDuring feature development, apply the workflow within the task's authorised scope.\n\n## Change assessment\n\nFollow [change-assessment.md](references/change-assessment.md), proportionally to the change:\n\n1. Trace the feature/files/diff through relevant shared components, styles, providers and tests to the affected journey. Before code exists, use intended behavior and revisit during implementation.\n2. Identify affected states, inputs, viewports and assistive-technology behavior. Define observable expectations before implementation.\n3. Read [wcag-2.2-aa.md](references/wcag-2.2-aa.md). Assess every plausibly affected A/AA criterion, beyond those named in an issue; resolve uncertainty using linked W3C guidance.\n4. Prefer native HTML. Composite ARIA patterns require complete semantics and keyboard behavior.\n5. Follow [testing.md](references/testing.md). Reuse sufficient evidence; fill gaps with focused checks against production components in context.\n6. Within authorised implementation, reproduce and fix confirmed barriers, then verify. In assessment-only work, report without editing implementation or tests until fixes are approved. Distinguish failures, risks and coverage gaps.\n\n## Payload contrast mode and remediation scope\n\nCheck feature contrast with enhanced contrast mode enabled: verify `html[data-enhanced-contrast]` and test the relevant light/dark theme and interaction state. Enabling the mode does not replace the other accessibility checks. Use the existing mode-switching tests rather than rechecking the shared setting for each feature; see [contrast setup](references/testing.md#payload-enhanced-contrast-setup). Continue checking ordinary-mode integration and behavior, but do not use an ordinary-mode contrast measurement alone to replace the shared palette in a feature.\n\nIf a measurement still fails, first verify the intended component variant, semantic tokens, inherited theme and loaded shared styles. Fix incorrect feature usage or custom styling at its source. A reproducible defect inherited from a shared component belongs to that component's owner; resolve it within authorized scope or report it with the exact mode/state and evidence. Do not add a feature-local color override merely to make a contrast check pass. Record the tested mode explicitly; enhanced-mode evidence does not establish contrast conformance for ordinary mode.\n\n## Test placement\n\n- General browser regressions: `test/a11y/e2e.spec.ts`, grouped by workflow with keyboard/focus assertions and axe checkpoints.\n- Audit validation: `test/a11y/WCAG.audit.spec.ts`, explicit audit command only.\n- Speech/virtual-cursor evidence: `test/a11y/screen-reader.spec.ts`, grouped by criterion.\n- Shared setup: `test/a11y/helpers.ts`; scenario-specific setup stays in its spec.\n- Keep component unit tests beside their component to verify low-level contracts; they cannot replace end-to-end evidence of a barrier in the rendered application.\n- Reuse existing test configurations and real UI; see `testing.md` for feature-fixture fallback. Do not create fixtures or criterion files by default.\n\n## Evidence boundaries\n\n- Clean axe scans do not prove criterion or product conformance.\n- DOM/accessibility-tree assertions do not prove exact speech. Use Guidepup for speech/cursor outcomes, regardless of how an issue was discovered.\n- Require human visual/AT confirmation when judgement, timing or platform behavior cannot be reliably automated.\n- AA conformance requires all applicable A and AA criteria. Qualified human review is required for VPAT/ACR conformance statements.\n\n## Handoff\n\nKeep it short; use a table when helpful. Include:\n\n- Assessed UI, states, input methods, browser/version, viewport, theme and relevant settings.\n- Applicable A/AA criteria, why they apply, and verified/unverified outcomes.\n- Findings/fixes: file/line, reproduction state and user impact; distinguish confirmed failures, suspected risks and coverage gaps.\n- Commands and actual results, including failed, skipped and not-run checks.\n- Remaining visual/AT verification, failures and limitations.\n\nFor verified UI fixes, follow [record-pr-demo](../record-pr-demo/SKILL.md), including its local preview, approval and publishing requirements. Never commit demo media. Recordings supplement tests, not screen-reader verification.\n\nNever claim conformance beyond the evidence.\n", "skills/payload-accessibility/references/change-assessment.md": "# Assessing new UI changes\n\n## Scope the journey\n\nStart from the feature, paths or comparison. Inspect staged, unstaged and relevant untracked files for local work; report the actual base for a branch/PR. Exclude unrelated local changes.\n\nRead relevant implementation, styles, config, labels and tests. Trace shared controls, hooks, providers and portals; check representative consumers, including nested drawers/mobile where relevant. CSS-only changes can affect clipping, contrast, focus and target geometry.\n\nWithout a diff, start from the intended journey and revisit once implemented. If accessible behavior is unaffected, explain briefly and skip browser checks.\n\n## Define expectations\n\nSelect relevant states: initial, open/closed, loading, empty, error, success, selected, disabled/read-only and permissions. Include input methods, themes, narrow layouts, text resizing and spacing as affected; do not require every combination.\n\nRead the full A/AA reference and connect:\n\n**Action/state → accessible outcome → criterion → evidence.**\n\nW3C success criteria are normative; Understanding documents, techniques and ARIA patterns guide interpretation/implementation. Respect exceptions; do not treat AAA criteria or recommended techniques as AA requirements.\n\nExample: an async picker in a drawer needs a name, keyboard selection, loading/error/results feedback and sensible focus on opening, dismissal and return. Consider 1.3.1, 2.1.1–2, 2.4.3/7/11, 3.3.1 and 4.1.2–3 as applicable. Test inside the drawer. Add live regions only for updates that need them, checking whether they qualify as status messages.\n\n## Verify proportionally\n\nUse an isolated test environment and disposable data; never reset a shared or developer database. Track and clean up assessment-created data, files and temporary settings, preserving unrelated work. Report anything left for review and clean it up when no longer needed.\n\nReuse assertions covering the same state, interaction and observable outcome against the current implementation. Matching test names, ARIA attributes or axe scans alone may be insufficient.\n\nFollow `testing.md`: browser tests for names, roles, states, keyboard and geometry; axe for machine-detectable failures; Guidepup for speech/cursor outcomes. New-feature tests assert expected accessible behavior; an absent feature is not an accessibility failure.\n\nWithin authorised implementation, reproduce confirmed barriers, fix and recheck. Separate unrelated pre-existing findings. Cover affected shared consumers without running unrelated suites. Follow repository production-test requirements for client/server bundling changes.\n\nIf browser/AT access is unavailable, continue source assessment and specify pending interactions and expected outcomes. Do not automatically change machine permissions or use DOM assertions as speech evidence.\n\n## Classify evidence\n\n- **Confirmed finding:** demonstrated barrier and user impact.\n- **Suspected risk:** source/design concern needing verification.\n- **Coverage gap:** missing evidence, without a demonstrated failure.\n- **Verified outcome:** a check ran and supports the outcome in the assessed state.\n\nUse the skill's handoff format. Source alone cannot verify rendered contrast, clipping, focus movement or speech. Explain irrelevant criteria only when useful; small changes do not need a full conformance checklist.\n", "skills/payload-accessibility/references/testing.md": "# Accessibility testing\n\n## Choose evidence by observable behavior\n\n| Outcome to prove                                                                        | Primary evidence                                                                                   |\n| --------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |\n| Accessible name, role, value, state, or relationship                                    | Playwright assertion against the rendered component                                                |\n| Keyboard operation, focus movement, dismissal, or focus restoration                     | Playwright interaction test                                                                        |\n| Reflow, clipping, target size, or DOM geometry                                          | Playwright measurement; add human visual review when quality or spatial meaning requires judgement |\n| Broad machine-detectable violations in a rendered state                                 | Existing `runAxeScan` helper                                                                       |\n| Exact synthesized speech, virtual cursor, browse mode, or assistive-technology grouping | Guidepup, with human confirmation when timing or platform behavior remains unreliable              |\n| Meaningful order, visible focus quality, sensory meaning, or other subjective outcome   | Human review, supported by automated checks where possible                                         |\n\nThe tool used by an original auditor does not determine the test layer. If Playwright can directly observe the reported name, role, state, relationship, focus, or keyboard behavior, keep the regression in the browser suite. Use Guidepup only when spoken output or screen-reader cursor behavior is itself the expected result.\n\n## Payload enhanced contrast setup\n\nTo measure Admin enhanced-mode contrast, use the Account enhanced-contrast toggle (`#field-highContrastMode`) or the existing fixture's theme setup, then assert that `html` has `data-enhanced-contrast`. Reuse the mode-switching coverage in `test/a11y/WCAG.audit.spec.ts`; revisit shared setting behavior when the change affects it.\n\nMeasure computed foreground/background colors in that mode for the actual enabled, hover, focus or other applicable state, recording theme, mode and state with the result. Check that custom feature inputs and controls inherit the enhanced tokens. If ordinary-mode measurements are also collected, label them separately rather than substituting feature-local colors. Preserve the user's preference after an interactive check; do not leave their account settings changed as a testing side effect.\n\n## Canonical suites\n\n- `test/a11y/WCAG.audit.spec.ts` preserves the original audit evidence and runs only with the explicit audit command.\n- `test/a11y/screen-reader.spec.ts` contains Guidepup VoiceOver and NVDA evidence.\n- `test/a11y/helpers.ts` contains setup reused across the suites.\n- `test/a11y/e2e.spec.ts` contains general workflow regressions, combining keyboard/focus assertions and axe checkpoints.\n\nIn the audit, use ordered `test.describe` groups named with the WCAG criterion and level. A test belongs under its primary criterion; note secondary affected criteria in the handoff rather than duplicating the scenario. Consolidate tests only when one arrangement, interaction, and assertion genuinely exercises every covered case.\n\nPrefer the existing a11y Payload config and real UI components. If it cannot render the feature, assess with an existing feature fixture and report which config was used. Keep regression placement consistent with the canonical suites; extend their setup only when needed. Scenario-specific setup stays in its spec; reusable helpers live in `test/a11y/helpers.ts`.\n\n## Regression quality\n\nBefore remediation, reproduce the reported state and verify that the assertion fails for the accessibility barrier—not navigation, fixture, selector, or server setup. After remediation, require the same assertion to pass.\n\nA test that already passes may represent an existing fix or a weak assertion. Recreate the exact page state, data, interaction method, and platform conditions; compare the assertion with the actual reported outcome; and strengthen proxy assertions. Never manufacture a failure with `test.fail`.\n\nSkipped or fixme tests are not conformance evidence. Tests should prove observable behavior rather than the presence of an implementation detail such as an ARIA attribute when user-facing behavior can be asserted directly.\n\n## Axe\n\nReuse the existing accessibility scan suite when it already covers the relevant page state. Otherwise call `runAxeScan` once per unique rendered state where it adds value, not once per criterion. Retain its JSON results as automated evidence, but do not convert rule tags directly into a conformance statement.\n\n## Guidepup\n\nThe screen-reader spec deliberately does not match the repository's `*e2e.spec.ts` CI discovery pattern. Until dedicated macOS and Windows runners exist, run it in a supported local or manually triggered environment.\n\nConfigure a test machine once:\n\n```bash\npnpm dlx @guidepup/setup setup\npnpm dlx @guidepup/setup install\npnpm exec playwright install webkit # macOS / VoiceOver\npnpm exec playwright install firefox # Windows / NVDA\n```\n\nThe operating-system setup changes accessibility and automation permissions, so a developer must explicitly review and run it on the test machine. Do not silently substitute a DOM assertion as proof of spoken output.\n\n## Commands\n\n```bash\n# Targeted general browser evidence\npnpm test:a11y --grep \"<test name>\" --workers=1\n\n# Complete browser WCAG evidence suite\npnpm test:a11y:audit --workers=1\n\n# Screen-reader evidence on a configured macOS or Windows machine\npnpm test:a11y:screen-reader\n```\n\nRun affected tests during development. Before handoff, verify changed behavior and affected shared consumers with a sufficient focused set or suite. Report scope and unavailable checks; repeat unrelated suites only with a reason.\n", "skills/payload-accessibility/references/wcag-2.2-aa.md": "# WCAG 2.2 Level AA engineering reference\n\nWCAG 2.2 Level AA requires every applicable Level A and Level AA success criterion. The summaries below are engineering prompts, not replacements for the normative [WCAG 2.2 Recommendation](https://www.w3.org/TR/WCAG22/) or its [How to Meet WCAG quick reference](https://www.w3.org/WAI/WCAG22/quickref/).\n\nFor a code change, assess every criterion the change can plausibly affect. Record applicability, tested states, evidence, and anything requiring human review. Do not mark a criterion `Not Applicable` merely because the current test fixture lacks the relevant content.\n\n## 1. Perceivable\n\n| Criterion                                                                                                                                      | Level | Engineering assessment                                                                                                                            |\n| ---------------------------------------------------------------------------------------------------------------------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------- |\n| [1.1.1 Non-text Content](https://www.w3.org/TR/WCAG22/#non-text-content)                                                                       | A     | Provide an equivalent text alternative for meaningful images, icons, charts, controls, and other non-text content; hide decoration appropriately. |\n| [1.2.1 Audio-only and Video-only (Prerecorded)](https://www.w3.org/TR/WCAG22/#audio-only-and-video-only-prerecorded)                           | A     | Provide an equivalent alternative for prerecorded audio-only or video-only media.                                                                 |\n| [1.2.2 Captions (Prerecorded)](https://www.w3.org/TR/WCAG22/#captions-prerecorded)                                                             | A     | Caption prerecorded synchronized media unless it is a clearly identified media alternative for text.                                              |\n| [1.2.3 Audio Description or Media Alternative (Prerecorded)](https://www.w3.org/TR/WCAG22/#audio-description-or-media-alternative-prerecorded) | A     | Provide audio description or a complete media alternative for prerecorded video content.                                                          |\n| [1.2.4 Captions (Live)](https://www.w3.org/TR/WCAG22/#captions-live)                                                                           | AA    | Caption live synchronized media.                                                                                                                  |\n| [1.2.5 Audio Description (Prerecorded)](https://www.w3.org/TR/WCAG22/#audio-description-prerecorded)                                           | AA    | Provide audio description for prerecorded video where visual information is needed to understand it.                                              |\n| [1.3.1 Info and Relationships](https://www.w3.org/TR/WCAG22/#info-and-relationships)                                                           | A     | Programmatically expose structure, labels, groups, headings, tables, and relationships conveyed visually.                                         |\n| [1.3.2 Meaningful Sequence](https://www.w3.org/TR/WCAG22/#meaningful-sequence)                                                                 | A     | Preserve a meaningful reading and interaction sequence when order affects understanding.                                                          |\n| [1.3.3 Sensory Characteristics](https://www.w3.org/TR/WCAG22/#sensory-characteristics)                                                         | A     | Do not make instructions depend only on shape, color, size, location, orientation, or sound.                                                      |\n| [1.3.4 Orientation](https://www.w3.org/TR/WCAG22/#orientation)                                                                                 | AA    | Support portrait and landscape unless a particular orientation is essential.                                                                      |\n| [1.3.5 Identify Input Purpose](https://www.w3.org/TR/WCAG22/#identify-input-purpose)                                                           | AA    | Programmatically identify the purpose of inputs collecting recognized personal data.                                                              |\n| [1.4.1 Use of Color](https://www.w3.org/TR/WCAG22/#use-of-color)                                                                               | A     | Do not use color as the only means of communicating information, state, action, or distinction.                                                   |\n| [1.4.2 Audio Control](https://www.w3.org/TR/WCAG22/#audio-control)                                                                             | A     | Let users pause, stop, or independently control audio that starts automatically and lasts more than three seconds.                                |\n| [1.4.3 Contrast (Minimum)](https://www.w3.org/TR/WCAG22/#contrast-minimum)                                                                     | AA    | Meet minimum text and image-of-text contrast, accounting for text size and allowed exceptions.                                                    |\n| [1.4.4 Resize Text](https://www.w3.org/TR/WCAG22/#resize-text)                                                                                 | AA    | Keep text and functionality usable when text is resized to 200 percent without assistive technology.                                              |\n| [1.4.5 Images of Text](https://www.w3.org/TR/WCAG22/#images-of-text)                                                                           | AA    | Use real text instead of images of text when the presentation can be achieved with available technology.                                          |\n| [1.4.10 Reflow](https://www.w3.org/TR/WCAG22/#reflow)                                                                                          | AA    | Preserve content and functionality without two-dimensional scrolling at the specified equivalent viewport sizes, except for essential layouts.    |\n| [1.4.11 Non-text Contrast](https://www.w3.org/TR/WCAG22/#non-text-contrast)                                                                    | AA    | Provide sufficient contrast for necessary component boundaries, states, focus indicators, and meaningful graphics.                                |\n| [1.4.12 Text Spacing](https://www.w3.org/TR/WCAG22/#text-spacing)                                                                              | AA    | Preserve content and functionality when users apply the specified line, paragraph, letter, and word spacing.                                      |\n| [1.4.13 Content on Hover or Focus](https://www.w3.org/TR/WCAG22/#content-on-hover-or-focus)                                                    | AA    | Make additional hover/focus content dismissible, hoverable, and persistent unless an exception applies.                                           |\n\n## 2. Operable\n\n| Criterion                                                                                                | Level | Engineering assessment                                                                                                                      |\n| -------------------------------------------------------------------------------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------- |\n| [2.1.1 Keyboard](https://www.w3.org/TR/WCAG22/#keyboard)                                                 | A     | Make all functionality operable through a keyboard interface without timing-dependent keystrokes, except where the input path is essential. |\n| [2.1.2 No Keyboard Trap](https://www.w3.org/TR/WCAG22/#no-keyboard-trap)                                 | A     | Let keyboard users move focus away from every component, with documented non-standard exit methods if needed.                               |\n| [2.1.4 Character Key Shortcuts](https://www.w3.org/TR/WCAG22/#character-key-shortcuts)                   | A     | Allow single-character shortcuts to be turned off, remapped, or active only on focus unless essential.                                      |\n| [2.2.1 Timing Adjustable](https://www.w3.org/TR/WCAG22/#timing-adjustable)                               | A     | Let users turn off, adjust, or extend time limits unless a defined exception applies.                                                       |\n| [2.2.2 Pause, Stop, Hide](https://www.w3.org/TR/WCAG22/#pause-stop-hide)                                 | A     | Give users control over qualifying moving, blinking, scrolling, or auto-updating information.                                               |\n| [2.3.1 Three Flashes or Below Threshold](https://www.w3.org/TR/WCAG22/#three-flashes-or-below-threshold) | A     | Avoid content that flashes more than three times per second unless it remains below the allowed thresholds.                                 |\n| [2.4.1 Bypass Blocks](https://www.w3.org/TR/WCAG22/#bypass-blocks)                                       | A     | Provide a mechanism to bypass repeated content.                                                                                             |\n| [2.4.2 Page Titled](https://www.w3.org/TR/WCAG22/#page-titled)                                           | A     | Give each page a title that identifies its topic or purpose.                                                                                |\n| [2.4.3 Focus Order](https://www.w3.org/TR/WCAG22/#focus-order)                                           | A     | Keep sequential focus order meaningful and operable.                                                                                        |\n| [2.4.4 Link Purpose (In Context)](https://www.w3.org/TR/WCAG22/#link-purpose-in-context)                 | A     | Make each link's purpose determinable from its text or programmatically associated context, subject to the ambiguity exception.             |\n| [2.4.5 Multiple Ways](https://www.w3.org/TR/WCAG22/#multiple-ways)                                       | AA    | Provide more than one way to locate pages in a set, except when a page is a step in a process.                                              |\n| [2.4.6 Headings and Labels](https://www.w3.org/TR/WCAG22/#headings-and-labels)                           | AA    | Use headings and labels that describe topic or purpose.                                                                                     |\n| [2.4.7 Focus Visible](https://www.w3.org/TR/WCAG22/#focus-visible)                                       | AA    | Ensure keyboard focus has a visible indicator.                                                                                              |\n| [2.4.11 Focus Not Obscured (Minimum)](https://www.w3.org/TR/WCAG22/#focus-not-obscured-minimum)          | AA    | Ensure the focused component is not entirely hidden by author-created content.                                                              |\n| [2.5.1 Pointer Gestures](https://www.w3.org/TR/WCAG22/#pointer-gestures)                                 | A     | Provide a single-pointer alternative to multipoint or path-based gestures unless the gesture is essential.                                  |\n| [2.5.2 Pointer Cancellation](https://www.w3.org/TR/WCAG22/#pointer-cancellation)                         | A     | Avoid completing functions on pointer-down, or provide an allowed cancellation, undo, or essential exception.                               |\n| [2.5.3 Label in Name](https://www.w3.org/TR/WCAG22/#label-in-name)                                       | A     | Include the visible label text in the accessible name of a control.                                                                         |\n| [2.5.4 Motion Actuation](https://www.w3.org/TR/WCAG22/#motion-actuation)                                 | A     | Provide a conventional input alternative and a way to disable motion-triggered operation unless essential.                                  |\n| [2.5.7 Dragging Movements](https://www.w3.org/TR/WCAG22/#dragging-movements)                             | AA    | Provide a non-dragging single-pointer alternative unless dragging is essential.                                                             |\n| [2.5.8 Target Size (Minimum)](https://www.w3.org/TR/WCAG22/#target-size-minimum)                         | AA    | Provide targets at least 24 by 24 CSS pixels or satisfy a spacing or stated exception.                                                      |\n\n## 3. Understandable\n\n| Criterion                                                                                                              | Level | Engineering assessment                                                                                                                                  |\n| ---------------------------------------------------------------------------------------------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| [3.1.1 Language of Page](https://www.w3.org/TR/WCAG22/#language-of-page)                                               | A     | Programmatically identify the page's default human language.                                                                                            |\n| [3.1.2 Language of Parts](https://www.w3.org/TR/WCAG22/#language-of-parts)                                             | AA    | Programmatically identify changes in human language, except for names, technical terms, indeterminate language, and vernacular phrases.                 |\n| [3.2.1 On Focus](https://www.w3.org/TR/WCAG22/#on-focus)                                                               | A     | Do not trigger an unexpected change of context merely when a component receives focus.                                                                  |\n| [3.2.2 On Input](https://www.w3.org/TR/WCAG22/#on-input)                                                               | A     | Do not unexpectedly change context when a setting changes unless users are advised beforehand.                                                          |\n| [3.2.3 Consistent Navigation](https://www.w3.org/TR/WCAG22/#consistent-navigation)                                     | AA    | Keep repeated navigation mechanisms in the same relative order unless the user initiates a change.                                                      |\n| [3.2.4 Consistent Identification](https://www.w3.org/TR/WCAG22/#consistent-identification)                             | AA    | Identify components with the same functionality consistently.                                                                                           |\n| [3.2.6 Consistent Help](https://www.w3.org/TR/WCAG22/#consistent-help)                                                 | A     | Keep repeated help mechanisms in the same relative order unless the user initiates a change.                                                            |\n| [3.3.1 Error Identification](https://www.w3.org/TR/WCAG22/#error-identification)                                       | A     | Identify input errors in text and describe the item in error.                                                                                           |\n| [3.3.2 Labels or Instructions](https://www.w3.org/TR/WCAG22/#labels-or-instructions)                                   | A     | Provide labels or instructions when content requires user input.                                                                                        |\n| [3.3.3 Error Suggestion](https://www.w3.org/TR/WCAG22/#error-suggestion)                                               | AA    | Suggest known corrections for detected input errors unless doing so would compromise security or purpose.                                               |\n| [3.3.4 Error Prevention (Legal, Financial, Data)](https://www.w3.org/TR/WCAG22/#error-prevention-legal-financial-data) | AA    | For qualifying consequential submissions, provide reversibility, validation with correction, or review and confirmation.                                |\n| [3.3.7 Redundant Entry](https://www.w3.org/TR/WCAG22/#redundant-entry)                                                 | A     | Auto-populate or make previously entered information selectable in the same process unless an exception applies.                                        |\n| [3.3.8 Accessible Authentication (Minimum)](https://www.w3.org/TR/WCAG22/#accessible-authentication-minimum)           | AA    | Avoid required cognitive-function tests in authentication unless an alternative, assistance, object recognition, or personal-content exception applies. |\n\n## 4. Robust\n\n| Criterion                                                                | Level | Engineering assessment                                                                                                      |\n| ------------------------------------------------------------------------ | ----- | --------------------------------------------------------------------------------------------------------------------------- |\n| [4.1.2 Name, Role, Value](https://www.w3.org/TR/WCAG22/#name-role-value) | A     | Programmatically expose component names and roles, user-settable states and values, and changes to those states and values. |\n| [4.1.3 Status Messages](https://www.w3.org/TR/WCAG22/#status-messages)   | AA    | Programmatically expose qualifying status messages so assistive technology can present them without moving focus.           |\n\n## Conformance boundary\n\nAutomated tests establish only the behaviors they assert. Product-level VPAT/ACR work must also define the evaluated product scope and environments, cover full pages and complete processes, assess every applicable criterion, include manual and assistive-technology evidence, account for known defects, and receive qualified human review. Axe results, passing regressions, or closed issues cannot independently establish `Supports`.\n", "skills/record-pr-demo/SKILL.md": "---\nname: record-pr-demo\ndescription: Use when a Payload pull request needs a concise visual walkthrough for reviewers.\n---\n\n# Record a PR Demo\n\nCreate a short, reviewer-focused screen recording of the current Payload feature. Produce and review the video locally before uploading anything to GitHub.\n\nThis skill is for feature demonstrations, not committed screenshot regression baselines.\n\n## Non-negotiable review gate\n\nUploading consumes GitHub storage and changes an external PR. Always stop after rendering the local MP4, show that exact file to the user, and request approval. A general request to “record and post a demo” does not waive this checkpoint.\n\nBefore showing the video, record its absolute path and SHA-256 digest. Immediately before an approved upload, recompute the digest. If it changed, show the new video and request approval again.\n\nDo not upload previews, rejected takes, raw intermediate recordings, or files the user has not reviewed. Never commit demo media to the repository.\n\n## Gesture-based scenarios\n\nDrive the application through browser gestures: paced pointer clicks, keystrokes, and wheel scrolling. Open the starting URL once, then navigate through visible controls. Use existing seeded data when possible. Optional `setup`/`teardown` hooks may seed and clean up recording-only data through the API outside the walkthrough. Within the scenario, use gestures to reach each demonstrated state; avoid API or Local API calls, direct navigation between steps, field filling, DOM mutations, and programmatic scrolling. Assertions and read-only DOM inspection may observe the result. Recording chrome, encoding, and verification remain harness operations. See [recording.md](references/recording.md#gesture-based-interactions) for the interaction contract and examples.\n\nUse `circleCursor(locator)` selectively to emphasize a value or result with two tight loops near the focus point and an eased finish. See [recording.md](references/recording.md#circle-a-result-for-emphasis) for timing and radius options.\n\nUse `await click(chrome.back)` and `await click(chrome.forward)` for browser-history steps. The shared window chrome provides these real history controls beside the live URL bar, with normal cursor movement and click feedback.\n\n## Required presentation chrome\n\nEvery scenario must export `presentation` with a change kind, title, and description. For a known sequence of steps, declare `annotationSteps`, then call `showAnnotation` to advance through that sequence. Use `hideAnnotation` when the explanation should no longer accompany the action. See [window-chrome.md](references/window-chrome.md) for the API contract and examples. Scripts supply content and intent; the shared renderer owns presentation. Do not inject markup, styles, badges, or layout rules into the application or recording chrome.\n\nKeep the default canvas and desktop viewport for ordinary demos. Use a smaller `--viewport` or `resizeWindow` only when demonstrating responsive reflow or breakpoints, or when the user explicitly requests different dimensions. Keep the canvas fixed while resizing the application. Do not shrink the viewport or canvas merely to crop surrounding content or emphasize a visual change.\n\nFor a before/after comparison, set `change.kind: 'Bug'` on the real unfixed scenario and `'Fix'` on the corrected scenario. Set `kind: 'Bug'` on an individual step only when its action visibly demonstrates a failure; leave setup and ordinary navigation unmarked. Write a short description of the visible action or outcome, and assert that state in the script.\n\n## Accessibility demonstrations\n\nSet `presentation.accessibility: true` when keyboard commands are part of the evidence, and `presentation.showAnnouncements: true` when relevant UI updates should be observed. The harness chooses the compatible presentation and preserves application focus styling. Captions are DOM observations, not screen-reader audio. Use `--a11y on` or `--a11y off` to override these options without editing the scenario; omit the flag to preserve its defaults. See [recording.md](references/recording.md#accessibility-observations) for privacy filtering and evidence limits.\n\n## Workflow\n\n1. Inspect the feature, relevant diff, and available test configs. Choose the smallest existing Payload config that demonstrates the real feature. Create a temporary config only when no existing config can show it clearly.\n2. Write a brief plan in `/tmp` with the opening state, 2–6 visible actions, and the final proof a reviewer should see. For a fix with a visible before, plan Before/After recordings of the bug and the fix; otherwise default to one current-state feature demo. For annotation content and APIs, use [recording.md](references/recording.md#editorial-annotations-over-the-recording).\n3. Start the relevant dev server and make its initial state deterministic. Do not expose credentials, personal data, tokens, or unrelated records.\n4. Read [recording.md](references/recording.md) and create a temporary scenario module in `/tmp`. Write readable, multi-line JavaScript with clear preparation and visible-step sections so the script is easy to review. Call `ready()` once after the opening UI is visible; this marks where the finished video starts. Make preparation repeatable so validation and recording each begin in the same state. Use optional `setup`/`teardown` hooks for API fixtures, or prepare content through the UI before `ready()`. Keep recording-only data in a disposable database. If creating content is part of the story, show that creation through the Admin.\n5. When recording through an agent, use the [recording job API](references/recording-jobs.md) and renew its lease only while the prompt is active. Use a take-specific label. For direct terminal use, run the candidate command from the repository root, for example `node .agents/skills/record-pr-demo/scripts/prepare-demo.mjs candidate --scenario /tmp/payload-pr-demo-feature.mjs --label feature-take-1`. It performs preflight checks, fast validation, human-paced recording, conversion, full decode verification, contact-sheet generation, hashing, manifest creation, and raw-video cleanup. Keep the demo concise enough to stay below the converter's default 10 MB budget.\n6. Watch the entire MP4, use the contact sheet for a quick state check, and show the exact local video inline using its absolute path. Include a clickable link to its take-specific `.scenario.mjs` snapshot beside the video and open that file in the Codex editor when available:\n\n   ```md\n   ![Feature demo](/absolute/path/to/payload-pr-demo-feature.mp4)\n\n   [Review recording script](/absolute/path/to/payload-pr-demo-feature.scenario.mjs)\n   ```\n\n7. Stop and ask the user to approve, reject, or request another take. Do not call `gh`, open an upload UI, or otherwise upload the file yet.\n8. Only after explicit approval of that recording, read [publishing.md](references/publishing.md) and verify the reviewed manifest. Preserve the complete existing PR description and append a final `## Preview` section with each approved video in its own paragraph. Use a PR comment only when the user explicitly asks for one.\n9. Verify the PR renders the uploaded video, then remove temporary scenarios, plans, raw recordings, and temporary fixture changes. Preserve the approved MP4 and its script snapshot until the upload is confirmed.\n\n## Completion criteria\n\n- Each recording tells one understandable visual story and ends on visible proof.\n- The recorded walkthrough uses browser gestures; optional API fixtures establish only its starting data and clean up afterward.\n- The first decoded frame shows the intended opening UI, without a blank startup screen.\n- Pointer movement is smooth, clicks have readable dwell time and visible ring feedback, and the cursor stays visible above popup menus and dialogs.\n- Editorial annotations use the shared component and [annotation API](references/recording.md#editorial-annotations-over-the-recording) and leave important UI visible.\n- Overflowing content, including popup menu lists, uses the scenario `scroll` helper for paced movement.\n- The approved artifact is an H.264 `.mp4`, within GitHub's applicable upload limit. Capture at the composition’s native dimensions.\n- The candidate command produced a contact sheet, manifest, and take-specific script snapshot. The video review includes a link to that script, and the manifest still matches before upload.\n- The user reviewed the exact bytes that were uploaded.\n- The existing PR description is preserved and ends with `## Preview` and the approved inline player, unless the user explicitly requested a comment.\n- GitHub contains no rejected or superseded takes.\n- No media or recording-only fixture remains in the working tree.\n\nExplicit user instructions about the feature, scenario, length, destination, or presentation override this skill's preferences, except that upload still requires review of the final file.\n", "skills/record-pr-demo/references/publishing.md": "# Publishing an Approved Demo\n\nRead this reference only after the user explicitly approves the final local MP4.\n\n## Verify the approved bytes\n\nVerify the saved candidate manifest immediately before upload:\n\n```bash\nnode .agents/skills/record-pr-demo/scripts/prepare-demo.mjs verify \\\n  --manifest /tmp/payload-pr-demo-feature.json\n```\n\nThis recomputes the SHA-256 digest and file size for the manifest's MP4 and checks the saved scenario snapshot against its recorded hash. If verification fails, do not upload. Show the changed file and request approval again.\n\nConfirm `gh auth status` succeeds and that the installed GitHub CLI command supports `--attach`. If it does not, use available browser automation to attach the approved local file through GitHub's PR description editor. Use the comment editor only when the user explicitly requests a comment. If the environment cannot select a local file, give the approved MP4 to the user for manual drag-and-drop into the same destination; do not commit it or substitute a release, LFS, or repository URL.\n\n## Append to the PR description by default\n\nRead the complete current body with `gh pr view <number-or-url> --json body` and save it before editing. Preserve that body verbatim, including all existing sections, links, and attachments. Append blank lines followed by this final section, keeping the video reference alone in its paragraph:\n\n```md\n## Preview\n\n![](/absolute/path/to/payload-pr-demo-feature.mp4)\n```\n\nWrite the complete combined body to `/tmp/payload-pr-body-with-demo.md`. Re-read the remote body immediately before editing; if it changed, rebuild the combined body from the latest version so concurrent edits are preserved. Do not replace an existing preview or remove existing content without explicit instructions.\n\n```bash\ngh pr edit <number-or-url> \\\n  --body-file /tmp/payload-pr-body-with-demo.md \\\n  --attach /absolute/path/to/payload-pr-demo-feature.mp4\n```\n\nGitHub CLI replaces the local reference with the uploaded attachment URL so it renders as an inline player. With browser automation, append the same `## Preview` section to the existing description and attach the approved MP4 beneath it.\n\n## Use a comment only when explicitly requested\n\nFor an explicitly requested comment, create `/tmp/payload-pr-demo-comment.md` with a video reference alone in its paragraph:\n\n```md\n## Preview\n\n![](/absolute/path/to/payload-pr-demo-feature.mp4)\n```\n\n```bash\ngh pr comment <number-or-url> \\\n  --body-file /tmp/payload-pr-demo-comment.md \\\n  --attach /absolute/path/to/payload-pr-demo-feature.mp4\n```\n\n## Verify and clean up\n\nRe-read the PR description and confirm the saved existing body is intact and the final `## Preview` section contains the uploaded attachment in its own paragraph. Open the PR and confirm the inline player renders at the bottom of the description. For an explicitly requested comment, verify its player in that comment instead. Do not treat a successful command exit as sufficient proof.\n\nAfter verification, remove temporary body snapshots, combined body/comment files, scenario, plan, raw WebM, and recording-only fixtures. Preserve the approved MP4 and its take-specific `.scenario.mjs` snapshot until the upload and rendering are confirmed; keep the script available alongside any retained video. Remove these review artifacts afterward only if the user does not want to keep them. Check `git status --short` and confirm no recording artifacts or temporary config changes remain.\n", "skills/record-pr-demo/references/recording-jobs.md": "# Recording jobs\n\nUse the job API when an agent starts a recording. It supervises the whole candidate command, including validation, capture, and conversion, independently of the prompt. It currently supports macOS and Linux.\n\n```sh\nnode .agents/skills/record-pr-demo/scripts/recording-job.mjs start \\\n  --scenario /tmp/demo.mjs --label feature-take-1\n```\n\nThe JSON result contains a job ID, output path, and log path. Artifacts live in a private temporary job directory. Inspect the returned log for progress.\n\nWhile the prompt is active, call `renew` about every 20 seconds. Each explicit renewal extends the lease by 60 seconds. Never put renewals in a background loop or inside the recording script: they must stop when the agent stops working.\n\n```sh\nnode .agents/skills/record-pr-demo/scripts/recording-job.mjs renew JOB_ID\nnode .agents/skills/record-pr-demo/scripts/recording-job.mjs status JOB_ID\nnode .agents/skills/record-pr-demo/scripts/recording-job.mjs stop JOB_ID\n```\n\n`status` never renews the lease. Omit the ID to list active jobs, including jobs whose start response was interrupted. Incomplete or corrupt metadata is reported separately in `unreadableJobs` and does not prevent other jobs from being listed. After `stop`, poll status until it reports `cancelled`, `failed`, or `completed` before reporting the outcome.\n\nIf the prompt is canceled, renewals cease and the supervisor interrupts the job after the lease expires. It allows up to 10 seconds for graceful shutdown, then kills remaining recording processes. Explicit stop requests and the default 10-minute maximum job duration use the same cleanup path. `start` accepts `--lease-seconds` and `--max-seconds` to change these limits.\n\nCanceled and failed jobs discard their own artifact directory, including partial MP4s from conversion. Successful jobs retain the MP4, script snapshot, contact sheet, and manifest for review. Status and logs remain available. Jobs manage their own output paths; output-path flags from the direct candidate command are rejected.\n\nVerify the returned manifest before an approved upload. Starting a job never uploads it. Direct `prepare-demo.mjs candidate` remains available for interactive terminal use, without lease supervision.\n", "skills/record-pr-demo/references/recording.md": "# Recording a Feature Demo\n\nRead this reference when preparing, recording, converting, or revising a local demo.\n\n## Prerequisites\n\n- Repository dependencies are installed, including `@playwright/test`.\n- The relevant Payload dev server is running, normally with `pnpm run dev <suite>`.\n- Chromium is available to Playwright.\n- `ffmpeg` and `ffprobe` are installed for conversion.\n\nCheck prerequisites in one command:\n\n```bash\nnode .agents/skills/record-pr-demo/scripts/prepare-demo.mjs preflight\n```\n\nIf something is missing, report it and obtain any required installation approval rather than substituting an unrelated capture method. Keep the dev server running through candidate review and revisions instead of restarting it for every take.\n\n## Required window chrome\n\nFor presentation metadata, viewport resizing, and annotation APIs, read [window-chrome.md](window-chrome.md). Use the live browser preview to iterate on the shared component without recording a video. Every scenario must export `presentation` with a change kind, title, and description. Validation, preview, and recording always use the shared chrome; there is no page-only mode.\n\n## Plan the visible story\n\nKeep the recording narrow. A useful plan identifies:\n\n- the route and deterministic starting state;\n- the exact interactions the reviewer needs to see;\n- the final visible state that proves the feature works;\n- anything dynamic that must be seeded, hidden, or stabilized.\n\nPrefer 10–45 seconds. Avoid long typing sequences, setup screens, loading waits, repeated navigation, and unrelated admin chrome. Use clear fixture labels that make sense without narration.\n\n## Editorial annotations over the recording\n\nFor a known step sequence, declare `presentation.annotationSteps` and select the [sidebar API](window-chrome.md#step-sidebar). Call `showAnnotation` when an explanation becomes relevant and `hideAnnotation` when it no longer applies. Keep the scenario’s change metadata constant. For a multi-step sidebar, supply the step’s one-based `index` and the full declared step count as `total` on every call. For a single current sidebar note without declared steps, `index` and `total` default to 1. If the scenario uses annotations, show the initial note before `ready()` and keep it visible at that marker. Starting annotations after an unannotated opening is rejected. Recordings without annotations remain supported. The shared component controls layout, progress, and transitions; see [window-chrome.md](window-chrome.md).\n\n```js\nawait showAnnotation({\n  title: 'What changed',\n  body: 'The cursor stays visible above popup controls.',\n  index: 1,\n  total: 2,\n})\nawait pause(1600)\nawait hideAnnotation()\n```\n\nDo not inject annotations into the application. Floating annotations and the old `type`, `position`, and `width` options are rejected with a migration error. Use the annotation API without scenario CSS. Check text fit, contrast, and timing in the rendered MP4, and include substantive explanation in the written PR walkthrough as a text alternative.\n\n## Scenario module\n\nCreate the scenario outside the repository, for example `/tmp/payload-pr-demo-relationship-drawer.mjs`. It must export presentation metadata and default-export an async function:\n\n```js\nexport const presentation = {\n  change: {\n    kind: 'Feature',\n    title: 'Create a post',\n    description: 'Open a new post from the collection list.',\n  },\n}\n\nexport default async function scenario({ baseURL, click, expect, page, pause, ready }) {\n  await page.goto(`${baseURL}/admin/collections/posts`)\n\n  const createButton = page.getByRole('link', { name: 'Create new Post' })\n  await expect(createButton).toBeVisible()\n  await ready()\n\n  await click(createButton)\n  await expect(page.getByRole('heading', { name: 'Create new Post' })).toBeVisible()\n  await pause(1200)\n}\n```\n\nPrefer existing seeded data. Prepare additional starting data through UI gestures before `ready()` or optional API fixture hooks. API seeding is useful for larger datasets and specific starting states; when creating content is itself part of the demonstration, show it through the Admin.\n\n### Optional API fixtures\n\nThe `prepare-demo.mjs` command calls `setup({ request, baseURL, label })` before opening the walkthrough and passes its return value as `fixture` to the scenario. `teardown({ request, fixture, baseURL, label })` runs afterward, including when the walkthrough fails. Both hooks share an isolated Playwright API request context; authenticate it as needed. These hooks are outside the recorded interaction sequence.\n\n```js\nexport async function setup({ request }) {\n  const login = await request.post('/api/users/login', {\n    data: { email: 'dev@payloadcms.com', password: 'test' },\n  })\n  if (!login.ok()) throw new Error(`Fixture login failed: ${login.status()}`)\n\n  const response = await request.post('/api/posts', {\n    data: { title: 'Autumn launch' },\n  })\n  if (!response.ok()) throw new Error(`Fixture creation failed: ${response.status()}`)\n  return { post: (await response.json()).doc }\n}\n\nexport async function teardown({ request, fixture }) {\n  const response = await request.delete(`/api/posts/${fixture.post.id}`)\n  if (!response.ok()) throw new Error(`Fixture cleanup failed: ${response.status()}`)\n}\n```\n\nCandidate mode prepares and removes a separate fixture for validation and recording. Make hooks repeatable, use a dedicated demo database, and remove only records the hook created. If setup fails after partial creation, setup must undo that partial work itself; teardown runs only after setup succeeds. The lower-level recorder functions do not orchestrate hooks; use `prepare-demo.mjs` when a scenario exports them.\n\nUse semantic locators where practical. Assert each important state before continuing so the recording fails instead of capturing the wrong screen. Let the final proof remain visible for at least a moment.\n\nThe recorder supplies:\n\n- `chrome.back` / `chrome.forward`: visible recording-window history buttons. Use `await click(chrome.back)` or `await click(chrome.forward)` for paced pointer gestures; unavailable directions are disabled.\n- `chrome.refresh`: reloads the application frame through the persistent toolbar button; use `await click(chrome.refresh)` for a visible refresh gesture.\n- `baseURL`: normalized without a trailing slash;\n- `click(locator, options?)`: smoothly moves to a locator, pauses, clicks, and pauses again;\n- `expect`: Playwright assertions;\n- `moveCursor(locator, options?)`: smoothly points at a locator and pauses without clicking;\n- `circleCursor(locator, options?)`: approaches a visible target, makes two tight loops near its center, and eases to rest without clicking;\n- `page`: the application iframe facade; navigation, locators, and evaluation target the app, while input devices and page events use the recording page;\n- `pressKey({ key, settleMs = 800 })`: press a key or shortcut with an 80ms hold, then let its result settle; validation skips the hold and settling time. The key logger observes the real key event immediately. Override `settleMs` when an action needs more or less time;\n- `pause(milliseconds = 700)`: a short presentation pause;\n- `ready()`: marks the loaded opening state and holds it for 1.2 seconds; call it exactly once before the first visible interaction;\n- `typeText({ locator, text, clear = false, delay = 50 })`: click to focus, optionally select all with `ControlOrMeta+A`, then type character by character;\n- `scroll(locator, options?)`: defaults to wheel input with the cursor inside the visible target; use `{ input: 'wheel', cursorPlacement: 'inside' }` for paced wheel scrolling with position verification;\n- `showAnnotation(options)` / `hideAnnotation()`: updates or clears the step note in the shared chrome panel;\n- `label`: the normalized recording label.\n\n## Gesture-based interactions\n\nThe scenario drives the same controls a person uses:\n\n- Open the starting route with one `page.goto()` before UI preparation and `ready()`. Reach subsequent routes by clicking visible links, navigation items, breadcrumbs, or buttons. Do not jump to known document URLs between steps.\n- Use the recorder's `click` helper for pointer actions. Use `pressKey({ key })` for shortcuts and navigation keys, and `typeText` or `page.keyboard.type()` for paced typing after focusing the control with a click. Do not use `fill()`, `selectOption()`, synthetic event dispatch, or DOM value assignments.\n- Use `scroll` with `input: 'wheel'` and `cursorPlacement: 'inside'` for visible scrolling. Reveal offscreen controls with a wheel gesture before clicking them; do not rely on locator auto-scrolling.\n- In the scenario function, create and reset content through these same gestures, including UI preparation before `ready()`. Put optional API seeding and cleanup in `setup`/`teardown`, outside the walkthrough. Do not call REST endpoints, the Local API, application functions, or mutate browser storage to advance the demonstrated interaction.\n- Locators, assertions, network observation, and read-only DOM measurements may verify state. Presentation annotations, window framing, recording, encoding, and verification are harness operations.\n\nFor example, edit a focused field through keyboard input:\n\n```js\nawait click(page.getByRole('textbox', { name: 'Title', exact: true }))\nawait pressKey({ key: 'ControlOrMeta+A' })\nawait page.keyboard.type('Halloween Sale', { delay: 50 })\nawait click(page.getByRole('button', { name: 'Save', exact: true }))\n```\n\nIf a refresh is part of the story, use `await click(chrome.refresh)` and assert the resulting UI. This visibly clicks the persistent toolbar button, reloads only the app frame, and spins the icon while it loads. Do not call `page.reload()` to advance the application during the walkthrough.\n\nThe recorder supplies cursor and click feedback automatically. Scenarios do not mount or style it. Keep the scenario on one page; separate browser-window stitching is outside this skill's current scope.\n\nUse `click` for visible interactions instead of calling `locator.click()` directly. Its defaults are a 450 ms eased cursor movement plus a 300 ms dwell before and after the click. `moveCursor` uses the same travel time and pauses for 300 ms after arriving. Override an individual action when the story needs more time:\n\n```js\nawait click(saveButton, { after: 900 })\nawait moveCursor(disabledDestination, { duration: 900, pauseAfter: 1200 })\n```\n\nCursor travel duration includes browser input processing time. Use the gesture’s `pauseAfter` (or `click`’s `after`) for a single reading hold before continuing. A following `pause()` adds to that hold; reserve it for a separate reading moment.\n\nChange the recording-wide defaults with `--mouse-move-ms` and `--interaction-pause-ms`. Keep a nonzero dwell for review recordings; faster values are mainly useful for recorder tests.\n\n## Circle a result for emphasis\n\nUse `circleCursor` selectively when the viewer should inspect a value or changed state. It moves to the area, makes two tight, slightly asymmetric loops near the focus point, and slows smoothly at the end. Ordinary navigation still uses `click` and `moveCursor`.\n\n```js\nawait circleCursor(page.locator('.tenant-selector'), {\n  duration: 1200,\n  pauseAfter: 700,\n})\n```\n\nThe default radius is 16 application CSS pixels, independent of the target's size. The gesture draws attention near a value rather than outlining the whole control. An optional positive `radius` adjusts the loop size. Use `position: { x, y }`, measured from the target padding box, to focus on a specific value within a larger control. Near a viewport edge the loop shifts inward to stay visible. It preserves focus and never clicks or draws on the application. Use the smallest meaningful visible locator; reveal offscreen targets with wheel scrolling first. Validation and screenshot preview retain the path but skip its presentation timing.\n\n## Scroll with wheel gestures\n\nDestructure `scroll` from the scenario argument and target the element whose `scrollTop` or `scrollLeft` changes, including an overflowing popup list. Always select wheel input and keep the pointer inside the target for real hit testing:\n\n```js\nawait scroll(tabsScroller, {\n  axis: 'x',\n  to: 'end',\n  duration: 950,\n  input: 'wheel',\n  cursorPlacement: 'inside',\n})\nawait click(revealedTab)\n```\n\nFor menus, click the trigger, wheel-scroll the actual overflowing list, then click the revealed item. Use a selector from the real markup. The helper sends small timed wheel deltas and verifies the resulting position; it never repairs a failed wheel gesture by assigning scroll offsets. Hover changes are expected. Choose a cursor position or pause that keeps the interaction readable rather than hiding tooltips or mutating application styles.\n\n`click` and `moveCursor` target the visible, unobstructed part of a control and never auto-scroll. Both the pointer and click use the same outer-page coordinates, including iframe scaling. An optional `position: { x, y }` is relative to the control's padding box in application CSS pixels and never falls back to another point. Clicks wait for enabled, stable controls and recheck the actual pointer position after the dwell; if the target moves away or becomes covered, the take fails rather than reporting a successful click.\n\nWait for completed application state before the next gesture. A selected label may update before server-rendered form data arrives: start `page.waitForResponse()` before the selection click, await the relevant successful refresh response, then assert the resulting form values before typing. Match an item's name independently of status badges (for example a Merged badge) so repeat validation can find it.\n\nThe lower-level helper also supports `input: 'animation'` for recorder development. It assigns scroll offsets and is not permitted in feature demo scenarios. Raw wheel calls bypass the helper's pacing and verification; use the helper instead.\n\n## Fast path\n\nFrom the repository root:\n\n```bash\nnode .agents/skills/record-pr-demo/scripts/prepare-demo.mjs candidate \\\n  --scenario /tmp/payload-pr-demo-relationship-drawer.mjs \\\n  --label relationship-drawer-take-1\n```\n\nCandidate mode automatically:\n\n1. checks Playwright, Chromium, ffmpeg, ffprobe, and the running server;\n2. validates the scenario without retaining video or presentation delays;\n3. records once with human-readable pacing;\n4. converts to H.264 MP4 and fully decodes it to detect corruption;\n5. writes a six-frame contact sheet, a take-specific `.scenario.mjs` copy, and a JSON manifest containing metadata and hashes;\n6. removes the lossless Matroska intermediate after successful packaging.\n\nIt ends at the local review gate and never uploads.\n\nCandidate mode refuses to overwrite an existing MP4, script snapshot, contact sheet, or manifest. It also rejects packaging if the scenario source changed during the take. Use a new take-specific `--label` for a revision so previously reviewed evidence remains intact.\n\nDuring scenario development, use the faster modes independently:\n\n```bash\nnode .agents/skills/record-pr-demo/scripts/prepare-demo.mjs validate \\\n  --scenario /tmp/payload-pr-demo-relationship-drawer.mjs\n\nnode .agents/skills/record-pr-demo/scripts/prepare-demo.mjs preview \\\n  --scenario /tmp/payload-pr-demo-relationship-drawer.mjs \\\n  --label relationship-drawer\n```\n\n`validate` runs the scenario without video or interaction delays. `preview` writes one final-state PNG, including the cursor position, so cursor and layout changes do not require a full recording.\n\nAfter asserting the first meaningful state, call `await ready()` before the first interaction. Candidate mode uses that marker to trim browser startup and leaves a 1.2-second hold on the loaded page. Recording fails if the marker is missing. Inspect the first frame of the candidate, especially after a cold server start.\n\nUseful options:\n\n- `--base-url http://localhost:4000`\n- `--viewport 1280x720`\n- `--output /tmp/custom-demo.mp4`\n- `--mouse-move-ms 450`\n- `--interaction-pause-ms 300`\n- `--contact-sheet /tmp/custom-demo-contact-sheet.png`\n- `--manifest /tmp/custom-demo.json`\n\nThe lower-level `record-demo.mjs` remains available for debugging the recorder itself. `convert-demo.mjs` is used internally by `prepare-demo.mjs` with the opening state marked by `ready()`. Use `prepare-demo.mjs` for PR demos so conversion, verification, and cleanup stay together.\n\n## Review the recording script\n\nEach candidate saves the scenario module beside its MP4 as `<video-name>.scenario.mjs`. The manifest records `scenarioSnapshot` and `scenarioSha256`; the original scenario path remains in `scenario`. Later edits to the working scenario do not change an earlier take's copy. The snapshot contains the scenario module, not its imported dependencies or the recorder runtime.\n\nPresent the script link alongside the video, using the absolute snapshot path, and open it in the Codex editor when available. Keep scenarios readable: use multi-line JavaScript and identify preparation, annotations, interactions, and assertions clearly. For another take, edit the working scenario and use a new label; preserve earlier snapshots with their videos.\n\n## Review the candidate\n\nThe command prints the MP4, duration, size, SHA-256, script snapshot, contact sheet, and manifest paths. Inspect the contact sheet first, then watch the entire video. Confirm that the opening frame is meaningful, actions are readable, no sensitive data is visible, and the final state proves the feature. Show the local MP4 and a clickable script snapshot link to the user, then stop for review.\n\nIf the file exceeds 10 MB, shorten the scenario first. Adjusting conversion quality with the lower-level converter is secondary. Do not silently raise the size budget because the applicable GitHub limit depends on the repository's plan and the uploader's access.\n\n## Accessibility observations\n\nOpt in per scenario:\n\n```js\nexport const presentation = {\n  accessibility: true,\n  change: {\n    kind: 'Fix',\n    title: 'Reorder sections with the keyboard',\n    description: 'Follow keyboard commands and movement announcements.',\n  },\n}\n```\n\nSet `presentation.accessibility: true` to show navigation keys and shortcuts. Ordinary character typing, spaces typed into editable fields, and input originating in password fields or `[data-private]` containers are excluded. Command history resets on navigation or presentation reset.\n\nAlso set `presentation.showAnnouncements: true` to display observed live-region text. This captures DOM text, not actual screen-reader audio. Feedback remains available when the step note is hidden. The recorder preserves application focus and native focus styling; it adds no focus outline.\n\nUse `pressKey({ key: 'Tab' })` and `pressKey({ key: 'Enter', settleMs: 800 })` for real keyboard events with readable pacing. Long announcements and older history may truncate, so verify the relevant evidence in the finished take. Preview with `?accessibility&announcements&kind=fix`; layout and styling come from the shared component.\n\n### Reuse a scenario with or without a11y feedback\n\nPass `--a11y on` or `--a11y off` to `prepare-demo.mjs` for candidate, preview, or validate mode, or to `record-demo.mjs`. `on` enables the integrated feedback, key history, and observed announcement captions; `off` disables the entire a11y presentation and observer. Omitting the flag preserves `presentation.accessibility` and `presentation.showAnnouncements`. These options do not change application accessibility or the walkthrough script. Use different take labels to keep each result reviewable. The candidate manifest records the override, cursor timing, click pauses, and viewport alongside the unchanged scenario snapshot.\n\n```sh\nnode .agents/skills/record-pr-demo/scripts/prepare-demo.mjs candidate --scenario /tmp/demo.mjs --a11y on --label demo-a11y\nnode .agents/skills/record-pr-demo/scripts/prepare-demo.mjs candidate --scenario /tmp/demo.mjs --a11y off --label demo-clean\n```\n\n### Capture resolution and encoding\n\nThe default canvas fits the initial application viewport at 1:1 scale, including space for chrome and annotations. With the left sidebar, a 1440×900 viewport produces an 1794×1086 video so the initial app window stays at 1:1 scale. Accessibility feedback appears at the bottom of the sidebar and uses the same canvas dimensions. The canvas stays fixed during responsive resizing. An explicit `presentation.canvas` overrides those dimensions and can scale the app to fit. `--viewport` controls the application iframe's CSS dimensions.\n\nThe MP4 converter uses H.264 CRF 18 to preserve detail through conversion. The existing 10 MB review/upload budget still applies.\n\nThe Chromium recorder streams PNG frames into a temporary FFV1 `.mkv` without writing individual images. Idle frames repeat at 25 fps to preserve presentation timing. The MP4 conversion is the only lossy encode; successful packaging deletes the intermediate. Lossless intermediates use more temporary disk space and CPU than the final MP4.\n", "skills/record-pr-demo/references/window-chrome.md": "# Shared recording chrome\n\nThe preview, validation, and recording mount the same browser component: [WindowChrome/index.mjs](../scripts/WindowChrome/index.mjs). That component is the source of truth for layout, styling, and animation. Scenarios supply presentation data and interactions; do not recreate the chrome or add scenario CSS.\n\n## Iterate without rendering video\n\n```bash\nnode .agents/skills/record-pr-demo/scripts/preview-chrome.mjs\n```\n\nOpen `http://127.0.0.1:4400`. Use `--port 4401` if needed. The server binds to loopback and serves only the preview assets. Edits appear on reload.\n\nThe preview contains a sample application, not Payload Admin. Use its viewport controls and timeline to inspect resizing. Light and Dark switch the chrome and sample application together, preserving the current viewport and timeline position. Query options include `?theme=dark`, `?kind=fix`, `?kind=bug` for the before-state overview label, and `?accessibility&announcements&kind=fix`. Review real application behavior in a scenario against the relevant Payload server.\n\n## Required scenario metadata\n\nEvery scenario must export `presentation`; missing metadata or `presentation: false` fails before the browser starts.\n\n```js\nexport const presentation = {\n  change: {\n    kind: 'Feature', // 'Feature', 'Fix', or 'Bug' for a before recording\n    title: 'Responsive collection lists',\n    description: 'Browse and manage content on desktop, tablet, and mobile.',\n  },\n  // Optional canvas override: even dimensions, at least 800×600.\n  theme: 'light', // 'light' or 'dark', fixed for the take\n  accessibility: false,\n  showAnnouncements: false,\n}\n```\n\n`--viewport` sets the initial application's CSS viewport. By default, the canvas fits that viewport at native scale, with room for the chrome and description: 1794×1086 for the default 1440×900 viewport, including with accessibility feedback. It stays fixed during responsive resizing. An explicit `presentation.canvas` overrides both the composition and encoded video dimensions and may scale the app to fit. See [capture resolution and encoding](recording.md#capture-resolution-and-encoding).\n\nThe window header automatically displays the current application viewport dimensions and updates them during resizing.\n\n## Step sidebar\n\nThe sidebar is the only annotation layout. For a known sequence viewers may need to reference, declare `annotationSteps`:\n\n```js\nconst steps = [\n  { title: 'Switch locale', body: 'Switch to Spanish, then go Back to the English document.' },\n  {\n    title: 'Locale mismatch',\n    body: 'English content is rendered, but Spanish remains selected.',\n    kind: 'Bug',\n  },\n]\n\nexport const presentation = {\n  annotationSteps: steps,\n  change: {\n    kind: 'Bug',\n    title: 'Locale mismatch after Back',\n    description: 'After Back, edits can save to the wrong translation.',\n  },\n}\n\n// After asserting the visible failure:\nawait showAnnotation({ ...steps[1], index: 2, total: steps.length })\n```\n\nEach step accepts `title`, `body`, and optional `kind: 'Bug'`. Titles remain required by `showAnnotation`; the sidebar displays body text and optional Bug markers. Reuse the declared entry when calling `showAnnotation`: its body, one-based index, and total must match the list. Use a step's `kind` to identify a demonstrated failure, not a setup or navigation action. The scenario's `change.kind` describes the whole walkthrough: Bug for before, Fix for after, or Feature for a feature demonstration.\n\nThe renderer handles layout, styling, step indicators, and scrolling. Scripts should advance the current step through `showAnnotation`, rather than manipulating the sidebar DOM or scroll position. Playground step selection is an inspection control, not a scenario API.\n\nWithout declared steps, `showAnnotation` displays the current note in the sidebar. Hiding annotations leaves the overview and enabled accessibility feedback visible. Keyboard history and announcement captions appear at the bottom of the sidebar. The playground provides Demo type and Many steps controls for inspection.\n\n## URL bar\n\nThe window header shows the live application URL, including its query string and hash. It follows document navigation and History API changes, including browser Back. It is read-only and does not change the application's URL. Credentials in URLs are omitted; non-web content shows only its protocol. The live preview uses the same bar.\n\n## History buttons\n\nBack and Forward in the window header navigate the application's own frame history. Buttons disable when that direction is unavailable. Scenarios use `await click(chrome.back)` and `await click(chrome.forward)` so the cursor visibly clicks the controls. They share the standard cursor movement, dwell and click feedback.\n\n## Presentation helpers\n\n- `showAnnotation({ title, body, index = 1, total = 1 })` replaces the step note. Pagination is one-based; the change title and description stay constant.\n- `hideAnnotation()` clears the step note while preserving the change description and any enabled accessibility feedback.\n- `setAnnotation` and `clearAnnotation` are compatibility aliases. `setAnnotation(null)` also clears the note; prefer `showAnnotation` and `hideAnnotation` in new scenarios.\n- `resizeWindow({ width, height, duration = 1000 })` animates the actual iframe viewport. Await it before another resize. Dimensions must be positive integers up to 7680×4320. Use it only when responsive reflow is part of the story.\n- `page` scopes navigation, locators, and evaluation to the application iframe; input devices, context, and page events belong to the containing recording page. `page.addInitScript` installs context-wide scripts for subsequent navigations. `page.goBack()` and `page.goForward()` are unsupported because browser history is shared with the wrapper.\n\nFloating annotations and `type`, `position`, and `width` options are unsupported. a mismatched declared step is rejected without replacing the previous note. The sidebar scrolls to keep the active step visible. Supplied content is inserted as text, not markup.\n\nThe component handles progress, transitions, reduced motion, and feedback visibility. Validation and screenshot preview apply presentation updates immediately. Inspect the final MP4 for legibility and pacing; do not duplicate the renderer's visual rules in scenario instructions.\n\nFor scenario examples, gesture requirements, and optional accessibility observations, see [recording.md](recording.md).\n\n## Capture architecture\n\nThe recorder captures one browser page containing the chrome and a live application iframe. A locally intercepted wrapper URL uses the application's origin. Application security headers remain intact; applications that prohibit framing cannot be recorded with this tool.\n\nResizing changes the iframe's CSS dimensions, so responsive breakpoints run at their real widths. The component scales the surrounding window uniformly to fit the composition. There is no screenshot relay or second app browser context.\n\n`ready()` and final screenshots wait for the composed page to render. Layout is shared across modes, but network requests, application animations, browser scheduling, and encoded bytes are not deterministic. Use assertions and repeatable starting data as described in [recording.md](recording.md).\n\n## Refresh feedback\n\n`await page.reload()` is a lower-level harness capability that reloads only the application iframe and reports loading, success, or failure in the chrome. Navigation and HTTP errors propagate to the scenario. Await a reload before starting another. Feature walkthroughs click `chrome.refresh` when demonstrating refresh; see the [gesture contract](recording.md#gesture-based-interactions).\n\nThe **Refresh frame** button sits between Forward and the URL bar in both preview and recordings. It stays visible and dim when idle, spins while the app reloads, and returns to the same dim icon afterward. Scenarios can click it with `await click(chrome.refresh)`. The playground’s **Simulate refresh** control reloads the frame with a brief minimum loading duration so the spinner is easy to inspect. Application-initiated navigations are not labeled as recorder refreshes.\n\n## Verification and accessibility boundaries\n\n```bash\nnode --test .agents/skills/record-pr-demo/scripts/*.test.mjs\n```\n\nBrowser tests mount the actual component. They cover resizing, annotation validation and transitions, reduced motion, focus preservation, keyboard history, and refresh feedback. Recorder integration checks the live iframe, encoded dimensions and pixels, video decode, and fast validation. Preview tests exercise keyboard controls and narrow host viewports.\n\nAccessibility evidence is scoped to the recording chrome and preview controls. Relevant WCAG 2.2 A/AA criteria include decorative feedback (1.1.1), structure and labels (1.3.1), non-color progress cues (1.4.1), preview reflow (1.4.10), keyboard operation (2.1.1), playback control (2.2.2), focus preservation (2.4.3, 2.4.7, 2.4.11), control semantics (4.1.2), and status updates (4.1.3). Automated evidence does not establish product or video conformance. Review contrast (1.4.3, 1.4.11), text resizing and spacing (1.4.4, 1.4.12), target sizes (2.5.8), visual focus, timing, and exact screen-reader announcements in their relevant rendered contexts.\n\nAccessibility feedback observes DOM text, not screen-reader audio. It is hidden from assistive technology, does not intercept input, and adds no application focus outline. Earlier commands use quieter keycaps; do not rely on it as the sole evidence of a keyboard action. The scaled preview is not an accessible replacement for operating the application.\n", "skills/record-pr-demo/scripts/accessibility-demo.mjs": "/** Observes app events for a demo; these captions are DOM text, not screen-reader output. */\nexport function observeAccessibility({ window: target = window, report }) {\n  const document = target.document\n  let observer\n  const regionSelector = '[aria-live], [role=\"status\"], [role=\"alert\"], [role=\"log\"]'\n  const normalize = (text) => (text ?? '').replace(/\\s+/g, ' ').trim()\n  const keys = {\n    Tab: 'Tab',\n    Enter: 'Enter',\n    ' ': 'Space',\n    Escape: 'Esc',\n    ArrowUp: '↑',\n    ArrowDown: '↓',\n    ArrowLeft: '←',\n    ArrowRight: '→',\n    Home: 'Home',\n    End: 'End',\n    PageUp: 'Page Up',\n    PageDown: 'Page Down',\n    Backspace: 'Backspace',\n    Delete: 'Delete',\n  }\n  const keydown = (event) => {\n    const eventPath = event.composedPath()\n    const origin = eventPath[0]\n    if (eventPath.some((element) => element.matches?.('input[type=\"password\"], [data-private]')))\n      return\n    const key =\n      keys[event.key] ??\n      ((event.ctrlKey || event.metaKey || event.altKey) && /^[a-z0-9]$/i.test(event.key)\n        ? event.key.toUpperCase()\n        : undefined)\n    if (!key || !event.isTrusted) return\n    if (\n      event.key === ' ' &&\n      origin?.closest?.('input, textarea, [contenteditable]:not([contenteditable=\"false\"])')\n    )\n      return\n    report({\n      key: [\n        event.ctrlKey && 'Ctrl',\n        event.metaKey && '⌘',\n        event.altKey && 'Alt',\n        event.shiftKey && 'Shift',\n        key,\n      ]\n        .filter(Boolean)\n        .join(' + '),\n    })\n  }\n  const captionRegion = (region) => {\n    if (!region?.isConnected) return\n    for (let element = region; element; element = element.parentElement) {\n      if (\n        element.hidden ||\n        element.getAttribute('aria-hidden') === 'true' ||\n        element.getAttribute('aria-busy') === 'true'\n      )\n        return\n      const style = target.getComputedStyle(element)\n      if (style.display === 'none' || style.visibility === 'hidden') return\n    }\n    const live = region.getAttribute('aria-live')\n    if (\n      live === 'off' ||\n      (!live && !['status', 'alert', 'log'].includes(region.getAttribute('role')))\n    )\n      return\n    const text = normalize(region.textContent)\n    if (text) report({ announcement: text })\n  }\n  const start = () => {\n    report({ reset: true })\n    document.addEventListener('keydown', keydown, true)\n    observer = new target.MutationObserver((records) => {\n      const regions = new Set()\n      for (const record of records) {\n        const element = record.target.nodeType === 1 ? record.target : record.target.parentElement\n        const region = element?.closest(regionSelector)\n        if (region) regions.add(region)\n        if (record.type === 'attributes') {\n          for (const nested of element.querySelectorAll(regionSelector)) regions.add(nested)\n        }\n        for (const node of record.addedNodes) {\n          if (node.nodeType !== 1) continue\n          if (node.matches(regionSelector)) regions.add(node)\n          for (const nested of node.querySelectorAll(regionSelector)) regions.add(nested)\n        }\n      }\n      for (const region of regions) captionRegion(region)\n    })\n    observer.observe(document, {\n      subtree: true,\n      childList: true,\n      characterData: true,\n      attributes: true,\n      attributeFilter: ['aria-busy', 'aria-hidden', 'aria-live', 'hidden'],\n    })\n  }\n  if (document.readyState === 'loading')\n    document.addEventListener('DOMContentLoaded', start, { once: true })\n  else start()\n  return () => {\n    observer?.disconnect()\n    document.removeEventListener('keydown', keydown, true)\n    document.removeEventListener('DOMContentLoaded', start)\n  }\n}\n", "skills/record-pr-demo/scripts/accessibility-demo.test.mjs": "import assert from 'node:assert/strict'\nimport { test } from 'node:test'\nimport { chromium, expect } from '@playwright/test'\nimport { createPresentation } from './presentation-demo.mjs'\n\nconst html = `<!doctype html><html><body style=\"margin:40px;font:20px system-ui\">\n<style>button:focus-visible { outline:2px solid rgb(120,50,180); outline-offset:3px }</style>\n<button id=\"first\">First control</button><button id=\"second\">Second control</button>\n<input aria-label=\"Private\" type=\"password\"><input aria-label=\"Title\">\n<div role=\"status\" id=\"status\"></div><div aria-live=\"off\" id=\"off\"></div>\n<div role=\"alert\" aria-busy=\"true\" id=\"busy\"></div>\n<div role=\"status\" hidden id=\"hidden\"></div>\n<dialog><button>Dialog action</button></dialog>\n<script>document.querySelector('#second').addEventListener('keydown',e=>{if(e.key==='ArrowDown')document.querySelector('#status').textContent='Moved to position 2'})</script>\n</body></html>`\n\nasync function withPresentation({ accessibility = true, showAnnouncements = true, run }) {\n  const browser = await chromium.launch({ headless: true })\n  const context = await browser.newContext({ viewport: { width: 1600, height: 1000 } })\n  await context.route('http://localhost:3000/fixture*', (route) =>\n    route.fulfill({ contentType: 'text/html', body: html }),\n  )\n  const stage = await context.newPage()\n  let presentation\n  try {\n    presentation = await createPresentation({\n      page: stage,\n      options: {\n        canvas: { width: 1600, height: 1000 },\n        accessibility,\n        showAnnouncements,\n        change: {\n          kind: 'Fix',\n          title: 'Keyboard reordering',\n          description: 'Keep movement and focus visible.',\n        },\n      },\n      viewport: { width: 1800, height: 1100 },\n      pauseScale: 1,\n    })\n    await presentation.setAnnotation({\n      title: 'Move a row',\n      body: 'Use the keyboard to reorder content.',\n      index: 1,\n      total: 2,\n    })\n    await presentation.appPage.goto('http://localhost:3000/fixture')\n    await run({ stage, app: presentation.appPage, presentation })\n  } finally {\n    await presentation?.stop()\n    await browser.close()\n  }\n}\n\ntest('should leave accessibility overlays absent unless enabled', async () => {\n  await withPresentation({\n    accessibility: false,\n    run: async ({ stage }) => {\n      await expect(stage.locator('[data-accessibility], .sidebar-feedback')).toHaveCount(0)\n      await expect(stage.locator('[data-focus-highlight]')).toHaveCount(0)\n    },\n  })\n})\n\ntest('should show trusted navigation keys without exposing ordinary or password typing', async () => {\n  await withPresentation({\n    run: async ({ stage, app }) => {\n      await app.locator('#first').focus()\n      await stage.keyboard.press('Tab')\n      await expect(app.locator('#second')).toBeFocused()\n      await expect(stage.locator('[data-keystroke]')).toHaveText('Tab')\n      await stage.keyboard.press('ArrowDown')\n      await expect(stage.locator('[data-keystroke]')).toHaveText('↓')\n      await expect(stage.locator('[data-announcement]')).toHaveText('Moved to position 2')\n      await app.getByRole('textbox', { name: 'Title' }).focus()\n      await stage.keyboard.type('Private ordinary typing')\n      await expect(stage.locator('[data-keystroke]')).toHaveText('↓')\n      await app.locator('input[type=password]').focus()\n      await stage.keyboard.press('ControlOrMeta+A')\n      await stage.keyboard.type('secret')\n      await expect(stage.locator('[data-keystroke]')).toHaveText('↓')\n      await expect(stage.locator('[data-accessibility]')).toHaveAttribute('aria-hidden', 'true')\n    },\n  })\n})\n\ntest('should preserve application focus styling in dialogs and scaled views without adding an outline', async () => {\n  await withPresentation({\n    run: async ({ stage, app, presentation }) => {\n      await app.locator('#first').focus()\n      await stage.keyboard.press('Tab')\n      await expect(app.locator('#second')).toBeFocused()\n      await expect(app.locator('#second')).toHaveCSS('outline-color', 'rgb(120, 50, 180)')\n      await expect(app.locator('#second')).toHaveCSS('outline-width', '2px')\n      await expect(app.locator('#second')).toHaveCSS('outline-offset', '3px')\n      await expect(stage.locator('[data-focus-highlight]')).toHaveCount(0)\n      await expect(stage.locator('[data-accessibility]')).toBeVisible()\n      const panel = await stage.locator('[data-accessibility]').boundingBox()\n      const application = await stage.locator('[data-pr-demo-app]').boundingBox()\n      assert.ok(panel.x + panel.width <= application.x)\n      await app.locator('dialog').evaluate((el) => el.showModal())\n      const action = app.getByRole('button', { name: 'Dialog action' })\n      await expect(action).toBeFocused()\n      await expect(action).toHaveCSS('outline-color', 'rgb(120, 50, 180)')\n      await expect(stage.locator('[data-focus-highlight]')).toHaveCount(0)\n      await app.locator('dialog').evaluate((el) => el.close())\n      await presentation.resizeWindow({ width: 600, height: 700, duration: 0 })\n      await expect(app.locator('#second')).toBeFocused()\n      await expect(app.locator('#second')).toHaveCSS('outline-width', '2px')\n      await expect(app.locator('#second')).toHaveCSS('outline-color', 'rgb(120, 50, 180)')\n      await expect(stage.locator('[data-focus-highlight]')).toHaveCount(0)\n    },\n  })\n})\n\ntest('should caption region changes while ignoring off hidden and busy regions', async () => {\n  await withPresentation({\n    run: async ({ stage, app }) => {\n      const caption = stage.locator('[data-announcement]')\n      await app.locator('#status').evaluate((el) => (el.textContent = 'Saved'))\n      await expect(caption).toHaveText('Saved')\n      await app.evaluate(() => {\n        document.querySelector('#off').textContent = 'Ignore off'\n        document.querySelector('#hidden').textContent = 'Ignore hidden'\n        document.querySelector('#busy').textContent = 'Still busy'\n      })\n      await stage.waitForTimeout(100)\n      await expect(caption).toHaveText('Saved')\n      await app.locator('#busy').evaluate((el) => el.setAttribute('aria-busy', 'false'))\n      await expect(caption).toHaveText('Still busy')\n      await app.evaluate(() => {\n        const region = document.createElement('div')\n        region.setAttribute('role', 'alert')\n        region.textContent = 'New alert'\n        document.body.append(region)\n      })\n      await expect(caption).toHaveText('New alert')\n      await app.goto('http://localhost:3000/fixture?next')\n      await app.locator('#status').evaluate((el) => (el.textContent = 'After navigation'))\n      await expect(caption).toHaveText('After navigation')\n      await app.reload()\n      await app.locator('#status').evaluate((el) => (el.textContent = 'After reload'))\n      await expect(caption).toHaveText('After reload')\n    },\n  })\n})\n\ntest('should reset key history on navigation and stop observing when the presentation stops', async () => {\n  await withPresentation({\n    run: async ({ stage, app, presentation }) => {\n      await app.locator('#first').focus()\n      await stage.keyboard.press('ArrowRight')\n      await expect(stage.locator('[data-keystroke]')).toHaveText('→')\n      await expect(stage.locator('[data-keystroke-overlay]')).toBeVisible()\n      await stage.keyboard.press('ArrowLeft')\n      await expect(stage.locator('[data-key-history-entry]')).toHaveText('→')\n      await app.goto('http://localhost:3000/fixture?reset')\n      await expect(stage.locator('[data-keystroke-overlay]')).toBeHidden()\n      await expect(stage.locator('[data-key-history-entry]')).toHaveCount(0)\n      await app.locator('#status').evaluate((el) => (el.textContent = 'Before stop'))\n      await expect(stage.locator('[data-announcement]')).toHaveText('Before stop')\n      await presentation.stop()\n      await app.locator('#status').evaluate((el) => (el.textContent = 'After stop'))\n      await stage.waitForTimeout(100)\n      await expect(stage.locator('[data-announcement]')).toHaveText('Before stop')\n    },\n  })\n})\n\ntest('should caption pending updates when a busy ancestor becomes available', async () => {\n  await withPresentation({\n    run: async ({ stage, app }) => {\n      await app.evaluate(() => {\n        const wrapper = document.createElement('div')\n        wrapper.id = 'busy-wrapper'\n        wrapper.setAttribute('aria-busy', 'true')\n        wrapper.innerHTML = '<div role=\"status\">Ready after loading</div>'\n        document.body.append(wrapper)\n      })\n      await stage.waitForTimeout(100)\n      assert.equal(\n        await stage.locator('[data-announcement]').textContent(),\n        'Waiting for an update…',\n      )\n      await app.locator('#busy-wrapper').evaluate((el) => el.setAttribute('aria-busy', 'false'))\n      await expect(stage.locator('[data-announcement]')).toHaveText('Ready after loading')\n    },\n  })\n})\n\ntest('should suppress keys from inputs inside private shadow hosts', async () => {\n  await withPresentation({\n    run: async ({ stage, app }) => {\n      await app.evaluate(() => {\n        const host = document.createElement('div')\n        host.id = 'private-host'\n        host.dataset.private = ''\n        host.attachShadow({ mode: 'open' }).innerHTML = '<input aria-label=\"Private shadow input\">'\n        document.body.append(host)\n      })\n      await app.getByRole('textbox', { name: 'Private shadow input' }).focus()\n      await stage.keyboard.press('ControlOrMeta+A')\n      await stage.waitForTimeout(100)\n      assert.equal(await stage.locator('[data-keystroke-overlay]').isVisible(), false)\n    },\n  })\n})\n\ntest('should keep key history inside the annotation panel without moving the application', async () => {\n  let plainWindow\n  await withPresentation({\n    accessibility: false,\n    showAnnouncements: false,\n    run: async ({ stage }) => {\n      plainWindow = await stage.locator('[data-window]').boundingBox()\n    },\n  })\n  await withPresentation({\n    showAnnouncements: false,\n    run: async ({ stage, app, presentation }) => {\n      await expect(stage.locator('[data-a11y-badge], [data-speaking-icon]')).toHaveCount(0)\n      await expect(stage.locator('[data-accessibility]')).toBeHidden()\n      await expect(stage.locator('.sidebar-feedback')).toBeHidden()\n      await expect(stage.locator('[data-announcement]')).toHaveCount(0)\n      const initialPanel = await stage.locator('.sidebar-shell').boundingBox()\n      const initialWindow = await stage.locator('[data-window]').boundingBox()\n      assert.deepEqual(initialWindow, plainWindow)\n      const overlay = stage.locator('[data-keystroke-overlay]')\n      await expect(overlay).toBeHidden()\n      await app.locator('#first').focus()\n      await stage.keyboard.press('Tab')\n      await expect(app.locator('#second')).toBeFocused()\n      await expect(overlay).toBeVisible()\n      await expect(stage.locator('.sidebar-feedback > .sidebar-heading')).toHaveText('Keyboard')\n      await expect(stage.locator('[data-keystroke]')).toHaveText('Tab')\n      await expect(overlay).toHaveCSS('pointer-events', 'none')\n      await expect(overlay).toHaveAttribute('aria-hidden', 'true')\n      const box = await overlay.boundingBox()\n      const windowBox = await stage.locator('[data-window]').boundingBox()\n      assert.ok(initialPanel.x + initialPanel.width <= windowBox.x + 1)\n      assert.ok(box.x >= initialPanel.x && box.y >= initialPanel.y)\n      assert.ok(box.x + box.width <= initialPanel.x + initialPanel.width)\n      assert.ok(box.y + box.height <= initialPanel.y + initialPanel.height)\n      assert.deepEqual(windowBox, initialWindow)\n      await stage.waitForTimeout(2100)\n      await expect(overlay).toBeVisible()\n      assert.deepEqual(await stage.locator('[data-window]').boundingBox(), initialWindow)\n      assert.deepEqual(await stage.locator('.sidebar-shell').boundingBox(), initialPanel)\n      await presentation.clearAnnotation()\n      await expect(stage.locator('.sidebar-steps')).toBeHidden()\n      await expect(overlay).toBeVisible()\n      assert.deepEqual(await stage.locator('[data-window]').boundingBox(), initialWindow)\n    },\n  })\n})\n\ntest('should keep captions and key history below the sidebar steps at every viewport', async () => {\n  await withPresentation({\n    run: async ({ stage, app, presentation }) => {\n      await app.locator('#first').focus()\n      for (const key of ['ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown', 'Enter']) {\n        await stage.keyboard.press(key)\n      }\n      await expect(stage.locator('[data-keystroke]')).toHaveText('Enter')\n      await expect(stage.locator('[data-key-history-entry]')).toHaveText(['↓', '→', '←'])\n      const previousColor = await stage\n        .locator('[data-key-history-entry] kbd')\n        .first()\n        .evaluate((el) => getComputedStyle(el).color)\n      const currentColor = await stage\n        .locator('[data-keystroke] kbd')\n        .first()\n        .evaluate((el) => getComputedStyle(el).color)\n      assert.notEqual(previousColor, currentColor)\n      await expect(stage.locator('[data-keystroke]')).toHaveCSS('opacity', '1')\n      for (const [index, opacity] of ['0.72', '0.5', '0.32'].entries()) {\n        await expect(stage.locator('[data-key-history-entry]').nth(index)).toHaveCSS(\n          'opacity',\n          opacity,\n        )\n      }\n      await expect(stage.locator('[data-a11y-badge], [data-speaking-icon]')).toHaveCount(0)\n      await app.locator('#status').evaluate((el) => {\n        el.textContent = 'Introduction moved to position 3 of 3.'\n      })\n      await expect(stage.locator('[data-caption]')).toBeVisible()\n      await expect(stage.locator('.sidebar-feedback > .sidebar-heading')).toHaveText(\n        'Activity & Keyboard',\n      )\n      await expect(stage.locator('[data-announcement]')).toHaveCSS('white-space', 'normal')\n      for (const viewport of [\n        { width: 1800, height: 1100 },\n        { width: 600, height: 700 },\n      ]) {\n        await presentation.resizeWindow({ ...viewport, duration: 0 })\n        const panel = await stage.locator('.sidebar-shell').boundingBox()\n        const appBox = await stage.locator('[data-window]').boundingBox()\n        const step = await stage.locator('.sidebar-step p').boundingBox()\n        const caption = await stage.locator('[data-announcement]').boundingBox()\n        const history = await stage.locator('[data-keystroke-overlay]').boundingBox()\n        assert.ok(panel.x + panel.width <= appBox.x + 1)\n        for (const box of [caption, history]) {\n          assert.ok(box.x >= panel.x && box.y >= panel.y)\n          assert.ok(box.x + box.width <= panel.x + panel.width)\n          assert.ok(box.y + box.height <= panel.y + panel.height)\n        }\n        assert.ok(step.y + step.height <= caption.y)\n        assert.ok(caption.y + caption.height <= history.y)\n        const row = await stage.locator('[data-accessibility]').boundingBox()\n        const change = await stage.locator('.sidebar-intro').boundingBox()\n        assert.ok(row.width >= panel.width * 0.85)\n        assert.ok(change.y + change.height <= row.y)\n      }\n    },\n  })\n})\n\ntest('should show each shortcut key in a separate keycap with plain plus separators', async () => {\n  await withPresentation({\n    showAnnouncements: false,\n    run: async ({ stage, app }) => {\n      await app.locator('#second').focus()\n      await stage.keyboard.press('Shift+Tab')\n      const chord = stage.locator('[data-keystroke]')\n      await expect(chord.locator('kbd')).toHaveText(['Shift', 'Tab'])\n      await expect(chord.locator('[data-key-separator]')).toHaveText('+')\n      await stage.keyboard.press('ControlOrMeta+Shift+ArrowDown')\n      await expect(chord.locator('kbd')).toHaveText([\n        process.platform === 'darwin' ? '⌘' : 'Ctrl',\n        'Shift',\n        '↓',\n      ])\n      await expect(chord.locator('[data-key-separator]')).toHaveCount(2)\n      await stage.keyboard.press('ArrowRight')\n      await expect(chord.locator('kbd')).toHaveText(['→'])\n      await expect(chord.locator('[data-key-separator]')).toHaveCount(0)\n    },\n  })\n})\n\ntest('should slide the previous command right at a scaled size and respect reduced motion', async () => {\n  await withPresentation({\n    run: async ({ stage, app }) => {\n      await stage.setViewportSize({ width: 1000, height: 800 })\n      await app.locator('#first').focus()\n      await stage.keyboard.press('ArrowUp')\n      await stage.waitForTimeout(250)\n      const previousLeft = await stage.locator('[data-keystroke]').evaluate((el) => {\n        window.previousCommand = el\n        return el.getBoundingClientRect().left\n      })\n      await stage.keyboard.press('ArrowDown')\n      const positions = await stage.locator('[data-key-history-entry]').evaluate((el) => {\n        const animation = el.getAnimations()[0]\n        if (!animation) throw new Error('Expected the prior command to animate')\n        animation.pause()\n        return [0, 110, 220].map((time) => {\n          animation.currentTime = time\n          return { x: el.getBoundingClientRect().left, isSameNode: el === window.previousCommand }\n        })\n      })\n      assert.ok(positions.every((position) => position.isSameNode))\n      assert.ok(Math.abs(positions[0].x - previousLeft) < 2)\n      assert.ok(positions[0].x < positions[1].x && positions[1].x < positions[2].x)\n      await stage.emulateMedia({ reducedMotion: 'reduce' })\n      await stage.keyboard.press('ArrowLeft')\n      await expect(stage.locator('[data-keystroke]')).toHaveText('←')\n      assert.equal(\n        await stage\n          .locator('[data-keystroke-overlay]')\n          .evaluate((el) => el.getAnimations({ subtree: true }).length),\n        0,\n      )\n      await expect(stage.locator('[data-key-history-entry]')).toHaveText(['↓', '↑'])\n    },\n  })\n})\n\ntest('should keep complete commands visible when keyboard history fills the sidebar', async () => {\n  await withPresentation({\n    showAnnouncements: false,\n    run: async ({ stage, app }) => {\n      await app.locator('#second').focus()\n      for (const key of [\n        'ControlOrMeta+Shift+ArrowDown',\n        'ControlOrMeta+Shift+ArrowRight',\n        'ControlOrMeta+Shift+ArrowUp',\n        'ControlOrMeta+Shift+ArrowLeft',\n      ]) {\n        await stage.keyboard.press(key)\n        await expect(stage.locator('[data-keystroke] kbd')).toHaveCount(3)\n        const geometry = await stage.locator('[data-keystroke-overlay]').evaluate((element) => ({\n          width: element.clientWidth,\n          content: element.scrollWidth,\n          count: element.children.length,\n        }))\n        assert.ok(geometry.content <= geometry.width + 1)\n        assert.ok(geometry.count >= 1)\n      }\n    },\n  })\n})\n\ntest('should keep shortcut groups separate throughout their slide', async () => {\n  await withPresentation({\n    run: async ({ stage }) => {\n      await stage.setViewportSize({ width: 1000, height: 800 })\n      const samples = await stage.evaluate(() => {\n        const root = document.querySelector('#demo-stage').shadowRoot\n        window.demoChrome.setAccessibilityState({ key: '⌘ + A' })\n        for (const animation of root.getAnimations({ subtree: true })) animation.finish()\n        window.demoChrome.setAccessibilityState({ key: 'Shift + Tab' })\n        const row = root.querySelector('[data-keystroke-overlay]')\n        const animations = [...row.children].flatMap((el) => el.getAnimations())\n        for (const animation of animations) animation.pause()\n        return [0, 55, 110, 165, 220].map((time) => {\n          for (const animation of animations) animation.currentTime = time\n          const [current, previous] = [...row.children].map((el) => el.getBoundingClientRect())\n          return { time, gap: previous.left - current.right }\n        })\n      })\n      for (const sample of samples) {\n        assert.ok(sample.gap >= 0, `Shortcut groups overlap at ${sample.time}ms`)\n      }\n    },\n  })\n})\n", "skills/record-pr-demo/scripts/annotation-demo.mjs": "export function createAnnotationInteraction({ presentation }) {\n  if (!presentation) throw new Error('Annotations require recording chrome')\n  let hasUsedAnnotations = false\n  let isAnnotationVisible = false\n  let isReady = false\n  let hasOpeningAnnotation = false\n  const openingAnnotationError = 'Show an initial annotation before ready() when using annotations.'\n  return {\n    markReady: () => {\n      if (hasUsedAnnotations && !isAnnotationVisible) throw new Error(openingAnnotationError)\n      hasOpeningAnnotation = isAnnotationVisible\n      isReady = true\n    },\n    hideAnnotation: async () => {\n      await presentation.clearAnnotation()\n      isAnnotationVisible = false\n    },\n    showAnnotation: async (options) => {\n      if (!options || typeof options !== 'object') {\n        throw new Error('Annotations require title and body')\n      }\n      if (['type', 'position', 'width'].some((key) => key in options)) {\n        throw new Error('Annotations always use the sidebar; remove type, position, and width')\n      }\n      if (isReady && !hasOpeningAnnotation) throw new Error(openingAnnotationError)\n      const { body, index = 1, total = 1, title } = options\n      await presentation.setAnnotation({ body, index, total, title })\n      hasUsedAnnotations = true\n      isAnnotationVisible = true\n    },\n  }\n}\n", "skills/record-pr-demo/scripts/annotation-demo.test.mjs": "import assert from 'node:assert/strict'\nimport { test } from 'node:test'\n\nimport { createAnnotationInteraction } from './annotation-demo.mjs'\n\ntest('should use the sidebar with a single annotation by default', async () => {\n  const updates = []\n  let clears = 0\n  const { showAnnotation, hideAnnotation } = createAnnotationInteraction({\n    presentation: {\n      setAnnotation: async (note) => updates.push(note),\n      clearAnnotation: async () => {\n        clears++\n      },\n    },\n  })\n  await showAnnotation({ title: 'Result', body: 'The feature works.' })\n  assert.deepEqual(updates, [{ index: 1, total: 1, title: 'Result', body: 'The feature works.' }])\n  await hideAnnotation()\n  assert.equal(clears, 1)\n})\n\ntest('should reject floating and placement options before changing annotations', async () => {\n  const { showAnnotation } = createAnnotationInteraction({\n    presentation: { setAnnotation: () => assert.fail('Invalid annotation must not render') },\n  })\n  for (const legacy of [\n    { type: 'floating' },\n    { type: 'panel' },\n    { position: { top: 20 } },\n    { width: 300 },\n  ]) {\n    await assert.rejects(\n      () => showAnnotation({ title: 'Invalid', body: 'Detail', ...legacy }),\n      /remove type, position, and width/,\n    )\n  }\n})\n\ntest('should require chrome for annotations', () => {\n  assert.throws(() => createAnnotationInteraction({}), /require recording chrome/)\n})\n\ntest('should require a visible opening note once annotations have been used', async () => {\n  const annotations = createAnnotationInteraction({\n    presentation: { setAnnotation: async () => {}, clearAnnotation: async () => {} },\n  })\n  await annotations.showAnnotation({ title: 'Opening', body: 'First note.' })\n  await annotations.hideAnnotation()\n  assert.throws(() => annotations.markReady(), /annotation.*before.*ready\\(\\)/i)\n  await annotations.showAnnotation({ title: 'Opening', body: 'First note.' })\n  annotations.markReady()\n  await annotations.hideAnnotation()\n  await annotations.showAnnotation({\n    title: 'Next',\n    body: 'Later notes may follow a hidden interval.',\n  })\n})\n\ntest('should allow an unannotated opening but reject introducing notes afterward', async () => {\n  let renders = 0\n  const annotations = createAnnotationInteraction({\n    presentation: {\n      setAnnotation: async () => {\n        renders++\n      },\n      clearAnnotation: async () => {},\n    },\n  })\n  annotations.markReady()\n  await annotations.hideAnnotation()\n  await assert.rejects(\n    () => annotations.showAnnotation({ title: 'Late start', body: 'Missing opening note.' }),\n    /annotation.*before.*ready\\(\\)/i,\n  )\n  assert.equal(renders, 0)\n})\n", "skills/record-pr-demo/scripts/capture-demo.mjs": "import { spawn } from 'node:child_process'\nimport { once } from 'node:events'\nimport { rm } from 'node:fs/promises'\n\n/**\n * Streams PNG frames into lossless FFV1, keeping only the latest frame in memory.\n * Repeats that frame at 25 fps during idle periods and encoder backpressure so\n * presentation timing follows wall time. The final converter performs the only\n * lossy encode. No PNG files are written to disk.\n */\nexport async function startLosslessCapture({\n  page,\n  output,\n  size,\n  fps = 25,\n  shutdownTimeoutMs = 10000,\n}) {\n  const session = await page.context().newCDPSession(page)\n  const encoder = spawn(\n    'ffmpeg',\n    [\n      '-v',\n      'error',\n      '-y',\n      '-f',\n      'image2pipe',\n      '-vcodec',\n      'png',\n      '-framerate',\n      String(fps),\n      '-i',\n      'pipe:0',\n      '-an',\n      '-c:v',\n      'ffv1',\n      '-threads',\n      '2',\n      '-f',\n      'matroska',\n      output,\n    ],\n    { stdio: ['pipe', 'ignore', 'pipe'] },\n  )\n  let stderr = ''\n  let failure\n  let latestFrame\n  let writtenFrames = 0\n  let timer\n  let startedAt\n  let stoppedAt\n  let stopPromise\n  let writing = Promise.resolve()\n  encoder.stderr.on('data', (data) => {\n    stderr = (stderr + data).slice(-8000)\n  })\n  encoder.stdin.on('error', (error) => {\n    failure ??= error\n  })\n  const completion = new Promise((resolve, reject) => {\n    encoder.once('error', reject)\n    encoder.once('close', (code) =>\n      code === 0 ? resolve() : reject(new Error(`Lossless capture failed (${code}): ${stderr}`)),\n    )\n  })\n  void completion.catch((error) => {\n    failure ??= error\n  })\n  const frameReceived = (event) => {\n    latestFrame = Buffer.from(event.data, 'base64')\n    void session.send('Page.screencastFrameAck', { sessionId: event.sessionId }).catch((error) => {\n      failure ??= error\n    })\n  }\n  const writeThrough = async (target) => {\n    if (failure) throw failure\n    while (writtenFrames < target) {\n      if (failure) throw failure\n      if (!encoder.stdin.write(latestFrame)) await once(encoder.stdin, 'drain')\n      writtenFrames++\n    }\n  }\n  const frameCount = (now) => Math.max(1, Math.ceil(((now - startedAt) * fps) / 1000))\n  const pump = () => {\n    writing = writeThrough(frameCount(performance.now()))\n    void writing\n      .then(() => {\n        if (stoppedAt === undefined) timer = setTimeout(pump, 10)\n      })\n      .catch((error) => {\n        failure ??= error\n      })\n  }\n  // Bound shutdown even if the encoder or its input pipe stops responding.\n  const finishEncoder = async () => {\n    const timeout = setTimeout(() => {\n      encoder.stdin.destroy(new Error('Lossless encoder shutdown timed out'))\n      encoder.kill('SIGKILL')\n    }, shutdownTimeoutMs)\n    timeout.unref()\n    try {\n      encoder.stdin.end()\n      await completion\n    } finally {\n      clearTimeout(timeout)\n    }\n  }\n  const boundShutdown = async ({ operation, run }) => {\n    let timeout\n    try {\n      await Promise.race([\n        Promise.resolve().then(run),\n        new Promise((_, reject) => {\n          timeout = setTimeout(() => reject(new Error(`${operation} timed out`)), shutdownTimeoutMs)\n        }),\n      ])\n    } finally {\n      clearTimeout(timeout)\n    }\n  }\n  const stop = () => {\n    stopPromise ??= (async () => {\n      stoppedAt = performance.now()\n      clearTimeout(timer)\n      let timeout\n      try {\n        await boundShutdown({\n          operation: 'Page.stopScreencast',\n          run: () => session.send('Page.stopScreencast'),\n        })\n        timeout = setTimeout(() => {\n          encoder.stdin.destroy(new Error('Lossless capture flush timed out'))\n          encoder.kill('SIGKILL')\n        }, shutdownTimeoutMs)\n        timeout.unref()\n        await writing\n        await writeThrough(frameCount(stoppedAt))\n      } catch (error) {\n        failure ??= error\n      } finally {\n        clearTimeout(timeout)\n        session.off('Page.screencastFrame', frameReceived)\n        await boundShutdown({ operation: 'CDP session detach', run: () => session.detach() }).catch(\n          (error) => {\n            failure ??= error\n          },\n        )\n        await finishEncoder().catch((error) => {\n          failure ??= error\n        })\n      }\n      if (failure) {\n        await rm(output, { force: true })\n        throw failure\n      }\n      return { frames: writtenFrames, duration: writtenFrames / fps }\n    })()\n    return stopPromise\n  }\n  try {\n    await once(encoder, 'spawn')\n    await session.send('Page.enable')\n    latestFrame = Buffer.from(\n      (await session.send('Page.captureScreenshot', { format: 'png' })).data,\n      'base64',\n    )\n    startedAt = performance.now()\n    session.on('Page.screencastFrame', frameReceived)\n    await session.send('Page.startScreencast', {\n      format: 'png',\n      maxWidth: size.width,\n      maxHeight: size.height,\n      everyNthFrame: 1,\n    })\n    pump()\n    return { startedAt, stop }\n  } catch (error) {\n    failure ??= error\n    await stop().catch(() => {})\n    throw error\n  }\n}\n", "skills/record-pr-demo/scripts/capture-demo.test.mjs": "import assert from 'node:assert/strict'\nimport { spawn, spawnSync } from 'node:child_process'\nimport { mkdtemp, rm, stat, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport path from 'node:path'\nimport { test } from 'node:test'\nimport { chromium } from '@playwright/test'\nimport { startLosslessCapture } from './capture-demo.mjs'\n\nfunction ffmpeg({ args, input }) {\n  const result = spawnSync('ffmpeg', ['-v', 'error', ...args], {\n    input,\n    maxBuffer: 8 * 1024 * 1024,\n  })\n  assert.equal(result.status, 0, result.stderr?.toString())\n  return result.stdout\n}\n\ntest('should preserve exact screenshot pixels, native size, updates, and wall-clock duration', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-lossless-'))\n  const browser = await chromium.launch({ headless: true })\n  try {\n    const page = await browser.newPage({ viewport: { width: 800, height: 600 } })\n    await page.setContent(\n      '<style>body{margin:0;background:#fff;color:#222;font:16px sans-serif}button{margin:40px}</style><button onclick=\"document.body.style.background=\\'#123456\\'\">Save document</button>Small, sharp text and a 1px border.',\n    )\n    const reference = await page.screenshot()\n    const output = path.join(directory, 'capture.mkv')\n    const capture = await startLosslessCapture({ page, output, size: { width: 800, height: 600 } })\n    await page.waitForTimeout(300)\n    await page.getByRole('button', { name: 'Save document' }).click()\n    await page.waitForTimeout(300)\n    const elapsed = (performance.now() - capture.startedAt) / 1000\n    const stopping = capture.stop()\n    assert.equal(capture.stop(), stopping)\n    const result = await stopping\n    assert.ok(\n      Math.abs(result.duration - elapsed) < 0.15,\n      `${result.duration}s video vs ${elapsed}s elapsed`,\n    )\n    const probe = spawnSync(\n      'ffprobe',\n      [\n        '-v',\n        'error',\n        '-select_streams',\n        'v:0',\n        '-show_entries',\n        'stream=codec_name,width,height',\n        '-of',\n        'json',\n        output,\n      ],\n      { encoding: 'utf8' },\n    )\n    assert.equal(probe.status, 0, probe.stderr)\n    assert.deepEqual(JSON.parse(probe.stdout).streams[0], {\n      codec_name: 'ffv1',\n      width: 800,\n      height: 600,\n    })\n    const first = ffmpeg({\n      args: ['-i', output, '-frames:v', '1', '-f', 'rawvideo', '-pix_fmt', 'rgba', 'pipe:1'],\n    })\n    const expected = ffmpeg({\n      args: ['-i', 'pipe:0', '-frames:v', '1', '-f', 'rawvideo', '-pix_fmt', 'rgba', 'pipe:1'],\n      input: reference,\n    })\n    assert.ok(first.equals(expected), 'Lossless capture changed the opening screenshot pixels')\n    const last = ffmpeg({\n      args: [\n        '-sseof',\n        '-0.08',\n        '-i',\n        output,\n        '-frames:v',\n        '1',\n        '-f',\n        'rawvideo',\n        '-pix_fmt',\n        'rgba',\n        'pipe:1',\n      ],\n    })\n    assert.deepEqual([...last.subarray(0, 4)], [0x12, 0x34, 0x56, 255])\n  } finally {\n    await browser.close()\n    await rm(directory, { recursive: true, force: true })\n  }\n})\n\ntest('should stop the encoder and remove partial output after the page closes', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-lossless-close-'))\n  const browser = await chromium.launch({ headless: true })\n  try {\n    const page = await browser.newPage({ viewport: { width: 800, height: 600 } })\n    const output = path.join(directory, 'capture.mkv')\n    const capture = await startLosslessCapture({ page, output, size: { width: 800, height: 600 } })\n    await page.waitForTimeout(100)\n    await page.close()\n    await assert.rejects(capture.stop(), /closed|detached/i)\n    await assert.rejects(stat(output), { code: 'ENOENT' })\n  } finally {\n    await browser.close()\n    await rm(directory, { recursive: true, force: true })\n  }\n})\n\ntest('should remove a failed scenario recording and restore signal listeners', async () => {\n  const { recordDemo } = await import('./record-demo.mjs')\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-lossless-error-'))\n  const output = path.join(directory, 'capture.mkv')\n  const scenario = path.join(directory, 'scenario.mjs')\n  const signals = ['SIGINT', 'SIGTERM'].map((name) => process.listenerCount(name))\n  try {\n    await writeFile(\n      scenario,\n      `export const presentation={change:{kind:'Fix',title:'Capture',description:'Failure cleanup'}};\n      export default async function({page,ready}){await page.goto('data:text/html,<button>Save</button>');await ready();throw new Error('Deliberate scenario failure')}`,\n    )\n    await assert.rejects(\n      recordDemo({\n        baseURL: 'http://capture.test',\n        label: 'cleanup',\n        output,\n        scenario,\n        viewport: { width: 800, height: 600 },\n      }),\n      /Deliberate scenario failure/,\n    )\n    await assert.rejects(stat(output), { code: 'ENOENT' })\n    assert.deepEqual(\n      ['SIGINT', 'SIGTERM'].map((name) => process.listenerCount(name)),\n      signals,\n    )\n  } finally {\n    await rm(directory, { recursive: true, force: true })\n  }\n})\n\ntest('should clean up capture when interrupted with SIGINT', { timeout: 20000 }, async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-lossless-interrupt-'))\n  const output = path.join(directory, 'capture.mkv')\n  const scenario = path.join(directory, 'scenario.mjs')\n  let child\n  try {\n    await writeFile(\n      scenario,\n      `export const presentation={change:{kind:'Fix',title:'Capture',description:'Cancellation cleanup'}};\n      export default async function({page,ready}){await page.goto('data:text/html,<button>Save</button>');await ready();console.log('CAPTURE_READY');await page.waitForTimeout(60000)}`,\n    )\n    child = spawn(\n      process.execPath,\n      [\n        new URL('./record-demo.mjs', import.meta.url).pathname,\n        '--scenario',\n        scenario,\n        '--output',\n        output,\n      ],\n      { stdio: ['ignore', 'pipe', 'pipe'] },\n    )\n    let stdout = ''\n    let stderr = ''\n    child.stdout.on('data', (data) => {\n      stdout += data\n      if (stdout.includes('CAPTURE_READY')) child.kill('SIGINT')\n    })\n    child.stderr.on('data', (data) => {\n      stderr += data\n    })\n    const result = await new Promise((resolve, reject) => {\n      child.once('error', reject)\n      child.once('close', (code, signal) => resolve({ code, signal }))\n    })\n    assert.ok(stdout.includes('CAPTURE_READY'), stderr)\n    assert.equal(result.signal, null)\n    assert.equal(result.code, 1, stderr)\n    await assert.rejects(stat(output), { code: 'ENOENT' })\n  } finally {\n    child?.kill('SIGKILL')\n    await rm(directory, { recursive: true, force: true })\n  }\n})\n\nfor (const stalledOperation of ['Page.stopScreencast', 'detach']) {\n  test(\n    `should finish encoder cleanup when ${stalledOperation} never settles`,\n    { timeout: 10000 },\n    async () => {\n      const directory = await mkdtemp(path.join(tmpdir(), 'demo-lossless-stalled-'))\n      const browser = await chromium.launch({ headless: true })\n      try {\n        const context = await browser.newContext({ viewport: { width: 800, height: 600 } })\n        const page = await context.newPage()\n        const newCDPSession = context.newCDPSession.bind(context)\n        context.newCDPSession = async (target) => {\n          const session = await newCDPSession(target)\n          if (stalledOperation === 'detach') {\n            session.detach = () => new Promise(() => {})\n          } else {\n            const send = session.send.bind(session)\n            session.send = (method, ...args) =>\n              method === stalledOperation ? new Promise(() => {}) : send(method, ...args)\n          }\n          return session\n        }\n        const output = path.join(directory, 'capture.mkv')\n        const capture = await startLosslessCapture({\n          page,\n          output,\n          size: { width: 800, height: 600 },\n          shutdownTimeoutMs: 250,\n        })\n        await page.waitForTimeout(100)\n        await assert.rejects(capture.stop(), /(?:Page.stopScreencast|CDP session detach) timed out/)\n        await assert.rejects(stat(output), { code: 'ENOENT' })\n      } finally {\n        await browser.close()\n        await rm(directory, { recursive: true, force: true })\n      }\n    },\n  )\n}\n", "skills/record-pr-demo/scripts/circle-demo.test.mjs": "import assert from 'node:assert/strict'\nimport { mkdtemp, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport path from 'node:path'\nimport { test } from 'node:test'\n\nimport { validateDemo } from './record-demo.mjs'\n\ntest('should circle a target without clicking or changing focus, then click normally', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-circle-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n\n  try {\n    await writeFile(\n      scenario,\n      `\n      export const presentation = {\n        canvas: { width: 1000, height: 700 },\n        change: { kind: 'Feature', title: 'Circle cursor', description: 'Emphasize a result.' },\n      }\n      export default async function({ circleCursor, click, expect, page }) {\n        await page.goto('data:text/html,' + encodeURIComponent('<style>body{margin:0}button{position:absolute;left:220px;top:180px;width:100px;height:40px}input{position:absolute;left:20px;top:20px}</style><input autofocus><button onclick=\"this.dataset.clicked=String(event.isTrusted)\">Target</button>'))\n        const target = page.getByRole('button', { name: 'Target' })\n        await click(page.locator('input'))\n        await expect(page.locator('input')).toBeFocused()\n        await page.evaluate(() => {\n          window.moves = []\n          document.addEventListener('mousemove', event => window.moves.push({ x: event.clientX, y: event.clientY }))\n        })\n        if (typeof circleCursor !== 'function') throw new Error('circleCursor helper is missing')\n        await circleCursor(target, {position:{x:35,y:20}})\n        await expect(page.locator('input')).toBeFocused()\n        await expect(target).not.toHaveAttribute('data-clicked')\n        const moves = await page.evaluate(() => window.moves)\n        const orbit = moves.slice(-76)\n        if (orbit.length < 30) throw new Error('Circle has too few points')\n        if (orbit.some(p => Math.hypot(p.x-257,p.y-202)>18)) throw new Error('Circle should stay tight around the focus point')\n        let turns = 0\n        for (let i=1;i<orbit.length;i++) {\n          const previous = Math.atan2(orbit[i-1].y-202,orbit[i-1].x-257)\n          const current = Math.atan2(orbit[i].y-202,orbit[i].x-257)\n          turns += Math.atan2(Math.sin(current-previous),Math.cos(current-previous))\n        }\n        if (Math.abs(turns-Math.PI*4)>0.5) throw new Error('Circle should make two loops')\n        const distance = (a,b) => Math.hypot(a.x-b.x,a.y-b.y)\n        const early = orbit.slice(20,30).reduce((n,p,i,a) => i ? n+distance(p,a[i-1]) : n,0)\n        const late = orbit.slice(-10).reduce((n,p,i,a) => i ? n+distance(p,a[i-1]) : n,0)\n        if (late >= early / 2) throw new Error('Circle did not ease out')\n        const before = moves.length\n        await click(target, {duration:100,before:0,after:0})\n        await expect(target).toHaveAttribute('data-clicked','true')\n        const after = await page.evaluate(() => window.moves)\n        const firstAfter = after[before]\n        if (distance(firstAfter,moves.at(-1))>5) throw new Error('Following click used stale pointer position')\n      }\n    `,\n    )\n    await validateDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'circle',\n      scenario,\n      viewport: { width: 800, height: 600 },\n    })\n  } finally {\n    await rm(directory, { recursive: true, force: true })\n  }\n})\n\ntest('should keep circles inside the frame and reject invalid options before moving', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-circle-edge-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n\n  try {\n    await writeFile(\n      scenario,\n      `\n      export const presentation = { change: { kind: 'Feature', title: 'Edge target', description: 'Keep the circle visible.' } }\n      export default async function({ circleCursor, moveCursor, page }) {\n        await page.goto('data:text/html,' + encodeURIComponent('<style>body{margin:0}button{position:fixed;right:0;bottom:0;width:80px;height:40px}</style><button>Edge</button>'))\n        const target = page.getByRole('button',{name:'Edge'})\n        await page.evaluate(() => {\n          window.moves=[]\n          document.addEventListener('mousemove', e => window.moves.push({x:e.clientX,y:e.clientY}))\n        })\n        if (typeof circleCursor !== 'function') throw new Error('circleCursor helper is missing')\n        for (const duration of [-1, Infinity, NaN]) {\n          let rejected=false\n          try { await moveCursor(target,{duration}) } catch(e) { rejected=/finite non-negative/.test(e.message) }\n          if(!rejected) throw new Error('Invalid cursor duration accepted')\n        }\n        for (const options of [{duration:-1},{duration:NaN},{radius:0},{radius:Infinity},{pauseAfter:-1}]) {\n          let rejected = false\n          try { await circleCursor(target, options) } catch (e) { rejected=/non-negative|positive|finite/.test(e.message) }\n          if (!rejected) throw new Error('Invalid circle option accepted')\n        }\n        if ((await page.evaluate(()=>window.moves.length)) !== 0) throw new Error('Invalid options moved the pointer')\n        await circleCursor(target, {duration:0,pauseAfter:0})\n        const moves=await page.evaluate(()=>window.moves)\n        if(moves.some(p=>p.x<0||p.y<0||p.x>=800||p.y>=600)) throw new Error('Circle left the app viewport')\n        if(moves.length<30) throw new Error('Zero-time validation skipped geometry')\n      }\n    `,\n    )\n    await validateDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'circle-edge',\n      scenario,\n      viewport: { width: 800, height: 600 },\n    })\n  } finally {\n    await rm(directory, { recursive: true, force: true })\n  }\n})\n\ntest('should include browser input time in the requested cursor travel duration', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-cursor-timing-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n\n  try {\n    await writeFile(\n      scenario,\n      `\n      export const presentation = { change: { kind: 'Feature', title: 'Cursor timing', description: 'Keep travel responsive.' } }\n      export default async function({ moveCursor, page }) {\n        await page.goto('data:text/html,' + encodeURIComponent('<style>button{position:absolute;left:500px;top:300px}</style><button>Target</button>'))\n        const target=page.getByRole('button',{name:'Target'})\n        await target.waitFor()\n        await page.evaluate(() => {\n          window.moveTimes=[]\n          document.addEventListener('mousemove', () => {\n            window.moveTimes.push(performance.now())\n            const until=performance.now()+25\n            while(performance.now()<until) {}\n          })\n        })\n        const startedAt=Date.now()\n        await moveCursor(target,{duration:1200,pauseAfter:0})\n        const elapsed=Date.now()-startedAt\n        const times=await page.evaluate(()=>window.moveTimes)\n        if(times.length<15) throw new Error('Movement lost its smooth samples')\n        if(elapsed<1000 || elapsed>1800) throw new Error('Cursor travel drifted from 1200ms: '+elapsed)\n      }\n    `,\n    )\n    await validateDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'cursor-timing',\n      scenario,\n      viewport: { width: 800, height: 600 },\n    })\n  } finally {\n    await rm(directory, { recursive: true, force: true })\n  }\n})\n", "skills/record-pr-demo/scripts/convert-demo.mjs": "import { spawnSync } from 'node:child_process'\nimport { mkdir, stat } from 'node:fs/promises'\nimport path from 'node:path'\n\nconst MAX_VIDEO_BYTES = 10 * 1024 * 1024\n\nexport async function convertDemo({ environment = process.env, input, output, trimStart }) {\n  if (!Number.isFinite(trimStart) || trimStart < 0) {\n    throw new Error('Conversion requires a valid opening ready time')\n  }\n\n  await mkdir(path.dirname(output), { recursive: true })\n  const result = spawnSync(\n    'ffmpeg',\n    [\n      '-y',\n      '-ss',\n      String(trimStart),\n      '-i',\n      input,\n      '-an',\n      '-c:v',\n      'libx264',\n      '-preset',\n      'medium',\n      '-crf',\n      '18',\n      '-pix_fmt',\n      'yuv420p',\n      '-movflags',\n      '+faststart',\n      output,\n    ],\n    { encoding: 'utf8', env: environment, maxBuffer: MAX_VIDEO_BYTES },\n  )\n\n  if (result.error) {\n    throw new Error(`ffmpeg failed to start: ${result.error.message}`)\n  }\n  if (result.status !== 0) {\n    throw new Error(`ffmpeg failed: ${(result.stderr || result.stdout).trim()}`)\n  }\n\n  if ((await stat(output)).size > MAX_VIDEO_BYTES) {\n    throw new Error('Converted video exceeds the 10240 KB upload budget. Shorten the demo.')\n  }\n}\n", "skills/record-pr-demo/scripts/convert-demo.test.mjs": "import assert from 'node:assert/strict'\nimport { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport path from 'node:path'\nimport { afterEach, test } from 'node:test'\n\nimport { convertDemo } from './convert-demo.mjs'\n\nconst testDirectories = []\n\nafterEach(async () => {\n  await Promise.all(\n    testDirectories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })),\n  )\n})\n\ntest('convertDemo uses the opening ready time for H.264 conversion', async () => {\n  const directory = await createFakeFfmpeg()\n  const input = path.join(directory, 'demo.webm')\n  const output = path.join(directory, 'demo.mp4')\n  await writeFile(input, 'recording')\n\n  await convertDemo({\n    environment: { ...process.env, PATH: `${directory}:${process.env.PATH}` },\n    input,\n    output,\n    trimStart: 1.25,\n  })\n\n  assert.equal(await readFile(output, 'utf8'), 'recording')\n  const ffmpegArgs = await readFile(path.join(directory, 'ffmpeg-args.txt'), 'utf8')\n  assert.match(ffmpegArgs, /-ss 1\\.25/)\n  assert.match(ffmpegArgs, /-c:v libx264/)\n  assert.match(ffmpegArgs, /-crf 18/)\n  assert.match(ffmpegArgs, /-pix_fmt yuv420p/)\n  assert.match(ffmpegArgs, /-movflags \\+faststart/)\n})\n\ntest('convertDemo rejects a missing opening ready time', async () => {\n  await assert.rejects(\n    convertDemo({ input: '/tmp/demo.webm', output: '/tmp/demo.mp4' }),\n    /valid opening ready time/,\n  )\n})\n\nasync function createFakeFfmpeg() {\n  const directory = await mkdtemp(path.join(tmpdir(), 'convert-pr-demo-test-'))\n  testDirectories.push(directory)\n  const ffmpegPath = path.join(directory, 'ffmpeg')\n\n  await writeFile(\n    ffmpegPath,\n    `#!/usr/bin/env bash\nprintf '%s ' \"$@\" > \"${directory}/ffmpeg-args.txt\"\ninput=\"\"\nprevious=\"\"\nfor argument in \"$@\"; do\n  if [ \"$previous\" = \"-i\" ]; then input=\"$argument\"; fi\n  previous=\"$argument\"\n  output=\"$argument\"\ndone\ncp \"$input\" \"$output\"\n`,\n  )\n  await chmod(ffmpegPath, 0o755)\n\n  return directory\n}\n", "skills/record-pr-demo/scripts/keyboard-demo.mjs": "export function createKeyInteraction({ page, pauseScale }) {\n  return async ({ key, settleMs = 800 }) => {\n    await page.keyboard.press(key, { delay: 80 * pauseScale })\n    await page.waitForTimeout(settleMs * pauseScale)\n  }\n}\n", "skills/record-pr-demo/scripts/keyboard-demo.test.mjs": "import assert from 'node:assert/strict'\nimport { test } from 'node:test'\nimport { createKeyInteraction } from './keyboard-demo.mjs'\n\nfor (const [name, options, pauseScale, expected] of [\n  ['default settling', {}, 1, 800],\n  ['custom settling', { settleMs: 800 }, 1, 800],\n  ['no settling', { settleMs: 0 }, 1, 0],\n  ['fast validation', { settleMs: 800 }, 0, 0],\n]) {\n  test(`should press the real key before ${name}`, async () => {\n    const calls = []\n    const page = {\n      keyboard: { press: async (...args) => calls.push(['press', ...args]) },\n      waitForTimeout: async (ms) => calls.push(['settle', ms]),\n    }\n    const pressKey = createKeyInteraction({ page, pauseScale })\n    await pressKey({ key: 'Shift+Tab', ...options })\n    assert.deepEqual(calls, [\n      ['press', 'Shift+Tab', { delay: 80 * pauseScale }],\n      ['settle', expected],\n    ])\n  })\n}\n\ntest('should propagate a failed key press without settling', async () => {\n  const pressKey = createKeyInteraction({\n    page: {\n      keyboard: {\n        press: async () => {\n          throw new Error('Input failed')\n        },\n      },\n      waitForTimeout: async () => assert.fail('Should not settle after a failed press'),\n    },\n    pauseScale: 1,\n  })\n  await assert.rejects(pressKey({ key: 'Enter' }), /Input failed/)\n})\n", "skills/record-pr-demo/scripts/prepare-demo.mjs": "#!/usr/bin/env node\n\nimport { spawnSync } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { access, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport { convertDemo } from './convert-demo.mjs'\nimport {\n  parseViewport,\n  previewDemo,\n  recordDemo,\n  sanitizeLabel,\n  validateDemo,\n} from './record-demo.mjs'\n\nconst DEFAULT_BASE_URL = 'http://localhost:3000'\nconst DEFAULT_INTERACTION_PAUSE_MS = 300\nconst DEFAULT_LABEL = 'feature-demo'\nconst DEFAULT_MOUSE_MOVE_MS = 450\nconst DEFAULT_VIEWPORT = { height: 900, width: 1440 }\nconst MODES = new Set(['candidate', 'preflight', 'preview', 'validate', 'verify'])\n\nexport function parseArgs(argv) {\n  const args = [...argv]\n  const requestedMode = args[0] && !args[0].startsWith('--') ? args.shift() : 'candidate'\n\n  if (!MODES.has(requestedMode)) {\n    throw new Error(`Unknown mode: ${requestedMode}`)\n  }\n\n  const values = new Map()\n  const supportedOptions = new Set([\n    '--a11y',\n    '--base-url',\n    '--contact-sheet',\n    '--interaction-pause-ms',\n    '--label',\n    '--manifest',\n    '--mouse-move-ms',\n    '--output',\n    '--raw-output',\n    '--scenario',\n    '--viewport',\n  ])\n\n  for (let index = 0; index < args.length; index += 2) {\n    const option = args[index]\n    const value = args[index + 1]\n\n    if (!supportedOptions.has(option)) {\n      throw new Error(`Unknown option: ${option}`)\n    }\n    if (!value || value.startsWith('--')) {\n      throw new Error(`${option} requires a value`)\n    }\n\n    values.set(option, value)\n  }\n\n  const scenario = values.get('--scenario')\n  if (!['preflight', 'verify'].includes(requestedMode) && !scenario) {\n    throw new Error(`--scenario is required for ${requestedMode} mode`)\n  }\n\n  const a11y = values.get('--a11y')\n  if (a11y !== undefined && !['on', 'off'].includes(a11y)) {\n    throw new Error('--a11y must be on or off')\n  }\n\n  const label = sanitizeLabel(values.get('--label') ?? DEFAULT_LABEL)\n  const output = values.get('--output') ?? `/tmp/payload-pr-demo-${label}.mp4`\n  const outputBase = output.replace(/\\.[^.]+$/, '')\n\n  return {\n    ...(a11y === undefined ? {} : { a11y }),\n    baseURL: values.get('--base-url') ?? DEFAULT_BASE_URL,\n    contactSheet: values.get('--contact-sheet') ?? `${outputBase}-contact-sheet.png`,\n    interactionPauseMs: parseTiming({\n      name: '--interaction-pause-ms',\n      value: values.get('--interaction-pause-ms') ?? DEFAULT_INTERACTION_PAUSE_MS,\n    }),\n    label,\n    manifest: values.get('--manifest') ?? `${outputBase}.json`,\n    mode: requestedMode,\n    mouseMoveMs: parseTiming({\n      name: '--mouse-move-ms',\n      value: values.get('--mouse-move-ms') ?? DEFAULT_MOUSE_MOVE_MS,\n    }),\n    output,\n    rawOutput: values.get('--raw-output') ?? `${outputBase}.mkv`,\n    scenario,\n    viewport: parseViewport(values.get('--viewport') ?? '1440x900'),\n  }\n}\n\nexport async function packageCandidate({\n  contactSheet,\n  environment = process.env,\n  label,\n  manifest,\n  output,\n  rawOutput,\n  recordingOptions,\n  scenario,\n  scenarioSource,\n  trimStart,\n}) {\n  if (!Number.isFinite(trimStart) || trimStart < 0) {\n    throw new Error('Candidate is missing a valid opening ready time')\n  }\n\n  await assertCandidatePathsAvailable({ contactSheet, manifest, output, rawOutput })\n\n  const resolvedContactSheet = path.resolve(contactSheet)\n  const resolvedManifest = path.resolve(manifest)\n  const resolvedOutput = path.resolve(output)\n  const resolvedRawOutput = path.resolve(rawOutput)\n  const resolvedScenario = path.resolve(scenario)\n  if (scenarioSource && !(await readFile(resolvedScenario)).equals(scenarioSource)) {\n    throw new Error(\n      'The scenario changed during this take. Use a new --label and record again so the script matches the video.',\n    )\n  }\n\n  await convertDemo({\n    environment,\n    input: resolvedRawOutput,\n    output: resolvedOutput,\n    trimStart,\n  })\n\n  runCommand({\n    args: ['-v', 'error', '-i', resolvedOutput, '-f', 'null', '-'],\n    command: 'ffmpeg',\n    environment,\n  })\n\n  const probe = runCommand({\n    args: [\n      '-v',\n      'error',\n      '-select_streams',\n      'v:0',\n      '-show_entries',\n      'stream=codec_name,width,height:format=duration',\n      '-of',\n      'json',\n      resolvedOutput,\n    ],\n    command: 'ffprobe',\n    environment,\n  })\n  const probeData = JSON.parse(probe.stdout)\n  const videoStream = probeData.streams?.[0]\n  const durationSeconds = Number(probeData.format?.duration)\n\n  if (\n    videoStream?.codec_name !== 'h264' ||\n    !Number.isFinite(durationSeconds) ||\n    !Number.isFinite(videoStream.width) ||\n    !Number.isFinite(videoStream.height)\n  ) {\n    throw new Error('Candidate metadata is incomplete or not GitHub-compatible H.264 video')\n  }\n\n  await mkdir(path.dirname(resolvedContactSheet), { recursive: true })\n  const previewFramesPerSecond = Math.min(3, 6 / Math.max(durationSeconds, 1))\n  runCommand({\n    args: [\n      '-y',\n      '-v',\n      'error',\n      '-i',\n      resolvedOutput,\n      '-vf',\n      `fps=${previewFramesPerSecond},scale=480:-2,tile=3x2:padding=8:margin=8`,\n      '-frames:v',\n      '1',\n      resolvedContactSheet,\n    ],\n    command: 'ffmpeg',\n    environment,\n  })\n\n  const fileStats = await stat(resolvedOutput)\n  const fileBuffer = await readFile(resolvedOutput)\n  const sha256 = createHash('sha256').update(fileBuffer).digest('hex')\n  const metadata = {\n    codec: videoStream.codec_name,\n    durationSeconds,\n    height: videoStream.height,\n    width: videoStream.width,\n  }\n  const script = await saveScenarioSnapshot({\n    output: resolvedOutput,\n    scenario: resolvedScenario,\n    source: scenarioSource,\n  })\n  const candidateManifest = {\n    contactSheet: resolvedContactSheet,\n    createdAt: new Date().toISOString(),\n    label,\n    metadata,\n    mp4: resolvedOutput,\n    ...(recordingOptions ? { recordingOptions } : {}),\n    scenario: resolvedScenario,\n    scenarioSnapshot: script.path,\n    scenarioSha256: script.sha256,\n    sha256,\n    sizeBytes: fileStats.size,\n  }\n\n  await mkdir(path.dirname(resolvedManifest), { recursive: true })\n  await writeFile(resolvedManifest, `${JSON.stringify(candidateManifest, null, 2)}\\n`)\n  await rm(resolvedRawOutput, { force: true })\n\n  return {\n    contactSheetPath: resolvedContactSheet,\n    manifestPath: resolvedManifest,\n    metadata,\n    outputPath: resolvedOutput,\n    scenarioSnapshotPath: script.path,\n    sha256,\n    sizeBytes: fileStats.size,\n  }\n}\n\nexport async function saveScenarioSnapshot({ output, scenario, source }) {\n  const scriptPath = scenarioSnapshotPath({ output })\n  const scriptSource = source ?? (await readFile(scenario))\n  const sha256 = createHash('sha256').update(scriptSource).digest('hex')\n  await mkdir(path.dirname(scriptPath), { recursive: true })\n  await writeFile(scriptPath, scriptSource, { flag: 'wx' })\n  return { path: scriptPath, sha256 }\n}\n\nexport async function verifyCandidateManifest(manifestPath) {\n  const resolvedManifest = path.resolve(manifestPath)\n  const candidateManifest = JSON.parse(await readFile(resolvedManifest, 'utf8'))\n\n  if (\n    typeof candidateManifest.mp4 !== 'string' ||\n    typeof candidateManifest.sha256 !== 'string' ||\n    !Number.isFinite(candidateManifest.sizeBytes) ||\n    typeof candidateManifest.scenarioSnapshot !== 'string' ||\n    typeof candidateManifest.scenarioSha256 !== 'string'\n  ) {\n    throw new Error(`Candidate manifest is incomplete: ${resolvedManifest}`)\n  }\n\n  const fileBuffer = await readFile(candidateManifest.mp4)\n  const fileStats = await stat(candidateManifest.mp4)\n  const sha256 = createHash('sha256').update(fileBuffer).digest('hex')\n\n  if (sha256 !== candidateManifest.sha256 || fileStats.size !== candidateManifest.sizeBytes) {\n    throw new Error(\n      `The current MP4 does not match the reviewed candidate in ${resolvedManifest}. Review it again before upload.`,\n    )\n  }\n\n  const scriptBuffer = await readFile(candidateManifest.scenarioSnapshot)\n  const scenarioSha256 = createHash('sha256').update(scriptBuffer).digest('hex')\n\n  if (scenarioSha256 !== candidateManifest.scenarioSha256) {\n    throw new Error(\n      `The scenario snapshot does not match the reviewed candidate in ${resolvedManifest}. Review it again before upload.`,\n    )\n  }\n\n  return { manifest: resolvedManifest, mp4: candidateManifest.mp4, sha256 }\n}\n\nexport async function assertCandidatePathsAvailable({ contactSheet, manifest, output, rawOutput }) {\n  const protectedPaths = [contactSheet, manifest, output, scenarioSnapshotPath({ output })].map(\n    (candidatePath) => path.resolve(candidatePath),\n  )\n  const allPaths = rawOutput ? [...protectedPaths, path.resolve(rawOutput)] : protectedPaths\n\n  if (new Set(allPaths).size !== allPaths.length) {\n    throw new Error(\n      'Candidate artifact paths must be distinct, including the scenario snapshot and raw recording',\n    )\n  }\n\n  const existingPaths = []\n\n  for (const candidatePath of protectedPaths) {\n    try {\n      await stat(candidatePath)\n      existingPaths.push(candidatePath)\n    } catch (error) {\n      if (error.code !== 'ENOENT') {\n        throw error\n      }\n    }\n  }\n\n  if (existingPaths.length > 0) {\n    throw new Error(\n      `Candidate review evidence already exists at ${existingPaths.join(', ')}. Use a new --label for the next take.`,\n    )\n  }\n}\n\nexport async function runPreparation(options) {\n  const startedAt = performance.now()\n\n  if (options.mode === 'verify') {\n    const result = await verifyCandidateManifest(options.manifest)\n    printStage('Reviewed candidate bytes verified', startedAt)\n    console.log(`Candidate: ${result.mp4}`)\n    console.log(`SHA256: ${result.sha256}`)\n    return result\n  }\n\n  await runPreflight({\n    baseURL: options.baseURL,\n    requiresServer: options.mode !== 'preflight',\n  })\n  printStage('Environment ready', startedAt)\n\n  if (options.mode === 'preflight') {\n    return\n  }\n\n  if (options.mode === 'validate') {\n    await runWithScenarioFixture(options, async (fixture) => {\n      await validateDemo({\n        a11y: options.a11y,\n        baseURL: options.baseURL,\n        fixture,\n        label: options.label,\n        scenario: options.scenario,\n        viewport: options.viewport,\n      })\n    })\n    printStage('Scenario validated', startedAt)\n    return\n  }\n\n  if (options.mode === 'preview') {\n    const previewOutput = options.output.replace(/\\.[^.]+$/, '-preview.png')\n\n    await runWithScenarioFixture(options, async (fixture) => {\n      await previewDemo({\n        a11y: options.a11y,\n        baseURL: options.baseURL,\n        fixture,\n        label: options.label,\n        output: previewOutput,\n        scenario: options.scenario,\n        viewport: options.viewport,\n      })\n    })\n    printStage(`Preview ready: ${path.resolve(previewOutput)}`, startedAt)\n    return path.resolve(previewOutput)\n  }\n\n  await assertCandidatePathsAvailable(options)\n  const scenarioSource = await readFile(options.scenario)\n\n  await runWithScenarioFixture(options, async (fixture) => {\n    await validateDemo({\n      a11y: options.a11y,\n      baseURL: options.baseURL,\n      fixture,\n      label: options.label,\n      scenario: options.scenario,\n      viewport: options.viewport,\n    })\n  })\n  printStage('Scenario validated', startedAt)\n\n  let trimStart\n  await runWithScenarioFixture(options, async (fixture) => {\n    await recordDemo({\n      a11y: options.a11y,\n      baseURL: options.baseURL,\n      fixture,\n      interactionPauseMs: options.interactionPauseMs,\n      label: options.label,\n      mouseMoveMs: options.mouseMoveMs,\n      onOpeningReady: (seconds) => {\n        trimStart = seconds\n      },\n      output: options.rawOutput,\n      scenario: options.scenario,\n      viewport: options.viewport,\n    })\n  })\n  printStage('Recording complete', startedAt)\n\n  const result = await packageCandidate({\n    contactSheet: options.contactSheet,\n    label: options.label,\n    manifest: options.manifest,\n    output: options.output,\n    rawOutput: options.rawOutput,\n    scenario: options.scenario,\n    scenarioSource,\n    recordingOptions: {\n      a11y: options.a11y ?? 'scenario',\n      mouseMoveMs: options.mouseMoveMs,\n      interactionPauseMs: options.interactionPauseMs,\n      viewport: options.viewport,\n    },\n    trimStart,\n  })\n  printStage('Candidate verified', startedAt)\n  printCandidate(result)\n\n  return result\n}\n\nasync function runPreflight({ baseURL, requiresServer }) {\n  const { chromium } = await import('@playwright/test')\n  await access(chromium.executablePath())\n\n  for (const command of ['ffmpeg', 'ffprobe']) {\n    runCommand({ args: ['-version'], command })\n  }\n\n  if (!requiresServer) {\n    return\n  }\n\n  let response\n  try {\n    response = await fetch(baseURL, {\n      redirect: 'manual',\n      signal: AbortSignal.timeout(5000),\n    })\n  } catch (error) {\n    throw new Error(`Payload server is not reachable at ${baseURL}: ${error.message}`)\n  }\n\n  if (response.status >= 500) {\n    throw new Error(`Payload server returned ${response.status} at ${baseURL}`)\n  }\n}\n\nexport async function runWithScenarioFixture(options, action) {\n  const scenarioURL = pathToFileURL(path.resolve(options.scenario)).href\n  const scenarioModule = await import(scenarioURL)\n  const { request } = await import('@playwright/test')\n  const requestContext = await request.newContext({ baseURL: options.baseURL })\n  const hasSetup = typeof scenarioModule.setup === 'function'\n  let isSetupComplete = !hasSetup\n  let fixture\n  const errors = []\n\n  try {\n    if (hasSetup) {\n      fixture = await scenarioModule.setup({\n        baseURL: options.baseURL,\n        label: options.label,\n        request: requestContext,\n      })\n      isSetupComplete = true\n    }\n\n    await action(fixture)\n  } catch (error) {\n    errors.push(error)\n  }\n\n  try {\n    if (isSetupComplete && typeof scenarioModule.teardown === 'function') {\n      await scenarioModule.teardown({\n        baseURL: options.baseURL,\n        fixture,\n        label: options.label,\n        request: requestContext,\n      })\n    }\n  } catch (error) {\n    errors.push(error)\n  }\n\n  try {\n    await requestContext.dispose()\n  } catch (error) {\n    errors.push(error)\n  }\n\n  if (errors.length === 1) throw errors[0]\n  if (errors.length > 1) {\n    throw new AggregateError(\n      errors,\n      `Scenario execution and cleanup failed: ${errors.map((error) => (error instanceof Error ? error.message : String(error))).join('; ')}`,\n      { cause: errors[0] },\n    )\n  }\n}\n\nfunction scenarioSnapshotPath({ output }) {\n  return path.resolve(`${output.replace(/\\.[^.]+$/, '')}.scenario.mjs`)\n}\n\nfunction parseTiming({ name, value }) {\n  const milliseconds = Number(value)\n\n  if (!Number.isFinite(milliseconds) || milliseconds < 0) {\n    throw new Error(`${name} must be a non-negative number`)\n  }\n\n  return milliseconds\n}\n\nfunction runCommand({ args, command, environment = process.env }) {\n  const result = spawnSync(command, args, {\n    encoding: 'utf8',\n    env: environment,\n    maxBuffer: 10 * 1024 * 1024,\n  })\n\n  if (result.error) {\n    throw new Error(`${command} failed to start: ${result.error.message}`)\n  }\n  if (result.status !== 0) {\n    throw new Error(`${command} failed: ${(result.stderr || result.stdout).trim()}`)\n  }\n\n  return result\n}\n\nfunction printStage(message, startedAt) {\n  const elapsedSeconds = ((performance.now() - startedAt) / 1000).toFixed(1)\n  console.log(`✓ ${message} (${elapsedSeconds}s)`)\n}\n\nfunction printCandidate(result) {\n  console.log(`\\nCandidate: ${result.outputPath}`)\n  console.log(`Duration: ${result.metadata.durationSeconds.toFixed(2)}s`)\n  console.log(`Size: ${(result.sizeBytes / 1024).toFixed(0)} KiB`)\n  console.log(`SHA256: ${result.sha256}`)\n  console.log(`Review script: ${result.scenarioSnapshotPath}`)\n  console.log(`Review sheet: ${result.contactSheetPath}`)\n  console.log(`Manifest: ${result.manifestPath}`)\n  console.log('Awaiting approval — nothing uploaded.')\n}\n\nfunction printHelp() {\n  console.log(`Usage: prepare-demo.mjs [candidate|validate|preview|preflight|verify] [options]\n\nModes:\n  candidate            Record, convert, verify, inventory, and prepare review assets (default)\n  validate             Run the scenario quickly without recording video\n  preview              Capture a fast final-state PNG without recording video\n  preflight            Check local recording tools; does not require a scenario or server\n  verify               Confirm an MP4 still matches its reviewed candidate manifest\n\nOptions:\n  --a11y on|off        Override a11y feedback; omit to use the scenario setting\n  --scenario PATH      Scenario module; required for candidate, validate, and preview\n  --label TEXT         Safe output label (default: ${DEFAULT_LABEL})\n  --base-url URL       Running Payload URL (default: ${DEFAULT_BASE_URL})\n  --output PATH        Candidate MP4 output\n  --raw-output PATH    Intermediate WebM output\n  --contact-sheet PATH Contact sheet PNG output\n  --manifest PATH      Candidate JSON manifest output\n  --viewport WxH       Viewport (default: ${DEFAULT_VIEWPORT.width}x${DEFAULT_VIEWPORT.height})\n  --mouse-move-ms MS   Cursor travel time (default: ${DEFAULT_MOUSE_MOVE_MS})\n  --interaction-pause-ms MS\n                       Dwell before and after clicks (default: ${DEFAULT_INTERACTION_PAUSE_MS})\n  --help               Show this help`)\n}\n\nconst isMain =\n  process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href\n\nif (isMain) {\n  if (process.argv.includes('--help')) {\n    printHelp()\n  } else {\n    try {\n      await runPreparation(parseArgs(process.argv.slice(2)))\n    } catch (error) {\n      console.error(error instanceof Error ? error.message : error)\n      process.exitCode = 1\n    }\n  }\n}\n", "skills/record-pr-demo/scripts/prepare-demo.test.mjs": "import assert from 'node:assert/strict'\nimport { createHash } from 'node:crypto'\nimport { chmod, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport path from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { afterEach, test } from 'node:test'\n\nimport * as preparation from './prepare-demo.mjs'\n\nconst { packageCandidate, parseArgs, verifyCandidateManifest } = preparation\n\nconst testDirectories = []\n\nafterEach(async () => {\n  await Promise.all(\n    testDirectories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })),\n  )\n})\n\ntest('parseArgs makes candidate creation the one-command default', () => {\n  const options = parseArgs(['--scenario', '/tmp/demo.mjs', '--label', 'Hierarchy Move'])\n\n  assert.deepEqual(options, {\n    baseURL: 'http://localhost:3000',\n    contactSheet: '/tmp/payload-pr-demo-hierarchy-move-contact-sheet.png',\n    interactionPauseMs: 300,\n    label: 'hierarchy-move',\n    manifest: '/tmp/payload-pr-demo-hierarchy-move.json',\n    mode: 'candidate',\n    mouseMoveMs: 450,\n    output: '/tmp/payload-pr-demo-hierarchy-move.mp4',\n    rawOutput: '/tmp/payload-pr-demo-hierarchy-move.mkv',\n    scenario: '/tmp/demo.mjs',\n    viewport: { height: 900, width: 1440 },\n  })\n})\n\ntest('parseArgs supports fast validation and preview modes', () => {\n  const validation = parseArgs(['validate', '--scenario', './demo.mjs'])\n  const preview = parseArgs(['preview', '--scenario', './demo.mjs'])\n\n  assert.equal(validation.mode, 'validate')\n  assert.equal(preview.mode, 'preview')\n})\n\ntest('parseArgs lets preflight run before a scenario exists', () => {\n  const options = parseArgs(['preflight', '--base-url', 'http://localhost:4000'])\n\n  assert.equal(options.mode, 'preflight')\n  assert.equal(options.scenario, undefined)\n})\n\ntest('parseArgs lets an approved candidate be verified from its manifest', () => {\n  const options = parseArgs(['verify', '--manifest', '/tmp/reviewed-demo.json'])\n\n  assert.equal(options.mode, 'verify')\n  assert.equal(options.manifest, '/tmp/reviewed-demo.json')\n  assert.equal(options.scenario, undefined)\n})\n\ntest('parseArgs requires a scenario for modes that execute one', () => {\n  assert.throws(() => parseArgs(['candidate']), /--scenario is required for candidate mode/)\n})\n\ntest('assertCandidatePathsAvailable prevents a revised take from replacing review evidence', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'prepare-pr-demo-existing-take-test-'))\n  testDirectories.push(directory)\n  const output = path.join(directory, 'demo.mp4')\n  await writeFile(output, 'reviewed candidate')\n\n  await assert.rejects(\n    preparation.assertCandidatePathsAvailable({\n      contactSheet: path.join(directory, 'demo-contact-sheet.png'),\n      manifest: path.join(directory, 'demo.json'),\n      output,\n      rawOutput: path.join(directory, 'demo.webm'),\n    }),\n    /Use a new --label for the next take/,\n  )\n})\n\ntest('packageCandidate converts, verifies, inventories, and cleans up a candidate', async () => {\n  const directory = await createFakeMediaTools()\n  const rawOutput = path.join(directory, 'demo.webm')\n  const output = path.join(directory, 'demo.mp4')\n  const contactSheet = path.join(directory, 'demo-contact-sheet.png')\n  const manifest = path.join(directory, 'demo.json')\n  const scenario = path.join(directory, 'scenario.mjs')\n\n  await writeFile(rawOutput, 'recording')\n  await writeFile(scenario, 'export default async function scenario() {}')\n\n  const result = await packageCandidate({\n    contactSheet,\n    environment: { ...process.env, PATH: `${directory}:${process.env.PATH}` },\n    label: 'demo',\n    manifest,\n    output,\n    rawOutput,\n    scenario,\n    recordingOptions: { a11y: 'off', mouseMoveMs: 300 },\n    trimStart: 1.25,\n  })\n\n  assert.equal(result.manifestPath, manifest)\n  assert.equal(result.metadata.codec, 'h264')\n  assert.equal(result.metadata.durationSeconds, 12.5)\n  assert.equal(result.metadata.height, 900)\n  assert.equal(result.metadata.width, 1440)\n  assert.equal(result.sha256, '3ebb153fb24e4411400e94a9a92b0ec458c3a8473e51e03cd37d4a34c99dfda6')\n  assert.equal((await stat(output)).size, 9)\n  assert.equal(await readFile(contactSheet, 'utf8'), 'contact-sheet')\n  await assert.rejects(stat(rawOutput), { code: 'ENOENT' })\n\n  const savedManifest = JSON.parse(await readFile(manifest, 'utf8'))\n  assert.deepEqual(savedManifest.recordingOptions, { a11y: 'off', mouseMoveMs: 300 })\n  assert.equal(savedManifest.mp4, output)\n  assert.equal(savedManifest.contactSheet, contactSheet)\n  assert.equal(savedManifest.scenario, scenario)\n  assert.equal(savedManifest.sha256, result.sha256)\n  assert.equal(savedManifest.sizeBytes, 9)\n  const scriptPath = path.join(directory, 'demo.scenario.mjs')\n  const originalSource = await readFile(scenario, 'utf8')\n  assert.equal(result.scenarioSnapshotPath, scriptPath)\n  assert.equal(savedManifest.scenarioSnapshot, scriptPath)\n  assert.equal(await readFile(scriptPath, 'utf8'), originalSource)\n  await writeFile(scenario, 'export default async function revisedScenario() {}')\n  assert.equal(await readFile(scriptPath, 'utf8'), originalSource)\n  assert.equal(\n    savedManifest.scenarioSha256,\n    createHash('sha256').update(originalSource).digest('hex'),\n  )\n  assert.match(await readFile(path.join(directory, 'convert-args.txt'), 'utf8'), /-ss 1\\.25/)\n})\n\ntest('packageCandidate rejects video that exceeds the upload budget', async () => {\n  const directory = await createFakeMediaTools({\n    outputBytes: 10 * 1024 * 1024 + 1,\n  })\n  const rawOutput = path.join(directory, 'demo.webm')\n  await writeFile(rawOutput, 'recording')\n\n  await assert.rejects(\n    packageCandidate({\n      contactSheet: path.join(directory, 'demo-contact-sheet.png'),\n      environment: { ...process.env, PATH: `${directory}:${process.env.PATH}` },\n      label: 'demo',\n      manifest: path.join(directory, 'demo.json'),\n      output: path.join(directory, 'demo.mp4'),\n      rawOutput,\n      scenario: path.join(directory, 'scenario.mjs'),\n      trimStart: 0,\n    }),\n    /exceeds the 10240 KB upload budget/,\n  )\n})\n\ntest('runWithScenarioFixture wraps execution in scenario setup and teardown hooks', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'prepare-pr-demo-fixture-test-'))\n  testDirectories.push(directory)\n  const scenario = path.join(directory, 'scenario.mjs')\n\n  await writeFile(\n    scenario,\n    `export const events = []\nexport async function setup({ label }) {\n  events.push('setup:' + label)\n  return { title: 'Prepared document' }\n}\nexport async function teardown({ fixture }) {\n  events.push('teardown:' + fixture.title)\n}\nexport default async function scenario() {}`,\n  )\n\n  assert.equal(typeof preparation.runWithScenarioFixture, 'function')\n\n  let receivedFixture\n  await preparation.runWithScenarioFixture(\n    {\n      baseURL: 'http://localhost:3000',\n      label: 'fixture-demo',\n      scenario,\n    },\n    async (fixture) => {\n      receivedFixture = fixture\n    },\n  )\n\n  assert.deepEqual(receivedFixture, { title: 'Prepared document' })\n  const scenarioModule = await import(pathToFileURL(scenario).href)\n  assert.deepEqual(scenarioModule.events, ['setup:fixture-demo', 'teardown:Prepared document'])\n})\n\ntest('runWithScenarioFixture preserves setup failures without running teardown on an absent fixture', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'prepare-pr-demo-setup-failure-test-'))\n  testDirectories.push(directory)\n  const scenario = path.join(directory, 'scenario.mjs')\n\n  await writeFile(\n    scenario,\n    `export async function setup() {\n  throw new Error('fixture setup failed')\n}\nexport async function teardown() {\n  throw new Error('teardown masked setup failure')\n}\nexport default async function scenario() {}`,\n  )\n\n  await assert.rejects(\n    preparation.runWithScenarioFixture(\n      { baseURL: 'http://localhost:3000', label: 'failure-demo', scenario },\n      async () => {},\n    ),\n    /fixture setup failed/,\n  )\n})\n\ntest('verifyCandidateManifest accepts unchanged reviewed bytes and rejects replacements', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'prepare-pr-demo-verification-test-'))\n  testDirectories.push(directory)\n  const output = path.join(directory, 'demo.mp4')\n  const manifest = path.join(directory, 'demo.json')\n\n  const scenarioSnapshot = path.join(directory, 'demo.scenario.mjs')\n  await writeFile(scenarioSnapshot, 'reviewed script')\n  await writeFile(output, 'recording')\n  await writeFile(\n    manifest,\n    JSON.stringify({\n      mp4: output,\n      scenarioSnapshot,\n      scenarioSha256: createHash('sha256').update('reviewed script').digest('hex'),\n      sha256: '3ebb153fb24e4411400e94a9a92b0ec458c3a8473e51e03cd37d4a34c99dfda6',\n      sizeBytes: 9,\n    }),\n  )\n\n  const result = await verifyCandidateManifest(manifest)\n  assert.equal(result.mp4, output)\n  assert.equal(result.sha256, '3ebb153fb24e4411400e94a9a92b0ec458c3a8473e51e03cd37d4a34c99dfda6')\n\n  await writeFile(output, 'replacement')\n  await assert.rejects(verifyCandidateManifest(manifest), /does not match the reviewed candidate/)\n})\n\nasync function createFakeMediaTools({ outputBytes } = {}) {\n  const directory = await mkdtemp(path.join(tmpdir(), 'prepare-pr-demo-test-'))\n  testDirectories.push(directory)\n\n  await writeFile(\n    path.join(directory, 'ffmpeg'),\n    `#!/usr/bin/env bash\nset -euo pipefail\nargs=\" $* \"\nif [[ \"$args\" == *\" -f null - \"* ]]; then\n  exit 0\nfi\noutput=\"\\${!#}\"\nif [[ \"$output\" == *.png ]]; then\n  printf contact-sheet > \"$output\"\n  exit 0\nfi\nprintf '%s ' \"$@\" > \"${directory}/convert-args.txt\"\ninput=\"\"\nprevious=\"\"\nfor argument in \"$@\"; do\n  if [ \"$previous\" = \"-i\" ]; then input=\"$argument\"; fi\n  previous=\"$argument\"\ndone\ncp \"$input\" \"$output\"\n${outputBytes ? `truncate -s ${outputBytes} \"$output\"` : ''}\n`,\n  )\n  await writeFile(\n    path.join(directory, 'ffprobe'),\n    `#!/usr/bin/env bash\nif [[ \" $* \" == *\" json \"* ]]; then\n  printf '{\"format\":{\"duration\":\"12.500000\"},\"streams\":[{\"codec_name\":\"h264\",\"height\":900,\"width\":1440}]}'\nelse\n  printf 'h264\\\\n'\nfi\n`,\n  )\n  await chmod(path.join(directory, 'ffmpeg'), 0o755)\n  await chmod(path.join(directory, 'ffprobe'), 0o755)\n\n  return directory\n}\n\ntest('should clean up a prepared fixture when the walkthrough fails', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-failed-walkthrough-'))\n  testDirectories.push(directory)\n  const scenario = path.join(directory, 'scenario.mjs')\n  await writeFile(\n    scenario,\n    `export const events = []\nexport async function setup({ request }) {\n  if (typeof request.post !== 'function') throw new Error('API context missing')\n  events.push('setup')\n  return { id: 'recording-only' }\n}\nexport async function teardown({ fixture, request }) {\n  if (typeof request.delete !== 'function') throw new Error('API context missing')\n  events.push('cleanup:' + fixture.id)\n}`,\n  )\n  await assert.rejects(\n    preparation.runWithScenarioFixture({ scenario, baseURL: 'http://localhost:3000' }, async () => {\n      throw new Error('Walkthrough failed')\n    }),\n    /Walkthrough failed/,\n  )\n  const module = await import(pathToFileURL(scenario).href)\n  assert.deepEqual(module.events, ['setup', 'cleanup:recording-only'])\n})\n\ntest('should protect an existing script snapshot from being overwritten by another take', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-existing-script-'))\n  testDirectories.push(directory)\n  const output = path.join(directory, 'demo.mp4')\n  await writeFile(path.join(directory, 'demo.scenario.mjs'), 'reviewed script')\n  await assert.rejects(\n    preparation.assertCandidatePathsAvailable({\n      output,\n      contactSheet: path.join(directory, 'demo.png'),\n      manifest: path.join(directory, 'demo.json'),\n    }),\n    /Use a new --label/,\n  )\n})\n\ntest('should reject packaging when the scenario changes during a take', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-script-changed-'))\n  testDirectories.push(directory)\n  const scenario = path.join(directory, 'scenario.mjs')\n  const scenarioSource = Buffer.from('export default async function original() {}')\n  await writeFile(scenario, 'export default async function revised() {}')\n  await assert.rejects(\n    packageCandidate({\n      scenario,\n      scenarioSource,\n      trimStart: 0,\n      output: path.join(directory, 'demo.mp4'),\n      rawOutput: path.join(directory, 'demo.webm'),\n      manifest: path.join(directory, 'demo.json'),\n      contactSheet: path.join(directory, 'demo.png'),\n    }),\n    /scenario changed during this take/,\n  )\n})\n\ntest('should reject colliding candidate paths before any artifacts exist', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'prepare-pr-demo-collision-'))\n  testDirectories.push(directory)\n  const output = path.join(directory, 'demo.mp4')\n  for (const overrides of [\n    { manifest: path.join(directory, 'demo.scenario.mjs') },\n    { contactSheet: output },\n    { rawOutput: output },\n  ]) {\n    await assert.rejects(\n      preparation.assertCandidatePathsAvailable({\n        contactSheet: path.join(directory, 'sheet.png'),\n        manifest: path.join(directory, 'demo.json'),\n        rawOutput: path.join(directory, 'demo.webm'),\n        output,\n        ...overrides,\n      }),\n      /distinct|collision/i,\n    )\n  }\n})\n\ntest('should reject a modified or missing scenario snapshot during verification', async () => {\n  const directory = await createFakeMediaTools()\n  const output = path.join(directory, 'demo.mp4')\n  const rawOutput = path.join(directory, 'demo.webm')\n  const manifest = path.join(directory, 'demo.json')\n  const scenario = path.join(directory, 'source.mjs')\n  await writeFile(rawOutput, 'recording')\n  await writeFile(scenario, 'export default async function scenario() {}')\n  const result = await packageCandidate({\n    contactSheet: path.join(directory, 'sheet.png'),\n    environment: { ...process.env, PATH: `${directory}:${process.env.PATH}` },\n    label: 'demo',\n    manifest,\n    output,\n    rawOutput,\n    scenario,\n    trimStart: 0,\n  })\n  await verifyCandidateManifest(manifest)\n  await writeFile(result.scenarioSnapshotPath, 'changed after review')\n  await assert.rejects(verifyCandidateManifest(manifest), /scenario snapshot.*does not match/i)\n  await rm(result.scenarioSnapshotPath)\n  await assert.rejects(verifyCandidateManifest(manifest))\n})\n\ntest('should preserve walkthrough errors alongside teardown errors', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'prepare-pr-demo-cleanup-'))\n  testDirectories.push(directory)\n  const scenario = path.join(directory, 'scenario.mjs')\n  await writeFile(\n    scenario,\n    `export async function teardown() { throw new Error('cleanup failed') }`,\n  )\n  const original = new Error('walkthrough failed')\n  await assert.rejects(\n    preparation.runWithScenarioFixture(\n      {\n        baseURL: 'http://localhost:3000',\n        scenario,\n      },\n      async () => {\n        throw original\n      },\n    ),\n    (error) => {\n      assert.equal(error.cause, original)\n      assert.deepEqual(\n        error.errors.map((error) => error.message),\n        ['walkthrough failed', 'cleanup failed'],\n      )\n      assert.match(error.message, /walkthrough failed/)\n      return true\n    },\n  )\n  await assert.rejects(\n    preparation.runWithScenarioFixture(\n      {\n        baseURL: 'http://localhost:3000',\n        scenario,\n      },\n      async () => {},\n    ),\n    /cleanup failed/,\n  )\n})\n\ntest('should accept a11y overrides and reject invalid modes', () => {\n  for (const a11y of ['on', 'off']) {\n    assert.equal(parseArgs(['--scenario', './demo.mjs', '--a11y', a11y]).a11y, a11y)\n  }\n  assert.throws(\n    () => parseArgs(['--scenario', './demo.mjs', '--a11y', 'maybe']),\n    /--a11y must be on or off/,\n  )\n})\n", "skills/record-pr-demo/scripts/presentation-demo.mjs": "import { readFile } from 'node:fs/promises'\n\n/** Mounts the live application inside the same browser page that records the chrome. */\nexport async function createPresentation({\n  page: stage,\n  options,\n  viewport,\n  baseURL = 'http://localhost:3000',\n  pauseScale,\n  startedAt = performance.now(),\n}) {\n  const wrapperURL = new URL('/__payload_pr_demo_chrome__', baseURL).href\n  const wrapper = (route) =>\n    route.fulfill({\n      contentType: 'text/html',\n      body: '<!doctype html><html><head><meta charset=\"utf-8\"><title>Demo recording</title><style>body{margin:0}</style></head><body><div id=\"demo-stage\"></div></body></html>',\n    })\n  if (options.accessibility) {\n    const observerSource = await readFile(\n      new URL('./accessibility-demo.mjs', import.meta.url),\n      'utf8',\n    )\n    await stage.context().addInitScript({\n      content: `${observerSource.replace('export function', 'function')}\n      if (window.name === 'pr-demo-app' && window.parent !== window) {\n        window.__stopDemoAccessibility = observeAccessibility({ report: state => window.parent.postMessage({ type: 'payload-demo-accessibility', state }, '*') })\n      }`,\n    })\n  }\n  await stage.route(wrapperURL, wrapper)\n  try {\n    await stage.goto(wrapperURL)\n    const source = await readFile(new URL('./WindowChrome/index.mjs', import.meta.url), 'utf8')\n    const sidebarSource = Buffer.from(\n      await readFile(new URL('./WindowChrome/sidebar.mjs', import.meta.url)),\n    ).toString('base64')\n    await stage.evaluate(\n      async ({ source, sidebarSource, options, viewport, shouldAnimateAnnotations }) => {\n        const { mountDemoChrome, bindDemoHistory } = await import(\n          `data:text/javascript;base64,${source}`\n        )\n        const root = document.querySelector('#demo-stage')\n        const app = document.createElement('iframe')\n        window.demoChrome = mountDemoChrome({\n          ...options,\n          onNavigate: (direction) => app.contentWindow.history.go(direction),\n          onRefresh: () => window.refreshDemoApplication(),\n          root,\n          viewport,\n          shouldAnimateFeedback: shouldAnimateAnnotations,\n        })\n        app.setAttribute('data-pr-demo-app', '')\n        app.name = 'pr-demo-app'\n        app.title = 'Payload application'\n        app.slot = 'content'\n        if (options.accessibility) {\n          window.demoAccessibilityListener = (event) => {\n            if (\n              event.source === app.contentWindow &&\n              event.data?.type === 'payload-demo-accessibility'\n            ) {\n              window.demoChrome.setAccessibilityState(event.data.state)\n            }\n          }\n          window.addEventListener('message', window.demoAccessibilityListener)\n        }\n        window.stopDemoHistory = bindDemoHistory({ app, chrome: window.demoChrome })\n        root.append(app)\n        const { mountAnnotationSidebar } = await import(\n          `data:text/javascript;base64,${sidebarSource}`\n        )\n        window.demoSidebar = mountAnnotationSidebar({\n          root,\n          change: options.change,\n          steps: options.annotationSteps,\n          shouldAnimate: shouldAnimateAnnotations,\n        })\n      },\n      {\n        source: Buffer.from(source).toString('base64'),\n        sidebarSource,\n        options,\n        viewport,\n        shouldAnimateAnnotations: pauseScale > 0,\n      },\n    )\n\n    const handle = await stage.locator('[data-pr-demo-app]').elementHandle()\n    const frame = await handle.contentFrame()\n    await handle.dispose()\n    if (!frame) throw new Error('Could not mount the application iframe')\n    const call = ({ method, value }) =>\n      stage.evaluate(\n        async ({ method, value }) => {\n          const target = method === 'setAnnotation' ? window.demoSidebar : window.demoChrome\n          await target[method](value)\n        },\n        { method, value },\n      )\n    const onAppNavigation = (navigatedFrame) => {\n      if (navigatedFrame === frame) {\n        void call({ method: 'setURL', value: frame.url() }).catch(() => {\n          // Navigation can invalidate a cosmetic URL update; the frame binding also syncs it.\n        })\n      }\n    }\n    stage.on('framenavigated', onAppNavigation)\n    await call({ method: 'setURL', value: frame.url() })\n    let currentViewport = { ...viewport }\n    let isResizing = false\n    let isRefreshing = false\n    const resizeWindow = async ({ width, height, duration = 1000 }) => {\n      if (isResizing) throw new Error('Await the previous resizeWindow before starting another')\n      isResizing = true\n      try {\n        await call({\n          method: 'animateViewport',\n          value: { width, height, duration: duration * pauseScale },\n        })\n        currentViewport = { width, height }\n      } finally {\n        isResizing = false\n      }\n    }\n    // Keep locators, navigation and evaluation in the real app frame. Input devices,\n    // request events and context-wide init scripts belong to the containing page.\n    const appPage = new Proxy(frame, {\n      get(target, property) {\n        if (property === 'viewportSize') return () => ({ ...currentViewport })\n        if (property === 'setViewportSize')\n          return (value) => resizeWindow({ ...value, duration: 0 })\n        if (property === 'reload')\n          return async (options) => {\n            if (isRefreshing)\n              throw new Error('Await the previous page.reload() before refreshing again')\n            isRefreshing = true\n            try {\n              await call({ method: 'setRefreshState', value: { state: 'refreshing' } })\n              await stage.evaluate(\n                () =>\n                  new Promise((resolve) =>\n                    requestAnimationFrame(() => requestAnimationFrame(resolve)),\n                  ),\n              )\n              const started = performance.now()\n              const [response] = await Promise.all([\n                target.waitForNavigation(options),\n                target.evaluate(() => location.reload()),\n              ])\n              if (response && response.status() >= 400)\n                throw new Error(`Refresh failed: HTTP ${response.status()}`)\n              await stage.waitForTimeout(\n                Math.max(0, 300 * pauseScale - (performance.now() - started)),\n              )\n              await call({ method: 'setRefreshState', value: { state: 'refreshed' } })\n              return response\n            } catch (error) {\n              await call({ method: 'setRefreshState', value: { state: 'failed' } }).catch(() => {})\n              throw error\n            } finally {\n              isRefreshing = false\n            }\n          }\n        if (property === 'goBack' || property === 'goForward')\n          return async () => {\n            throw new Error(\n              `${property} is not supported in presentation mode; use await click(chrome.${property === 'goBack' ? 'back' : 'forward'})`,\n            )\n          }\n        if (property === 'addInitScript') return stage.context().addInitScript.bind(stage.context())\n        const owner = property in target ? target : stage\n        const value = Reflect.get(owner, property)\n        return typeof value === 'function' ? value.bind(owner) : value\n      },\n    })\n    const refreshBinding = await stage.exposeFunction('refreshDemoApplication', () =>\n      appPage.reload(),\n    )\n    return {\n      page: stage,\n      appPage,\n      chrome: {\n        back: stage.getByRole('button', { name: 'Back', exact: true }),\n        forward: stage.getByRole('button', { name: 'Forward', exact: true }),\n        refresh: stage.getByRole('button', { name: 'Refresh frame', exact: true }),\n      },\n      startedAt,\n      resizeWindow,\n      setAnnotation: (value) => call({ method: 'setAnnotation', value }),\n      clearAnnotation: () => call({ method: 'setAnnotation', value: null }),\n      flush: () =>\n        stage.evaluate(\n          () =>\n            new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))),\n        ),\n      stop: async () => {\n        stage.off('framenavigated', onAppNavigation)\n        await refreshBinding?.dispose()\n        await stage.evaluate(() => {\n          window.stopDemoHistory?.()\n          window.demoSidebar?.destroy()\n        })\n        if (options.accessibility) {\n          await frame.evaluate(() => window.__stopDemoAccessibility?.()).catch(() => {})\n          await stage.evaluate(() => {\n            window.removeEventListener('message', window.demoAccessibilityListener)\n            delete window.demoAccessibilityListener\n          })\n        }\n        await stage.unroute(wrapperURL, wrapper)\n      },\n    }\n  } catch (error) {\n    await stage.unroute(wrapperURL, wrapper)\n    throw error\n  }\n}\n", "skills/record-pr-demo/scripts/presentation-demo.test.mjs": "import assert from 'node:assert/strict'\nimport { spawnSync } from 'node:child_process'\nimport { mkdtemp, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport path from 'node:path'\nimport { test } from 'node:test'\nimport { convertDemo } from './convert-demo.mjs'\nimport { previewDemo, recordDemo, validateDemo } from './record-demo.mjs'\n\nasync function withScenario({ run }) {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-presentation-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n  try {\n    await writeFile(\n      scenario,\n      `\n      export const presentation = {\n        change: { kind: 'Feature', title: 'Responsive lists', description: 'Manage posts at any size.' },\n      }\n      export default async function ({ page, expect, ready, resizeWindow, setAnnotation, clearAnnotation }) {\n        if (typeof resizeWindow !== 'function') throw new Error('Missing resizeWindow helper')\n        await page.goto('data:text/html,<style>body{margin:0;background:rgb(0,200,0)}@media(max-width:600px){body{background:rgb(0,0,200)}}</style><button>Real app button</button>')\n        await setAnnotation({ index: 1, total: 2, title: 'Desktop', body: 'Full layout.' })\n        await ready()\n        await resizeWindow({ width: 390, height: 720, duration: 240 })\n        await expect(page.getByRole('button', { name: 'Real app button' })).toBeVisible()\n        if (await page.evaluate(() => innerWidth) !== 390) throw new Error('Application was not really resized')\n        await expect(page.locator('body')).toHaveCSS('background-color', 'rgb(0, 0, 200)')\n        await clearAnnotation()\n        await setAnnotation({ index: 2, total: 2, title: 'Mobile', body: 'Compact layout.' })\n      }\n    `,\n    )\n    await run({ directory, scenario })\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n}\n\ntest('should preview the shared presentation while resizing the live application iframe', async () => {\n  await withScenario({\n    run: async ({ directory, scenario }) => {\n      const output = path.join(directory, 'preview.png')\n      await previewDemo({\n        baseURL: 'http://localhost:3000',\n        label: 'preview',\n        output,\n        scenario,\n        viewport: { width: 1280, height: 720 },\n      })\n      const probe = spawnSync('ffprobe', [\n        '-v',\n        'error',\n        '-show_entries',\n        'stream=width,height',\n        '-of',\n        'json',\n        output,\n      ])\n      assert.equal(probe.status, 0, probe.stderr.toString())\n      assert.deepEqual(JSON.parse(probe.stdout).streams[0], { width: 1634, height: 1000 })\n      const pixel = spawnSync('ffmpeg', [\n        '-v',\n        'error',\n        '-i',\n        output,\n        '-vf',\n        'crop=2:2:400:500',\n        '-frames:v',\n        '1',\n        '-f',\n        'rawvideo',\n        '-pix_fmt',\n        'rgb24',\n        '-',\n      ])\n      assert.equal(pixel.status, 0, pixel.stderr.toString())\n      assert.ok(\n        pixel.stdout[2] > 150 && pixel.stdout[0] < 80,\n        'Preview must contain the blue mobile application frame',\n      )\n    },\n  })\n})\n\ntest('should record a fixed-size canvas across genuine viewport changes and retain ready timing', async () => {\n  await withScenario({\n    run: async ({ directory, scenario }) => {\n      const output = path.join(directory, 'recording.webm')\n      let readyTime\n      await recordDemo({\n        baseURL: 'http://localhost:3000',\n        label: 'record',\n        output,\n        scenario,\n        viewport: { width: 1280, height: 720 },\n        onOpeningReady: (value) => {\n          readyTime = value\n        },\n      })\n      assert.ok(readyTime > 0)\n      const converted = path.join(directory, 'recording.mp4')\n      await convertDemo({ input: output, output: converted, trimStart: readyTime })\n      const opening = spawnSync('ffmpeg', [\n        '-v',\n        'error',\n        '-i',\n        converted,\n        '-vf',\n        'crop=2:2:400:500',\n        '-frames:v',\n        '1',\n        '-f',\n        'rawvideo',\n        '-pix_fmt',\n        'rgb24',\n        '-',\n      ])\n      assert.equal(opening.status, 0, opening.stderr.toString())\n      assert.ok(\n        opening.stdout[1] > 150 && opening.stdout[0] < 80 && opening.stdout[2] < 80,\n        'Composed MP4 must open on the ready green application frame',\n      )\n      const probe = spawnSync('ffprobe', [\n        '-v',\n        'error',\n        '-show_entries',\n        'stream=width,height',\n        '-of',\n        'json',\n        output,\n      ])\n      assert.equal(probe.status, 0, probe.stderr.toString())\n      assert.deepEqual(JSON.parse(probe.stdout).streams[0], { width: 1634, height: 1000 })\n      const pixel = spawnSync('ffmpeg', [\n        '-v',\n        'error',\n        '-sseof',\n        '-0.2',\n        '-i',\n        output,\n        '-vf',\n        'crop=2:2:400:500',\n        '-frames:v',\n        '1',\n        '-f',\n        'rawvideo',\n        '-pix_fmt',\n        'rgb24',\n        '-',\n      ])\n      assert.equal(pixel.status, 0, pixel.stderr.toString())\n      assert.ok(\n        pixel.stdout[2] > 150 && pixel.stdout[0] < 80,\n        'Recording must contain the blue mobile application frame',\n      )\n      const decode = spawnSync('ffmpeg', ['-v', 'error', '-i', output, '-f', 'null', '-'])\n      assert.equal(decode.status, 0, decode.stderr.toString())\n    },\n  })\n})\n\ntest('should exercise the same presentation helpers during fast validation', async () => {\n  await withScenario({\n    run: async ({ scenario }) => {\n      await validateDemo({\n        baseURL: 'http://localhost:3000',\n        label: 'validation',\n        scenario,\n        viewport: { width: 1280, height: 720 },\n      })\n    },\n  })\n})\n\ntest('should resize the live application iframe in the recorded page without image capture', async () => {\n  const { chromium } = await import('@playwright/test')\n  const { createPresentation } = await import('./presentation-demo.mjs')\n  const browser = await chromium.launch({ headless: true })\n  let presentation\n  try {\n    const context = await browser.newContext({ viewport: { width: 1634, height: 1000 } })\n    await context.route('http://app.test/editor', (route) =>\n      route.fulfill({\n        contentType: 'text/html',\n        body: `<style>body{margin:0;background:green}@media(max-width:600px){body{background:blue}}</style><button onclick=\"this.textContent='Clicked'\">Real button</button><script>window.widths=[];addEventListener('resize',()=>window.widths.push(innerWidth))</script>`,\n      }),\n    )\n    const stage = await context.newPage()\n    presentation = await createPresentation({\n      browser,\n      page: stage,\n      baseURL: 'http://app.test',\n      viewport: { width: 1280, height: 720 },\n      pauseScale: 1,\n      options: {\n        change: {\n          kind: 'Fix',\n          title: 'Native iframe resize',\n          description: 'One browser renders the app and its chrome.',\n        },\n      },\n    })\n    assert.ok(presentation.appPage, 'Application must live in the recorded iframe')\n    await presentation.appPage.goto('http://app.test/editor')\n    assert.equal(await presentation.appPage.evaluate(() => window.self !== window.top), true)\n    assert.equal(await stage.locator('iframe').count(), 1)\n    assert.equal(await stage.locator('[data-frame]').count(), 0)\n    await presentation.appPage.getByRole('button', { name: 'Real button' }).click()\n    assert.equal(await presentation.appPage.getByRole('button').textContent(), 'Clicked')\n    await presentation.appPage.reload()\n    assert.equal(await stage.locator('iframe').count(), 1)\n    assert.equal(await presentation.appPage.getByRole('button').textContent(), 'Real button')\n    for (const method of ['goBack', 'goForward']) {\n      await assert.rejects(\n        () => presentation.appPage[method](),\n        new RegExp(`use await click\\\\(chrome\\\\.${method === 'goBack' ? 'back' : 'forward'}\\\\)`),\n      )\n    }\n    await presentation.resizeWindow({ width: 390, height: 720, duration: 500 })\n    const widths = await presentation.appPage.evaluate(() => window.widths)\n    assert.ok(new Set(widths).size >= 8, 'The real iframe must reflow throughout the animation')\n    assert.equal(await presentation.appPage.evaluate(() => innerWidth), 390)\n    assert.deepEqual(stage.viewportSize(), { width: 1634, height: 1000 })\n    assert.equal(\n      browser.contexts().length,\n      1,\n      'Record one page/context, with no second app browser surface',\n    )\n    assert.equal(context.pages().length, 1)\n    assert.equal(\n      await presentation.appPage\n        .locator('body')\n        .evaluate((el) => getComputedStyle(el).backgroundColor),\n      'rgb(0, 0, 255)',\n    )\n  } finally {\n    await presentation?.stop()\n    await browser.close()\n  }\n})\n\ntest('should preserve app-relative pointer positions when the iframe is scaled to fit', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-scaled-pointer-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n  try {\n    await writeFile(\n      scenario,\n      `\n      export const presentation = {\n        change: { kind: 'Fix', title: 'Scaled pointer', description: 'Keep input coordinates accurate.' },\n      }\n      export default async function ({ page, moveCursor, click }) {\n        await page.goto('data:text/html,' + encodeURIComponent(\\`<style>body{margin:0}button{display:block;width:240px;height:240px;border:0;padding:0}</style><button onmousemove=\"window.moved=[event.clientX,event.clientY]\" onclick=\"window.clicked=[event.clientX,event.clientY]\">Target</button>\\`))\n        const target = page.getByRole('button', { name: 'Target' })\n        await moveCursor(target, { position: { x: 100, y: 100 }, duration: 0, pauseAfter: 0 })\n        const moved = await page.evaluate(() => window.moved)\n        if (moved.some(value => Math.abs(value - 100) > 1)) throw new Error('Wrong move coordinates: ' + moved)\n        await click(target, { position: { x: 100, y: 100 }, duration: 0, before: 0, after: 0 })\n        const clicked = await page.evaluate(() => window.clicked)\n        if (clicked.some(value => Math.abs(value - 100) > 1)) throw new Error('Wrong click coordinates: ' + clicked)\n      }\n    `,\n    )\n    await validateDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'scaled-pointer',\n      scenario,\n      viewport: { width: 1920, height: 1080 },\n    })\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('should route the existing annotation API into chrome without floating overlays', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-panel-api-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n  try {\n    await writeFile(\n      scenario,\n      `\n      export const presentation = {change:{kind:'Feature',title:'Unified annotations',description:'One API for the recording.'}}\n      export default async function ({page, expect, showAnnotation, hideAnnotation, setAnnotation, clearAnnotation}) {\n        await page.goto('data:text/html,<input aria-label=\"Editor\">')\n        await page.getByRole('textbox').focus()\n        const stage=page.context().pages()[0]\n        await showAnnotation({title:'First step',body:'Panel detail.',index:1,total:2})\n        await expect(stage.locator('.sidebar-step p')).toHaveText('Panel detail.')\n        await expect(stage.locator('.sidebar-step')).toHaveAttribute('aria-current','step')\n        await expect(page.locator('[data-pr-demo-annotation]')).toHaveCount(0)\n        await expect(page.getByRole('textbox')).toBeFocused()\n        await showAnnotation({title:'Next step',body:'Fast validation settles immediately.',index:2,total:2})\n        await expect(stage.locator('.sidebar-step p')).toHaveText('Fast validation settles immediately.')\n        try {\n          await showAnnotation({type:'floating',body:'Legacy note.',position:{top:20,right:20}})\n          throw new Error('Floating annotation was accepted')\n        } catch(error) {\n          if(!error.message.includes('remove type, position, and width')) throw error\n        }\n        await expect(stage.locator('.sidebar-step p')).toHaveText('Fast validation settles immediately.')\n        await showAnnotation({title:'Single note',body:'No progress ring.'})\n        await expect(stage.locator('.sidebar-step p')).toHaveText('No progress ring.')\n        await expect(page.locator('[data-pr-demo-annotation]')).toHaveCount(0)\n        await hideAnnotation()\n        await expect(stage.locator('.sidebar-steps')).toBeHidden()\n        await expect(stage.locator('.sidebar-intro p')).toHaveText('One API for the recording.')\n        await setAnnotation({title:'Alias step',body:'Same panel.',index:2,total:2})\n        await expect(stage.locator('.sidebar-step p')).toHaveText('Same panel.')\n        try { await showAnnotation({title:'Invalid',body:'Detail',index:3,total:2}); throw new Error('Invalid step accepted') }\n        catch(error) { if(!error.message.includes('pagination')) throw error }\n        await expect(stage.locator('.sidebar-step p')).toHaveText('Same panel.')\n        await clearAnnotation()\n        await expect(stage.locator('.sidebar-steps')).toBeHidden()\n      }\n    `,\n    )\n    await validateDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'panel-api',\n      scenario,\n      viewport: { width: 1280, height: 720 },\n    })\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('should indicate real reloads through completion and failure while viewport dimensions remain visible', async () => {\n  const { chromium, expect } = await import('@playwright/test')\n  const { createPresentation } = await import('./presentation-demo.mjs')\n  const browser = await chromium.launch({ headless: true })\n  let presentation\n  let release\n  try {\n    const context = await browser.newContext({ viewport: { width: 1634, height: 1000 } })\n    let requests = 0\n    await context.route('http://app.test/reload', async (route) => {\n      requests++\n      if (requests === 2)\n        await new Promise((resolve) => {\n          release = resolve\n        })\n      if (requests === 3) return route.abort('failed')\n      await route.fulfill({ contentType: 'text/html', body: `<button>Loaded ${requests}</button>` })\n    })\n    const stage = await context.newPage()\n    presentation = await createPresentation({\n      page: stage,\n      baseURL: 'http://app.test',\n      viewport: { width: 1280, height: 720 },\n      pauseScale: 1,\n      options: {\n        change: { kind: 'Fix', title: 'Refresh status', description: 'See the real frame reload.' },\n      },\n    })\n    await presentation.appPage.goto('http://app.test/reload')\n    const initialPanel = await stage.locator('.sidebar-shell').boundingBox()\n    const pending = presentation.appPage.reload()\n    await expect(stage.getByRole('status')).toHaveText('Refreshing…')\n    await expect.poll(() => Boolean(release)).toBe(true)\n    await assert.rejects(() => presentation.appPage.reload(), /Await the previous/)\n    await presentation.resizeWindow({ width: 390, height: 720, duration: 100 })\n    await expect(stage.locator('[data-size]')).toHaveText('390 × 720')\n    await expect(stage.getByRole('status')).toHaveText('Refreshing…')\n    assert.deepEqual(await stage.locator('.sidebar-shell').boundingBox(), initialPanel)\n    release()\n    const response = await pending\n    assert.equal(response.status(), 200)\n    assert.equal(requests, 2)\n    await expect(presentation.appPage.getByRole('button')).toHaveText('Loaded 2')\n    await expect(stage.getByRole('status')).toHaveText('Refreshed')\n    await assert.rejects(() => presentation.appPage.reload({ timeout: 3000 }))\n    await expect(stage.getByRole('status')).toHaveText('Refresh failed')\n    await stage.waitForTimeout(1100)\n    await expect(stage.getByRole('status')).toHaveText('Refresh failed')\n  } finally {\n    release?.()\n    await presentation?.stop()\n    await browser.close()\n  }\n})\n\nfor (const accessibility of [false, true]) {\n  test(`should preserve one CSS pixel per captured pixel with accessibility ${accessibility}`, async () => {\n    await withScenario({\n      run: async ({ directory, scenario }) => {\n        await writeFile(\n          scenario,\n          `\n          export const presentation = {\n            accessibility: ${accessibility},\n            change: {kind:'Feature', title:'Native detail', description:'Preserve thin borders.'},\n          }\n          export default async function ({page, expect, ready, showAnnotation, resizeWindow}) {\n            await page.goto('data:text/html,<button>Native app</button>')\n            await showAnnotation({index:1,total:1,title:'Inspect controls',body:'Keep their original dimensions.'})\n            await ready()\n            const stage = page.context().pages()[0]\n            const geometry = await stage.evaluate(() => {\n              const bounds = document.querySelector('iframe').getBoundingClientRect()\n              return {width:bounds.width,height:bounds.height,canvasHeight:innerHeight}\n            })\n            expect(geometry).toEqual({width:1440,height:900,canvasHeight:1086})\n            await resizeWindow({width:390,height:720,duration:0})\n            expect(await stage.evaluate(() => innerHeight)).toBe(1086)\n          }\n        `,\n        )\n        const output = path.join(directory, 'native.png')\n        await previewDemo({\n          baseURL: 'http://localhost:3000',\n          label: 'native-detail',\n          output,\n          scenario,\n          viewport: { width: 1440, height: 900 },\n        })\n        const probe = spawnSync('ffprobe', [\n          '-v',\n          'error',\n          '-show_entries',\n          'stream=width,height',\n          '-of',\n          'json',\n          output,\n        ])\n        assert.equal(probe.status, 0, probe.stderr.toString())\n        assert.deepEqual(JSON.parse(probe.stdout).streams[0], {\n          width: 1794,\n          height: 1086,\n        })\n      },\n    })\n  })\n}\n\ntest('should show the live application URL through navigation and browser history', async () => {\n  const { chromium, expect } = await import('@playwright/test')\n  const { createPresentation } = await import('./presentation-demo.mjs')\n  const browser = await chromium.launch({ headless: true })\n  let presentation\n  try {\n    const context = await browser.newContext()\n    await context.route('http://app.test/**', (route) =>\n      route.fulfill({\n        contentType: 'text/html',\n        body: '<h1>Application</h1>',\n      }),\n    )\n    const stage = await context.newPage()\n    presentation = await createPresentation({\n      page: stage,\n      baseURL: 'http://app.test',\n      viewport: { width: 1280, height: 720 },\n      pauseScale: 0,\n      options: {\n        change: { kind: 'Fix', title: 'URL bar', description: 'Follow the real application URL.' },\n      },\n    })\n    const address = stage.getByRole('textbox', { name: 'Application URL' })\n    await presentation.appPage.goto('http://app.test/editor')\n    await expect(address).toHaveText('http://app.test/editor')\n    await presentation.appPage.evaluate(() => history.pushState({}, '', '?locale=es'))\n    await expect(address).toHaveText('http://app.test/editor?locale=es')\n    await expect(presentation.chrome.back).toBeEnabled()\n    await expect(presentation.chrome.forward).toBeDisabled()\n    await presentation.chrome.back.click()\n    await expect(address).toHaveText('http://app.test/editor')\n    await expect(presentation.chrome.back).toBeDisabled()\n    await expect(presentation.chrome.forward).toBeEnabled()\n    await presentation.chrome.forward.click()\n    await expect(address).toHaveText('http://app.test/editor?locale=es')\n    await presentation.chrome.back.click()\n    await expect(address).toHaveText('http://app.test/editor')\n    await presentation.appPage.evaluate(() => history.replaceState({}, '', '?locale=en#title'))\n    await expect(address).toHaveText('http://app.test/editor?locale=en#title')\n    await presentation.appPage.goto('http://app.test/list?locale=en')\n    await expect(address).toHaveText('http://app.test/list?locale=en')\n  } finally {\n    await presentation?.stop()\n    await browser.close()\n  }\n})\n\ntest('should use the shared sidebar during recorder resizing and reject mismatched step descriptions', async () => {\n  const { chromium, expect } = await import('@playwright/test')\n  const { createPresentation } = await import('./presentation-demo.mjs')\n  const browser = await chromium.launch({ headless: true })\n  try {\n    const stage = await browser.newPage({ viewport: { width: 1634, height: 1000 } })\n    const steps = Array.from({ length: 12 }, (_, index) => ({\n      title: `Step ${index + 1}`,\n      body: `Visible outcome ${index + 1}. This description explains the action shown in the application.`,\n      ...(index === 11 ? { kind: 'Bug' } : {}),\n    }))\n    steps[0].body = 'A long opening description that fits in the scrollable sidebar. '.repeat(8)\n    const presentation = await createPresentation({\n      page: stage,\n      options: {\n        annotationSteps: steps,\n        change: { kind: 'Bug', title: 'Before', description: 'Show the visible failure.' },\n      },\n      viewport: { width: 1280, height: 720 },\n      pauseScale: 0,\n    })\n    await presentation.setAnnotation({ ...steps[0], index: 1, total: 12 })\n    await presentation.flush()\n    const sidebar = stage.locator('.annotation-sidebar')\n    const initial = await sidebar.boundingBox()\n    const initialWindow = await stage.locator('[data-window]').boundingBox()\n    assert.ok(Math.abs(initial.y - initialWindow.y) < 0.1)\n    assert.ok(Math.abs(initial.height - initialWindow.height) < 0.1)\n\n    assert.equal(await sidebar.locator('button').count(), 0)\n    await presentation.resizeWindow({ width: 390, height: 720 })\n    await presentation.flush()\n    assert.deepEqual(await sidebar.boundingBox(), initial)\n    const panel = await sidebar.boundingBox()\n    const window = await stage.locator('[data-window]').boundingBox()\n    assert.ok(Math.abs(panel.x + panel.width - window.x) < 0.1)\n    await assert.rejects(\n      () =>\n        presentation.setAnnotation({\n          title: 'Different',\n          body: 'Stale description',\n          index: 12,\n          total: 12,\n        }),\n      /must match/,\n    )\n    await presentation.setAnnotation({ ...steps[11], index: 12, total: 12 })\n    await presentation.flush()\n    await expect(sidebar.locator('[aria-current=step]')).toContainText('Visible outcome 12')\n    assert.ok((await sidebar.locator('.sidebar-steps').evaluate((e) => e.scrollTop)) > 0)\n    await presentation.stop()\n  } finally {\n    await browser.close()\n  }\n})\n\ntest('should keep navigation URL update failures non-fatal', async () => {\n  const { chromium } = await import('@playwright/test')\n  const { createPresentation } = await import('./presentation-demo.mjs')\n  const browser = await chromium.launch({ headless: true })\n  try {\n    const stage = await browser.newPage({ viewport: { width: 1634, height: 1000 } })\n    const presentation = await createPresentation({\n      page: stage,\n      options: { change: { kind: 'Fix', title: 'Navigation', description: 'Keep recording.' } },\n      viewport: { width: 1280, height: 720 },\n      pauseScale: 0,\n    })\n    const originalEvaluate = stage.evaluate\n    let failedUpdates = 0\n    stage.evaluate = async () => {\n      failedUpdates++\n      throw new Error('Execution context was destroyed during navigation')\n    }\n    stage.emit(\n      'framenavigated',\n      stage.frames().find((frame) => frame.parentFrame()),\n    )\n    await new Promise((resolve) => setImmediate(resolve))\n    stage.evaluate = originalEvaluate\n    assert.equal(failedUpdates, 1)\n    await presentation.setAnnotation({\n      index: 1,\n      total: 1,\n      title: 'Still recording',\n      body: 'Navigation continues.',\n    })\n    await presentation.stop()\n  } finally {\n    await browser.close()\n  }\n})\n", "skills/record-pr-demo/scripts/preview-chrome.mjs": "#!/usr/bin/env node\nimport { createServer } from 'node:http'\nimport { readFile } from 'node:fs/promises'\nimport path from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\n/** Serves only the known preview assets on loopback; no app or video encoder is required. */\nexport async function startChromePreview({ port = 4400 } = {}) {\n  const assets = new Map([\n    ['/', ['preview/index.html', 'text/html']],\n    ['/preview/index.mjs', ['preview/index.mjs', 'text/javascript']],\n    ['/WindowChrome/sidebar.mjs', ['WindowChrome/sidebar.mjs', 'text/javascript']],\n    ['/preview/application.html', ['preview/application.html', 'text/html']],\n    ['/accessibility-demo.mjs', ['accessibility-demo.mjs', 'text/javascript']],\n    [\n      '/preview/accessibility-application.html',\n      ['preview/accessibility-application.html', 'text/html'],\n    ],\n    ['/WindowChrome/index.mjs', ['WindowChrome/index.mjs', 'text/javascript']],\n  ])\n  const server = createServer(async (request, response) => {\n    const asset = assets.get(new URL(request.url, 'http://localhost').pathname)\n    if (!asset) {\n      response.writeHead(404).end('Not found')\n      return\n    }\n    try {\n      const content = await readFile(new URL(asset[0], import.meta.url))\n      response\n        .writeHead(200, {\n          'Content-Type': `${asset[1]}; charset=utf-8`,\n          'Cache-Control': 'no-store',\n        })\n        .end(content)\n    } catch {\n      response.writeHead(500).end('Could not read preview asset')\n    }\n  })\n  await new Promise((resolve, reject) => {\n    server.once('error', reject)\n    server.listen(port, '127.0.0.1', resolve)\n  })\n  return { server, url: `http://127.0.0.1:${server.address().port}` }\n}\n\nif (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {\n  const args = process.argv.slice(2)\n  if (\n    args.length &&\n    (args.length !== 2 || args[0] !== '--port' || !/^\\d+$/.test(args[1]) || Number(args[1]) > 65535)\n  ) {\n    throw new Error('Usage: preview-chrome.mjs [--port 4400]')\n  }\n  const { server, url } = await startChromePreview({ port: args.length ? Number(args[1]) : 4400 })\n  console.log(\n    `Chrome preview: ${url}\\nEdits appear on reload; no recording or conversion required.`,\n  )\n  for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => server.close())\n}\n", "skills/record-pr-demo/scripts/preview-chrome.test.mjs": "import assert from 'node:assert/strict'\nimport { test } from 'node:test'\nimport { chromium, expect } from '@playwright/test'\nimport { startChromePreview } from './preview-chrome.mjs'\n\n// This tests the same component and controls shipped to the user, not a mock preview.\ntest('should scrub real responsive content without changing the sidebar geometry', async () => {\n  const { server, url } = await startChromePreview({ port: 0 })\n  const browser = await chromium.launch({ headless: true })\n  try {\n    const page = await browser.newPage({ viewport: { width: 1120, height: 1000 } })\n    await page.goto(url)\n    await page.frameLocator('iframe').getByRole('heading', { name: 'Posts', exact: true }).waitFor()\n    const sidebar = page.locator('#chrome .sidebar-shell')\n    const initial = await sidebar.boundingBox()\n    const slider = page.getByRole('slider')\n    for (const milliseconds of [1600, 2000, 2800]) {\n      await slider.evaluate((element, value) => {\n        element.value = String(value)\n        element.dispatchEvent(new Event('input', { bubbles: true }))\n      }, milliseconds)\n      assert.equal(\n        await page\n          .frameLocator('iframe')\n          .locator('body')\n          .evaluate(() => innerWidth),\n        768,\n      )\n      assert.deepEqual(await sidebar.boundingBox(), initial)\n      assert.equal(await page.locator('.sidebar-step').nth(1).getAttribute('aria-current'), 'step')\n    }\n    for (const [milliseconds, step] of [\n      [1300, 1],\n      [3500, 2],\n      [4000, 3],\n    ]) {\n      await slider.evaluate((element, value) => {\n        element.value = String(value)\n        element.dispatchEvent(new Event('input', { bubbles: true }))\n      }, milliseconds)\n      assert.equal(\n        await page\n          .locator('.sidebar-step')\n          .nth(step - 1)\n          .getAttribute('aria-current'),\n        'step',\n      )\n    }\n    await slider.focus()\n    await page.keyboard.press('End')\n    assert.equal(await page.locator('.sidebar-step').nth(2).getAttribute('aria-current'), 'step')\n    assert.equal(\n      await page\n        .frameLocator('iframe')\n        .locator('body')\n        .evaluate(() => innerWidth),\n      390,\n    )\n    assert.deepEqual(await sidebar.boundingBox(), initial)\n    await page.getByLabel('Annotation', { exact: true }).uncheck()\n    assert.equal(await page.locator('#chrome .sidebar-intro').isVisible(), true)\n    assert.equal(await page.locator('#chrome .sidebar-steps').isVisible(), false)\n    await page.emulateMedia({ reducedMotion: 'reduce' })\n    await page.getByRole('button', { name: 'Desktop', exact: true }).click()\n    await page.getByRole('button', { name: 'Play resize', exact: true }).click()\n    assert.equal(await page.locator('#chrome [data-size]').textContent(), '390 × 720')\n    await page.getByRole('button', { name: 'Dark', exact: true }).click()\n    assert.equal(\n      await page.getByRole('button', { name: 'Dark', exact: true }).getAttribute('aria-pressed'),\n      'true',\n    )\n    assert.equal(\n      await page.locator('[data-canvas]').evaluate((e) => getComputedStyle(e).backgroundColor),\n      'rgb(25, 25, 25)',\n    )\n    assert.equal(\n      await page\n        .frameLocator('iframe')\n        .locator('body')\n        .evaluate((e) => getComputedStyle(e).backgroundColor),\n      'rgb(25, 25, 25)',\n    )\n    assert.equal(await page.locator('[data-size]').textContent(), '390 × 720')\n    assert.equal(await page.locator('#timeline').inputValue(), '5200')\n    assert.equal(new URL(page.url()).searchParams.get('theme'), 'dark')\n    await page.getByRole('button', { name: 'Light', exact: true }).click()\n    assert.equal(\n      await page.locator('[data-canvas]').evaluate((e) => getComputedStyle(e).backgroundColor),\n      'rgb(255, 255, 255)',\n    )\n    assert.equal(\n      await page\n        .frameLocator('iframe')\n        .locator('body')\n        .evaluate((e) => getComputedStyle(e).backgroundColor),\n      'rgb(255, 255, 255)',\n    )\n    await page.setViewportSize({ width: 320, height: 900 })\n    assert.equal(\n      await page.evaluate(() => document.documentElement.scrollWidth > innerWidth),\n      false,\n    )\n    assert.equal((await fetch(`${url}/package.json`)).status, 404)\n  } finally {\n    await browser.close()\n    await new Promise((resolve) => server.close(resolve))\n  }\n})\n\ntest('should refresh the real frame from the persistent toolbar button with keyboard controls', async () => {\n  const { server, url } = await startChromePreview({ port: 0 })\n  const browser = await chromium.launch({ headless: true })\n  try {\n    const { expect } = await import('@playwright/test')\n    const page = await browser.newPage({ viewport: { width: 1120, height: 1000 } })\n    let loads = 0\n    page.on('request', (request) => {\n      if (request.url().endsWith('/preview/application.html')) loads++\n    })\n    await page.route('**/preview/application.html', async (route) => {\n      if (loads > 1) await new Promise((resolve) => setTimeout(resolve, 200))\n      await route.continue()\n    })\n    await page.goto(url)\n    await page.frameLocator('iframe').getByRole('heading', { name: 'Posts', exact: true }).waitFor()\n    await page.getByRole('button', { name: 'Mobile', exact: true }).click()\n    const button = page.getByRole('button', { name: 'Refresh frame', exact: true })\n    await button.focus()\n    await page.keyboard.press('Enter')\n    await expect(page.locator('#chrome').getByRole('status')).toHaveText('Refreshing…')\n    await expect(page.locator('[data-size]')).toHaveText('390 × 720')\n    await expect(page.locator('#chrome').getByRole('status')).toHaveText('Refreshed')\n    assert.equal(loads, 2)\n    assert.equal(await button.evaluate((e) => e === e.getRootNode().activeElement), true)\n    await expect(page.locator('#chrome').getByRole('status')).toBeHidden()\n    await button.click()\n    await expect(page.locator('#chrome').getByRole('status')).toHaveText('Refreshing…')\n    await expect(page.locator('[data-size]')).toBeVisible()\n    await expect(page.locator('[data-size]')).toHaveText('390 × 720')\n    await expect(page.locator('#chrome').getByRole('status')).toHaveText('Refreshed')\n    await expect(page.getByRole('button', { name: 'Simulate refresh', exact: true })).toHaveCount(0)\n    await button.click()\n    await expect(page.locator('[data-refresh-button]')).toHaveAttribute('data-state', 'refreshing')\n    await expect(page.locator('[data-refresh-icon]')).toHaveCSS('animation-name', 'refresh-spin')\n    await expect.poll(() => loads).toBe(4)\n    await expect(page.locator('#chrome').getByRole('status')).toHaveText('Refreshed')\n    await expect(page.locator('[data-refresh-button]')).toBeVisible()\n    await page.keyboard.press('Tab')\n    await page.mouse.move(0, 0)\n    await expect(page.locator('[data-refresh-button]')).toHaveCSS('opacity', '0.35')\n  } finally {\n    await browser.close()\n    await new Promise((resolve) => server.close(resolve))\n  }\n})\n\ntest('should preview accessibility observations from real keyboard interactions', async () => {\n  const { server, url } = await startChromePreview({ port: 0 })\n  const browser = await chromium.launch({ headless: true })\n  try {\n    const { expect } = await import('@playwright/test')\n    const page = await browser.newPage({ viewport: { width: 1600, height: 1200 } })\n    await page.goto(`${url}/?accessibility&announcements&kind=fix`)\n    const app = page.frameLocator('iframe')\n    await page.getByRole('button', { name: 'Dark', exact: true }).click()\n    await expect(app.locator('html')).toHaveCSS('background-color', 'rgb(25, 25, 25)')\n    await page.getByRole('button', { name: 'Light', exact: true }).click()\n    await expect(app.locator('html')).toHaveCSS('background-color', 'rgb(250, 249, 246)')\n    const clickIntroduction = async () => {\n      const box = await app.getByRole('button', { name: 'Move Introduction down' }).boundingBox()\n      await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2)\n    }\n    await clickIntroduction()\n    await expect(page.locator('[data-announcement]')).toHaveText(\n      'Introduction moved to position 2 of 3.',\n    )\n    await page.keyboard.press('Shift+Tab')\n    await expect(page.locator('[data-keystroke]')).toHaveText('Shift + Tab')\n    await page.keyboard.press('Enter')\n    await expect(page.locator('[data-keystroke]')).toHaveText('Enter')\n    await expect(page.locator('[data-focus-highlight]')).toHaveCount(0)\n    await page.emulateMedia({ reducedMotion: 'reduce' })\n    await page.getByRole('button', { name: 'Refresh frame', exact: true }).click()\n    await clickIntroduction()\n    await expect(page.locator('[data-announcement]')).toHaveText(\n      'Introduction moved to position 2 of 3.',\n    )\n  } finally {\n    await browser.close()\n    await new Promise((resolve) => server.close(resolve))\n  }\n})\n\ntest('should keep the sidebar fixed while resizing and reveal current steps in long lists', async () => {\n  const { server, url } = await startChromePreview({ port: 0 })\n  const browser = await chromium.launch({ headless: true })\n  try {\n    const page = await browser.newPage({ viewport: { width: 1120, height: 1000 } })\n    await page.goto(`${url}/?manySteps&kind=bug`)\n    const panel = page.locator('.annotation-sidebar')\n    const list = page.locator('.sidebar-steps')\n    await expect(panel).toBeVisible()\n    await expect(panel.locator('.sidebar-step')).toHaveCount(12)\n    await expect(panel.locator('.sidebar-step [data-kind=Bug]')).toHaveCount(2)\n    const initial = await panel.boundingBox()\n    const header = await panel.locator('.sidebar-intro').boundingBox()\n    const marker = panel.locator('[aria-current=step] .sidebar-dot')\n    await expect(marker).toHaveCSS('background-color', 'rgb(13, 153, 255)')\n    const markerBounds = await marker.boundingBox()\n    const textBounds = await panel.locator('[aria-current=step] p').boundingBox()\n    const cardBounds = await panel.locator('[aria-current=step]').boundingBox()\n    const introBounds = await panel.locator('.sidebar-intro').boundingBox()\n    assert.ok(markerBounds.x > cardBounds.x + cardBounds.width * 0.8)\n    assert.ok(markerBounds.y >= cardBounds.y)\n    assert.ok(markerBounds.y + markerBounds.height < textBounds.y + textBounds.height)\n    assert.ok(Math.abs(introBounds.x - cardBounds.x) < 0.1)\n\n    const window = await page.locator('[data-window]').boundingBox()\n    assert.ok(Math.abs(initial.y - window.y) < 0.1)\n    assert.ok(Math.abs(initial.height - window.height) < 0.1)\n    assert.ok(Math.abs(initial.x + initial.width - window.x) < 0.1)\n    await expect(panel).toHaveCSS('border-top-right-radius', '0px')\n    await expect(page.locator('[data-window]')).toHaveCSS('border-top-left-radius', '0px')\n    await expect(page.locator('[data-window]')).toHaveCSS('border-top-width', '0px')\n    await expect(page.locator('.sidebar-shell')).toHaveCSS('background-color', 'rgb(221, 221, 221)')\n    await expect(panel.locator('.sidebar-step').first()).toHaveCSS(\n      'background-color',\n      'rgb(255, 255, 255)',\n    )\n    await expect(panel.locator('.sidebar-intro p')).toHaveCSS('color', 'rgb(37, 36, 34)')\n    await page.getByRole('button', { name: 'Dark', exact: true }).click()\n    await expect(page.locator('.sidebar-shell')).toHaveCSS('background-color', 'rgb(35, 35, 35)')\n    await expect(panel.locator('.sidebar-step').first()).toHaveCSS(\n      'background-color',\n      'rgb(25, 25, 25)',\n    )\n    await expect(panel.locator('.sidebar-intro p')).toHaveCSS('color', 'rgb(237, 237, 235)')\n    await expect(panel.locator('.sidebar-step [data-kind=Bug]').first()).toHaveCSS(\n      'background-color',\n      'rgb(96, 51, 42)',\n    )\n    assert.deepEqual(await panel.boundingBox(), initial)\n    await page.getByRole('button', { name: 'Light', exact: true }).click()\n\n    await page.getByRole('button', { name: 'Mobile', exact: true }).click()\n    assert.deepEqual(await panel.boundingBox(), initial)\n    const resizedWindow = await page.locator('[data-window]').boundingBox()\n    assert.ok(Math.abs(initial.x + initial.width - resizedWindow.x) < 0.1)\n    await page.getByRole('slider').focus()\n    await page.keyboard.press('End')\n    await expect.poll(() => list.evaluate((e) => e.scrollTop)).toBeGreaterThan(0)\n    await expect\n      .poll(async () => {\n        const current = await panel.locator('[aria-current=step]').boundingBox()\n        const bounds = await list.boundingBox()\n        return current.y >= bounds.y && current.y + current.height <= bounds.y + bounds.height + 1\n      })\n      .toBe(true)\n    assert.deepEqual(await panel.locator('.sidebar-intro').boundingBox(), header)\n    await page.emulateMedia({ reducedMotion: 'reduce' })\n    await page.getByRole('slider').focus()\n    await page.keyboard.press('Home')\n    await expect.poll(() => list.evaluate((e) => e.scrollTop)).toBeLessThan(2)\n    await panel.locator('.sidebar-step').nth(1).focus()\n    await page.keyboard.press('Enter')\n    await expect(panel.locator('[aria-current=step]')).toContainText('Update dates hide')\n    await expect(panel.locator('[aria-current=step] [data-kind=Bug]')).toHaveCSS(\n      'background-color',\n      'rgb(255, 226, 224)',\n    )\n  } finally {\n    await browser.close()\n    await new Promise((resolve) => server.close(resolve))\n  }\n})\n", "skills/record-pr-demo/scripts/record-demo.mjs": "#!/usr/bin/env node\n\nimport { mkdir, rm } from 'node:fs/promises'\nimport path from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport { getDefaultCanvas } from './WindowChrome/index.mjs'\nimport { startLosslessCapture } from './capture-demo.mjs'\n\nimport { createAnnotationInteraction } from './annotation-demo.mjs'\nimport { createKeyInteraction } from './keyboard-demo.mjs'\nimport { createPresentation } from './presentation-demo.mjs'\nimport { createScrollInteraction } from './scroll-demo.mjs'\n\nconst DEFAULT_BASE_URL = 'http://localhost:3000'\nconst DEFAULT_INTERACTION_PAUSE_MS = 300\nconst DEFAULT_LABEL = 'feature-demo'\nconst DEFAULT_MOUSE_MOVE_MS = 450\nconst DEFAULT_VIEWPORT = { height: 900, width: 1440 }\n\nexport function parseArgs(argv) {\n  const values = new Map()\n  const supportedOptions = new Set([\n    '--a11y',\n    '--base-url',\n    '--interaction-pause-ms',\n    '--label',\n    '--mouse-move-ms',\n    '--output',\n    '--scenario',\n    '--viewport',\n  ])\n\n  for (let index = 0; index < argv.length; index += 2) {\n    const option = argv[index]\n    const value = argv[index + 1]\n\n    if (!supportedOptions.has(option)) {\n      throw new Error(`Unknown option: ${option}`)\n    }\n    if (!value || value.startsWith('--')) {\n      throw new Error(`${option} requires a value`)\n    }\n\n    values.set(option, value)\n  }\n\n  const scenario = values.get('--scenario')\n  if (!scenario) {\n    throw new Error('--scenario is required')\n  }\n\n  const a11y = values.get('--a11y')\n  if (a11y !== undefined && !['on', 'off'].includes(a11y)) {\n    throw new Error('--a11y must be on or off')\n  }\n\n  const label = sanitizeLabel(values.get('--label') ?? DEFAULT_LABEL)\n\n  return {\n    ...(a11y === undefined ? {} : { a11y }),\n    baseURL: values.get('--base-url') ?? DEFAULT_BASE_URL,\n    interactionPauseMs: parseTiming({\n      name: '--interaction-pause-ms',\n      value: values.get('--interaction-pause-ms') ?? DEFAULT_INTERACTION_PAUSE_MS,\n    }),\n    label,\n    mouseMoveMs: parseTiming({\n      name: '--mouse-move-ms',\n      value: values.get('--mouse-move-ms') ?? DEFAULT_MOUSE_MOVE_MS,\n    }),\n    output: values.get('--output') ?? `/tmp/payload-pr-demo-${label}.mkv`,\n    scenario,\n    viewport: parseViewport(values.get('--viewport') ?? '1440x900'),\n  }\n}\n\nfunction parseTiming({ name, value }) {\n  const milliseconds = Number(value)\n\n  if (!Number.isFinite(milliseconds) || milliseconds < 0) {\n    throw new Error(`${name} must be a non-negative number`)\n  }\n\n  return milliseconds\n}\n\nexport function parseViewport(value) {\n  const match = /^(\\d+)x(\\d+)$/.exec(value)\n  if (!match) {\n    throw new Error('Viewport must use WIDTHxHEIGHT, for example 1440x900')\n  }\n\n  const width = Number(match[1])\n  const height = Number(match[2])\n\n  if (width < 640 || height < 480) {\n    throw new Error('Viewport must be at least 640x480')\n  }\n\n  return { height, width }\n}\n\nexport function sanitizeLabel(value) {\n  const label = value\n    .toLowerCase()\n    .replace(/[^a-z0-9]+/g, '-')\n    .replace(/^-+|-+$/g, '')\n\n  if (!label) {\n    throw new Error('Label must contain at least one letter or number')\n  }\n\n  return label\n}\n\nexport async function recordDemo({\n  a11y,\n  baseURL,\n  fixture,\n  interactionPauseMs = DEFAULT_INTERACTION_PAUSE_MS,\n  label,\n  mouseMoveMs = DEFAULT_MOUSE_MOVE_MS,\n  onOpeningReady,\n  output,\n  scenario,\n  viewport,\n}) {\n  return executeDemo({\n    a11y,\n    baseURL,\n    fixture,\n    interactionPauseMs,\n    label,\n    mouseMoveMs,\n    onOpeningReady,\n    output,\n    pauseScale: 1,\n    scenario,\n    trailingPauseMs: 900,\n    viewport,\n  })\n}\n\nexport async function validateDemo({ a11y, baseURL, fixture, label, scenario, viewport }) {\n  await executeDemo({\n    a11y,\n    baseURL,\n    fixture,\n    interactionPauseMs: 0,\n    label,\n    mouseMoveMs: 0,\n    pauseScale: 0,\n    scenario,\n    trailingPauseMs: 0,\n    viewport,\n  })\n}\n\nexport async function previewDemo({ a11y, baseURL, fixture, label, output, scenario, viewport }) {\n  return executeDemo({\n    a11y,\n    baseURL,\n    fixture,\n    interactionPauseMs: 0,\n    label,\n    mouseMoveMs: 0,\n    pauseScale: 0,\n    scenario,\n    screenshotOutput: output,\n    trailingPauseMs: 0,\n    viewport,\n  })\n}\n\nasync function executeDemo({\n  a11y,\n  baseURL,\n  fixture,\n  interactionPauseMs,\n  label,\n  mouseMoveMs,\n  onOpeningReady,\n  output,\n  pauseScale,\n  scenario,\n  screenshotOutput,\n  trailingPauseMs,\n  viewport,\n}) {\n  if (a11y !== undefined && !['on', 'off'].includes(a11y)) {\n    throw new Error('--a11y must be on or off')\n  }\n  const parsedBaseURL = new URL(baseURL)\n  const scenarioURL = pathToFileURL(path.resolve(scenario)).href\n  const scenarioModule = await import(scenarioURL)\n\n  if (typeof scenarioModule.default !== 'function') {\n    throw new Error(`Scenario must default-export a function: ${scenario}`)\n  }\n\n  const change = scenarioModule.presentation?.change\n\n  if (\n    !['Feature', 'Fix', 'Bug'].includes(change?.kind) ||\n    typeof change.title !== 'string' ||\n    !change.title.trim() ||\n    typeof change.description !== 'string' ||\n    !change.description.trim()\n  ) {\n    throw new Error(\n      'Every scenario must export presentation with a change kind, title, and description; recording chrome cannot be disabled',\n    )\n  }\n\n  const { chromium, expect } = await import('@playwright/test')\n  const browser = await chromium.launch({\n    headless: true,\n    handleSIGINT: false,\n    handleSIGTERM: false,\n  })\n  const presentationOptions = {\n    ...scenarioModule.presentation,\n    ...(a11y === undefined\n      ? {}\n      : { accessibility: a11y === 'on', showAnnouncements: a11y === 'on' }),\n  }\n  const recordedViewport =\n    presentationOptions.canvas ??\n    getDefaultCanvas({\n      viewport,\n    })\n  const context = await browser.newContext({\n    viewport: recordedViewport,\n    colorScheme: scenarioModule.presentation.theme ?? 'light',\n  })\n\n  await context.addInitScript(() => {\n    window.addEventListener('DOMContentLoaded', () => {\n      const cursor = document.createElement('div')\n      cursor.setAttribute('data-pr-demo-cursor', 'mac-arrow')\n      cursor.setAttribute('aria-hidden', 'true')\n      cursor.setAttribute('popover', 'manual')\n      cursor.innerHTML = `<svg aria-hidden=\"true\" height=\"23\" viewBox=\"0 0 28 36\" width=\"18\" xmlns=\"http://www.w3.org/2000/svg\">\n        <path d=\"M2 2.2V27l6.7-6.4 5.1 12.7 5-2-5.2-12.2H23L2 2.2Z\" fill=\"#111827\" stroke=\"#fff\" stroke-linejoin=\"round\" stroke-width=\"2.2\" />\n      </svg>`\n      Object.assign(cursor.style, {\n        background: 'transparent',\n        border: '0',\n        height: '23px',\n        insetBlockStart: '0',\n        insetInlineStart: '0',\n        margin: '0',\n        opacity: '0',\n        overflow: 'visible',\n        padding: '0',\n        pointerEvents: 'none',\n        position: 'fixed',\n        transform: 'translate(0, 0)',\n        transition: 'opacity 120ms ease',\n        width: '18px',\n        zIndex: '2147483647',\n      })\n      const cursorGraphic = cursor.querySelector('svg')\n      Object.assign(cursorGraphic.style, {\n        filter: 'drop-shadow(0 1px 2px rgb(0 0 0 / 65%))',\n        transformOrigin: '2px 2px',\n        transition: 'transform 100ms ease',\n      })\n      document.documentElement.append(cursor)\n      cursor.showPopover()\n\n      const promoteCursor = () => {\n        if (cursor.matches(':popover-open')) cursor.hidePopover()\n        cursor.showPopover()\n      }\n\n      document.addEventListener(\n        'toggle',\n        (event) => {\n          if (event.target !== cursor && event.newState === 'open') promoteCursor()\n        },\n        true,\n      )\n      new MutationObserver((records) => {\n        if (records.some(({ target }) => target instanceof HTMLDialogElement && target.open)) {\n          promoteCursor()\n        }\n      }).observe(document.documentElement, {\n        attributeFilter: ['open'],\n        attributes: true,\n        subtree: true,\n      })\n\n      let pointer = { x: 0, y: 0 }\n      let clickPulse\n      let clickPoint\n      let clickAnimation\n      const positionClickPulse = () => {\n        if (!clickPulse) return\n        clickPulse.style.left = `${clickPoint.x - pointer.x}px`\n        clickPulse.style.top = `${clickPoint.y - pointer.y}px`\n      }\n      const cursorActivityType = 'payload-pr-demo-cursor-active'\n      let latestCursorActivity = 0\n      window.addEventListener('message', (event) => {\n        if (event.data?.type !== cursorActivityType) return\n        const isParent = window.parent !== window && event.source === window.parent\n        const isChild = [...document.querySelectorAll('iframe')].some(\n          (frame) => frame.contentWindow === event.source,\n        )\n        if (\n          (isParent || isChild) &&\n          Number.isFinite(event.data.timestamp) &&\n          event.data.timestamp >= latestCursorActivity\n        ) {\n          latestCursorActivity = event.data.timestamp\n          cursor.style.transition = 'none'\n          cursor.style.opacity = '0'\n        }\n      })\n      const positionCursor = ({ clientX, clientY, timeStamp }) => {\n        latestCursorActivity = performance.timeOrigin + timeStamp\n        // Transfer cursor ownership between the recording chrome and its live app frame.\n        if (window.parent !== window) {\n          window.parent.postMessage(\n            { type: cursorActivityType, timestamp: latestCursorActivity },\n            '*',\n          )\n        } else {\n          for (const frame of document.querySelectorAll('iframe')) {\n            frame.contentWindow?.postMessage(\n              { type: cursorActivityType, timestamp: latestCursorActivity },\n              '*',\n            )\n          }\n        }\n        pointer = { x: clientX, y: clientY }\n        cursor.style.transition = 'opacity 120ms ease'\n        promoteCursor()\n        cursor.style.opacity = '1'\n        cursor.style.transform = `translate(${clientX}px, ${clientY}px)`\n        positionClickPulse()\n      }\n      document.addEventListener('mousemove', positionCursor, { passive: true })\n      document.addEventListener('mouseout', (event) => {\n        if (!event.relatedTarget || event.relatedTarget instanceof HTMLIFrameElement) {\n          cursor.style.opacity = '0'\n        }\n      })\n      document.addEventListener(\n        'mousedown',\n        (event) => {\n          positionCursor(event)\n          cursorGraphic.style.transform = 'scale(0.82)'\n          clickAnimation?.cancel()\n          clickPulse?.remove()\n          const pulse = document.createElement('span')\n          pulse.setAttribute('data-pr-demo-click', '')\n          pulse.setAttribute('aria-hidden', 'true')\n          Object.assign(pulse.style, {\n            position: 'absolute',\n            width: '28px',\n            height: '28px',\n            boxSizing: 'border-box',\n            border: '2px solid var(--color-bg-brand, #0d99ff)',\n            borderRadius: '50%',\n            background: 'color-mix(in srgb, var(--color-bg-brand, #0d99ff) 12%, transparent)',\n            pointerEvents: 'none',\n            transform: 'translate(-50%, -50%)',\n            zIndex: '-1',\n          })\n          clickPulse = pulse\n          clickPoint = { ...pointer }\n          cursor.prepend(pulse)\n          positionClickPulse()\n          const isReducedMotion = matchMedia('(prefers-reduced-motion: reduce)').matches\n          const animation = pulse.animate(\n            isReducedMotion\n              ? [{ opacity: 0.9 }, { opacity: 0.9, offset: 0.7 }, { opacity: 0 }]\n              : [\n                  {\n                    opacity: 0.9,\n                    transform: 'translate(-50%, -50%) scale(0.55)',\n                  },\n                  { opacity: 0.55, offset: 0.5 },\n                  { opacity: 0, transform: 'translate(-50%, -50%) scale(1.4)' },\n                ],\n            { duration: 420, easing: 'ease-out' },\n          )\n          clickAnimation = animation\n          animation.onfinish = () => {\n            pulse.remove()\n            if (clickPulse === pulse) {\n              clickPulse = undefined\n              clickAnimation = undefined\n            }\n          }\n        },\n        true,\n      )\n      document.addEventListener(\n        'mouseup',\n        () => {\n          cursorGraphic.style.transform = 'scale(1)'\n        },\n        true,\n      )\n    })\n  })\n\n  const recordedPage = await context.newPage()\n  let capture\n  let presentation\n  const resolvedOutput = output ? path.resolve(output) : undefined\n  const resolvedScreenshotOutput = screenshotOutput ? path.resolve(screenshotOutput) : undefined\n  let isOpeningReady = false\n  let scenarioError\n\n  const interrupted = () => {\n    void context.close().catch(() => {})\n  }\n  process.once('SIGINT', interrupted)\n  process.once('SIGTERM', interrupted)\n  try {\n    if (resolvedOutput) {\n      await mkdir(path.dirname(resolvedOutput), { recursive: true })\n      capture = await startLosslessCapture({\n        page: recordedPage,\n        output: resolvedOutput,\n        size: recordedViewport,\n      })\n    }\n    presentation = await createPresentation({\n      page: recordedPage,\n      options: presentationOptions,\n      viewport,\n      baseURL,\n      pauseScale,\n      startedAt: capture?.startedAt ?? performance.now(),\n    })\n    const page = presentation.appPage\n    const pointerInteractions = createPointerInteractions({\n      interactionPauseMs,\n      mouseMoveMs,\n      page,\n      pauseScale,\n    })\n    const pressKey = createKeyInteraction({ page, pauseScale })\n    const annotationInteractions = createAnnotationInteraction({\n      presentation,\n    })\n    await scenarioModule.default({\n      clearAnnotation: annotationInteractions.hideAnnotation,\n      resizeWindow: presentation.resizeWindow,\n      setAnnotation: (annotation) =>\n        annotation === null\n          ? annotationInteractions.hideAnnotation()\n          : annotationInteractions.showAnnotation(annotation),\n      baseURL: parsedBaseURL.toString().replace(/\\/$/, ''),\n      chrome: presentation.chrome,\n      click: pointerInteractions.click,\n      circleCursor: pointerInteractions.circleCursor,\n      pressKey,\n      typeText: async ({ locator, text, clear = false, delay = 50 }) => {\n        await pointerInteractions.click(locator)\n        if (clear) await pressKey({ key: 'ControlOrMeta+A' })\n        await page.keyboard.type(text, { delay })\n      },\n      expect,\n      fixture,\n      hideAnnotation: annotationInteractions.hideAnnotation,\n      label,\n      moveCursor: pointerInteractions.moveCursor,\n      page,\n      pause: (milliseconds = 700) => page.waitForTimeout(milliseconds * pauseScale),\n      ready: async () => {\n        if (isOpeningReady) throw new Error('Scenario may call ready() only once')\n        annotationInteractions.markReady()\n        isOpeningReady = true\n        await presentation.flush()\n        onOpeningReady?.((performance.now() - presentation.startedAt) / 1000)\n        await page.waitForTimeout(1200 * pauseScale)\n      },\n      scroll: createScrollInteraction({\n        moveCursor: pointerInteractions.moveCursor,\n        page: recordedPage,\n      }),\n      showAnnotation: annotationInteractions.showAnnotation,\n    })\n    if (output && !isOpeningReady) {\n      throw new Error('Recording scenario must call ready() after its opening state is visible')\n    }\n    if (trailingPauseMs > 0) {\n      await page.waitForTimeout(trailingPauseMs)\n    }\n    await presentation.flush()\n    if (resolvedScreenshotOutput) {\n      await mkdir(path.dirname(resolvedScreenshotOutput), { recursive: true })\n      await recordedPage.screenshot({ path: resolvedScreenshotOutput })\n    }\n  } catch (error) {\n    scenarioError = error\n  } finally {\n    try {\n      try {\n        await capture?.stop()\n      } catch (error) {\n        scenarioError ??= error\n      }\n      await presentation?.stop().catch((error) => {\n        scenarioError ??= error\n      })\n    } finally {\n      process.off('SIGINT', interrupted)\n      process.off('SIGTERM', interrupted)\n      try {\n        await browser.close()\n      } finally {\n        if (scenarioError && resolvedOutput) await rm(resolvedOutput, { force: true })\n      }\n    }\n  }\n\n  if (scenarioError) {\n    throw scenarioError\n  }\n\n  return resolvedOutput ?? resolvedScreenshotOutput\n}\n\nfunction createPointerInteractions({ interactionPauseMs, mouseMoveMs, page, pauseScale }) {\n  let pointerPosition = { x: 0, y: 0 }\n\n  const getTargetPoint = async ({ locator, position, pagePoint }) => {\n    await locator.waitFor({ state: 'visible' })\n    const box = await locator.boundingBox()\n    if (!box) throw new Error('Cannot move the demo cursor to an element without a bounding box')\n    const local = await locator.evaluate(\n      (element, { position, pagePoint, box }) => {\n        const rect = element.getBoundingClientRect()\n        // The document remains the wheel surface after its border box scrolls away.\n        const isDocumentScroller = element === document.scrollingElement\n        let left = isDocumentScroller ? 0 : Math.max(0, rect.left)\n        let top = isDocumentScroller ? 0 : Math.max(0, rect.top)\n        let right = isDocumentScroller ? innerWidth : Math.min(innerWidth, rect.right)\n        let bottom = isDocumentScroller ? innerHeight : Math.min(innerHeight, rect.bottom)\n        const rootStyle = getComputedStyle(document.documentElement)\n        for (\n          let parent = isDocumentScroller ? null : element.parentElement;\n          parent;\n          parent = parent.parentElement\n        ) {\n          // Root overflow, and body overflow propagated from a visible root, clip at the viewport.\n          const isViewportOverflow =\n            parent === document.documentElement ||\n            (parent === document.body &&\n              document.scrollingElement === document.documentElement &&\n              rootStyle.overflowX === 'visible' &&\n              rootStyle.overflowY === 'visible')\n          if (isViewportOverflow) continue\n          const style = getComputedStyle(parent)\n          const clip = parent.getBoundingClientRect()\n          if (/(auto|scroll|hidden|clip)/.test(style.overflowX)) {\n            left = Math.max(left, clip.left)\n            right = Math.min(right, clip.right)\n          }\n          if (/(auto|scroll|hidden|clip)/.test(style.overflowY)) {\n            top = Math.max(top, clip.top)\n            bottom = Math.min(bottom, clip.bottom)\n          }\n        }\n        const points = pagePoint\n          ? [\n              {\n                x: rect.left + ((pagePoint.x - box.x) * rect.width) / box.width,\n                y: rect.top + ((pagePoint.y - box.y) * rect.height) / box.height,\n              },\n            ]\n          : position\n            ? [\n                {\n                  x: rect.left + element.clientLeft + position.x,\n                  y: rect.top + element.clientTop + position.y,\n                },\n              ]\n            : [\n                { x: (left + right) / 2, y: (top + bottom) / 2 },\n                ...[0.1, 0.5, 0.9].flatMap((x) =>\n                  [0.1, 0.5, 0.9].map((y) => ({\n                    x: left + (right - left) * x,\n                    y: top + (bottom - top) * y,\n                  })),\n                ),\n              ]\n        const point = points.find(({ x, y }) => {\n          if (right <= left || bottom <= top || x < left || x >= right || y < top || y >= bottom)\n            return false\n          let hit = document.elementFromPoint(x, y)\n          while (hit?.shadowRoot) {\n            const nested = hit.shadowRoot.elementFromPoint(x, y)\n            if (!nested || nested === hit) break\n            hit = nested\n          }\n          for (let candidate = hit; candidate; candidate = candidate.getRootNode().host) {\n            if (element.contains(candidate)) return true\n          }\n          return false\n        })\n        if (!point) {\n          throw new Error(\n            'Demo target must be visible and unobstructed; reveal it with wheel scrolling before clicking',\n          )\n        }\n        const { x, y } = point\n        return {\n          x: x - rect.left,\n          y: y - rect.top,\n          width: rect.width,\n          height: rect.height,\n        }\n      },\n      { position, pagePoint, box },\n    )\n    return {\n      x: box.x + local.x * (box.width / local.width),\n      y: box.y + local.y * (box.height / local.height),\n    }\n  }\n\n  const moveCursor = async (\n    locator,\n    { duration = mouseMoveMs, pauseAfter = interactionPauseMs, position } = {},\n  ) => {\n    const targetPosition = await getTargetPoint({ locator, position })\n    await moveToPoint({ targetPosition, duration, pauseAfter })\n  }\n\n  const moveToPoint = async ({ targetPosition, duration, pauseAfter = 0 }) => {\n    if (!Number.isFinite(duration) || duration < 0) {\n      throw new Error('Cursor duration must be a finite non-negative number')\n    }\n    const startedAt = performance.now()\n    let progress = 0\n\n    do {\n      progress = duration === 0 ? 1 : Math.min(1, (performance.now() - startedAt) / duration)\n      const easedProgress =\n        progress < 0.5 ? 4 * progress * progress * progress : 1 - Math.pow(-2 * progress + 2, 3) / 2\n\n      await page.mouse.move(\n        pointerPosition.x + (targetPosition.x - pointerPosition.x) * easedProgress,\n        pointerPosition.y + (targetPosition.y - pointerPosition.y) * easedProgress,\n      )\n\n      if (progress < 1) {\n        const elapsed = performance.now() - startedAt\n        const nextFrame = Math.min(duration, (Math.floor(elapsed / 16) + 1) * 16)\n        const remaining = nextFrame - elapsed\n        if (remaining > 0) await page.waitForTimeout(remaining)\n      }\n    } while (progress < 1)\n\n    pointerPosition = targetPosition\n\n    if (pauseAfter > 0) {\n      await page.waitForTimeout(pauseAfter)\n    }\n  }\n\n  const circleCursor = async (\n    locator,\n    { duration = 1200, pauseAfter = interactionPauseMs, position, radius = 16 } = {},\n  ) => {\n    for (const [name, value] of Object.entries({ duration, pauseAfter })) {\n      if (!Number.isFinite(value) || value < 0) {\n        throw new Error(`Circle ${name} must be a finite non-negative number`)\n      }\n    }\n    if (radius !== undefined && (!Number.isFinite(radius) || radius <= 0)) {\n      throw new Error('Circle radius must be a finite positive number')\n    }\n\n    const target = await getTargetPoint({ locator, position })\n    const box = await locator.boundingBox()\n    const frame = await locator.evaluate((element) => {\n      const rect = element.getBoundingClientRect()\n      return {\n        x: rect.x,\n        y: rect.y,\n        width: rect.width,\n        height: rect.height,\n        viewportWidth: innerWidth,\n        viewportHeight: innerHeight,\n      }\n    })\n    const scaleX = box.width / frame.width\n    const scaleY = box.height / frame.height\n    const left = box.x - frame.x * scaleX\n    const top = box.y - frame.y * scaleY\n    const width = frame.viewportWidth * scaleX\n    const height = frame.viewportHeight * scaleY\n    // Leave room for the slight asymmetry, even beside viewport edges.\n    const radiusX = Math.min(radius * scaleX, (width - 4) / 2.08)\n    const radiusY = Math.min(radius * scaleY, (height - 4) / 2.08)\n    const center = {\n      x: Math.max(left + radiusX * 1.04 + 2, Math.min(left + width - radiusX * 1.04 - 2, target.x)),\n      y: Math.max(top + radiusY * 1.04 + 2, Math.min(top + height - radiusY * 1.04 - 2, target.y)),\n    }\n    const startAngle = Math.atan2(\n      (pointerPosition.y - center.y) / radiusY,\n      (pointerPosition.x - center.x) / radiusX,\n    )\n    const pointAt = (angle) => {\n      const looseness = 1 + 0.03 * Math.sin(3 * angle)\n      return {\n        x: center.x + Math.cos(angle) * radiusX * looseness,\n        y: center.y + Math.sin(angle) * radiusY * looseness,\n      }\n    }\n    await moveToPoint({ targetPosition: pointAt(startAngle), duration: mouseMoveMs })\n\n    const steps = Math.max(75, Math.ceil(duration / 16))\n    const stepDelay = (duration * pauseScale) / steps\n    const startedAt = performance.now()\n    for (let step = 1; step <= steps; step += 1) {\n      const progress = step / steps\n      const easedProgress = progress * progress * (3 - 2 * progress)\n      const point = pointAt(startAngle + Math.PI * 4 * easedProgress)\n      await page.mouse.move(point.x, point.y)\n      pointerPosition = point\n      const remaining = startedAt + step * stepDelay - performance.now()\n      if (step < steps && remaining > 0) await page.waitForTimeout(remaining)\n    }\n    if (pauseAfter * pauseScale > 0) await page.waitForTimeout(pauseAfter * pauseScale)\n  }\n\n  const click = async (\n    locator,\n    {\n      after = interactionPauseMs,\n      before = interactionPauseMs,\n      duration = mouseMoveMs,\n      position,\n    } = {},\n  ) => {\n    const target = await locator.elementHandle()\n    if (!target) throw new Error('Demo click target is unavailable')\n\n    try {\n      await target.waitForElementState('enabled', { timeout: 10_000 })\n      await target.waitForElementState('stable', { timeout: 10_000 })\n      await moveCursor(locator, { duration, pauseAfter: before, position })\n      await target.waitForElementState('enabled', { timeout: 10_000 })\n      await target.waitForElementState('stable', { timeout: 10_000 })\n      await getTargetPoint({ locator, pagePoint: pointerPosition })\n      // Use the same outer-page point for the visible cursor and the actual click.\n      await page.mouse.click(pointerPosition.x, pointerPosition.y)\n    } finally {\n      await target.dispose()\n    }\n\n    if (after > 0) {\n      await page.waitForTimeout(after)\n    }\n  }\n\n  return { circleCursor, click, moveCursor }\n}\n\nfunction printHelp() {\n  console.log(`Usage: record-demo.mjs --scenario PATH [options]\n\nOptions:\n  --a11y on|off        Override a11y feedback; omit to use the scenario setting\n  --base-url URL       Running Payload URL (default: ${DEFAULT_BASE_URL})\n  --interaction-pause-ms MS\n                       Dwell before and after clicks (default: ${DEFAULT_INTERACTION_PAUSE_MS})\n  --label TEXT         Safe output label (default: ${DEFAULT_LABEL})\n  --mouse-move-ms MS   Smooth cursor travel time (default: ${DEFAULT_MOUSE_MOVE_MS})\n  --output PATH        Lossless Matroska output (default: /tmp/payload-pr-demo-<label>.mkv)\n  --viewport WxH       Initial application viewport inside chrome (default: 1440x900)\n  --scenario PATH      Module exporting presentation metadata and a default async function\n  --help               Show this help`)\n}\n\nconst isMain =\n  process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href\n\nif (isMain) {\n  if (process.argv.includes('--help')) {\n    printHelp()\n  } else {\n    try {\n      const output = await recordDemo(parseArgs(process.argv.slice(2)))\n      console.log(output)\n    } catch (error) {\n      console.error(error instanceof Error ? error.message : error)\n      process.exitCode = 1\n    }\n  }\n}\n", "skills/record-pr-demo/scripts/record-demo.test.mjs": "import assert from 'node:assert/strict'\nimport { spawnSync } from 'node:child_process'\nimport { mkdtemp, rm, stat, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport path from 'node:path'\nimport { test } from 'node:test'\n\nimport * as recorder from './record-demo.mjs'\nimport { packageCandidate } from './prepare-demo.mjs'\n\nconst { parseArgs, parseViewport, sanitizeLabel } = recorder\nconst presentationExport = `export const presentation = {\n  change: { kind: 'Fix', title: 'Recorder test', description: 'Verify the recording behavior.' },\n};\\n`\n\ntest('parseArgs applies recording defaults and derives a safe output path', () => {\n  const options = parseArgs(['--scenario', '/tmp/demo-scenario.mjs'])\n\n  assert.deepEqual(options, {\n    baseURL: 'http://localhost:3000',\n    interactionPauseMs: 300,\n    label: 'feature-demo',\n    mouseMoveMs: 450,\n    output: '/tmp/payload-pr-demo-feature-demo.mkv',\n    scenario: '/tmp/demo-scenario.mjs',\n    viewport: { height: 900, width: 1440 },\n  })\n})\n\ntest('parseArgs accepts explicit recording options', () => {\n  const options = parseArgs([\n    '--scenario',\n    './scenario.mjs',\n    '--base-url',\n    'http://localhost:4000',\n    '--label',\n    'Relationship Drawer',\n    '--output',\n    '/tmp/relationship-demo.webm',\n    '--viewport',\n    '1280x720',\n    '--mouse-move-ms',\n    '900',\n    '--interaction-pause-ms',\n    '450',\n  ])\n\n  assert.deepEqual(options, {\n    baseURL: 'http://localhost:4000',\n    interactionPauseMs: 450,\n    label: 'relationship-drawer',\n    mouseMoveMs: 900,\n    output: '/tmp/relationship-demo.webm',\n    scenario: './scenario.mjs',\n    viewport: { height: 720, width: 1280 },\n  })\n})\n\ntest('parseArgs rejects a missing scenario', () => {\n  assert.throws(() => parseArgs([]), /--scenario is required/)\n})\n\ntest('parseArgs rejects unknown options', () => {\n  assert.throws(\n    () => parseArgs(['--scenario', './scenario.mjs', '--surprise']),\n    /Unknown option: --surprise/,\n  )\n})\n\ntest('parseArgs rejects invalid interaction timing values', () => {\n  assert.throws(\n    () => parseArgs(['--scenario', './scenario.mjs', '--mouse-move-ms', '-1']),\n    /--mouse-move-ms must be a non-negative number/,\n  )\n  assert.throws(\n    () => parseArgs(['--scenario', './scenario.mjs', '--interaction-pause-ms', 'quick']),\n    /--interaction-pause-ms must be a non-negative number/,\n  )\n})\n\ntest('parseViewport rejects malformed or impractical dimensions', () => {\n  assert.throws(() => parseViewport('wide'), /WIDTHxHEIGHT/)\n  assert.throws(() => parseViewport('300x200'), /at least 640x480/)\n})\n\ntest('sanitizeLabel prevents labels from becoming unsafe file paths', () => {\n  assert.equal(sanitizeLabel('../../Feature Demo!'), 'feature-demo')\n  assert.throws(() => sanitizeLabel('...'), /at least one letter or number/)\n})\n\ntest('recordDemo saves a completed browser recording before closing the browser', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-browser-test-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n  const output = path.join(directory, 'demo.webm')\n\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}export default async function scenario({ page, ready }) {\n        await page.goto('data:text/html,<main>Recorded demo</main>')\n        await ready()\n        await page.waitForTimeout(100)\n      }`,\n    )\n\n    assert.equal(typeof recorder.recordDemo, 'function')\n\n    await recorder.recordDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'browser-test',\n      output,\n      scenario,\n      viewport: { height: 480, width: 640 },\n    })\n\n    assert.ok((await stat(output)).size > 0)\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('should expose annotation helpers to recording scenarios', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-annotation-scenario-test-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}export default async function scenario({ expect, hideAnnotation, page, showAnnotation }) {\n        await page.goto('data:text/html,<main>Annotation demo</main>')\n        const stage = page.context().pages()[0]\n        await showAnnotation({title:'What changed',body:'The feature works.'})\n        await expect(stage.locator('.sidebar-step p')).toHaveText('The feature works.')\n        await showAnnotation({title:'Result',body:'The second note replaces the first.'})\n        await expect(stage.locator('.sidebar-steps')).toHaveCount(1)\n        await expect(stage.locator('.sidebar-step p')).toHaveText('The second note replaces the first.')\n        await expect(page.locator('[data-pr-demo-annotation]')).toHaveCount(0)\n        await hideAnnotation()\n        await expect(stage.locator('.sidebar-steps')).toBeHidden()\n      }`,\n    )\n\n    await recorder.validateDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'annotation-scenario-test',\n      scenario,\n      viewport: { height: 480, width: 640 },\n    })\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('should reject a recording without an opening ready marker', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-missing-ready-test-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}export default async function scenario({ page }) {\n        await page.goto('data:text/html,<main>Missing ready marker</main>')\n      }`,\n    )\n\n    await assert.rejects(\n      recorder.recordDemo({\n        baseURL: 'http://localhost:3000',\n        label: 'missing-ready-test',\n        output: path.join(directory, 'demo.webm'),\n        scenario,\n        viewport: { height: 480, width: 640 },\n      }),\n      /must call ready\\(\\)/,\n    )\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('recordDemo exposes a smoothly paced click helper', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-click-test-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n  const output = path.join(directory, 'demo.webm')\n\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}export default async function scenario({ click, moveCursor, page, ready }) {\n        await page.goto('data:text/html,<button type=\"button\">Click me</button>')\n        await moveCursor(page.locator('body'), { duration: 0, pauseAfter: 0 })\n        await ready()\n        await page.evaluate(() => {\n          window.demoPointerState = { clicks: 0, moves: 0 }\n          document.addEventListener('mousemove', () => { window.demoPointerState.moves += 1 })\n          document.querySelector('button').addEventListener('click', () => {\n            window.demoPointerState.clicks += 1\n          })\n        })\n\n        const startedAt = Date.now()\n        await click(page.getByRole('button', { name: 'Click me' }))\n        const elapsedMs = Date.now() - startedAt\n        const state = await page.evaluate(() => window.demoPointerState)\n\n        if (elapsedMs < 120) throw new Error('paced click completed too quickly')\n        if (state.moves < 4) throw new Error('cursor did not move smoothly')\n        if (state.clicks !== 1) throw new Error('button was not clicked exactly once')\n      }`,\n    )\n\n    await recorder.recordDemo({\n      baseURL: 'http://localhost:3000',\n      interactionPauseMs: 30,\n      label: 'click-test',\n      mouseMoveMs: 80,\n      output,\n      scenario,\n      viewport: { height: 480, width: 640 },\n    })\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('recordDemo renders a Mac-style arrow cursor', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-cursor-test-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n  const output = path.join(directory, 'demo.webm')\n\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}export default async function scenario({ page, ready }) {\n        await page.goto('data:text/html,<main>Cursor demo</main>')\n        await ready()\n        const cursor = page.locator('[data-pr-demo-cursor=\"mac-arrow\"]')\n        await cursor.waitFor()\n        const graphic = cursor.locator('svg')\n        if ((await graphic.count()) !== 1) {\n          throw new Error('Mac-style cursor SVG is missing')\n        }\n        if ((await graphic.getAttribute('width')) !== '18') {\n          throw new Error('Mac-style cursor width is not 18px')\n        }\n        if ((await graphic.getAttribute('height')) !== '23') {\n          throw new Error('Mac-style cursor height is not 23px')\n        }\n        const styles = await cursor.evaluate((element) => {\n          const style = getComputedStyle(element)\n          return {\n            backgroundColor: style.backgroundColor,\n            borderWidth: style.borderTopWidth,\n            padding: style.paddingTop,\n          }\n        })\n        if (styles.backgroundColor !== 'rgba(0, 0, 0, 0)' || styles.borderWidth !== '0px' || styles.padding !== '0px') {\n          throw new Error('cursor popover has a visible background, border, or padding')\n        }\n      }`,\n    )\n\n    await recorder.recordDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'cursor-test',\n      output,\n      scenario,\n      viewport: { height: 480, width: 640 },\n    })\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('should trim startup frames to the ready opening state', async ({ mock }) => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-opening-test-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n  const rawVideo = path.join(directory, 'demo.webm')\n  const convertedVideo = path.join(directory, 'demo.mp4')\n  let trimStart\n  let annotationBounds\n  const { chromium } = await import('@playwright/test')\n  const launch = chromium.launch.bind(chromium)\n  mock.method(chromium, 'launch', async (options) => {\n    const browser = await launch(options)\n    const newContext = browser.newContext.bind(browser)\n    mock.method(browser, 'newContext', async (options) => {\n      const context = await newContext(options)\n      const newPage = context.newPage.bind(context)\n      mock.method(context, 'newPage', async () => {\n        const page = await newPage()\n        // Capture starts before page creation resolves to the caller.\n        await new Promise((resolve) => setTimeout(resolve, 350))\n        return page\n      })\n      return context\n    })\n    return browser\n  })\n\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}export default async function scenario({ page, ready, showAnnotation, fixture }) {\n        await page.goto('data:text/html,<body style=\"margin:0;background:white\"><script>setTimeout(() => { document.body.style.background = \"rgb(0, 200, 0)\"; document.body.id = \"ready\" }, 1400)</script></body>')\n        await page.locator('#ready').waitFor()\n        await showAnnotation({title:'Opening annotation', body:'Visible from the first frame.'})\n        fixture.recordBounds(await page.context().pages()[0].locator('.sidebar-step').boundingBox())\n        await ready()\n      }`,\n    )\n\n    await recorder.recordDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'opening-test',\n      fixture: {\n        recordBounds: (bounds) => {\n          annotationBounds = bounds\n        },\n      },\n      onOpeningReady: (seconds) => {\n        trimStart = seconds\n      },\n      output: rawVideo,\n      scenario,\n      viewport: { height: 480, width: 640 },\n    })\n\n    assert.ok(trimStart > 1.4, `Expected delayed opening marker, got ${trimStart}`)\n    await packageCandidate({\n      contactSheet: path.join(directory, 'contact-sheet.png'),\n      label: 'opening-test',\n      manifest: path.join(directory, 'manifest.json'),\n      output: convertedVideo,\n      rawOutput: rawVideo,\n      scenario,\n      trimStart,\n    })\n\n    const firstFrame = spawnSync('ffmpeg', [\n      '-v',\n      'error',\n      '-i',\n      convertedVideo,\n      '-vf',\n      'crop=2:2:800:500',\n      '-frames:v',\n      '1',\n      '-f',\n      'rawvideo',\n      '-pix_fmt',\n      'rgb24',\n      '-',\n    ])\n    assert.equal(firstFrame.status, 0, firstFrame.stderr.toString())\n    assert.ok(\n      firstFrame.stdout[0] < 80 && firstFrame.stdout[1] > 150 && firstFrame.stdout[2] < 80,\n      'Opening frame does not show the ready green page',\n    )\n    const annotationFrame = spawnSync('ffmpeg', [\n      '-v',\n      'error',\n      '-i',\n      convertedVideo,\n      '-vf',\n      `crop=${Math.floor(annotationBounds.width)}:${Math.floor(annotationBounds.height)}:${Math.round(annotationBounds.x)}:${Math.round(annotationBounds.y)}`,\n      '-frames:v',\n      '1',\n      '-f',\n      'rawvideo',\n      '-pix_fmt',\n      'rgb24',\n      '-',\n    ])\n    assert.equal(annotationFrame.status, 0, annotationFrame.stderr.toString())\n    let darkPixels = 0\n    for (let index = 0; index < annotationFrame.stdout.length; index += 3) {\n      if (\n        annotationFrame.stdout[index] < 180 &&\n        annotationFrame.stdout[index + 1] < 180 &&\n        annotationFrame.stdout[index + 2] < 180\n      )\n        darkPixels++\n    }\n    assert.ok(darkPixels > 100, 'Opening frame has an empty annotation section')\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('should keep the recorded cursor visible above a popup and modal dialog', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-top-layer-test-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}export default async function scenario({ moveCursor, page }) {\n        await page.goto('data:text/html,<button style=\"position:fixed;left:125px;top:125px\">Behind popup</button>')\n        await moveCursor(page.getByRole('button', { name: 'Behind popup' }), { pauseAfter: 150 })\n        await page.evaluate(() => {\n          const popup = document.createElement('div')\n          popup.id = 'popup'\n          popup.setAttribute('popover', 'auto')\n          popup.innerHTML = '<button>Popup item</button>'\n          Object.assign(popup.style, { background: 'red', border: '0', height: '100px', left: '100px', margin: '0', padding: '20px', position: 'fixed', top: '100px', width: '200px' })\n          document.body.append(popup)\n          popup.showPopover()\n        })\n        await page.waitForTimeout(150)\n        await assertCursorVisible(page)\n        await moveCursor(page.getByRole('button', { name: 'Popup item' }), { pauseAfter: 150 })\n        await assertCursorVisible(page)\n\n        await page.evaluate(() => {\n          document.querySelector('#popup').hidePopover()\n          const dialog = document.createElement('dialog')\n          dialog.innerHTML = '<button>Dialog item</button>'\n          Object.assign(dialog.style, { background: 'blue', border: '0', height: '100px', left: '100px', margin: '0', padding: '20px', position: 'fixed', top: '100px', width: '200px' })\n          document.body.append(dialog)\n          dialog.showModal()\n        })\n        await page.waitForTimeout(150)\n        await assertCursorVisible(page)\n        await moveCursor(page.getByRole('button', { name: 'Dialog item' }), { pauseAfter: 150 })\n        await assertCursorVisible(page)\n      }\n\n      async function assertCursorVisible(page) {\n        const cursor = page.locator('[data-pr-demo-cursor]')\n        const box = await cursor.boundingBox()\n        const clip = { x: box.x, y: box.y, width: 18, height: 23 }\n        const withCursor = await page.screenshot({ clip })\n        await cursor.evaluate((element) => { element.style.opacity = '0' })\n        await page.waitForTimeout(150)\n        const withoutCursor = await page.screenshot({ clip })\n        await cursor.evaluate((element) => { element.style.opacity = '1' })\n        if (withCursor.equals(withoutCursor)) throw new Error('cursor is hidden behind the top layer')\n      }`,\n    )\n\n    await recorder.validateDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'top-layer-test',\n      scenario,\n      viewport: { height: 480, width: 640 },\n    })\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('validateDemo executes a scenario without retaining video and forwards fixture data', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-validation-test-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}export default async function scenario({ fixture, page, pause }) {\n        await page.goto('data:text/html,<main>Validation</main>')\n        if (fixture.documentTitle !== 'Prepared document') {\n          throw new Error('fixture data was not forwarded')\n        }\n        const startedAt = Date.now()\n        await pause(500)\n        if (Date.now() - startedAt > 100) {\n          throw new Error('presentation pause was not removed during validation')\n        }\n      }`,\n    )\n\n    assert.equal(typeof recorder.validateDemo, 'function')\n\n    const result = await recorder.validateDemo({\n      baseURL: 'http://localhost:3000',\n      fixture: { documentTitle: 'Prepared document' },\n      label: 'validation-test',\n      scenario,\n      viewport: { height: 480, width: 640 },\n    })\n\n    assert.equal(result, undefined)\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('should expose scrolling through the real recorder cursor helper during validation', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-scroll-test-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}export default async function scenario({ expect, page, scroll }) {\n        await page.goto('data:text/html,<div id=\"scroller\" style=\"width:200px;height:24px;overflow:auto\"><div style=\"width:264px;height:24px\">Tabs</div></div>')\n        const result = await scroll(page.locator('#scroller'), { axis: 'x', duration: 100, settle: 0 })\n        expect(result).toEqual({ position: 64, target: 64 })\n        await expect(page.locator('[data-pr-demo-scroll-anchor]')).toHaveCount(0)\n        await expect(page.locator('[data-pr-demo-cursor]')).toHaveCSS('opacity', '1')\n      }`,\n    )\n\n    await recorder.validateDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'scroll-test',\n      scenario,\n      viewport: { height: 480, width: 640 },\n    })\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('should smoothly scroll an open popup menu list', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-popup-scroll-test-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}export default async function scenario({ expect, page, scroll }) {\n        await page.goto('data:text/html,<main>Popup scroll</main>')\n        await page.evaluate(() => {\n          const popup = document.createElement('div')\n          popup.setAttribute('popover', 'manual')\n          popup.innerHTML = '<div id=\"menu-list\" style=\"height:100px;width:160px;overflow:auto\"><div style=\"height:300px\">Menu items</div></div>'\n          Object.assign(popup.style, { left: '100px', margin: '0', padding: '20px', position: 'fixed', top: '80px' })\n          document.body.append(popup)\n          popup.showPopover()\n        })\n        const result = await scroll(page.locator('#menu-list'), { duration: 100, settle: 0 })\n        expect(result).toEqual({ position: 200, target: 200 })\n        await expect(page.locator('[popover]:popover-open')).toHaveCount(2)\n        await expect(page.locator('[data-pr-demo-scroll-anchor]')).toHaveCount(0)\n      }`,\n    )\n\n    await recorder.validateDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'popup-scroll-test',\n      scenario,\n      viewport: { height: 480, width: 640 },\n    })\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('should reject missing or invalid presentation before running a scenario in every mode', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'required-demo-chrome-'))\n  try {\n    for (const [name, header] of [\n      ['missing', ''],\n      ['disabled', 'export const presentation = false;'],\n      ['empty-change', 'export const presentation = { change: {} };'],\n      [\n        'invalid-kind',\n        \"export const presentation = { change: { kind: 'Other', title: 'Demo', description: 'Details' } };\",\n      ],\n      [\n        'blank-title',\n        \"export const presentation = { change: { kind: 'Fix', title: ' ', description: 'Details' } };\",\n      ],\n      [\n        'missing-description',\n        \"export const presentation = { change: { kind: 'Fix', title: 'Demo' } };\",\n      ],\n      [\n        'non-string-description',\n        \"export const presentation = { change: { kind: 'Fix', title: 'Demo', description: 42 } };\",\n      ],\n    ]) {\n      const scenario = path.join(directory, `${name}.mjs`)\n      await writeFile(\n        scenario,\n        `${header}\\nexport default async function () { throw new Error('Scenario ran without chrome') }`,\n      )\n      for (const method of ['recordDemo', 'previewDemo', 'validateDemo']) {\n        await assert.rejects(\n          () =>\n            recorder[method]({\n              baseURL: 'http://localhost:3000',\n              label: 'required-chrome',\n              scenario,\n              viewport: { width: 640, height: 480 },\n              output:\n                method === 'validateDemo'\n                  ? undefined\n                  : path.join(\n                      directory,\n                      method === 'previewDemo' ? 'preview.png' : 'recording.webm',\n                    ),\n            }),\n          /must export presentation.*change/,\n        )\n      }\n    }\n  } finally {\n    await rm(directory, { recursive: true, force: true })\n  }\n})\n\ntest('should show a temporary click ring at the click point above popups', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-click-indicator-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}\n      export default async function({page,click,moveCursor,expect}) {\n        await page.goto('data:text/html,'+encodeURIComponent('<style>:root{--color-bg-brand:rgb(21,125,230)}</style><div id=\"popup\" popover=\"manual\" style=\"position:fixed;left:80px;top:80px;margin:0;padding:20px\"><button>Click target</button><button style=\"margin-left:180px\">Next target</button></div><script>document.querySelector(\"#popup\").showPopover()</script>'))\n        const first=page.getByRole('button',{name:'Click target',exact:true})\n        const next=page.getByRole('button',{name:'Next target',exact:true})\n        await click(first,{duration:0,before:0,after:0})\n        const ring=page.locator('[data-pr-demo-click]')\n        await expect(ring).toBeVisible()\n        await expect(ring).toHaveAttribute('aria-hidden','true')\n        await expect(ring).toHaveCSS('pointer-events','none')\n        await expect(ring).toHaveCSS('border-top-color','rgb(21, 125, 230)')\n        const isInTopLayer=await ring.evaluate(el=>el.parentElement.matches('[data-pr-demo-cursor]:popover-open'))\n        if(!isInTopLayer)throw new Error('Click indicator is below the popup layer')\n        const initial=await ring.boundingBox()\n        const original=await ring.elementHandle()\n        await moveCursor(next,{duration:0,pauseAfter:0})\n        const moved=await ring.boundingBox()\n        if(Math.abs(initial.x+initial.width/2-moved.x-moved.width/2)>1 || Math.abs(initial.y+initial.height/2-moved.y-moved.height/2)>1)throw new Error('Click ring followed the cursor instead of staying at the click point')\n        await click(next,{duration:0,before:0,after:0})\n        await expect(ring).toHaveCount(1)\n        if(await original.evaluate(el=>el.isConnected))throw new Error('Prior click indicator was not cleaned up')\n        await original.dispose()\n        await page.waitForTimeout(500)\n        await expect(ring).toHaveCount(0)\n        await page.emulateMedia({reducedMotion:'reduce'})\n        await click(first,{duration:0,before:0,after:0})\n        const frames=await ring.evaluate(el=>el.getAnimations()[0].effect.getKeyframes())\n        if(frames.some(frame=>frame.transform))throw new Error('Reduced-motion click indicator should not expand')\n        await page.waitForTimeout(500)\n        await expect(ring).toHaveCount(0)\n      }\n    `,\n    )\n    await recorder.validateDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'click-indicator',\n      scenario,\n      viewport: { width: 640, height: 480 },\n    })\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('should click scaled targets, type with keys, and require wheel input to reveal targets', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-gestures-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}\n      export default async function({page,click,typeText,pressKey,expect,scroll}) {\n        await page.goto('data:text/html,'+encodeURIComponent('<style>body{margin:0}button,input{display:block;margin:30px}#scroller{height:180px;overflow:auto}#spacer{height:800px}</style><input aria-label=\"Title\" value=\"Old title\" onkeydown=\"this.dataset.key=event.key\" oninput=\"this.dataset.trusted=event.isTrusted\"><button onclick=\"this.textContent=String.fromCharCode(67,108,105,99,107,101,100)\">Click target</button><div id=\"scroller\"><div id=\"spacer\"></div><button>Offscreen</button></div>'))\n        await click(page.getByRole('button',{name:'Click target',exact:true}))\n        await expect(page.getByRole('button',{name:'Clicked',exact:true})).toBeVisible()\n        await typeText({locator:page.getByRole('textbox',{name:'Title'}),text:'New title',clear:true,delay:1})\n        await expect(page.getByRole('textbox',{name:'Title'})).toHaveValue('New title')\n        await expect(page.getByRole('textbox',{name:'Title'})).toHaveAttribute('data-key','e')\n        await expect(page.getByRole('textbox',{name:'Title'})).toHaveAttribute('data-trusted','true')\n        await pressKey({key:'Home',settleMs:0})\n        await expect(page.getByRole('textbox',{name:'Title'})).toHaveAttribute('data-key','Home')\n        let rejected=false\n        try { await click(page.getByRole('button',{name:'Offscreen',exact:true})) } catch(error) { rejected=/wheel|visible/.test(error.message) }\n        if(!rejected)throw new Error('Offscreen click silently scrolled')\n        await expect(page.locator('#scroller')).toHaveJSProperty('scrollTop',0)\n        await scroll(page.locator('#scroller'),{duration:100,settle:0})\n        await click(page.getByRole('button',{name:'Offscreen',exact:true}))\n      }\n    `,\n    )\n    await recorder.validateDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'gestures',\n      scenario,\n      viewport: { width: 1800, height: 1100 },\n    })\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\nfor (const mode of ['disabled', 'moving', 'covered', 'partial', 'explicit']) {\n  test(`should handle ${mode} click targets safely`, async () => {\n    const directory = await mkdtemp(path.join(tmpdir(), 'demo-click-safety-'))\n    const scenario = path.join(directory, 'scenario.mjs')\n    try {\n      await writeFile(\n        scenario,\n        `${presentationExport}\n        export default async function({page,click,expect}) {\n          const mode = ${JSON.stringify(mode)}\n          await page.goto('data:text/html,' + encodeURIComponent(\n            '<style>body{margin:0}button{position:absolute;left:60px;top:60px;width:240px;height:80px}#cover{position:absolute;left:140px;top:60px;width:80px;height:80px}</style>' +\n            '<button '+(mode==='disabled'?'disabled':'')+' onclick=\"this.dataset.clicked=String(event.isTrusted)\">Target</button>' +\n            (mode==='partial'||mode==='explicit'?'<div id=\"cover\"></div>':'')\n          ))\n          const target=page.getByRole('button',{name:'Target'})\n          if(mode==='disabled') await target.evaluate(el=>setTimeout(()=>{el.disabled=false},200))\n          if(mode==='moving'||mode==='covered') await target.evaluate((el,mode)=>{\n            el.addEventListener('pointerenter',()=>setTimeout(()=>{\n              if(mode==='moving') el.style.left='400px'\n              else { const cover=document.createElement('div');cover.style='position:absolute;inset:0;background:white';document.body.append(cover) }\n            },30),{once:true})\n          },mode)\n          if(mode==='moving'||mode==='covered'||mode==='explicit') {\n            await pressKey({key:'Home',settleMs:0})\n        await expect(page.getByRole('textbox',{name:'Title'})).toHaveAttribute('data-key','Home')\n        let rejected=false\n            try { await click(target,{duration:0,before:250,after:0,...(mode==='explicit'?{position:{x:120,y:40}}:{})}) }\n            catch(error) { rejected=/visible|unobstructed/.test(error.message) }\n            if(!rejected)throw new Error('Unsafe click returned success')\n            await expect(target).not.toHaveAttribute('data-clicked','true')\n          } else {\n            await click(target,{duration:0,before:0,after:0})\n            await expect(target).toHaveAttribute('data-clicked','true')\n          }\n        }\n      `,\n      )\n      await recorder.validateDemo({\n        baseURL: 'http://localhost:3000',\n        label: 'click-safety',\n        scenario,\n        viewport: { width: 1800, height: 1100 },\n      })\n    } finally {\n      await rm(directory, { force: true, recursive: true })\n    }\n  })\n}\n\ntest('should keep wheel scrolling the document after its root border box leaves the viewport', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-document-wheel-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}\n      export default async function({page,scroll,expect}) {\n        await page.goto('data:text/html,'+encodeURIComponent('<!doctype html><style>html{height:100%}body{margin:0;min-height:3000px}</style><button>Page content</button>'))\n        const document=page.locator('html')\n        await scroll(document,{to:800,duration:120,settle:0})\n        await scroll(document,{to:120,duration:120,settle:0})\n        await expect.poll(()=>page.evaluate(()=>window.scrollY)).toBe(120)\n      }\n    `,\n    )\n    await recorder.validateDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'document-wheel',\n      scenario,\n      viewport: { width: 1280, height: 720 },\n    })\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('should accept a11y overrides and reject invalid modes', () => {\n  for (const a11y of ['on', 'off']) {\n    assert.equal(parseArgs(['--scenario', './demo.mjs', '--a11y', a11y]).a11y, a11y)\n  }\n  assert.throws(\n    () => parseArgs(['--scenario', './demo.mjs', '--a11y', 'maybe']),\n    /--a11y must be on or off/,\n  )\n})\n\ntest('should toggle a11y feedback for the same scenario without changing its exported defaults', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-a11y-override-'))\n  try {\n    for (const isEnabled of [false, true]) {\n      const scenario = path.join(directory, `scenario-${isEnabled}.mjs`)\n      await writeFile(\n        scenario,\n        `${presentationExport.replace('change:', `accessibility: ${isEnabled}, showAnnouncements: ${isEnabled}, change:`)}\n        Object.freeze(presentation)\n        export default async function ({ page, ready, fixture, expect }) {\n          await page.route('**/fixture', route => route.fulfill({contentType:'text/html',body:'<button>First control</button><div role=\"status\">Ready</div>'}))\n          await page.goto('http://localhost:3000/fixture')\n          const feedback = await page.evaluate(() => {\n            const chrome = window.parent.document.querySelector('#demo-stage').shadowRoot\n            return {\n              panel: Boolean(chrome.querySelector('[data-accessibility]')),\n              captions: Boolean(chrome.querySelector('[data-announcement]')),\n              observer: typeof window.__stopDemoAccessibility === 'function',\n            }\n          })\n          expect(feedback).toEqual({panel: fixture.isEnabled, captions: fixture.isEnabled, observer: fixture.isEnabled})\n          expect(presentation.accessibility).toBe(${isEnabled})\n          await ready()\n        }`,\n      )\n      for (const a11y of [undefined, 'on', 'off']) {\n        await recorder.validateDemo({\n          a11y,\n          baseURL: 'http://localhost:3000',\n          fixture: { isEnabled: a11y === undefined ? isEnabled : a11y === 'on' },\n          label: 'a11y-override',\n          scenario,\n          viewport: { width: 1280, height: 720 },\n        })\n      }\n    }\n  } finally {\n    await rm(directory, { recursive: true, force: true })\n  }\n})\n\ntest('should capture native canvas dimensions without changing application layout or clicks', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-density-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n  const output = path.join(directory, 'native.webm')\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport.replace('change:', 'canvas: {width:800,height:600}, change:')}\n      export default async function({page, click, ready, expect}) {\n        await page.goto('data:text/html,' + encodeURIComponent('<button style=\"margin:30px\" data-result=\"Clicked\" onclick=\"this.textContent=this.dataset.result\">Activate</button>'))\n        expect(page.viewportSize()).toEqual({width:640,height:480})\n        const stage = page.context().pages()[0]\n        expect(stage.viewportSize()).toEqual({width:800,height:600})\n        const scale = await stage.locator('[data-canvas]').evaluate(el => getComputedStyle(el).transform)\n        expect(scale).toBe('matrix(1, 0, 0, 1, 0, 0)')\n        await ready()\n        await click(page.getByRole('button', {name:'Activate'}))\n        await expect(page.getByRole('button', {name:'Clicked'})).toBeVisible()\n      }`,\n    )\n    await recorder.recordDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'density',\n      output,\n      scenario,\n      viewport: { width: 640, height: 480 },\n      interactionPauseMs: 0,\n      mouseMoveMs: 0,\n    })\n    const probe = spawnSync(\n      'ffprobe',\n      [\n        '-v',\n        'error',\n        '-select_streams',\n        'v:0',\n        '-show_entries',\n        'stream=width,height',\n        '-of',\n        'json',\n        output,\n      ],\n      { encoding: 'utf8' },\n    )\n    assert.equal(probe.status, 0, probe.stderr)\n    const stream = JSON.parse(probe.stdout).streams[0]\n    assert.equal(stream.width, 800)\n    assert.equal(stream.height, 600)\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('should click visible controls after scrolling when body overflow propagates to the viewport', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-body-overflow-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}\n      export default async function ({page, click, scroll, ready, expect}) {\n        await page.goto('data:text/html,' + encodeURIComponent('<!doctype html><style>html,body{margin:0;height:100%}body{overflow-x:hidden}</style><div style=\"height:900px\"></div><button data-result=\"Clicked\" onclick=\"this.textContent=this.dataset.result\">Activate</button><div style=\"height:40px\"></div>'))\n        await ready()\n        await scroll(page.locator('html'), {to:'end', duration:100, settle:0})\n        await click(page.getByRole('button',{name:'Activate'}))\n        await expect(page.getByRole('button',{name:'Clicked'})).toBeVisible()\n      }\n    `,\n    )\n    await recorder.validateDemo({\n      baseURL: 'http://localhost:3000',\n      label: 'body-overflow',\n      scenario,\n      viewport: { width: 1280, height: 720 },\n    })\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('should reject notes introduced after an unannotated ready marker through either API', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-opening-note-'))\n  try {\n    for (const method of ['showAnnotation', 'setAnnotation']) {\n      const scenario = path.join(directory, `${method}.mjs`)\n      await writeFile(\n        scenario,\n        `${presentationExport}\n        export default async function ({page, ready, ${method}}) {\n          await page.goto('data:text/html,<main>Loaded app</main>')\n          await ready()\n          await ${method}({title:'Too late',body:'No annotation was visible at ready.'})\n        }\n      `,\n      )\n      await assert.rejects(\n        () =>\n          recorder.validateDemo({\n            baseURL: 'http://localhost:3000',\n            label: 'opening-note',\n            scenario,\n            viewport: { width: 1280, height: 720 },\n          }),\n        /annotation.*before.*ready\\(\\)/i,\n      )\n    }\n  } finally {\n    await rm(directory, { force: true, recursive: true })\n  }\n})\n\ntest('should show only one cursor when moving between chrome and the app frame', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-cursor-ownership-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}\n      export default async function ({page, chrome, click, ready, expect}) {\n        await page.context().route('http://cursor.test/app', route => route.fulfill({\n          contentType: 'text/html',\n          body: '<button onclick=\"history.pushState({}, String(), location.pathname + String.fromCharCode(35))\">Spanish</button><button>Open drawer</button>',\n        }))\n        await page.goto('http://cursor.test/app')\n        await ready()\n        const stage = page.context().pages()[0]\n        const stageCursor = stage.locator('[data-pr-demo-cursor]')\n        const appCursor = page.locator('[data-pr-demo-cursor]')\n        await click(page.getByRole('button', {name:'Spanish', exact:true}))\n        await expect(stageCursor).toHaveCSS('opacity', '0')\n        await expect(appCursor).toHaveCSS('opacity', '1')\n        await click(chrome.back)\n        await page.evaluate(() => window.parent.postMessage({ type: 'payload-pr-demo-cursor-active', timestamp: 0 }, '*'))\n        await stage.evaluate(() => new Promise(resolve => setTimeout(resolve, 50)))\n        await expect(stageCursor).toHaveCSS('opacity', '1')\n        await expect(appCursor).toHaveCSS('opacity', '0')\n        await click(page.getByRole('button', {name:'Open drawer', exact:true}))\n        await expect(stageCursor).toHaveCSS('opacity', '0')\n        await expect(appCursor).toHaveCSS('opacity', '1')\n        await stage.evaluate(() => document.querySelector('iframe').contentWindow.postMessage({ type: 'payload-pr-demo-cursor-active', timestamp: 0 }, '*'))\n        await stage.evaluate(() => new Promise(resolve => setTimeout(resolve, 50)))\n        await expect(appCursor).toHaveCSS('opacity', '1')\n      }\n    `,\n    )\n    await recorder.validateDemo({\n      baseURL: 'http://cursor.test',\n      label: 'cursor-ownership',\n      scenario,\n      viewport: { width: 1280, height: 720 },\n    })\n  } finally {\n    await rm(directory, { recursive: true, force: true })\n  }\n})\n\ntest('should click both shadow hosts and controls inside nested shadow roots', async () => {\n  const directory = await mkdtemp(path.join(tmpdir(), 'record-pr-demo-shadow-click-'))\n  const scenario = path.join(directory, 'scenario.mjs')\n  try {\n    await writeFile(\n      scenario,\n      `${presentationExport}\n      export default async function ({page, click, ready, expect}) {\n        await page.context().route('http://shadow.test/app', route => route.fulfill({\n          contentType: 'text/html',\n          body: '<div id=\"target\"><template shadowrootmode=\"open\"><div><template shadowrootmode=\"open\"><button>Nested action</button></template></div></template></div><output>0</output><script>let count=0;document.querySelector(\"#target\").addEventListener(\"click\",()=>document.querySelector(\"output\").textContent=String(++count))</script>',\n        }))\n        await page.goto('http://shadow.test/app')\n        await ready()\n        await click(page.locator('#target'))\n        await expect(page.locator('output')).toHaveText('1')\n        await click(page.getByRole('button', {name:'Nested action'}))\n        await expect(page.locator('output')).toHaveText('2')\n      }\n    `,\n    )\n    await recorder.validateDemo({\n      baseURL: 'http://shadow.test',\n      label: 'shadow-click',\n      scenario,\n      viewport: { width: 1280, height: 720 },\n    })\n  } finally {\n    await rm(directory, { recursive: true, force: true })\n  }\n})\n", "skills/record-pr-demo/scripts/recording-job.mjs": "#!/usr/bin/env node\nimport { spawn, spawnSync } from 'node:child_process'\nimport { randomUUID } from 'node:crypto'\nimport { mkdir, open, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport path from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { parseArgs } from './prepare-demo.mjs'\n\nconst jobsRoot = path.join(tmpdir(), `payload-demo-jobs-${process.getuid?.() ?? 'local'}`)\nconst script = fileURLToPath(import.meta.url)\nconst activeStates = new Set(['starting', 'running', 'stopping'])\n\nfunction jobPath({ id }) {\n  if (!/^[0-9a-f-]{36}$/.test(id)) throw new Error('Invalid recording job ID')\n  return path.join(jobsRoot, id)\n}\nasync function readJSON({ file }) {\n  return JSON.parse(await readFile(file, 'utf8'))\n}\nasync function saveJSON({ file, value }) {\n  const temporary = `${file}.${randomUUID()}.tmp`\n  await writeFile(temporary, JSON.stringify(value), { mode: 0o600 })\n  await rename(temporary, file)\n}\n\n/** Starts a supervised candidate; artifacts are confined to its private directory. */\nexport async function startRecordingJob({ args, leaseMs = 60000, maxDurationMs = 600000 }) {\n  if (process.platform === 'win32')\n    throw new Error('Recording jobs currently require macOS or Linux')\n  if (![leaseMs, maxDurationMs].every((value) => Number.isFinite(value) && value > 0))\n    throw new Error('Job durations must be positive')\n  const options = parseArgs(['candidate', ...args])\n  if (\n    args.some((arg) => ['--output', '--raw-output', '--manifest', '--contact-sheet'].includes(arg))\n  )\n    throw new Error('Recording jobs manage their own artifact paths')\n  const id = randomUUID()\n  const directory = jobPath({ id })\n  const artifacts = path.join(directory, 'artifacts')\n  await mkdir(artifacts, { recursive: true, mode: 0o700 })\n  const output = path.join(artifacts, `${options.label}.mp4`)\n  const state = {\n    id,\n    status: 'starting',\n    createdAt: Date.now(),\n    output,\n    log: path.join(directory, 'recording.log'),\n  }\n  const workerArgs = [...args]\n  const scenarioIndex = workerArgs.indexOf('--scenario')\n  workerArgs[scenarioIndex + 1] = path.resolve(options.scenario)\n  await saveJSON({\n    file: path.join(directory, 'config.json'),\n    value: { args: workerArgs, leaseMs, maxDurationMs },\n  })\n  await saveJSON({\n    file: path.join(directory, 'lease.json'),\n    value: { expiresAt: Date.now() + leaseMs },\n  })\n  await saveJSON({ file: path.join(directory, 'state.json'), value: state })\n  const worker = spawn(process.execPath, [script, 'worker', id], {\n    cwd: process.cwd(),\n    detached: true,\n    stdio: 'ignore',\n  })\n  await new Promise((resolve, reject) => {\n    worker.once('spawn', resolve)\n    worker.once('error', reject)\n  })\n  worker.unref()\n  return state\n}\n\n/** Reads status without extending the lease. Renewal must come from the active caller. */\nexport async function recordingJobStatus({ id } = {}) {\n  if (!id) {\n    const names = await readdir(jobsRoot).catch((error) => {\n      if (error.code === 'ENOENT') return []\n      throw error\n    })\n    const ids = names.filter((name) => /^[0-9a-f-]{36}$/.test(name))\n    const results = await Promise.allSettled(ids.map((id) => recordingJobStatus({ id })))\n    return {\n      jobs: results\n        .filter((result) => result.status === 'fulfilled')\n        .map((result) => result.value)\n        .filter((job) => activeStates.has(job.status)),\n      unreadableJobs: results.flatMap((result, index) =>\n        result.status === 'rejected' ? [{ id: ids[index], error: result.reason.message }] : [],\n      ),\n    }\n  }\n  const directory = jobPath({ id })\n  const state = await readJSON({ file: path.join(directory, 'state.json') })\n  const lease = await readJSON({ file: path.join(directory, 'lease.json') })\n  return { ...state, leaseExpiresAt: lease.expiresAt }\n}\nexport async function renewRecordingJob({ id }) {\n  const directory = jobPath({ id })\n  const state = await recordingJobStatus({ id })\n  if (!activeStates.has(state.status)) throw new Error(`Cannot renew ${state.status} recording`)\n  if (Date.now() >= state.leaseExpiresAt) throw new Error('Recording lease has expired')\n  const { leaseMs } = await readJSON({ file: path.join(directory, 'config.json') })\n  await saveJSON({\n    file: path.join(directory, 'lease.json'),\n    value: { expiresAt: Date.now() + leaseMs },\n  })\n  return recordingJobStatus({ id })\n}\nexport async function stopRecordingJob({ id }) {\n  const state = await recordingJobStatus({ id })\n  if (activeStates.has(state.status))\n    await writeFile(path.join(jobPath({ id }), 'stop'), '', { mode: 0o600 })\n  return { ...state, stopRequested: activeStates.has(state.status) }\n}\n\n// Chromium may create a separate process group. Remember descendants before\n// interrupting the recorder, then match creation times before killing survivors.\nfunction processTree({ pid }) {\n  const result = spawnSync('ps', ['-axo', 'pid=,ppid=,lstart='], { encoding: 'utf8' })\n  if (result.status !== 0) return new Map()\n  const processes = result.stdout\n    .trim()\n    .split('\\n')\n    .map((line) => {\n      const [, id, parent, started] = line.match(/^\\s*(\\d+)\\s+(\\d+)\\s+(.+)$/) ?? []\n      return { pid: Number(id), parent: Number(parent), started }\n    })\n  const owned = new Map([[pid, processes.find((item) => item.pid === pid)?.started]])\n  for (let changed = true; changed;) {\n    changed = false\n    for (const item of processes)\n      if (owned.has(item.parent) && !owned.has(item.pid)) {\n        owned.set(item.pid, item.started)\n        changed = true\n      }\n  }\n  return owned\n}\nfunction killSurvivors({ owned }) {\n  // Query each known PID's start time without following unrelated reparented processes.\n  const result = spawnSync('ps', ['-axo', 'pid=,lstart='], { encoding: 'utf8' })\n  if (result.status !== 0) return\n  for (const line of result.stdout.trim().split('\\n')) {\n    const [, pid, started] = line.match(/^\\s*(\\d+)\\s+(.+)$/) ?? []\n    if (owned.has(Number(pid)) && owned.get(Number(pid)) === started) {\n      try {\n        process.kill(Number(pid), 'SIGKILL')\n      } catch (error) {\n        if (error.code !== 'ESRCH') throw error\n      }\n    }\n  }\n}\n\n/** Owns the child process group through capture and conversion, including forced cleanup. */\nexport async function superviseRecordingJob({\n  directory,\n  command,\n  args,\n  maxDurationMs,\n  pollMs = 1000,\n  graceMs = 10000,\n}) {\n  const stateFile = path.join(directory, 'state.json')\n  let state = await readJSON({ file: stateFile })\n  const log = await open(state.log, 'a', 0o600)\n  let child\n  let timer\n  let hardStop\n  let reason\n  let checking = false\n  let isFinished = false\n  let statusWrite = Promise.resolve()\n  let ownedProcesses = new Map()\n  const signal = (name) => {\n    try {\n      process.kill(-child.pid, name)\n    } catch (error) {\n      if (error.code !== 'ESRCH') throw error\n    }\n  }\n  const cancel = (why) => {\n    if (reason || isFinished) return\n    reason = why\n    state = { ...state, status: 'stopping', reason }\n    statusWrite = saveJSON({ file: stateFile, value: state }).catch((error) => {\n      // Status persistence must never disable the cancellation watchdog.\n      state = { ...state, statusWriteError: error.message }\n    })\n    ownedProcesses = processTree({ pid: child.pid })\n    signal('SIGINT')\n    hardStop = setTimeout(() => {\n      signal('SIGKILL')\n      killSurvivors({ owned: ownedProcesses })\n    }, graceMs)\n  }\n  const interrupted = () => cancel('stopped')\n  try {\n    child = spawn(command, args, { detached: true, stdio: ['ignore', log.fd, log.fd] })\n    const completed = new Promise((resolve, reject) => {\n      child.once('error', reject)\n      child.once('close', (code, signal) => resolve({ code, signal }))\n    })\n    void completed.catch(() => {})\n    process.once('SIGINT', interrupted)\n    process.once('SIGTERM', interrupted)\n    state = { ...state, status: 'running', pid: child.pid }\n    await saveJSON({ file: stateFile, value: state })\n    const check = async () => {\n      if (checking || reason) return\n      checking = true\n      try {\n        const lease = await readJSON({ file: path.join(directory, 'lease.json') })\n        const stop = await readFile(path.join(directory, 'stop')).then(\n          () => true,\n          (error) => {\n            if (error.code === 'ENOENT') return false\n            throw error\n          },\n        )\n        if (stop) cancel('stopped')\n        else if (Date.now() - state.createdAt >= maxDurationMs) cancel('duration-limit')\n        else if (Date.now() >= lease.expiresAt) cancel('lease-expired')\n      } catch {\n        cancel('control-error')\n      } finally {\n        checking = false\n      }\n    }\n    timer = setInterval(() => void check(), pollMs)\n    await check()\n    const result = await completed\n    isFinished = true\n    clearInterval(timer)\n    clearTimeout(hardStop)\n    await statusWrite\n    state = {\n      ...state,\n      status: reason ? 'cancelled' : result.code === 0 ? 'completed' : 'failed',\n      reason,\n      exitCode: result.code,\n      finishedAt: Date.now(),\n    }\n  } catch (error) {\n    isFinished = true\n    if (child?.pid) signal('SIGKILL')\n    state = { ...state, status: 'failed', error: error.message, finishedAt: Date.now() }\n  } finally {\n    clearInterval(timer)\n    clearTimeout(hardStop)\n    process.off('SIGINT', interrupted)\n    process.off('SIGTERM', interrupted)\n    if (ownedProcesses.size) killSurvivors({ owned: ownedProcesses })\n    await log.close()\n    if (state.status !== 'completed')\n      await rm(path.join(directory, 'artifacts'), { recursive: true, force: true })\n    await saveJSON({ file: stateFile, value: state })\n  }\n  return state\n}\n\nasync function main({ args }) {\n  const [action, ...rest] = args\n  if (action === 'start') {\n    let leaseMs = 60000,\n      maxDurationMs = 600000\n    const candidate = []\n    for (let i = 0; i < rest.length; i += 2) {\n      if (rest[i] === '--lease-seconds') leaseMs = Number(rest[i + 1]) * 1000\n      else if (rest[i] === '--max-seconds') maxDurationMs = Number(rest[i + 1]) * 1000\n      else candidate.push(rest[i], rest[i + 1])\n    }\n    return startRecordingJob({ args: candidate, leaseMs, maxDurationMs })\n  }\n  if (action === 'status' && rest.length === 0) return recordingJobStatus()\n  if (rest.length !== 1)\n    throw new Error('Usage: recording-job.mjs start --scenario PATH | status|renew|stop JOB_ID')\n  const id = rest[0]\n  if (action === 'status') return recordingJobStatus({ id })\n  if (action === 'renew') return renewRecordingJob({ id })\n  if (action === 'stop') return stopRecordingJob({ id })\n  if (action === 'worker') {\n    const directory = jobPath({ id })\n    const config = await readJSON({ file: path.join(directory, 'config.json') })\n    const state = await recordingJobStatus({ id })\n    return superviseRecordingJob({\n      directory,\n      command: process.execPath,\n      args: [\n        fileURLToPath(new URL('./prepare-demo.mjs', import.meta.url)),\n        'candidate',\n        ...config.args,\n        '--output',\n        state.output,\n      ],\n      maxDurationMs: config.maxDurationMs,\n    })\n  }\n  throw new Error(`Unknown recording job action: ${action}`)\n}\nif (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {\n  try {\n    console.log(JSON.stringify(await main({ args: process.argv.slice(2) })))\n  } catch (error) {\n    console.error(error.message)\n    process.exitCode = 1\n  }\n}\n", "skills/record-pr-demo/scripts/recording-job.test.mjs": "import assert from 'node:assert/strict'\nimport { createServer } from 'node:http'\nimport { randomUUID } from 'node:crypto'\nimport { mkdtemp, mkdir, readFile, rename, rm, writeFile, stat } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport path from 'node:path'\nimport { test } from 'node:test'\nimport {\n  superviseRecordingJob,\n  startRecordingJob,\n  recordingJobStatus,\n  renewRecordingJob,\n  stopRecordingJob,\n} from './recording-job.mjs'\n\nasync function fixture({ run, leaseMs = 150, command }) {\n  const directory = await mkdtemp(path.join(tmpdir(), 'demo-job-test-'))\n  await mkdir(path.join(directory, 'artifacts'))\n  const output = path.join(directory, 'artifacts', 'demo.mp4')\n  await writeFile(output, 'partial video')\n  await writeFile(\n    path.join(directory, 'state.json'),\n    JSON.stringify({\n      status: 'starting',\n      createdAt: Date.now(),\n      output,\n      log: path.join(directory, 'job.log'),\n    }),\n  )\n  await writeFile(\n    path.join(directory, 'lease.json'),\n    JSON.stringify({ expiresAt: Date.now() + leaseMs }),\n  )\n  try {\n    await run({\n      directory,\n      output,\n      start: ({ code, maxDurationMs = 5000, graceMs = 100 }) =>\n        superviseRecordingJob({\n          directory,\n          command: command ?? process.execPath,\n          args: ['-e', code],\n          maxDurationMs,\n          pollMs: 20,\n          graceMs,\n        }),\n    })\n  } finally {\n    await rm(directory, { recursive: true, force: true })\n  }\n}\nconst wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms))\n\ntest('should stop on lease expiry and remove partial conversion output', async () => {\n  await fixture({\n    run: async ({ start, output }) => {\n      const state = await start({\n        code: 'process.on(\"SIGINT\",()=>process.exit(0));setInterval(()=>{},1000)',\n      })\n      assert.equal(state.status, 'cancelled')\n      assert.equal(state.reason, 'lease-expired')\n      await assert.rejects(stat(output), { code: 'ENOENT' })\n    },\n  })\n})\n\ntest('should preserve successful artifacts while the caller renews the lease', async () => {\n  await fixture({\n    leaseMs: 1000,\n    run: async ({ directory, start, output }) => {\n      const renew = setInterval(\n        () =>\n          void (async () => {\n            const temporary = path.join(directory, 'lease-next.json')\n            await writeFile(temporary, JSON.stringify({ expiresAt: Date.now() + 1000 }))\n            await rename(temporary, path.join(directory, 'lease.json'))\n          })(),\n        50,\n      )\n      try {\n        const state = await start({ code: 'setTimeout(()=>process.exit(0),350)' })\n        assert.equal(state.status, 'completed')\n        assert.ok((await stat(output)).size > 0)\n      } finally {\n        clearInterval(renew)\n      }\n    },\n  })\n})\n\ntest('should honor stop requests and escalate when the recorder ignores SIGINT', async () => {\n  await fixture({\n    leaseMs: 5000,\n    run: async ({ directory, start, output }) => {\n      const running = start({ code: 'process.on(\"SIGINT\",()=>{});setInterval(()=>{},1000)' })\n      await wait(150)\n      await writeFile(path.join(directory, 'stop'), '')\n      const state = await running\n      assert.equal(state.status, 'cancelled')\n      assert.equal(state.reason, 'stopped')\n      await assert.rejects(stat(output), { code: 'ENOENT' })\n    },\n  })\n})\n\ntest('should enforce a duration limit even with a valid lease', async () => {\n  await fixture({\n    leaseMs: 5000,\n    run: async ({ start }) => {\n      const state = await start({ code: 'setInterval(()=>{},1000)', maxDurationMs: 150 })\n      assert.equal(state.reason, 'duration-limit')\n    },\n  })\n})\n\ntest('should clean partial artifacts after recorder failure', async () => {\n  await fixture({\n    leaseMs: 5000,\n    run: async ({ start, output }) => {\n      const state = await start({ code: 'process.exit(2)' })\n      assert.equal(state.status, 'failed')\n      assert.equal(state.exitCode, 2)\n      await assert.rejects(stat(output), { code: 'ENOENT' })\n    },\n  })\n})\n\ntest('should handle failure to start the recorder without leaving artifacts', async () => {\n  await fixture({\n    command: '/nonexistent/payload-recorder',\n    run: async ({ start, output }) => {\n      const state = await start({ code: '' })\n      assert.equal(state.status, 'failed')\n      await assert.rejects(stat(output), { code: 'ENOENT' })\n    },\n  })\n})\n\ntest('should reject unsafe IDs, unmanaged output paths, and invalid durations', async () => {\n  await assert.rejects(recordingJobStatus({ id: '../../other' }), /Invalid/)\n  await assert.rejects(\n    startRecordingJob({ args: ['--scenario', '/tmp/demo.mjs', '--output', '/tmp/user.mp4'] }),\n    /own artifact/,\n  )\n  await assert.rejects(\n    startRecordingJob({ args: ['--scenario', '/tmp/demo.mjs'], leaseMs: 0 }),\n    /positive/,\n  )\n})\n\ntest(\n  'should also stop descendants that create a separate process group',\n  { timeout: 5000 },\n  async () => {\n    await fixture({\n      leaseMs: 5000,\n      run: async ({ directory, start }) => {\n        const pidFile = path.join(directory, 'grandchild.pid')\n        const grandchild = 'process.on(\"SIGINT\",()=>{});setInterval(()=>{},1000)'\n        const code = `const {spawn}=require('node:child_process');const fs=require('node:fs');const child=spawn(process.execPath,['-e',${JSON.stringify(grandchild)}],{detached:true,stdio:'ignore'});fs.writeFileSync(${JSON.stringify(pidFile)},String(child.pid));process.on('SIGINT',()=>{});setInterval(()=>{},1000)`\n        const running = start({ code })\n        let pid\n        for (let i = 0; i < 50; i++) {\n          try {\n            pid = Number(await readFile(pidFile, 'utf8'))\n            break\n          } catch {\n            await wait(20)\n          }\n        }\n        assert.ok(pid)\n        await writeFile(path.join(directory, 'stop'), '')\n        await running\n        for (let i = 0; i < 50; i++) {\n          try {\n            process.kill(pid, 0)\n          } catch (error) {\n            assert.equal(error.code, 'ESRCH')\n            return\n          }\n          await wait(20)\n        }\n        assert.fail('Detached recording descendant is still running')\n      },\n    })\n  },\n)\n\ntest(\n  'should start, find, inspect, renew, and stop a real recording job',\n  { timeout: 30000 },\n  async () => {\n    const directory = await mkdtemp(path.join(tmpdir(), 'demo-job-api-'))\n    const server = createServer((request, response) => response.end('Demo fixture'))\n    await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))\n    let job\n    const finish = async () => {\n      for (let i = 0; i < 300; i++) {\n        const state = await recordingJobStatus({ id: job.id })\n        if (['completed', 'cancelled', 'failed'].includes(state.status)) return state\n        await wait(50)\n      }\n      throw new Error('Recording job did not finish')\n    }\n    try {\n      const scenario = path.join(directory, 'scenario.mjs')\n      await writeFile(\n        scenario,\n        `export const presentation={change:{kind:'Fix',title:'Recording lease',description:'Stop a real recording safely.'}};export default async function({page,ready,pause}){await page.goto('data:text/html,<button>Save document</button>');await ready();console.log('JOB_CAPTURE_READY');await pause(30000)}`,\n      )\n      job = await startRecordingJob({\n        args: ['--scenario', scenario, '--base-url', `http://127.0.0.1:${server.address().port}`],\n      })\n      const before = await recordingJobStatus({ id: job.id })\n      const after = await recordingJobStatus({ id: job.id })\n      assert.equal(after.leaseExpiresAt, before.leaseExpiresAt, 'Reading status renewed the lease')\n      assert.ok((await recordingJobStatus()).jobs.some((candidate) => candidate.id === job.id))\n      const renewed = await renewRecordingJob({ id: job.id })\n      assert.ok(renewed.leaseExpiresAt >= before.leaseExpiresAt)\n      for (let i = 0; i < 200; i++) {\n        const log = await readFile(job.log, 'utf8').catch(() => '')\n        if ((log.match(/JOB_CAPTURE_READY/g) ?? []).length >= 2) break\n        await wait(50)\n      }\n      assert.ok(\n        ((await readFile(job.log, 'utf8')).match(/JOB_CAPTURE_READY/g) ?? []).length >= 2,\n        'Recording never reached the active capture phase',\n      )\n      const stopped = await stopRecordingJob({ id: job.id })\n      assert.equal(stopped.stopRequested, true)\n      const state = await finish()\n      assert.equal(state.status, 'cancelled')\n      assert.equal(state.reason, 'stopped')\n      await assert.rejects(stat(job.output), { code: 'ENOENT' })\n      await assert.rejects(renewRecordingJob({ id: job.id }), /Cannot renew cancelled/)\n      await rm(path.dirname(job.log), { recursive: true, force: true })\n      job = await startRecordingJob({\n        args: ['--scenario', scenario, '--base-url', `http://127.0.0.1:${server.address().port}`],\n        leaseMs: 3000,\n      })\n      const expired = await finish()\n      assert.equal(expired.status, 'cancelled')\n      assert.equal(expired.reason, 'lease-expired')\n      await assert.rejects(stat(job.output), { code: 'ENOENT' })\n    } finally {\n      if (job) {\n        await stopRecordingJob({ id: job.id })\n        await finish()\n        await rm(path.dirname(job.log), { recursive: true, force: true })\n      }\n      await new Promise((resolve) => server.close(resolve))\n      await rm(directory, { recursive: true, force: true })\n    }\n  },\n)\n\ntest('should keep cancelling when writing stopping status fails', { timeout: 5000 }, async () => {\n  await fixture({\n    leaseMs: 5000,\n    run: async ({ directory, start, output }) => {\n      const pidFile = path.join(directory, 'recorder.pid')\n      const code = `process.on('SIGINT',()=>{});require('node:fs').writeFileSync(${JSON.stringify(pidFile)},String(process.pid));setInterval(()=>{},1000)`\n      const running = start({ code })\n      let pid\n      for (let i = 0; i < 100; i++) {\n        try {\n          pid = Number(await readFile(pidFile, 'utf8'))\n          break\n        } catch {\n          await wait(10)\n        }\n      }\n      assert.ok(pid)\n      const stateFile = path.join(directory, 'state.json')\n      await rm(stateFile)\n      await mkdir(stateFile)\n      await writeFile(path.join(directory, 'stop'), '')\n      // Final persistence also fails, but only after the child and artifacts are gone.\n      await assert.rejects(running, (error) =>\n        ['EISDIR', 'ENOTEMPTY', 'EEXIST'].includes(error.code),\n      )\n      assert.throws(() => process.kill(pid, 0), { code: 'ESRCH' })\n      await assert.rejects(stat(output), { code: 'ENOENT' })\n    },\n  })\n})\n\ntest('should discover healthy jobs alongside incomplete and corrupt entries', async () => {\n  const root = path.join(tmpdir(), `payload-demo-jobs-${process.getuid?.() ?? 'local'}`)\n  const ids = [randomUUID(), randomUUID(), randomUUID()]\n  try {\n    for (const id of ids) await mkdir(path.join(root, id), { recursive: true, mode: 0o700 })\n    await writeFile(\n      path.join(root, ids[0], 'state.json'),\n      JSON.stringify({ id: ids[0], status: 'running' }),\n    )\n    await writeFile(\n      path.join(root, ids[0], 'lease.json'),\n      JSON.stringify({ expiresAt: Date.now() + 60000 }),\n    )\n    await writeFile(path.join(root, ids[2], 'state.json'), '{invalid json')\n    const status = await recordingJobStatus()\n    assert.ok(status.jobs.some((job) => job.id === ids[0]))\n    assert.ok(status.unreadableJobs.some((job) => job.id === ids[1]))\n    assert.ok(status.unreadableJobs.some((job) => job.id === ids[2]))\n  } finally {\n    await Promise.all(ids.map((id) => rm(path.join(root, id), { recursive: true, force: true })))\n  }\n})\n", "skills/record-pr-demo/scripts/scroll-demo.mjs": "export function createScrollInteraction({ moveCursor, page }) {\n  return async function scroll(\n    locator,\n    {\n      axis = 'y',\n      to = 'end',\n      duration = 950,\n      easing = 'easeInOutSine',\n      cursorPlacement = 'inside',\n      input = 'wheel',\n      settle = 150,\n    } = {},\n  ) {\n    if (!['x', 'y'].includes(axis) || !['animation', 'wheel'].includes(input)) {\n      throw new Error('Scroll axis must be x or y and input must be animation or wheel')\n    }\n    if (!['outside', 'inside'].includes(cursorPlacement) || easing !== 'easeInOutSine') {\n      throw new Error('Scroll requires outside/inside cursor placement and easeInOutSine easing')\n    }\n    if (![duration, settle].every((value) => Number.isFinite(value) && value >= 0)) {\n      throw new Error('Scroll timing must be finite and non-negative')\n    }\n    if (to !== 'start' && to !== 'end' && !Number.isFinite(to)) {\n      throw new Error('Scroll target must be start, end, or a finite number')\n    }\n    if (input === 'wheel' && cursorPlacement !== 'inside') {\n      throw new Error('Wheel input requires cursorPlacement: inside for real hit testing')\n    }\n\n    await locator.waitFor({ state: 'visible' })\n    const range = await locator.evaluate((element, axis) => {\n      const maximum =\n        axis === 'x'\n          ? element.scrollWidth - element.clientWidth\n          : element.scrollHeight - element.clientHeight\n      const direction = axis === 'x' && getComputedStyle(element).direction === 'rtl' ? -1 : 1\n\n      return {\n        direction,\n        maximum,\n        start: axis === 'x' ? element.scrollLeft : element.scrollTop,\n      }\n    }, axis)\n\n    if (range.maximum <= 0) {\n      throw new Error(`Demo scroll target does not overflow on axis ${axis}`)\n    }\n    const offset = to === 'start' ? 0 : to === 'end' ? range.maximum : to\n    const target = Math.round(Math.max(0, Math.min(range.maximum, offset))) * range.direction || 0\n    let anchor\n\n    try {\n      if (cursorPlacement === 'outside') {\n        const box = await locator.boundingBox()\n        const viewport = page.viewportSize()\n\n        if (!box || !viewport) throw new Error('Cannot place the cursor outside this scroller')\n        const candidates = [\n          { x: box.x + box.width / 2, y: box.y + box.height + 8 },\n          { x: box.x + box.width / 2, y: box.y - 8 },\n          { x: box.x + box.width + 8, y: box.y + box.height / 2 },\n          { x: box.x - 8, y: box.y + box.height / 2 },\n        ]\n        const point = candidates.find(\n          ({ x, y }) => x >= 0 && y >= 0 && x < viewport.width && y < viewport.height,\n        )\n\n        if (!point) throw new Error('No visible position outside the scroller for the demo cursor')\n        anchor = await page.evaluateHandle(({ x, y }) => {\n          const element = document.createElement('div')\n          element.setAttribute('data-pr-demo-scroll-anchor', '')\n          Object.assign(element.style, {\n            position: 'fixed',\n            left: `${x}px`,\n            top: `${y}px`,\n            width: '1px',\n            height: '1px',\n            opacity: '0',\n            pointerEvents: 'none',\n          })\n          document.documentElement.append(element)\n          return element\n        }, point)\n        await moveCursor(page.locator('[data-pr-demo-scroll-anchor]'), {\n          pauseAfter: 0,\n        })\n      } else {\n        await moveCursor(locator, { pauseAfter: 0 })\n      }\n\n      if (input === 'animation') {\n        await locator.evaluate(\n          async (element, { axis, duration, start, target }) => {\n            const property = axis === 'x' ? 'scrollLeft' : 'scrollTop'\n            const direction = Math.sign(target - start)\n            let previous = start\n            const startedAt = performance.now()\n\n            await new Promise((resolve, reject) => {\n              const frame = (now) => {\n                if (!element.isConnected) return reject(new Error('Scroll target was removed'))\n                const progress = duration === 0 ? 1 : Math.min(1, (now - startedAt) / duration)\n                const eased = (1 - Math.cos(Math.PI * progress)) / 2\n                element[property] = progress === 1 ? target : start + (target - start) * eased\n                const current = element[property]\n\n                if ((current - previous) * direction < -0.5) {\n                  return reject(new Error('Demo scroll progress was not monotonic'))\n                }\n                previous = current\n                if (progress === 1) return resolve()\n                requestAnimationFrame(frame)\n              }\n              requestAnimationFrame(frame)\n            })\n          },\n          { axis, duration, start: range.start, target },\n        )\n      } else {\n        const steps = Math.max(1, Math.ceil(duration / 40))\n        let previous = range.start\n\n        for (let step = 1; step <= steps; step += 1) {\n          const eased = (1 - Math.cos((Math.PI * step) / steps)) / 2\n          // Chromium exposes whole-pixel scroll positions, so each checkpoint must be attainable.\n          const next =\n            step === steps ? target : Math.round(range.start + (target - range.start) * eased)\n          const delta = next - previous\n\n          await page.mouse.wheel(axis === 'x' ? delta : 0, axis === 'y' ? delta : 0)\n          await waitForPosition({ axis, locator, target: next })\n          const current = await readPosition({ axis, locator })\n\n          if ((current - previous) * Math.sign(target - range.start) < -0.5) {\n            throw new Error('Demo wheel scroll progress was not monotonic')\n          }\n          previous = current\n          if (duration > 0) await page.waitForTimeout(duration / steps)\n        }\n      }\n      await waitForPosition({ axis, locator, target })\n      if (settle > 0) await page.waitForTimeout(settle)\n      const position = await readPosition({ axis, locator })\n\n      if (Math.abs(position - target) > 0.5)\n        throw new Error('Demo scroll did not settle at its target')\n      return { position, target }\n    } finally {\n      if (anchor) {\n        try {\n          await anchor.evaluate((element) => element.remove())\n        } finally {\n          await anchor.dispose()\n        }\n      }\n    }\n  }\n}\n\nasync function readPosition({ axis, locator }) {\n  return locator.evaluate(\n    (element, axis) => (axis === 'x' ? element.scrollLeft : element.scrollTop),\n    axis,\n  )\n}\n\nasync function waitForPosition({ axis, locator, target }) {\n  const deadline = Date.now() + 2000\n\n  do {\n    if (Math.abs((await readPosition({ axis, locator })) - target) <= 0.5) return\n    await new Promise((resolve) => setTimeout(resolve, 16))\n  } while (Date.now() < deadline)\n  throw new Error(`Demo scroll did not reach ${target} on axis ${axis}`)\n}\n", "skills/record-pr-demo/scripts/scroll-demo.test.mjs": "import assert from 'node:assert/strict'\nimport { after, before, test } from 'node:test'\n\nimport { chromium } from '@playwright/test'\n\nimport { createScrollInteraction } from './scroll-demo.mjs'\n\nlet browser\n\nbefore(async () => {\n  browser = await chromium.launch({ headless: true })\n})\nafter(async () => {\n  await browser?.close()\n})\n\nasync function withScroller({ run, direction = 'ltr' }) {\n  const page = await browser.newPage({ viewport: { width: 640, height: 480 } })\n\n  try {\n    await page.setContent(`<style>\n      #scroller { margin: 50px; width: 200px; height: 24px; overflow: auto; direction: ${direction}; }\n      #content { width: 600px; height: 240px; display: flex; }\n      button { flex: 0 0 100px; height: 24px; }\n    </style><div id=\"scroller\"><div id=\"content\">\n      <button>A</button><button>B</button><button>C</button><button>D</button><button>E</button><button>F</button>\n    </div></div>`)\n    const locator = page.locator('#scroller')\n    const moveCursor = async (target) => {\n      const box = await target.boundingBox()\n\n      await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2)\n    }\n    const scroll = createScrollInteraction({ moveCursor, page })\n\n    await run({ locator, moveCursor, page, scroll })\n  } finally {\n    await page.close()\n  }\n}\n\nfor (const axis of ['x', 'y']) {\n  test(`should reach ${axis} start, end, numeric and clamped targets`, async () => {\n    await withScroller({\n      run: async ({ locator, page, scroll }) => {\n        const maximum = axis === 'x' ? 400 : 216\n\n        for (const [to, target] of [\n          ['end', maximum],\n          ['start', 0],\n          [80, 80],\n          [10000, maximum],\n          [-20, 0],\n        ]) {\n          assert.deepEqual(await scroll(locator, { axis, to, duration: 50, settle: 0 }), {\n            position: target,\n            target,\n          })\n          assert.equal(await page.locator('[data-pr-demo-scroll-anchor]').count(), 0)\n        }\n      },\n    })\n  })\n}\n\ntest('should interpret horizontal RTL targets as distance from the start', async () => {\n  await withScroller({\n    direction: 'rtl',\n    run: async ({ locator, scroll }) => {\n      assert.deepEqual(\n        await scroll(locator, {\n          axis: 'x',\n          to: 'end',\n          duration: 50,\n          settle: 0,\n        }),\n        {\n          position: -400,\n          target: -400,\n        },\n      )\n      assert.deepEqual(\n        await scroll(locator, {\n          axis: 'x',\n          to: 'start',\n          duration: 50,\n          settle: 0,\n        }),\n        {\n          position: 0,\n          target: 0,\n        },\n      )\n    },\n  })\n})\n\ntest('should fail clearly when the target does not overflow', async () => {\n  await withScroller({\n    run: async ({ locator, scroll }) => {\n      await locator.locator('#content').evaluate((element) => {\n        element.style.width = '100px'\n        element.replaceChildren()\n      })\n      await assert.rejects(scroll(locator, { axis: 'x' }), /does not overflow/)\n    },\n  })\n})\n\ntest('should animate monotonically with sine easing and avoid hover churn', async () => {\n  await withScroller({\n    run: async ({ locator, page, scroll }) => {\n      await page.evaluate(() => {\n        window.hoverCount = 0\n        document.querySelectorAll('button').forEach((button) => {\n          button.addEventListener('mouseenter', () => {\n            window.hoverCount += 1\n          })\n        })\n        const element = document.querySelector('#scroller')\n        window.samples = []\n        let startedAt\n        const sample = (time) => {\n          if (element.scrollLeft > 0 && !startedAt) startedAt = time\n          if (startedAt)\n            window.samples.push({\n              time: time - startedAt,\n              position: element.scrollLeft,\n            })\n          window.sampleFrame = requestAnimationFrame(sample)\n        }\n        window.sampleFrame = requestAnimationFrame(sample)\n      })\n      await scroll(locator, {\n        axis: 'x',\n        duration: 500,\n        settle: 30,\n        input: 'animation',\n        cursorPlacement: 'outside',\n      })\n      const { samples, hoverCount } = await page.evaluate(() => {\n        cancelAnimationFrame(window.sampleFrame)\n        return { samples: window.samples, hoverCount: window.hoverCount }\n      })\n\n      assert.equal(hoverCount, 0)\n      assert.ok(samples.length > 10)\n      for (let index = 1; index < samples.length; index += 1) {\n        assert.ok(samples[index].position >= samples[index - 1].position)\n      }\n      assert.equal(samples.at(-1).position, 400)\n      // A sine ease spends the first quarter below a linear quarter-distance.\n      const quarter = samples.find(({ time }) => time >= 100)\n\n      assert.ok(quarter.position < 100)\n    },\n  })\n})\n\ntest('should remove the cursor anchor when cursor movement fails', async () => {\n  await withScroller({\n    run: async ({ locator, page }) => {\n      const scroll = createScrollInteraction({\n        page,\n        moveCursor: async () => {\n          throw new Error('cursor failed')\n        },\n      })\n\n      await assert.rejects(scroll(locator, { axis: 'x' }), /cursor failed/)\n      assert.equal(await page.locator('[data-pr-demo-scroll-anchor]').count(), 0)\n    },\n  })\n})\n\ntest('should remove the anchor when the scroller disappears during animation', async () => {\n  await withScroller({\n    run: async ({ locator, moveCursor, page }) => {\n      const scroll = createScrollInteraction({\n        page,\n        moveCursor: async (anchor) => {\n          await moveCursor(anchor)\n          await locator.evaluate((element) => {\n            setTimeout(() => element.remove(), 40)\n          })\n        },\n      })\n\n      await assert.rejects(\n        scroll(locator, {\n          axis: 'x',\n          duration: 300,\n          input: 'animation',\n          cursorPlacement: 'outside',\n        }),\n        /target was removed/,\n      )\n      assert.equal(await page.locator('[data-pr-demo-scroll-anchor]').count(), 0)\n    },\n  })\n})\n\ntest('should send real wheel events and never repair prevented input', async () => {\n  await withScroller({\n    run: async ({ locator, page, scroll }) => {\n      await locator.evaluate((element) => {\n        window.wheels = []\n        element.addEventListener('wheel', (event) => window.wheels.push(event.deltaX))\n      })\n      assert.deepEqual(\n        await scroll(locator, {\n          axis: 'x',\n          duration: 200,\n          settle: 30,\n        }),\n        { position: 400, target: 400 },\n      )\n      const wheels = await page.evaluate(() => window.wheels)\n\n      assert.ok(wheels.length > 1)\n      assert.ok(wheels.every((delta) => delta > 0 && delta < 400))\n      await locator.evaluate((element) => {\n        element.addEventListener('wheel', (event) => event.preventDefault(), {\n          passive: false,\n        })\n      })\n      await assert.rejects(\n        scroll(locator, {\n          axis: 'x',\n          to: 'start',\n          duration: 0,\n        }),\n        /did not reach/,\n      )\n      assert.equal(await locator.evaluate((element) => element.scrollLeft), 400)\n    },\n  })\n})\n\ntest('should pace whole-pixel wheel deltas over a short overflow range', async () => {\n  await withScroller({\n    run: async ({ locator, page, scroll }) => {\n      await locator.locator('#content').evaluate((element) => {\n        element.style.height = '168px'\n        element.addEventListener('wheel', (event) => {\n          window.wheelDeltas ??= []\n          window.wheelDeltas.push(event.deltaY)\n        })\n      })\n      assert.deepEqual(await scroll(locator, { duration: 1000, settle: 0 }), {\n        position: 144,\n        target: 144,\n      })\n      const deltas = await page.evaluate(() => window.wheelDeltas)\n      assert.ok(deltas.length > 5)\n      assert.ok(deltas.every(Number.isInteger))\n    },\n  })\n})\n", "skills/record-pr-demo/scripts/sidebar-layout.test.mjs": "import assert from 'node:assert/strict'\nimport { test } from 'node:test'\nimport { chromium, expect } from '@playwright/test'\n\nimport { createPresentation } from './presentation-demo.mjs'\n\nasync function withSidebar({\n  run,\n  accessibility = false,\n  stepCount = 12,\n  shouldDeclareSteps = true,\n}) {\n  const browser = await chromium.launch({ headless: true })\n  let presentation\n  try {\n    const page = await browser.newPage({ viewport: { width: 1794, height: 1086 } })\n    const steps = Array.from({ length: stepCount }, (_, index) => ({\n      title: `Step ${index + 1}`,\n      body: `Inspect the result of step ${index + 1} before continuing to the next part of the walkthrough.`,\n    }))\n    presentation = await createPresentation({\n      page,\n      options: {\n        accessibility,\n        showAnnouncements: accessibility,\n        annotationSteps: shouldDeclareSteps ? steps : undefined,\n        change: {\n          kind: 'Feature',\n          title: 'Resize the application',\n          description: 'Keep the walkthrough attached at every size.',\n        },\n      },\n      viewport: { width: 1440, height: 900 },\n      baseURL: 'http://sidebar.test',\n      pauseScale: 1,\n    })\n    await presentation.setAnnotation({ ...steps.at(-1), index: stepCount, total: stepCount })\n    await presentation.flush()\n    await run({ page, presentation })\n  } finally {\n    await presentation?.stop()\n    await browser.close()\n  }\n}\n\nasync function geometry({ page }) {\n  return page.evaluate(() => {\n    const shadow = document.querySelector('#demo-stage').shadowRoot\n    const rect = (selector) => {\n      const r = shadow.querySelector(selector).getBoundingClientRect()\n      return { x: r.x, y: r.y, width: r.width, height: r.height }\n    }\n    return {\n      sidebar: rect('.annotation-sidebar'),\n      window: rect('[data-window]'),\n      list: rect('.sidebar-steps'),\n      current: rect('[aria-current=step]'),\n    }\n  })\n}\n\ntest('should shrink the sidebar with the window and keep its active step visible', async () => {\n  await withSidebar({\n    run: async ({ page, presentation }) => {\n      const initial = await geometry({ page })\n      await presentation.resizeWindow({ width: 700, height: 400, duration: 100 })\n      await presentation.flush()\n      const resized = await geometry({ page })\n      assert.ok(\n        resized.sidebar.height < initial.sidebar.height - 200,\n        'Sidebar should follow vertical shrinkage',\n      )\n      assert.ok(\n        Math.abs(resized.sidebar.y - resized.window.y) < 1,\n        'Sidebar and window should share their top edge',\n      )\n      assert.ok(\n        Math.abs(resized.sidebar.height - resized.window.height) < 1,\n        'Sidebar and window should share their height',\n      )\n      await expect\n        .poll(async () => {\n          const { current, list } = await geometry({ page })\n          return current.y >= list.y - 1 && current.y + current.height <= list.y + list.height + 1\n        })\n        .toBe(true)\n    },\n  })\n})\n\ntest('should keep the window beside the sidebar after an animated shrink and expansion', async () => {\n  await withSidebar({\n    run: async ({ page, presentation }) => {\n      await page.evaluate(() => {\n        window.sidebarResizeSamples = []\n        window.shouldSampleSidebar = true\n        const sample = () => {\n          const shadow = document.querySelector('#demo-stage').shadowRoot\n          const sidebar = shadow.querySelector('.annotation-sidebar').getBoundingClientRect()\n          const windowRect = shadow.querySelector('[data-window]').getBoundingClientRect()\n          window.sidebarResizeSamples.push(\n            Math.max(\n              Math.abs(sidebar.right - windowRect.left),\n              Math.abs(sidebar.top - windowRect.top),\n              Math.abs(sidebar.height - windowRect.height),\n            ),\n          )\n          if (window.shouldSampleSidebar) requestAnimationFrame(sample)\n        }\n        requestAnimationFrame(sample)\n      })\n      for (const viewport of [\n        { width: 390, height: 400 },\n        { width: 1440, height: 900 },\n        { width: 1920, height: 1080 },\n      ]) {\n        await presentation.resizeWindow({ ...viewport, duration: 180 })\n        await presentation.flush()\n        const result = await geometry({ page })\n        assert.ok(\n          Math.abs(result.sidebar.x + result.sidebar.width - result.window.x) < 1,\n          'Window should remain attached to the sidebar',\n        )\n        assert.ok(\n          Math.abs(result.sidebar.y - result.window.y) < 1,\n          'Window should not drop below the sidebar',\n        )\n        assert.ok(\n          Math.abs(result.sidebar.height - result.window.height) < 1,\n          'Sidebar height should track the scaled window',\n        )\n      }\n      const samples = await page.evaluate(() => {\n        window.shouldSampleSidebar = false\n        return window.sidebarResizeSamples\n      })\n      assert.ok(samples.length > 5, 'Animated resize should be sampled between endpoints')\n      assert.ok(\n        Math.max(...samples) < 1,\n        'Sidebar and window should stay attached during animation',\n      )\n    },\n  })\n})\n\ntest('should keep the overview while hiding steps without mounting a top panel', async () => {\n  await withSidebar({\n    run: async ({ page, presentation }) => {\n      const window = await page.locator('[data-window]').boundingBox()\n      await expect(page.locator('.footer, .note, .step-progress')).toHaveCount(0)\n      await expect(page.locator('.sidebar-intro')).toHaveText(\n        'Keep the walkthrough attached at every size.',\n      )\n      await presentation.clearAnnotation()\n      await expect(page.locator('.sidebar-steps')).toBeHidden()\n      await expect(page.locator('.sidebar-intro')).toBeVisible()\n      assert.deepEqual(await page.locator('[data-window]').boundingBox(), window)\n    },\n  })\n})\n\ntest('should keep the active step visible when a wrapped caption changes sidebar space', async () => {\n  await withSidebar({\n    accessibility: true,\n    run: async ({ page }) => {\n      await page.evaluate(() =>\n        window.demoChrome.setAccessibilityState({\n          announcement:\n            'The document was saved and the selected item moved to its new position. '.repeat(4),\n        }),\n      )\n      await expect(page.locator('[data-announcement]')).toHaveCSS('white-space', 'normal')\n      const feedback = await page.locator('[data-accessibility]').boundingBox()\n      const cards = await page.locator('.sidebar-steps').boundingBox()\n      assert.ok(feedback.y - (cards.y + cards.height) >= 9, 'Feedback needs space above its card')\n      await expect\n        .poll(async () => {\n          const active = await page.locator('[aria-current=step]').boundingBox()\n          const list = await page.locator('.sidebar-steps').boundingBox()\n          return active.y >= list.y && active.y + active.height <= list.y + list.height + 1\n        })\n        .toBe(true)\n    },\n  })\n})\n\nfor (const accessibility of [false, true]) {\n  test(`should keep consistent long-list spacing with feedback ${accessibility}`, async () => {\n    await withSidebar({\n      accessibility,\n      run: async ({ page }) => {\n        if (accessibility) {\n          await page.evaluate(() =>\n            window.demoChrome.setAccessibilityState({\n              key: 'Tab',\n              announcement: 'All changes saved.',\n            }),\n          )\n        }\n        const list = page.locator('.sidebar-steps')\n        await expect\n          .poll(() => list.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop))\n          .toBeLessThan(2)\n        const edges = page.locator('.sidebar-steps-viewport')\n        await expect(edges).toHaveAttribute('data-overflow-above', '')\n        await expect(edges).not.toHaveAttribute('data-overflow-below', '')\n        const intro = await page.locator('.sidebar-intro').boundingBox()\n        const walkthrough = await page.locator('.sidebar-intro + .sidebar-heading').boundingBox()\n        const standardGap = walkthrough.y - intro.y - intro.height\n        const shell = await page.locator('.sidebar-shell').boundingBox()\n        const last = await page.locator('.sidebar-step').last().boundingBox()\n        let header\n        if (accessibility) {\n          header = await page.locator('.sidebar-feedback > .sidebar-heading').boundingBox()\n          assert.ok(\n            Math.abs(header.y - last.y - last.height - standardGap) < 1,\n            'Section gaps should match',\n          )\n        } else {\n          await expect(page.locator('.sidebar-feedback')).toHaveCount(0)\n          assert.ok(\n            Math.abs(shell.y + shell.height - last.y - last.height - 10) < 1,\n            'List needs the normal bottom inset',\n          )\n        }\n        const bounds = await list.boundingBox()\n        await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2)\n        await page.mouse.wheel(0, -150)\n        await expect\n          .poll(() => list.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop))\n          .toBeGreaterThan(50)\n        if (accessibility) {\n          assert.deepEqual(\n            await page.locator('.sidebar-feedback > .sidebar-heading').boundingBox(),\n            header,\n          )\n          const currentList = await list.boundingBox()\n          assert.ok(Math.abs(header.y - currentList.y - currentList.height - standardGap) < 1)\n        }\n        await page.mouse.wheel(0, -10000)\n        await expect.poll(() => list.evaluate((el) => el.scrollTop)).toBeLessThan(2)\n        await expect(edges).not.toHaveAttribute('data-overflow-above', '')\n        await expect(edges).toHaveAttribute('data-overflow-below', '')\n        assert.deepEqual(await page.locator('.sidebar-shell').boundingBox(), shell)\n      },\n    })\n  })\n}\n\ntest('should hide scroll shadows when cards fit and respect reduced motion', async () => {\n  await withSidebar({\n    stepCount: 2,\n    run: async ({ page, presentation }) => {\n      const edges = page.locator('.sidebar-steps-viewport')\n      await expect(edges).not.toHaveAttribute('data-overflow-above', '')\n      await expect(edges).not.toHaveAttribute('data-overflow-below', '')\n      const styles = await edges.evaluate((element) => ({\n        top: getComputedStyle(element, '::before').opacity,\n        bottom: getComputedStyle(element, '::after').opacity,\n        pointerEvents: getComputedStyle(element, '::before').pointerEvents,\n      }))\n      assert.deepEqual(styles, { top: '0', bottom: '0', pointerEvents: 'none' })\n      await page.emulateMedia({ reducedMotion: 'reduce' })\n      assert.equal(\n        await edges.evaluate((element) => getComputedStyle(element, '::before').transitionDuration),\n        '0s',\n      )\n      await presentation.clearAnnotation()\n      await expect(edges).toBeHidden()\n    },\n  })\n})\n\ntest('should extend edge shadows across the sidebar without inset seams at scaled sizes', async () => {\n  await withSidebar({\n    run: async ({ page }) => {\n      for (const width of [1120, 1600, 1794]) {\n        await page.setViewportSize({ width, height: 1086 })\n        const edges = await page.locator('.sidebar-steps-viewport').evaluate((element) => {\n          const top = getComputedStyle(element, '::before')\n          const bottom = getComputedStyle(element, '::after')\n          return {\n            top: top.top,\n            bottom: bottom.bottom,\n            left: top.left,\n            right: top.right,\n            width: parseFloat(top.width),\n            viewport: element.clientWidth,\n          }\n        })\n        assert.ok(parseFloat(edges.top) <= 0)\n        assert.ok(parseFloat(edges.bottom) <= 0)\n        assert.ok(parseFloat(edges.left) <= 0)\n        assert.ok(parseFloat(edges.right) <= 0)\n        assert.ok(edges.width >= edges.viewport)\n      }\n    },\n  })\n})\n\ntest('should reveal replacement current notes without resetting an unchanged note', async () => {\n  await withSidebar({\n    shouldDeclareSteps: false,\n    stepCount: 1,\n    run: async ({ page, presentation }) => {\n      const list = page.locator('.sidebar-steps')\n      await presentation.setAnnotation({\n        title: 'Original note',\n        body: 'Review the original long note. '.repeat(250),\n        index: 1,\n        total: 1,\n      })\n      const bounds = await list.boundingBox()\n      await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2)\n      await page.mouse.wheel(0, 500)\n      await expect.poll(() => list.evaluate((el) => el.scrollTop)).toBeGreaterThan(100)\n      const replacement = {\n        title: 'Replacement note',\n        body: 'Read the replacement long note. '.repeat(250),\n        index: 1,\n        total: 1,\n      }\n      await presentation.setAnnotation(replacement)\n      await expect\n        .poll(() => list.evaluate((el) => el.scrollTop), { timeout: 1500 })\n        .toBeLessThan(2)\n      await page.mouse.wheel(0, 500)\n      await expect.poll(() => list.evaluate((el) => el.scrollTop)).toBeGreaterThan(100)\n      await presentation.setAnnotation(replacement)\n      await page.waitForTimeout(400)\n      assert.ok((await list.evaluate((el) => el.scrollTop)) > 100)\n    },\n  })\n})\n", "skills/record-pr-demo/scripts/window-chrome.test.mjs": "import assert from 'node:assert/strict'\nimport { readFile } from 'node:fs/promises'\nimport { test } from 'node:test'\nimport { chromium } from '@playwright/test'\n\nasync function withChrome({ run }) {\n  const browser = await chromium.launch({ headless: true })\n  try {\n    const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } })\n    await page.setContent('<input aria-label=\"Keep focus\"><div id=\"root\"></div>')\n    const source = await readFile(\n      new URL('./WindowChrome/index.mjs', import.meta.url),\n      'utf8',\n    ).catch(() => '')\n    await page.addScriptTag({\n      type: 'module',\n      content: `${source}\\nwindow.mountDemoChrome = typeof mountDemoChrome === 'function' ? mountDemoChrome : null`,\n    })\n    assert.equal(\n      await page.evaluate(() => typeof window.mountDemoChrome),\n      'function',\n      'Shared chrome mount is missing',\n    )\n    await page.evaluate(() => {\n      window.chromeDemo = window.mountDemoChrome({\n        root: document.querySelector('#root'),\n      })\n    })\n    await run({ page })\n  } finally {\n    await browser.close()\n  }\n}\n\ntest('should animate the live iframe viewport continuously with the surrounding window', async () => {\n  await withChrome({\n    run: async ({ page }) => {\n      const result = await page.evaluate(async () => {\n        const host = document.querySelector('#root')\n        const frame = document.createElement('iframe')\n        frame.slot = 'content'\n        frame.title = 'Responsive application'\n        frame.srcdoc =\n          '<style>body{margin:0;background:green}@media(max-width:600px){body{background:blue}}</style><main>Live application</main>'\n        const loaded = new Promise((resolve) =>\n          frame.addEventListener('load', resolve, { once: true }),\n        )\n        host.append(frame)\n        await loaded\n        const root = host.shadowRoot\n        const samples = []\n        const timer = setInterval(\n          () =>\n            samples.push({\n              width: root.querySelector('[data-content]').clientWidth,\n              appWidth: frame.contentWindow.innerWidth,\n            }),\n          16,\n        )\n        await window.chromeDemo.animateViewport({ width: 390, height: 720, duration: 400 })\n        clearInterval(timer)\n        return {\n          samples,\n          finalWidth: frame.contentWindow.innerWidth,\n          background: frame.contentWindow.getComputedStyle(frame.contentDocument.body)\n            .backgroundColor,\n        }\n      })\n      assert.ok(new Set(result.samples.map((sample) => sample.width)).size >= 12)\n      for (const sample of result.samples) assert.equal(sample.width, sample.appWidth)\n      assert.equal(result.finalWidth, 390)\n      assert.equal(result.background, 'rgb(0, 0, 255)')\n    },\n  })\n})\n\ntest('should spin the persistent refresh control without moving content, including reduced motion', async () => {\n  await withChrome({\n    run: async ({ page }) => {\n      const root = page.locator('#root')\n      const content = await root.locator('[data-content]').boundingBox()\n      const refresh = root.getByRole('button', { name: 'Refresh frame', exact: true })\n      assert.equal(await refresh.isVisible(), true)\n      await page.getByLabel('Keep focus').focus()\n      await page.evaluate(() => window.chromeDemo.setRefreshState({ state: 'refreshing' }))\n      const status = root.getByRole('status')\n      assert.equal(await status.textContent(), 'Refreshing…')\n      assert.equal(\n        await root.locator('[data-refresh]').evaluate((e) => getComputedStyle(e).position),\n        'absolute',\n      )\n      assert.equal(await root.locator('[data-refresh]').evaluate((e) => e.clientWidth), 1)\n      assert.equal(await root.locator('[data-size]').textContent(), '1280 × 720')\n      assert.deepEqual(await root.locator('[data-content]').boundingBox(), content)\n      for (const width of [768, 390]) {\n        await page.evaluate((width) => window.chromeDemo.setViewport({ width, height: 720 }), width)\n        const boxes = await root\n          .locator('[data-size]')\n          .evaluate((e) => ({ width: e.clientWidth, scroll: e.scrollWidth }))\n        assert.ok(boxes.scroll <= boxes.width)\n        assert.equal(await status.isVisible(), true)\n      }\n      const completion = await page.evaluate(async () => {\n        const root = document.querySelector('#root').shadowRoot\n        const icon = root.querySelector('[data-refresh-icon]')\n        const animation = icon.getAnimations()[0]\n        animation.currentTime = 200\n        window.chromeDemo.setRefreshState({ state: 'refreshed' })\n        const continued = icon.getAnimations()[0] === animation\n        await new Promise((resolve) =>\n          icon.addEventListener('animationiteration', resolve, { once: true }),\n        )\n        return {\n          continued,\n          spinning: root.querySelector('[data-refresh-button]').hasAttribute('data-spinning'),\n        }\n      })\n      assert.equal(completion.continued, true)\n      assert.equal(completion.spinning, false)\n      await page.evaluate(() => window.chromeDemo.setRefreshState({ state: 'refreshing' }))\n      await page.emulateMedia({ reducedMotion: 'reduce' })\n      assert.equal(\n        await root\n          .locator('[data-refresh-icon]')\n          .evaluate((e) => getComputedStyle(e).animationName),\n        'none',\n      )\n      assert.equal(\n        await page.getByLabel('Keep focus').evaluate((e) => e === document.activeElement),\n        true,\n      )\n      await page.evaluate(() => window.chromeDemo.setRefreshState({ state: 'refreshed' }))\n      assert.equal(await status.textContent(), 'Refreshed')\n      assert.equal(await refresh.isVisible(), true)\n      assert.equal(await refresh.evaluate((e) => getComputedStyle(e).opacity), '0.35')\n      await page.waitForTimeout(1100)\n      assert.equal(await status.isVisible(), false)\n      await page.evaluate(() => window.chromeDemo.setRefreshState({ state: 'failed' }))\n      assert.equal(await status.textContent(), 'Refresh failed')\n      await page.evaluate(() => window.chromeDemo.setRefreshState({ state: 'idle' }))\n      assert.equal(await status.isVisible(), false)\n    },\n  })\n})\n\ntest('should reject invalid viewport sizes without moving the window', async () => {\n  await withChrome({\n    run: async ({ page }) => {\n      const content = page.locator('#root [data-content]')\n      const bounds = await content.boundingBox()\n      for (const size of [\n        { width: 0, height: 720 },\n        { width: 390.5, height: 720 },\n        { width: 390, height: -1 },\n      ]) {\n        await assert.rejects(\n          page.evaluate((size) => window.chromeDemo.setViewport(size), size),\n          /positive integers/,\n        )\n        assert.deepEqual(await content.boundingBox(), bounds)\n      }\n    },\n  })\n})\n", "skills/record-pr-demo/scripts/WindowChrome/index.mjs": "/** Shared presentation surface. Scenarios supply content, never presentation CSS. */\nexport function mountDemoChrome({\n  root,\n  viewport = { width: 1280, height: 720 },\n  theme = 'light',\n  onNavigate,\n  onRefresh,\n  shouldAnimateFeedback = true,\n  accessibility = false,\n  showAnnouncements = false,\n  canvas = getDefaultCanvas({ viewport }),\n}) {\n  validateSize({ ...canvas, name: 'Canvas' })\n  validateSize({ ...viewport, name: 'Viewport' })\n  if (canvas.width < 800 || canvas.height < 600 || canvas.width % 2 || canvas.height % 2) {\n    throw new Error('Canvas must be at least 800×600 with even dimensions')\n  }\n  if (!['light', 'dark'].includes(theme)) throw new Error('Theme must be light or dark')\n  if (typeof accessibility !== 'boolean')\n    throw new Error('Presentation accessibility must be a boolean')\n  if (typeof showAnnouncements !== 'boolean')\n    throw new Error('Presentation showAnnouncements must be a boolean')\n  const hasAnnouncements = accessibility && showAnnouncements\n  const shadow = root.attachShadow({ mode: 'open' })\n  shadow.innerHTML = `<style>\n    :host { --font-mono:ui-monospace,\"SFMono-Regular\",Menlo,Consolas,monospace; display:block; position:relative; width:100%; aspect-ratio:${canvas.width}/${canvas.height}; font:16px/1.5 system-ui,sans-serif; -webkit-font-smoothing:antialiased; }\n    * { box-sizing:border-box; }\n    [hidden] { display:none; }\n    .stage { position:absolute; inset:0 auto auto 0; width:${canvas.width}px; height:${canvas.height}px; transform-origin:top left; overflow:hidden; color:var(--ink); background:var(--stage); }\n    .light { --paper:#fff; --ink:#252422; --sub:#66635e; --stage:var(--paper); --shell:#dddddd; --line:#c7c7c7; --rim:#ffffffa6; --badge:#ffffff70; }\n    .dark { --paper:#191919; --ink:#ededeb; --sub:#ffffff; --stage:var(--paper); --shell:#232323; --line:var(--badge); --rim:#ffffff12; --badge:#2d2d2d; }\n    .light { --keycap-bg:var(--color-bg-secondary,#f5f5f5); --keycap-border:var(--color-border,#e6e6e6); --keycap-text:var(--color-text,rgba(0,0,0,.9)); }\n    .dark { --keycap-bg:var(--color-bg-secondary,#383838); --keycap-border:var(--color-border,#444444); --keycap-text:var(--color-text,#fff); }\n    .window { position:absolute; padding:10px; border:1px solid var(--rim); border-radius:18px; background:var(--shell); transform-origin:top left; }\n    .header { height:36px; display:flex; align-items:center; justify-content:flex-start; padding:0 0 8px; gap:8px; }\n    .history { display:flex; align-items:center; gap:3px; }\n    .history button { display:grid; place-items:center; width:28px; height:28px; padding:0; border:0; border-radius:6px; background:transparent; color:var(--ink); cursor:pointer; }\n    .history button:hover:not(:disabled) { background:var(--badge); }\n    .history button:disabled, .history .refresh { color:var(--sub); opacity:.35; }\n    .history button:disabled { cursor:default; }\n    .history button:focus-visible { outline:2px solid #0d99ff; outline-offset:1px; }\n    .history svg { width:17px; height:17px; pointer-events:none; }\n    .address { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; border:1px solid var(--line); border-radius:7px; padding:3px 9px; background:var(--badge); color:var(--sub); font:12px/1.5 var(--font-mono); }\n    .history .refresh:hover, .history .refresh:focus-visible, .history .refresh[data-spinning] { opacity:1; }\n    .refresh[data-spinning] svg { animation:refresh-spin 650ms linear infinite; }\n    @keyframes refresh-spin { to { transform:rotate(360deg); } }\n    @media (prefers-reduced-motion:reduce) { .refresh[data-spinning] svg { animation:none; } }\n    .size { flex:none; padding:3px 9px; border:1px solid var(--line); border-radius:7px; background:var(--badge); color:var(--sub); font:12px/1.5 var(--font-mono); font-variant-numeric:tabular-nums; }\n    .content { position:relative; overflow:hidden; border-radius:8px; background:var(--paper); }\n    ::slotted([slot=content]) { display:block; width:100%; height:100%; border:0; }\n\n    .kind { font-family:var(--font-mono); align-self:flex-start; padding-inline:6px; border:1px solid var(--kind-border); border-radius:4px; background:var(--kind-bg); color:var(--kind-text); font-size:12px; font-weight:500; line-height:16px; }\n    .light { --kind-bug-bg:var(--color-bg-danger-tertiary,#ffe2e0); --kind-bug-border:var(--color-border-danger,#ffc7c2); --kind-bug-text:var(--color-text-danger,#dc3412); }\n    .dark { --kind-bug-bg:var(--color-bg-danger-tertiary,#60332a); --kind-bug-border:var(--color-border-danger,#864537); --kind-bug-text:var(--color-text-danger,#ffafa3); }\n    .kind[data-kind=\"Bug\"] { --kind-bg:var(--kind-bug-bg); --kind-border:var(--kind-bug-border); --kind-text:var(--kind-bug-text); }\n    [data-refresh] { position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip-path:inset(50%); white-space:nowrap; border:0; }\n    .accessibility { flex:none; min-height:0; display:flex; flex-direction:column; align-items:stretch; gap:10px; margin:10px; padding:9px; border:1px solid var(--line); border-radius:8px; background:var(--paper); pointer-events:none; }\n    .accessibility:not(:has([data-caption]:not([hidden]),[data-keystroke-overlay]:not([hidden]))) { display:none; }\n\n    .accessibility[hidden], .announcement-line[hidden], .keystroke-overlay[hidden] { display:none; }\n    .announcement-line { min-width:0; color:var(--ink); font-size:12px; line-height:18px; }\n    .announcement { min-width:0; overflow:hidden; overflow-wrap:anywhere; white-space:normal; display:-webkit-box; -webkit-line-clamp:3; -webkit-box-orient:vertical; }\n    .key-slot { min-width:0; }\n    .keystroke-overlay { position:relative; display:flex; align-items:center; gap:6px; width:100%; min-height:22px; overflow:hidden; pointer-events:none; color:var(--ink); }\n    .keystroke { display:flex; flex:none; align-items:center; gap:3px; font:11px/1.5 var(--font-mono); }\n    .keystroke[data-key-history-entry]:nth-child(2) { opacity:.72; }\n    .keystroke[data-key-history-entry]:nth-child(3) { opacity:.5; }\n    .keystroke[data-key-history-entry]:nth-child(4) { opacity:.32; }\n    .keystroke[data-key-history-entry] kbd { color:var(--sub); }\n    .keystroke[data-keystroke] { font-weight:600; }\n    .keystroke[data-keystroke] kbd { border-color:var(--ink); background:var(--ink); color:var(--paper); }\n    .keystroke kbd { display:inline-flex; align-items:center; justify-content:center; min-height:22px; padding:1px 5px; border:1px solid var(--keycap-border); border-radius:var(--radius-medium,5px); background:var(--keycap-bg); color:var(--keycap-text); font:inherit; white-space:nowrap; }\n    .key-separator { font:inherit; }\n\n  </style>\n  <div class=\"stage ${theme}\" data-canvas>\n    ${accessibility ? `<div class=\"accessibility\" data-accessibility aria-hidden=\"true\">${hasAnnouncements ? '<div class=\"announcement-line\" data-caption hidden><span class=\"announcement\" data-announcement>Waiting for an update…</span></div>' : ''}<div class=\"key-slot\"><div class=\"keystroke-overlay\" data-keystroke-overlay aria-hidden=\"true\" hidden><span class=\"keystroke\" data-keystroke></span></div></div></div>` : ''}\n    <div class=\"window\" data-window>\n      <div class=\"header\"><div class=\"history\" aria-label=\"Browser history\"><button type=\"button\" data-back aria-label=\"Back\" title=\"Back\" disabled><svg viewBox=\"0 0 20 20\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.7\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M12 4 6 10l6 6M6 10h11\"/></svg></button><button type=\"button\" data-forward aria-label=\"Forward\" title=\"Forward\" disabled><svg viewBox=\"0 0 20 20\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.7\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"m8 4 6 6-6 6M14 10H3\"/></svg></button><button type=\"button\" class=\"refresh\" data-refresh-button data-state=\"idle\" aria-label=\"Refresh frame\" title=\"Refresh frame\"><svg data-refresh-icon aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\"><path d=\"M13 6a5.2 5.2 0 1 0 .1 4M13 2v4H9\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg></button></div><span data-refresh role=\"status\" aria-live=\"polite\" aria-atomic=\"true\" hidden></span><div class=\"address\" data-url role=\"textbox\" aria-label=\"Application URL\" aria-readonly=\"true\">about:blank</div><span class=\"size\" data-size></span></div>\n      <div class=\"content\" data-content><slot name=\"content\"></slot></div>\n    </div>\n\n  </div>`\n  const find = (selector) => shadow.querySelector(selector)\n  find('[data-back]').onclick = () => onNavigate?.(-1)\n  find('[data-forward]').onclick = () => onNavigate?.(1)\n  find('[data-refresh-button]').onclick = () => {\n    if (find('[data-refresh-button]').dataset.state !== 'refreshing') {\n      void Promise.resolve(onRefresh?.()).catch(() => {})\n    }\n  }\n  const keyAnimations = new Set()\n  const cancelKeyAnimations = () => {\n    for (const animation of keyAnimations) animation.cancel()\n    keyAnimations.clear()\n  }\n  let refreshTimer\n  const finishRefreshSpin = () => {\n    find('[data-refresh-button]').removeAttribute('data-spinning')\n  }\n  let currentViewport = viewport\n  let isDestroyed = false\n\n  const layout = () => {\n    if (isDestroyed) return\n    find('[data-canvas]').style.transform = `scale(${root.clientWidth / canvas.width})`\n    const { width, height } = currentViewport\n    const windowWidth = width + 22\n    const windowHeight = height + 58\n    const scale = Math.min(\n      1,\n      (canvas.width - 332) / windowWidth,\n      (canvas.height - 64) / windowHeight,\n    )\n    const windowY = (canvas.height - windowHeight * scale) / 2\n    Object.assign(find('[data-window]').style, {\n      width: `${windowWidth}px`,\n      left: '316px',\n      top: `${windowY}px`,\n      transform: `scale(${scale})`,\n    })\n    Object.assign(find('[data-content]').style, { width: `${width}px`, height: `${height}px` })\n    find('[data-size]').textContent = `${width} × ${height}`\n  }\n  layout()\n  const canAnimateFeedback = () =>\n    shouldAnimateFeedback && !matchMedia('(prefers-reduced-motion: reduce)').matches\n  const observer = new ResizeObserver(layout)\n  observer.observe(root)\n\n  let activeAnimation\n  const cancelAnimation = () => {\n    if (!activeAnimation) return\n    cancelAnimationFrame(activeAnimation.id)\n    activeAnimation.resolve()\n    activeAnimation = undefined\n  }\n\n  return {\n    setTheme(value) {\n      if (!['light', 'dark'].includes(value)) throw new Error('Theme must be light or dark')\n      if (isDestroyed) return\n      find('[data-canvas]').className = `stage ${value}`\n    },\n    setHistoryState({ canGoBack, canGoForward }) {\n      if (isDestroyed) return\n      find('[data-back]').disabled = !canGoBack || !onNavigate\n      find('[data-forward]').disabled = !canGoForward || !onNavigate\n    },\n    setURL(value) {\n      if (isDestroyed) return\n      const url = new URL(value)\n      url.username = ''\n      url.password = ''\n      const displayURL = ['http:', 'https:', 'about:'].includes(url.protocol)\n        ? url.href\n        : url.protocol\n      find('[data-url]').textContent = displayURL\n      find('[data-url]').title = displayURL\n    },\n    setAccessibilityState({ key, announcement, reset = false }) {\n      if (!accessibility || isDestroyed) return\n      if (reset) {\n        cancelKeyAnimations()\n        find('[data-keystroke-overlay]').hidden = true\n        find('[data-keystroke-overlay]').innerHTML =\n          '<span class=\"keystroke\" data-keystroke></span>'\n        if (hasAnnouncements) {\n          find('[data-announcement]').textContent = 'Waiting for an update…'\n          find('[data-caption]').hidden = true\n        }\n      }\n      if (key) {\n        const history = find('[data-keystroke-overlay]')\n        const previousPositions = new Map(\n          [...history.children]\n            .filter((el) => el.textContent)\n            .map((el) => [\n              el,\n              {\n                left: el.getBoundingClientRect().left,\n                opacity: Number(getComputedStyle(el).opacity),\n              },\n            ]),\n        )\n        cancelKeyAnimations()\n        for (const el of history.children) {\n          if (!el.textContent) el.remove()\n          else {\n            el.removeAttribute('data-keystroke')\n            el.setAttribute('data-key-history-entry', '')\n          }\n        }\n        const chord = document.createElement('span')\n        chord.className = 'keystroke'\n        chord.setAttribute('data-keystroke', '')\n        key.split(' + ').forEach((label, index) => {\n          if (index > 0) {\n            const separator = document.createElement('span')\n            separator.className = 'key-separator'\n            separator.setAttribute('data-key-separator', '')\n            separator.textContent = ' + '\n            chord.append(separator)\n          }\n          const keycap = document.createElement('kbd')\n          keycap.textContent = label\n          chord.append(keycap)\n        })\n        history.prepend(chord)\n        while (history.children.length > 4) history.lastElementChild.remove()\n        history.hidden = false\n        while (history.children.length > 1 && history.scrollWidth > history.clientWidth) {\n          history.lastElementChild.remove()\n        }\n        if (canAnimateFeedback() && history.offsetWidth > 0) {\n          const scale = root.clientWidth / canvas.width\n          const gap = parseFloat(getComputedStyle(history).columnGap) || 0\n          const chordBounds = chord.getBoundingClientRect()\n          // Enter behind the prior group, including when its slide is interrupted.\n          const entryOffset = previousPositions.size\n            ? (Math.min(...[...previousPositions.values()].map(({ left }) => left)) -\n                chordBounds.right) /\n                scale -\n              gap\n            : -chordBounds.width / scale - gap\n          for (const el of history.children) {\n            const previous = previousPositions.get(el)\n            const opacity = Number(getComputedStyle(el).opacity)\n            const offset =\n              previous === undefined\n                ? entryOffset\n                : (previous.left - el.getBoundingClientRect().left) / scale\n            const animation = el.animate(\n              [\n                {\n                  transform: `translateX(${offset}px)`,\n                  opacity: previous?.opacity ?? 0,\n                },\n                { transform: 'translateX(0)', opacity },\n              ],\n              { duration: 220, easing: 'cubic-bezier(.2,.8,.2,1)' },\n            )\n            keyAnimations.add(animation)\n            animation.onfinish = () => keyAnimations.delete(animation)\n          }\n        }\n      }\n      if (hasAnnouncements && announcement) {\n        find('[data-announcement]').textContent = announcement\n        find('[data-caption]').hidden = false\n      }\n    },\n    animateViewport({ width, height, duration = 1000 }) {\n      validateSize({ width, height, name: 'Viewport' })\n      if (!Number.isFinite(duration) || duration < 0)\n        throw new Error('Resize duration must be non-negative')\n      cancelAnimation()\n      const initial = currentViewport\n      if (duration === 0 || matchMedia('(prefers-reduced-motion: reduce)').matches) {\n        currentViewport = { width, height }\n        layout()\n        return Promise.resolve()\n      }\n      return new Promise((resolve) => {\n        const animation = { resolve, id: 0 }\n        activeAnimation = animation\n        const startedAt = performance.now()\n        const tick = (now) => {\n          if (activeAnimation !== animation) return\n          const progress = Math.min(1, (now - startedAt) / duration)\n          const eased = progress * progress * (3 - 2 * progress)\n          currentViewport = {\n            width: Math.round(initial.width + (width - initial.width) * eased),\n            height: Math.round(initial.height + (height - initial.height) * eased),\n          }\n          layout()\n          if (progress < 1) animation.id = requestAnimationFrame(tick)\n          else {\n            activeAnimation = undefined\n            resolve()\n          }\n        }\n        animation.id = requestAnimationFrame(tick)\n      })\n    },\n    setViewport(value) {\n      validateSize({ ...value, name: 'Viewport' })\n      cancelAnimation()\n      currentViewport = { width: value.width, height: value.height }\n      layout()\n    },\n    setRefreshState({ state }) {\n      if (!['idle', 'refreshing', 'refreshed', 'failed'].includes(state)) {\n        throw new Error('Invalid refresh state')\n      }\n      clearTimeout(refreshTimer)\n      if (isDestroyed) return\n      const status = find('[data-refresh]')\n      const button = find('[data-refresh-button]')\n      const icon = find('[data-refresh-icon]')\n      icon.removeEventListener('animationiteration', finishRefreshSpin)\n      if (state === 'refreshing') {\n        button.setAttribute('data-spinning', '')\n      } else if (icon.getAnimations().length) {\n        icon.addEventListener('animationiteration', finishRefreshSpin, { once: true })\n      } else {\n        finishRefreshSpin()\n      }\n      status.hidden = state === 'idle'\n      button.dataset.state = state\n      button.setAttribute('aria-disabled', String(state === 'refreshing'))\n      status.textContent = {\n        idle: '',\n        refreshing: 'Refreshing…',\n        refreshed: 'Refreshed',\n        failed: 'Refresh failed',\n      }[state]\n      if (state === 'refreshed')\n        refreshTimer = setTimeout(() => {\n          status.hidden = true\n          button.dataset.state = 'idle'\n          status.textContent = ''\n        }, 650)\n    },\n    destroy() {\n      cancelKeyAnimations()\n      find('[data-refresh-icon]').removeEventListener('animationiteration', finishRefreshSpin)\n      clearTimeout(refreshTimer)\n      cancelAnimation()\n      isDestroyed = true\n      observer.disconnect()\n      shadow.replaceChildren()\n    },\n  }\n}\n\nfunction validateSize({ width, height, name }) {\n  if (\n    !Number.isInteger(width) ||\n    !Number.isInteger(height) ||\n    width < 1 ||\n    height < 1 ||\n    width > 7680 ||\n    height > 4320\n  ) {\n    throw new Error(`${name} dimensions must be positive integers up to 7680×4320`)\n  }\n}\n\n/** Reserve room for the initial viewport, sidebar, browser chrome, and margins. */\nexport function getDefaultCanvas({ viewport }) {\n  return {\n    width: Math.ceil((viewport.width + 22 + 332) / 2) * 2,\n    height: Math.ceil(Math.max(1000, viewport.height + 58 + 128) / 2) * 2,\n  }\n}\n\n/** Follows the iframe's own history without navigating the recording wrapper. */\nexport function bindDemoHistory({ app, chrome }) {\n  let navigation\n  const sync = () => {\n    chrome.setURL(app.contentWindow.location.href)\n    chrome.setHistoryState({\n      canGoBack: navigation?.canGoBack ?? false,\n      canGoForward: navigation?.canGoForward ?? false,\n    })\n  }\n  const attach = () => {\n    navigation?.removeEventListener('currententrychange', sync)\n    // Opaque or external frames cannot expose their history to the recording wrapper.\n    try {\n      navigation = app.contentWindow.navigation\n      sync()\n    } catch {\n      navigation = undefined\n      chrome.setHistoryState({ canGoBack: false, canGoForward: false })\n      return\n    }\n    navigation?.addEventListener('currententrychange', sync)\n  }\n  app.addEventListener('load', attach)\n  return () => {\n    app.removeEventListener('load', attach)\n    navigation?.removeEventListener('currententrychange', sync)\n  }\n}\n", "skills/record-pr-demo/scripts/WindowChrome/sidebar.mjs": "/** Shared walkthrough sidebar for the playground and recordings. */\nexport function mountAnnotationSidebar({ root, change, steps, onSelect, shouldAnimate = true }) {\n  if (\n    !change ||\n    !['Feature', 'Fix', 'Bug'].includes(change.kind) ||\n    !change.title?.trim() ||\n    !change.description?.trim()\n  ) {\n    throw new Error('Presentation requires kind (Feature, Fix, or Bug), title, and description')\n  }\n  const hasDeclaredSteps = steps !== undefined\n  if (\n    hasDeclaredSteps &&\n    (!Array.isArray(steps) ||\n      !steps.length ||\n      steps.some(\n        (step) =>\n          !step ||\n          typeof step.body !== 'string' ||\n          !step.body.trim() ||\n          (step.kind !== undefined && step.kind !== 'Bug'),\n      ))\n  ) {\n    throw new Error(\n      'Sidebar requires nonempty annotationSteps with body text and optional kind: Bug',\n    )\n  }\n  steps = steps ?? [{ body: '' }]\n  const shadow = root.shadowRoot\n  const style = document.createElement('style')\n  // Extend the shell 1px beneath the window to prevent seams at fractional preview scales.\n  style.textContent = `\n    .window { border:0; padding-bottom:12px; border-top-left-radius:0; border-bottom-left-radius:0; }\n    .sidebar-shell { position:absolute; left:16px; width:301px; border-radius:18px 0 0 18px; background:var(--sidebar-bg,var(--shell)); overflow:hidden; }\n    .annotation-sidebar { width:300px; height:100%; color:var(--ink); overflow:hidden; display:flex; flex-direction:column; }\n    .sidebar-feedback { flex:none; display:flex; flex-direction:column; }\n    .sidebar-feedback:not(:has([data-caption]:not([hidden]),[data-keystroke-overlay]:not([hidden]))) { display:none; }\n    .sidebar-feedback .accessibility { margin-block-start:0; }\n    .sidebar-feedback > .sidebar-heading { margin-block-start:8px; }\n    .annotation-sidebar:has([data-caption]:not([hidden]),[data-keystroke-overlay]:not([hidden])) .sidebar-steps { padding-block-end:0; }\n    .sidebar-overview-row { flex:none; height:36px; display:flex; align-items:center; padding-bottom:8px; margin:10px 10px 0; }\n    .sidebar-overview-row .sidebar-heading { flex:1; margin:0; }\n    .sidebar-heading { flex:none; margin:10px 10px 8px; padding:3px 9px; border:1px solid var(--line); border-radius:7px; background:var(--badge); color:var(--sub); font:12px/1.5 var(--font-mono); }\n    .sidebar-intro { flex:none; display:flex; align-items:flex-start; gap:10px; margin:0 10px 8px; padding:9px; border:1px solid var(--line); border-radius:8px; background:var(--paper); }\n    .sidebar-intro + .sidebar-heading { margin-top:0; }\n    .sidebar-intro p { margin:0; min-width:0; color:var(--ink); font-size:12px; line-height:1.4; }\n    .sidebar-steps-viewport { position:relative; flex:1; min-height:0; }\n    .sidebar-steps-viewport::before, .sidebar-steps-viewport::after { content:\"\"; position:absolute; inset-inline:-1px; height:12px; z-index:1; pointer-events:none; mask-image:linear-gradient(to right,transparent,#000 18px,#000 calc(100% - 18px),transparent); opacity:0; transition:${shouldAnimate ? 'opacity 160ms ease' : 'none'}; }\n    .sidebar-steps-viewport::before { inset-block-start:-1px; background:linear-gradient(to bottom,var(--scroll-edge-shadow, rgb(0 0 0 / .14)),transparent); }\n    .sidebar-steps-viewport::after { inset-block-end:-1px; background:linear-gradient(to top,var(--scroll-edge-shadow, rgb(0 0 0 / .14)),transparent); }\n    .sidebar-steps-viewport[data-overflow-above]::before, .sidebar-steps-viewport[data-overflow-below]::after { opacity:1; }\n    .dark .sidebar-steps-viewport { --scroll-edge-shadow:rgb(0 0 0 / .4); }\n    .sidebar-steps { height:100%; min-height:0; overflow-y:auto; overscroll-behavior:contain; scrollbar-width:thin; scrollbar-color:var(--sub) transparent; list-style:none; margin:0; padding:0 10px 10px; }\n    .sidebar-step { width:100%; position:relative; display:block; border:1px solid var(--line); border-radius:8px; padding:0; overflow:hidden; background:var(--paper); color:var(--ink); text-align:left; }\n    button.sidebar-step { cursor:pointer; }\n    .sidebar-step :is(p,.sidebar-step-title) { opacity:.5; transition:opacity 200ms ease; }\n    button.sidebar-step:hover :is(p,.sidebar-step-title) { opacity:.85; }\n    .sidebar-step:focus-visible { outline:2px solid #0d99ff; outline-offset:-2px; }\n    .sidebar-step[aria-current=step] :is(p,.sidebar-step-title) { opacity:1; }\n    .sidebar-dot { position:absolute; z-index:1; pointer-events:none; right:8px; top:8px; width:8px; height:8px; border-radius:50%; background:transparent; }\n    [aria-current=step] .sidebar-dot { background:#0d99ff; }\n    .sidebar-steps li + li { margin-top:6px; }\n    .sidebar-step-title { display:flex; align-items:center; margin:0; padding:9px 9px 0; border:0; border-radius:0; background:var(--paper); color:var(--sub); font:12px/1.5 var(--font-mono); }\n    .sidebar-step p { margin:0; padding:9px; font-size:12px; line-height:1.4; color:var(--ink); }\n    .sidebar-step-title + p { padding-top:9px; }\n    @media(prefers-reduced-motion:reduce) { .sidebar-step :is(p,.sidebar-step-title), .sidebar-steps-viewport::before, .sidebar-steps-viewport::after { transition:none; } }\n  `\n  shadow.append(style)\n  const shell = document.createElement('div')\n  shell.className = 'sidebar-shell'\n  const panel = document.createElement('section')\n  panel.className = 'annotation-sidebar'\n  panel.setAttribute('aria-label', 'Walkthrough steps')\n  const heading = document.createElement('div')\n  heading.className = 'sidebar-heading'\n  heading.textContent = `Overview · ${change.kind}`\n  heading.title = change.title\n  const overviewRow = document.createElement('div')\n  overviewRow.className = 'sidebar-overview-row'\n  overviewRow.append(heading)\n  const walkthroughHeading = document.createElement('div')\n  walkthroughHeading.className = 'sidebar-heading'\n  walkthroughHeading.textContent = 'Walkthrough'\n  const intro = document.createElement('div')\n  intro.className = 'sidebar-intro'\n  const description = document.createElement('p')\n  description.textContent = change.description\n  intro.append(description)\n  const listViewport = document.createElement('div')\n  listViewport.className = 'sidebar-steps-viewport'\n  const list = document.createElement('ol')\n  list.className = 'sidebar-steps'\n  list.tabIndex = 0\n  list.setAttribute('aria-label', 'Scrollable walkthrough steps')\n  const buttons = steps.map((step, index) => {\n    const item = document.createElement('li')\n    const button = document.createElement(onSelect ? 'button' : 'div')\n    if (onSelect) button.type = 'button'\n    button.className = 'sidebar-step'\n    const dot = document.createElement('span')\n    dot.className = 'sidebar-dot'\n    dot.setAttribute('aria-hidden', 'true')\n    const text = document.createElement('div')\n    if (step.kind === 'Bug') {\n      const title = document.createElement('div')\n      title.className = 'sidebar-step-title'\n      const pill = document.createElement('span')\n      pill.className = 'kind'\n      pill.dataset.kind = 'Bug'\n      pill.textContent = 'Bug'\n      title.append(pill)\n      text.append(title)\n    }\n    const body = document.createElement('p')\n    body.textContent = step.body\n    text.append(body)\n    button.append(dot, text)\n    if (onSelect) button.addEventListener('click', () => onSelect(index))\n    item.append(button)\n    list.append(item)\n    return button\n  })\n  listViewport.append(list)\n  panel.append(overviewRow, intro, walkthroughHeading, listViewport)\n  const feedback = shadow.querySelector('[data-accessibility]')\n  if (feedback) {\n    const feedbackSection = document.createElement('div')\n    feedbackSection.className = 'sidebar-feedback'\n    feedbackSection.setAttribute('aria-hidden', 'true')\n    const feedbackHeading = document.createElement('div')\n    feedbackHeading.className = 'sidebar-heading'\n    feedbackHeading.textContent = feedback.querySelector('[data-caption]')\n      ? 'Activity & Keyboard'\n      : 'Keyboard'\n    feedbackSection.append(feedbackHeading, feedback)\n    panel.append(feedbackSection)\n  }\n  const stage = shadow.querySelector('[data-canvas]')\n  shell.append(panel)\n  stage.append(shell)\n  let currentIndex\n  let scrollFrame\n  const updateScrollIndicators = () => {\n    const hasOverflow = list.clientHeight > 0 && list.scrollHeight - list.clientHeight > 1\n    listViewport.toggleAttribute('data-overflow-above', hasOverflow && list.scrollTop > 1)\n    listViewport.toggleAttribute(\n      'data-overflow-below',\n      hasOverflow && list.scrollTop + list.clientHeight < list.scrollHeight - 1,\n    )\n  }\n  list.addEventListener('scroll', updateScrollIndicators, { passive: true })\n  const revealCurrentStep = () => {\n    const button = buttons[currentIndex]\n    if (!button || !list.clientHeight) return\n    const bounds = list.getBoundingClientRect()\n    const step = button.getBoundingClientRect()\n    const scale = list.clientHeight / bounds.height\n    const top = (step.top - bounds.top) * scale + list.scrollTop\n    const bottom = (step.bottom - bounds.top) * scale + list.scrollTop\n    const padding = 24\n    let target = list.scrollTop\n    if (top < target + padding || bottom - top > list.clientHeight - padding * 2) {\n      target = top - padding\n    } else if (bottom > target + list.clientHeight - padding) {\n      target = bottom - list.clientHeight + padding\n    }\n    if (Math.abs(target - list.scrollTop) > 1) {\n      list.scrollTo({\n        top: Math.max(0, target),\n        behavior:\n          shouldAnimate && !matchMedia('(prefers-reduced-motion: reduce)').matches\n            ? 'smooth'\n            : 'instant',\n      })\n    }\n  }\n  const layout = () => {\n    const window = shadow.querySelector('[data-window]')\n    const scale = new DOMMatrixReadOnly(window.style.transform).a\n    const top = window.style.top\n    const height = `${window.offsetHeight * scale}px`\n    const hasChanged = shell.style.top !== top || shell.style.height !== height\n    Object.assign(shell.style, { top, height })\n    if (hasChanged) {\n      cancelAnimationFrame(scrollFrame)\n      scrollFrame = requestAnimationFrame(revealCurrentStep)\n    }\n  }\n  // WindowChrome owns placement; the sidebar only follows its rendered geometry.\n  const observer = new MutationObserver(layout)\n  observer.observe(shadow.querySelector('[data-window]'), {\n    attributes: true,\n    attributeFilter: ['style'],\n  })\n  const listObserver = new ResizeObserver(() => {\n    updateScrollIndicators()\n    cancelAnimationFrame(scrollFrame)\n    scrollFrame = requestAnimationFrame(revealCurrentStep)\n  })\n  listObserver.observe(list)\n  const sidebar = {\n    setAnnotation(annotation) {\n      if (annotation === null) {\n        sidebar.update({ index: currentIndex ?? 0, visible: false })\n        return\n      }\n      const { index, total, title, body } = annotation\n      if (\n        !Number.isInteger(index) ||\n        !Number.isInteger(total) ||\n        index < 1 ||\n        total < index ||\n        !title?.trim() ||\n        typeof body !== 'string'\n      ) {\n        throw new Error(\n          'Annotation requires title, body, and integer pagination: 1 ≤ index ≤ total',\n        )\n      }\n      if (hasDeclaredSteps && (total !== steps.length || body !== steps[index - 1]?.body)) {\n        throw new Error('Annotation must match its declared annotationSteps entry and total')\n      }\n      const shouldReveal = !hasDeclaredSteps && buttons[0].querySelector('p').textContent !== body\n      if (!hasDeclaredSteps) buttons[0].querySelector('p').textContent = body\n      sidebar.update({ index: hasDeclaredSteps ? index - 1 : 0, visible: true, shouldReveal })\n    },\n    destroy: () => {\n      observer.disconnect()\n      listObserver.disconnect()\n      list.removeEventListener('scroll', updateScrollIndicators)\n      cancelAnimationFrame(scrollFrame)\n    },\n    update({ index, visible, shouldReveal = false }) {\n      if (!Number.isInteger(index) || index < 0 || index >= steps.length) {\n        throw new Error('Sidebar step index is outside annotationSteps')\n      }\n      const shouldRevealStep = shouldReveal || index !== currentIndex || (list.hidden && visible)\n      currentIndex = index\n      list.hidden = !visible\n      listViewport.hidden = !visible\n      buttons.forEach((button, i) => {\n        if (i === index) button.setAttribute('aria-current', 'step')\n        else button.removeAttribute('aria-current')\n      })\n      layout()\n      updateScrollIndicators()\n      if (shouldRevealStep && visible) {\n        cancelAnimationFrame(scrollFrame)\n        scrollFrame = requestAnimationFrame(revealCurrentStep)\n      }\n    },\n  }\n  sidebar.update({ index: 0, visible: false })\n  return sidebar\n}\n", "skills/record-pr-demo/scripts/preview/accessibility-application.html": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <title>Accessibility recording sample</title>\n    <style>\n      :root {\n        color-scheme: light dark;\n        font:\n          18px/1.5 system-ui,\n          sans-serif;\n        color: light-dark(#252422, #ededeb);\n        background: light-dark(#faf9f6, #191919);\n      }\n      body {\n        margin: 0;\n        padding: 48px;\n        box-sizing: border-box;\n      }\n      * {\n        box-sizing: border-box;\n      }\n      main {\n        max-width: 1000px;\n        margin: auto;\n      }\n      h1 {\n        font-size: 32px;\n        letter-spacing: -1px;\n        margin: 8px 0;\n      }\n      p {\n        color: light-dark(#66635e, #bbb8b0);\n      }\n      .eyebrow {\n        font-size: 12px;\n        letter-spacing: 1px;\n        text-transform: uppercase;\n      }\n      ol {\n        list-style: none;\n        padding: 0;\n        margin: 32px 0;\n        display: grid;\n        gap: 12px;\n      }\n      li {\n        padding: 20px 24px;\n        border: 1px solid light-dark(#d8d5cf, #66635e);\n        border-radius: 12px;\n        display: flex;\n        align-items: center;\n        justify-content: space-between;\n        gap: 24px;\n        background: light-dark(white, #232321);\n      }\n      button {\n        font: inherit;\n        color: inherit;\n        background: transparent;\n        border: 1px solid light-dark(#bcb9b2, #77746c);\n        padding: 8px 16px;\n        border-radius: 8px;\n        cursor: pointer;\n      }\n      button:focus-visible {\n        outline: 2px solid currentColor;\n        outline-offset: 5px;\n      }\n      #status {\n        min-height: 28px;\n        color: light-dark(#66635e, #bbb8b0);\n        font-size: 16px;\n      }\n      .index {\n        color: light-dark(#77746c, #bbb8b0);\n        font-size: 14px;\n        margin-inline-end: 16px;\n      }\n      .hint {\n        font-size: 14px;\n      }\n      button:disabled {\n        opacity: 0.5;\n        cursor: default;\n      }\n      @media (prefers-color-scheme: dark) {\n        :root {\n          color-scheme: dark;\n        }\n      }\n      @media (min-width: 768px) {\n        body {\n          padding: 64px;\n        }\n      }\n    </style>\n  </head>\n  <body>\n    <main>\n      <div class=\"eyebrow\">Recorder sample · Keyboard interaction</div>\n      <h1>Build your story</h1>\n      <p>\n        Reorder sections without dragging. The recording makes input, focus, and updates visible.\n      </p>\n      <ol id=\"sections\">\n        <li>\n          <span><span class=\"index\">01</span>Introduction</span\n          ><button aria-label=\"Move Introduction down\">Move down ↓</button>\n        </li>\n        <li>\n          <span><span class=\"index\">02</span>Highlights</span\n          ><button aria-label=\"Move Highlights down\">Move down ↓</button>\n        </li>\n        <li>\n          <span><span class=\"index\">03</span>Next steps</span\n          ><button aria-label=\"Move Next steps down\" disabled>Move down ↓</button>\n        </li>\n      </ol>\n      <button id=\"save\">Save changes</button>\n      <p id=\"status\" role=\"status\" aria-atomic=\"true\"></p>\n      <p class=\"hint\">\n        Use Tab to move between controls and Enter to activate. This is a sample, not a Payload PR\n        demo.\n      </p>\n    </main>\n    <script>\n      const list = document.querySelector('#sections')\n      list.addEventListener('click', (event) => {\n        const button = event.target.closest('button')\n        if (!button) return\n        const row = button.closest('li'),\n          next = row.nextElementSibling\n        if (!next) return\n        const name = button\n          .getAttribute('aria-label')\n          .replace(/^Move /, '')\n          .replace(/ down$/, '')\n        next.after(row)\n        ;[...list.children].forEach((row, index) => {\n          row.querySelector('.index').textContent = String(index + 1).padStart(2, '0')\n          row.querySelector('button').disabled = index === list.children.length - 1\n        })\n        button.focus()\n        document.querySelector('#status').textContent =\n          name + ' moved to position ' + ([...list.children].indexOf(row) + 1) + ' of 3.'\n      })\n      document.querySelector('#save').addEventListener('click', () => {\n        document.querySelector('#status').textContent = 'All changes saved.'\n      })\n    </script>\n  </body>\n</html>\n", "skills/record-pr-demo/scripts/preview/application.html": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <title>Sample collection list</title>\n  </head>\n  <body>\n    <style>\n      body {\n        color-scheme: light dark;\n        --bg: light-dark(#fff, #191919);\n        --ink: light-dark(#171717, #eee);\n        --sub: light-dark(#666, #aaa);\n        --line: light-dark(#ddd, #383838);\n        --soft: light-dark(#f6f6f6, #232323);\n      }\n      * {\n        box-sizing: border-box;\n      }\n      body {\n        display: block;\n        margin: 0;\n        background: var(--bg);\n        color: var(--ink);\n        font:\n          16px/1.5 system-ui,\n          sans-serif;\n      }\n      .app {\n        display: flex;\n        height: 720px;\n      }\n      .nav {\n        width: 205px;\n        border-right: 1px solid var(--line);\n        padding: 30px 20px;\n        flex-shrink: 0;\n      }\n      .brand {\n        font-size: 24px;\n        font-weight: 600;\n        margin-bottom: 42px;\n      }\n      .nav-item {\n        padding: 10px 12px;\n        color: var(--sub);\n        margin-bottom: 4px;\n      }\n      .active {\n        background: var(--soft);\n        color: var(--ink);\n        border-radius: 5px;\n      }\n      .nav-label {\n        font-size: 12px;\n        color: var(--sub);\n        padding: 10px 12px;\n      }\n      .main {\n        padding: 28px 40px;\n        flex: 1;\n        min-width: 0;\n      }\n      .crumb {\n        font-size: 13px;\n        color: var(--sub);\n        margin-bottom: 38px;\n      }\n      .heading {\n        display: flex;\n        align-items: center;\n        justify-content: space-between;\n        gap: 12px;\n        margin-bottom: 26px;\n      }\n      h1 {\n        font-size: 32px;\n        font-weight: 500;\n        margin: 0;\n        letter-spacing: -1px;\n      }\n      .create {\n        background: var(--ink);\n        color: var(--bg);\n        padding: 9px 16px;\n        border-radius: 5px;\n        white-space: nowrap;\n        font-size: 14px;\n      }\n      .search {\n        border: 1px solid var(--line);\n        padding: 12px;\n        border-radius: 5px;\n        color: var(--sub);\n        margin-bottom: 24px;\n        font-size: 14px;\n      }\n      .row {\n        display: grid;\n        grid-template-columns: minmax(0, 1fr) 120px 125px;\n        gap: 12px;\n        padding: 18px 12px;\n        border-bottom: 1px solid var(--line);\n        align-items: center;\n      }\n      .thead {\n        font-size: 13px;\n        color: var(--sub);\n        padding-block: 12px;\n      }\n      .status {\n        font-size: 13px;\n      }\n      .date {\n        color: var(--sub);\n        font-size: 13px;\n      }\n      .footer {\n        font-size: 13px;\n        color: var(--sub);\n        margin-top: 28px;\n      }\n      .menu {\n        display: none;\n      }\n      .title {\n        overflow-wrap: anywhere;\n      }\n      @media (max-width: 900px) {\n        .nav {\n          width: 170px;\n        }\n        .main {\n          padding: 28px 24px;\n        }\n        .row {\n          grid-template-columns: minmax(0, 1fr) 90px;\n        }\n        .date {\n          display: none;\n        }\n      }\n      @media (max-width: 600px) {\n        .nav {\n          display: none;\n        }\n        .main {\n          padding: 22px;\n        }\n        .menu {\n          display: inline;\n          margin-right: 14px;\n        }\n        .crumb {\n          margin-bottom: 32px;\n        }\n        .row {\n          grid-template-columns: minmax(0, 1fr) 76px;\n          padding-inline: 0;\n          gap: 8px;\n        }\n        h1 {\n          font-size: 29px;\n        }\n        .create {\n          padding: 8px 12px;\n        }\n        .search {\n          margin-bottom: 18px;\n        }\n      }\n    </style>\n    <div class=\"app\">\n      <aside class=\"nav\">\n        <div class=\"brand\">◧ Payload</div>\n        <div class=\"nav-label\">COLLECTIONS</div>\n        <div class=\"nav-item active\">Posts</div>\n        <div class=\"nav-item\">Media</div>\n        <div class=\"nav-item\">Users</div>\n        <div class=\"nav-label\" style=\"margin-top: 24px\">GLOBALS</div>\n        <div class=\"nav-item\">Navigation</div>\n        <div class=\"nav-item\">Settings</div>\n      </aside>\n      <main class=\"main\">\n        <div class=\"crumb\"><span class=\"menu\">☰</span>Dashboard / Posts</div>\n        <div class=\"heading\">\n          <h1>Posts</h1>\n          <span class=\"create\">Create new</span>\n        </div>\n        <div class=\"search\">Search by title</div>\n        <div class=\"row thead\">\n          <span>Title</span><span>Status</span><span class=\"date\">Updated</span>\n        </div>\n        <div class=\"row\">\n          <span class=\"title\">Building with Payload</span><span class=\"status\">Published</span\n          ><span class=\"date\">Oct 15, 2026</span>\n        </div>\n        <div class=\"row\">\n          <span class=\"title\">A better editing experience</span><span class=\"status\">Draft</span\n          ><span class=\"date\">Oct 14, 2026</span>\n        </div>\n        <div class=\"row\">\n          <span class=\"title\">Introducing our new website</span><span class=\"status\">Published</span\n          ><span class=\"date\">Oct 12, 2026</span>\n        </div>\n        <div class=\"row\">\n          <span class=\"title\">What's coming next</span><span class=\"status\">Draft</span\n          ><span class=\"date\">Oct 10, 2026</span>\n        </div>\n        <div class=\"footer\">1–4 of 4 posts</div>\n      </main>\n    </div>\n  </body>\n</html>\n", "skills/record-pr-demo/scripts/preview/index.html": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <title>Recording chrome preview</title>\n    <style>\n      :root {\n        color-scheme: light;\n        font:\n          13px/1.5 system-ui,\n          sans-serif;\n        color: light-dark(#252422, #ededeb);\n        background: light-dark(#fff, #191919);\n        --control-line: light-dark(#dededb, #41413e);\n        --control-bg: light-dark(#f4f4f2, #252523);\n        --selected-bg: light-dark(#fff, #484845);\n      }\n      * {\n        box-sizing: border-box;\n      }\n      [hidden] {\n        display: none !important;\n      }\n      body {\n        max-width: 1120px;\n        margin: 16px auto;\n        padding: 0 16px;\n      }\n      button,\n      input,\n      select {\n        font: inherit;\n      }\n      button {\n        display: inline-flex;\n        align-items: center;\n        justify-content: center;\n        gap: 6px;\n        min-height: 32px;\n        padding: 4px 10px;\n        border: 1px solid var(--control-line);\n        border-radius: 6px;\n        background: var(--control-bg);\n        color: inherit;\n        cursor: pointer;\n      }\n      button:hover {\n        background: var(--selected-bg);\n      }\n      :is(button, input, select):focus-visible {\n        outline: 2px solid #0d99ff;\n        outline-offset: 2px;\n      }\n      .controls {\n        display: flex;\n        align-items: center;\n        flex-wrap: wrap;\n        gap: 8px;\n        padding: 8px;\n        margin-bottom: 12px;\n        border: 1px solid var(--control-line);\n        border-radius: 10px;\n        background: light-dark(#fafaf9, #20201e);\n      }\n      .presets {\n        display: flex;\n        align-items: center;\n        gap: 2px;\n        padding: 2px;\n        border: 1px solid var(--control-line);\n        border-radius: 7px;\n        background: var(--control-bg);\n      }\n      .icon-button {\n        width: 30px;\n        min-height: 30px;\n        padding: 6px;\n      }\n      .presets .icon-button {\n        border-color: transparent;\n        background: transparent;\n      }\n      .presets button[aria-pressed='true'] {\n        background: var(--selected-bg);\n        border-color: var(--control-line);\n        box-shadow: 0 1px 2px #0000000a;\n      }\n      .icon-button svg {\n        width: 16px;\n        height: 16px;\n        flex: none;\n      }\n      .toolbar-field {\n        display: flex;\n        align-items: center;\n        gap: 6px;\n        font-size: 12px;\n        color: light-dark(#66635e, #bbb8b0);\n      }\n      select {\n        height: 32px;\n        min-width: 76px;\n        border: 1px solid var(--control-line);\n        border-radius: 6px;\n        padding: 3px 6px;\n        color: light-dark(#252422, #ededeb);\n        background: var(--selected-bg);\n        cursor: pointer;\n      }\n      .toolbar-divider {\n        height: 22px;\n        width: 1px;\n        background: var(--control-line);\n        margin-inline: 2px;\n      }\n      .toggles {\n        display: flex;\n        flex-wrap: wrap;\n        gap: 8px;\n        margin-left: auto;\n      }\n      .check-toggle {\n        display: flex;\n        align-items: center;\n        gap: 5px;\n        min-height: 32px;\n        padding: 3px 6px;\n        border-radius: 6px;\n        font-size: 12px;\n        white-space: nowrap;\n        cursor: pointer;\n      }\n      .check-toggle:hover {\n        background: var(--control-bg);\n      }\n      input[type='checkbox'] {\n        width: 14px;\n        height: 14px;\n        margin: 0;\n        accent-color: light-dark(#252422, #ededeb);\n      }\n      .timeline {\n        display: grid;\n        grid-template-columns: auto minmax(0, 1fr) auto;\n        align-items: center;\n        gap: 12px;\n        margin-top: 12px;\n      }\n      .timeline input {\n        width: 100%;\n        min-height: 24px;\n        margin: 0;\n        accent-color: light-dark(#252422, #ededeb);\n      }\n      output {\n        font:\n          11px/1.5 ui-monospace,\n          monospace;\n        font-variant-numeric: tabular-nums;\n      }\n      .status {\n        color: light-dark(#66635e, #bbb8b0);\n        font-size: 11px;\n        margin-top: 8px;\n      }\n      #chrome {\n        overflow: hidden;\n      }\n      @media (max-width: 600px) {\n        .toggles {\n          margin-left: 0;\n        }\n        .toolbar-divider {\n          display: none;\n        }\n      }\n      @media (pointer: coarse) {\n        button,\n        select,\n        .check-toggle {\n          min-height: 44px;\n        }\n        .icon-button {\n          width: 44px;\n        }\n      }\n    </style>\n  </head>\n  <body>\n    <div class=\"controls\" aria-label=\"Preview controls\">\n      <div class=\"presets\" role=\"group\" aria-label=\"Window size\">\n        <button\n          type=\"button\"\n          class=\"icon-button\"\n          aria-label=\"Desktop\"\n          title=\"Desktop\"\n          data-width=\"1280\"\n          aria-pressed=\"true\"\n        >\n          <svg\n            viewBox=\"0 0 24 24\"\n            fill=\"none\"\n            stroke=\"currentColor\"\n            stroke-width=\"1.75\"\n            stroke-linecap=\"round\"\n            stroke-linejoin=\"round\"\n            aria-hidden=\"true\"\n            focusable=\"false\"\n          >\n            <rect x=\"3\" y=\"4\" width=\"18\" height=\"13\" rx=\"2\" />\n            <path d=\"M8 21h8m-4-4v4\" />\n          </svg></button\n        ><button\n          type=\"button\"\n          class=\"icon-button\"\n          aria-label=\"Tablet\"\n          title=\"Tablet\"\n          data-width=\"768\"\n          aria-pressed=\"false\"\n        >\n          <svg\n            viewBox=\"0 0 24 24\"\n            fill=\"none\"\n            stroke=\"currentColor\"\n            stroke-width=\"1.75\"\n            stroke-linecap=\"round\"\n            stroke-linejoin=\"round\"\n            aria-hidden=\"true\"\n            focusable=\"false\"\n          >\n            <rect x=\"5\" y=\"2\" width=\"14\" height=\"20\" rx=\"2\" />\n            <path d=\"M11 18h2\" />\n          </svg></button\n        ><button\n          type=\"button\"\n          class=\"icon-button\"\n          aria-label=\"Mobile\"\n          title=\"Mobile\"\n          data-width=\"390\"\n          aria-pressed=\"false\"\n        >\n          <svg\n            viewBox=\"0 0 24 24\"\n            fill=\"none\"\n            stroke=\"currentColor\"\n            stroke-width=\"1.75\"\n            stroke-linecap=\"round\"\n            stroke-linejoin=\"round\"\n            aria-hidden=\"true\"\n            focusable=\"false\"\n          >\n            <rect x=\"7\" y=\"2\" width=\"10\" height=\"20\" rx=\"2\" />\n            <path d=\"M11 18h2\" />\n          </svg>\n        </button>\n      </div>\n      <div class=\"presets\" role=\"group\" aria-label=\"Theme\">\n        <button\n          type=\"button\"\n          class=\"icon-button\"\n          aria-label=\"Light\"\n          title=\"Light\"\n          data-theme=\"light\"\n          aria-pressed=\"true\"\n        >\n          <svg\n            viewBox=\"0 0 24 24\"\n            fill=\"none\"\n            stroke=\"currentColor\"\n            stroke-width=\"1.75\"\n            stroke-linecap=\"round\"\n            stroke-linejoin=\"round\"\n            aria-hidden=\"true\"\n            focusable=\"false\"\n          >\n            <circle cx=\"12\" cy=\"12\" r=\"4\" />\n            <path\n              d=\"M12 2v2m0 16v2M2 12h2m16 0h2M5 5l1.5 1.5m11 11L19 19M5 19l1.5-1.5m11-11L19 5\"\n            />\n          </svg></button\n        ><button\n          type=\"button\"\n          class=\"icon-button\"\n          aria-label=\"Dark\"\n          title=\"Dark\"\n          data-theme=\"dark\"\n          aria-pressed=\"false\"\n        >\n          <svg\n            viewBox=\"0 0 24 24\"\n            fill=\"none\"\n            stroke=\"currentColor\"\n            stroke-width=\"1.75\"\n            stroke-linecap=\"round\"\n            stroke-linejoin=\"round\"\n            aria-hidden=\"true\"\n            focusable=\"false\"\n          >\n            <path d=\"M20.5 13A9 9 0 0 1 11 3.5 9 9 0 1 0 20.5 13Z\" />\n          </svg>\n        </button>\n      </div>\n      <span class=\"toolbar-divider\" aria-hidden=\"true\"></span>\n      <label class=\"toolbar-field\"\n        ><span>Demo</span\n        ><select id=\"change-kind\" aria-label=\"Demo type\">\n          <option value=\"feature\">Feature</option>\n          <option value=\"fix\">Fix</option>\n          <option value=\"bug\">Bug</option>\n        </select></label\n      >\n      <div class=\"toggles\">\n        <label class=\"check-toggle\"><input type=\"checkbox\" id=\"many-steps\" />Many steps</label>\n        <label class=\"check-toggle\"\n          ><input type=\"checkbox\" id=\"annotation\" checked />Annotation</label\n        >\n      </div>\n    </div>\n    <div id=\"chrome\"></div>\n    <div class=\"timeline\">\n      <button type=\"button\" id=\"play\">Play resize</button>\n      <input\n        id=\"timeline\"\n        type=\"range\"\n        min=\"0\"\n        max=\"5200\"\n        step=\"1\"\n        value=\"0\"\n        aria-label=\"Resize timeline in milliseconds\"\n      />\n      <output id=\"time\" for=\"timeline\">0.00 / 5.20 s</output>\n    </div>\n    <div class=\"status\" id=\"status\" aria-live=\"polite\">\n      Window: 1280 × 720. Canvas: 1600 × 1000.\n    </div>\n    <script type=\"module\" src=\"/preview/index.mjs\"></script>\n  </body>\n</html>\n", "skills/record-pr-demo/scripts/preview/index.mjs": "import { bindDemoHistory, getDefaultCanvas, mountDemoChrome } from '../WindowChrome/index.mjs'\nimport { mountAnnotationSidebar } from '../WindowChrome/sidebar.mjs'\nimport { observeAccessibility } from '../accessibility-demo.mjs'\n\nconst isAccessibility = new URLSearchParams(location.search).has('accessibility')\n\nlet theme = new URLSearchParams(location.search).get('theme') === 'dark' ? 'dark' : 'light'\n\nconst canvas = getDefaultCanvas({ viewport: { width: 1280, height: 720 } })\nconst root = document.querySelector('#chrome')\nconst application = document.createElement('iframe')\nconst change = {\n  kind:\n    { feature: 'Feature', fix: 'Fix', bug: 'Bug' }[\n      new URLSearchParams(location.search).get('kind')\n    ] ?? 'Feature',\n  title: isAccessibility ? 'Make keyboard interactions visible' : 'Responsive collection lists',\n  description: isAccessibility\n    ? 'Follow keyboard input and movement announcements.'\n    : 'Browse and manage content on desktop, tablet, and mobile.',\n}\nconst chrome = mountDemoChrome({\n  onNavigate: (direction) => application.contentWindow.history.go(direction),\n  onRefresh: refreshApplication,\n  root,\n  canvas,\n  accessibility: isAccessibility,\n  showAnnouncements: new URLSearchParams(location.search).has('announcements'),\n  theme,\n})\napplication.slot = 'content'\napplication.title = 'Responsive sample application'\napplication.src = isAccessibility\n  ? '/preview/accessibility-application.html'\n  : '/preview/application.html'\nbindDemoHistory({ app: application, chrome })\nlet stopAccessibility\nif (isAccessibility)\n  application.addEventListener('load', () => {\n    stopAccessibility?.()\n    stopAccessibility = observeAccessibility({\n      window: application.contentWindow,\n      report: (state) => chrome.setAccessibilityState(state),\n    })\n  })\nfunction applyTheme() {\n  chrome.setTheme(theme)\n  document.documentElement.style.colorScheme = theme\n  if (application.contentDocument?.body) {\n    application.contentDocument.documentElement.style.colorScheme = theme\n    application.contentDocument.body.style.colorScheme = theme\n  }\n  document.querySelectorAll('[data-theme]').forEach((button) => {\n    button.setAttribute('aria-pressed', String(button.dataset.theme === theme))\n  })\n}\napplication.addEventListener('load', applyTheme)\ndocument.querySelectorAll('[data-theme]').forEach((button) => {\n  button.addEventListener('click', () => {\n    theme = button.dataset.theme\n    const url = new URL(location.href)\n    url.searchParams.set('theme', theme)\n    history.replaceState(null, '', url)\n    applyTheme()\n  })\n})\napplyTheme()\nconst changeKind = document.querySelector('#change-kind')\nchangeKind.value = new URLSearchParams(location.search).get('kind') ?? 'feature'\nchangeKind.addEventListener('change', () => {\n  const url = new URL(location.href)\n  url.searchParams.set('kind', changeKind.value)\n  location.href = url.href\n})\nroot.append(application)\nconst timeline = document.querySelector('#timeline')\nconst play = document.querySelector('#play')\nconst timelineDuration = 5200\nconst tabletArrival = 1600\nconst tabletDeparture = 2800\nconst mobileArrival = 4000\nlet time = 0\nlet animation\nlet width = 1280\n\nconst steps = [\n  {\n    title: 'See the full picture',\n    body: 'View post titles, publishing status, and update dates together.',\n  },\n  {\n    kind: 'Bug',\n    title: 'Keep essential details visible',\n    body: 'Update dates hide as space narrows; titles and status remain.',\n  },\n  {\n    title: 'Make room for content',\n    body: 'The sidebar collapses so the post list can use the full width.',\n  },\n]\nconst manySteps = document.querySelector('#many-steps')\nmanySteps.checked = new URLSearchParams(location.search).has('manySteps')\nif (manySteps.checked) {\n  steps.push(\n    {\n      title: 'Review field spacing',\n      body: 'Check that labels and values have room at smaller widths.',\n    },\n    {\n      title: 'Inspect the collection navigation',\n      body: 'Keep the collection links available while browsing content.',\n    },\n    {\n      title: 'Compare publishing statuses',\n      body: 'Published and draft items stay easy to distinguish.',\n    },\n    {\n      kind: 'Bug',\n      title: 'Check longer document titles',\n      body: 'Long names should remain readable within the list.',\n    },\n    { title: 'Review row actions', body: 'Keep the actions close to the document they belong to.' },\n    {\n      title: 'Inspect the mobile layout',\n      body: 'Confirm the list makes good use of a narrow window.',\n    },\n    {\n      title: 'Return to the collection overview',\n      body: 'Review the overall layout after checking individual details.',\n    },\n    {\n      title: 'Compare the available themes',\n      body: 'Check text and controls against both light and dark backgrounds.',\n    },\n    {\n      title: 'Finish the walkthrough',\n      body: 'The current step stays visible while earlier steps remain available above.',\n    },\n  )\n}\nmanySteps.addEventListener('change', () => {\n  const url = new URL(location.href)\n  if (manySteps.checked) url.searchParams.set('manySteps', '')\n  else url.searchParams.delete('manySteps')\n  location.href = url.href\n})\nconst sidebar = mountAnnotationSidebar({\n  root,\n  change,\n  steps,\n  onSelect: (index) => {\n    renderAt({\n      milliseconds: manySteps.checked\n        ? (index * timelineDuration) / steps.length + 1\n        : [0, tabletArrival, mobileArrival][index],\n    })\n    stop()\n  },\n})\n\nfunction renderAt({ milliseconds }) {\n  time = Math.max(0, Math.min(timelineDuration, milliseconds))\n  const isFirstResize = time <= tabletArrival\n  const progress = Math.max(0, Math.min(1, (time - (isFirstResize ? 400 : tabletDeparture)) / 1200))\n  const eased = progress * progress * (3 - 2 * progress)\n  width = Math.round(isFirstResize ? 1280 - 512 * eased : 768 - 378 * eased)\n  chrome.setViewport({ width, height: 720 })\n  const stepIndex = manySteps.checked\n    ? Math.min(steps.length - 1, Math.floor((time / timelineDuration) * steps.length))\n    : time < tabletArrival\n      ? 0\n      : time < mobileArrival\n        ? 1\n        : 2\n  const step = { ...steps[stepIndex], index: stepIndex + 1 }\n  sidebar.setAnnotation(\n    document.querySelector('#annotation').checked ? { ...step, total: steps.length } : null,\n  )\n  timeline.value = String(time)\n  document.querySelector('#time').textContent =\n    `${(time / 1000).toFixed(2)} / ${(timelineDuration / 1000).toFixed(2)} s`\n  document.querySelectorAll('[data-width]').forEach((button) => {\n    button.setAttribute('aria-pressed', String(Number(button.dataset.width) === width))\n  })\n}\nfunction stop() {\n  cancelAnimationFrame(animation)\n  animation = undefined\n  play.textContent = 'Play resize'\n  document.querySelector('#status').textContent =\n    `Window: ${width} × 720. Canvas: ${canvas.width} × ${canvas.height}.`\n}\ndocument.querySelectorAll('[data-width]').forEach((button) =>\n  button.addEventListener('click', () => {\n    const target = Number(button.dataset.width)\n    renderAt({\n      milliseconds: target === 1280 ? 0 : target === 768 ? tabletArrival : timelineDuration,\n    })\n    stop()\n  }),\n)\ntimeline.addEventListener('input', () => {\n  renderAt({ milliseconds: Number(timeline.value) })\n  stop()\n})\ndocument\n  .querySelector('#annotation')\n  .addEventListener('change', () => renderAt({ milliseconds: time }))\nplay.addEventListener('click', () => {\n  if (animation !== undefined) {\n    stop()\n    return\n  }\n  if (matchMedia('(prefers-reduced-motion: reduce)').matches) {\n    renderAt({ milliseconds: timelineDuration })\n    stop()\n    return\n  }\n  const start = performance.now()\n  const offset = time >= timelineDuration ? 0 : time\n  play.textContent = 'Pause'\n  const tick = (now) => {\n    renderAt({ milliseconds: offset + now - start })\n    if (time < timelineDuration) animation = requestAnimationFrame(tick)\n    else stop()\n  }\n  animation = requestAnimationFrame(tick)\n})\nrenderAt({ milliseconds: 0 })\nstop()\n\nlet isRefreshing = false\n\nasync function refreshApplication() {\n  if (isRefreshing) return\n  isRefreshing = true\n  chrome.setRefreshState({ state: 'refreshing' })\n  try {\n    const loaded = new Promise((resolve) =>\n      application.addEventListener('load', resolve, { once: true }),\n    )\n    application.contentWindow.location.reload()\n    await loaded\n    chrome.setRefreshState({ state: 'refreshed' })\n  } catch {\n    chrome.setRefreshState({ state: 'failed' })\n  } finally {\n    isRefreshing = false\n  }\n}\n", "skills/respond-to-discussion-features/SKILL.md": "---\nname: respond-to-discussion-features\ndescription: '---'\n---\n\n---\ndescription: Find GitHub discussions resolved by recent releases and draft response comments to inform the community.\nargument-hint: <time-period> (default: 2months, e.g., \"3months\", \"6weeks\", \"2025-11-01\")\nallowed-tools: Bash(gh release list:*, gh release view:*, gh api graphql:*), Glob, Grep, Read, Write, TodoWrite\n---\n\n# Respond to Community\n\nFind open GitHub discussions in \"Feature Requests & Ideas\" that have been resolved by recent releases, and generate draft comments to post.\n\n## Arguments\n\n- `$ARGUMENTS` - Time period to analyze (default: `2months`)\n- Accepts: `Ndays`, `Nweeks`, `Nmonths`, or ISO date `YYYY-MM-DD`\n\n## Process\n\n### Step 1: Setup & Fetch Releases\n\n1. Parse time period from `$ARGUMENTS` (default: 2months)\n2. Create TodoWrite with: Fetch releases | Parse release notes | Fetch discussions | Match features to discussions | Generate output\n3. Run `gh release list --repo payloadcms/payload --limit 30` to get recent releases\n4. Filter to releases within the time period\n5. For each release, fetch notes: `gh release view <tag> --repo payloadcms/payload --json body -q '.body'`\n\n### Step 2: Parse Release Notes\n\n1. Extract feature and fix entries from each release:\n   - Lines containing `feat:` or `feat(`\n   - Lines containing `fix:` or `fix(`\n2. For each entry, capture:\n   - PR title (the description text)\n   - PR number (from `#NNNN` pattern)\n   - Package scope if present (from `feat(scope):` pattern)\n   - Version it shipped in\n3. Build keyword list from titles (feature names, package names, key terms)\n\n### Step 3: Fetch Discussions\n\n1. Use GraphQL to paginate through all open Feature Request discussions:\n\n```\ngh api graphql -f query='\n{\n  repository(owner: \"payloadcms\", name: \"payload\") {\n    discussions(first: 100, states: OPEN, categoryId: \"MDE4OkRpc2N1c3Npb25DYXRlZ29yeTMyMzY4NTUx\", orderBy: {field: CREATED_AT, direction: DESC}) {\n      pageInfo { hasNextPage endCursor }\n      nodes {\n        number\n        title\n        url\n        createdAt\n        body\n      }\n    }\n  }\n}'\n```\n\n2. Continue paginating with `after: \"<endCursor>\"` until all discussions fetched\n3. Store: number, title, URL, createdAt, body (for matching)\n\n### Step 4: Match Features to Discussions\n\nFor each feature/fix from releases:\n\n1. Search discussion titles and bodies for keyword matches\n2. Consider semantic variations (e.g., \"groupBy\" matches \"group by\", \"group-by\")\n3. Filter: only include if discussion was created BEFORE the feature's release date\n4. Score matches by keyword overlap\n5. Flag ambiguous matches as \"Needs Verification\"\n\nMultiple discussions can match the same PR - include all matches.\n\n### Step 5: Generate Output\n\n1. Create output directory if needed: `.claude/artifacts/`\n2. Generate markdown file: `.claude/artifacts/community-response-YYYY-MM-DD.md`\n\n**Output structure:**\n\n```markdown\n# Community Response: Features Shipped [start date] → [end date]\n\n## Summary\n\nFound **N discussions** resolved by releases vX.XX.X → vX.XX.X\n\n## Matches\n\n| Discussion Title | Discussion Link                                        | PR Title   | PR Link                                         |\n| ---------------- | ------------------------------------------------------ | ---------- | ----------------------------------------------- |\n| [title]          | https://github.com/payloadcms/payload/discussions/NNNN | [pr title] | https://github.com/payloadcms/payload/pull/NNNN |\n\n## Draft Comments\n\n### 1. [Discussion Title]\n\n**Link:** https://github.com/payloadcms/payload/discussions/NNNN\n\n> [Draft comment]\n\n---\n```\n\n**Comment template:**\n\n- Lead with \"Shipped in vX.XX.X 🎉\" or \"Fixed in vX.XX.X 🎉\"\n- Brief description of what shipped (1-2 sentences)\n- Code example if the feature involves configuration\n- PR link at the end\n- Keep concise: 3-6 lines typical\n\n3. Present summary to user: \"Found N matches. Output written to .claude/artifacts/community-response-YYYY-MM-DD.md\"\n\n## Edge Cases\n\n| Scenario                             | Action                                        |\n| ------------------------------------ | --------------------------------------------- |\n| No `$ARGUMENTS`                      | Use default: 2months                          |\n| No releases in time period           | Report \"No releases found\" and stop           |\n| No matches found                     | Create output with \"No matches found\" message |\n| API rate limited                     | Report error, suggest waiting and retrying    |\n| Ambiguous match                      | Include with \"⚠️ Needs Verification\" note     |\n| Discussion already has team response | Include anyway - human reviewer will skip     |\n\n## Remember\n\n- Create TodoWrite with 5 steps upfront\n- Mark steps in_progress before starting, completed after finishing\n- Full URLs in output table (not just issue numbers)\n- Comments should be helpful and concise\n- Better to surface a false positive than miss a real match\n- Human will review before posting - don't need to be perfect\n- Auto-save to `.claude/artifacts/` directory\n", "skills/triage/SKILL.md": "---\nname: triage\ndescription: Triage a GitHub issue and present findings on validity, code locations,\n  and optionally create a failing test or resolution plan.\nargument-hint: <issue-number-or-url>\nallowed-tools: Bash(gh issue view:*), Task, TodoWrite, Write, AskUserQuestion\n---\n\n# Triage GitHub Issue\n\nQuickly triage GitHub issues to determine validity and identify where the issue exists in code. Do not write code during triage.\n\n## Process\n\n### Step 1: Validate & Fetch\n\n1. Check if `$ARGUMENTS` provided - if missing, ask user and stop\n2. Create TodoWrite with: Fetch and validate issue data | Investigate codebase | Analyze validity and generate report | Offer next steps\n3. Fetch issue data: `gh issue view $ARGUMENTS --json author,title,number,body,comments,labels,url`\n4. If command fails: Inform user and stop\n5. Extract title, body, comments, labels, state, URL\n6. Verify issue has sufficient info to investigate\n\n### Step 2: Investigate\n\n1. Use Task tool with subagent_type=Explore to examine relevant parts of codebase\n2. Think step by step through the code paths involved until you understand the relevant files, functions, and logic\n3. Focus on understanding the problem space before judging validity\n\n### Step 3: Analyze & Report\n\n1. Think step by step about whether this issue is valid - be critical and consider alternative explanations\n2. Determine verdict: Valid | Invalid | Needs Info\n3. Determine confidence: High | Medium | Low\n4. If valid: Think deeply about the root cause before proposing fix direction\n5. Generate findings using output structure below\n6. Auto-save to `.claude/artifacts/triage-<issue-number>.md`\n7. Present findings to user\n\n### Step 4: Offer Next Steps\n\nUse AskUserQuestion with multiSelect: true:\n\n\"What would you like to do next?\"\n\n- **Create failing test** - Write integration test that reproduces the issue\n- **Create resolution plan** - Generate full plan using `/superpowers:write-plan`\n- **Done for now** - End triage\n\nIf user selects test: Write an integration test that reproduces the issue.\nIf user selects plan: Use `/superpowers:write-plan` to create detailed implementation plan.\n\n## Output Structure\n\n```markdown\n# Triage: #<issue-number> - <title>\n\n**Verdict:** Valid | Invalid | Needs Info\n**Confidence:** High | Medium | Low\n\n## Problem\n\n1-2 sentences on what's broken and why.\n\n## Reproduction\n\nSteps to reproduce from investigation:\n\n1. ...\n2. ...\n\n## Code Locations\n\n- `path/file.ts:123` - what's here\n- `path/other.ts:456` - related\n\n## Fix Direction\n\nBrief hints on potential approach (not full plan):\n\n- Consider X\n- May need to change Y\n\n## Issue Link\n\n<url>\n```\n\n## When to Stop\n\n**STOP immediately when:**\n\n- `$ARGUMENTS` not provided (ask for it)\n- `gh issue view` command fails\n- Issue not found or inaccessible\n- Cannot understand issue after investigation\n- Insufficient information to determine validity\n\n**Ask for clarification rather than guessing.**\n\n## Remember\n\n- Create TodoWrite with 4 steps upfront\n- Mark steps in_progress before starting, completed after finishing\n- Use Explore agent for investigation\n- Be critical about issue validity\n- Auto-save findings to `.claude/artifacts/`\n- Single question at end with multi-select options\n- DO NOT write code during triage (tests come after, if requested)\n- Stop when blocked, don't guess\n", "skills/triage-ci-flake/SKILL.md": "---\nname: triage-ci-flake\ndescription: Use when CI tests fail on main branch after PR merge, when investigating flaky test failures, or when user provides a PR URL/number to aggregate all failing tests\nallowed-tools: Write, Bash(date:*), Bash(mkdir -p *)\ndisable-model-invocation: true\n---\n\n# Triage CI Failure\n\n## Overview\n\nSystematic workflow designed specifically for triaging and fixing end-to-end (e2e) test failures in CI, especially flaky Playwright tests that pass locally but fail in CI. E2E tests that made it to `main` are usually flaky due to timing, bundling, or environment differences.\n\n**CRITICAL RULE: You MUST run the reproduction workflow before proposing any fixes. No exceptions.**\n\n## When to Use\n\n- CI test fails on `main` branch after PR was merged\n- Test passes locally but fails in CI\n- Test failure labeled as \"flaky\" or intermittent\n- E2E test timing out in CI only\n- User provides a PR URL/number with failing checks\n\n## PR-Based Workflow (When PR URL/Number Provided)\n\nWhen the user provides a PR URL (e.g., `https://github.com/payloadcms/payload/pull/16701`) or PR number:\n\n### Step 1: Fetch PR Status Checks\n\nFirst, use `tool_search` with query \"github pull request status checks\" to load the GitHub tools.\n\nThen use the `github-pull-request_pullRequestStatusChecks` tool to get all failing checks:\n\n```\nTool: github-pull-request_pullRequestStatusChecks\nParameters:\n  pullRequestNumber: <extracted from URL or provided>\n  repo: { owner: \"payloadcms\", name: \"payload\" }\n```\n\n### Step 2: Aggregate Failing Tests\n\nParse the status checks response and create a summary table:\n\n| Suite                 | Check Status | Target URL |\n| --------------------- | ------------ | ---------- |\n| admin**e2e**list-view | failed       | [link]     |\n| plugin-import-export  | failed       | [link]     |\n\nFor each failing check, the `context` field contains the test suite name (e.g., `admin__e2e__list-view`).\n\n### Step 3: Extract Failure Details from Each Check\n\nFor each failing check:\n\n1. Visit the `targetUrl` to get detailed failure logs\n2. Extract the specific test name and error message\n3. Add to the aggregated failure list\n\nPresent a consolidated summary:\n\n```markdown\n## Failing Tests Summary\n\n### 1. admin**e2e**list-view (3/4)\n\n- **Test**: \"should use custom pagination limit\"\n- **Error**: Locator `.per-page__button` not found\n- **File**: test/admin/e2e/list-view/e2e.spec.ts:1495\n\n### 2. plugin-import-export\n\n- **Test**: \"should inherit limit from list view URL\"\n- **Error**: Locator `.per-page__button` not found\n- **File**: test/plugin-import-export/e2e.spec.ts:150\n```\n\n### Step 4: Identify Common Patterns\n\nLook for patterns across failures:\n\n- Same selector errors → likely a component change needing test updates\n- Same test file → localized issue\n- Different errors in same suite → may be test pollution\n\n### Step 5: Proceed with Triage\n\nFor each unique failure, follow the standard reproduction workflow below.\n\n## MANDATORY First Steps\n\n**YOU MUST EXECUTE THESE COMMANDS. Reading code or analyzing logs does NOT count as reproduction.**\n\n1. **Extract** suite name, test name, and error from CI logs\n2. **EXECUTE**: Kill port 3000 to avoid conflicts\n3. **EXECUTE**: `pnpm dev $SUITE_NAME` (use run_in_background=true)\n4. **EXECUTE**: Wait for server to be ready (check with curl or sleep)\n5. **EXECUTE**: Run the specific failing test with Playwright directly (npx playwright test test/TEST_SUITE_NAME/e2e.spec.ts:31:3 --headed -g \"TEST_DESCRIPTION_TARGET_GOES_HERE\")\n6. **If test passes**, **EXECUTE**: `pnpm prepare-run-test-against-prod`\n7. **EXECUTE**: `pnpm dev:prod $SUITE_NAME` and run test again\n\n**Only after EXECUTING these commands and seeing their output** can you proceed to analysis and fixes.\n\n**\"Analysis from logs\" is NOT reproduction. You must RUN the commands.**\n\n## Core Workflow\n\n```dot\ndigraph triage_ci {\n    \"CI failure reported\" [shape=box];\n    \"Extract details from CI logs\" [shape=box];\n    \"Identify suite and test name\" [shape=box];\n    \"Run dev server: pnpm dev $SUITE\" [shape=box];\n    \"Run specific test by name\" [shape=box];\n    \"Did test fail?\" [shape=diamond];\n    \"Debug with dev code\" [shape=box];\n    \"Run prepare-run-test-against-prod\" [shape=box];\n    \"Run: pnpm dev:prod $SUITE\" [shape=box];\n    \"Run specific test again\" [shape=box];\n    \"Did test fail now?\" [shape=diamond];\n    \"Debug bundling issue\" [shape=box];\n    \"Unable to reproduce - check logs\" [shape=box];\n    \"Fix and verify\" [shape=box];\n\n    \"CI failure reported\" -> \"Extract details from CI logs\";\n    \"Extract details from CI logs\" -> \"Identify suite and test name\";\n    \"Identify suite and test name\" -> \"Run dev server: pnpm dev $SUITE\";\n    \"Run dev server: pnpm dev $SUITE\" -> \"Run specific test by name\";\n    \"Run specific test by name\" -> \"Did test fail?\";\n    \"Did test fail?\" -> \"Debug with dev code\" [label=\"yes\"];\n    \"Did test fail?\" -> \"Run prepare-run-test-against-prod\" [label=\"no\"];\n    \"Run prepare-run-test-against-prod\" -> \"Run: pnpm dev:prod $SUITE\";\n    \"Run: pnpm dev:prod $SUITE\" -> \"Run specific test again\";\n    \"Run specific test again\" -> \"Did test fail now?\";\n    \"Did test fail now?\" -> \"Debug bundling issue\" [label=\"yes\"];\n    \"Did test fail now?\" -> \"Unable to reproduce - check logs\" [label=\"no\"];\n    \"Debug with dev code\" -> \"Fix and verify\";\n    \"Debug bundling issue\" -> \"Fix and verify\";\n}\n```\n\n## Step-by-Step Process\n\n### 1. Extract CI Details\n\nFrom CI logs or GitHub Actions URL, identify:\n\n- **Suite name**: Directory name (e.g., `i18n`, `fields`, `lexical`)\n- **Test file**: Full path (e.g., `test/i18n/e2e.spec.ts`)\n- **Test name**: Exact test description\n- **Error message**: Full stack trace\n- **Test type**: E2E (Playwright)\n\n### 2. Reproduce with Dev Code\n\n**CRITICAL: Always run the specific test by name, not the full suite.**\n\n**SERVER MANAGEMENT RULES:**\n\n1. **ALWAYS kill all servers before starting a new one**\n2. **NEVER assume ports are free**\n3. **ALWAYS wait for server ready confirmation before running tests**\n\n```bash\n# ========================================\n# STEP 2A: STOP ALL SERVERS\n# ========================================\nlsof -ti:3000 | xargs kill -9 2>/dev/null || echo \"Port 3000 clear\"\n\n# ========================================\n# STEP 2B: START DEV SERVER\n# ========================================\n# Start dev server with the suite (in background with run_in_background=true)\npnpm dev $SUITE_NAME\n\n# ========================================\n# STEP 2C: WAIT FOR SERVER READY\n# ========================================\n# Wait for server to be ready (REQUIRED - do not skip)\nuntil curl -s http://localhost:3000/admin > /dev/null 2>&1; do sleep 1; done && echo \"Server ready\"\n\n# ========================================\n# STEP 2D: RUN SPECIFIC TEST\n# ========================================\n# Run ONLY the specific failing test using Playwright directly\n# For E2E tests (DO NOT use pnpm test:e2e as it spawns its own server):\npnpm exec playwright test test/$SUITE_NAME/e2e.spec.ts -g \"exact test name\"\n\n```\n\n**Did the test fail?**\n\n- ✅ **YES**: You reproduced it! Proceed to debug with dev code.\n- ❌ **NO**: Continue to step 3 (bundled code test).\n\n### 3. Reproduce with Bundled Code\n\nIf test passed with dev code, the issue is likely in bundled/production code.\n\n**IMPORTANT: You MUST stop the dev server before starting prod server.**\n\n```bash\n# ========================================\n# STEP 3A: STOP ALL SERVERS (INCLUDING DEV SERVER FROM STEP 2)\n# ========================================\nlsof -ti:3000 | xargs kill -9 2>/dev/null || echo \"Port 3000 clear\"\n\n# ========================================\n# STEP 3B: BUILD AND PACK FOR PROD\n# ========================================\n# Build all packages and pack them (this takes time - be patient)\npnpm prepare-run-test-against-prod\n\n# ========================================\n# STEP 3C: START PROD SERVER\n# ========================================\n# Start prod dev server (in background with run_in_background=true)\npnpm dev:prod $SUITE_NAME\n\n# ========================================\n# STEP 3D: WAIT FOR SERVER READY\n# ========================================\n# Wait for server to be ready (REQUIRED - do not skip)\nuntil curl -s http://localhost:3000/admin > /dev/null 2>&1; do sleep 1; done && echo \"Server ready\"\n\n# ========================================\n# STEP 3E: RUN SPECIFIC TEST\n# ========================================\n# Run the specific test again using Playwright directly\npnpm exec playwright test test/$SUITE_NAME/e2e.spec.ts -g \"exact test name\"\n```\n\n**Did the test fail now?**\n\n- ✅ **YES**: Bundling or production build issue. Look for:\n  - Missing exports in package.json\n  - Build configuration problems\n  - Code that behaves differently when bundled\n- ❌ **NO**: Unable to reproduce locally. Proceed to step 4.\n\n### 4. Unable to Reproduce\n\nIf you cannot reproduce locally after both attempts:\n\n- Review CI logs more carefully for environment differences\n- Check for race conditions (run test multiple times: `for i in {1..10}; do pnpm test:e2e...; done`)\n- Look for CI-specific constraints (memory, CPU, timing)\n- Consider if it's a true race condition that's highly timing-dependent\n\n## Common Flaky Test Patterns\n\n### Race Conditions\n\n- Page navigating while assertions run\n- Network requests not settled before assertions\n- State updates not completed\n\n**Fix patterns:**\n\n- Use Playwright's web-first assertions (`toBeVisible()`, `toHaveText()`)\n- Wait for specific conditions, not arbitrary timeouts\n- Use `waitForFunction()` with condition checks\n\n### Test Pollution\n\n- Tests leaving data in database\n- Shared state between tests\n- Missing cleanup in `afterEach`\n\n**Fix patterns:**\n\n- Track created IDs and clean up in `afterEach`\n- Use isolated test data\n- Don't use `deleteAll` that affects other tests\n\n### Timing Issues\n\n- `setTimeout`/`sleep` instead of condition-based waiting\n- Not waiting for page stability\n- Animations/transitions not complete\n\n**Fix patterns:**\n\n- Use `waitForPageStability()` helper\n- Wait for specific DOM states\n- Use Playwright's built-in waiting mechanisms\n\n## Linting Considerations\n\nWhen fixing e2e tests, be aware of these eslint rules:\n\n- `playwright/no-networkidle` - Avoid `waitForLoadState('networkidle')` (use condition-based waiting instead)\n- `payload/no-wait-function` - Avoid custom `wait()` functions (use Playwright's built-in waits)\n- `payload/no-flaky-assertions` - Avoid non-retryable assertions\n- `playwright/prefer-web-first-assertions` - Use built-in Playwright assertions\n\n**Existing code may violate these rules** - when adding new code, follow the rules even if existing code doesn't.\n\n## Verification\n\nAfter fixing:\n\n```bash\n# Ensure dev server is running on port 3000\n# Run test multiple times to confirm stability\nfor i in {1..10}; do\n  pnpm exec playwright test test/$SUITE_NAME/e2e.spec.ts -g \"exact test name\" || break\ndone\n\n# Run full suite\npnpm exec playwright test test/$SUITE_NAME/e2e.spec.ts\n\n# If you modified bundled code, test with prod build\nlsof -ti:3000 | xargs kill -9 2>/dev/null\npnpm prepare-run-test-against-prod\npnpm dev:prod $SUITE_NAME\nuntil curl -s http://localhost:3000/admin > /dev/null; do sleep 1; done\npnpm exec playwright test test/$SUITE_NAME/e2e.spec.ts\n```\n\n## The Iron Law\n\n**NO FIX WITHOUT REPRODUCTION FIRST**\n\nIf you propose a fix before completing steps 1-3 of the workflow, you've violated this skill.\n\n**This applies even when:**\n\n- The fix seems obvious from the logs\n- You've seen this error before\n- Time pressure from the team\n- You're confident about the root cause\n- The logs show clear stack traces\n\n**No exceptions. Run the reproduction workflow first.**\n\n## Rationalization Table\n\nEvery excuse for skipping reproduction, and why it's wrong:\n\n| Rationalization                      | Reality                                        |\n| ------------------------------------ | ---------------------------------------------- |\n| \"The logs show the exact error\"      | Logs show symptoms, not root cause. Reproduce. |\n| \"I can see the problem in the code\"  | You're guessing. Reproduce to confirm.         |\n| \"This is obviously a race condition\" | Maybe. Reproduce to be sure.                   |\n| \"I've seen this error before\"        | This might be different. Reproduce.            |\n| \"The stack trace is clear\"           | Stack trace shows where, not why. Reproduce.   |\n| \"Time pressure - need to fix fast\"   | Reproducing IS fast. Guessing wastes time.     |\n| \"The test file shows the issue\"      | Reading ≠ running. Execute the commands.       |\n| \"I'll analyze the code first\"        | Code analysis comes AFTER reproduction.        |\n| \"Let me investigate the root cause\"  | Reproduction IS the investigation.             |\n| \"I need to understand the error\"     | Understanding comes from seeing it fail.       |\n\n## Red Flags - STOP\n\nThese thoughts mean you're about to violate the skill:\n\n- \"Let me just fix the obvious issue\" → STOP. Execute reproduction first.\n- \"I'll increase the timeout\" → STOP. Find root cause via reproduction.\n- \"This looks like X from the logs\" → STOP. Run the test.\n- \"I'll run the full suite\" → STOP. Run specific test first.\n- \"Let me check the code\" → STOP. Run reproduction first.\n- \"I can see the problem in the stack trace\" → STOP. Reproduce to confirm.\n- \"The logs are clear enough\" → STOP. Execute the commands.\n- \"Let me analyze...\" → STOP. Analysis comes after reproduction.\n\n**All of these mean: Stop immediately. Execute the reproduction commands. No analysis without execution.**\n\n## Example Session\n\n**CORRECT approach - executes commands first:**\n\n```\nUser: CI failed on i18n suite - https://github.com/.../actions/runs/XXX\n\nAgent:\n1. Extracted details from CI logs:\n   - Suite: i18n\n   - Test: \"ensure translations update correctly when switching language\"\n   - File: test/i18n/e2e.spec.ts:124\n   - Error: \"Error loading language: en\" TypeError: network error\n\n2. Executing reproduction workflow:\n   [Uses Bash tool to kill ports]\n   $ lsof -ti:3000 | xargs kill -9 2>/dev/null || echo \"Port 3000 clear\"\n\n   [Uses Bash tool with run_in_background=true]\n   $ pnpm dev i18n\n\n   [Waits for server to start with curl check]\n   $ until curl -s http://localhost:3000/admin > /dev/null; do sleep 1; done && echo \"Server ready\"\n\n   [Uses Bash tool to run Playwright directly]\n   $ pnpm exec playwright test test/i18n/e2e.spec.ts -g \"ensure translations update correctly when switching language\"\n\n   Output shows: Test PASSED locally\n\n3. Test passed with dev code, trying bundled code:\n   [Kills ports again]\n   $ lsof -ti:3000 | xargs kill -9 2>/dev/null\n\n   [Uses Bash tool]\n   $ pnpm prepare-run-test-against-prod\n\n   [Uses Bash tool with run_in_background=true]\n   $ pnpm dev:prod i18n\n\n   [Waits for server]\n   $ until curl -s http://localhost:3000/admin > /dev/null; do sleep 1; done\n\n   [Uses Bash tool]\n   $ pnpm exec playwright test test/i18n/e2e.spec.ts -g \"ensure translations update correctly when switching language\"\n\n   Output shows: Test FAILED - reproduced!\n\n4. Now that I've reproduced it, analyzing the failure...\n   [Code analysis, root cause identification]\n\n5. Implementing fix: [specific changes]\n\n6. Verification:\n   [Uses Bash tool]\n   $ for i in {1..10}; do pnpm test:e2e i18n -g \"exact test\"; done\n   All 10 runs passed!\n```\n\n**INCORRECT approach - analyzes without executing:**\n\n```\nUser: CI failed on i18n suite\n\nAgent: Looking at the error logs, I can see this is a race condition...\n[Analyzes code, proposes fix without running any commands]\n\n❌ WRONG - This violates the skill. Must execute reproduction commands first.\n```\n\n## Common Mistakes\n\n| Mistake                           | Fix                                                      |\n| --------------------------------- | -------------------------------------------------------- |\n| Running full test suite first     | Run specific test by name                                |\n| Skipping dev code reproduction    | Always try dev code first                                |\n| Not testing with bundled code     | If dev passes, test with `prepare-run-test-against-prod` |\n| Proposing fix without reproducing | Follow the workflow - reproduce first                    |\n| Using `networkidle` in new code   | Use condition-based waiting with `waitForFunction()`     |\n| Adding arbitrary `wait()` calls   | Use Playwright's built-in assertions and waits           |\n\n## Key Principles\n\n1. **Reproduce before fixing**: Never propose a fix without reproducing the issue\n2. **Test specifically**: Run the exact failing test, not the full suite\n3. **Dev first, prod second**: Check dev code before bundled code\n4. **Follow the workflow**: No shortcuts - the steps exist to save time\n5. **Verify stability**: Run tests multiple times to confirm fix\n\n## Completion: Creating a PR\n\n**After you have:**\n\n1. ✅ Reproduced the issue\n2. ✅ Implemented a fix\n3. ✅ Verified the fix passes locally (multiple runs)\n4. ✅ Tested with prod build (if applicable)\n\n**You MUST prompt the user to create a PR:**\n\n```\nThe fix has been verified and is ready for review. Would you like me to create a PR with these changes?\n\nSummary of changes:\n- [List files modified]\n- [Brief description of the fix]\n- [Verification results]\n```\n\n**IMPORTANT:**\n\n- **DO NOT automatically create a PR** - always ask the user first\n- Provide a clear summary of what was changed and why\n- Include verification results (number of test runs, pass rate)\n- Let the user decide whether to create the PR immediately or make additional changes first\n\nThis ensures the user has visibility and control over what gets submitted for review.\n", "skills/triage-ci-flake/agents/openai.yaml": "policy:\n  allow_implicit_invocation: false\n", "skills/ui4/SKILL.md": "---\nname: ui4\ndescription: 'Manually invoked skill for reskinning Payload UI components. Requires Figma URL. Usage: /ui4'\n---\n\n# Payload UI Reskin (ui4)\n\n**Figma URL is REQUIRED.** If not provided, ask before proceeding.\n\n---\n\n## Process\n\n### Step 0: Icon Scan\n\n**Goal:** Identify icon dependencies before starting work.\n\n1. **Scan component files** for icon imports:\n\n   ```\n   grep -E \"from.*icons|import.*Icon\" packages/ui/src/elements/ComponentName/\n   ```\n\n2. **List existing icons** in `packages/ui/src/icons/`:\n\n   - Each icon has its own folder with `index.tsx` + `index.css`\n\n3. **Compare Figma design** to available icons:\n\n   - Does the design use icons not currently in the component?\n   - Does the design use icons that don't exist yet?\n\n4. **Document findings:**\n   - **Existing & used:** No action needed\n   - **Existing but not imported:** Will need to add import\n   - **Missing from codebase:** Flag for user — need to source/create icon\n\n**Figma Icons Source:**\n\nWhen updating or creating icons, reference the Figma icon library at:\n\n```\n~/figma/figma/fpl/icons/src/icons/\n```\n\nIcon naming convention: `icon-{size}-{name}.tsx` (e.g., `icon-16-close.tsx`, `icon-24-chevron-down.tsx`)\n\nTo find the correct icon:\n\n1. Note the icon name from Figma design (e.g., \"close\", \"chevron-down\")\n2. Check both 16px and 24px variants if they exist\n3. Read the corresponding files and extract the SVG paths for each size\n\n**Icon implementation rules:**\n\n1. **Props:** Icon components MUST accept these props (keep existing props when updating):\n\n   ```typescript\n   type IconProps = {\n     readonly className?: string\n     readonly size?: 16 | 24 // Add more sizes as needed\n     // ... keep any existing component-specific props\n   }\n   ```\n\n2. **Multi-size support:** Store path data keyed by size:\n\n   ```typescript\n   const paths = {\n     16: 'M4.854 4.146...', // from icon-16-{name}.tsx\n     24: 'M6.854 6.146...', // from icon-24-{name}.tsx\n   }\n   ```\n\n3. **SVG rendering:** Use the size prop to select path and viewBox:\n\n   ```tsx\n   <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} fill=\"none\">\n     <path d={paths[size]} fill=\"currentColor\" />\n   </svg>\n   ```\n\n4. **Payload conventions:**\n\n   - Use `fill=\"currentColor\"` instead of `fill=\"var(--color-icon)\"`\n   - Use `fillRule` and `clipRule` (React camelCase) instead of kebab-case\n   - Default size should match most common usage (typically 24)\n\n5. **Reference implementation:** See `packages/ui/src/icons/Chevron/index.tsx` for the pattern.\n\n**If icons are missing from Figma source:** Ask user how to proceed before continuing.\n\n---\n\n### Step 1: SCSS → CSS Migration\n\n**Goal:** Syntax conversion only. Component must look IDENTICAL after.\n\n1. Read component files: `packages/ui/src/elements/ComponentName/` or `packages/ui/src/fields/ComponentName/`\n2. Create `index.css` with converted styles:\n   - `$var` → `var(--token)`\n   - Keep CSS nesting with `&` (preferred)\n   - Remove `@use`/`@import` (tokens are global)\n   - Inline any mixins\n3. Update import: `import './index.scss'` → `import './index.css'`\n4. Delete `index.scss`\n5. Wrap in `@layer payload-default {}`\n6. **Convert legacy `var(--base)` to `--spacer` tokens** (see below)\n7. **Check for SCSS-only variables** (see below)\n\n---\n\n#### SCSS Variable Dependencies\n\n**CRITICAL:** The `packages/ui/src/scss/` folder has been removed. All global tokens now live in `packages/ui/src/css/`. Any CSS variable you use must exist there.\n\n**Before using a variable, verify it exists in the CSS folder:**\n\n```bash\ngrep -r \"variable-name\" packages/ui/src/css/\n```\n\n**If a variable is only in SCSS:**\n\n1. Check if there's an equivalent in the CSS folder\n2. If not, add it to the appropriate CSS file:\n   - `spacing.css` — spacers, gutters, layout spacing, breakpoints\n   - `colors.css` — color tokens\n   - `typography.css` — font tokens\n   - `radius.css` — border-radius tokens\n   - `utilities.css` — accessibility, misc utilities\n\n**Common SCSS-only variables to watch for:**\n\n| SCSS Variable           | CSS Equivalent / Action                          |\n| ----------------------- | ------------------------------------------------ |\n| `--spacing-view-bottom` | Defined in `spacing.css`                         |\n| `--breakpoint-m-width`  | Defined in `spacing.css` (1024px)                |\n| `--breakpoint-s-width`  | Defined in `spacing.css` (768px)                 |\n| `--gutter-h`            | Defined in `spacing.css`                         |\n| `$breakpoint-m-width`   | Use `var(--breakpoint-m-width)` in media queries |\n| `@include mid-break`    | Use `@media (max-width: 1024px)`                 |\n| `@include small-break`  | Use `@media (max-width: 768px)`                  |\n\n---\n\n#### Legacy Token Migration: `var(--base)` → `--spacer`\n\n**What is `--base`?** A legacy spacing token equal to `20px` (1.25rem). It must be replaced with `--spacer-*` tokens.\n\n**Spacer token values:**\n\n| Token          | Value | Pixels |\n| -------------- | ----- | ------ |\n| `--spacer-0`   | 0     | 0px    |\n| `--spacer-1`   | 4px   | 4px    |\n| `--spacer-2`   | 8px   | 8px    |\n| `--spacer-2-5` | 12px  | 12px   |\n| `--spacer-3`   | 16px  | 16px   |\n| `--spacer-4`   | 24px  | 24px   |\n| `--spacer-5`   | 32px  | 32px   |\n| `--spacer-6`   | 40px  | 40px   |\n\n**Conversion strategy:**\n\n1. **Direct match:** If the result equals a spacer token, use it directly:\n\n   ```css\n   /* Before: var(--base) = 20px → closest is --spacer-3 (16px) or --spacer-4 (24px) */\n   padding: var(--base);\n\n   /* After: Choose semantically correct size */\n   padding: var(--spacer-4); /* if 24px is acceptable */\n   ```\n\n2. **Calculated values:** When exact pixel value is important, use `calc()`:\n\n   ```css\n   /* Before: calc(var(--base) * 0.5) = 10px */\n   gap: calc(var(--base) * 0.5);\n\n   /* After: calc(var(--spacer-1) * 2.5) = 10px */\n   gap: calc(var(--spacer-1) * 2.5);\n   ```\n\n3. **ALWAYS round to nearest spacer token.** Never use `calc()` to preserve non-standard pixel values. Round all calculated values to the nearest token:\n\n   | Pixel Range | Token                 | Notes                         |\n   | ----------- | --------------------- | ----------------------------- |\n   | 0-2px       | `--spacer-0`          | Use 0                         |\n   | 3-6px       | `--spacer-1` (4px)    | 5-6px rounds to 4px           |\n   | 7-10px      | `--spacer-2` (8px)    | 10px rounds DOWN to 8px       |\n   | 11-14px     | `--spacer-2-5` (12px) | 13.33px rounds to 12px        |\n   | 15-20px     | `--spacer-3` (16px)   | 15px, 20px both round to 16px |\n   | 21-28px     | `--spacer-4` (24px)   |                               |\n   | 29-36px     | `--spacer-5` (32px)   | 30px rounds to 32px           |\n   | 37-48px     | `--spacer-6` (40px)   |                               |\n\n4. **Common `var(--base)` conversions** (base = 20px):\n\n   | Original             | Pixels | Rounded Token                                                   |\n   | -------------------- | ------ | --------------------------------------------------------------- |\n   | `var(--base) * 0.25` | 5px    | `--spacer-1` (4px)                                              |\n   | `var(--base) * 0.3`  | 6px    | `--spacer-1` (4px)                                              |\n   | `var(--base) * 0.4`  | 8px    | `--spacer-2`                                                    |\n   | `var(--base) * 0.5`  | 10px   | `--spacer-2` (8px)                                              |\n   | `var(--base) * 0.6`  | 12px   | `--spacer-2-5`                                                  |\n   | `var(--base) / 1.5`  | 13.3px | `--spacer-2-5` (12px)                                           |\n   | `var(--base) * 0.75` | 15px   | `--spacer-3` (16px)                                             |\n   | `var(--base) * 0.8`  | 16px   | `--spacer-3`                                                    |\n   | `var(--base)`        | 20px   | `--spacer-3` (16px) or `--spacer-4` (24px)                      |\n   | `var(--base) * 1.2`  | 24px   | `--spacer-4`                                                    |\n   | `var(--base) * 1.5`  | 30px   | `--spacer-5` (32px)                                             |\n   | `var(--base) * 2`    | 40px   | `--spacer-6`                                                    |\n   | `var(--base) * 3`    | 60px   | `calc(var(--spacer-4) * 2.5)` — only use calc for values > 40px |\n\n   **Rule:** For values ≤ 40px, ALWAYS use a single token. For values > 40px, use `calc()` with a spacer token.\n\n5. **Check Figma design:** The best approach is to check the Figma design for the intended spacing value and use the matching `--spacer-*` token directly.\n\n---\n\n**CRITICAL: SCSS nesting patterns that DON'T work in CSS:**\n\n**1. BEM element concatenation (`&__element`):**\n\n```scss\n// SCSS - WORKS (produces .block__element)\n.block {\n  &__element {\n    color: red;\n  }\n  &__other {\n    color: blue;\n  }\n}\n```\n\n```css\n/* CSS - DOES NOT WORK! &__element is invalid */\n/* You must use flat selectors: */\n.block { ... }\n.block__element { color: red; }\n.block__other { color: blue; }\n```\n\n**2. BEM modifier concatenation (`&--modifier`):**\n\n```scss\n// SCSS - WORKS (produces .block--active)\n.block {\n  &--active {\n    background: blue;\n  }\n}\n```\n\n```css\n/* CSS - DOES NOT WORK! Use flat selector: */\n.block { ... }\n.block--active { background: blue; }\n```\n\n**3. Parent reference from child:**\n\n```scss\n// SCSS - WORKS\n.child {\n  opacity: 0.5;\n  .parent--active & {\n    opacity: 1;\n  }\n}\n```\n\n```css\n/* CSS - DOES NOT WORK! Restructure: */\n.child {\n  opacity: 0.5;\n}\n.parent--active .child {\n  opacity: 1;\n}\n```\n\n**What DOES work in CSS nesting:**\n\n- `&:hover`, `&:focus`, `&:active` (pseudo-classes)\n- `&::before`, `&::after` (pseudo-elements)\n- `.parent { .child { } }` (descendant nesting with space)\n\n**Migration rule:** Convert all `&__` and `&--` to flat BEM selectors.\n\n**Post-migration validation:** After creating the CSS file, run the ui4-review skill to catch any remaining violations (SCSS nesting patterns, hardcoded values, legacy variables). Fix any issues before proceeding.\n\n### Step 2: Analyze Figma Component Variants\n\n**Goal:** Understand ALL visual states before implementing CSS.\n\n1. **Get metadata first** to discover variants:\n\n   ```\n   mcp_figma2_get_metadata(fileKey, nodeId)\n   ```\n\n2. **Parse variant properties** from symbol names. Common patterns:\n\n   - `State=Default, Validation=None, Selected=false, Read Only=false`\n   - Properties often include: State, Validation, Selected, Disabled, Read Only, Size\n\n3. **Build a variant matrix:**\n\n   | State   | Validation | Selected | Read Only | CSS Mapping                |\n   | ------- | ---------- | -------- | --------- | -------------------------- |\n   | Default | None       | false    | false     | base styles                |\n   | Hover   | None       | false    | false     | `:hover`                   |\n   | Focus   | None       | false    | false     | `:focus-visible`           |\n   | Default | Invalid    | false    | false     | `.error` or `&--error`     |\n   | Default | None       | true     | false     | `.is-selected`             |\n   | Default | None       | false    | true      | `.read-only`, `[disabled]` |\n\n4. **Fetch design context for key variants** (in parallel):\n\n   - Default unselected\n   - Selected\n   - Hover\n   - Focus\n   - Invalid/Error\n   - Disabled/Read-only\n\n   ```\n   mcp_figma2_get_design_context(fileKey, variantNodeId)\n   ```\n\n5. **Compare visual differences** between variants:\n   - Border color changes?\n   - Background color changes?\n   - Inner element visibility/opacity?\n   - Focus ring/outline?\n   - Text color changes?\n\n**If access fails:** STOP. Ask user to share file.\n\n### Step 3: Restyle to Match Figma\n\n1. **Read token files** (do this BEFORE writing CSS):\n\n   - `packages/ui/src/css/spacing.css` — spacer tokens\n   - `packages/ui/src/css/colors.css` — color tokens\n   - `packages/ui/src/css/typography.css` — text tokens\n   - `packages/ui/src/css/radius.css` — border-radius tokens\n   - `packages/ui/src/css/utilities.css` — accessibility tokens\n\n2. **Update styles** using tokens from files:\n\n   - Colors: `--bg-*`, `--text-*`, `--icon-*`, `--border-*`\n   - Spacing: `--spacer-*` (ALWAYS check file for matching value)\n   - Typography: `--text-body-*`, `--text-heading-*`\n   - Radius: `--radius-none/small/medium/large/full`\n   - **Focus states: `--accessibility-focus-color`** (NEVER use `--color-border-selected` directly)\n\n3. **Focus state rules:**\n\n   - Always use `--accessibility-focus-color` for focus outlines/borders\n   - Use `:focus-visible` (not `:focus`) for keyboard-only focus\n   - Standard focus outline: `outline: 1px solid var(--accessibility-focus-color)`\n   - For parent containers: use `:has(:focus-visible)` to detect child focus\n\n4. **Use canonical shorthands** — see the shorthand table in `.agents/skills/ui4-review/SKILL.md`.\n\n5. **Color rules — NEVER GUESS:**\n\n   - **Always extract exact token from Figma design context** — the `get_design_context` response includes CSS with token names\n   - **Don't assume hierarchy** — e.g., don't assume \"less prominent = tertiary\". Check the design.\n   - **When creating new elements** (icons, buttons, etc.), fetch the specific Figma node to get correct colors\n   - If Figma shows a raw hex value, map it to the closest token and note this for user review\n\n6. **Spacing rules:**\n   - First choice: use `--spacer-*` token\n   - If no match: use rem and tell user\n   - NEVER use px (except 1px borders)\n\n### Step 4: Ensure Test Collection Has All Variants\n\n**Goal:** Before visual verification, ensure the test collection has field variants for all states.\n\n1. **Read the test collection config:**\n\n   ```\n   test/v4/collections/{ComponentName}/index.ts\n   ```\n\n2. **Check for required variants** based on Figma variant matrix from Step 2:\n\n   | Figma Variant    | Required Field Config                                                                     |\n   | ---------------- | ----------------------------------------------------------------------------------------- |\n   | Default          | `{ name: 'default', type: 'component' }`                                                  |\n   | Required         | `{ name: 'required', type: 'component', required: true }`                                 |\n   | Disabled         | `{ name: 'disabled', type: 'component', admin: { disabled: true }, defaultValue: '...' }` |\n   | Read Only        | `{ name: 'readOnly', type: 'component', admin: { readOnly: true }, defaultValue: '...' }` |\n   | With Description | `{ name: 'withDescription', type: 'component', admin: { description: 'Help text' } }`     |\n\n3. **Add missing variants** if any are missing. Include `defaultValue` for disabled/readOnly so there's visible content to test.\n\n4. **Restart dev server** if collection was modified: `pnpm run dev v4`\n\n---\n\n### Step 5: Verify with Playwright (LOOP)\n\n**Dev Server:** Use `pnpm run dev v4` when working on field components. The `test/v4` suite has dedicated collections for each field type with various states (default, required, disabled).\n\n**URL Pattern:**\n\n- Fields: `http://localhost:3000/admin/collections/{field-type}-fields/create`\n- Elements: Use the appropriate page that displays the element\n\n**Handling Modal Dialogs (beforeunload):**\n\nWhen the browser has unsaved changes, a \"beforeunload\" dialog may block ALL Playwright operations. You'll see this error pattern:\n\n```\n### Error\nError: Tool \"browser_snapshot\" does not handle the modal state.\n### Modal state\n- [\"beforeunload\" dialog with message \"\"]: can be handled by browser_handle_dialog\n```\n\n**BEFORE retrying any operation**, you MUST dismiss the dialog:\n\n1. Call `browser_handle_dialog({ accept: true })` to dismiss\n2. Then retry your intended operation (navigate, snapshot, screenshot, etc.)\n\nIf the dialog persists after handling, call `browser_close()` to close the tab, then `browser_navigate` to reopen the page fresh.\n\n**Verification Steps:**\n\n1. Navigate: `browser_navigate` to component page\n2. Screenshot: `browser_take_screenshot({ fullPage: true })`\n3. Compare to Figma design\n4. Check:\n   - [ ] Padding correct?\n   - [ ] Margin correct?\n   - [ ] Gap correct?\n   - [ ] Flex alignment correct?\n   - [ ] Colors match?\n5. **Verify ALL variant states:**\n   - [ ] Default state matches Figma default variant?\n   - [ ] Hover state matches Figma hover variant? (use `browser_hover`)\n   - [ ] Focus state matches Figma focus variant? (tab to element)\n   - [ ] Error state matches Figma invalid variant? (trigger validation)\n   - [ ] Disabled/read-only matches Figma disabled variant?\n   - [ ] Selected state matches Figma selected variant? (if applicable)\n6. **If wrong:** fix CSS → goto step 1\n7. **If correct:** continue\n\n### Step 6: User Confirmation\n\nShare screenshot and dev server URL. User validates or requests changes.\n\n---\n\n## CSS Structure\n\nAlways use `@layer` and CSS nesting:\n\n```css\n@layer payload-default {\n  .component {\n    display: flex;\n    gap: var(--spacer-2);\n    padding: var(--spacer-2) var(--spacer-3);\n    background: var(--bg-default-secondary);\n    border: 1px solid var(--border-default-default);\n    border-radius: var(--radius-medium);\n\n    &__header {\n      display: flex;\n      gap: var(--spacer-1);\n    }\n\n    &--error {\n      border-color: var(--border-danger-strong);\n    }\n\n    &:hover {\n      background: var(--bg-default-secondary-hover);\n    }\n  }\n}\n```\n\n---\n\n## Red Flags - STOP\n\n| Thought                        | Reality                                  |\n| ------------------------------ | ---------------------------------------- |\n| \"I'll use flat selectors\"      | Use CSS nesting with `&`                 |\n| \"I'll use 8px here\"            | Read spacing.css, use token              |\n| \"No matching spacer\"           | Did you actually check spacing.css?      |\n| \"I'll guess the colors\"        | Read colors.css, use exact token         |\n| \"Close enough\"                 | Screenshot and compare to Figma          |\n| \"Skip verification\"            | Always run Playwright loop               |\n| \"Just need the default state\"  | Get metadata first, analyze ALL variants |\n| \"I'll figure out states later\" | Build variant matrix BEFORE writing CSS  |\n\n---\n\n## Step 7: Write Variant E2E Tests\n\n**Goal:** Create e2e tests that verify all visual variants from the Figma design.\n\n1. **Create test file** in `test/v4/collections/{ComponentName}/e2e.spec.ts`\n\n2. **Test structure:**\n\n   ```typescript\n   import type { Page } from '@playwright/test'\n   import { expect, test } from '@playwright/test'\n   import path from 'path'\n   import { fileURLToPath } from 'url'\n\n   import {\n     ensureCompilationIsDone,\n     initPageConsoleErrorCatch,\n   } from '../../../__helpers/e2e/helpers.js'\n   import { AdminUrlUtil } from '../../../__helpers/shared/adminUrlUtil.js'\n   import { initPayloadE2ENoConfig } from '../../../__helpers/shared/initPayloadE2ENoConfig.js'\n   import { TEST_TIMEOUT_LONG } from '../../../playwright.config.js'\n   import { componentFieldsSlug } from '../../slugs.js'\n\n   const filename = fileURLToPath(import.meta.url)\n   const currentFolder = path.dirname(filename)\n   const dirname = path.resolve(currentFolder, '../../')\n\n   const { beforeAll, describe } = test\n\n   let page: Page\n   let serverURL: string\n   let url: AdminUrlUtil\n\n   describe('ComponentName Field Variants', () => {\n     beforeAll(async ({ browser }, testInfo) => {\n       testInfo.setTimeout(TEST_TIMEOUT_LONG)\n       ;({ serverURL } = await initPayloadE2ENoConfig({ dirname }))\n       url = new AdminUrlUtil(serverURL, componentFieldsSlug)\n       const context = await browser.newContext()\n       page = await context.newPage()\n       initPageConsoleErrorCatch(page)\n       await ensureCompilationIsDone({ page, serverURL })\n     })\n\n     // Test each variant from the Figma design\n   })\n   ```\n\n3. **Write tests for each Figma variant:**\n\n   Map the variant matrix from Step 2 to test cases:\n\n   ```typescript\n   test('default state renders correctly', async () => {\n     await page.goto(url.create)\n     const field = page.locator('#field-componentName')\n     await expect(field).toBeVisible()\n     // Verify visual properties match Figma default variant\n   })\n\n   test('hover state shows correct styling', async () => {\n     await page.goto(url.create)\n     const field = page.locator('#field-componentName')\n     await field.hover()\n     // Verify hover styles match Figma hover variant\n   })\n\n   test('focus state shows correct styling', async () => {\n     await page.goto(url.create)\n     const field = page.locator('#field-componentName')\n     await field.focus()\n     // Verify focus ring/outline matches Figma focus variant\n   })\n\n   test('error state renders correctly', async () => {\n     await page.goto(url.create)\n     // Trigger validation by submitting without required field\n     await page.locator('button#action-save').click()\n     const field = page.locator('#field-requiredComponent')\n     // Verify error styling matches Figma invalid variant\n   })\n\n   test('disabled state renders correctly', async () => {\n     await page.goto(url.create)\n     const field = page.locator('#field-disabledComponent')\n     await expect(field).toBeDisabled()\n     // Verify disabled styling matches Figma disabled variant\n   })\n\n   test('read-only state renders correctly', async () => {\n     await page.goto(url.create)\n     const field = page.locator('#field-readOnlyComponent')\n     await expect(field).toHaveAttribute('readonly')\n     // Verify read-only styling matches Figma read-only variant\n   })\n   ```\n\n4. **Collection variants already configured:** (See Step 4)\n\n   The test collection should already have all required variants from Step 4.\n\n5. **Run tests to verify:**\n\n   ```bash\n   pnpm run test:e2e --grep \"ComponentName Field Variants\"\n   ```\n\n---\n\n## Step 8: Run ui4-review\n\n**After user confirms the component looks correct, invoke the `ui4-review` skill.**\n\nThis will:\n\n1. Scan all changed CSS files\n2. Auto-fix any remaining hardcoded values\n3. Report what was fixed/flagged\n\n---\n\n## Reference\n\n- Example migrated component: `packages/ui/src/elements/Button/index.css`\n- Token files: `packages/ui/src/css/*.css`\n- **Legacy token migration:** See Step 1 for `var(--base)` → `--spacer` conversion table\n- **v4 test suite:** `test/v4/` — dedicated collections per field type\n  - Each collection should have: default, required, disabled, readOnly field variants\n  - Disabled/readOnly fields need `defaultValue` for visible content\n  - Run with: `pnpm run dev v4`\n  - URL: `http://localhost:3000/admin/collections/{slug}/create`\n  - Available: `text-fields`, `textarea-fields`, `email-fields`, `number-fields`, `password-fields`, `checkbox-fields`, `select-fields`, `relationship-fields`, `upload-fields`, `slug-fields`, `code-fields`, `json-fields`, `collapsible-fields`, `group-fields`, `tabs-fields`, `point-fields`, `radio-fields`, `row-fields`, `array-fields`, `blocks-fields`, `date-fields`\n- **E2E test examples:** See `test/fields/collections/*/e2e.spec.ts` for patterns\n  - Test helper imports from `test/__helpers/e2e/helpers.js`\n  - Use `AdminUrlUtil` for URL construction\n  - Use `initPayloadE2ENoConfig` for test setup\n", "skills/ui4-convert-tests/SKILL.md": "---\nname: ui4-convert-tests\ndescription: Use when UI changes are complete and e2e tests need updating. Analyzes what changed in UI components and systematically finds/fixes affected tests.\n---\n\n# UI4 Convert Tests\n\n## Overview\n\nAfter completing UI changes, this skill systematically identifies and fixes affected e2e tests. It analyzes the diff to understand _what kind_ of changes were made (not just which files), then finds tests that need updates.\n\n## When to Use\n\n- UI changes are finalized and ready for test fixes\n- CI is failing on tests due to your UI changes\n- Before opening a PR to ensure tests pass\n\n## Process\n\n### Step 1: Analyze What Changed\n\n**Goal:** Understand the _nature_ of your changes to predict test impact.\n\n```bash\n# Get changed UI files\ngit diff main --name-only -- 'packages/ui/src/**/*.tsx' 'packages/ui/src/**/*.css'\n```\n\n**For each changed file, categorize the changes:**\n\n#### A. Selector Changes (IDs, classes)\n\n```bash\ngit diff main -- <file> | grep -E '^\\-.*className|^\\-.*id=|^\\+.*className|^\\+.*id='\n```\n\n#### B. Structural Changes (elements moved)\n\nLook for components being:\n\n- Moved INTO a popup, drawer, or dropdown\n- Wrapped in new parent elements\n- Made conditional\n\n```bash\ngit diff main -- <file> | grep -E 'Popup|PopupList|Drawer|Dropdown'\n```\n\n#### C. Text/Label Changes\n\n```bash\n# Translation keys\ngit diff main -- <file> | grep -E \"t\\('|i18n\\.t\\(\"\n\n# Hardcoded text\ngit diff main -- <file> | grep -E 'placeholder=|aria-label='\n```\n\n**Build a change summary:**\n\n| Change Type | What Changed                                  | Test Impact         |\n| ----------- | --------------------------------------------- | ------------------- |\n| Selector    | `.btn:has-text(\"Create\")` → `#create-new-doc` | Update locators     |\n| Structure   | Button moved into popup                       | Add popup open step |\n| Text        | \"Search by ID\" → \"Search\"                     | Update assertions   |\n\n### Step 2: Find Affected Tests\n\n**Search strategy:** Cast a wide net, then narrow down.\n\n```bash\n# Search for component name references (not just selectors)\ngrep -rn \"QueryPreset\\|query-preset\\|preset\" test/**/*.ts --include=\"*.spec.ts\" --include=\"*.ts\"\n\n# Search for specific selectors from Step 1\ngrep -rn \"\\.list-header\\|Create New\\|#create-new\" test/**/*.ts\n```\n\n**Key test locations:**\n\n| Pattern                                | Where to Look                 |\n| -------------------------------------- | ----------------------------- |\n| Component-specific                     | `test/<feature>/e2e.spec.ts`  |\n| Shared helpers                         | `test/<feature>/helpers/*.ts` |\n| Cross-cutting                          | `test/__helpers/e2e/*.ts`     |\n| Multiple features using same component | Search ALL test dirs          |\n\n**Don't just search for exact selectors!** Also search for:\n\n- Component names (e.g., `QueryPreset`, `ListHeader`)\n- Feature names (e.g., `preset`, `filter`, `search`)\n- Text content that changed (e.g., `\"Create New\"`, `\"Search by\"`)\n\n### Step 3: Analyze Test Dependencies\n\n**Before fixing, understand the test:**\n\n1. **Read the full test** - Understand what it's actually testing\n2. **Check for helpers** - Is there a shared helper that handles this selector?\n3. **Look for patterns** - Are multiple tests doing the same thing?\n\n**If multiple tests use the same selector, create/update a helper:**\n\n```typescript\n// test/<feature>/helpers/togglePreset.ts\nexport async function openCreatePreset(page: Page) {\n  await page.click('#select-preset') // Open popup first\n  await page.click('#create-new-preset')\n}\n```\n\nThis centralizes the fix and prevents future duplication.\n\n### Step 4: Categorize Fixes Needed\n\n| Change Type                 | Fix Strategy                                    |\n| --------------------------- | ----------------------------------------------- |\n| **Selector renamed**        | Direct string replacement                       |\n| **Element moved to popup**  | Add click to open popup before clicking element |\n| **Element moved to drawer** | Add drawer open/close handling                  |\n| **Text simplified**         | Update assertion to match new text              |\n| **Element removed**         | Rework test logic or delete test                |\n| **Props changed**           | Update attribute assertions                     |\n| **Conditional rendering**   | May need to set up state before element appears |\n\n### Step 5: Run Affected Tests\n\n**Run tests BEFORE making fixes to confirm they actually fail:**\n\n```bash\n# Use isolated port to avoid conflicts\nPORT=3150 pnpm test:e2e <suite> --max-failures=1\n\n# Run specific test by name\nPORT=3150 pnpm test:e2e <suite> -g \"test name\" --max-failures=1\n```\n\n**Document failure patterns:**\n\n- `Timeout waiting for locator('.old-selector')` → Selector changed\n- `locator resolved to 0 elements` → Element moved or removed\n- `expected \"New Text\" received \"Old Text\"` → Text content changed\n\n### Step 6: Apply Fixes\n\n**Priority: Fix helpers first, then individual tests.**\n\n#### Pattern 1: Selector Renamed\n\n```typescript\n// Before\nawait page.click('.list-header .btn:has-text(\"Create\")')\n\n// After - prefer IDs when available\nawait page.click('#create-new-doc')\n```\n\n#### Pattern 2: Element Moved Into Popup\n\n```typescript\n// Before - direct click\nawait page.click('#edit-preset')\n\n// After - open popup first\nawait page.click('#select-preset') // Opens the popup\nawait page.click('#edit-preset') // Now visible in popup\n```\n\n#### Pattern 3: Text Content Simplified\n\n```typescript\n// Before - specific placeholder text\nawait expect(input).toHaveAttribute('placeholder', /(Search by ID)/)\n\n// After - simplified text\nawait expect(input).toHaveAttribute('placeholder', 'Search')\n```\n\n#### Pattern 4: Create Reusable Helper\n\nWhen the same interaction is needed in multiple tests:\n\n```typescript\n// test/<feature>/helpers/interactions.ts\nexport async function openEditPreset(page: Page) {\n  await page.click('#select-preset')\n  await page.click('#edit-preset')\n}\n\n// In tests - import and use\nimport { openEditPreset } from './helpers/interactions.js'\nawait openEditPreset(page)\n```\n\n### Step 7: Verify Fixes\n\n```bash\n# Run same tests that failed\nPORT=3150 pnpm test:e2e <suite> --max-failures=1\n```\n\nOnly commit after tests pass.\n\n## Common Patterns (Real Examples)\n\n### Pattern: Buttons Moved Into Popup Menu\n\n**Symptom:** Test times out waiting for button that used to be directly visible.\n\n**Detection:** Check if buttons were wrapped in `<Popup>` or `<PopupList>`:\n\n```bash\ngit diff main -- <file> | grep -E 'PopupList|Popup'\n```\n\n**Fix:** Add popup trigger click before clicking the button:\n\n```typescript\n// Before: Button was directly in toolbar\nawait page.click('#edit-preset')\n\n// After: Button is now inside a popup\nawait page.click('#select-preset') // Opens popup\nawait page.click('#edit-preset') // Now visible\n```\n\n**Bonus:** If multiple tests need this, create a helper function.\n\n### Pattern: Class-Based Selector → ID Selector\n\n**Symptom:** `.some-class` or `:has-text(\"Button Text\")` no longer finds element.\n\n**Detection:** Component added `id=` attribute:\n\n```bash\ngit diff main -- <file> | grep -E '^\\+.*id='\n```\n\n**Fix:** Use the more stable ID:\n\n```typescript\n// Before: Fragile class + text selector\nawait page.click('.list-header .btn:has-text(\"Create New\")')\n\n// After: Stable ID selector\nawait page.click('#create-new-doc')\n```\n\n### Pattern: Placeholder/Label Text Simplified\n\n**Symptom:** Assertion fails with `expected \"New Text\" received \"Old Text\"`.\n\n**Detection:** Translation key or hardcoded text changed:\n\n```bash\ngit diff main -- <file> | grep -E 'placeholder=|t\\('\n```\n\n**Fix:** Update assertion to match new text:\n\n```typescript\n// Before: Verbose placeholder\nawait expect(input).toHaveAttribute('placeholder', /(Search by ID, Title)/)\n\n// After: Simplified\nawait expect(input).toHaveAttribute('placeholder', 'Search')\n```\n\n### Pattern: Same Fix Needed Across Multiple Tests\n\n**Symptom:** Several tests in different suites fail with similar selector issues.\n\n**Detection:**\n\n```bash\n# Find all tests using the old selector\ngrep -rn \"old-selector\\|.old-class\" test/**/*.ts\n```\n\n**Fix:**\n\n1. Check if a helper already exists in `test/<feature>/helpers/`\n2. If yes, fix the helper (fixes all tests at once)\n3. If no, create one and refactor tests to use it\n\n### Pattern: Tests in Different Suites Share Components\n\nWhen you change a shared component (like `ListControls`, `QueryPresetBar`), multiple test suites may be affected.\n\n**Detection:**\n\n```bash\n# Find component name references across all tests\ngrep -rn \"QueryPreset\\|ListControl\" test/**/*.ts | cut -d: -f1 | sort -u\n```\n\n**Common cross-suite components:**\n\n- `ListControls` → affects any list view tests\n- `QueryPresetBar` → query-presets, group-by, admin tests\n- `Search` → i18n, admin, most collection tests\n- `Button` → nearly everything\n\n## Quick Reference: Common Payload Test Selectors\n\n| Component     | Common Selectors                                    |\n| ------------- | --------------------------------------------------- |\n| Search        | `.search-filter__input`, `#search-filter-input`     |\n| List View     | `.collection-list`, `tbody tr`, `.table-row`        |\n| Popup         | `.popup__content`, `.popup-button-list__button`     |\n| Modal         | `dialog`, `[id^=doc-drawer_]`, `[id^=list-drawer_]` |\n| Buttons       | `.btn`, `button[type=\"button\"]`                     |\n| Query Presets | `#select-preset`, `.query-preset-bar__*`            |\n\n## Test Commands Reference\n\n```bash\n# Run all e2e tests for a test suite (auto-starts dev server)\nPORT=3150 pnpm test:e2e <suite-name>\n\n# Run specific test file\nPORT=3150 pnpm test:e2e test/<suite>/e2e.spec.ts\n\n# Run with headed browser (see what's happening)\nPORT=3150 pnpm test:e2e:headed test/<suite>/e2e.spec.ts\n\n# Run in debug mode (step through)\nPORT=3150 pnpm test:e2e:debug test/<suite>/e2e.spec.ts\n\n# Run specific test by name pattern\nPORT=3150 pnpm test:e2e test/<suite>/e2e.spec.ts -g \"test name pattern\"\n\n# Stop on first failure (useful during debugging)\nPORT=3150 pnpm test:e2e test/<suite>/e2e.spec.ts --max-failures=1\n```\n\n**Note:** The `pnpm test:e2e` command automatically:\n\n1. Starts a dev server if the port is free\n2. Reuses an existing dev server if the port is in use\n3. Runs playwright tests against that port\n\n## Running Tests with Isolation\n\n### Quick Start: Isolated Test Run\n\n**Pick a unique port in the 3100-3199 range:**\n\n```bash\n# Run tests on an isolated port (MongoDB auto-starts its own in-memory server)\nPORT=3150 pnpm test:e2e query-presets --max-failures=1\n```\n\nThat's it for MongoDB (default). Each test run starts its own in-memory MongoDB server, so no database conflicts occur.\n\n### Postgres Isolation\n\nFor Postgres tests, use a unique database per worktree/repo:\n\n```bash\n# Create a unique database for this worktree\nPGPASSWORD=payload psql -h localhost -p 5433 -U payload -c \"CREATE DATABASE payload_worktree1;\"\n\n# Run tests against that database\nPOSTGRES_URL=\"postgres://payload:payload@localhost:5433/payload_worktree1\" \\\n  PORT=3150 pnpm test:e2e query-presets --max-failures=1\n```\n\nOr use the custom schema approach (no separate DB needed):\n\n```bash\n# Tests will use a separate schema within the same database\nPAYLOAD_DATABASE=postgres-custom-schema PORT=3150 pnpm test:e2e query-presets\n```\n\n### Why Isolation Matters\n\n| Scenario           | Port Conflict?  | DB Conflict?                 |\n| ------------------ | --------------- | ---------------------------- |\n| MongoDB in-memory  | Yes (same port) | No (each run has own server) |\n| Postgres           | Yes (same port) | Yes (same tables)            |\n| Multiple worktrees | Yes             | Yes (Postgres only)          |\n\n**Solution:** Always set `PORT` to avoid port conflicts. For Postgres, also isolate the database.\n\n## Common Mistakes\n\n**Dev server not running or wrong port:**\nTests read `PORT` env var (default `3000`). Two approaches:\n\n**Option A: Use isolated port (preferred for parallel test suites)**\n\n```bash\n# Run tests on custom port - script handles everything\nPORT=3105 pnpm test:e2e test/query-presets/e2e.spec.ts\n```\n\n**Option B: Kill existing ports and use default**\n\n```bash\n# Kill all dev server ports\nlsof -ti:3000,3001,3002,3003,3004,3005,3006,3007,3008,3009 | xargs kill -9 2>/dev/null\n\n# Tests use 3000 by default\npnpm test:e2e test/query-presets/e2e.spec.ts\n```\n\n**Wrong test suite running:**\nEach test suite (fields, query-presets, localization, etc.) has its own Payload config. Tests will fail or behave unexpectedly if the wrong dev server is running.\n\n**Not running tests before fixing:**\nAlways verify tests actually fail before making changes. If a test passes, don't change it.\n\n**Not checking helper files:**\nTest helpers in `test/*/helpers/` often contain shared selectors that affect multiple tests.\n\n**Missing popup interactions:**\nWhen elements move into popups, tests need to open the popup first.\n\n**Forgetting confirmation dialogs:**\nDelete actions often add confirmation modals - tests need to handle the confirm step.\n\n**Placeholder text changes:**\nSearch placeholders, button labels, and other text content may change.\n\n**Modal slug mismatches:**\nWhen deleting/confirming actions, the modal slug may change. Check the component code for the actual `slug` prop passed to `<Modal>` or drawer components.\n\n## Example: QueryPresetBar Changes\n\n**Old structure (chips):**\n\n```typescript\n// Direct buttons visible\nawait page.click('#create-new-preset')\nawait page.click('#edit-preset')\nawait page.click('#delete-preset')\nawait page.click('.chip__remove') // clear\n```\n\n**New structure (popup dropdown):**\n\n```typescript\n// Open popup first\nawait page.click('#select-preset')\n// Then click menu items\nawait page.click('.popup-button-list__button:has-text(\"Create New\")')\nawait page.click('.popup-button-list__button:has-text(\"Edit\")')\nawait page.click('.popup-button-list__button:has-text(\"Delete\")')\n// Clear uses dedicated button\nawait page.click('.query-preset-bar__clear')\n```\n", "skills/ui4-review/SKILL.md": "---\nname: ui4-review\ndescription: Review UI4 CSS migrations for proper token usage. Checks that CSS variables are used instead of hardcoded values.\n---\n\n# UI4 Review\n\nReviews CSS changes and **auto-fixes** token violations.\n\n---\n\n## Important: Palette vs Semantic Tokens\n\n**`--ramp-*` tokens** are the raw color palette (e.g., `--ramp-white-1000`, `--ramp-blue-500`). These are used **only** in `colors.css` to define semantic tokens.\n\n**`--color-*` tokens** are context-aware semantic tokens (e.g., `--color-bg`, `--color-text-brand`). These handle light/dark theming automatically.\n\n**Components and elements should ALWAYS use `--color-*` semantic tokens, never `--ramp-*` palette tokens directly.**\n\n```css\n/* ❌ BAD - using raw palette */\nbackground: var(--ramp-white-1000);\n\n/* ✅ GOOD - using semantic token */\nbackground: var(--color-bg);\n```\n\n---\n\n## Process\n\n### Step 1: Get Changed CSS Files\n\n```bash\ngit status --porcelain | grep '\\.css$'\n```\n\nOr if a specific file is provided, use that directly.\n\n### Step 2: Parallel Violation Detection\n\n**Run these grep searches IN PARALLEL** to detect all violation types at once:\n\n```bash\n# 1. SCSS Nesting Violations (BEM patterns that don't work in CSS)\ngrep -n '&__\\|&--' \"$FILE\"\n\n# 2. Hardcoded Spacing (px/rem values that should be tokens)\ngrep -nE ':\\s*[0-9]+px|:\\s*[0-9.]+rem' \"$FILE\"\n\n# 3. Hardcoded Colors (hex, rgb, rgba - includes box-shadow)\ngrep -nE '#[0-9a-fA-F]{3,8}|rgba?\\(' \"$FILE\"\n\n# 4. Legacy Theme Variables\ngrep -nE 'var\\(--theme-|var\\(--style-|var\\(--base\\)' \"$FILE\"\n\n# 5. Old Token Names (pre-UI4 naming)\ngrep -nE '\\-\\-bg-default|\\-\\-bg-secondary|\\-\\-text-default|\\-\\-text-secondary|\\-\\-icon-default|\\-\\-icon-secondary|\\-\\-border-default|\\-\\-border-strong' \"$FILE\"\n\n# 6. Raw Palette Usage (should use semantic tokens instead)\n# Skip this check for colors.css which defines the semantic tokens\ngrep -nE 'var\\(--ramp-' \"$FILE\"\n```\n\n**Invoke all 6 grep commands in a single parallel batch**, then analyze results.\n\n**Note:** Raw `--ramp-*` violations are only flagged in component CSS files, not in `colors.css` where they're used to define semantic tokens.\n\n### Step 3: Auto-Fix by Priority\n\n1. **SCSS Nesting** (breaks CSS entirely) — Fix first\n2. **Legacy Variables** (deprecated) — Replace with new tokens\n3. **Old Token Names** (pre-UI4) — Convert to `--color-*` naming\n4. **Raw Palette Usage** (`--ramp-*` in components) — Replace with semantic `--color-*` tokens\n5. **Hardcoded Values** (spacing, colors, radius) — Replace with tokens\n\n### Step 4: Report\n\nAfter fixing, report:\n\n- Total violations found\n- Violations auto-fixed\n- Violations that need manual review (no clear token match)\n\n---\n\n## Violation Reference\n\n### SCSS Nesting (BREAKS CSS)\n\n| Pattern                     | Issue               | Fix                                  |\n| --------------------------- | ------------------- | ------------------------------------ |\n| `&__element`                | BEM element concat  | Use flat `.block__element` selector  |\n| `&--modifier`               | BEM modifier concat | Use flat `.block--modifier` selector |\n| `.child { .parent--mod & }` | Parent reference    | Move to `.parent--mod .child`        |\n\n**What DOES work:** `&:hover`, `&:focus`, `&::before`, `& .child`\n\n---\n\n### Spacing Tokens\n\n| Value          | Token          |\n| -------------- | -------------- |\n| 4px / 0.25rem  | `--spacer-1`   |\n| 8px / 0.5rem   | `--spacer-2`   |\n| 12px / 0.75rem | `--spacer-2-5` |\n| 16px / 1rem    | `--spacer-3`   |\n| 24px / 1.5rem  | `--spacer-4`   |\n| 32px / 2rem    | `--spacer-5`   |\n| 40px / 2.5rem  | `--spacer-6`   |\n\n**Rounding rules — ALWAYS round to nearest token:**\n\n| Pixel Range | Token                 | Notes                         |\n| ----------- | --------------------- | ----------------------------- |\n| 0-2px       | `--spacer-0`          | Use 0                         |\n| 3-6px       | `--spacer-1` (4px)    | 5-6px rounds to 4px           |\n| 7-10px      | `--spacer-2` (8px)    | 10px rounds DOWN to 8px       |\n| 11-14px     | `--spacer-2-5` (12px) | 13.33px rounds to 12px        |\n| 15-20px     | `--spacer-3` (16px)   | 15px, 20px both round to 16px |\n| 21-28px     | `--spacer-4` (24px)   |                               |\n| 29-36px     | `--spacer-5` (32px)   | 30px rounds to 32px           |\n| 37-48px     | `--spacer-6` (40px)   |                               |\n\n**Rule:** For values ≤ 40px, ALWAYS use a single token (no `calc()`). For values > 40px, use `calc()` with a spacer token.\n\n**Exceptions:** `0`, percentages, `auto`, `inherit`, `-1px` (for clip offsets)\n\n---\n\n### Stroke Width Tokens\n\n| Value | Token                  |\n| ----- | ---------------------- |\n| 1px   | `--stroke-width-small` |\n\n---\n\n### Radius Tokens\n\n| Value            | Token             |\n| ---------------- | ----------------- |\n| 2px / 0.125rem   | `--radius-small`  |\n| 5px / 0.3125rem  | `--radius-medium` |\n| 13px / 0.8125rem | `--radius-large`  |\n| 9999px           | `--radius-full`   |\n\n---\n\n### Elevation Tokens (Box Shadows)\n\nDefined in `packages/ui/src/css/elevations.css`.\n\n**Never use hardcoded `rgba()` for box-shadows.** Use elevation tokens instead:\n\n| Token                          | Use Case                          |\n| ------------------------------ | --------------------------------- |\n| `--elevation-300-tooltip`      | Tooltips, small floating elements |\n| `--elevation-400-menu-panel`   | Menus, dropdowns, floating panels |\n| `--elevation-500-modal-window` | Modals, dialogs, full overlays    |\n\n```css\n/* ❌ BAD - hardcoded shadow */\nbox-shadow: 0 -2px 16px -2px rgba(0, 0, 0, 0.2);\n\n/* ✅ GOOD - elevation token */\nbox-shadow: var(--elevation-400-menu-panel);\n```\n\nElevations automatically adjust for light/dark themes.\n\n---\n\n### Semantic Color Tokens (UI4 Naming)\n\nAll semantic colors use the `--color-` prefix. The `default` category and variant are implicit.\n\n| Old Name            | New Name (UI4)            |\n| ------------------- | ------------------------- |\n| `--bg-default`      | `--color-bg`              |\n| `--bg-secondary`    | `--color-bg-secondary`    |\n| `--bg-hover`        | `--color-bg-hover`        |\n| `--bg-selected`     | `--color-bg-selected`     |\n| `--bg-brand`        | `--color-bg-brand`        |\n| `--bg-danger`       | `--color-bg-danger`       |\n| `--bg-success`      | `--color-bg-success`      |\n| `--bg-warning`      | `--color-bg-warning`      |\n| `--text-default`    | `--color-text`            |\n| `--text-secondary`  | `--color-text-secondary`  |\n| `--text-tertiary`   | `--color-text-tertiary`   |\n| `--text-brand`      | `--color-text-brand`      |\n| `--text-danger`     | `--color-text-danger`     |\n| `--text-success`    | `--color-text-success`    |\n| `--icon-default`    | `--color-icon`            |\n| `--icon-secondary`  | `--color-icon-secondary`  |\n| `--icon-tertiary`   | `--color-icon-tertiary`   |\n| `--icon-brand`      | `--color-icon-brand`      |\n| `--icon-danger`     | `--color-icon-danger`     |\n| `--border-default`  | `--color-border`          |\n| `--border-strong`   | `--color-border-strong`   |\n| `--border-selected` | `--color-border-selected` |\n| `--border-brand`    | `--color-border-brand`    |\n\n---\n\n### Legacy Variables (Replace Immediately)\n\n| Legacy                  | Replacement            |\n| ----------------------- | ---------------------- |\n| `--theme-elevation-0`   | `--color-bg`           |\n| `--theme-elevation-50`  | `--color-bg-secondary` |\n| `--theme-elevation-100` | `--color-border`       |\n| `--theme-text`          | `--color-text`         |\n| `--style-radius-m`      | `--radius-medium`      |\n\n**`var(--base)` Conversion:** Legacy token = 20px. Convert using:\n\n| Original            | Pixels | Replacement                     |\n| ------------------- | ------ | ------------------------------- |\n| `var(--base) * 0.4` | 8px    | `var(--spacer-2)`               |\n| `var(--base) * 0.5` | 10px   | `calc(var(--spacer-1) * 2.5)`   |\n| `var(--base) * 0.6` | 12px   | `var(--spacer-2-5)`             |\n| `var(--base)`       | 20px   | `calc(var(--spacer-4) * 0.833)` |\n| `var(--base) * 2`   | 40px   | `var(--spacer-6)`               |\n\nSee ui4 skill Step 1 for full conversion table.\n\n---\n\n## Behavior\n\n**DO NOT just report violations. FIX THEM immediately using replace_string_in_file or multi_replace_string_in_file.**\n\nWhen a violation has no clear token match (e.g., `3px` or an unusual rem value), flag it for manual review but don't guess.\n\nFor each violation:\n\n1. Identify the exact line and value\n2. Determine the correct token replacement\n3. Use `replace_string_in_file` to fix it immediately\n4. Report what was fixed\n\n**Only flag (don't fix) when:**\n\n- No matching token exists (e.g., 18px badge size)\n- Value is intentional (e.g., `1px` border, `0`)\n- Ambiguous replacement\n\n**Empty CSS files:** If a component's CSS file becomes empty after migration (all styles now handled by shared components like `Button`), delete the CSS file and remove its import from the component.\n\n---\n\n## Output Format\n\nAfter auto-fixing, report:\n\n```\n## Auto-Fixed\n\n✅ Collapsible/index.css:9 — `height: 2rem` → `height: var(--spacer-5)`\n✅ Collapsible/index.css:120 — `width: 2rem` → `width: var(--spacer-5)`\n\n## Flagged (Manual Review)\n\n⚠️ ErrorPill/index.css:15 — `height: 1.125rem` (18px) — no matching token\n```\n\n---\n\n## Summary\n\nAfter all fixes, provide a simple summary:\n\n| File                  | Fixed | Flagged |\n| --------------------- | ----- | ------- |\n| Collapsible/index.css | 2     | 1       |\n| ErrorPill/index.css   | 0     | 2       |\n"}}
