{"name": "nextjs", "version": "0.1.0", "hash": "sha256:3fe9e048f2cfc36331212c8df428d20793556a2f66dcb7f099980f33d973be49", "files": {"ABSORB_REPORT.md": "# Absorb report: nextjs\n\n- **Source:** https://github.com/vercel/next.js at `012544435e7e`\n- **Licence:** MIT\n- **Project names searched for:** next.js, nextjs-project\n\n## What was absorbed\n\n| Piece | Kind | Class | Project names | Project paths |\n|---|---|---|---|---|\n| authoring-skills | skill | mixed | next.js ×1 |  |\n| backport-pr | skill | mixed | next.js ×5 |  |\n| create-pr | skill | mixed | next.js ×2 | .github/pull_request_template.md |\n| dce-edge | skill | mixed |  | test/e2e/app-dir/app/standalone.test.ts |\n| deploy-release-test | skill | mixed | next.js ×10 | .github/workflows/test_e2e_deploy_release.yml, scripts/wait-for-preview-tarball.mjs |\n| docs-diagrams | skill | mixed | next.js ×2 | docs/01-app/04-glossary.mdx, scripts |\n| flags | skill | mixed | next.js ×2 |  |\n| gate-tests | skill | mixed |  | test/lib/gate/conditions.ts, test/lib/gate/README.md, test/development, test/production, test/e2e, test/e2e/app-dir/use-offline, test/e2e/app-dir/concurrent-router-queue, test/jest-global-setup.ts, test/e2e/app-dir, test/unit/gate |\n| gh-stack | skill | mechanics |  |  |\n| insight-error-page | skill | mixed | next.js ×2 | packages/next/src/next-devtools/dev-overlay/components/instant/instant-guidance-data.ts, packages/next/src/server/app-render/sync-io-messages.ts, docs/01-app, docs/01-app/02-guides/instant-navigation.mdx, errors/blocking-prerender-random.mdx, errors |\n| next-rspack | skill | mixed | next.js ×3 | rspack/package.json, rspack/crates/binding/Cargo.toml, rspack/rust-toolchain.toml, packages/next-rspack/package.json, packages/next-rspack, rspack/crates/binding, rspack/crates/binding/package.json, packages/next, packages/next/src/lib/bundler.ts, packages/next/src/build/webpack-config.ts, packages/next/src/build/webpack/loaders, .github/workflows/release-next-rspack.yml |\n| pr-status-triage | skill | mixed | next.js ×9 | scripts/pr-status.js, .github/workflows/retry_test.yml, scripts/test-new-tests.mjs, contributing/core/testing.md |\n| react-sync | skill | mixed | next.js ×9 |  |\n| react-vendoring | skill | mixed |  | packages/next/src/compiled, packages/next/types |\n| rebase-pr | skill | mixed | next.js ×4 |  |\n| router-act | skill | mixed | next.js ×2 | test/lib/router-act.ts, test/e2e/app-dir/segment-cache/prefetch-app-shell/prefetch-app-shell.test.ts, test/e2e/app-dir/segment-cache/staleness/components/link-accordion.tsx, test/e2e/app-dir/segment-cache/staleness |\n| run-tests | skill | mixed | next.js ×4 | scripts/install-native.mjs, scripts/run-jest.sh, test/unit, packages/next, packages/font, .github/workflows/build_and_test.yml, crates/next-core/src/next_import_map.rs, packages/next/src/build/create-compiler-aliases.ts, test/e2e, test/AGENTS.md, test/.gitignore, scripts/test-new-tests.mjs |\n| runtime-debug | skill | mixed | next.js ×2 | packages/next/src/server/patch-error-inspect.ts |\n| rust-turbopack | skill | mixed | next.js ×4 | turbopack/AGENTS.md, packages/next-swc, packages/next/src/build/swc/generated-native.d.ts, packages/next-swc/package.json, turbopack/crates/turbopack-tests/README.md, .cargo/config.toml, scripts/wasi-test-host/README.md, bench/large-app-router, bench/nested-deps-app-router-many-pages, bench/BENCHMARKING.md, bench |\n| sandbox-bench | skill | mixed | next.js ×16 | bench/render-pipeline, scripts |\n| update-docs | skill | mixed | next.js ×7 | docs/01-app, docs/02-pages, packages/next/src, packages/next/src/client/components, packages/next/src/server, packages/next/src/shared/lib, packages/next/src/build, packages/next/src/lib, docs/01-app/03-api-reference/02-components/image.mdx, docs/01-app/03-api-reference/05-config, docs/01-app/03-api-reference/02-components, docs/01-app/03-api-reference/04-functions |\n| v8-jit | skill | mixed | next.js ×3 |  |\n| write-api-reference | skill | mixed | next.js ×2 | docs/01-app/03-api-reference, test |\n| write-guide | skill | mixed |  | docs/01-app/02-guides |\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- **authoring-skills** (skill): names next.js\n- **backport-pr** (skill): names next.js\n- **create-pr** (skill): names next.js; paths .github/pull_request_template.md\n- **dce-edge** (skill): paths test/e2e/app-dir/app/standalone.test.ts\n- **deploy-release-test** (skill): names next.js; paths .github/workflows/test_e2e_deploy_release.yml, scripts/wait-for-preview-tarball.mjs\n- **docs-diagrams** (skill): names next.js; paths docs/01-app/04-glossary.mdx, scripts\n- **flags** (skill): names next.js\n- **gate-tests** (skill): paths test/lib/gate/conditions.ts, test/lib/gate/README.md, test/development, test/production, test/e2e, test/e2e/app-dir/use-offline, test/e2e/app-dir/concurrent-router-queue, test/jest-global-setup.ts, test/e2e/app-dir, test/unit/gate\n- **insight-error-page** (skill): names next.js; paths packages/next/src/next-devtools/dev-overlay/components/instant/instant-guidance-data.ts, packages/next/src/server/app-render/sync-io-messages.ts, docs/01-app, docs/01-app/02-guides/instant-navigation.mdx, errors/blocking-prerender-random.mdx, errors\n- **next-rspack** (skill): names next.js; paths rspack/package.json, rspack/crates/binding/Cargo.toml, rspack/rust-toolchain.toml, packages/next-rspack/package.json, packages/next-rspack, rspack/crates/binding, rspack/crates/binding/package.json, packages/next, packages/next/src/lib/bundler.ts, packages/next/src/build/webpack-config.ts, packages/next/src/build/webpack/loaders, .github/workflows/release-next-rspack.yml\n- **pr-status-triage** (skill): names next.js; paths scripts/pr-status.js, .github/workflows/retry_test.yml, scripts/test-new-tests.mjs, contributing/core/testing.md\n- **react-sync** (skill): names next.js\n- **react-vendoring** (skill): paths packages/next/src/compiled, packages/next/types\n- **rebase-pr** (skill): names next.js\n- **router-act** (skill): names next.js; paths test/lib/router-act.ts, test/e2e/app-dir/segment-cache/prefetch-app-shell/prefetch-app-shell.test.ts, test/e2e/app-dir/segment-cache/staleness/components/link-accordion.tsx, test/e2e/app-dir/segment-cache/staleness\n- **run-tests** (skill): names next.js; paths scripts/install-native.mjs, scripts/run-jest.sh, test/unit, packages/next, packages/font, .github/workflows/build_and_test.yml, crates/next-core/src/next_import_map.rs, packages/next/src/build/create-compiler-aliases.ts, test/e2e, test/AGENTS.md, test/.gitignore, scripts/test-new-tests.mjs\n- **runtime-debug** (skill): names next.js; paths packages/next/src/server/patch-error-inspect.ts\n- **rust-turbopack** (skill): names next.js; paths turbopack/AGENTS.md, packages/next-swc, packages/next/src/build/swc/generated-native.d.ts, packages/next-swc/package.json, turbopack/crates/turbopack-tests/README.md, .cargo/config.toml, scripts/wasi-test-host/README.md, bench/large-app-router, bench/nested-deps-app-router-many-pages, bench/BENCHMARKING.md, bench\n- **sandbox-bench** (skill): names next.js; paths bench/render-pipeline, scripts\n- **update-docs** (skill): names next.js; paths docs/01-app, docs/02-pages, packages/next/src, packages/next/src/client/components, packages/next/src/server, packages/next/src/shared/lib, packages/next/src/build, packages/next/src/lib, docs/01-app/03-api-reference/02-components/image.mdx, docs/01-app/03-api-reference/05-config, docs/01-app/03-api-reference/02-components, docs/01-app/03-api-reference/04-functions\n- **v8-jit** (skill): names next.js\n- **write-api-reference** (skill): names next.js; paths docs/01-app/03-api-reference, test\n- **write-guide** (skill): paths docs/01-app/02-guides\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- `.claude/skills/README.md`: not a skill (a skill is a folder with a SKILL.md)\n\n## Self-test\n\nNo case could be generated.\n", "ATTRIBUTION.md": "# Attribution: nextjs\n\nThis harness was absorbed from https://github.com/vercel/next.js at commit `012544435e7e4891d272809c9132a488c39e2791` on 2026-11-27 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/authoring-skills/SKILL.md` (skill)\n- `skills/backport-pr/SKILL.md` (skill)\n- `skills/create-pr/SKILL.md` (skill)\n- `skills/dce-edge/SKILL.md` (skill)\n- `skills/deploy-release-test/SKILL.md` (skill)\n- `skills/deploy-release-test/agents/openai.yaml` (skill)\n- `skills/docs-diagrams/SKILL.md` (skill)\n- `skills/docs-diagrams/review-checklist.md` (skill)\n- `skills/docs-diagrams/scripts/gen.mjs` (skill)\n- `skills/docs-diagrams/scripts/lib.mjs` (skill)\n- `skills/docs-diagrams/scripts/measure.py` (skill)\n- `skills/docs-diagrams/scripts/render.sh` (skill)\n- `skills/docs-diagrams/style-tokens.md` (skill)\n- `skills/flags/SKILL.md` (skill)\n- `skills/gate-tests/SKILL.md` (skill)\n- `skills/gh-stack/SKILL.md` (skill)\n- `skills/gh-stack/references/commands.md` (skill)\n- `skills/gh-stack/references/stack-design.md` (skill)\n- `skills/gh-stack/references/troubleshooting.md` (skill)\n- `skills/insight-error-page/SKILL.md` (skill)\n- `skills/next-rspack/SKILL.md` (skill)\n- `skills/pr-status-triage/SKILL.md` (skill)\n- `skills/pr-status-triage/ci-reading.md` (skill)\n- `skills/pr-status-triage/local-repro.md` (skill)\n- `skills/pr-status-triage/workflow.md` (skill)\n- `skills/react-sync/SKILL.md` (skill)\n- `skills/react-sync/scripts/build-for-next.sh` (skill)\n- `skills/react-vendoring/SKILL.md` (skill)\n- `skills/rebase-pr/SKILL.md` (skill)\n- `skills/router-act/SKILL.md` (skill)\n- `skills/run-tests/SKILL.md` (skill)\n- `skills/run-tests/flaky-tests.md` (skill)\n- `skills/runtime-debug/SKILL.md` (skill)\n- `skills/rust-turbopack/SKILL.md` (skill)\n- `skills/rust-turbopack/benchmarking.md` (skill)\n- `skills/sandbox-bench/SKILL.md` (skill)\n- `skills/sandbox-bench/references/methodology.md` (skill)\n- `skills/sandbox-bench/scripts/bench-analyze.mjs` (skill)\n- `skills/sandbox-bench/scripts/bench-collect.mjs` (skill)\n- `skills/sandbox-bench/scripts/bench-common.mjs` (skill)\n- `skills/sandbox-bench/scripts/bench-db.mjs` (skill)\n- `skills/sandbox-bench/scripts/bench-stats.mjs` (skill)\n- `skills/sandbox-bench/scripts/bench-status.mjs` (skill)\n- `skills/sandbox-bench/scripts/config.mjs` (skill)\n- `skills/sandbox-bench/scripts/sandbox-e2e.mjs` (skill)\n- `skills/sandbox-bench/scripts/sandbox-gate.mjs` (skill)\n- `skills/sandbox-bench/scripts/sandbox-ssr.mjs` (skill)\n- `skills/sandbox-bench/scripts/sandbox-sweep.mjs` (skill)\n- `skills/update-docs/SKILL.md` (skill)\n- `skills/update-docs/references/CODE-TO-DOCS-MAPPING.md` (skill)\n- `skills/update-docs/references/DOC-CONVENTIONS.md` (skill)\n- `skills/v8-jit/SKILL.md` (skill)\n- `skills/write-api-reference/SKILL.md` (skill)\n- `skills/write-guide/SKILL.md` (skill)\n", "harness.yaml": "$schema: https://harnessprotocol.io/schema/v1/harness.schema.json\nversion: '1'\nkind: profile\nmetadata:\n  name: nextjs\n  description: 'The Next.js repository''s agent skills: tests, PRs, backports, Turbopack and docs.'\n  version: 0.1.0\n  license: MIT\nskills:\n- name: authoring-skills\n  source: ./skills/authoring-skills\n- name: backport-pr\n  source: ./skills/backport-pr\n- name: create-pr\n  source: ./skills/create-pr\n- name: dce-edge\n  source: ./skills/dce-edge\n- name: deploy-release-test\n  source: ./skills/deploy-release-test\n- name: docs-diagrams\n  source: ./skills/docs-diagrams\n- name: flags\n  source: ./skills/flags\n- name: gate-tests\n  source: ./skills/gate-tests\n- name: gh-stack\n  source: ./skills/gh-stack\n- name: insight-error-page\n  source: ./skills/insight-error-page\n- name: next-rspack\n  source: ./skills/next-rspack\n- name: pr-status-triage\n  source: ./skills/pr-status-triage\n- name: react-sync\n  source: ./skills/react-sync\n- name: react-vendoring\n  source: ./skills/react-vendoring\n- name: rebase-pr\n  source: ./skills/rebase-pr\n- name: router-act\n  source: ./skills/router-act\n- name: run-tests\n  source: ./skills/run-tests\n- name: runtime-debug\n  source: ./skills/runtime-debug\n- name: rust-turbopack\n  source: ./skills/rust-turbopack\n- name: sandbox-bench\n  source: ./skills/sandbox-bench\n- name: update-docs\n  source: ./skills/update-docs\n- name: v8-jit\n  source: ./skills/v8-jit\n- name: write-api-reference\n  source: ./skills/write-api-reference\n- name: write-guide\n  source: ./skills/write-guide\nx-origin:\n  repository: https://github.com/vercel/next.js\n  commit: 012544435e7e4891d272809c9132a488c39e2791\n  license: MIT\n  license_basis: detected\n  license_files:\n  - license.md\n  absorbed_at: '2026-11-27'\n", "license.md": "The MIT License (MIT)\n\nCopyright (c) 2025 Vercel, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n", "skills/authoring-skills/SKILL.md": "---\nname: authoring-skills\ndescription: >\n  How to create and maintain agent skills in .agents/skills/. Use when\n  creating a new SKILL.md, writing skill descriptions, choosing frontmatter\n  fields, or deciding what content belongs in a skill vs AGENTS.md.\n  Covers the supported spec fields, description writing, naming conventions,\n  and the relationship between always-loaded AGENTS.md and on-demand skills.\nuser-invocable: false\nmetadata:\n  internal: true\n---\n\n# Authoring Skills\n\nUse this skill when creating or modifying agent skills in `.agents/skills/`.\n\n## When to Create a Skill\n\nCreate a skill when content is:\n\n- Too detailed for AGENTS.md (code templates, multi-step workflows, diagnostic procedures)\n- Only relevant for specific tasks (not needed every session)\n- Self-contained enough to load independently\n\nKeep in AGENTS.md instead when:\n\n- It's a one-liner rule or guardrail every session needs\n- It's a general-purpose gotcha any agent could hit\n\n## File Structure\n\n```\n.agents/skills/\n└── my-skill/\n    ├── SKILL.md          # Required: frontmatter + content\n    ├── workflow.md        # Optional: supplementary detail\n    └── examples.md        # Optional: referenced from SKILL.md\n```\n\n## Supported Frontmatter Fields\n\n```yaml\n---\nname: my-skill # Required. Used for $name references and /name commands.\ndescription: > # Required. How Claude decides to auto-load the skill.\n  What this covers and when to use it. Include file names and keywords.\nargument-hint: '<pr-number>' # Optional. Hint for expected arguments.\nuser-invocable: false # Optional. Set false to hide from / menu.\ndisable-model-invocation: true # Optional. Set true to prevent auto-triggering.\nallowed-tools: [Bash, Read] # Optional. Tools allowed without permission.\nmodel: opus # Optional. Model override.\ncontext: fork # Optional. Isolated subagent execution.\nagent: Explore # Optional. Subagent type (with context: fork).\n---\n```\n\nOnly use fields from this list. Unknown fields are silently ignored.\n\n## Writing Descriptions\n\nThe `description` is the primary matching surface for auto-activation. Include:\n\n1. **What the skill covers** (topic)\n2. **When to use it** (trigger scenario)\n3. **Key file names** the skill references (e.g. `config-shared.ts`)\n4. **Keywords** a user or agent might mention (e.g. \"feature flag\", \"DCE\")\n\n```yaml\n# Too vague - won't auto-trigger reliably\ndescription: Helps with flags.\n\n# Good - specific files and concepts for matching\ndescription: >\n  How to add or modify Next.js experimental feature flags end-to-end.\n  Use when editing config-shared.ts, config-schema.ts, define-env-plugin.ts.\n```\n\n## Content Conventions\n\n### Structure for Action\n\nSkills should tell the agent what to **do**, not just what to **know**:\n\n- Lead with \"Use this skill when...\"\n- Include step-by-step procedures\n- Add code templates ready to adapt\n- End with verification commands\n- Cross-reference related skills in a \"Related Skills\" section\n\n### Relationship to AGENTS.md\n\n| AGENTS.md (always loaded)               | Skills (on demand)                                                     |\n| --------------------------------------- | ---------------------------------------------------------------------- |\n| One-liner guardrails                    | Step-by-step workflows                                                 |\n| \"Keep require() behind if/else for DCE\" | Full DCE pattern with code examples, verification commands, edge cases |\n| Points to skills via `$name`            | Expands on AGENTS.md rules                                             |\n\nWhen adding a skill, also add a one-liner summary to the relevant AGENTS.md section with a `$skill-name` reference.\n\n### Naming\n\n- Short, descriptive, topic-scoped: `flags`, `dce-edge`, `react-vendoring`\n- No repo prefix (already scoped by `.agents/skills/`)\n- Hyphens for multi-word names\n\n### Supplementary Files\n\nFor complex skills, use a hub + detail pattern:\n\n```\npr-status-triage/\n├── SKILL.md         # Overview, quick commands, links to details\n├── workflow.md      # Prioritization and patterns\n└── local-repro.md   # CI env matching\n```\n", "skills/backport-pr/SKILL.md": "---\nname: backport-pr\ndescription: >\n  Backport a merged Next.js pull request from canary to an LTS release branch\n  (releases/lts/active or releases/lts/maintenance). Use when the user asks to\n  backport, cherry-pick, or open a backport PR from a PR number to an older\n  Next.js version. Covers finding the merged PR commit, creating a backport\n  branch from the target release branch, cherry-picking from canary,\n  validating, and opening the PR with the release branch as the base.\nmetadata:\n  internal: true\n---\n\n# Backport PR\n\nUse this skill when a user asks to backport a merged Next.js PR to a release\nbranch.\n\n## Inputs\n\n- Require a PR number and a target release branch. Almost always the target\n  is one of the LTS branches: `releases/lts/active` (the current major's\n  release line) or `releases/lts/maintenance` (the previous major's). Only in\n  exceptionally rare circumstances — a fix for an older minor line that\n  neither LTS branch supports anymore — is the target a non-LTS branch\n  (`next-<major>-<minor>`, which any maintainer can create by pushing a\n  branch from that line's last tag).\n- If the target branch is not provided and cannot be inferred confidently from\n  the user's request, ask before mutating git state — and default to an LTS\n  branch unless the user explicitly names an old minor line.\n- Treat the target branch as variable; do not hard-code a specific branch\n  except when the user explicitly asks for it.\n\n## Workflow\n\n1. Inspect the current worktree before changing branches:\n\n   ```bash\n   git status --short\n   git branch --show-current\n   ```\n\n   Preserve unrelated user changes. Do not overwrite, reset, or stash them\n   without the user's consent.\n\n2. Sync the source and target branches:\n\n   ```bash\n   git fetch origin canary:refs/remotes/origin/canary <target-branch>:refs/remotes/origin/<target-branch>\n   ```\n\n3. Identify the commit that landed the PR on `canary`:\n\n   ```bash\n   gh pr view <pr-number> --repo vercel/next.js --json number,title,state,url,mergeCommit,baseRefName,headRefName\n   git log origin/canary --oneline --fixed-strings --grep=\"(#<pr-number>)\"\n   ```\n\n   Prefer `mergeCommit.oid` when the PR is `MERGED` and the commit is contained\n   in `origin/canary`. If GitHub does not return a usable merge commit, use the\n   `git log --grep` result and verify the commit subject references the PR\n   number.\n\n4. Create the backport branch from the release branch:\n\n   ```bash\n   git switch -c backport-<pr-number>-to-<target-branch> origin/<target-branch>\n   ```\n\n   Bootstrapping this checkout does not require `pnpm build-all` since\n   `pnpm install` pulls in recent native bindings. Before running Next.js\n   integration tests, build what the branch switch and cherry-pick changed:\n   `pnpm build` for JS changes, `pnpm build-all` only for Rust/Turbopack\n   changes. Skip builds entirely if the task is limited to preparing the\n   cherry-pick or PR.\n\n5. Cherry-pick the landed commit with provenance:\n\n   ```bash\n   git cherry-pick -x <merged-commit-sha>\n   ```\n\n   Resolve conflicts in favor of preserving the release branch's compatibility\n   constraints. If the cherry-pick is empty, verify whether the change is already\n   present on the release branch and report that instead of opening a duplicate\n   PR.\n\n6. Verify with the narrowest commands that cover the touched files. Prefer\n   focused tests, `pnpm types` for TypeScript-only risk, and the relevant\n   integration test mode for behavior changes.\n\n7. Open the backport PR using `$create-pr`.\n\n   Override the normal `$create-pr` base branch: use `--base <target-branch>`,\n   not `canary`. Keep the PR as a draft unless the user explicitly asks\n   otherwise.\n\n## PR Shape\n\nThe PR title should indicate the target branch and the original PR title.\n\nUse a title like:\n\n```text\n[lts-active] <original PR title>\n```\n\nor\n\n```text\n[lts-maintenance] <original PR title>\n```\n\nUse a concise PR body:\n\n```markdown\nBackports <original PR title/link> to `<target-branch>`.\n\n<!-- NEXT_JS_LLM -->\n```\n\n## Related Skills\n\n- `$create-pr` - Create the branch commit, push it, and open the draft PR.\n- `$pr-status-triage` - Check CI failures or review feedback after the PR exists.\n", "skills/create-pr/SKILL.md": "---\nname: create-pr\ndescription: >\n  Create Git branches, commits, pushes, and GitHub pull requests for Next.js.\n  Use when the user asks to create a branch, commit current changes, open a\n  PR or draft PR, publish a pull request, or recover from gh pr create / PR\n  template issues. Covers .github/pull_request_template.md, --body formatting,\n  <agent-name>/ branch names, and Codex app git directives.\nmetadata:\n  internal: true\n---\n\n# Create PR\n\nUse this skill when turning local work into a GitHub pull request.\n\n## Fork PRs vs Branch PRs\n\nBefore writing a PR description, check whether this is a branch PR (the\nbranch lives in `vercel/next.js`) or a fork PR (an external contribution from\na fork). You may write full descriptions for branch PRs, but not for fork\nPRs — inform the user, offer to review their description or provide technical\ndetails, and give them the GitHub URL to create the PR themselves. See\n\"GitHub Pull Requests and Issues\" in `AGENTS.md` for the full policy.\n\n## Workflow\n\n1. Inspect the current state before mutating Git:\n\n   ```bash\n   git status --short\n   git branch --show-current\n   git diff -- <paths>\n   ```\n\n   Stage only files that belong to the requested change. Preserve unrelated\n   user changes.\n\n2. Create or confirm the branch:\n\n   ```bash\n   git switch -c <agent-name>/<short-topic>\n   ```\n\n   Prefix the branch with your agent's name as a single lowercase word, such\n   as `codex/`, `claude/`, or `fleet/` (e.g. `claude/<short-topic>`), unless\n   the user asks for a different name. If a\n   `.git/*lock` or `Operation not permitted` error appears, rerun the same Git\n   command with sandbox escalation. Do not assume a branch namespace conflict\n   until checking refs with `git branch --list`, `git show-ref`, or\n   `git for-each-ref`.\n\n3. Validate and commit:\n\n   ```bash\n   git add <paths>\n   git diff --cached --check\n   git commit -m \"<concise message>\"\n   ```\n\n   Keep commit messages concise and do not add generated-tool or co-author\n   footers.\n\n4. Push the branch:\n\n   ```bash\n   git push -u origin <branch>\n   ```\n\n5. Create the PR as a draft unless the user explicitly asks otherwise:\n\n   ```bash\n   gh pr create --draft --base canary --head <branch> --title \"<title>\" --body '<body>'\n   ```\n\n   For this repo, prefer `canary` as the base branch. If GitHub network access\n   fails in the sandbox, rerun with escalation.\n\n## PR Body\n\nFollow the \"PR Descriptions\" section in `AGENTS.md`: the\n`.github/pull_request_template.md` structure (`What?` / `Why?` / `How?`, issue\nlinks) plus a `Verification` section. Use this PR body format:\n\n```markdown\n### What?\n\n<what changed>\n\n### Why?\n\n<motivation>\n\n### How?\n\n<implementation notes, if not obvious from the diff>\n\nFixes #<number>\n\n### Verification\n\n- `<command that passed>`\n- Not run: `<command>` (`<reason>`)\n\n<!-- NEXT_JS_LLM -->\n```\n\nThe \"what\" should be explained from the end-user perspective or developer perspective. Only include implementation changes in \"How?\" if they're not obvious from the diff.\n\nA \"why\" should be included if the change isn't self-explanatory, or if the motivation is not clear from the diff.\nOmitting the \"why\" should be used sparingly and only for small changes.\n\nDo not include trivial verification commands that CI already covers (e.g. `pnpm run build`), but do include any manual verification steps. If the PR changes a test, you don't need to repeat the command to run that test. But if you used an existing test to validate some behavior didn't change, include that test.\n\nUse `--body` with this filled content.\n\n## Recovery\n\n- If a PR may already exist, check before creating a duplicate:\n\n  ```bash\n  gh pr view --head <branch> --json url,isDraft,title\n  ```\n\n- If approval is denied for `gh pr create`, report that the branch is pushed\n  but the PR was not created, and provide the exact corrected command.\n- After successful Codex app Git actions, include the appropriate final-response\n  directives for branch creation, staging, committing, pushing, and PR creation.\n\n## Related Skills\n\n- `$pr-status-triage` - Analyze CI failures and PR review feedback after the PR exists.\n- `$gh-stack` - Manage stacked branches and dependent pull requests.\n- `$rebase-pr` - Rebase a PR onto canary or restack dependent PRs.\n", "skills/dce-edge/SKILL.md": "---\nname: dce-edge\ndescription: >\n  DCE-safe require() patterns and edge runtime constraints. Use when writing\n  conditional require() calls, guarding Node-only imports (node:stream etc.),\n  or editing define-env-plugin.ts / app-render / stream-utils for edge builds.\n  Covers if/else branching for webpack DCE, TypeScript definite assignment,\n  the NEXT_RUNTIME vs real feature flag distinction, and forcing flags false\n  for edge in define-env.ts.\nmetadata:\n  internal: true\n---\n\n# DCE + Edge\n\nUse this skill when changing conditional `require()` paths, Node-only imports, or edge/runtime branching.\n\n## DCE-Safe `require()` Pattern\n\nWebpack only DCEs a `require()` when it sits inside the dead branch of an `if/else` whose condition DefinePlugin can evaluate at compile time.\n\n```ts\n// CORRECT - webpack can eliminate the dead branch\nif (process.env.__NEXT_USE_NODE_STREAMS) {\n  require('node:stream')\n} else {\n  // web path\n}\n```\n\nWhat does NOT work:\n\n- **Early-return/throw guards**: webpack doesn't do control-flow analysis for throws/returns, so the `require()` is still traced.\n- **Bare `if` without `else`**: works for inline `node:*` specifiers but NOT for `require('./some-module')` that pulls a new file into the module graph.\n\nAlways test edge changes with `pnpm test-start-webpack` on `test/e2e/app-dir/app/standalone.test.ts` (has edge routes), not with `NEXT_SKIP_ISOLATE=1` which skips the full webpack compilation.\n\n## TypeScript + DCE Interaction\n\nUse `if/else` (not two independent `if` blocks) when assigning a variable conditionally on `process.env.X`. TypeScript cannot prove exhaustiveness across `if (flag) { x = a }; if (!flag) { x = b }` and will error with \"variable used before being assigned\". The `if/else` pattern satisfies both TypeScript (definite assignment) and webpack DCE.\n\n## Compile-Time Switcher Pattern\n\nPlatform-specific code (node vs web) can use a single `.ts` switcher module that conditionally `require()`s either `.node.ts` or `.web.ts` into a typed variable, then re-exports the shared runtime API as named exports. Keep the branch as `if/else` so DefinePlugin can dead-code-eliminate the unused `require()`. Keep shared types canonical in `.node.ts`, with `.web.ts` importing them via `import type` and the switcher re-exporting types as needed. Examples: `stream-ops.ts` and `debug-channel-server.ts`.\n\n## `NEXT_RUNTIME` Is Not a Feature Flag\n\nIn user-project webpack server compilers, `process.env.NEXT_RUNTIME` is inlined to `'nodejs'`. Guarding Node-only `require('node:*')` paths with `NEXT_RUNTIME === 'nodejs'` does **not** prune anything. For feature-gated codepaths, guard on the real feature define (e.g. `process.env.__NEXT_USE_NODE_STREAMS`).\n\n## Edge Runtime Constraints\n\nEdge routes do NOT use pre-compiled runtime bundles. They are compiled by the user's webpack/Turbopack, so `define-env.ts` controls DCE. Feature flags that gate `node:*` imports must be forced to `false` for edge builds in `define-env.ts` (`isEdgeServer ? false : flagValue`), otherwise webpack will try to resolve `node:stream` etc. and fail.\n\n## `app-page.ts` Template Gotchas\n\n- `app-page.ts` is a build template compiled by the user's bundler. Any `require()` in this file is traced by webpack/turbopack at `next build` time. You cannot require internal modules with relative paths because they won't be resolvable from the user's project. Instead, export new helpers from `entry-base.ts` and access them via `entryBase.*` in the template.\n- Template helpers should stay out of `RenderResult`. If `app-page.ts` needs a Node-stream-only utility, prefer a small dedicated helper module in `server/stream-utils/` (with DCE-safe `if/else` + `require()`).\n\n## Verification\n\n- Validate edge bundling regressions with `pnpm test-start-webpack test/e2e/app-dir/app/standalone.test.ts`\n- For module-resolution/build-graph fixes, verify without `NEXT_SKIP_ISOLATE=1`\n\n## Related Skills\n\n- `$flags` - flag wiring (config/schema/define-env/runtime env)\n- `$react-vendoring` - entry-base boundaries and vendored React\n- `$runtime-debug` - reproduction and verification workflow\n", "skills/deploy-release-test/SKILL.md": "---\nname: deploy-release-test\ndescription: >\n  Validate a commit-specific Next.js preview package and manually trigger the\n  entire Next.js deployment test suite through the test_e2e_deploy_release.yml\n  GitHub Actions workflow. Use only when asked to run the full deploy test suite\n  or this workflow specifically from an internal vercel/next.js PR branch. Do\n  not use for focused deployment-test sanity checks; run the relevant tests\n  locally with pnpm test-deploy instead. Covers resolving the latest branch SHA,\n  waiting for vercel-packages, preserving default workflow inputs, dispatching\n  the workflow, and verifying the run.\nmetadata:\n  internal: true\n---\n\n# Deploy Release Test\n\nUse this skill only when manually running the entire Next.js deployment test\nsuite for a pull request. Treat package validation as a hard gate: never\ndispatch the workflow until the exact commit's redirected tarball responds\nsuccessfully.\n\n## Scope\n\nDo not use this workflow to sanity-check one deployment test or a focused group\nof tests. Follow\n[Running Deploy Tests Locally](../../../contributing/core/testing.md#running-deploy-tests-locally)\ninstead:\n\n```bash\nNEXT_TEST_VERSION=https://vercel-packages.vercel.app/next/commits/<commit-sha>/next pnpm test-deploy <path-to-test>\n```\n\nIf a request to \"run deploy tests\" does not explicitly call for the entire\nsuite, prefer the focused local workflow and scope it to the affected tests.\n\n## Inputs\n\n- Accept a PR number or determine the PR from the current branch.\n- Use repository `vercel/next.js` and workflow\n  `.github/workflows/test_e2e_deploy_release.yml`.\n- Require the PR head branch to exist in `vercel/next.js`. A fork branch cannot\n  run this secret-bearing workflow; use the repository's PR adoption process\n  first when appropriate.\n\n## Workflow\n\n1. Resolve the PR branch and its latest commit from GitHub, not merely from the\n   local checkout:\n\n   ```bash\n   gh pr view <pr-number> --repo vercel/next.js \\\n     --json number,url,headRefName,headRefOid,isCrossRepository\n   ```\n\n   If no PR number was supplied, omit `<pr-number>` to detect the PR from the\n   current branch. Stop if `isCrossRepository` is `true`. Record `headRefName`\n   as the branch and `headRefOid` as the commit SHA.\n\n2. Construct the exact package URL:\n\n   ```text\n   https://vercel-packages.vercel.app/next/commits/<commit-sha>/next\n   ```\n\n3. Wait for the package to become downloadable before dispatching anything:\n\n   ```bash\n   node scripts/wait-for-preview-tarball.mjs --commit-sha <commit-sha>\n   ```\n\n   Keep the wait in an ongoing terminal session and poll it so the user still\n   receives progress updates. The helper uses `HEAD`, follows the redirect to\n   Vercel Blob, and only succeeds when the final artifact is available. Do not\n   substitute a check that accepts the initial redirect: that endpoint can\n   redirect even while the blob still returns 404.\n\n   If the helper times out or reports an authorization or build failure, do not\n   dispatch the workflow. Report the failure and inspect the commit's\n   `build-and-deploy` / `upload-preview-tarballs` checks if useful.\n\n4. Resolve the PR again immediately after validation. Compare the current\n   `headRefName` and `headRefOid` with the recorded values. If either changed,\n   return to step 2 and validate the new commit-specific URL. Never reuse the\n   old package URL for a moved branch.\n\n5. Trigger the workflow from the PR branch and pass only `nextVersion`:\n\n   ```bash\n   gh workflow run test_e2e_deploy_release.yml \\\n     --repo vercel/next.js \\\n     --ref <pr-branch> \\\n     -f nextVersion=https://vercel-packages.vercel.app/next/commits/<commit-sha>/next\n   ```\n\n   Do not pass any other `-f` values. Leaving them unspecified preserves the\n   workflow defaults, including `vercelCliVersion: vercel@latest` and empty\n   optional overrides.\n\n6. Find and verify the newly created run:\n\n   ```bash\n   gh run list --repo vercel/next.js \\\n     --workflow test_e2e_deploy_release.yml \\\n     --branch <pr-branch> \\\n     --event workflow_dispatch \\\n     --limit 5 \\\n     --json databaseId,url,status,conclusion,headBranch,headSha,displayTitle,createdAt\n   ```\n\n   Confirm that the newest matching run has:\n   - `headBranch` equal to the PR branch\n   - `headSha` equal to the validated commit SHA\n   - `displayTitle` containing the exact commit-specific package URL\n\n   A race can still move the branch between the final check and dispatch. If the\n   run's `headSha` differs, report the mismatch and do not trigger another run\n   until the new SHA's package has been validated.\n\n## Completion Report\n\nReport the PR branch, validated SHA and package URL, workflow run URL, and its\ncurrent status. Do not wait for the full deployment suite unless the user asks\nyou to monitor it.\n\n## Related Skills\n\n- `$pr-status-triage` - Inspect failures if the deployment workflow does not pass.\n- `$create-pr` - Create or update the internal PR branch before deployment testing.\n", "skills/deploy-release-test/agents/openai.yaml": "interface:\n  display_name: 'Deploy Release Test'\n  short_description: 'Trigger the full deploy release test suite'\n  default_prompt: 'Use $deploy-release-test to validate the latest PR commit package and trigger the full Next.js deployment test suite.'\n", "skills/docs-diagrams/SKILL.md": "---\nname: docs-diagrams\ndescription: >\n  Draw diagrams for the Next.js docs in the style of the ones already\n  published there: the light/dark PNGs an mdx references with\n  `<Image srcLight=\"/docs/light/<name>.png\" srcDark=\"/docs/dark/<name>.png\">`.\n  Use when a guide or API reference needs a new diagram or an existing one\n  needs a change. Hand-written SVG from a primitives library, rendered by\n  headless Chrome at 2x. No AI image generation.\ndisable-model-invocation: true\nmetadata:\n  internal: true\n---\n\n# Docs diagrams\n\nUse the diagrams already published in the docs as references. They share a faint grid background, bordered panels with soft shadows, gray skeleton UI, gray arrows, and a small accent palette in which each color has a consistent meaning. This skill reproduces that visual language from code.\n\n## Files\n\n| Task                                                          | Read                                       |\n| ------------------------------------------------------------- | ------------------------------------------ |\n| Colors, sizes, fonts, what each color means, shape anatomy    | [style-tokens.md](style-tokens.md)         |\n| Reviewing a render before handing it off                      | [review-checklist.md](review-checklist.md) |\n| Primitives: canvas, panels, tree rows, windows, holes, badges | [scripts/lib.mjs](scripts/lib.mjs)         |\n| Generate SVG + HTML for every diagram module                  | [scripts/gen.mjs](scripts/gen.mjs)         |\n| Screenshot light + dark PNGs at 2x                            | [scripts/render.sh](scripts/render.sh)     |\n| Measure a render's margins from the ink                       | [scripts/measure.py](scripts/measure.py)   |\n\n## Workflow\n\n### 1. Read the mdx\n\nThe `<Image>` block gives you the file names (`srcLight=\"/docs/light/<name>.png\"`), the `width` and `height` the page reserves, and the `alt` text, which is the brief.\n\nThe paragraph before the image often states the color legend in words (\"gray marks static output and blue marks content that can render at request time\"). When it does, the drawing has to match that sentence exactly. When it does not, take the states the alt text names (a Suspense fallback, request-time content), map them with \"What the colors mean\" in [style-tokens.md](style-tokens.md), and suggest adding the legend sentence to the mdx in your hand-off.\n\nDraw only what the brief names. The alt text and surrounding paragraph determine which values, rows, and labels appear. Use the labels from the alt text and `docs/01-app/04-glossary.mdx` for terminology the brief leaves open.\n\n### 2. Pull references from the docs\n\nThe images are not in this repo; they are served from the docs blob store. List what exists and fetch two or three that explain something similar, in both themes, before drawing:\n\n```bash\ngrep -rhoE 'srcLight=\"[^\"]+\"' docs | sort -u\ncurl -sL -o ref.png \"https://h8DxKfmAPhn8O0p3.public.blob.vercel-storage.com/docs/light/nested-layouts.png\"\n```\n\nUse the full `srcLight` path: most images live under `/docs/`, some under `/learn/`. Swap `light` for `dark` for the dark variant. If the page you are drawing for already has images, those are the first references. Look at more than one: the anatomy is consistent, and you want the shared parts rather than one image's quirks. Published files are a mix of 1x and 2x; that is history, not a target. Always produce 2x.\n\n### 3. Write a diagram module\n\nCopy `scripts/` into a scratch folder outside the repo and add `diagrams/<name>.mjs`:\n\n```js\nexport default {\n  name: 'my-diagram', // must equal the mdx srcLight basename\n  width: 1600, // what the mdx declares\n  height: 700,\n  draw(t, lib, { width, height }) {\n    const k = width / 1600\n    const s = []\n    // compose lib primitives here, laid out from a few named constants\n    return s.join('\\n')\n  },\n}\n```\n\n`lib.mjs` has the shapes the docs are built from:\n\n- Panels and rows: `panel`, `treePanel`, `urlPill`, `urlStack`, `codePanel`.\n- Arrows and captions: `arrow`, `bracketArrow`, `bracketCaption`, `callout`.\n- Browser windows: `browserWindow(t, x, y, w, h, url, body = '')` for the frame, `pageLayout` for the page inside it, `postCard` and `commentRows` for the content, `skel.*` for single placeholders. Pass the URL and body as positional arguments.\n- States and comparisons: `hole` (not rendered yet), `card` (rendered or highlighted), `grid` (columns and spans for bars).\n- Badges and legends: `badge`, `statusBadge`, `legendRow`, `swatchLegend`.\n- Text: `label`, `code`, `textWidth` for sizing a block around a label, and the `icons`.\n\nBuild a window's page with `pageLayout` rather than placing skeleton atoms by hand. It carries the spacing that makes placeholders read as a page, and returns `regions.post` and `regions.comments` for the usual split of the content column.\n\nWhen the brief describes moments or stages (before and after, Shell → Prefetch → Navigation), the docs show them as a row of browser windows with arrows between them, each window showing the page at that moment. Content that has rendered at one moment stays rendered, in the same style, in every later moment. When values or APIs need comparing across the moments, bar rows go underneath, split at the gaps between the windows. `grid` lays out those bars; its column headers sit under the windows and double as their captions (the comment on `grid` says how to line the two up). Use `grid` on its own when windows would add nothing.\n\nLay the block out from named constants and center it on the canvas. When a diagram needs a shape `lib` does not have, add it to `lib.mjs` using the existing tokens, in the same style, so the next diagram gets it too. Never hard-code a color or a one-off offset inside a shape.\n\nA module may export an array of diagrams when several share a drawing. Helper modules without a default export are skipped.\n\n### 4. Render\n\nRun `./render.sh` from inside the scratch folder. It runs `node gen.mjs` and screenshots each `<name>-<theme>.html` with headless Chrome at `--force-device-scale-factor=2`. Output lands in `light/<name>.png` and `dark/<name>.png`, the names the mdx expects. `node gen.mjs <name>` regenerates one diagram while iterating.\n\nThe script defaults to the macOS Google Chrome path. On Linux, Windows, or a machine with Chrome installed elsewhere, set `CHROME` to the browser executable:\n\n```bash filename=\"Terminal\"\nCHROME=/path/to/chrome ./render.sh\n```\n\n### 5. Review\n\nLook at both PNGs at full size, against [review-checklist.md](review-checklist.md) and against the references from step 2. Run `python3 scripts/measure.py light/<name>.png` for the margins. Fix in constants and re-render. Do not hand off a PNG you have not looked at.\n\n### 6. Hand off\n\nDeliver the PNGs with their pixel dimensions and the mdx path each one matches. Uploading to the blob store is a manual step by the docs maintainer, so the PNGs are the deliverable, not a commit. Check that the mdx `srcLight` basename and the PNG name agree, including singular vs plural. If you added a primitive to `lib.mjs`, commit it back into this skill, or hand off the diff if you cannot commit.\n\n## What the docs typically draw\n\nThe published diagrams are combinations of a few shapes. These are the common kinds, each with a page where you can see it. There are more, and a new concept may need a new combination.\n\n- **File tree → URL**: a file-tree panel (folder, file, layout and route icons; the row the page is about is bold with a blue dot; elided children are a gray `...` row) with gray arrows to URL pills (globe + path, gray-filled when the path is not routable), bracket arrows beside the tree for which layout wraps which routes, and mono status badges (`Routable`, `Not Routable`). See [Layouts and Pages](https://nextjs.org/docs/app/getting-started/layouts-and-pages) and [Project structure](https://nextjs.org/docs/app/getting-started/project-structure).\n- **Files → component hierarchy**: a file list with an arrow to a code panel (React logo and a title in the bar, nested JSX in the docs' syntax colors). See [Project structure](https://nextjs.org/docs/app/getting-started/project-structure).\n- **Browser window with skeleton UI**: traffic lights and a URL pill, the page as gray skeleton shapes (avatar, bars, sidebar, image placeholders). Content that has not rendered yet is a dashed hole; content that has arrived or is the subject is a solid accent card, sometimes floated outside the window with a blue arrow. A row of windows with arrows between them shows a sequence; bracket captions underneath name the groups. See [Fetching Data](https://nextjs.org/docs/app/getting-started/fetching-data) and [Caching](https://nextjs.org/docs/app/getting-started/caching).\n- **Region map with badges**: a window whose regions are outlined and tinted by category, each tagged with a letter badge, with callouts on leader lines and a legend. The same badges tag rows in a tree and lines in a code panel so the views cross-reference. See [Parallel Routes](https://nextjs.org/docs/app/api-reference/file-conventions/parallel-routes).\n- **Zone graph**: dashed, color-coded boxes with a tag in the corner, mono route pills inside, gray arrows between them labelled with mono pills (`SOFT NAV`, `HARD NAV`). See [Multi-zones](https://nextjs.org/docs/app/guides/multi-zones).\n\nSome docs images are product screenshots (DevTools panels, the bundle analyzer, OS dialogs). Capture those from the real UI; this skill does not draw them.\n\n## Conventions\n\n**Canvas.** The docs canvas is 1600 CSS px wide and the page scales it to the column, so the sizes in the tokens are sizes at 1600. For a new diagram, declare 1600 and let the height follow the content. If a page already declares a narrower width, match it and scale element sizes by `k = width / 1600`, otherwise the picture renders larger than its neighbours once the page scales it. `grid`, `swatchLegend`, `arrow`, `pageLayout`, `postCard` and `commentRows` take or derive `k` and scale their defaults by it; pass `× k` sizes to `skel.*`, `hole` and `card` yourself.\n\n**Margins.** The mdx `height` wins: fit the content to the declared box. Top must equal bottom and left must equal right, within 4px; the two pairs need not match each other. Measure from the ink with `scripts/measure.py`, not from the coordinates you passed: text drawn with `dominant-baseline=\"central\"` has its visual top about `0.35 × size` above its `y`, and `textWidth` is a heuristic, so expect to nudge by a few px after measuring.\n\n**Color.** Within one picture a color means exactly one thing in the bars and the legend; if the legend says blue is \"request-time content\", nothing else may be blue. In the windows, rendered UI is always gray skeleton, whatever the bars say gray means; that is the docs' convention. Blue in a window marks the one state the picture is about (not included in static output, or newly rendered), the same state blue marks in the bars. See \"What the colors mean\" in [style-tokens.md](style-tokens.md).\n\n**Alignment.** Equal margins, shared edges, text centered in its box, arrows and splits lined up vertically through the whole diagram. This is the review bar.\n\n**Type.** Code and routes in Geist Mono, everything else in Inter. Geist Mono must be installed locally; the fallback is `ui-monospace`.\n\n## Related skills\n\n- `$write-guide` and `$write-api-reference` produce the mdx that references these images.\n- `$update-docs` for finding which docs pages a code change touches.\n", "skills/docs-diagrams/review-checklist.md": "# Review checklist\n\nOpen both PNGs at full size next to the reference images, then complete this checklist before handing anything off. Each item comes from a problem found in a real draft.\n\n## Against the references\n\n- [ ] Same kind, same anatomy: a reader could not tell this image was drawn by someone else.\n- [ ] Colors mean what they mean in the neighbouring diagrams (see \"What the colors mean\" in [style-tokens.md](style-tokens.md)). No accent used only to fill the palette.\n- [ ] Within this picture every accent means one thing, in every part of the picture (windows, bars, legend).\n\n## Edges and padding\n\n- [ ] Nothing inside a panel touches its border. Holes, cards and rows sit inside the padding.\n- [ ] Sibling elements share top and bottom edges (sidebar squares vs content box, tree rows vs their URL pills).\n- [ ] Skeleton UI reads as a page: avatars are round and sit in their row, bars have breathing room, the post is a card and the comments are rows, the sidebar is clearly separate from the content. If a window's page was laid out by hand instead of `pageLayout`, check these especially.\n- [ ] Every card or hole spans the full width of its content box.\n- [ ] Bars and brackets start and end on the edges of the things they describe, to the pixel.\n\n## Composition\n\n- [ ] Left equals right and top equals bottom, within 4px. Measure from the ink with `python3 scripts/measure.py light/<name>.png` rather than trusting the coordinates you passed. The script ignores the grid; panel shadows still count, so the bottom reads a few px smaller than it is.\n- [ ] On a canvas narrower than 1600, element sizes were scaled by `width / 1600`, so the picture will not render larger than its neighbours.\n- [ ] The whole block is centered as one unit, not each column separately.\n- [ ] Arrow heads, bar splits and leader lines line up with what they point at.\n- [ ] Captions are centered under their windows or brackets.\n\n## Text\n\n- [ ] Labels are vertically centered (`dominant-baseline=\"central\"`, not a hand-tuned `y`).\n- [ ] Inter actually loaded: compare the \"a\" and \"g\" with a reference image. If Chrome screenshotted a fallback font, raise `--virtual-time-budget`.\n- [ ] Code, routes and mono pills are in Geist Mono.\n- [ ] Labels use the docs' terms (App Shell, Suspense fallback, per-link prefetch, Route Group). Check the glossary when unsure.\n- [ ] Nothing is clipped at the canvas edge.\n\n## Meaning\n\n- [ ] The colors match the legend sentence in the mdx paragraph before the `<Image>`.\n- [ ] Only what the brief names is in the picture: no extra rows, values or labels pulled in from elsewhere.\n- [ ] Each frame of a sequence shows the right amount of content for its moment.\n- [ ] The alt text in the mdx still describes this picture.\n- [ ] Width and height in the mdx match the SVG (the PNG is exactly 2× each).\n\n## Both themes\n\n- [ ] Dark background is `#0D0D0D`, not pure black. Grid lines are visible but faint.\n- [ ] Accent fills in dark mode are the navy / plum / wine tokens, not the light-mode pastels.\n- [ ] Shadows are stronger in dark mode and barely visible in light mode.\n\n## Files\n\n- [ ] Output names equal the mdx `srcLight` / `srcDark` basenames, including singular vs plural.\n- [ ] You handed off `light/<name>.png` and `dark/<name>.png` with their pixel dimensions and the mdx each belongs to.\n- [ ] Any primitive you added to `lib.mjs` is committed back into this skill so the next diagram gets it.\n", "skills/docs-diagrams/style-tokens.md": "# Style tokens\n\nMeasured from published docs diagrams of every kind listed in SKILL.md. All values are CSS px on a 1600-wide canvas; `lib.mjs` holds the same values in its `themes` object. Use the token, not a new hex.\n\n## Canvas\n\n| Property   | Value                                                                                                                                  |\n| ---------- | -------------------------------------------------------------------------------------------------------------------------------------- |\n| Width      | 1600 (render at 2x → 3200). Match the width the mdx declares if a page uses another.                                                   |\n| Height     | per diagram, declared in the mdx                                                                                                       |\n| Background | light `#FBFBFB`, dark `#0D0D0D`                                                                                                        |\n| Grid       | 40px squares, 1px lines, light `#F7F7F7`, dark `#161616`, an SVG `<pattern>` over the bg                                               |\n| Margins    | about 60 when the height is yours to choose; equal top/bottom and equal left/right always. Center the whole block, never left-align it |\n\n## Colors\n\n| Token                               | Light                                                                                            | Dark                                | Used for                                            |\n| ----------------------------------- | ------------------------------------------------------------------------------------------------ | ----------------------------------- | --------------------------------------------------- |\n| `panelTop` → `panelBottom`          | `#FFFFFF` → `#F9F9F9`                                                                            | `#313131` → `#282828`               | vertical gradient on every panel and window         |\n| `panelStroke`                       | `#D9D9D9`                                                                                        | `#484848`                           | 1px panel, pill and card borders                    |\n| `panelMuted`                        | `#F1F1F1`                                                                                        | `#1F1F1F`                           | gray-filled rows and pills (elided, not routable)   |\n| `divider`                           | `#E8E8E8`                                                                                        | `#434343`                           | 1px lines between rows                              |\n| `shadow`                            | `rgba(0,0,0,0.08)`                                                                               | `rgba(0,0,0,0.5)`                   | blurred rect under panels, offset 6px               |\n| `titleBar` / `titleBarDivider`      | `#F7F7F7` / `#E3E3E3`                                                                            | `#232323` / `#3A3A3A`               | browser and code panel title bars                   |\n| `text`                              | `#2E2E2E`                                                                                        | `#D4D4D4`                           | labels in trees and pills                           |\n| `textSubtle`                        | `#616161`                                                                                        | `#8F8F8F`                           | URL in the window bar, code panel title, callouts   |\n| `textMuted`                         | `#8F8F8F`                                                                                        | `#A1A1A1`                           | captions, legend text, muted rows                   |\n| `icon` / `iconMuted`                | `#9A9A9A` / `#CECECE`                                                                            | `#888888` / `#555555`               | folder, file, globe, lock glyphs                    |\n| `arrow`                             | `#A8A8A8`                                                                                        | `#878787`                           | arrows, brackets, bracket captions                  |\n| `skel`                              | `#C9C9C9`                                                                                        | `#4A4A4A`                           | skeleton bars, avatars, squares, image placeholders |\n| `blue.stroke` / `.fill` / `.text`   | `#0070F3` / `#D5E6FA` / `#0067D6`                                                                | `#0A72EF` / `#10233D` / `#52A8FF`   | the primary accent                                  |\n| `blue.dot`                          | `#197DF3`                                                                                        | `#0761C9`                           | the \"this file\" marker in trees                     |\n| `blue.skelOn` / `.thumbOn`          | `#A8B9CD` / `#C1D2E5`                                                                            | `#2F4A6E` / `#1E3657`               | skeleton inside a blue region                       |\n| `purple.stroke` / `.fill` / `.text` | `#8E4EC6` / `#EAE0F2` / `#793AAF`                                                                | `#9A5CD0` / `#2A1F38` / `#C4A1E6`   | second accent (static regions, zone C, slot B)      |\n| `red.stroke` / `.fill` / `.text`    | `#E5484D` / `#F7DFE0` / `#CA2A30`                                                                | same stroke / `#3A1D1F` / `#F08A8E` | negative badges, zone B                             |\n| `green.stroke` / `.fill` / `.text`  | `#46A758` / `#DCEBDF` / `#46A758`                                                                | same stroke / `#1B2E1F` / `#6FCB80` | positive badges                                     |\n| `gray.stroke` / `.fill` / `.text`   | `#8F8F8F` / `#DEDEDE` / `#666666`                                                                | `#6F6F6F` / `#2A2A2A` / `#B0B0B0`   | neutral mono pills (`SOFT NAV`)                     |\n| `static.stroke` / `.fill` / `.text` | `#C9C9C9` / `#F1F1F1` / `#666666`                                                                | `#4A4A4A` / `#1F1F1F` / `#B0B0B0`   | a static / prerendered region in a bar or grid cell |\n| `code.*`                            | GitHub Light: tag `#005CC5`, attr `#6F42C1`, keyword `#D73A49`, ident `#E36209`, punct `#909295` | GitHub Dark equivalents             | code panels                                         |\n| `code.react`                        | `#61DAFB`                                                                                        | same                                | React logo in code panel titles                     |\n| `trafficLights`                     | `#FF6059` `#FFBD2E` `#28CA42`                                                                    | same                                | the three window dots                               |\n\n## What the colors mean\n\nThe docs use color as a legend, so keep the meaning stable across a diagram and consistent with its neighbours:\n\n- **Gray**: static, prerendered, already there, or not the focus. Skeleton UI is always gray unless it sits inside an accent region. A static _region_ in a bar or grid cell is a stroked `static` card (`panelMuted` fill, `skel` stroke), so it has the same weight as the accent cards beside it; the darker `gray` accent is for mono pills.\n- **Blue, dashed stroke + fill**: not included in static output at this stage; can render at request time (a Suspense hole, \"request-time content\").\n- **Blue, solid stroke + fill**: content that has rendered, arrived, or is highlighted as the subject (streamed card, selected `<Link>`, slot A).\n- **Gray, dashed stroke, no fill**: a Suspense fallback standing in for content.\n- **Purple**: a second category next to blue (static vs dynamic regions, slot B, zone C), never a second shade of request-time content.\n- **Red / green**: judgments (not routable / routable). Only in badges and zone boxes.\n\nWithin one picture every accent means exactly one thing, and the same thing in every part of the picture. Rendered UI inside a window stays gray skeleton regardless; only the state the picture is about gets the accent.\n\n## Typography\n\n| Text                      | Font       | Size | Weight | Notes                                                      |\n| ------------------------- | ---------- | ---- | ------ | ---------------------------------------------------------- |\n| Tree rows, URL pills      | Inter      | 20   | 400    | 600 for the highlighted row; `dominant-baseline=\"central\"` |\n| Captions, legend text     | Inter      | 20   | 400    | `textMuted`                                                |\n| Callout labels            | Inter      | 22   | 600    | `textSubtle`, leader line in the region's accent           |\n| Window URL                | Inter      | 20   | 400    | `textSubtle`, after a lock glyph; scales with the window   |\n| Stage / column captions   | Inter      | 16   | 500    | `textMuted`, centered under the thing they name            |\n| Code panel body           | Geist Mono | 20   | 400    | 36px line height                                           |\n| Mono pills, status badges | Geist Mono | 18   | 400    | centered                                                   |\n| Letter badges             | Inter      | 19   | 500    | in a 32px rounded square                                   |\n\nInter comes from Google Fonts in the HTML wrapper (`display=block` so Chrome waits for it). Geist Mono must be installed locally (`~/Library/Fonts/GeistMono-*.otf`); if it is missing the fallback `ui-monospace` is acceptable but say so when you hand off.\n\n## Anatomy\n\n**Panel**: radius 10, 1px `panelStroke` snapped to the half pixel, `panelTop→panelBottom` gradient, shadow rect offset 6px blurred 8px.\n\n**Tree row**: 80 tall, 32px side padding, 18px icon, text 32px after the icon, 40px indent per depth, 1px `divider` between rows. Blue dot: 10px radius with a 16px radius `blue.fill` glow, 42px from the right edge. Muted row: `panelMuted` fill, muted icon and text.\n\n**URL pill**: a one-row panel, globe at 32px, path at 64px. Stack several in one panel with dividers when they belong to one tree.\n\n**Arrow**: 2px, round caps, open chevron head 10px long and 14px tall. Gray by default; blue when it carries streamed content. Bracket arrows beside a tree have a 10px corner radius and the same head.\n\n**Browser window**: reference size 527×476. Title bar 70 tall, traffic lights radius 9 at 37/65/93px, URL pill 320×44 radius 8 starting at 155px. All of it scales with the width you pass (`k = w / 527`).\n\n**Skeleton**: bars 24 tall radius 6, avatar radius 28, image placeholder is a tile with a sun and a mountain in `textMuted` at 60% opacity. Placeholders stand for real UI, so they keep real proportions: an avatar is a circle no taller than the row it sits in, bars have at least their own height of space between them, nothing touches a neighbour or the window edge.\n\n**Page inside a window** (`pageLayout`): 28px padding at `k = 1`. Header row: avatar radius 14 and a 16px title bar centered on it, 16px apart. 24px below, a 110px-wide sidebar of four 14px bars (widths 1 / 0.75 / 0.9 / 0.6) spread evenly from the content's top edge to its bottom edge, then 24px, then the content column to the right padding. Content is a `postCard` (outlined card, 16px padding, 14px title bar, 8px body lines 18px apart) and `commentRows` (7px avatars with one 8px line each), or a `hole` / `card` spanning the same rect when that content is not there yet. Everything scales with the window's `k`.\n\n**Hole**: 2px dashed stroke `8 5`, radius 10, fill from the accent. Optional centered label at `min(18, h/3)`. Scale `strokeWidth`, `dash` and `labelSize` down inside small windows.\n\n**Badges**: letter badge 32px square, radius 8, 2px accent stroke, `badgeFill`. Status pill 34 tall, radius 6, 1.5px stroke, mono text.\n\n**Grid**: column headers 20px/600 `textSubtle` with optional 15px subtitles (header 70 tall with subtitles, 48 without), a right-aligned mono label column, dashed `divider` lines between columns, rows 56 tall with 20px gaps, cells inset 10px from the dividers. All defaults scale with `k`. Cells are `card` / `hole` spans; a `swatchLegend` explains fill styles when the cells carry no text. Under a row of windows, the grid starts 16px below them.\n\n**Text metrics**: there are no font metrics at generation time. `textWidth(str, size, { mono })` is the heuristic (0.52 × size per character for Inter, 0.58 for Geist Mono); size blocks with it rather than a new constant, then measure.\n\n**Code panel**: 54px title bar with the React logo and a file name, 28px padding, 36px lines.\n\n## Crispness\n\nSnap every 1px stroke to a `.5` coordinate (`x + 0.5`, `width - 1`). Leave 1.5px and 2px strokes on integers. Render with `--force-device-scale-factor=2` and `--hide-scrollbars`.\n", "skills/docs-diagrams/scripts/gen.mjs": "// Renders every diagram module in ./diagrams to <name>-<theme>.html and\n// <theme>/<name>.svg. render.sh screenshots the HTML files at 2x.\n//\n// A diagram module default-exports one or more { name, width, height, draw }\n// objects; draw(t, lib) returns the SVG body for theme `t`.\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport * as lib from './lib.mjs'\n\nconst here = path.dirname(fileURLToPath(import.meta.url))\nconst out = process.cwd()\nconst only = process.argv[2] // optional: render a single diagram by name\n\nconst dir = path.join(here, 'diagrams')\nif (!fs.existsSync(dir)) {\n  console.error(\n    `No diagrams/ folder next to gen.mjs. Add diagrams/<name>.mjs (see SKILL.md).`\n  )\n  process.exit(1)\n}\nfor (const file of fs\n  .readdirSync(dir)\n  .filter((f) => f.endsWith('.mjs'))\n  .sort()) {\n  const mod = await import(pathToFileURL(path.join(dir, file)).href)\n  if (!mod.default) continue // a helper module shared between diagrams\n  const diagrams = [].concat(mod.default)\n  for (const d of diagrams) {\n    if (only && d.name !== only) continue\n    for (const [theme, t] of Object.entries(lib.themes)) {\n      const width = d.width ?? 1600\n      const svg = lib.canvas(\n        t,\n        width,\n        d.height,\n        d.draw(t, lib, { width, height: d.height })\n      )\n      fs.mkdirSync(path.join(out, theme), { recursive: true })\n      fs.writeFileSync(\n        path.join(out, `${d.name}-${theme}.html`),\n        lib.html(t, svg)\n      )\n      fs.writeFileSync(path.join(out, theme, `${d.name}.svg`), svg)\n    }\n    console.log(`generated ${d.name} (${d.width ?? 1600}×${d.height})`)\n  }\n}\n", "skills/docs-diagrams/scripts/lib.mjs": "// Primitives for Next.js docs diagrams.\n//\n// Every value here was measured from diagrams already published in the docs\n// (see style-tokens.md). Coordinates are CSS px on a canvas that is normally\n// 1600 wide; render.sh screenshots at 2x. Keep colors and sizes as tokens on\n// the theme object; drawing functions take a theme `t` and return SVG strings.\n\nexport const themes = {\n  light: {\n    bg: '#FBFBFB',\n    grid: '#F7F7F7',\n    // Panels (file trees, URL pills, code panels, browser windows)\n    panelTop: '#FFFFFF',\n    panelBottom: '#F9F9F9',\n    panelStroke: '#D9D9D9',\n    panelMuted: '#F1F1F1',\n    divider: '#E8E8E8',\n    shadow: 'rgba(0,0,0,0.08)',\n    titleBar: '#F7F7F7',\n    titleBarDivider: '#E3E3E3',\n    // Text\n    text: '#2E2E2E',\n    textMuted: '#8F8F8F',\n    textSubtle: '#616161',\n    icon: '#9A9A9A',\n    iconMuted: '#CECECE',\n    arrow: '#A8A8A8',\n    // Skeleton UI\n    skel: '#C9C9C9',\n    // Accents: stroke / light fill / text. Inside a tinted region, skeleton\n    // bars use `skelOn` and image placeholders `thumbOn`.\n    blue: {\n      stroke: '#0070F3',\n      fill: '#D5E6FA',\n      text: '#0067D6',\n      badgeFill: '#CDE7FF',\n      dot: '#197DF3',\n      skelOn: '#A8B9CD',\n      thumbOn: '#C1D2E5',\n    },\n    purple: {\n      stroke: '#8E4EC6',\n      fill: '#EAE0F2',\n      text: '#793AAF',\n      badgeFill: '#EDDBF9',\n      skelOn: '#BFB6C8',\n      thumbOn: '#D6CDDF',\n    },\n    red: {\n      stroke: '#E5484D',\n      fill: '#F7DFE0',\n      text: '#CA2A30',\n      badgeFill: '#F5DDDE',\n    },\n    green: {\n      stroke: '#46A758',\n      fill: '#DCEBDF',\n      text: '#46A758',\n      badgeFill: '#DCEBDF',\n    },\n    gray: {\n      stroke: '#8F8F8F',\n      fill: '#DEDEDE',\n      text: '#666666',\n      badgeFill: '#DEDEDE',\n    },\n    // A static / prerendered region in a bar or grid cell: lighter than `gray`\n    static: {\n      stroke: '#C9C9C9',\n      fill: '#F1F1F1',\n      text: '#666666',\n      badgeFill: '#F1F1F1',\n    },\n    // Code (GitHub Light, as used in the component hierarchy panels)\n    code: {\n      tag: '#005CC5',\n      attr: '#6F42C1',\n      keyword: '#D73A49',\n      ident: '#E36209',\n      punct: '#909295',\n      plain: '#2E2E2E',\n      react: '#61DAFB',\n    },\n    trafficLights: ['#FF6059', '#FFBD2E', '#28CA42'],\n  },\n  dark: {\n    bg: '#0D0D0D',\n    grid: '#161616',\n    panelTop: '#313131',\n    panelBottom: '#282828',\n    panelStroke: '#484848',\n    panelMuted: '#1F1F1F',\n    divider: '#434343',\n    shadow: 'rgba(0,0,0,0.5)',\n    titleBar: '#232323',\n    titleBarDivider: '#3A3A3A',\n    text: '#D4D4D4',\n    textMuted: '#A1A1A1',\n    textSubtle: '#8F8F8F',\n    icon: '#888888',\n    iconMuted: '#555555',\n    arrow: '#878787',\n    skel: '#4A4A4A',\n    blue: {\n      stroke: '#0A72EF',\n      fill: '#10233D',\n      text: '#52A8FF',\n      badgeFill: '#0D2A4D',\n      dot: '#0761C9',\n      skelOn: '#2F4A6E',\n      thumbOn: '#1E3657',\n    },\n    purple: {\n      stroke: '#9A5CD0',\n      fill: '#2A1F38',\n      text: '#C4A1E6',\n      badgeFill: '#2F2240',\n      skelOn: '#4A3D5C',\n      thumbOn: '#3A2E49',\n    },\n    red: {\n      stroke: '#E5484D',\n      fill: '#3A1D1F',\n      text: '#F08A8E',\n      badgeFill: '#3A1D1F',\n    },\n    green: {\n      stroke: '#46A758',\n      fill: '#1B2E1F',\n      text: '#6FCB80',\n      badgeFill: '#1B2E1F',\n    },\n    gray: {\n      stroke: '#6F6F6F',\n      fill: '#2A2A2A',\n      text: '#B0B0B0',\n      badgeFill: '#2A2A2A',\n    },\n    static: {\n      stroke: '#4A4A4A',\n      fill: '#1F1F1F',\n      text: '#B0B0B0',\n      badgeFill: '#1F1F1F',\n    },\n    code: {\n      tag: '#79B8FF',\n      attr: '#B392F0',\n      keyword: '#F97583',\n      ident: '#FFAB70',\n      punct: '#8B949E',\n      plain: '#D4D4D4',\n      react: '#61DAFB',\n    },\n    trafficLights: ['#FF6059', '#FFBD2E', '#28CA42'],\n  },\n}\n\nexport const sans = `font-family=\"Inter, system-ui, sans-serif\"`\nexport const mono = `font-family=\"'Geist Mono', ui-monospace, monospace\"`\n\n// Snap a 1px stroke to the half pixel so it renders crisp at 1x and 2x.\nconst half = (v) => Math.round(v) + 0.5\n\nlet idCounter = 0\nconst uid = (prefix) => `${prefix}${++idCounter}`\n\n// ---------------------------------------------------------------------------\n// Canvas\n\nexport function canvas(t, W, H, body) {\n  return [\n    `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${W}\" height=\"${H}\" viewBox=\"0 0 ${W} ${H}\">`,\n    `<defs>`,\n    `<pattern id=\"grid\" width=\"40\" height=\"40\" patternUnits=\"userSpaceOnUse\"><path d=\"M40 0H0V40\" fill=\"none\" stroke=\"${t.grid}\" stroke-width=\"1\"/></pattern>`,\n    `<filter id=\"shadow\" x=\"-20%\" y=\"-20%\" width=\"140%\" height=\"160%\"><feGaussianBlur stdDeviation=\"8\"/></filter>`,\n    `<linearGradient id=\"panel\" x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\"><stop offset=\"0\" stop-color=\"${t.panelTop}\"/><stop offset=\"1\" stop-color=\"${t.panelBottom}\"/></linearGradient>`,\n    `</defs>`,\n    `<rect width=\"${W}\" height=\"${H}\" fill=\"${t.bg}\"/><rect width=\"${W}\" height=\"${H}\" fill=\"url(#grid)\"/>`,\n    body,\n    `</svg>`,\n  ].join('\\n')\n}\n\n// Wrap diagram HTML so headless Chrome waits for Inter before screenshotting.\nexport function html(t, svg) {\n  return `<!doctype html><html><head><link href=\"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=block\" rel=\"stylesheet\"><style>html,body{margin:0;background:${t.bg}}svg{display:block}</style></head><body>${svg}</body></html>`\n}\n\n// ---------------------------------------------------------------------------\n// Text\n\nexport function label(\n  t,\n  x,\n  y,\n  str,\n  {\n    size = 20,\n    weight = 400,\n    color = t.text,\n    anchor = 'start',\n    font = sans,\n  } = {}\n) {\n  return `<text x=\"${x}\" y=\"${y}\" text-anchor=\"${anchor}\" dominant-baseline=\"central\" font-size=\"${size}\" font-weight=\"${weight}\" fill=\"${color}\" ${font}>${esc(str)}</text>`\n}\n\nexport function code(t, x, y, str, opts = {}) {\n  return label(t, x, y, str, { font: mono, ...opts })\n}\n\n// Approximate rendered width of a string. There are no font metrics at\n// generation time, so this is the heuristic the primitives use; use it in\n// modules too when a block's width depends on a label.\nexport function textWidth(str, size, { mono: isMono = false } = {}) {\n  return String(str).length * size * (isMono ? 0.58 : 0.52)\n}\n\nexport const esc = (s) =>\n  String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\n\n// ---------------------------------------------------------------------------\n// Panels\n\n// A white-to-off-white card with a 1px border and a soft shadow. Base for the\n// file tree, URL pill, code panel and browser window.\nexport function panel(\n  t,\n  x,\n  y,\n  w,\n  h,\n  {\n    radius = 10,\n    shadow = true,\n    fill = 'url(#panel)',\n    stroke = t.panelStroke,\n  } = {}\n) {\n  const s = []\n  if (shadow)\n    s.push(\n      `<rect x=\"${x}\" y=\"${y + 6}\" width=\"${w}\" height=\"${h}\" rx=\"${radius}\" fill=\"${t.shadow}\" filter=\"url(#shadow)\"/>`\n    )\n  s.push(\n    `<rect x=\"${half(x)}\" y=\"${half(y)}\" width=\"${w - 1}\" height=\"${h - 1}\" rx=\"${radius}\" fill=\"${fill}\" stroke=\"${stroke}\"/>`\n  )\n  return s.join('\\n')\n}\n\n// ---------------------------------------------------------------------------\n// Icons (18px glyphs, drawn at x,y = top-left, stroke 1.5)\n\nexport const icons = {\n  folder: (x, y, c) =>\n    `<path d=\"M${x + 1.5} ${y + 5} a1.5 1.5 0 0 1 1.5 -1.5 h4.2 l2 2 h6.3 a1.5 1.5 0 0 1 1.5 1.5 v7.5 a1.5 1.5 0 0 1 -1.5 1.5 h-12.5 a1.5 1.5 0 0 1 -1.5 -1.5 z\" fill=\"none\" stroke=\"${c}\" stroke-width=\"1.5\" stroke-linejoin=\"round\"/>`,\n  file: (x, y, c) =>\n    `<path d=\"M${x + 4} ${y + 1.5} h6 l4 4 v9.5 a1.5 1.5 0 0 1 -1.5 1.5 h-8.5 a1.5 1.5 0 0 1 -1.5 -1.5 v-12 a1.5 1.5 0 0 1 1.5 -1.5 z M${x + 10} ${y + 1.5} v4 h4\" fill=\"none\" stroke=\"${c}\" stroke-width=\"1.5\" stroke-linejoin=\"round\"/>`,\n  layout: (x, y, c) =>\n    `<rect x=\"${x + 2}\" y=\"${y + 2.5}\" width=\"14\" height=\"13\" rx=\"1.5\" fill=\"none\" stroke=\"${c}\" stroke-width=\"1.5\"/><path d=\"M${x + 2} ${y + 7} H${x + 16} M${x + 7} ${y + 7} V${y + 15.5}\" stroke=\"${c}\" stroke-width=\"1.5\"/>`,\n  globe: (x, y, c) =>\n    `<circle cx=\"${x + 9}\" cy=\"${y + 9}\" r=\"7\" fill=\"none\" stroke=\"${c}\" stroke-width=\"1.5\"/><path d=\"M${x + 2} ${y + 9} H${x + 16} M${x + 9} ${y + 2} c-3 2.5 -3 11.5 0 14 M${x + 9} ${y + 2} c3 2.5 3 11.5 0 14\" fill=\"none\" stroke=\"${c}\" stroke-width=\"1.5\"/>`,\n  lock: (x, y, c) =>\n    `<rect x=\"${x + 4}\" y=\"${y + 8}\" width=\"10\" height=\"8\" rx=\"1.5\" fill=\"${c}\"/><path d=\"M${x + 6} ${y + 8} V${y + 6} a3 3 0 0 1 6 0 V${y + 8}\" fill=\"none\" stroke=\"${c}\" stroke-width=\"1.5\"/>`,\n  route: (x, y, c) =>\n    `<path d=\"M${x + 11} ${y + 3} c-3 0 -3 3 -3 5 v6 M${x + 5} ${y + 9} h6\" fill=\"none\" stroke=\"${c}\" stroke-width=\"1.5\" stroke-linecap=\"round\"/>`,\n  react: (x, y, c) => {\n    const cx = x + 9,\n      cy = y + 9\n    return (\n      [0, 60, 120]\n        .map(\n          (a) =>\n            `<ellipse cx=\"${cx}\" cy=\"${cy}\" rx=\"8\" ry=\"3\" fill=\"none\" stroke=\"${c}\" stroke-width=\"1.2\" transform=\"rotate(${a} ${cx} ${cy})\"/>`\n        )\n        .join('') + `<circle cx=\"${cx}\" cy=\"${cy}\" r=\"1.6\" fill=\"${c}\"/>`\n    )\n  },\n}\n\n// ---------------------------------------------------------------------------\n// File tree panel: the \"app / page.js → URL\" family.\n//\n// rows: [{ label, icon, depth = 0, bold, dot, muted }]\n// Returns { svg, rowY(i) } so arrows can be aligned to rows.\n\nexport const TREE_ROW = 80\n\nexport function treePanel(t, x, y, w, rows, { indent = 40, pad = 32 } = {}) {\n  const h = rows.length * TREE_ROW\n  const s = [panel(t, x, y, w, h)]\n  rows.forEach((r, i) => {\n    const ry = y + i * TREE_ROW\n    if (r.muted) {\n      const rx = half(x),\n        ryy = half(ry)\n      const isLast = i === rows.length - 1\n      s.push(\n        `<path d=\"M${rx} ${ryy} H${rx + w - 1} V${ryy + TREE_ROW - 1 - (isLast ? 10 : 0)} ${isLast ? `a10 10 0 0 1 -10 10 H${rx + 10} a10 10 0 0 1 -10 -10` : `H${rx}`} Z\" fill=\"${t.panelMuted}\"/>`\n      )\n    }\n    if (i > 0)\n      s.push(\n        `<line x1=\"${x + 1}\" x2=\"${x + w - 1}\" y1=\"${half(ry)}\" y2=\"${half(ry)}\" stroke=\"${t.divider}\"/>`\n      )\n    const ix = x + pad + (r.depth || 0) * indent\n    const color = r.muted ? t.iconMuted : t.icon\n    if (r.icon) s.push(icons[r.icon](ix, ry + TREE_ROW / 2 - 9, color))\n    s.push(\n      label(t, ix + 32, ry + TREE_ROW / 2, r.label, {\n        weight: r.bold ? 600 : 400,\n        color: r.muted ? t.textMuted : t.text,\n      })\n    )\n    if (r.dot) s.push(dot(t, x + w - pad - 10, ry + TREE_ROW / 2))\n  })\n  return { svg: s.join('\\n'), h, rowY: (i) => y + i * TREE_ROW + TREE_ROW / 2 }\n}\n\n// The blue \"this is the file we are talking about\" marker, with a soft glow.\nexport function dot(t, cx, cy, color = t.blue) {\n  return `<circle cx=\"${cx}\" cy=\"${cy}\" r=\"16\" fill=\"${color.fill}\" opacity=\"0.8\"/><circle cx=\"${cx}\" cy=\"${cy}\" r=\"10\" fill=\"${color.dot}\"/>`\n}\n\n// URL pill: globe + path. `muted` renders the \"not routable\" variant.\nexport function urlPill(\n  t,\n  x,\n  y,\n  w,\n  path,\n  { muted = false, h = TREE_ROW } = {}\n) {\n  const s = [\n    panel(t, x, y, w, h, { fill: muted ? t.panelMuted : 'url(#panel)' }),\n  ]\n  s.push(icons.globe(x + 32, y + h / 2 - 9, muted ? t.iconMuted : t.icon))\n  s.push(\n    label(t, x + 64, y + h / 2, path, { color: muted ? t.textMuted : t.text })\n  )\n  return s.join('\\n')\n}\n\n// Stack several URL pills into one panel (dividers between them).\nexport function urlStack(t, x, y, w, paths) {\n  const h = paths.length * TREE_ROW\n  const s = [panel(t, x, y, w, h)]\n  paths.forEach((p, i) => {\n    const ry = y + i * TREE_ROW\n    if (p.muted)\n      s.push(\n        `<rect x=\"${x + 1}\" y=\"${ry + 1}\" width=\"${w - 2}\" height=\"${TREE_ROW - 2}\" rx=\"${i === 0 || i === paths.length - 1 ? 10 : 0}\" fill=\"${t.panelMuted}\"/>`\n      )\n    if (i > 0)\n      s.push(\n        `<line x1=\"${x + 1}\" x2=\"${x + w - 1}\" y1=\"${half(ry)}\" y2=\"${half(ry)}\" stroke=\"${t.divider}\"/>`\n      )\n    s.push(\n      icons.globe(x + 32, ry + TREE_ROW / 2 - 9, p.muted ? t.iconMuted : t.icon)\n    )\n    s.push(\n      label(t, x + 64, ry + TREE_ROW / 2, p.path, {\n        color: p.muted ? t.textMuted : t.text,\n      })\n    )\n  })\n  return s.join('\\n')\n}\n\n// ---------------------------------------------------------------------------\n// Arrows\n\n// Straight horizontal arrow with an open chevron head.\nexport function arrow(\n  t,\n  x1,\n  x2,\n  y,\n  { color = t.arrow, width = 2, k = 1 } = {}\n) {\n  const dir = x2 > x1 ? 1 : -1\n  const hx = x2 - dir * 10 * k\n  return (\n    `<line x1=\"${x1}\" x2=\"${x2 - dir}\" y1=\"${y}\" y2=\"${y}\" stroke=\"${color}\" stroke-width=\"${width * k}\" stroke-linecap=\"round\"/>` +\n    `<path d=\"M${hx} ${y - 7 * k} L${x2} ${y} L${hx} ${y + 7 * k}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"${width * k}\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>`\n  )\n}\n\n// Bracket arrow used beside file trees: leaves row `fromY` to the left, drops\n// to row `toY`, and points back in. `x` is the panel's left edge.\nexport function bracketArrow(\n  t,\n  x,\n  fromY,\n  toY,\n  { reach = 60, color = t.arrow } = {}\n) {\n  const bx = x - reach\n  return (\n    `<path d=\"M${x} ${fromY} H${bx + 10} a10 10 0 0 0 -10 10 V${toY - 10} a10 10 0 0 0 10 10 H${x - 2}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"2\" stroke-linecap=\"round\"/>` +\n    `<path d=\"M${x - 10} ${toY - 7} L${x} ${toY} L${x - 10} ${toY + 7}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>`\n  )\n}\n\n// Caption bracket under a group of things, with centered text beneath it.\nexport function bracketCaption(t, x1, x2, y, text) {\n  return (\n    `<path d=\"M${x1} ${y - 12} v4 a8 8 0 0 0 8 8 H${x2 - 8} a8 8 0 0 0 8 -8 v-4\" fill=\"none\" stroke=\"${t.arrow}\" stroke-width=\"2\" stroke-linecap=\"round\"/>` +\n    label(t, (x1 + x2) / 2, y + 40, text, {\n      size: 20,\n      color: t.textMuted,\n      anchor: 'middle',\n    })\n  )\n}\n\n// ---------------------------------------------------------------------------\n// Browser window. Proportions are the docs' 527×476 window at 1600 wide; pass\n// a smaller `w` and everything scales with it.\n\nexport function browserWindow(t, x, y, w, h, url, body = '') {\n  const k = w / 527 // scale factor relative to the reference window\n  const bar = Math.round(70 * k)\n  const r = Math.round(12 * k)\n  const s = [panel(t, x, y, w, h, { radius: r })]\n  s.push(\n    `<path d=\"M${half(x)} ${half(y) + bar} V${half(y) + r} a${r} ${r} 0 0 1 ${r} -${r} H${half(x) + w - 1 - r} a${r} ${r} 0 0 1 ${r} ${r} V${half(y) + bar} Z\" fill=\"${t.titleBar}\"/>`\n  )\n  s.push(\n    `<line x1=\"${x + 1}\" x2=\"${x + w - 1}\" y1=\"${half(y + bar)}\" y2=\"${half(y + bar)}\" stroke=\"${t.titleBarDivider}\"/>`\n  )\n  t.trafficLights.forEach((c, i) =>\n    s.push(\n      `<circle cx=\"${x + 37 * k + i * 28 * k}\" cy=\"${y + bar / 2}\" r=\"${9 * k}\" fill=\"${c}\"/>`\n    )\n  )\n  const pw = 320 * k,\n    ph = 44 * k,\n    px = x + 155 * k,\n    py = y + (bar - ph) / 2\n  s.push(\n    `<rect x=\"${half(px)}\" y=\"${half(py)}\" width=\"${pw - 1}\" height=\"${ph - 1}\" rx=\"${8 * k}\" fill=\"${t.panelTop}\" stroke=\"${t.panelStroke}\"/>`\n  )\n  s.push(\n    `<g transform=\"translate(${px + 12 * k} ${py + ph / 2 - 9 * k}) scale(${k})\">${icons.lock(0, 0, t.icon)}</g>`\n  )\n  s.push(\n    label(t, px + 36 * k, py + ph / 2, url, {\n      size: 20 * k,\n      color: t.textSubtle,\n    })\n  )\n  s.push(body)\n  return { svg: s.join('\\n'), x, y, w, h, contentY: y + bar, k }\n}\n\n// Skeleton pieces\nexport const skel = {\n  bar: (t, x, y, w, h = 24, color = t.skel) =>\n    `<rect x=\"${x}\" y=\"${y}\" width=\"${w}\" height=\"${h}\" rx=\"${Math.min(6, h / 2)}\" fill=\"${color}\"/>`,\n  avatar: (t, cx, cy, r = 28, color = t.skel) =>\n    `<circle cx=\"${cx}\" cy=\"${cy}\" r=\"${r}\" fill=\"${color}\"/>`,\n  square: (t, x, y, size = 24, color = t.skel) =>\n    `<rect x=\"${x}\" y=\"${y}\" width=\"${size}\" height=\"${size}\" rx=\"${size / 5}\" fill=\"${color}\"/>`,\n  // Image placeholder: tile with a mountain and a sun.\n  thumb: (t, x, y, w, h, color = t.skel, detail = t.textMuted) => {\n    const s = Math.min(w, h)\n    return (\n      `<rect x=\"${x}\" y=\"${y}\" width=\"${w}\" height=\"${h}\" rx=\"${s / 8}\" fill=\"${color}\"/>` +\n      `<circle cx=\"${x + w * 0.32}\" cy=\"${y + h * 0.32}\" r=\"${s * 0.09}\" fill=\"${detail}\" opacity=\"0.6\"/>` +\n      `<path d=\"M${x + w * 0.12} ${y + h * 0.82} L${x + w * 0.42} ${y + h * 0.5} L${x + w * 0.6} ${y + h * 0.66} L${x + w * 0.72} ${y + h * 0.56} L${x + w * 0.9} ${y + h * 0.82} Z\" fill=\"${detail}\" opacity=\"0.6\"/>`\n    )\n  },\n}\n\n// The page inside a browser window, laid out the way the docs draw it: a\n// header row (avatar + title bar), a sidebar of short bars, and a content\n// column that shares its top and bottom edges with the sidebar. Everything is\n// scaled by the window's `k`. Returns the content rect; fill it per moment\n// with `postCard`, `commentRows`, `hole` and `card`.\nexport function pageLayout(t, win, { sidebar = true } = {}) {\n  const { x, y, w, h, contentY, k } = win\n  const pad = 28 * k\n  const s = []\n  // header: avatar and a title bar, vertically centered on each other\n  const r = 14 * k\n  const hy = contentY + pad + r\n  s.push(skel.avatar(t, x + pad + r, hy, r))\n  s.push(\n    skel.bar(\n      t,\n      x + pad + r * 2 + 16 * k,\n      hy - 8 * k,\n      w - pad * 2 - r * 2 - 16 * k,\n      16 * k\n    )\n  )\n  // sidebar and content column\n  const top = hy + r + 24 * k\n  const bottom = y + h - pad\n  const sbW = sidebar ? 110 * k : 0\n  if (sidebar) {\n    // a stack of short bars from the top, like a nav list\n    const widths = [1, 0.75, 0.9, 0.6]\n    const bh = 14 * k\n    widths.forEach((f, i) =>\n      s.push(skel.bar(t, x + pad, top + i * 40 * k, sbW * f, bh))\n    )\n  }\n  const cx = x + pad + sbW + (sidebar ? 24 * k : 0)\n  const content = { x: cx, y: top, w: x + w - pad - cx, h: bottom - top }\n  // the usual split of the content column: post on top, comments below\n  const gap = 12 * k\n  const postH = Math.round((content.h - gap) * 0.56)\n  const regions = {\n    post: { x: cx, y: top, w: content.w, h: postH },\n    comments: {\n      x: cx,\n      y: top + postH + gap,\n      w: content.w,\n      h: content.h - postH - gap,\n    },\n  }\n  return { svg: s.join('\\n'), content, regions, k }\n}\n\n// A post card: outlined card with a title bar and body lines. `color` 'skel'\n// draws it as plain rendered UI; an accent name draws it as an accent card\n// with the skeleton tinted to match.\nexport function postCard(t, x, y, w, h, k = 1, color = 'skel') {\n  const accent = color !== 'skel' ? t[color] : null\n  const c = accent ? accent.skelOn : t.skel\n  const pad = 16 * k\n  const frame = accent\n    ? card(t, x, y, w, h, { color, radius: 8 * k, strokeWidth: 1.5 * k })\n    : `<rect x=\"${x}\" y=\"${y}\" width=\"${w}\" height=\"${h}\" rx=\"${8 * k}\" fill=\"none\" stroke=\"${t.panelStroke}\" stroke-width=\"${1.5 * k}\"/>`\n  // title bar plus at most three body lines; the card's height is the caller's\n  const lines = Math.max(\n    1,\n    Math.min(3, Math.floor((h - pad * 2 - 14 * k) / (18 * k)))\n  )\n  let body = skel.bar(\n    t,\n    x + pad,\n    y + pad,\n    Math.min(120 * k, w * 0.45),\n    14 * k,\n    c\n  )\n  for (let i = 0; i < lines; i++) {\n    const ly = y + pad + 14 * k + 10 * k + i * 18 * k\n    if (ly + 8 * k > y + h - pad) break\n    body += skel.bar(\n      t,\n      x + pad,\n      ly,\n      (w - pad * 2) * (i === lines - 1 ? 0.6 : 1),\n      8 * k,\n      c\n    )\n  }\n  return frame + body\n}\n\n// Comment rows: small avatar + one line each, spread evenly over the height.\nexport function commentRows(\n  t,\n  x,\n  y,\n  w,\n  h,\n  k = 1,\n  color = 'skel',\n  rows = 3,\n  { frame = color !== 'skel' } = {}\n) {\n  const c = color !== 'skel' ? t[color].skelOn : t.skel\n  let out = ''\n  if (frame) {\n    out += card(t, x, y, w, h, { color, radius: 8 * k, strokeWidth: 1.5 * k })\n    const pad = 12 * k\n    x += pad\n    y += pad\n    w -= pad * 2\n    h -= pad * 2\n  }\n  const r = 7 * k\n  const step = rows > 1 ? Math.min(34 * k, (h - r * 2) / (rows - 1)) : 0\n  const widths = [0.7, 0.45, 0.6]\n  for (let i = 0; i < rows; i++) {\n    const cy = y + r + i * step\n    out += skel.avatar(t, x + r, cy, r, c)\n    out += skel.bar(\n      t,\n      x + r * 2 + 10 * k,\n      cy - 4 * k,\n      (w - r * 2 - 10 * k) * widths[i % widths.length],\n      8 * k,\n      c\n    )\n  }\n  return out\n}\n\n// A region that has not rendered yet. Blue dashed by default; `style: 'gray'`\n// gives the Suspense-fallback look. Optional centered label.\nexport function hole(\n  t,\n  x,\n  y,\n  w,\n  h,\n  {\n    style = 'blue',\n    label: text,\n    radius = 10,\n    strokeWidth = 2,\n    dash = '8 5',\n    labelSize = Math.min(18, h / 3),\n  } = {}\n) {\n  const c = style === 'gray' ? null : t[style]\n  const rect = c\n    ? `<rect x=\"${x}\" y=\"${y}\" width=\"${w}\" height=\"${h}\" rx=\"${radius}\" fill=\"${c.fill}\" stroke=\"${c.stroke}\" stroke-width=\"${strokeWidth}\" stroke-dasharray=\"${dash}\"/>`\n    : `<rect x=\"${x}\" y=\"${y}\" width=\"${w}\" height=\"${h}\" rx=\"${radius}\" fill=\"none\" stroke=\"${t.panelStroke}\" stroke-width=\"${strokeWidth}\" stroke-dasharray=\"${dash}\"/>`\n  return (\n    rect +\n    (text\n      ? label(t, x + w / 2, y + h / 2, text, {\n          size: labelSize,\n          weight: 500,\n          color: c ? c.text : t.textMuted,\n          anchor: 'middle',\n        })\n      : '')\n  )\n}\n\n// A solid accent card (content that has rendered, a highlighted row, a route box).\nexport function card(\n  t,\n  x,\n  y,\n  w,\n  h,\n  {\n    color = 'blue',\n    radius = 10,\n    dashed = false,\n    strokeWidth = 2,\n    dash = '8 5',\n    label: text,\n    labelSize = Math.min(18, h / 3),\n  } = {}\n) {\n  const c = t[color]\n  return (\n    `<rect x=\"${x}\" y=\"${y}\" width=\"${w}\" height=\"${h}\" rx=\"${radius}\" fill=\"${c.fill}\" stroke=\"${c.stroke}\" stroke-width=\"${strokeWidth}\"${dashed ? ` stroke-dasharray=\"${dash}\"` : ''}/>` +\n    (text\n      ? label(t, x + w / 2, y + h / 2, text, {\n          size: labelSize,\n          weight: 500,\n          color: c.text,\n          anchor: 'middle',\n        })\n      : '')\n  )\n}\n\n// ---------------------------------------------------------------------------\n// Badges and legends\n\n// Letter badge (A, B, S, D) anchored at its top-left corner.\nexport function badge(t, x, y, letter, color = 'blue', size = 32) {\n  const c = t[color]\n  return (\n    `<rect x=\"${x}\" y=\"${y}\" width=\"${size}\" height=\"${size}\" rx=\"${size / 4}\" fill=\"${c.badgeFill}\" stroke=\"${c.stroke}\" stroke-width=\"2\"/>` +\n    label(t, x + size / 2, y + size / 2, letter, {\n      size: size * 0.6,\n      weight: 500,\n      color: c.text,\n      anchor: 'middle',\n    })\n  )\n}\n\n// Mono status pill: \"Routable\", \"HARD NAV\", \"Zone A\".\nexport function statusBadge(\n  t,\n  x,\n  y,\n  text,\n  color = 'gray',\n  { size = 18, padX = 14, h = 34 } = {}\n) {\n  const c = t[color]\n  const w = Math.round(textWidth(text, size, { mono: true }) + padX * 2)\n  return (\n    `<rect x=\"${x}\" y=\"${y}\" width=\"${w}\" height=\"${h}\" rx=\"6\" fill=\"${c.badgeFill}\" stroke=\"${c.stroke}\" stroke-width=\"1.5\"/>` +\n    code(t, x + w / 2, y + h / 2, text, {\n      size,\n      color: c.text,\n      anchor: 'middle',\n    })\n  )\n}\n\n// Legend row: badge + description.\nexport function legendRow(t, x, y, letter, color, text) {\n  return (\n    badge(t, x, y, letter, color, 36) +\n    label(t, x + 52, y + 18, text, { size: 20, color: t.textMuted })\n  )\n}\n\n// Callout: label with a leader line ending at (tx, ty).\nexport function callout(\n  t,\n  x,\n  y,\n  text,\n  tx,\n  ty,\n  { color = t.arrow, anchor = 'end' } = {}\n) {\n  const lx = anchor === 'end' ? x + 16 : x - 16\n  return (\n    label(t, x, y, text, {\n      size: 22,\n      weight: 600,\n      color: t.textSubtle,\n      anchor,\n    }) +\n    `<line x1=\"${lx}\" y1=\"${y}\" x2=\"${tx}\" y2=\"${ty}\" stroke=\"${color}\" stroke-width=\"2\" stroke-linecap=\"round\"/>`\n  )\n}\n\n// ---------------------------------------------------------------------------\n// Code panel with a title bar (React icon + file name) and highlighted lines.\n// lines: array of arrays of [text, tokenName]; tokenName indexes t.code.\n\nexport function codePanel(\n  t,\n  x,\n  y,\n  w,\n  title,\n  lines,\n  { lineHeight = 36, size = 20, pad = 28 } = {}\n) {\n  const bar = 54\n  const h = bar + pad * 2 + lines.length * lineHeight - (lineHeight - size)\n  const s = [panel(t, x, y, w, h)]\n  s.push(\n    `<path d=\"M${half(x)} ${half(y) + bar} V${half(y) + 10} a10 10 0 0 1 10 -10 H${half(x) + w - 11} a10 10 0 0 1 10 10 V${half(y) + bar} Z\" fill=\"${t.titleBar}\"/>`\n  )\n  s.push(\n    `<line x1=\"${x + 1}\" x2=\"${x + w - 1}\" y1=\"${half(y + bar)}\" y2=\"${half(y + bar)}\" stroke=\"${t.titleBarDivider}\"/>`\n  )\n  s.push(icons.react(x + 24, y + bar / 2 - 9, t.code.react))\n  s.push(\n    label(t, x + 54, y + bar / 2, title, { size: 18, color: t.textSubtle })\n  )\n  lines.forEach((tokens, i) => {\n    const ly = y + bar + pad + i * lineHeight + size / 2\n    let cx = x + pad\n    tokens.forEach(([text, kind = 'plain']) => {\n      s.push(code(t, cx, ly, text, { size, color: t.code[kind] }))\n      cx += textWidth(text, size, { mono: true })\n    })\n  })\n  return { svg: s.join('\\n'), h }\n}\n\n// Legend row whose key is a fill style rather than a letter: a small card or\n// hole drawn the way the thing it explains is drawn.\n// kind: { color, dashed } for a card, or { hole: 'blue' | 'gray' } for a hole.\n// `k` scales every size for canvases narrower than 1600 (k = width / 1600).\n// Its width is 60k + textWidth(text, 20k) when several sit in one row.\nexport function swatchLegend(t, x, y, kind, text, { k = 1 } = {}) {\n  const sw = kind.hole\n    ? hole(t, x, y, 44 * k, 24 * k, {\n        style: kind.hole,\n        radius: 6 * k,\n        strokeWidth: 2 * k,\n        dash: `${8 * k} ${5 * k}`,\n      })\n    : card(t, x, y, 44 * k, 24 * k, {\n        color: kind.color ?? 'blue',\n        dashed: !!kind.dashed,\n        radius: 6 * k,\n        strokeWidth: 2 * k,\n        dash: `${8 * k} ${5 * k}`,\n      })\n  return (\n    sw +\n    label(t, x + 60 * k, y + 12 * k, text, { size: 20 * k, color: t.textMuted })\n  )\n}\n\n// ---------------------------------------------------------------------------\n// Grid: column headers across the top (stages, moments, variants), a label\n// column on the left (one per row), faint dashed dividers between columns.\n// Draw the cells yourself with `card` / `hole` from the returned geometry:\n//   const g = grid(t, x, y, { columns, rows }); g.span(row, fromCol, toCol) -> { x, y, w, h }\n// To line the columns up with a row of windows above: colW = windowW + gap,\n// inset = gap / 2, x = first window's x - labelW - gap - gap / 2, and\n// y = window bottom + 16 * k. The column headers then sit under the windows\n// and double as their captions. The dividers extend `inset` beyond the first\n// and last window on each side; include that when centering the block.\n//\n// columns: [{ title, subtitle, subtitleMono }]   rows: [{ label, mono = true, muted }]\n\nexport function grid(\n  t,\n  x,\n  y,\n  {\n    columns,\n    rows,\n    k = 1, // scales every default below and the text (k = width / 1600)\n    labelW = 200 * k,\n    labelHeader,\n    labelHeaderMono = true,\n    colW = 260 * k,\n    rowH = 56 * k,\n    rowGap = 20 * k,\n    headerH = (columns.some((c) => c.subtitle) ? 70 : 48) * k,\n    gap = 40 * k, // between the label column and the first column\n    inset = 10 * k, // cell inset from the column dividers\n  }\n) {\n  const s = []\n  const colX = (i) => x + labelW + gap + i * colW\n  const rowY = (r) => y + headerH + r * (rowH + rowGap)\n  const h = headerH + rows.length * rowH + (rows.length - 1) * rowGap\n  const w = labelW + gap + columns.length * colW\n  // Header text is centered 12px below `y` so its cap height starts at `y`;\n  // the dividers end at the last row, so [y, y + h] is the visual box.\n  if (labelHeader)\n    s.push(\n      (labelHeaderMono ? code : label)(t, x + labelW, y + 12 * k, labelHeader, {\n        size: 18 * k,\n        color: t.textMuted,\n        anchor: 'end',\n      })\n    )\n  columns.forEach((c, i) => {\n    const cx = colX(i) + colW / 2\n    s.push(\n      label(t, cx, y + 12 * k, c.title, {\n        size: 20 * k,\n        weight: 600,\n        color: t.textSubtle,\n        anchor: 'middle',\n      })\n    )\n    if (c.subtitle)\n      s.push(\n        (c.subtitleMono ? code : label)(t, cx, y + 42 * k, c.subtitle, {\n          size: 15 * k,\n          color: t.textMuted,\n          anchor: 'middle',\n        })\n      )\n  })\n  for (let i = 0; i <= columns.length; i++) {\n    const dx = half(colX(i))\n    s.push(\n      `<line x1=\"${dx}\" x2=\"${dx}\" y1=\"${y + headerH - 10 * k}\" y2=\"${y + h}\" stroke=\"${t.divider}\" stroke-dasharray=\"${4 * k} ${4 * k}\"/>`\n    )\n  }\n  rows.forEach((r, i) => {\n    const cy = rowY(i) + rowH / 2\n    s.push(\n      (r.mono === false ? label : code)(t, x + labelW, cy, r.label, {\n        size: 20 * k,\n        color: r.muted ? t.textMuted : t.text,\n        anchor: 'end',\n      })\n    )\n  })\n  return {\n    svg: s.join('\\n'),\n    w,\n    h,\n    colX,\n    rowY,\n    span: (r, from, to = from) => ({\n      x: colX(from) + inset,\n      y: rowY(r),\n      w: (to - from + 1) * colW - inset * 2,\n      h: rowH,\n    }),\n  }\n}\n", "skills/docs-diagrams/scripts/measure.py": "#!/usr/bin/env python3\n\"\"\"Ink margins of a rendered diagram, in CSS px (the PNGs are 2x).\n\nUsage: python3 measure.py light/<name>.png [dark/<name>.png ...]\n\nCounts a pixel as ink when it differs from the background by more than a\nthreshold, which skips the grid; panel shadows still count at the bottom,\nso expect the bottom margin to read a few px smaller than the top.\n\"\"\"\nimport sys\nfrom PIL import Image\n\nTHRESHOLD = 40\n\nfor path in sys.argv[1:]:\n    im = Image.open(path).convert('RGB')\n    w, h = im.size\n    bg = im.getpixel((0, 0))\n    px = im.load()\n    def ink(x, y):\n        p = px[x, y]\n        return abs(p[0] - bg[0]) + abs(p[1] - bg[1]) + abs(p[2] - bg[2]) > THRESHOLD\n    cols = [x for x in range(w) if any(ink(x, y) for y in range(0, h, 2))]\n    rows = [y for y in range(h) if any(ink(x, y) for x in range(0, w, 2))]\n    if not cols or not rows:\n        print(f'{path}: no ink found'); continue\n    left, right = cols[0] / 2, (w - 1 - cols[-1]) / 2\n    top, bottom = rows[0] / 2, (h - 1 - rows[-1]) / 2\n    print(f'{path}: left {left:g} right {right:g} top {top:g} bottom {bottom:g}  (canvas {w // 2}x{h // 2})')\n", "skills/docs-diagrams/scripts/render.sh": "#!/usr/bin/env bash\n# Render every diagram module in ./diagrams to light/<name>.png and dark/<name>.png at 2x.\n#\n# Usage: copy lib.mjs, gen.mjs, diagrams/ and this script into a scratch folder,\n# add or edit a module in diagrams/, then run ./render.sh from that folder.\n# Set CHROME=/path/to/chrome when Chrome is not installed at the default macOS path.\nset -euo pipefail\n\nCHROME=\"${CHROME:-/Applications/Google Chrome.app/Contents/MacOS/Google Chrome}\"\ncd \"$(dirname \"$0\")\"\n\nrm -f ./*.html light/*.png dark/*.png light/*.svg dark/*.svg\nnode gen.mjs\n\nfor svg in light/*.svg; do\n  name=\"$(basename \"$svg\" .svg)\"\n  height=\"$(node -e \"const s=require('fs').readFileSync('$svg','utf8');console.log(/height=\\\"(\\d+)\\\"/.exec(s)[1])\")\"\n  width=\"$(node -e \"const s=require('fs').readFileSync('$svg','utf8');console.log(/width=\\\"(\\d+)\\\"/.exec(s)[1])\")\"\n  for theme in light dark; do\n    \"$CHROME\" --headless=new --disable-gpu --hide-scrollbars \\\n      --force-device-scale-factor=2 \\\n      --window-size=\"$width,$height\" \\\n      --virtual-time-budget=4000 \\\n      --screenshot=\"$PWD/$theme/$name.png\" \\\n      \"file://$PWD/$name-$theme.html\" 2>/dev/null\n    echo \"rendered $theme/$name.png ($((width * 2))x$((height * 2)))\"\n  done\ndone\n", "skills/flags/SKILL.md": "---\nname: flags\ndescription: >\n  How to add or modify Next.js experimental feature flags end-to-end.\n  Use when editing config-shared.ts, config-schema.ts, define-env-plugin.ts,\n  next-server.ts, export/worker.ts, or module.compiled.js. Covers type\n  declaration, zod schema, build-time injection, runtime env plumbing,\n  and the decision between runtime env-var branching vs separate bundle variants.\nmetadata:\n  internal: true\n---\n\n# Feature Flags\n\nUse this skill when adding or changing framework feature flags in Next.js internals.\n\n## Required Wiring\n\nAll flags need: `config-shared.ts` (type) → `config-schema.ts` (zod). If the flag is consumed in user-bundled code (client components, edge routes, `app-page.ts` template), also add it to `define-env.ts` for build-time injection. Runtime-only flags consumed exclusively in pre-compiled bundles can skip `define-env.ts`.\n\n## Where the Flag Is Consumed\n\n**Client/bundled code only** (e.g. `__NEXT_PPR` in client components): `define-env.ts` is sufficient. Webpack/Turbopack replaces `process.env.X` at the user's build time.\n\n**Pre-compiled runtime bundles** (e.g. code in `app-render.tsx`): The flag must also be set as a real `process.env` var at runtime, because `app-render.tsx` runs from pre-compiled bundles where `define-env.ts` doesn't reach. Two approaches:\n\n- **Runtime env var**: Set in `next-server.ts` + `export/worker.ts`. Both code paths stay in one bundle. Simple but increases bundle size.\n- **Separate bundle variant**: Add DefinePlugin entry in `next-runtime.webpack-config.js` (scoped to `bundleType === 'app'`), new taskfile tasks, update `module.compiled.js` selector, and still set env var in `next-server.ts` + `export/worker.ts` for bundle selection. Eliminates dead code but adds build complexity.\n\nFor runtime flags, also add the field to the `NextConfigRuntime` Pick type in `config-shared.ts`.\n\n## Runtime-Bundle Model\n\n- Runtime bundles are built by `next-runtime.webpack-config.js` (rspack) via `taskfile.js` bundle tasks.\n- Bundle selection occurs at runtime in `src/server/route-modules/app-page/module.compiled.js` based on `process.env` vars.\n- Variants: `{turbo/webpack} × {experimental/stable/nodestreams/experimental-nodestreams} × {dev/prod}` = up to 16 bundles per route type.\n- `define-env.ts` affects user bundling, not pre-compiled runtime internals.\n- `process.env.X` checks in `app-render.tsx` are either replaced by DefinePlugin at runtime-bundle-build time, or read as actual env vars at server startup. They are NOT affected by the user's defines from `define-env.ts`.\n- **Gotcha**: DefinePlugin entries in `next-runtime.webpack-config.js` must be scoped to the correct `bundleType` (e.g. `app` only, not `server`) to avoid replacing assignment targets in `next-server.ts`.\n\n## Related Skills\n\n- `$dce-edge` - DCE-safe require patterns and edge constraints\n- `$react-vendoring` - entry-base boundaries and vendored React\n- `$runtime-debug` - reproduction and verification workflow\n", "skills/gate-tests/SKILL.md": "---\nname: gate-tests\ndescription: >\n  How to use the `@gate` / `@force-gate` test directives instead of `it.skip`\n  or fake-green skip patterns. Use when a test is known-failing under some\n  test-matrix dimension (dev mode, a bundler, an experimental flag like\n  cacheComponents), when converting `if (isNextDev) return` guards or\n  env-var `describe.skip` branches, when adding a condition to\n  test/lib/gate/conditions.ts, or when keying a fixture's experimental flag\n  on a __NEXT_TEST_AXIS letter. Covers directive choice, condition tiers,\n  the test-axis fixture pattern, pitfalls, and verification commands.\nuser-invocable: false\nmetadata:\n  internal: true\n---\n\n# Gating tests with `@gate` / `@force-gate`\n\nFull reference: [`test/lib/gate/README.md`](../../../test/lib/gate/README.md).\nThis skill is the decision guide: which directive to reach for, the standard\nconversion patterns, and how to verify.\n\n## Never write these — gate instead\n\n| Anti-pattern                                                           | Replacement                                                                 |\n| ---------------------------------------------------------------------- | --------------------------------------------------------------------------- |\n| `it.skip('...')` for a known failure                                   | `// @gate <cond>` (or `@gate FIXME` if no condition explains it)            |\n| `if (isNextDev) { test('skipped in dev mode', () => {}); return }`     | `// @force-gate prefetching` (or `!dev`) on the `describe`                  |\n| `(flagEnabled ? describe.skip : describe)(...)` keyed on `process.env` | `// @force-gate <cond>` (lazy) on the `describe`                            |\n| Duplicating a fixture directory per flag state                         | one fixture keyed on `__NEXT_TEST_AXIS` + a `@gate`/`@force-gate`           |\n| Branching expectations on `process.env.__NEXT_CACHE_COMPONENTS`        | `if (await gate((c) => c.cacheComponents))` (`gate` from `next-test-utils`) |\n\nThe skip patterns are fake-greens: nothing tells you when the bug they hide is\nfixed. `@gate` still runs the body and fails the suite the day the \"known\nfailure\" starts passing, so stale workarounds get deleted instead of rotting.\n\n## Choosing the directive\n\nDon't add mode gates that the test directory already guarantees:\n\n- `@gate dev` is unnecessary in `test/development/`: these tests only run in\n  dev mode.\n- `@gate start` is unnecessary in `test/production/`: these tests only run in\n  production build/start mode.\n- `@gate !deploy` is unnecessary outside `test/e2e/`: only `test/e2e/` tests\n  run in deploy mode.\n\nThe same applies to `@force-gate dev`, `@force-gate start`, and\n`@force-gate !deploy` in those respective locations.\n\nAsk what kind of difference you're encoding:\n\n1. **A behavior change — both states assert something meaningful.** Don't\n   gate the test at all: fork inside the body with the runtime `gate()` —\n   same condition registry, no inversion — which pinpoints exactly what\n   differs, and also covers `it.each`, where a pragma cannot attach:\n   `if (await gate((c) => c.cacheComponents)) { ... } else { ... }`. It\n   mirrors React's `gate(flags => ...)`; a pragma expression string works\n   too (`await gate('cacheComponents && !dev')`). A suite-level pragma is\n   too coarse here — it hides _what_ is different between the states.\n2. **A flag that changes the behavior of existing surface**\n   (`cacheComponents`, `optimisticRouting`) **and the suite is written for one\n   state.** `// @gate <cond>` on the test or `describe`. The body runs; a\n   false condition inverts the expectation (failure absorbed, a pass fails as\n   \"stale gate\"). The off state fails for a meaningful reason — the behavior\n   differs — so a pass is real information: the gate is stale, delete it.\n3. **A new API — the off state proves nothing.** Typically\n   `// @force-gate <cond>` (lazy) on the `describe`. An API that throws when\n   its flag is off — or is inert, like `useOffline()`, which compiles to a\n   hook that always reports online — can only fail vacuously (often slowly,\n   by timing out), and browser e2e time is considerable, so skip the run\n   (and the fixture build) instead of paying for it. Working example:\n   `test/e2e/app-dir/use-offline/`. This is discretion, not a rule: when the\n   flag changes behavior the suite can observe, the off state is meaningful\n   and `@gate` buys the staleness check.\n4. **`@force-gate <cond>` also when running the body is impossible**, not\n   merely failing: prefetching is off in dev, deploy has no local build\n   output, the fixture cannot even build under the condition.\n   - Static condition (`!dev`, `bundler`…) → real Jest `○ skipped` at\n     collection.\n   - Lazy condition on a `describe` → the fixture **build is skipped** when\n     false; tests report passed-with-`⚠ skipped by @force-gate` (Jest cannot\n     skip at runtime). Build-skipping covers `start`/`dev` suites where\n     `nextTestSetup` owns the build — not `skipStart` suites, not deploy.\n5. Pragmas stack: a common pair is a static `// @force-gate prefetching` plus\n   a lazy `// @gate <flag>` on the same `describe`.\n\n### Is the off-state run worth its cost?\n\nBrowser e2e time is not free, so weigh what the gated-off run buys. For a\nbehavior flag it usually replaces a run that was already being paid for — a\nfixture that pins its flags runs identically with and without the axis set,\nso keying the flag on an axis converts a redundant duplicate into coverage —\nand it is what proves a pass isn't vacuous: a test that passes with the\nfeature off wasn't testing the feature. Absorbed failures also fail fast, so\nthe off-state run is cheaper than it sounds. For a new API the calculus\nflips: the off state can only throw, which proves nothing, so use a lazy\n`// @force-gate <flag>` on the `describe` — the fixture build is skipped\ntoo, so the off state costs almost nothing.\n\n## Conditions\n\nEvery name in a pragma must be declared in `test/lib/gate/conditions.ts`\n(typos fail the suite at collection). Two tiers:\n\n- **static** — the run's shape: `dev`, `start`, `deploy`, `mode`, `turbopack`,\n  `rspack`, `webpack`, `bundler`, `react18`, `wasm`, `linux`, `macos`,\n  `windows`, `ci`; the deploy host `vercel`; specialized CI variants\n  `adapter`, `nodeMiddleware`, `standaloneOutput`, `turbopackDev`, and\n  `turbopackBuild`; plus the always-false `FIXME`/`TODO`.\n  `prod` and `prefetching` are semantic aliases for `!dev` — prefer the name\n  that states _why_ the suite cannot run.\n  `vercel` is true only in a deploy run with `NEXT_TEST_DEPLOY_TARGET_VERCEL=1`,\n  which our CI sets on every Vercel deploy job. Other platforms run the\n  deploy suites through `NEXT_TEST_DEPLOY_SCRIPT_PATH` to test their\n  adapters, so prefer it over `deploy` when the reason is Vercel-specific:\n  `@force-gate !deploy || vercel` skips only other platforms, `!vercel` skips\n  only Vercel.\n- **lazy** — a predicate over the fixture's _resolved_ `next.config`\n  (`cacheComponents`, `ppr`, `useOffline`, `output`, …).\n\nAdding one is a two-line change; follow the guidance at the top of\n`conditions.ts`. The rule that matters: **lazy conditions read the resolved\nconfig, never `process.env`** — env vars don't survive config resolution\n(`__NEXT_CACHE_COMPONENTS` only applies when the fixture doesn't set\n`cacheComponents` itself, and resolution implies flags the fixture never\nmentions).\n\n## Pattern: cover both states of an experimental flag\n\nInstead of pinning a flag on (which makes the plain and axis runs identical),\nkey it on a test axis and gate the suite. Axes are lettered (`A`, `B`, …) —\na fixed enumeration, not a boolean and not a sharding bucket. Key the flag so\nit is **enabled by default** — then the suite exercises the feature in plain\nlocal runs with no special env, and the axis run covers the off state:\n\n```js\n// next.config.js — pin every dimension except the one under test\nconst nextConfig = {\n  cacheComponents: true,\n  experimental: {\n    concurrentRouterQueue: process.env.__NEXT_TEST_AXIS !== 'A',\n  },\n}\n```\n\n```ts\n// @gate concurrentRouterQueue\nit('fails loudly on link navigation', async () => { ... })\n```\n\nThe plain run exercises the feature; the axis-A run covers the off state —\nthe gated tests are expected to fail there, and the suite fails the day they\nstart passing. Working example: `test/e2e/app-dir/concurrent-router-queue/`\n(tests whose expectations hold in both states stay ungated). The same keying\npairs with a lazy `@force-gate` when the off state proves nothing —\n`test/e2e/app-dir/use-offline/` — which skips the redundant axis run (build\nincluded) instead of covering it. Axis `A` aliases `__NEXT_CACHE_COMPONENTS`\nfor now (see `test/jest-global-setup.ts`) — fine, because these fixtures pin\n`cacheComponents` explicitly, so that run's env default is a no-op for them.\n\n**Keep exactly one flag varying per fixture.** A red shard must attribute to a\nsingle dimension.\n\n## Pitfalls\n\n- A pragma the transform can't attach is a **hard error**: a blank line\n  between pragma and `it(`, `it.each`/`it.failing`, or a pragma inside a\n  JSDoc block. Prose comments must not begin with `@gate`. A pragma on a\n  skipped test (`it.skip`, `xit`, …) errors as ambiguous — remove the skip or\n  the pragma. A skip without a pragma is respected.\n- A `describe`-level gate does not reach `it.each` tests.\n- Gated-false bodies that fail by _stalling_ waste the full Jest timeout —\n  and under a lazy gate they fail the suite anyway (the runtime inversion\n  only absorbs thrown errors; a static gate rides Jest's native\n  `test.failing`, which does absorb timeouts). Bodies that fail via `retry()`\n  timeouts also make the off-state run slow; a fast first assertion is worth\n  having.\n- Failures cascade in the off state: an absorbed failure mid-body skips the\n  body's cleanup (e.g. a browser context left offline), so later tests may\n  fail for cascade reasons. Acceptable for a tripwire, but don't puzzle over\n  the individual failure messages in a gated-off run.\n- `afterEach` failures (e.g. redbox matchers) are not gated, only the body is.\n  Hooks under a false lazy `@force-gate` are the exception: they are skipped\n  with the suite instead of running against a fixture that was never booted.\n- Gated titles are unchanged in the Jest output; the\n  `⚠ gated test failed as expected` log line is the only signal.\n- `pragma-transform.js` bails out early on files containing neither `@gate`\n  nor `@force-gate` as substrings — keep both checks if you touch it.\n\n## Verify a gated suite in every state it can run in\n\n```sh\n# plain run (flag on): expect normal passes, no warnings\nNEXT_SKIP_ISOLATE=1 pnpm test-start-webpack test/e2e/app-dir/<suite>/<suite>.test.ts\n\n# axis run (flag off): expect `⚠ gated test failed as expected (@gate …)`\n__NEXT_TEST_AXIS=A NEXT_SKIP_ISOLATE=1 pnpm test-start-webpack test/e2e/app-dir/<suite>/<suite>.test.ts\n\n# dev (static @force-gate !dev): expect `○ skipped` at collection, no fixture boot\nNEXT_SKIP_ISOLATE=1 pnpm test-dev-webpack test/e2e/app-dir/<suite>/<suite>.test.ts\n```\n\nA suite with a lazy `@force-gate` on the `describe` should additionally show\n`skipping build` behavior (no `next build`) in the state where the condition\nis false.\n\nUnit tests for the infrastructure itself: `pnpm test-unit test/unit/gate/`.\n\n## Related skills\n\n- `$flags` — adding the experimental flag itself (config-shared, schema,\n  define-env)\n- `$router-act` — the prefetch-timing patterns most gated suites also use\n", "skills/gh-stack/SKILL.md": "---\nname: gh-stack\ndescription: >\n  Manages stacked PRs and splits multi-part work into reviewable branches with gh-stack.\n  Use for stack creation, viewing, edits, push, submit, sync, rebase, merge, or checkout;\n  when asked to split or isolate work for review; whenever a user mentions a stack,\n  branch layers, dependent PRs, or gh stack; or when a stack is checked out.\nmetadata:\n  author: github\n  version: '0.1.0'\n---\n\n# gh-stack\n\n`gh stack` is a [GitHub CLI](https://cli.github.com/) extension for stacked branches and pull\nrequests. A stack is an ordered chain of branches rooted on a trunk, where each branch has one PR\nbased on the branch below it, so a reviewer sees only that layer's diff.\n\n`gh stack` prints a stack trunk-first, left to right:\n\n```\n(main) <- auth <- api <- frontend\n```\n\nLeft is the **bottom**, right is the **top**. `auth` is based on `main` and merges first;\n`frontend` merges last. `up` moves toward the top, away from trunk; `down` moves toward it.\nFoundational work belongs at the bottom, code that depends on it above. For how to choose the\nlayers, read `references/stack-design.md`.\n\n## Setup\n\n```bash\ngh extension install github/gh-stack\ngit config rerere.enabled true         # remember conflict resolutions\ngit config remote.pushDefault origin   # required if the repo has more than one remote\n```\n\n## Non-interactive use\n\n`gh stack` branches on whether **stdout is a TTY**. Piped, most commands error cleanly or print\nstatic text; under a PTY the same commands open a prompt or a full-screen TUI and block forever.\nAgent harnesses differ, so always pass the flags below instead of relying on that detection.\n\n**Multiple remotes:** never run `push`, `submit`, `sync`, `rebase`, or `link` without\n`--remote <name>` unless `remote.pushDefault` is configured. `checkout` and `trunk` have no\n`--remote` flag and require the config.\n\n| Always run                                | Never run bare      | Why                                           |\n| ----------------------------------------- | ------------------- | --------------------------------------------- |\n| `gh stack view --json`                    | `gh stack view`     | opens a TUI under a PTY                       |\n| `gh stack submit --auto`                  | `gh stack submit`   | prompts for a title per new PR                |\n| `gh stack merge <target> --yes`           | `gh pr merge`       | `gh pr merge` cannot merge a stack            |\n| `gh stack init <branch>...`               | `gh stack init`     | prompts for branch names                      |\n| `gh stack add <branch>`                   | `gh stack add`      | prompts for a name, and fails even when piped |\n| `gh stack checkout <target>`              | `gh stack checkout` | opens a selection menu                        |\n| `gh stack up` / `down` / `top` / `bottom` | `gh stack switch`   | `switch` is menu-only                         |\n| —                                         | `gh stack modify`   | TUI-only, no non-interactive path             |\n\n- `view --short` is safe in both modes, but it is formatted for humans. Use `--json` to parse.\n- **`checkout <pr>` when a different local stack already covers those branches** cannot be forced.\n  Run `gh stack unstack --local` first (this keeps the stack on GitHub), then retry.\n\n## Branch placement\n\n- **Starting multi-part work:** create the stack before writing files. Do not implement every\n  concern on trunk and split it later. Put one dependent concern in each layer, bottom to top.\n- **Editing an existing stack:** check out the layer that owns the change before editing. Never\n  commit a lower layer's concern on the current top branch. Run `gh stack view --json`; if\n  ownership is unclear, inspect `git log --all -- <path>`. Then check out the owner, edit, commit,\n  rebase upstack, and return to top.\n\n```bash\ngh stack down                   # or: gh stack checkout api\ngit add ... && git commit -m \"Add get-user endpoint\"\ngh stack rebase --upstack       # replay every branch above onto the change\ngh stack top                    # return to where you were\ngh stack push\n```\n\n## Core loop\n\n```bash\ngh stack init auth              # create the stack and check out its branch\ngit add ... && git commit -m \"Add auth middleware\"\ngh stack add api                # next layer, branched from the current one\ngit add ... && git commit -m \"Add API routes\"\ngh stack submit --auto          # push every branch and open draft PRs\ngh stack view --json            # confirm\n```\n\nAdd `--open` to `submit` to create PRs ready for review instead of drafts. Branch names are\nverbatim — `gh stack add refactor/foo` creates `refactor/foo`.\n\n## Staying in sync\n\n```bash\ngh stack sync                   # fetch, reconcile with GitHub, rebase, push, refresh PR state\ngh stack sync --prune           # also delete local branches for merged PRs\n```\n\nPruning never happens without `--prune` when non-interactive. If the local and remote stacks have\ndiverged, `sync` prints both chains, makes no changes, and exits 0 with `Sync aborted` — see\n`references/troubleshooting.md`.\n\n## Merging\n\nScope the merge with an argument:\n\n```bash\ngh stack merge 42 --yes          # PR #42 plus every unmerged PR below it\ngh stack merge 7 --yes           # every unmerged PR in stack #7\ngh stack merge 42 --yes --squash # or --merge, --rebase, --merge-method <method>\n```\n\nPass a PR number to merge that PR and every unmerged PR below it, or a stack number to merge every\nunmerged PR in that stack. The operation is all-or-nothing: if any PR in that set cannot merge,\nnone do.\n\nWithout a method flag the last-used method is reused. If the base branch uses a merge queue, the\nstack is queued instead and the queue picks the method, ignoring any flag you passed with a\nwarning; queued PRs may land in separate groups.\n\n## Reading state\n\n`gh stack view --json` writes JSON to **stdout**. Status messages go to **stderr** — do not parse\nthem, branch on exit codes instead.\n\n```\ntrunk           string\ncurrentBranch   string\nbranches[]      name, head, base, isCurrent, isMerged, isQueued, needsRebase\nbranches[].pr   number, url, state (\"OPEN\" | \"MERGED\" | \"QUEUED\"); absent when no PR exists\n```\n\n`base` is the saved SHA of the parent branch that this branch was last known to contain. It may be\nolder than the parent's current tip. `needsRebase` is true when the current parent tip is no longer\nan ancestor of the branch.\n\n## Exit codes\n\n| Code | Meaning                    | Recovery                                                   |\n| ---- | -------------------------- | ---------------------------------------------------------- |\n| 0    | Success                    | —                                                          |\n| 1    | Generic error              | Read stderr                                                |\n| 2    | Not in a stack             | `gh stack init`, or `gh stack checkout <target>`           |\n| 3    | Rebase conflict            | Follow the Exit 3 recovery below                           |\n| 4    | GitHub API failure         | Check `gh auth status`, retry                              |\n| 5    | Invalid arguments          | Fix the invocation; see `<command> --help`                 |\n| 6    | Disambiguation required    | Branch is in several stacks; check out a non-shared branch |\n| 7    | Rebase already in progress | `gh stack rebase --continue` or `--abort`                  |\n| 8    | Stack file locked          | Another `gh stack` process is writing; retry after ~5s     |\n| 9    | Stacked PRs unavailable    | Not enabled on the repository; tell the user               |\n| 10   | Modify recovery required   | `gh stack modify --abort`                                  |\n\n**Exit 3 recovery:**\n\n- After `gh stack rebase`: resolve the files, run `git add`, then\n  `gh stack rebase --continue`; use `gh stack rebase --abort` to restore the stack.\n- After `gh stack sync`: the stack has already been restored. Run `gh stack rebase` to recreate the\n  conflict, then resolve and continue as above.\n\n## Constraints\n\n- Stacks are strictly linear: one parent, at most one child. Use separate stacks for parallel work.\n- There is no non-interactive reorder or removal. Errors may suggest `gh stack modify`, but it is\n  TUI-only — restructure with `unstack` then `init` instead.\n- PR titles and bodies are auto-generated. Use `gh pr edit` afterwards to change them.\n- `checkout <branch-name>` resolves against local stacks only. Use a stack or PR number to pull a\n  stack down from GitHub.\n\n## More detail\n\n`gh stack <command> --help` is authoritative for flags and arguments. Note that\n`gh stack help <command>` does **not** work — it prints the top-level help.\n\nOpen the reference whose trigger matches the task; no need to preload all three.\n\n- `references/stack-design.md` — read before creating a stack, when deciding how many layers to\n  use, what belongs in each one, or whether work belongs in a new stack.\n- `references/commands.md` — read when a command fails unexpectedly or you need its preconditions,\n  side effects, atomicity, or ordering guarantees.\n- `references/troubleshooting.md` — read on a rebase conflict, after a squash-merge, on local and\n  remote divergence, when restructuring a stack, or when driving stacks from another tool.\n", "skills/gh-stack/references/commands.md": "# Command behavior\n\n`gh stack <command> --help` is authoritative for flags and arguments. (`gh stack help <command>` only prints the top-level help.) This file only covers behavior `--help` does not\nexplain: preconditions, side effects, atomicity, and failure modes.\n\n## Contents\n\n- [init](#init)\n- [add](#add)\n- [push](#push)\n- [submit](#submit)\n- [link](#link)\n- [sync](#sync)\n- [rebase](#rebase)\n- [view](#view)\n- [checkout](#checkout)\n- [unstack](#unstack)\n- [merge](#merge)\n- [Navigation](#navigation)\n\n## init\n\nCreates the stack and checks out the **last** branch in the list, so a single `init` can lay down\nthe whole chain: `gh stack init auth api frontend`.\n\n`init` processes branch arguments from bottom to top. Existing branches are adopted. If the first\nbranch does not exist, it is created from the trunk; each later new branch is created from the\nbranch immediately before it. There is no separate adopt mode — existence decides. `--base`\nselects a non-default trunk.\n\n`init` also enables `git rerere`. Under a TTY the first run in a repo asks for confirmation; set\n`git config rerere.enabled true` beforehand to skip it.\n\n## add\n\n- **Must run from the top branch** of the stack (or the trunk when the stack is still empty).\n  Anywhere else it exits **5** with `can only add branches on top of the stack`. Run `gh stack top`\n  first.\n- **Uncommitted changes carry over.** Without `-Am`, `add` does not touch the working tree, so\n  staged and unstaged changes follow you onto the new branch. Commit or stash first for a clean start.\n- **`add -Am` commits in place when the current branch has no commits yet** — for example\n  immediately after `init` — instead of creating a branch. This is deliberate: the first layer\n  usually needs its content before a second layer exists.\n- `-A` and `-u` are mutually exclusive, and both require `-m`.\n\n## push\n\nPushes every active (non-merged, non-queued) branch in one multi-ref push with per-branch\n`--force-with-lease`.\n\n**Not atomic.** Some branches may update while another is rejected. A rejection means that branch\nmoved on the remote; fix that branch and rerun — rerunning is safe and skips what already landed.\n\n`push` never creates or updates pull requests. Use `submit` for that.\n\n## submit\n\nPushes each active branch, then creates a PR for every branch that lacks one, basing it on the\nfirst non-merged ancestor, then links them into a Stack on GitHub.\n\n- **Not atomic.** Branches are pushed sequentially with per-branch `--force-with-lease`. If a later\n  push is rejected, earlier pushes and PR updates stand. Fix the rejection and rerun the same command.\n- **A fully merged stack cannot be extended.** When every PR in the current stack is already merged,\n  `submit` forks the remaining unmerged branches into a **new** stack rooted at the trunk and creates\n  it on GitHub, leaving the merged stack untouched.\n- **Title generation with `--auto`:** a branch with a single commit uses that commit's subject as\n  the title and its body as the PR body. A branch with multiple commits humanizes the branch name\n  (hyphens and underscores become spaces). There is no flag for a custom title or body; use\n  `gh pr edit` afterwards.\n- `--open` marks new _and existing_ PRs ready for review; without it new PRs are drafts.\n- Requires stacked PRs to be enabled on the repository. If not, `submit` exits **9** when\n  non-interactive (under a TTY it offers to create ordinary unstacked PRs instead).\n\n## link\n\nCreates or updates a stack on GitHub **without any local tracking state**. This is the path for\nbranches managed by another tool or living in another worktree — see `troubleshooting.md`.\n\n- Arguments are given bottom to top. Each is a branch name or a PR number; a numeric argument is\n  tried as a PR number first and falls back to a branch name.\n- **A numeric first argument is treated as a stack number only when a stack with that number\n  exists.** In that case the remaining arguments are appended to the top of that stack and you do\n  not re-list its current PRs: `gh stack link 7 feature-c`. Arguments already in the stack are\n  skipped; arguments belonging to a different stack are rejected.\n- Branch arguments are pushed automatically (non-force, atomic). Missing PRs are created with\n  auto-generated titles and correctly chained bases; existing PRs with a wrong base are corrected.\n- Stack membership is **additive only** — `link` never removes a PR from a stack.\n\n## sync\n\nThe routine command. Steps, in order:\n\n1. **Fetch** from the remote.\n2. **Reconcile with the GitHub stack.** PRs added to the stack on github.com are pulled down and\n   appended locally. On divergence, aborts when non-interactive (see `troubleshooting.md`).\n3. **Fast-forward the trunk.** Skipped when already current; warns when diverged.\n4. **Cascade rebase when needed.** This runs if the trunk moved, a stack branch was fast-forwarded\n   from its remote, or a branch no longer contains its expected parent. Merged PRs are handled\n   automatically. On conflict, **all branches are restored** to their pre-rebase state and the\n   command exits **3**.\n5. **Push** all active branches, atomically.\n6. **Refresh PR state** from GitHub.\n7. **Sync the stack object** — link open PRs into a stack, additively. Only when two or more PRs\n   exist. `sync` never opens PRs; that is `submit`.\n8. **Prune** local branches for merged PRs, only when `--prune` is passed in a non-interactive\n   environment.\n\n## rebase\n\nPulls from the remote and cascade-rebases. Use it when `sync` reported a conflict or when you need\nto rebase only part of the stack.\n\n- `--upstack` rebases from the current branch to the top. This is what you run after editing a\n  lower layer.\n- `--downstack` rebases from the trunk to the current branch.\n- `--no-trunk` skips fetching and the trunk rebase entirely, aligning stack branches with each\n  other only.\n- `--continue` after staging resolutions; `--abort` restores every branch.\n- A merged PR is detected automatically and replayed with `--onto` against the correct target, so a\n  squash-merged parent does not produce spurious conflicts.\n- Starting a rebase while one is in progress exits **7**.\n\n## view\n\n- `--json` writes the machine-readable payload to stdout. Its schema is in `SKILL.md`.\n- Bare `view` opens a full-screen TUI when stdout is a TTY, and prints static text when piped.\n- `--short` prints a compact one-line-per-branch summary and never opens the TUI, but it is\n  formatted for humans; parse `--json` instead.\n- `view` refreshes PR state from GitHub as a side effect, best-effort — it does not fail when the\n  API is unreachable.\n\n## checkout\n\nAccepts a stack number, PR number, PR URL, or branch name.\n\n- A bare number resolves as a **stack number first**, then a PR number, then a branch name.\n- Stack numbers, PR numbers, and PR URLs fetch from GitHub, pull the branches down, and set the\n  stack up locally.\n- A **branch name resolves against locally tracked stacks only** and never contacts GitHub. Use a\n  stack or PR number to pull a stack that is not tracked locally.\n- If a local stack already exists over those branches with a different composition, `checkout`\n  cannot be forced past it. Run `gh stack unstack --local` first, then retry.\n- `checkout` has no flags. It relies on `remote.pushDefault` when several remotes exist.\n\n## unstack\n\nRemoves the stack **grouping** only. It never deletes pull requests or branches.\n\n- With no argument it targets the active stack — the one containing the current branch — removing\n  it on GitHub and locally.\n- With a stack number it works from anywhere in the repository, tracked locally or not, via the API.\n  Local tracking is also removed when present.\n- `--local` removes local tracking only and never contacts GitHub. Combining `--local` with a stack\n  number that is not tracked locally is an error.\n- An unknown stack number exits **2**.\n\n## merge\n\n- Scope with an argument: pass a PR number to merge that PR and every unmerged PR below it in the\n  stack, or pass a stack number to merge every unmerged PR in that stack.\n- **All-or-nothing.** If any PR in that exact merge set cannot be merged, none are, and the reason\n  is reported.\n- The method comes from `--squash`, `--rebase`, `--merge`, or `--merge-method <method>`. Without\n  one, the last-used method is reused.\n- Only basic PR state is checked before merging: open and not a draft. Bypassing merge requirements\n  is not supported for stacks.\n- **A merge queue on the base branch overrides everything.** The stack is added to the queue rather\n  than merged; the queue chooses the method and any method flag you passed is ignored with a\n  warning. Queued PRs are submitted together but land as the queue processes them, so they may merge\n  in separate groups rather than all at once.\n- `gh pr merge` cannot merge a stack. Always use `gh stack merge`.\n\n## Navigation\n\n`up`, `down`, `top`, `bottom`, and `trunk` are always non-interactive. `up` and `down` accept a\ncount (`gh stack up 3`). Movement clamps at the stack bounds, and merged branches are skipped when\nnavigating from an active branch, so `bottom` lands on the lowest _unmerged_ branch.\n\n`gh stack switch` is a selection menu with no non-interactive path. Use the commands above instead.\n", "skills/gh-stack/references/stack-design.md": "# Designing a stack\n\nHow to decide what goes in each layer. Read this before running `gh stack init`.\n\n## Contents\n\n- [Plan the layers before writing code](#plan-the-layers-before-writing-code)\n- [Branch naming](#branch-naming)\n- [Staging changes deliberately](#staging-changes-deliberately)\n- [When to add a layer](#when-to-add-a-layer)\n- [One stack, one story](#one-stack-one-story)\n\n## Plan the layers before writing code\n\nA stack is a dependency chain. If code in one layer depends on code in another, the dependency must\nlive in the same branch or a lower one. That constraint is much cheaper to satisfy by planning than\nby restructuring later, because there is no non-interactive in-place reorder — fixing the order\nmeans `unstack` and `init` again.\n\nDecide the layers first, then write code into them:\n\n```\n(main) <- todo-app/models <- todo-app/api <- todo-app/frontend <- todo-app/integration\n```\n\n- `todo-app/models` — shared types and schema\n- `todo-app/api` — routes that use the models\n- `todo-app/frontend` — components that call the routes\n- `todo-app/integration` — tests exercising the whole feature\n\nThis is illustrative. Infer the stack topic and layer names from the actual task; do not reuse\n`todo-app` or these layer names literally.\n\nThe failure mode to avoid is writing everything on one branch and trying to split it afterwards.\nIf a task is large enough to warrant a stack, create the stack at the start.\n\n## Branch naming\n\nPrefer a shared topic prefix plus the layer's concern:\n`<topic>/<concern>` — for example, `billing/schema`, `billing/api`, `billing/ui`.\nThis keeps related branches recognizable without using generic names that could belong to any\nstack. **User and repository branch naming conventions take precedence; follow them instead.**\n\nNames are used exactly as given — nothing is prepended or transformed, and slashes are kept, so\n`gh stack add refactor/foo` creates a branch literally named `refactor/foo`.\n\nIf you pass `-m` without a branch name, the name is generated from the commit message in\ndate-and-slug form (for example `03-24-add_api_routes`). Prefer naming the branch yourself.\n\n## Staging changes deliberately\n\nUse `git add` and `git commit` directly rather than the `add -Am` shortcut. The point is control\nover which changes land in which branch. With several modified files in the working tree, stage the\nsubset that belongs to the current layer, commit it, then create the next branch and stage the rest\nthere:\n\n```bash\ngit add internal/models/user.go internal/models/session.go\ngit commit -m \"Add user and session models\"\n\ngh stack add api-routes\ngit add internal/api/routes.go internal/api/handlers.go\ngit commit -m \"Add user API routes\"\n```\n\nMultiple commits per branch are fine. What matters is that every commit in a branch serves the same\nconcern, and that a change belonging to a different concern goes in a different branch.\n\nNote that `gh stack add <branch>` without `-Am` does not touch the working tree, so uncommitted\nchanges carry over to the new branch. Commit or stash first if you want the new layer to start clean.\n\n## When to add a layer\n\nAdd a branch when you start a **different concern that depends on what you have built so far**.\nSignals:\n\n- Moving from backend to frontend, or from core logic to tests or documentation\n- The next changes have a different reviewer audience\n- The current branch's diff is already large enough to review on its own\n\nA layer that cannot be described in one sentence is usually two layers.\n\n## One stack, one story\n\nA stack should read as a coherent progression: a reviewer walks the PRs bottom to top and sees the\nfeature being built.\n\n**Use a single stack** when every branch serves the same feature or project, even if the layers span\ndifferent concerns.\n\n**Start a separate stack** for unrelated work — a different feature, an unrelated bug fix, an\nindependent refactor. Do not mix efforts into one stack just because you happened to work on both.\nUse `gh stack init` for the new effort, or `gh stack checkout <target>` to move between existing\nstacks.\n\nA trivial incidental fix can ride along in the current stack. Once it grows into its own project, it\ndeserves its own stack.\n", "skills/gh-stack/references/troubleshooting.md": "# Troubleshooting and recovery\n\n## Contents\n\n- [Rebase conflicts (exit 3)](#rebase-conflicts-exit-3)\n- [After a squash merge](#after-a-squash-merge)\n- [Local and remote stacks have diverged](#local-and-remote-stacks-have-diverged)\n- [Restructuring a stack](#restructuring-a-stack)\n- [Branch belongs to several stacks (exit 6)](#branch-belongs-to-several-stacks-exit-6)\n- [Driving stacks from another tool or worktree](#driving-stacks-from-another-tool-or-worktree)\n- [Stack file is locked (exit 8)](#stack-file-is-locked-exit-8)\n- [An interrupted modify session (exit 10)](#an-interrupted-modify-session-exit-10)\n\n## Rebase conflicts (exit 3)\n\n`rebase` and `sync` both exit 3 on conflict. `sync` restores every branch to its pre-rebase state\nfirst, so a failed `sync` leaves nothing half-applied; a failed `rebase` stops mid-flight and waits.\n\n```bash\ngh stack rebase\n# exit 3 — conflicted paths are listed on stderr\ngit add <resolved paths>\ngh stack rebase --continue     # repeat if the next branch also conflicts\n```\n\n`gh stack rebase --abort` restores every branch in the stack, not just the current one.\n\nBecause `init` enables `git rerere`, a conflict you resolve once is replayed automatically the next\ntime the same conflict appears — which is common, since a change low in the stack is rebased through\nevery branch above it. Without `rerere`, repeated conflicts may need manual resolution on each\naffected layer.\n\n## After a squash merge\n\nA squash merge replaces the branch's commits with one new commit, so the originals no longer exist\nin the trunk's history and an ordinary rebase would try to replay them again.\n\n`gh stack sync` detects this and rebases with `--onto` against the correct target, skipping the\nmerged branch:\n\n```bash\ngh stack sync\ngh stack view --json    # merged branch reports \"isMerged\": true, \"state\": \"MERGED\"\n```\n\nNo manual action is needed. If the replay conflicts, `sync` restores all branches and exits 3.\nRun `gh stack rebase` to rerun the rebase, which will stop at the conflict and allow you to resolve\nand then `--continue` until complete. Use `gh stack sync --prune` to also delete local branches for\nmerged PRs.\n\n## Local and remote stacks have diverged\n\nDivergence means the local stack and the stack on GitHub changed in different ways — for example\nbranches were added locally while a PR was added to the stack on github.com.\n\nWhen non-interactive, `sync` prints both chains, changes nothing, and exits **0** with\n`Sync aborted`. Success here does not mean the sync happened; check for that message, or re-run\n`gh stack view --json` and compare.\n\nTwo resolution paths:\n\n- **Keep the remote version.** Drop local tracking and pull the stack back down.\n\n  ```bash\n  gh stack unstack --local          # keeps the stack on GitHub\n  gh stack checkout <stack-number>  # or a PR number\n  ```\n\n- **Keep the local version.** Remove the grouping on GitHub, then recreate it from local state.\n\n  ```bash\n  gh stack unstack                  # removes the grouping; PRs and branches survive\n  gh stack submit --auto\n  ```\n\nNeither path deletes pull requests or branches.\nRemote unstacking leaves PRs that are merging (auto-merge enabled) or are queued (in a merge queue)\nstacked. If needed, clear that state before retrying.\n\n## Restructuring a stack\n\nThere is no non-interactive reorder, rename, or removal. `add` run from the wrong branch suggests\n`gh stack modify`, but that is TUI-only. Tear the stack down and rebuild it instead:\n\n```bash\ngh stack unstack                       # removes local tracking and the GitHub grouping\n# Rename or drop branches, and rewrite ancestry as needed.\ngh stack init --base main branch-1 branch-2 branch-3\ngh stack submit --auto                 # re-link on GitHub\n```\n\n`init` adopts branches that already exist, so the rebuild reuses them rather than creating new ones.\nExisting PRs survive. Once Git ancestry is correct, `submit` updates their base branches and\nre-links the stack on GitHub.\n\nChanging metadata does **not** change Git ancestry. Reorder commits first, then rebuild the stack.\nFor example, to change `main <- models <- migration <- ui` into\n`main <- migration <- models <- ui`:\n\n```bash\nold_models=$(git rev-parse models)\nold_migration=$(git rev-parse migration)\ngit rebase --onto main \"$old_models\" migration\ngit rebase --onto migration main models\ngit rebase --onto models \"$old_migration\" ui\ngh stack unstack\ngh stack init --base main migration models ui\n```\n\nThe first rebase moves migration-only commits onto trunk, the second replays model commits above\nthem, and the third replays UI-only commits above models. Preserve the old boundary SHAs before\nmoving any branch. For a different reorder, identify each layer's range with\n`git log <old-parent>..<branch>`, then replay the ranges bottom to top.\n\n## Branch belongs to several stacks (exit 6)\n\nCommands exit 6 when the current branch cannot identify a single stack — typically because it is the\ntrunk of more than one stack. There is no flag to disambiguate.\n\n```bash\ngh stack checkout <a-branch-unique-to-the-intended-stack>\n```\n\nThen rerun. Commands that take an explicit stack number (`merge 7`, `unstack 7`) sidestep the\nproblem entirely, since they do not infer the stack from the current branch.\n\n## Driving stacks from another tool or worktree\n\n`gh stack link` creates and updates stacks purely through the API, with no local tracking state.\nUse it when branches are managed by jj, Sapling, git-town, a separate worktree, or any workflow\nwhere the local `.git/gh-stack` file would be wrong or absent.\n\n```bash\ngh stack link branch-a branch-b branch-c        # bottom to top\ngh stack link --base develop --open a b c       # non-default trunk, ready for review\ngh stack link 10 20 30                          # by PR number\ngh stack link 7 feature-d                       # append to existing stack #7\n```\n\nBecause `link` writes no local state, the local navigation commands (`up`, `down`, `top`, `bottom`)\nwill not work on the result. Use `gh stack checkout <stack-number>` if you later want local tracking.\n\n## Stack file is locked (exit 8)\n\nAnother `gh stack` process holds the exclusive lock on `.git/gh-stack.lock`. The lock times out\nafter about five seconds, so wait and retry. A persistent exit 8 means another process still holds\nthe lock; identify and stop that process before retrying.\n\n## An interrupted modify session (exit 10)\n\n`gh stack modify` is TUI-only and should never be invoked by an agent. If a repository is left in\nthis state by someone else, restore it:\n\n```bash\ngh stack modify --abort\n```\n\nRelated: `submit` also detects a pending modify state, and under a TTY asks before overwriting the\nstack on GitHub with local state.\n", "skills/insight-error-page/SKILL.md": "---\nname: insight-error-page\ndescription: Write or audit an insight-kind error page for the Next.js dev overlay. Use when creating a new `errors/<slug>.mdx` page, auditing an existing one, or checking that a page matches the framework fix cards. Covers page structure, title alignment, FixCard cards with Copy prompt button, code snippets, terminology verification against canonical docs, and Vercel technical writing style.\nmetadata:\n  internal: true\n---\n\n# Insight Error Page — Write & Audit\n\nWrite or audit an `errors/<slug>.mdx` insight-kind page that ships from this repo to `nextjs.org` and mirrors the fix-card set in the Next.js dev overlay.\n\n> **Terminology**: the frontmatter uses `kind: insight` but the body text calls these \"errors\" — never \"insights\". Write \"this error\", \"error pages\", \"dismiss the error\".\n\n## When to use this skill\n\n- **Write mode**: \"create the error page for `next-prerender-random`\", \"write the sync IO docs\"\n- **Audit mode**: \"audit the blocking-prerender-dynamic page\", \"check the error pages match the framework\"\n- Any task involving `errors/*.mdx` insight pages (frontmatter has `kind: insight`)\n\n## Source of truth chain\n\nEvery decision traces back to one of these. When in doubt, read the source — don't guess.\n\n| What                                          | Source file                                                                                   | How to read it                                                                                       |\n| --------------------------------------------- | --------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |\n| Card titles, IDs, groups, snippets, link URLs | `packages/next/src/next-devtools/dev-overlay/components/instant/instant-guidance-data.ts`     | Each `FixCard[]` array is one error family                                                           |\n| Error headline (literal text user sees)       | `packages/next/src/server/app-render/sync-io-messages.ts`, `blocking-route-messages.ts`, etc. | `createSyncIOError`, `createDynamicBodyError`, etc. — the template string is the headline            |\n| Existing page (content to preserve)           | `errors/<slug>.mdx` in this repo                                                              | Read the full file; relocate useful content that doesn't fit fix cards into Gotchas or Other options |\n| Canonical API docs (terminology)              | `docs/01-app/` in this repo                                                                   | Cross-check every API name, directive name, and concept against the published docs                   |\n| Template structure                            | This skill file (below)                                                                       | The canonical shape of the page                                                                      |\n| Vercel writing style                          | The `vercel-technical-writing` skill in `vercel/front` (not present here)                     | Apply end-to-end; see \"Voice and style\" below for the rules condensed                                |\n\n## Before you start\n\n1. **Read the framework card data** for the error family you're writing. Find the matching `FixCard[]` in `instant-guidance-data.ts`. Note every card's `id`, `title`, `group`, `link`, and `snippets`.\n2. **Read the factory message** that produces the dev-overlay headline. Find `createSyncIOError`, `createSyncIOClientError`, `createDynamicBodyError`, etc. The headline template (minus the `Route \"...\"` prefix) becomes the page `title`.\n3. **Read the existing `errors/<slug>.mdx`** if it exists. Note every pattern, code example, and caveat. You must preserve all useful content — relocate it if the new structure doesn't have a 1:1 slot for it.\n4. **Read the canonical docs** for every API you'll reference: `use cache`, `cacheLife`, `cacheTag`, `connection`, `Suspense`, `useEffect`, `use client`, `generateStaticParams`, etc. Use the exact terminology from the published docs.\n5. **Apply Vercel technical writing style** (active voice, sentence-case headings, no banned words). The full `vercel-technical-writing` skill lives in `vercel/front`; the condensed rules below are the minimum bar.\n\n## Page structure (mandatory)\n\nEvery page follows this exact shape. Do not add, remove, or reorder sections.\n\n```\n---\ntitle: <literal dev-overlay headline, no period, strip Route \"...\" prefix>\nkind: insight\n---\n\n<the Instant Navigations callout div — the styled box linking the blog post and the Ensuring instant navigations guide; copy it from any existing insight page>\n\n<Framing, 2-3 paragraphs. Paragraph 1 opens \"During <phase>, <event>\" in past tense (e.g. \"During prerendering, a Server Component called ...\"), names the APIs, and states the mechanism or consequence. Never open a paragraph with inline code — lead with a word (\"The `params` prop ...\"). Later paragraphs carry the teaching and cross-link sibling pages (parallel API families + client/server counterpart) using the \"For X, see Y\" formula.>\n\n## Ways to fix this\n\n<FixCardGrid> wrapping one <FixCard /> per framework card, in framework order\n\n## <Card 1 title>\n  Choose this fix when ...\n  ### Patterns\n  ### Trade-off\n  ### Gotchas\n  (optional: ### Short-lived caches — only for cache fixes)\n\n## <Card 2 title>\n  ...\n\n## <Card N title>\n  ...\n\n(optional: ## Other options — for useful patterns that don't map to a framework fix card but are still relevant. Examples: bridging to a different error page's fix (\"Cache the value in a Server Component\" on a client page, linking to the server page), upstream content from `errors/<slug>.mdx` that doesn't fit the card structure, alternative APIs that sidestep the problem entirely. Each option gets its own `###` heading with framing prose, a code snippet, and a \"Learn more\" link to the page that covers it in full.)\n\n## Verifying the fix\n  (canonical two paragraphs — see \"Verifying the fix\" rule below)\n\n## Don't want this validation?\n  (canonical opt-out block — see \"Don't want this validation?\" rule below.\n   Exception: sync-IO pages replace this with \"## Why `instant = false` doesn't clear this error\",\n   because the opt-out cannot suppress sync-IO aborts.)\n\n## Related Insights\n  (full list of every other insight-kind error page, current page omitted)\n```\n\n## Rules (hard requirements)\n\n### Frontmatter\n\n- `title` = the dev-overlay display headline, no period. That is the string the overlay shows (see the headline strings in `errors.tsx` / the factory in e.g. `sync-io-messages.ts`), with the `Route \"...\"` prefix stripped and any inline expression genericized (the client-hook overlay shows `` `useSearchParams()` `` inline; its docs title says \"in a Client Component\" instead).\n- `kind: insight` — always present.\n\n### Verifying the fix\n\nEvery page has a `## Verifying the fix` section before the opt-out block. No page has a top-level Good to know; page-specific tips go in Gotchas under the relevant fix section. Two canonical paragraphs:\n\n1. The observable check: \"After applying a fix, reload the route and confirm the page immediately paints meaningful UI, with any `<Suspense>` fallbacks covering only the regions that stream in.\" (navigation insights say \"navigate to the route and confirm the insight no longer appears in the dev overlay and ...\" instead of \"reload the route\"). Followed by the empty-shell caveat sentence: a boundary around the whole page body can pass validation with an empty shell.\n2. The tooling paragraph: dev overlay points at the failing component; from a build, the output is more abbreviated. Run `next build --debug-prerender` for full user-frame stack traces and `next build --debug-build-paths /dashboard /settings` to iterate on specific routes. Copy the exact wording from an existing page.\n\nState the check as what the reader sees in the browser, not as framework artifacts (\"the static shell renders real content\" was retired for this reason — a fallback is expected after a correct fix; the check is that it covers only the streamed region).\n\n### `<FixCard>` cards\n\n- Wrap all cards in a single `<FixCardGrid>` (the same component used in `docs/01-app/02-guides/instant-navigation.mdx`).\n- One `<FixCard />` per framework card, in the same order as the framework `FixCard[]` array.\n- `title` = card title from framework, **verbatim**. If it reads awkward as a heading, change the framework first — never the docs.\n- `href` = `#` + the auto-slug of the title (e.g. \"Generate on every request\" → `#generate-on-every-request`). This must match what the heading auto-generates.\n- `group` = card group from framework (`dynamic`, `cache`, `client`, `stream`, `defer`, `measure`, `block`, `render`, `ignore`, `upgrade`, `disable`, `static`).\n- `snippets` = the same `snippets` array as the matching framework `FixCard` in `instant-guidance-data.ts`. Copy it verbatim. No description prose lives on the card — the snippets carry the visual.\n- Self-close the tag (`<FixCard ... />`). The card has no children.\n- **No `prompt` prop.** The \"Copy prompt\" button builds the prompt dynamically at click time from the page URL and the card's `title` + `href`. The agent receives a prompt that points at the rule docs and names the fix — it then reads the docs page (the same one the user is on) for every constraint and code shape. That is why this skill exists: the docs page itself **is** the prompt's source of truth.\n\n### `## <Fix>` sections\n\n- Heading text = card title, verbatim. Auto-slugs to the `href` above.\n- Opens with: \"Choose this fix when `<condition>`.\"\n- `### Patterns` — one `####` per meaningfully different shape of the fix. Each has:\n  - 1–2 sentences of plain-prose framing\n  - One short, readable `jsx filename=\"app/...\"` snippet (complete, copy-paste-ready, no `...existing code...`)\n  - Optional `Learn more:` link below the snippet\n- `### Trade-off` — 1 paragraph. Mandatory. Describe the trade-off **in the context of this error**, not the generic API trade-off. If the only honest trade-off is the canonical API behavior (e.g. \"GSP requires a rebuild when the list changes\"), keep it to one sentence and link out to the API reference. Don't repeat what the API reference page already covers.\n- `### Gotchas` — bulleted list. Mandatory (at least 1 bullet).\n- Optional `### Short-lived caches` subsection for cache fixes (document the 5-minute threshold).\n\n### Code snippets\n\n- Must be valid React. Do not show unstable APIs (random, time, crypto) inline during render in a Client Component — that causes a hydration mismatch. Defer to `useEffect` + `useState` or an event handler.\n- Lazy `useState` initializers (e.g. `useState(() => someUnstableCall())`) run during SSR — warn against this in Gotchas.\n- `useRef` lazy-init pattern is valid for stable IDs (initialize in a getter function, not inline). Only applicable when the value should be computed once and frozen — not when it should reflect the current moment.\n- Always include `filename=\"app/...\"` on code blocks.\n- When a pattern defers rendering to after hydration (e.g. `useEffect`), the Trade-off must link to [Preventing flash before hydration](/docs/app/guides/preventing-flash-before-hydration).\n\n### Cross-links\n\n- Framing paragraph: link to sibling pages (client ↔ server counterpart, parallel API families).\n- Gotchas: link to the `-client` page when warning about inline render in Client Components.\n- Related Insights: the full list of every other insight-kind error page, current page omitted. This is an index of the Insight family, not a curated short list. Order: body errors → metadata/viewport → unstable-value errors (server then client) → navigation Insights. Do not add API references or guides to this section; those belong inline in the body where relevant.\n- Every API reference and file convention must be inline-linked throughout, not reserved for the Related Insights section.\n- **Cross-page pattern linking**: When a fix on one page is covered in depth on a sibling page, show only the most common pattern inline and link out to the sibling for the full set. For example, a server page's \"Render on the client\" fix shows one client pattern and links to the `-client` page; a client page's \"Other options\" section bridges to the server page's cache fix. Don't duplicate entire sections across sibling pages — keep each page lean and let the sibling be the canonical reference.\n- **First-party only**: link only to `nextjs.org/docs/*`, `react.dev/*`, `developer.mozilla.org/*`, and other canonical first-party references. **Never** link to personal blogs, community write-ups, conference talks, X/Bluesky posts, GitHub gists, or any third-party source — including the page author's own blog. If a third-party post inspired a pattern, internalize the idea and write it in our own voice without citation. Sibling error pages, our own docs, and primary API specs are the only acceptable destinations.\n\n### Terminology (verify against canonical docs)\n\n- `use cache` directive (not `\"use cache\"` in prose)\n- Cache Components (capitalized)\n- static shell (link to `/docs/app/glossary#static-shell`)\n- `instant` (not `instant`)\n- `cacheLife` / `cacheTag` / `revalidateTag` / `updateTag` — use published names exactly\n- `connection()` from `next/server`\n- Client Component / Server Component (capitalized)\n- [prerendering](/docs/app/glossary#prerendering) — always linked on first use\n\n### Allow blocking route section (canonical pattern)\n\nWhen the framework card set includes `instant = false` (group `block`), use the canonical `## Allow blocking route` section shape. All pages with this fix must match. Cross-page consistency matters — diverging from this shape produces a page that reads like an outlier.\n\n**Intro**: One paragraph explaining what setting `instant` to `false` does and what the trade-off is. Optional second paragraph noting when this is _rarely_ the right answer (for example, on client-hook or cache fixes where a Suspense boundary is almost always feasible). Phrase the rarity directly.\n\n**Patterns**: For page-body errors (runtime data, uncached data, client hooks), use both `#### Opt the page out` and `#### Opt the layout out`. For viewport errors, use only `#### Opt the layout out` (viewport always lives on a layout). Each pattern has:\n\n- 1–2 sentences of framing explaining when to use that scope\n- A `jsx filename=\"app/...\"` snippet showing the export\n- A `Learn more:` link\n\nAfter the pattern snippets, include a \"Use either pattern when:\" bulleted list (2 bullets: layout-shell-not-meaningful + incremental migration; phrase singular for viewport pages with one pattern) and a single-sentence \"Don't use this to dismiss the error. Choose [Sibling fix A](#anchor-a) or [Sibling fix B](#anchor-b) when either is feasible.\" closer.\n\n**Trade-off**: One paragraph. \"Navigations to this route are not instant. The user waits for the full server render before any HTML arrives. Use this only when that latency is the deliberate cost of the route's purpose.\"\n\n**Gotchas** (mandatory bullets, in this order):\n\n- Setting `instant` to `false` opts out only the segment that exports it. Descendant segments remain validated by their own config or the global default.\n- This export does not disable prerendering. The route still prerenders if it can. It only disables instant-navigation validation for the route.\n- Page-specific gotchas (for example, viewport pages add framework-synthesized routes gotcha) come after the two canonical bullets.\n\n**Never** add a gotcha that says `Confirm with the user that ...` in user-facing body prose. The page is what the user reads — write for them, not for the agent. Guardrails the agent should apply belong in the actual code-shape guidance under the `### Patterns` heading (which the agent reads via the docs link in the copied prompt).\n\n### Don't want this validation?\n\nEvery insight page ends (just before `## Related Insights`) with the canonical opt-out block — except the six sync-IO pages (random/current-time/crypto and their `-client` variants), which replace it with `## Why \\`instant = false\\` doesn't clear this error`, because the sync-IO abort happens in the prerender path and the opt-out cannot suppress it. It teaches the reader how to opt out of validation per-segment, subtree-wide, and app-wide, since instant-navigation validation runs by default in Cache Components apps. Copy verbatim:\n\n```mdx\n## Don't want this validation?\n\nInstant-navigation validation runs by default in [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error.\n\n- **One segment**: add [`export const instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations.\n- **Entire app**: set [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`.\n\nSee [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.\n```\n\n### Writing style\n\n- Lead each section with the answer: \"Choose this fix when ...\"\n- Sentence-case headings, no periods\n- No em-dashes for emphasis\n- No banned words: `easy`, `quick`, `simple`, `just`, `very`, `basically`, `obviously`, `utilize`, `facilitate`, `leverage`, `robust`, `seamless`, `cutting-edge`, `innovative`\n- No filler: `In this guide ...`, `As mentioned above ...`, `Let's take a look at ...`, `It's worth noting ...`\n- Active voice + direct address: \"You wrap the component\" not \"the component is wrapped\"\n- No \"Default.\" labels on patterns (removed during review — patterns don't have a default)\n- No semicolons in prose — split into two sentences, or use \", and\" for an elliptical contrast\n- Never open a paragraph or sentence with inline code — lead with a word (\"The `params` prop ...\")\n- Code in headings is fine only when it names a real API with its exact casing (`await connection()`, `cacheLife`); concepts stay prose (\"Opt the page out\")\n- `Learn more:` link text = the target page's exact title for guides (\"Streaming\", \"Ensuring instant navigations\"), the bare code name matching the doc title for API references ([`connection`], [`io`], [`searchParams`] — no parens); third-party APIs keep their canonical spelling ([`performance.now()`])\n\n## Audit checklist\n\nWhen auditing an existing page, check every item:\n\n- [ ] `title` = overlay display headline, no period, inline expressions genericized\n- [ ] `kind: insight` in frontmatter\n- [ ] No top-level Good to know; `## Verifying the fix` present with the two canonical paragraphs (observable check + `--debug-prerender` tooling)\n- [ ] All cards wrapped in a single `<FixCardGrid>`\n- [ ] One `<FixCard />` per framework card, in framework order\n- [ ] Every `<FixCard />` `title` = card title verbatim\n- [ ] Every `<FixCard />` `href` = `#` + auto-slug of the heading\n- [ ] Every `<FixCard />` `group` matches framework card group\n- [ ] Every `<FixCard />` `snippets` = the framework card's `snippets` array, verbatim\n- [ ] No `prompt` prop on any `<FixCard />` — the copy button generates the prompt from `title` + `href` + the page URL\n- [ ] `<FixCard />` is self-closing (no children, no description prose)\n- [ ] Every `## <Fix>` heading = card title verbatim\n- [ ] Every fix section has `### Patterns`, `### Trade-off`, `### Gotchas`\n- [ ] No \"Default.\" labels on patterns\n- [ ] No `Confirm with the user ...` phrasing anywhere in the page. The page is for the user; the agent reads the same page via the docs link in the copied prompt.\n- [ ] If the page has `## Allow blocking route`, it matches the canonical shape: patterns (page-body errors use both Opt the page out + Opt the layout out; viewport errors use Opt the layout out only), \"Use either pattern when\" list, \"Don't use this to dismiss the error\" closer, canonical 2-bullet Gotchas\n- [ ] Code snippets are valid React (no inline `Math.random()` during render in Client Components)\n- [ ] `useState(() => Math.random())` warned against in Gotchas\n- [ ] All API references inline-linked throughout\n- [ ] Sibling pages cross-linked in framing paragraph (inline body links carry the bulk of API references)\n- [ ] `## Don't want this validation?` present, verbatim per the canonical block (sync-IO pages instead have `## Why \\`instant = false\\` doesn't clear this error`)\n- [ ] `## Related Insights` section present, listing every other insight-kind error page (current page omitted)\n- [ ] Upstream `errors/<slug>.mdx` content preserved (relocated to Gotchas or Other options if needed)\n- [ ] Terminology matches canonical docs (verified, not assumed)\n- [ ] Vercel technical writing style applied (no banned words, active voice, sentence-case headings)\n- [ ] Framework card `link` URLs point to the correct heading auto-slugs (if not, flag as a framework follow-up)\n- [ ] Short-lived caches subsection present under cache fixes (when applicable)\n- [ ] No prose semicolons; no paragraph opens with inline code\n- [ ] `Learn more:` texts follow the title/bare-API convention and every target is the best page for the pattern\n\n## File locations\n\n- New pages: `errors/<slug>.mdx` (this repo)\n- URL: `https://nextjs.org/docs/messages/<slug>`\n- `nextjs.org` clones `errors/` from canary on every deploy (sync pipeline lives in `vercel/front`)\n- Framework cards: `packages/next/src/next-devtools/dev-overlay/components/instant/instant-guidance-data.ts`\n- Factory messages: `packages/next/src/server/app-render/sync-io-messages.ts`, `blocking-route-messages.ts`, `use-cache-messages.ts`\n\n## Reference page\n\nThe canonical reference page is `errors/blocking-prerender-random.mdx`. When writing a new page, read it first to match the exact structure, tone, and level of detail.\n", "skills/next-rspack/SKILL.md": "---\nname: next-rspack\ndescription: >\n  Maintain @next/rspack-core and @next/rspack-binding packages. Use when editing\n  rspack/package.json, rspack/crates/binding/Cargo.toml, rspack/rust-toolchain.toml,\n  or packages/next-rspack/package.json. Covers upgrading @rspack/core npm version,\n  rspack_* crate versions, Rust toolchain version, building and linking for local\n  testing, and NEXT_RSPACK environment variable usage. Does NOT apply to root\n  rust-toolchain.toml (that's for Turbopack).\nmetadata:\n  internal: true\n---\n\n# Next.js with Rspack\n\n## When to Use\n\nUse this skill when you need to:\n\n- Upgrade `@rspack/core` npm package version\n- Upgrade rspack crate dependency versions\n- Upgrade Rust version in `rspack/rust-toolchain.toml` (rspack directory only)\n- Fix Rspack-related compilation issues\n- Develop Rspack-specific features in Next.js\n\n> **⚠️ Scope Limitation**: This skill only applies to code and configuration under the `rspack/` directory. The `rust-toolchain.toml` in the repository root is for Turbopack and is outside the scope of this skill.\n\n## Architecture Overview\n\n### Package Structure\n\n```\nrspack/                          # Independent workspace (separate rust toolchain and npm releases)\n├── Cargo.toml                   # Rust workspace configuration\n├── rust-toolchain.toml          # Rust version configuration\n├── package.json                 # @next/rspack-core package definition\n├── lib/\n│   ├── index.js                 # Exports @rspack/core + custom plugins\n│   └── index.d.ts               # Type definitions\n└── crates/\n    └── binding/\n        ├── Cargo.toml           # Rust crate dependencies (rspack_* crates)\n        └── package.json         # @next/rspack-binding package definition\n\npackages/\n└── next-rspack/\n    └── package.json             # References @next/rspack-core\n```\n\n### Dependency Graph\n\n```\npackages/next-rspack\n    └── @next/rspack-core (rspack/package.json)\n            ├── @rspack/core (npm dependency)\n            └── @next/rspack-binding (rspack/crates/binding)\n                    └── rspack_* crates (Cargo.toml dependencies)\n```\n\n### Version Mapping Rules\n\n| @rspack/core npm version | rspack crate version | Notes                                             |\n| ------------------------ | -------------------- | ------------------------------------------------- |\n| `2.0.0-rc.0`             | `0.100.0-rc.0`       | npm major.minor maps to crate 0.(major\\*50+minor) |\n| `1.3.x`                  | `0.53.x`             | e.g., 1.3 → 0.53                                  |\n| `1.2.x`                  | `0.52.x`             | e.g., 1.2 → 0.52                                  |\n\n## Upgrade Process\n\n### Step 1: Get Upstream Version Information\n\nQuery https://github.com/web-infra-dev/rspack to obtain:\n\n- Target `@rspack/core` npm version\n- Corresponding rspack crate version\n- Rust channel version from `rust-toolchain.toml`\n\n### Step 2: Update npm Dependencies\n\nEdit `rspack/package.json`:\n\n```json\n{\n  \"dependencies\": {\n    \"@rspack/core\": \"<new version>\",\n    \"@next/rspack-binding\": \"workspace:*\"\n  }\n}\n```\n\n### Step 3: Update Cargo.toml\n\nEdit `rspack/crates/binding/Cargo.toml`, update all rspack crate versions:\n\n```toml\n[dependencies]\nrspack_binding_builder        = { version = \"=<new crate version>\" }\nrspack_binding_builder_macros = { version = \"=<new crate version>\" }\nrspack_core                   = { version = \"=<new crate version>\" }\nrspack_error                  = { version = \"=<new crate version>\" }\nrspack_hook                   = { version = \"=<new crate version>\" }\nrspack_plugin_externals       = { version = \"=<new crate version>\" }\nrspack_regex                  = { version = \"=<new crate version>\" }\n# rspack_sources version is managed separately, may not follow the main version\n\n[target.'cfg(...)'.dependencies]\nrspack_binding_builder = { version = \"=<new crate version>\", features = [\"plugin\"] }\n\n[build-dependencies]\nrspack_binding_build = { version = \"=<new crate version>\" }\n```\n\n### Step 4: Update Rust Toolchain\n\nEdit `rspack/rust-toolchain.toml`:\n\n```toml\n[toolchain]\nprofile = \"default\"\ncomponents = [\"rust-src\"]\nchannel = \"<nightly version matching upstream rspack>\"\n```\n\n### Step 5: Verify Build\n\n```bash\n# Execute in rspack directory\ncd rspack\n\n# Check Rust code\ncargo check\n\n# Build binding (requires Rust installed)\npnpm build\n```\n\n### Step 6: Link to packages/next-rspack\n\n`rspack/` is an independent workspace not included in the root pnpm-workspace, manual linking is required:\n\n```bash\n# Execute from repository root\ncd packages/next-rspack\n\n# Link locally built @next/rspack-core\npnpm link ../../rspack\n```\n\nOr modify `packages/next-rspack/package.json` to use local path (for local testing only, do not commit):\n\n```json\n{\n  \"dependencies\": {\n    \"@next/rspack-core\": \"link:../../rspack\"\n  }\n}\n```\n\n> **Important**: After linking, run `pnpm install` in the root directory to update dependency relationships.\n\n### Step 7: Run Tests\n\n```bash\n# Execute from repository root\npnpm test-rspack\n```\n\n## Key Files Checklist\n\nFiles to check/modify during upgrade:\n\n| File Path                            | Modification                                                                          |\n| ------------------------------------ | ------------------------------------------------------------------------------------- |\n| `rspack/package.json`                | `@rspack/core` version, package version                                               |\n| `rspack/crates/binding/Cargo.toml`   | rspack\\_\\* crate versions                                                             |\n| `rspack/crates/binding/package.json` | binding package version                                                               |\n| `rspack/rust-toolchain.toml`         | Rust nightly version                                                                  |\n| `packages/next-rspack/package.json`  | `@next/rspack-core` version reference (update on release, use link for local testing) |\n\n## Pre-requisites for Local Testing\n\nBefore running `pnpm test-rspack`, you must build and link `@next/rspack-core`:\n\n```bash\n# 1. Build @next/rspack-core\ncd rspack\npnpm install\npnpm build\n\n# 2. Link to packages/next-rspack\ncd ../packages/next-rspack\npnpm link ../../rspack\n\n# 3. Return to root and update dependencies\ncd ../..\npnpm install\n\n# 4. Run tests\npnpm test-rspack\n```\n\n> **Note**: After modifying Rust code under `rspack/`, you need to re-run `pnpm build` from step 1.\n\n## Test Commands\n\n```bash\n# Full test suite (using Rspack compiler)\npnpm test-rspack\n\n# Development mode tests\npnpm test-dev-rspack\n\n# Production mode tests\npnpm test-start-rspack\n\n# Run specific tests only\npnpm run with-rspack pnpm testonly -- <test-pattern>\n```\n\nAll test commands set environment variables via `with-rspack`:\n\n```bash\ncross-env NEXT_RSPACK=1 NEXT_TEST_USE_RSPACK=1\n```\n\n## Development Notes\n\n### Environment Variable Differentiation\n\nUse the `NEXT_RSPACK` environment variable to differentiate compilers in `packages/next/` code:\n\n```typescript\n// Check if using Rspack\nconst isRspack = Boolean(process.env.NEXT_RSPACK)\n\nif (process.env.NEXT_RSPACK) {\n  // Rspack-specific logic\n} else {\n  // Webpack logic\n}\n```\n\n### Common Code Locations\n\n- Compiler selection logic: `packages/next/src/lib/bundler.ts`\n- Webpack configuration: `packages/next/src/build/webpack-config.ts`\n- Loader adaptations: `packages/next/src/build/webpack/loaders/`\n\n### Custom Plugins\n\n`@next/rspack-core` exports = `@rspack/core` + custom plugins:\n\n- `NextExternalsPlugin` - externals handling plugin implemented in Rust\n\n## Release Process\n\nRelease via GitHub Actions workflow:\n\n- Workflow: `.github/workflows/release-next-rspack.yml`\n- Supports dry-run mode\n- Supports multiple npm tags (latest, alpha, beta, canary)\n\n## References\n\n- Upstream Rspack repository: https://github.com/web-infra-dev/rspack\n- Rspack documentation: https://rspack.rs\n- Next.js with Rspack example: `examples/with-rspack/`\n", "skills/pr-status-triage/SKILL.md": "---\nname: pr-status-triage\ndescription: >\n  Triage CI failures and PR review comments using scripts/pr-status.js.\n  Use when investigating failing CI jobs, flaky tests, or PR review feedback.\n  Covers blocker-first prioritization (build > lint > types > tests),\n  CI env var matching for local reproduction, the Known Flaky Tests\n  distinction, and reading CI by hand: retry-tests attempts, paginated job\n  lists, docs-only runs, cancelled shards, and external failures.\nmetadata:\n  internal: true\n---\n\n# PR Status Triage\n\nUse this skill when the user asks about PR status, CI failures, or review comments in the Next.js monorepo.\n\n## Workflow\n\nStart by fetching data to answer the user's query:\n\n- For a targeted question about specific review comments, run `node scripts/pr-status.js [PR] --comments-only`. This skips all Actions run, job, log, and flaky-test requests.\n- For CI status or general triage, run `node scripts/pr-status.js [PR]` (no `--wait`) to snapshot the current state, then start triaging immediately from the jobs that have already finished. Re-fetch on demand as more results land instead of waiting for the whole workflow to complete.\n- Use `--wait` only when the final run state itself is what you need: confirming an all-green run before handing back, or picking up results after retriggering failed jobs.\n\nThen:\n\n1. Read `scripts/pr-status/results/index.md`.\n2. For a targeted review question, inspect the relevant `thread-{N}.md`, `review-{id}.md`, or `comment-{id}.md` files. For full triage, also analyze each `job-{id}.md` and review file for failures and feedback.\n3. Prioritize blocking jobs first: build, lint, types, then test jobs.\n4. Treat failures as real until disproven; check the \"Known Flaky Tests\" section before calling anything flaky. For base, step, attempt, and log details, use [ci-reading.md](./ci-reading.md).\n5. Reproduce test failures locally with the same mode and environment as CI (e.g. dev or start, webpack or turbopack).\n6. After addressing review comments, reply to the thread describing what was done, then resolve it. Use `reply-and-resolve-thread` to do both in one step, or use `reply-thread` + `resolve-thread` separately. See `scripts/pr-status/results/thread-N.md` files for ready-to-use commands.\n7. When the only remaining failures are known flaky tests and no code changes are needed, wait for the workflow run to finish, then retrigger the failing CI jobs with `gh run rerun <run-id> --failed`. Then re-run the analysis with `--wait` to pick up the rerun results and go back to step 1. Repeat this loop up to 5 times.\n8. Start fixing as results come in; do not wait for the whole workflow before beginning on failures that have already reported. A push, on the other hand, should wait for the workflow to complete.\n\n## CI Analysis Tips\n\n- Prioritize CI failures over review comments.\n- Prioritize blocking jobs first: build, lint, types, then test jobs.\n- Common fast checks:\n  - `rust check / build` → Run `cargo fmt -- --check`, then `cargo fmt`\n  - `lint / build` → Run `pnpm prettier --write <file>` for prettier errors\n  - test failures → Run the specific failing test path locally\n\nRun tests in the mode (e.g.):\n\n```bash\n# Development mode with Turbopack\npnpm test-dev-turbo test/path/to/test.ts\n\n# Production build and start with Webpack\npnpm test-start-webpack test/path/to/test.ts\n```\n\n## Quick Commands\n\n```bash\nnode scripts/pr-status.js                  # current branch PR\nnode scripts/pr-status.js <number>         # specific PR\nnode scripts/pr-status.js [PR] --wait      # waits for the run to finish, then re-analyzes (final confirmation or after reruns)\nnode scripts/pr-status.js [PR] --comments-only  # reviews/comments only; skips CI jobs\nnode scripts/pr-status.js --skip-flaky-check  # skip flaky test detection\n```\n\nThread interaction:\n\n```bash\nnode scripts/pr-status.js reply-thread <threadNodeId> \"<body>\"           # reply to a review thread\nnode scripts/pr-status.js resolve-thread <threadNodeId>                  # resolve a review thread\nnode scripts/pr-status.js reply-and-resolve-thread <threadNodeId> \"<body>\"  # reply and resolve in one step\n```\n\n## References\n\n- [workflow.md](./workflow.md) — prioritization, common failure patterns, resolving review threads\n- [local-repro.md](./local-repro.md) — mode/env matching and isolation guidance\n- [ci-reading.md](./ci-reading.md) — reading CI without the script: failing steps, cancelled shards, canary noise, run attempts, docs-only runs, job pagination, job logs, flake detection\n", "skills/pr-status-triage/ci-reading.md": "# Reading Next.js CI Directly\n\nUse this when `scripts/pr-status.js` does not answer the question: earlier\ncanary attempts, a red job whose cause is unclear, or green runs that may hide\nflakes.\n\n## Classify the failure\n\n- **`thank you, next`** (`build-and-test`) and **`thank you, build`**\n  (`build-and-deploy`) aggregate their `needs:` jobs. When one fails, look at\n  the failed or cancelled job underneath.\n- **Don't classify a job by its name suffix.** Matrix entries call reusable\n  workflows, so `test prod (6/10, 18.3.1) / build` ends in `/ build` even when\n  its test step failed. Read the failing step:\n\n  ```bash\n  gh api repos/vercel/next.js/actions/jobs/<job-id> \\\n    --jq '.steps[] | select(.conclusion==\"failure\") | \"\\(.number) \\(.name)\"'\n  ```\n\n- **For a cancelled shard, read the log before rerunning.** A stalled test can\n  run into the job timeout, but the log can also contain assertion failures.\n  Compare `Starting <file> retry N/2` with `<file> finished on retry N/2` to\n  find work still running at cancellation. Check-run annotations\n  (`gh api repos/vercel/next.js/check-runs/<id>/annotations`) can show the\n  timeout.\n- **Treat `skipped` as conditional, not broken.** Read the job's `if:` and\n  `needs:` before concluding anything. `retry_test.yml`, for example,\n  deliberately skips its report job before the third attempt.\n- Compare failures by test file. Shards are rebalanced by timing.\n\n## Check base and infrastructure causes\n\n1. **Compare with the base.** PR CI runs on `refs/pull/N/merge`, so a newer\n   canary can affect the result. Check canary's check runs and logs at the\n   exact base SHA. An error in a file the PR didn't change can still come from\n   the PR's callers, dependencies, configuration, or tests, so compare\n   signatures and reproduce at the base when it matters. Rebase only after the\n   base is fixed.\n2. **Recognize common external failures, then still read the log:**\n   - `ERR_PNPM_NO_MATURE_MATCHING_VERSION ... minimumReleaseAge`: an install\n     selected a version that is newer than `minimumReleaseAge` in\n     `pnpm-workspace.yaml`.\n   - Many unrelated jobs failing quickly with `curl: (22) ... 504` while\n     downloading tools.\n   - A `startup_failure` with no jobs.\n   - `Wait for preview tarball` timing out. It gates the deploy-test matrix.\n3. **`PR Stack CI Gate`** can skip a stacked PR's matrix while predecessor PRs\n   are red. The skipped jobs are not passing evidence. Don't apply the bypass\n   label without the owner's decision.\n4. If every assertion passed but `afterAll` timed out, report it as a teardown\n   failure.\n\n## Rerun safely\n\n- Wait until the workflow run completes. GitHub refuses some rerun requests\n  while the run is active.\n- Rerun only failed jobs: `gh run rerun <run-id> --failed`.\n- Follow the rerun limit in `SKILL.md` step 7 when the failure appears\n  unrelated.\n- A green rerun on the same SHA shows the failure is intermittent; it does not\n  prove the change is unrelated. A repeated identical failure is strong\n  evidence of a persistent problem, so investigate it instead of rerunning.\n\n## Canary attempts\n\n`.github/workflows/retry_test.yml` (`retry-tests`) handles completed\n`build-and-test` and `build-and-deploy` runs on `canary`. When the required job\ndid not succeed and `run_attempt < 3`, it reruns the failed jobs in the same\nrun, which increments `run_attempt`.\n\n- A final green run with `run_attempt >= 2` had at least one earlier red\n  attempt. Read each attempt with\n  `GET /repos/vercel/next.js/actions/runs/<id>/attempts/<n>/jobs`. The plain\n  run jobs endpoint and `pr-status.js` describe the latest attempt.\n- A 404 for `/attempts/<n>/jobs` means that attempt doesn't exist.\n- Reruns create new job IDs, and passing jobs can be copied into the next\n  attempt. Use `run_attempt == 1` entries when counting first executions.\n- `retry-tests` runs are `workflow_run` runs, so their `head_sha` can differ\n  from the run they retried. The log names the target:\n  `Using conclusion 'failure' from .../runs/<run-id>/job/<job-id>`.\n- A commit can have several workflow runs and check suites. Name the workflow\n  (for example `build-and-test`) when reporting a result.\n- Re-read `run_attempt` before reporting; it changes while retries run.\n\n## Docs-only runs\n\n`build_and_test.yml`'s `Determine changes` job sets `docs-only`. When it is\ntrue, test jobs are skipped, but the workflow can still succeed.\n\n- Unexpanded names like `test dev` usually indicate a skipped matrix job.\n  Expanded names like `test prod (9/10, 18.3.1) / build` indicate it ran.\n- Markdown-only changes are not automatically `docs-only`; check the gate.\n- A docs-only success is not evidence that a flaky test passed.\n\n## Listing jobs and checks\n\nLarge runs have more than 100 jobs, so a single page can look complete.\n\n```bash\ngh api \"repos/vercel/next.js/actions/runs/<run-id>/attempts/<n>/jobs?per_page=30\" --paginate \\\n  --jq '.jobs[] | select((.conclusion // \"running\") | test(\"failure|timed_out|cancelled\")) | {name, id, conclusion}'\ngh api \"repos/vercel/next.js/actions/runs/<run-id>/attempts/<n>/jobs?per_page=1\" --jq .total_count\n```\n\n- Trust counts only when the unique listed jobs match `total_count`.\n- Retry 5xx responses and never count an error body as job data. Smaller pages\n  are useful when large pages fail.\n- For every attempt of one check:\n\n  ```bash\n  gh api -X GET repos/vercel/next.js/commits/<sha>/check-runs \\\n    -f check_name=\"<exact job name>\" -f filter=all -f per_page=100 --paginate\n  ```\n\n## Reading logs\n\n```bash\ngh api --allow-escape-sequences repos/vercel/next.js/actions/jobs/<job-id>/logs \\\n  | sed 's/\\x1b\\[[0-9;]*m//g' > /tmp/job-<job-id>.log\n```\n\n- `gh` 2.97 and later refuses to print job logs, which contain ANSI escape\n  sequences, unless you pass `--allow-escape-sequences`. Older `gh` fails on\n  the flag as unknown, so drop it there (`scripts/pr-status.js` checks\n  `gh api --help` for the same reason). Check the file contents before\n  treating a grep miss as evidence.\n- The jobs endpoint can return a completed job's log while other jobs in the\n  run are still active.\n- Useful markers:\n  - `Starting <file> retry N/2`\n  - `finished on retry N/2`\n  - `failed to pass within 2 retries`\n  - ` ●`\n  - `FAIL `\n- Each failed file prints one large `--test output start-- ... --test output end--`\n  line. Exclude it before printing matches:\n  `grep -v -- '--test output start--'`.\n- `run-tests.js` retries each test file twice in a job. Search green logs for\n  `finished on retry` and `failed to pass within` when looking for flakes.\n- A `next dev exited ... signal 139` line is a real dev-server failure, even if\n  a later retry passes.\n\n## Flake detection\n\n`Test new and changed tests for flakes (dev|prod)` runs added or changed test\nfiles three times concurrently with `--retries 0`\n(`scripts/test-new-tests.mjs --flake-detection`). Existing tests in those\nfiles run too. For local test setup and repeat commands, see\n`contributing/core/testing.md`.\n\n## Reporting\n\n- Name the run, attempt, commit SHA, workflow, job, step, and test file.\n- Separate observed facts from inferences.\n- Report raw counts and the scanned window, not rates or \"never\" from a small\n  sample.\n\n## `pr-status.js` output\n\n- `scripts/pr-status.js` writes generated files to `scripts/pr-status/results/`\n  and `scripts/pr-status/intermediate/`. They are gitignored, but root Prettier\n  can still check them. Remove them before `pnpm prettier-check` or `pnpm lint`.\n- It has no `--help` mode. Read the argument parsing before passing an unknown\n  option.\n", "skills/pr-status-triage/local-repro.md": "# Local Reproduction Guide\n\n## Match CI Job Mode\n\n- Dev-mode failures: use `pnpm test-dev-turbo` or `pnpm test-dev-webpack` based on job mode.\n- Start-mode failures: use `pnpm test-start-turbo` or `pnpm test-start-webpack`.\n\n## Match CI Environment Variables\n\nRead the \"Job Environment Variables\" section in `index.md` and mirror them locally. Key variables:\n\n- `IS_WEBPACK_TEST=1` — forces webpack mode (turbopack is default locally).\n- `NEXT_SKIP_ISOLATE=1` — skips package isolation; **never use** when verifying module resolution or build-time compilation fixes.\n- Feature flags like `__NEXT_USE_NODE_STREAMS=true`, `__NEXT_CACHE_COMPONENTS=true` change DefinePlugin replacements.\n\nExample: a failure in \"test node streams prod\" needs:\n\n```bash\nIS_WEBPACK_TEST=1 __NEXT_USE_NODE_STREAMS=true __NEXT_CACHE_COMPONENTS=true NEXT_TEST_MODE=start\n```\n\n## Isolation Rule\n\nWhen validating module-resolution, entrypoint-export, or internal require-path fixes, rerun without `NEXT_SKIP_ISOLATE=1`.\n\n## One-Run Log Analysis\n\nCapture once, analyze multiple times:\n\n```bash\nHEADLESS=true pnpm test-dev-turbo test/path/to/test.ts > /tmp/test-output.log 2>&1\ngrep \"●\" /tmp/test-output.log\ngrep -A5 \"Error:\" /tmp/test-output.log\ntail -5 /tmp/test-output.log\n```\n", "skills/pr-status-triage/workflow.md": "# CI Triage Workflow\n\n## Prioritization Order\n\n1. Build failures\n2. Lint failures\n3. Type failures\n4. Test failures\n5. Review comments (after CI blockers)\n\n## Failure Handling Rules\n\n- Investigate each failing job as if it is caused by the current changes.\n- Do not assume flakiness by default.\n- If the job output has a \"Known Flaky Tests\" section, use it as historical context, not as automatic dismissal.\n\n## Common Patterns\n\n- `rust check / build`:\n  - Run `cargo fmt -- --check`\n  - Fix with `cargo fmt`\n- `lint / build`:\n  - Run `pnpm prettier --write <file>`\n  - Run the repo lint command if needed\n- test failures:\n  - Run the exact failing test file locally\n  - Match dev vs start mode to the CI job\n\n## Resolving Review Threads\n\nAfter addressing a review comment (e.g., making the requested code change), or when you detect the current code already addresses it:\n\n1. Reply to the thread describing what action was taken:\n   ```bash\n   node scripts/pr-status.js reply-thread <threadNodeId> \"Done -- <description of changes>\"\n   ```\n2. Then resolve the thread:\n   ```bash\n   node scripts/pr-status.js resolve-thread <threadNodeId>\n   ```\n\nOr do both in one step:\n\n```bash\nnode scripts/pr-status.js reply-and-resolve-thread <threadNodeId> \"Done -- <description of changes>\"\n```\n\nThe ready-to-use commands with the correct thread IDs are at the bottom of each `thread-N.md` file in `scripts/pr-status/results/`.\n\n**Important:** Always reply with a description of the actions taken before resolving. This gives the reviewer context about what changed.\n", "skills/react-sync/SKILL.md": "---\nname: react-sync\ndescription: >\n  Build local React changes in the bundle variants consumed by Next.js, sync\n  them into a local Next.js checkout, and test the resulting integration. Use\n  when working on React changes that need validation in Next.js, or when asked\n  to run buildForNext, pnpm sync-react, or synchronize a React checkout with\n  Next.js.\nmetadata:\n  internal: true\n---\n\n# Sync React to Next.js\n\nUse this skill when syncing a local React checkout into this Next.js checkout.\n\n## Build and sync\n\n1. Build React from its own checkout. Pass this skill's script by its absolute\n   path, because the working directory must be the React repository.\n\n   ```bash\n   cd <react-repo>\n   bash <next-repo>/.agents/skills/react-sync/scripts/build-for-next.sh\n   ```\n\n   This creates `build/oss-stable` and `build/oss-experimental` with the\n   bundle variants that Next.js consumes.\n\n2. Sync the build into Next.js:\n\n   ```bash\n   cd <next-repo>\n   PATH=\"$(dirname \"$(command -v corepack)\"):$PATH\" \\\n     pnpm sync-react --version <react-repo>\n   ```\n\n   Work around a Codex `PATH`-precedence bug by keeping the directory containing\n   the active Corepack shim first on `PATH`. Codex injects a separate bundled\n   `pnpm` executable ahead of the user's Corepack shim, and command lookup\n   happens before Corepack reads the repository's `packageManager` field. The\n   prefix makes both this command and `sync-react`'s nested `pnpm install`\n   resolve through Corepack to the repository-pinned pnpm version. Invoking\n   only the outer command with `corepack pnpm` is insufficient because the\n   nested command still resolves `pnpm` from `PATH`.\n\n3. Inspect the sync result before testing. Preserve unrelated changes in both\n   checkouts. Rebuild Next.js when required, then run the focused test command\n   matching the changed behavior.\n\n## Related Skills\n\n- `$react-vendoring` - vendored React runtime and type boundaries after syncing.\n", "skills/react-sync/scripts/build-for-next.sh": "#!/usr/bin/env bash\nset -euo pipefail\nset -x\n\nbundles=(\n  \"react/index\"\n  \"react/jsx\"\n  \"react-jsx-runtime.react-server\"\n  \"react-jsx-dev-runtime.react-server\"\n  \"react/compiler-runtime\"\n  \"react.react-server\"\n  \"react-dom/index\"\n  \"react-dom/client\"\n  \"react-dom/profiling\"\n  \"react-dom/server\"\n  \"react-dom.react-server\"\n  \"react-dom-server.browser\"\n  \"react-dom-server.bun\"\n  \"react-dom-server.edge\"\n  \"react-dom-server.node\"\n  \"react-dom-server-legacy.browser\"\n  \"react-dom-server-legacy.node\"\n  \"react-is\"\n  \"scheduler\"\n  \"react-server-dom-webpack/\"\n  \"react-server-dom-turbopack/\"\n)\n\ntype=\"BUN_DEV,BUN_PROD,NODE_DEV,NODE_PROD,NODE_PROFILING,ESM_DEV,ESM_PROD,NODE_ES2015\"\n\nRELEASE_CHANNEL=stable node ./scripts/rollup/build.js \"${bundles[@]}\" --type=\"$type\"\nmv ./build/node_modules ./build/oss-stable\n\nRELEASE_CHANNEL=experimental node ./scripts/rollup/build.js \"${bundles[@]}\" --type=\"$type\" --unsafe-partial\nmv ./build/node_modules ./build/oss-experimental\n", "skills/react-vendoring/SKILL.md": "---\nname: react-vendoring\ndescription: >\n  React vendoring and react-server layer boundaries. Use when editing\n  entry-base.ts, $$compiled.internal.d.ts, compiled/react* packages,\n  or taskfile.js copy_vendor_react. Covers the entry-base.ts boundary\n  (all react-server-dom-webpack/* imports must go through it), vendored\n  React channels, type declarations, Turbopack remap to\n  react-server-dom-turbopack, ComponentMod access patterns, and ESLint\n  suppression for guarded requires.\nmetadata:\n  internal: true\n---\n\n# React Vendoring\n\nUse this skill for changes touching vendored React, `react-server-dom-webpack/*`, or react-server layer boundaries.\n\n## App Router Vendoring\n\nReact is NOT resolved from `node_modules` for App Router. It's vendored into `packages/next/src/compiled/` during `pnpm build` (task: `copy_vendor_react()` in `taskfile.js`). Pages Router resolves React from `node_modules` normally.\n\n- **Two channels**: stable (`compiled/react/`) and experimental (`compiled/react-experimental/`). The runtime bundle webpack config aliases to the correct channel via `makeAppAliases({ experimental })`.\n\n## `entry-base.ts` Boundary\n\nOnly `entry-base.ts` is compiled in rspack's `(react-server)` layer. ALL imports from `react-server-dom-webpack/*` (Flight server/static APIs) must go through `entry-base.ts`. Other files like `stream-ops.node.ts` or `app-render.tsx` must access Flight APIs via the `ComponentMod` parameter (which is the `entry-base.ts` module exposed through the `app-page.ts` build template).\n\nDirect imports from `react-server-dom-webpack/server.node` or `react-server-dom-webpack/static` in files outside `entry-base.ts` will fail at runtime with \"The react-server condition must be enabled\". Dev mode may mask this error, but production workers fail immediately.\n\n## Type Declarations\n\n`packages/next/types/$$compiled.internal.d.ts` contains `declare module` blocks for vendored React packages. When adding new APIs (e.g. `renderToPipeableStream`, `prerenderToNodeStream`), you must add type declarations here. The bare specifier types (e.g. `declare module 'react-server-dom-webpack/server'`) are what source code in `src/` imports against.\n\n## Adding Node.js-Only React APIs\n\nThese exist in `.node` builds but not in the type definitions. Steps:\n\n1. Add type declarations to `$$compiled.internal.d.ts`.\n2. Export the API from `entry-base.ts` behind a `process.env` guard.\n3. Access it via `ComponentMod` in other files.\n\n```typescript\n// In entry-base.ts (react-server layer) only:\n/* eslint-disable import/no-extraneous-dependencies */\nexport let renderToPipeableStream: ... | undefined\nif (process.env.__NEXT_USE_NODE_STREAMS) {\n  renderToPipeableStream = (\n    require('react-server-dom-webpack/server.node') as typeof import('react-server-dom-webpack/server.node')\n  ).renderToPipeableStream\n} else {\n  renderToPipeableStream = undefined\n}\n/* eslint-enable import/no-extraneous-dependencies */\n\n// In other files, access via ComponentMod:\nComponentMod.renderToPipeableStream!(payload, clientModules, opts)\n```\n\n## ESLint Practical Rule\n\nFor guarded runtime `require()` blocks that need `import/no-extraneous-dependencies` suppression, prefer scoped block disable/enable. If using `eslint-disable-next-line`, the comment must be on the line immediately before the `require()` call, NOT before the `const` declaration. When the `const` and `require()` are on different lines, this is error-prone.\n\n## Turbopack Remap\n\n`react-server-dom-webpack/*` is silently remapped to `react-server-dom-turbopack/*` by Turbopack's import map. Code says \"webpack\" everywhere, but Turbopack gets its own bindings at runtime. This affects debugging: stack traces and error messages will reference the turbopack variant.\n\n## Related Skills\n\n- `$flags` - flag wiring (config/schema/define-env/runtime env)\n- `$dce-edge` - DCE-safe require patterns and edge constraints\n- `$runtime-debug` - reproduction and verification workflow\n", "skills/rebase-pr/SKILL.md": "---\nname: rebase-pr\ndescription: >\n  Rebase a Next.js PR onto the latest canary, or restack dependent PRs after a\n  lower layer changes. Use when a PR conflicts with canary, when asked to\n  rebase, restack, or update a branch, when CI fails after a rebase, or when\n  using gh stack in vercel/next.js. Covers fetching canary in shallow clones,\n  checking that canary is healthy, git rebase --onto, safe force-with-lease\n  pushes, tree and ancestry checks, lockfiles, lint, snapshots, and gh stack\n  behavior in this repository.\nmetadata:\n  internal: true\n---\n\n# Rebase PR\n\nUse this skill when moving a Next.js PR, or a stack of PRs, onto a newer base.\nPrefer rebase over merge. Keep the PR's draft state unchanged. For general\n`gh stack` commands, see `$gh-stack`.\n\n## Before rebasing\n\n1. Check the current worktree. Don't rebase over unrelated local changes.\n2. Fetch the base with an explicit forced refspec:\n\n   ```bash\n   git fetch origin +refs/heads/canary:refs/remotes/origin/canary\n   ```\n\n3. In a shallow clone, deepen until Git finds a merge base:\n\n   ```bash\n   git fetch --deepen=200 origin +refs/heads/canary:refs/remotes/origin/canary\n   git merge-base HEAD origin/canary\n   ```\n\n   Without a merge base, Git can replay unrelated history and report many\n   add/add conflicts. Abort and deepen instead of resolving them.\n\n4. Check canary's own CI at the base commit. If canary is broken in the same\n   area, wait for a fix instead of pushing a rebase that can only fail.\n5. Review new canary commits in the PR's area:\n   `git log <old-base>..origin/canary -- <paths>`. If an equivalent change\n   already landed, stop and discuss the new scope with the PR owner.\n\n## Rebase\n\n- Run `git rebase origin/canary`, or use `--onto` for a known old base.\n- List all conflicts before classifying them:\n  `git diff --name-only --diff-filter=U`. Generated files can hide source\n  conflicts in truncated output.\n- Resolve conflicts by preserving both intents. Search canary for new callers of\n  APIs the PR removes or renames.\n- A squash-style rebase rewrites the PR's commit history. Only use it with the\n  PR owner's approval and with a backup branch of the old head.\n- Re-fetch canary immediately before pushing. If it moved, ask the PR owner\n  whether to repeat the rebase. Usually it isn't needed, and repeating it\n  automatically can loop.\n\n## Verify\n\nA clean text rebase can still fail CI:\n\n- Run ESLint and TypeScript for changed files, plus the commands for the\n  affected package. New canary lint rules can apply to old PR code.\n- Compile changed Rust or TypeScript call sites.\n- Run tests and snapshots that canary added since the PR's old base. In\n  Turbopack, run the relevant full snapshot suite, not only PR-specific\n  fixtures.\n- After any `package.json` change, update `pnpm-lock.yaml` and run\n  `pnpm install --frozen-lockfile`. `--lockfile-only` does not populate\n  `node_modules`. Revert unrelated lockfile rewrites.\n- Don't commit unrelated generated output from a native rebuild.\n- If CI fails after the rebase, use `$pr-status-triage` to compare with canary\n  before changing code.\n\n## Push safely\n\n- Pin `--force-with-lease` to the exact remote SHA you inspected:\n\n  ```bash\n  git push --force-with-lease=refs/heads/<branch>:<old-remote-sha> origin <branch>\n  ```\n\n- If the remote moved, stop and inspect it. Never overwrite another person's\n  commits without asking.\n- After pushing, check the PR's head SHA, base, draft state, and mergeability.\n\n## Restack dependent PRs\n\nIf the PRs form a `gh stack`, restack with `gh stack rebase --upstack` (or\n`gh stack sync`). See `$gh-stack` for conflict handling. Afterwards, still check\neach layer as in steps 4, 5 and 7 below.\n\nOtherwise, or if the tool fails, restack by hand. Work bottom-up and push one\nbranch at a time:\n\n1. Commit each change on the layer that owns it. Use history or blame when\n   ownership is unclear.\n2. Push the lower branch, then fetch its exact remote tip.\n3. Rebase the child onto that tip:\n   `git rebase --onto <new-parent-tip> <old-parent-tip> <child>`.\n4. Check that the child's own changes are unchanged with `git range-diff`.\n5. Run formatting, lint, and focused checks on every layer. A mistake in a\n   middle layer can fail every layer above it.\n6. Push the child with an exact lease. Repeat upward.\n7. Verify `git merge-base --is-ancestor <parent> <child>` for remote heads and\n   check each PR's mergeability.\n\n## `gh stack` in vercel/next.js\n\n- `gh stack link` needs read access to the repository's PRs and stacks because\n  it lists stacks first. Linking is optional. A PR whose base is its parent\n  branch already shows the stacked diff.\n- `gh stack link` appends PRs to the top of an existing stack.\n- GitHub can refuse to change the base of a PR that belongs to a stack. Omit\n  `base` when updating only the body.\n- `gh stack submit --auto` can warn that it could not create a GitHub stack\n  while still creating dependent PRs. Check every PR's base and draft state.\n- `gh stack view --json` can lag behind real refs. Confirm with\n  `git rev-parse` and `git merge-base`.\n- `PR Stack CI Gate` can skip a stacked PR's tests while predecessor PRs are\n  red. See `$pr-status-triage`.\n\n## Related Skills\n\n- `$gh-stack` - general stacked-PR commands\n- `$create-pr` - branch, commit, and PR creation\n- `$pr-status-triage` - CI failures after a rebase\n", "skills/router-act/SKILL.md": "---\nname: router-act\ndescription: >\n  How to write end-to-end tests using createRouterAct and LinkAccordion.\n  Use when writing or modifying tests that need to control the timing of\n  internal Next.js requests (like prefetches) or assert on their responses.\n  Covers the act API, fixture patterns, prefetch control via LinkAccordion,\n  fake clocks, and avoiding flaky testing patterns.\nuser-invocable: false\nmetadata:\n  internal: true\n---\n\n# Router Act Testing\n\nUse this skill when writing or modifying tests that involve prefetch requests, client router navigations, or the segment cache. The `createRouterAct` utility from `test/lib/router-act.ts` lets you assert on prefetch and navigation responses in an end-to-end way without coupling to the exact number of requests or the protocol details. This is why most client router-related tests use this pattern.\n\n## When NOT to Use `act`\n\nDon't bother with `act` if you don't need to instrument the network responses — either to control their timing or to assert on what's included in them. If all you're doing is waiting for some part of the UI to appear after a navigation, regular Playwright helpers like `browser.elementById()`, `browser.elementByCss()`, and `browser.waitForElementByCss()` are sufficient.\n\n## Core Principles\n\n1. **Use `LinkAccordion` to control when prefetches happen.** Never let links be visible outside an `act` scope.\n2. **Prefer `'no-requests'`** whenever the data should be served from cache. This is the strongest assertion — it proves the cache is working.\n3. **Avoid retry/polling timers.** The `act` utility exists specifically to replace inherently flaky patterns like `retry()` loops or `setTimeout` waits for network activity. If you find yourself wanting to poll, you're probably not using `act` correctly.\n4. **Avoid the `block` feature.** It's prone to false negatives. Prefer `includes` and `'no-requests'` assertions instead.\n\n## Act API\n\n### Config Options\n\n```typescript\n// Assert NO router requests are made (data served from cache).\n// Prefer this whenever possible — it's the strongest assertion.\nawait act(async () => { ... }, 'no-requests')\n\n// Expect at least one response containing this substring\nawait act(async () => { ... }, { includes: 'Page content' })\n\n// Expect multiple responses (checked in order)\nawait act(async () => { ... }, [\n  { includes: 'First response' },\n  { includes: 'Second response' },\n])\n\n// Assert the same content appears in two separate responses\nawait act(async () => { ... }, [\n  { includes: 'Repeated content' },\n  { includes: 'Repeated content' },\n])\n\n// Expect at least one request, don't assert on content\nawait act(async () => { ... })\n```\n\n### How `includes` Matching Works\n\n- The `includes` substring is matched against the HTTP response body. Use text content that appears literally in the rendered output (e.g. `'Dynamic content (stale time 60s)'`).\n- Extra responses that don't match any `includes` assertion are silently ignored — you only need to assert on the responses you care about. This keeps tests decoupled from the exact number of requests the router makes.\n- Each `includes` expectation claims exactly one response. If the same substring appears in N separate responses, provide N separate `{ includes: '...' }` entries.\n\n### App Shell requests are ignored by default\n\nWhen App Shells are enabled (the default when Cache Components is on), a `prefetch` is split into two phases: an **App Shell** prefetch — the param/searchParam-independent chrome of the route (layouts, loading boundaries, static shell) — and a separate per-link/per-page data prefetch. The App Shell is conceptually part of the route, not prefetch data, so **`act` ignores App Shell requests for all assertion purposes** (they carry a `next-router-prefetch: '3'` header).\n\nThis means you generally do **not** need to account for the extra App Shell response in your assertions. If a `Loading...` fallback now arrives in both the App Shell prefetch and the per-link prefetch, you still write a single `{ includes: 'Loading...' }` — the App Shell copy is invisible to matching. Likewise, `'no-requests'` still passes even if an App Shell prefetch fires, and `block: 'reject'` won't match content that appears only in the App Shell.\n\nApp Shell requests are still intercepted, fulfilled, and awaited (so the shell is cached and no requests are left in flight) — they just don't participate in `includes` matching, `no-requests`, `block: 'reject'`, or the \"at least one request\" check. An App Shell response that returns an error status (4xx/5xx) still fails the test.\n\nTo assert on App Shell responses directly — for tests specifically about App Shell behavior — opt in at the `act` instance level:\n\n```typescript\nconst act = createRouterAct(page, { includeAppShellRequests: true })\n```\n\nWith this option, App Shell requests are treated like any other router request. Prefer expressing App Shell behavior through observable outcomes (e.g. an instant navigation rendering the cached shell before the data response arrives) rather than asserting on prefetch content where practical. See `test/e2e/app-dir/segment-cache/prefetch-app-shell/prefetch-app-shell.test.ts` for the canonical example.\n\n### What `act` Does Internally\n\n`act` intercepts all router requests — prefetches, navigations, and Server Actions — made during the scope:\n\n1. Installs a Playwright route handler to intercept router requests\n2. Runs your scope function\n3. Waits for a `requestIdleCallback` (captures IntersectionObserver-triggered prefetches)\n4. Fulfills buffered responses to the browser\n5. Repeats steps 3-4 until no more requests arrive\n6. Asserts on the responses based on the config\n\nResponses are buffered and only forwarded to the browser after the scope function returns. This means you cannot navigate to a new page and wait for it to render within the same scope — that would deadlock. Trigger the navigation (click the link) and let `act` handle the rest. Read destination page content _after_ `act` returns:\n\n```typescript\nawait act(\n  async () => {\n    /* toggle accordion, click link */\n  },\n  { includes: 'Page content' }\n)\n\n// Read content after act returns, not inside the scope\nexpect(await browser.elementById('my-content').text()).toBe('Page content')\n```\n\n## LinkAccordion Pattern\n\n### Why LinkAccordion Exists\n\n`LinkAccordion` controls when `<Link>` components enter the DOM. A Next.js `<Link>` triggers a prefetch when it enters the viewport (via IntersectionObserver). By hiding the Link behind a checkbox toggle, you control exactly when prefetches happen — only when you explicitly toggle the accordion inside an `act` scope.\n\n```tsx\n// components/link-accordion.tsx\n'use client'\nimport Link from 'next/link'\nimport { useState } from 'react'\n\nexport function LinkAccordion({ href, children, prefetch }) {\n  const [isVisible, setIsVisible] = useState(false)\n  return (\n    <>\n      <input\n        type=\"checkbox\"\n        checked={isVisible}\n        onChange={() => setIsVisible(!isVisible)}\n        data-link-accordion={href}\n      />\n      {isVisible ? (\n        <Link href={href} prefetch={prefetch}>\n          {children}\n        </Link>\n      ) : (\n        `${children} (link is hidden)`\n      )}\n    </>\n  )\n}\n```\n\n### Standard Navigation Pattern\n\nAlways toggle the accordion and click the link inside the same `act` scope:\n\n```typescript\nawait act(\n  async () => {\n    // 1. Toggle accordion — Link enters DOM, triggers prefetch\n    const toggle = await browser.elementByCss(\n      'input[data-link-accordion=\"/target-page\"]'\n    )\n    await toggle.click()\n\n    // 2. Click the now-visible link — triggers navigation\n    const link = await browser.elementByCss('a[href=\"/target-page\"]')\n    await link.click()\n  },\n  { includes: 'Expected page content' }\n)\n```\n\n## Common Sources of Flakiness\n\n### Using `browser.back()` with open accordions\n\nDo not use `browser.back()` to return to a page where accordions were previously opened. BFCache restores the full React state including `useState` values, so previously-opened Links are immediately visible. This triggers IntersectionObserver callbacks outside any `act` scope — if the cached data is stale, uncontrolled re-prefetches fire and break subsequent `no-requests` assertions.\n\nThe only safe use of `browser.back()`/`browser.forward()` is when testing BFCache behavior specifically.\n\n**Fix:** navigate forward to a fresh hub page instead. See [Hub Pages](#hub-pages).\n\n### Using visible `<Link>` components outside `act` scopes\n\nAny `<Link>` visible in the viewport can trigger a prefetch at any time via IntersectionObserver. If this happens outside an `act` scope, the request is uncontrolled and can interfere with subsequent assertions. Always hide links behind `LinkAccordion` and only toggle them inside `act`.\n\n### Using retry/polling timers to wait for network activity\n\n`retry()`, `setTimeout`, or any polling pattern to wait for prefetches or navigations to settle is inherently flaky. `act` deterministically waits for all router requests to complete before returning.\n\n### Navigating and waiting for render in the same `act` scope\n\nResponses are buffered until the scope exits. Clicking a link then reading destination content in the same scope deadlocks. Read page content after `act` returns instead.\n\n## Hub Pages\n\nWhen you need to navigate away from a page and come back to test staleness, use \"hub\" pages instead of `browser.back()`. Each hub is a fresh page with its own `LinkAccordion` components that start closed.\n\nHub pages use `connection()` to ensure they are dynamically rendered. This guarantees that navigating to a hub always produces a router request, which lets `act` properly manage the navigation and wait for the page to fully render before continuing.\n\n**Hub page pattern:**\n\n```tsx\n// app/my-test/hub-a/page.tsx\nimport { Suspense } from 'react'\nimport { connection } from 'next/server'\nimport { LinkAccordion } from '../../components/link-accordion'\n\nasync function Content() {\n  await connection()\n  return <div id=\"hub-a-content\">Hub a</div>\n}\n\nexport default function Page() {\n  return (\n    <>\n      <Suspense fallback=\"Loading...\">\n        <Content />\n      </Suspense>\n      <ul>\n        <li>\n          <LinkAccordion href=\"/my-test/target-page\">Target page</LinkAccordion>\n        </li>\n      </ul>\n    </>\n  )\n}\n```\n\n**Target pages link to hubs via LinkAccordion too:**\n\n```tsx\n// On target pages, add LinkAccordion links to hub pages\n<LinkAccordion href=\"/my-test/hub-a\">Hub A</LinkAccordion>\n```\n\n**Test flow:**\n\n```typescript\n// 1. Navigate to target (first visit)\nawait act(\n  async () => {\n    /* toggle accordion, click link */\n  },\n  { includes: 'Target content' }\n)\n\n// 2. Navigate to hub-a (fresh page, all accordions closed)\nawait act(\n  async () => {\n    const toggle = await browser.elementByCss(\n      'input[data-link-accordion=\"/my-test/hub-a\"]'\n    )\n    await toggle.click()\n    const link = await browser.elementByCss('a[href=\"/my-test/hub-a\"]')\n    await link.click()\n  },\n  { includes: 'Hub a' }\n)\n\n// 3. Advance time\nawait page.clock.setFixedTime(startDate + 60 * 1000)\n\n// 4. Navigate back to target from hub (controlled prefetch)\nawait act(async () => {\n  const toggle = await browser.elementByCss(\n    'input[data-link-accordion=\"/my-test/target-page\"]'\n  )\n  await toggle.click()\n  const link = await browser.elementByCss('a[href=\"/my-test/target-page\"]')\n  await link.click()\n}, 'no-requests') // or { includes: '...' } if data is stale\n```\n\n## Fake Clock Setup\n\nSegment cache staleness tests use Playwright's clock API to control `Date.now()`:\n\n```typescript\nasync function startBrowserWithFakeClock(url: string) {\n  let page!: Playwright.Page\n  const startDate = Date.now()\n\n  const browser = await next.browser(url, {\n    async beforePageLoad(p: Playwright.Page) {\n      page = p\n      await page.clock.install()\n      await page.clock.setFixedTime(startDate)\n    },\n  })\n\n  const act = createRouterAct(page)\n  return { browser, page, act, startDate }\n}\n```\n\n- `setFixedTime` changes `Date.now()` return value but timers still run in real time\n- The segment cache uses `Date.now()` for staleness checks\n- Advancing the clock doesn't trigger IntersectionObserver — only viewport changes do\n- `setFixedTime` does NOT fire pending `setTimeout`/`setInterval` callbacks\n\n## Reference\n\n- `createRouterAct`: `test/lib/router-act.ts`\n- `LinkAccordion`: `test/e2e/app-dir/segment-cache/staleness/components/link-accordion.tsx`\n- Example tests: `test/e2e/app-dir/segment-cache/staleness/`\n", "skills/run-tests/SKILL.md": "---\nname: run-tests\ndescription: >\n  Run Next.js tests reliably in a fresh checkout or worktree, and reproduce or\n  fix flaky tests. Use for Playwright browser install errors, missing build\n  outputs, pnpm test-unit or Jest selection surprises, run-tests.js repeats,\n  CI env flags for snapshot tests, native binding selection, ignored fixture\n  files such as tsconfig.json, CI-only test type/lint\n  gates, CPU-starved flakes, fixed waits, requestIdleCallback starvation, or\n  flake-detection failures.\nmetadata:\n  internal: true\n---\n\n# Run Tests\n\nUse this skill when running, adding, or debugging tests in the Next.js repo.\nThe basic commands are in the root `AGENTS.md`. For flaky tests, read\n[flaky-tests.md](./flaky-tests.md).\n\n## Bootstrap a fresh checkout\n\n1. Run `pnpm install --frozen-lockfile`. If you are deliberately building native\n   bindings from source and the native postinstall fails, use\n   `NEXT_SKIP_NATIVE_POSTINSTALL=1` (see `scripts/install-native.mjs`).\n2. Build JS with workspace dependencies: `pnpm build`. In a fresh checkout, a bare\n   `pnpm --filter=next build` can miss workspace outputs such as polyfills.\n3. Install the browser version that matches the repo's Playwright:\n   `pnpm exec playwright install chromium`. A different Chromium can still fail\n   with `Executable doesn't exist`.\n4. Rust or Turbopack changes need a native build before Next.js e2e tests. See\n   the root `AGENTS.md` rebuild rules.\n\n## Choose the command\n\n- Mode-specific scripts such as `pnpm test-dev-turbo` call `scripts/run-jest.sh`\n  and set the mode and bundler.\n- A dev-only test can be skipped by `test-start-*`. Check `isNextDev`, gates,\n  and the CI job before choosing a command.\n- `pnpm test-unit <file>` appends `<file>` to\n  `jest test/unit/ packages/next/ packages/font`, so it can run all of those\n  suites. Use `pnpm exec jest <file>` for one file.\n- Jest only searches the `roots` in `jest.config.js`. A copied test outside\n  those roots reports `No tests found`. Use a temporary worktree for experiments.\n- `node run-tests.js` is the CI runner:\n  - `--retries 0 --runs N` repeats each selected file; repeats require\n    `--retries 0` and fail when `NEXT_SKIP_ISOLATE` is set.\n  - `--concurrency 1` serializes files.\n  - `--debug` shows test output.\n  - It selects files, not individual test names. Use a Jest script with `-t` to\n    focus one case.\n\n## Match CI\n\n- Inline snapshots can depend on CI env flags. Use the exact `afterBuild:` flags\n  from `.github/workflows/build_and_test.yml`, keep them set for the full run,\n  and use the same bundler. For example `build-output-prerender` expects\n  `__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true`. The `react-dom/server` build\n  depends on runtime and bundler: Edge contexts get `server.edge` (no\n  `renderToPipeableStream`), Node contexts get `server.node`, and the Pages\n  renderer differs between bundlers. Check\n  `crates/next-core/src/next_import_map.rs` (Turbopack) and\n  `packages/next/src/build/create-compiler-aliases.ts` (webpack).\n- For exact replication of a failed job, use `$pr-status-triage` and its\n  `local-repro.md`.\n- Isolated installs use a `.node` file from `packages/next-swc/native` when\n  present; otherwise they use the installed `@next/swc-*` package. Check the\n  logged `swcNativeDirectory` before trusting a native-binding repro.\n- `nextTestSetup({ dependencies })` installs dependencies in the isolated app.\n  A `require()` in the Jest test file still resolves from the repo. Run\n  isolated tools as child processes with their `cwd` in the test app.\n- New `test/e2e` suites also run in deploy mode. Read `test/AGENTS.md` before\n  adding file patches or log assertions.\n\n## Quick smoke testing\n\nFor fast feedback, generate a fixture with\n`pnpm new-test --args true <name> e2e`. Run Next.js with the fixture as the\nworking directory and an absolute path to the built CLI:\n\n```bash\ncd <fixture-dir>\nnode <repo>/packages/next/dist/bin/next dev --port <port>\n```\n\nProbe it with `curl --max-time 10`. If a throwaway app symlinks packages from\nthe checkout, link `next`, `react`, and `react-dom` individually. Set\n`turbopack.root` and `outputFileTracingRoot` to a common parent when the build\nneeds to resolve the linked `next` package.\n\n## Commit fixtures completely\n\n- `test/.gitignore` ignores `tsconfig.json` under `e2e/**`, `production/**`,\n  and `development/**`. If the fixture needs that file, force-add it with\n  `git add -f`. Don't force-add generated `next-env.d.ts`.\n- The root `.gitignore` only ignores the Rust `target` directories of the Cargo\n  workspaces. If you add a Cargo workspace, add its `target` path there.\n- Before pushing, compare the tracked fixture files with the files the test\n  needs. Use `git ls-tree -r --name-only HEAD -- <dir>`, or\n  `git check-ignore -v <path>` for a single path.\n\n## Gates beyond the test run\n\n- `pnpm --filter=next types` uses `tsconfig.build.json`, which excludes tests.\n  When test files change, run `pnpm lint-typescript` (or the full\n  `pnpm types-and-precompiled` when its clean-tree check is appropriate).\n- `pnpm lint-language` runs `alex` on Markdown files. After editing docs, run\n  `pnpm exec alex <files> --quiet`.\n- CI checks the PR merged with current canary. If Prettier passes locally but\n  fails in CI, compare `.prettierignore` and the formatter config with canary.\n- Common test-file ESLint rules include `jest/no-standalone-expect` and\n  `@typescript-eslint/prefer-as-const`.\n- Treat unexpected snapshot churn as a possible regression. Find the source of\n  the output change before updating snapshots.\n\n## Related Skills\n\n- `$pr-status-triage` - CI failure triage and exact CI env reproduction\n- `$gate-tests` - `@gate` / `@force-gate` instead of skips\n- `$router-act` - deterministic client-router tests\n", "skills/run-tests/flaky-tests.md": "# Reproducing and Fixing Flaky Tests\n\n## Reproduce first\n\n- Record the CI signature before changing code: test file, case, assertion,\n  mode, bundler, env flags, run, attempt, and commit SHA.\n- Reproduce in the same mode and bundler. Take an unmodified baseline count\n  before trying a fix.\n- Many flakes need CPU pressure. Try both:\n  - Pin the test and a few busy loops to one CPU, for example with `taskset`.\n  - Run busy loops across all CPUs while increasing test concurrency.\n- Compare results only on the same commit, command, load, and machine.\n- Use `node run-tests.js --retries 0 --runs <n> --concurrency 1 <file>` for\n  whole-file repeats. Use a Jest script with `-t` for one case.\n- Artificial delays can help explain a race, but they are not a substitute for\n  reproducing the CI-equivalent failure.\n- To find a race, write timestamped request or event logs to a separate file\n  for each run. Don't use timestamps from buffered output as timing data.\n\n## Write flake-safe tests\n\n- Use `retry()` or event-driven waits, never fixed sleeps.\n- In dev mode, a newly visited route may compile on demand. Give the destination\n  page a stable selector and wait for it before asserting page content.\n- Control client-router requests with `createRouterAct` and `LinkAccordion`\n  (`$router-act`). Waiting for network idle can include unrelated prefetches.\n- A Playwright `page.click()` on an interactive element can delay a later\n  `requestIdleCallback` on a static page until something renders. If a test\n  depends on an idle callback, check whether a DOM `element.click()` is the\n  right trigger.\n- Flake detection runs added or changed test files three times concurrently\n  with `--retries 0` (`scripts/test-new-tests.mjs --flake-detection`). A fix\n  should pass repeated `node run-tests.js --retries 0 --runs 3 <file>` runs.\n- Don't wrap Jest snapshot matchers in `retry()`. Poll a plain value, then\n  assert the snapshot once.\n- Keep concurrent runs independent: use unique mutable files and dynamic ports\n  (`server.listen(0)` or `findPort()`). See `contributing/core/testing.md`.\n- Adding a test to an existing file makes flake detection run that file. Put an\n  unrelated test in a new suite if the existing file has unrelated\n  concurrency hazards.\n- Close servers and connections in teardown. A suite whose assertions passed\n  can still fail when `afterAll` times out.\n\n## Report and bisect\n\n- Report raw counts per case and load, such as \"7 of 17 runs\". Avoid rates,\n  \"never\", or \"always\" from small samples.\n- Label results as observed or inferred. Present a mechanism as a hypothesis\n  until evidence distinguishes it from alternatives.\n- A green rerun on the same SHA shows intermittency. It doesn't prove the PR is\n  unrelated.\n- Bisect scripts should fail closed. Mark a commit good only when the expected\n  test ran and passed. Use exit `125` for unrelated failures.\n- Detect the bug with a stable condition when error text changes over history.\n  Keep each run's logs in its own directory and give parallel test binaries\n  separate cache directories.\n", "skills/runtime-debug/SKILL.md": "---\nname: runtime-debug\ndescription: >\n  Debug and verification workflow for runtime-bundle and module-resolution\n  regressions. Use when diagnosing unexpected module inclusions, bundle\n  size regressions, or CI failures related to NEXT_SKIP_ISOLATE, nft.json\n  traces, or runtime bundle selection (module.compiled.js). Covers CI env\n  mirroring, full stack traces via __NEXT_SHOW_IGNORE_LISTED, route trace\n  inspection, and webpack stats diffing.\nmetadata:\n  internal: true\n---\n\n# Runtime Debug\n\nUse this skill when reproducing runtime-bundle, module-resolution, or user-bundle inclusion regressions.\n\n## Local Repro Discipline\n\n- Mirror CI env vars when reproducing CI failures.\n- Key variables: `IS_WEBPACK_TEST=1` forces webpack (turbopack is default), `NEXT_SKIP_ISOLATE=1` skips packing next.js.\n- For module-resolution validation, always rerun without `NEXT_SKIP_ISOLATE=1`.\n\n## Stack Trace Visibility\n\nSet `__NEXT_SHOW_IGNORE_LISTED=true` to disable the ignore-list filtering in dev server error output. By default, Next.js collapses internal frames to `at ignore-listed frames`, which hides useful context when debugging framework internals. Defined in `packages/next/src/server/patch-error-inspect.ts`.\n\n## User-Bundle Regression Guardrail\n\nWhen user `next build` starts bundling internal Node-only helpers unexpectedly:\n\n1. Inspect route trace artifacts (`.next/server/.../page.js.nft.json`).\n2. Inspect traced server chunks for forbidden internals (e.g. `next/dist/server/stream-utils/node-stream-helpers.js`, `node:stream/promises`).\n3. Add a `test-start-webpack` assertion that reads the route trace and traced server chunks, and fails on forbidden internals. This validates user-project bundling (not publish-time runtime bundling).\n\n## Bundle Tracing / Inclusion Proof\n\nTo prove what user bundling includes, emit webpack stats from the app's `next.config.js`:\n\n```js\n// next.config.js\nmodule.exports = {\n  webpack(config) {\n    config.profile = true\n    return config\n  },\n}\n```\n\nThen use `stats.toJson({ modules: true, chunks: true, reasons: true })` and diff `webpack-stats-server.json` between modes. This gives concrete inclusion reasons (e.g. which module required `node:stream/promises`) and is more reliable than analyzer HTML alone.\n\n## Related Skills\n\n- `$flags` - flag wiring (config/schema/define-env/runtime env)\n- `$dce-edge` - DCE-safe require patterns and edge constraints\n- `$react-vendoring` - entry-base boundaries and vendored React\n", "skills/rust-turbopack/SKILL.md": "---\nname: rust-turbopack\ndescription: >\n  Build, test, verify, and benchmark Rust changes in the Next.js repository,\n  including Turbopack crates and next-napi-bindings. Use for native-binding\n  rebuilds before e2e tests, clippy or Miri, Turbopack snapshot and execution\n  fixtures, UPDATE=1 snapshot refreshes, fixture discovery, analyzer graph\n  snapshots, wasi test failures, worktree target\n  directory mistakes, Rust disk usage, TURBO_ENGINE_IGNORE_DIRTY, persistent\n  cache benchmarks, RSS measurements, or Criterion runs.\nmetadata:\n  internal: true\n---\n\n# Rust and Turbopack\n\nUse this skill when changing or verifying Rust code. Code-level `turbo_tasks`\nrules live in `turbopack/AGENTS.md`. Benchmark guidance is in\n[benchmarking.md](./benchmarking.md).\n\n## Rebuild before Next.js tests\n\nNext.js e2e tests use the compiled native binding, not Rust source. After a\nRust change, rebuild before running Next.js tests, even when `cargo check`\npasses:\n\n```bash\n(cd packages/next-swc && CARGO_PROFILE_DEV_DEBUG=0 pnpm build-native)\npnpm build-all\n```\n\n- The first command is a faster debug native build. The second matches the\n  normal full JS and Rust build.\n- Check that the test uses the binding you built. The test harness logs\n  `swcNativeDirectory`.\n- A debug native build can make build-heavy tests slower than CI.\n- Native builds can update\n  `packages/next/src/build/swc/generated-native.d.ts`. Commit only intended\n  changes.\n- `@napi-rs/cli` is a dependency of `packages/next-swc`. Run it through\n  `pnpm --filter @next/swc exec napi ...`, and pass `--cwd` as an absolute path.\n\n## Run CI-equivalent checks\n\n- Format with `cargo fmt --all`, then gate with `cargo fmt --all -- --check`.\n  Re-run formatting after the last edit, including mechanical renames.\n- CI clippy uses warnings as errors. The `packages/next-swc` script is:\n  `cargo clippy --workspace --all-targets -- -D warnings -A deprecated`.\n  For a focused check, also run clippy for affected dependents with\n  `--all-targets`.\n- `turbopack` depends on `turbopack-node` without default features. For a\n  standalone `cargo check -p turbopack`, enable\n  `--features turbopack-node/process_pool`.\n- CI runs Miri on a fixed package allowlist with specific flags. Run it with\n  `pnpm --filter @next/swc run test-cargo-unit-miri` (see `packages/next-swc/package.json`)\n  from the checkout so `rust-toolchain.toml` selects the pinned nightly. A bare\n  `cargo miri test -p <crate>` omits those flags and can abort on filesystem\n  access. Add a crate to the allowlist only after confirming it runs under Miri.\n- Cargo commands can update `Cargo.lock`. Check `git status` and revert\n  unrelated changes.\n- For an internal compiler error related to incremental compilation, delete the\n  affected `*/incremental` directories in the target directory and retry.\n\n## Turbopack fixtures\n\n- Refresh snapshot tests with `UPDATE=1 cargo nextest run -E 'test(snapshot)'`,\n  as documented in `turbopack/crates/turbopack-tests/README.md`. Without\n  nextest, use\n  `UPDATE=1 cargo test -p turbopack-tests --test snapshot <filter>`.\n  Then run again without `UPDATE` and review the diff.\n- Snapshot `output/` files are tracked. Execution-test `output/` directories\n  are ignored. Use a snapshot fixture when exact generated code matters.\n- Fixture tests are generated from directory globs at compile time. After adding\n  or deleting a fixture directory, touch the relevant harness (for example\n  `tests/snapshot.rs`, `tests/execution.rs`, or\n  `turbopack-ecmascript/src/references/tests.rs`) so Cargo rebuilds it.\n- Execution fixtures enable scope hoisting by default. Add a\n  `\"scopeHoisting\": false` fixture when testing generated cross-module code.\n- Prettier can rewrite syntax-sensitive fixture input. Use `// prettier-ignore`\n  when the exact syntax is what the test checks.\n- Snapshot tests embed the workspace root at compile time\n  (`TURBO_PNPM_WORKSPACE_DIR` in `.cargo/config.toml`). Run them from the\n  checkout that built the test binary.\n- Analyzer graph snapshots include `Effect` debug output. After changing it,\n  run `UPDATE=1 cargo test -p turbopack-ecmascript --lib analyzer::tests` and\n  check that the snapshot diff contains only the intended change.\n\n## wasi tests\n\nUse `scripts/wasi-test-host/README.md` for host setup and commands.\n\n- The `test next-swc wasi` job runs Rust tests on a target that aborts on panic.\n  A failing assertion can stop the whole test binary. Tests that require\n  unwinding need a wasm-specific ignore, like existing examples.\n- A contended `parking_lot` lock panics on wasm. Tests that need blocking locks\n  must account for that platform limitation.\n\n## Target directories\n\n- Don't share one `CARGO_TARGET_DIR` between worktrees. Cargo can reuse a\n  workspace crate built from another worktree and test the wrong source. Use\n  one target directory per worktree.\n- Rust targets can become very large. Check free disk space before broad builds.\n  `target/debug/incremental` is disposable when it causes disk pressure.\n- For a test binary, use the executable path printed by\n  `cargo test --no-run`.\n- Rust's test harness hides output from passing tests. Pass `-- --nocapture`\n  when you need instrumentation output.\n- Parallel copies of tests that use a persistent cache need separate cache or\n  target directories.\n\n## Related Skills\n\n- `$pr-status-triage` - CI failure triage\n- `$sandbox-bench` - end-to-end render-pipeline A/B benchmarks\n", "skills/rust-turbopack/benchmarking.md": "# Benchmarking Turbopack and `next build`\n\nUse this when measuring compile time, persistence, or memory of `next build` /\n`next dev` with locally built native bindings (for example on the `bench/`\napps such as `bench/large-app-router` or\n`bench/nested-deps-app-router-many-pages`), or when running Criterion benches\nin Turbopack crates. For render-pipeline throughput, see\n`bench/BENCHMARKING.md` and `$sandbox-bench`.\n\n## Build the arms correctly\n\n- **A native binding built from a dirty git tree disables the Turbopack\n  persistent cache.** `next build` prints\n  `WARNING: The git repository is dirty: File System Cache is disabled`, so\n  \"warm\" builds behave like cold ones. Commit locally before building, or set\n  `TURBO_ENGINE_IGNORE_DIRTY=1` for every arm\n  (`turbo-tasks-backend/src/database/db_versioning.rs`). Use the same env for\n  base and candidate.\n- Build release bindings (`pnpm build-native-release` in `packages/next-swc`)\n  for both arms from the exact base and head SHAs. Record the SHA from the build\n  log.\n- Build the baseline in **its own worktree**\n  (`git worktree add <dir> <base-sha>`), never in the checkout you're editing:\n  cargo compiles whatever is on disk at that moment. Don't share\n  `CARGO_TARGET_DIR` between worktrees (see [SKILL.md](./SKILL.md)). Check\n  that the arm binaries actually differ (hash them).\n- Per arm, swap **both** `packages/next/dist` and\n  `packages/next-swc/native/*.node`, and rebuild `dist` after rebasing so JS\n  matches the bindings. A base worktree needs its own `react` / `react-dom`.\n- **Keep a separate `.next` per arm.** Persistent cache data from another native\n  binary can be incompatible. Prime each arm with one cold and one warm build.\n- If a swap script moves binaries between the repo and parked copies, check\n  which arm is active before replacing a file, and verify with a marker (for\n  example a new span name in the `.node`).\n\n## Run\n\n- Size the workload small first (for example a generated app that compiles in\n  a few seconds), then scale up.\n- Interleave arms (ABBA) in one contiguous batch, discard a warm-up per arm,\n  and run pairs in both orders. Whichever binary runs second often looks\n  slower. Keep other cargo/rustc work off the machine during a batch, and record\n  the CPU model, since the host can change between batches.\n- Don't run cargo builds while a Criterion benchmark is running.\n- With SMT, \"N CPUs\" scaling runs should pin one logical CPU per physical core\n  (`taskset` on Linux), together with `TURBO_TASKS_AVAILABLE_PARALLELISM`.\n- Large `.next` caches take several GB per arm. Check free disk before each\n  build.\n\n## Measure memory correctly\n\n- For `next dev` the large process is the forked server, not the CLI parent.\n  Report the launched process, the largest process, and the whole process tree\n  separately.\n- On Linux:\n  - `wait4()` / `ru_maxrss` is the peak of the single largest process in the\n    waited tree, not the main process and not the tree total. It is KiB.\n  - Poll `VmHWM` in `/proc/<pid>/status` for one process. For the tree, sample\n    the sum of `VmRSS` or read cgroup `memory.peak`.\n- On macOS, `ru_maxrss` is in bytes, and `/proc` and cgroups don't exist.\n- `.next/trace` has thousands of events. Aggregate the direct children of\n  `next-build` (for example `turbopack-module-graph`,\n  `turbopack-write-entrypoints`, `turbopack-persistence`, `static-generation`)\n  instead of printing everything.\n\n## Criterion\n\n- The name filter only skips `bench_function` closures. Setup in the\n  surrounding function runs for every filter, so move untimed setup into the\n  closure (for example via `OnceCell`).\n- `--save-baseline NAME` still overwrites `target/criterion/<id>/new/`. Back up\n  `target/criterion` before exploratory runs that could clobber reported\n  results.\n- To resume an interrupted run, count completed IDs from\n  `target/criterion/**/new/estimates.json`, not from `time:` log lines.\n- With linear sampling, the reported center is a linear-regression estimate,\n  not a mean.\n- `cargo run -q 2>&1 | tee out.csv` mixes compiler warnings into the data.\n  Redirect only stdout to data files.\n\n## Report\n\n- Compute statistics from the raw per-run data with a script, not from rounded\n  console output. Re-measure after refactors before quoting numbers in a PR.\n- Report directional estimates with uncertainty. A non-significant result is\n  \"no detected difference\", not proof of equivalence. Keep order-sensitive\n  results in the report as a warning, and check every row before claiming \"no\n  regressions\".\n- Don't compare timings across machines (local x86 against CI ARM) as if\n  paired.\n", "skills/sandbox-bench/SKILL.md": "---\nname: sandbox-bench\ndescription: >\n  Benchmark React or Next.js changes on Vercel Sandbox VMs with paired\n  A/B statistics: react PR/commit vs base, or Next.js PR/commit vs base,\n  measured end-to-end through the bench/render-pipeline app (rps,\n  latency, p95; TTFB, RSS and document/Flight bytes when the Next\n  side captures them) and, for React changes, through the react\n  repo's flight-ssr-bench fixture (Node AND Edge web-streams paths,\n  Fizz and Flight+Fizz). Use whenever the user asks to bench, perf\n  test, or A/B a React PR, a react-server-dom / Flight / vendored React\n  change, or a Next.js PR (\"is this PR faster\", \"does this regress\n  RSC?\", \"measure the perf impact of <commit>\"), even if they don't say\n  \"benchmark\" — any request to quantify a server-side performance\n  difference between two revisions belongs here. Runs remotely\n  (laptop-free), applies correctness gates before measuring, and\n  reports boot-level confidence intervals.\nmetadata:\n  internal: true\n---\n\n# Sandbox bench: paired A/B perf runs for React and Next.js changes\n\nMeasures what a change is actually worth, end to end: two revisions\n(\"arms\") built into otherwise-identical Next.js apps, exercised by the\n`bench/render-pipeline` harness on Vercel Sandbox VMs, compared with\npaired statistics that treat the VM boot as the unit of replication.\nAll heavy work happens on sandbox VMs; the laptop only orchestrates.\n\nScripts live in `scripts/` next to this file and run from anywhere.\nArms are git refs, resolved in cached clones of react and next.js;\nthe Next side defaults to canary. Everything is cached\ncontent-addressed: first use of a new pair builds caches (~45-60 min\nextra, once); later runs boot straight into measurement.\n\n## One-time setup\n\n1. `node scripts/config.mjs show` — if it reports NOT CONFIGURED, ask\n   the user which Vercel **team** and **project** the sandbox VMs\n   should run under (these are billed resources; never guess, never\n   default), then `node scripts/config.mjs set team=<slug> project=<name>`.\n   Config lives in `~/.config/sandbox-bench/config.json` — never commit\n   team/project names into the repo.\n2. The Vercel CLI session must have access to that team. On a 403,\n   stop launching (don't retry through it) and check whether access is\n   already back: `vercel whoami --scope <team-slug>` plus one scoped\n   read call (e.g. `vercel sandbox ls`) — grants drop and recover on\n   their own, and a transient 403 needs no login at all. If\n   verification still fails, run `vercel login <team-slug>` yourself\n   as a background task (the token lives with the CLI session, not\n   with the user). It opens a browser/device confirmation — relay the\n   URL if one is printed — but keep re-running the verification pair\n   every minute or two while it waits: access often returns before\n   the login flow reports success, and once verification passes, kill\n   the pending login and resume. After a 403 outage, expect in-flight runs to have died:\n   run `node scripts/bench-status.mjs` and follow its recovery\n   actions (measurement VMs will have hit their ~5h timeout if the\n   outage was long — those cells need relaunching, not collecting).\n3. react and next.js clones land in the cache on first use (or point\n   `reactRepo`/`nextRepo` in the config at existing checkouts).\n\nBefore the first real run with a new configuration, sanity-check the\nplan with `--dry-run` (prints what would happen, touches nothing).\n\n## Workflow\n\n### 1. Resolve what's being compared\n\n- **React PR**: `--pr <url|number>` — base is computed automatically\n  (merge-base of the PR head with react main).\n- **React refs**: `--arms base=<ref>,cand=<ref>` — base FIRST. For a\n  multi-commit branch, base is the merge-base with main, not `cand^`.\n- **Next.js PR**: `--next-pr <url|number>`. The React side defaults to\n  whatever each Next ref vendors (that's what would ship); pass\n  `--react-ref` only to pin both arms to one specific React build.\n- **Next refs**: `--next-arms base=<ref>,cand=<ref>`.\n\nExactly one side varies; the other is identical in both arms. That\nisolation is what makes the numbers attributable — never vary both.\n\n### 2. Gate correctness before spending bench compute\n\nA bench number from an arm that fails its own tests is meaningless.\nFor any arm that is not already CI-green upstream (hand-assembled\nbranches, cherry-picks with resolved conflicts, local commits):\n\n```sh\nnode scripts/sandbox-gate.mjs --arms cand=<ref>\n```\n\nThe bench itself enforces the primary gate: every react arm's commit\nmust have green CI on the react repo, checked automatically before any\nbuild or VM is spent. PRs and main-history commits normally satisfy\nthis with no extra work. For local or unpushed refs (no CI exists),\ngate on a VM with sandbox-gate.mjs and then pass --allow-ungated to\nthe bench. The VM gate runs the full test suite in prod mode (the\nchannel that gets benched). PASS requires seeing the actual test\ncounts in the output. If a gate fails, report the failures and stop —\ndo not bench a broken arm. Each arm is gated in its own\nlockfile's environment. Bench the exact sha the gate prints (a branch\nref can move between gate and bench).\n\n### 3. Launch the bench (background, non-blocking)\n\n```sh\nbash -c 'node scripts/sandbox-e2e.mjs --pr <url> --label <slug> \\\n  2>&1 | grep --line-buffered -v \"^live \"; exit ${PIPESTATUS[0]}'\n```\n\nFor React PRs, launch BOTH suites (separate background tasks; they\nshare arm builds and caches):\n\n```sh\nbash -c 'node scripts/sandbox-ssr.mjs --pr <url> --label <slug>-ssr \\\n  2>&1 | grep --line-buffered -v \"^live \"; exit ${PIPESTATUS[0]}'\n```\n\nThe e2e suite measures the Node path through a real Next.js app; the\nssr suite measures the react repo's flight-ssr-bench fixture — 8\nvariants (Fizz and Flight+Fizz, Node and Edge web streams, sync and\nasync), each sequentially with Flight script injection and behind an\nHTTP server at c=1/c=10. Edge cells are the ssr suite's headline (the\ne2e suite cannot see that path); its Node and Fizz-only cells\nattribute an effect to the Flight layer, the Fizz layer, or the\nstream plumbing. The fixture (the workload) is pinned to one ref for\nboth arms — react main by default — so only the React builds differ;\nif the PR itself edits the fixture, the launcher says so and the run\ndoes not measure those edits. Next PRs run the e2e suite only.\n\n- Run it as a background task and proceed on its completion\n  notification. Never hold a foreground wait; never poll in a loop —\n  the rule is about control flow, not status relay: reading the\n  output tail to answer \"how's it going\" is always fine.\n- The harness handles the invariants internally: both arms in the same\n  VM, interleaved ABBA, paired per (vm, run); detached remote\n  execution (transport drops don't kill runs); build fingerprints\n  recorded in every result row.\n- `live ...` lines are streaming estimates for progress display only.\n  Never stop a run early because a live p-value looks good, and never\n  report a live number — sequential peeking manufactures false\n  positives. Only the final analysis counts.\n- Defaults (16 VMs × 2 paired runs) implement the methodology; don't\n  reduce VM count to save time — boots are the unit of inference, and\n  fewer boots means wider intervals, not faster answers.\n- Sandbox compute is internal capacity, not a budget: launch, relaunch,\n  and confirm runs without asking about cost or shrinking them to\n  save it.\n- The Next side's default, `canary`, is the latest published canary\n  release (the launcher prints its version and sha), so repeat benches\n  reuse the built snapshot until a new canary ships.\n- Useful flags: `--bench-env KEY=VALUE` (runtime-only env for the\n  bench process — it does NOT affect the snapshot's app build), `--isolate-routes`\n  (tail investigations), `--no-profile` (skip the CPU capture that\n  runs by default after the timed runs), `--prepare` (build caches\n  only — use when two cells will share an arm, to avoid duplicate\n  builds racing).\n- CPU profiles are captured by default: one profile pass per arm runs\n  strictly AFTER the timed runs (it cannot touch the numbers), costs\n  ~45-60 min extra VM wall-clock, and lands in `<runDir>/prof-vm<N>/`\n  as standard V8 `.cpuprofile` files. Cross-VM profile diffs are\n  highly stable (observed 16/16 sign agreement on real movers), so one\n  profiled cell suffices to rank hot paths. Analysis caveats:\n  aggregate by (functionName, line, column) — bare minified names\n  collide across the bundle — and never diff arms by minified name\n  (the minifier renames between builds); match positions or code\n  snippets instead.\n- The bench exercises Next's node-streams path\n  (`__NEXT_USE_NODE_STREAMS` is inlined as true for the node runtime\n  at build time). React changes that only touch the EDGE stream\n  configs are not exercised end-to-end and will (correctly) bench as\n  no detected difference.\n\n### 4. Read the result like a skeptical data scientist\n\nThe goal is the truth about the change, not making its author feel\ngood. The final analysis prints, per route/phase/metric, the\nboot-level mean, ±95% CI, and p across boots. Apply the policy in\n[references/methodology.md](references/methodology.md):\n\n- Claim only boot-level p < 0.01, with the CI, on an A/A-validated\n  team/config (see methodology).\n- The PR is a hypothesis, not an explanation. Claims come from the\n  analysis output alone. When the numbers agree with the PR's story,\n  check whether the captured data actually discriminates that\n  mechanism from alternatives — a latency win attributed to smaller\n  payloads should come with a document-bytes delta; if the bytes\n  didn't move, the story doesn't hold and the report says so.\n- Use every captured metric, and voice anything that does not add up:\n  one metric family moving against the others, effects with no\n  byte-level or RSS trace, throughput moving without latency,\n  sign flips across boots. An inconsistency you cannot explain\n  belongs in the report, not in the drawer.\n- The `within-run p` shown in brackets is a diagnostic, never a claim.\n- Check the fingerprint header first: two distinct fingerprints = valid\n  A/B; \"inconsistent fingerprints\" = invalid, report no numbers. The\n  fingerprint hashes both bundlers' compiled server files — arms\n  touching only client files can still legitimately show identical\n  fingerprints with different version strings.\n- Per-boot values are printed; if boots disagree in sign, say so.\n- Any claim that will drive a decision gets one independent\n  confirmation run before it's stated as fact.\n\nRe-analyze any past run without re-running it:\n`node scripts/bench-analyze.mjs <runDir>`.\n\n### 5. Report\n\nName what was measured with links: the PR title (printed in the\nanalysis header, stored in meta.json) linking to the PR; for ref\narms, the commit title. Lead with a table of the significant cells,\neach row carrying the effect with its unit, the CI, and p:\n\n```\n## [<PR title>](<PR url>) — e2e, Vercel Sandbox (x86 Xeon), <n> boots\n\nSignificant (boot-level p < 0.01, A/A-validated):\n| cell | effect | 95% CI | p |\n|---|---|---|---|\n| /dashboard under load | +14.4% throughput (req/s) | ±3.2% | <0.0001 |\n| /dashboard serial | −10.7% median latency (ms) | ±0.6% | <0.0001 |\n\nNo detected difference: <every cell not in the table, by name>.\nFlags: <cells at 0.01 ≤ p < 0.05, sign disagreements across boots,\nfingerprint caveats, anything that does not add up>\n```\n\nOne row per cell: rps and median restate each other, so report the\nthroughput number (add a p95 row only when the tail moves differently\nfrom the median). Document metrics (raw/gzip/Flight KB) get their own\nrows when they differ — they are the mechanism evidence. When the\nNext side predates the document-metrics harness (vercel/next.js#95828)\nthose cells are absent; say so instead of silently reporting less. State the platform next to the numbers. Magnitudes\nare platform-dependent (GC share differs by CPU); direction and\nmechanism transfer, percentages do not. Never present a\nnoise-compatible delta as a small win or loss — it is \"no detected\ndifference\".\n\n## Results database\n\nEvery collected run lands in one SQLite file,\n`~/.cache/sandbox-bench/results.db` — raw measurements and artifacts\n(CPU profiles, logs) only, written exclusively by the importer, never\nby hand. The launcher imports and verifies automatically at\ncollection; `bench-analyze` reads the db and nothing else, so every\nstatistic is a pure function of it. Numbers in reports come from the\nanalysis output verbatim — never retype, recompute, or aggregate them\nyourself.\n\n- `node scripts/bench-db.mjs ls` — all runs with sample/artifact counts.\n- `node scripts/bench-db.mjs verify [runId]` — integrity checks:\n  sqlite-level, referential, one fingerprint per arm, paired sample\n  counts, artifact sha256. Run it before drawing on old data.\n- `node scripts/bench-db.mjs export out.db <runId...>` — cut a\n  self-contained db of specific runs (with their profiles) to send to\n  someone. It opens in any SQLite tool.\n- `node scripts/bench-analyze.mjs <runId>` — re-analyze anything in\n  the db; a run-dir argument imports it first.\n\n## Keeping the user informed\n\nThe launcher narrates itself on stdout: launch facts first (run dir,\narms, CI verdicts), then a progress line every ~2 minutes with rows\ncollected and interim per-route effects with confidence. Relay to the\nuser: the run dir and expected duration right after launching,\nnotable interim shifts if they ask how it's going, and the full\nverdict from the final analysis when the completion notification\narrives. The analysis names metrics that were `not captured on this\nrun` — repeat that in the verdict when it limits what the data can\nsay (document metrics absent means the payload mechanism is\nunverified, not verified-identical).\n\nWhile a run is active, open any reply with a one-line status per run:\nread the tail of the launcher's output and quote its latest progress\nline. If the session supports timed wakeups or reminders, schedule a\ncheck at each expected transition (arm builds -> experiment snapshot\n-> measuring, then every ~15 minutes of measurement) and post the\nprogress line; if not, say when the next update will arrive so\nsilence is never ambiguous. Interim effects in progress lines are\nstreaming estimates — share them as progress, never as claims.\n\nIf a launcher process dies (session teardown, crash), the remote VMs\nkeep executing their measurement loops — the data is not lost. `node\nscripts/bench-collect.mjs <runDir>` reconnects, waits for the loops,\ndownloads the results, cleans up, and analyzes. Run it before the VMs\nhit their ~5h timeout.\n\n## Failure recovery\n\n- **First move, always: `node scripts/bench-status.mjs`.** Session\n  restarts silently kill background launchers while their detached VMs\n  keep measuring, and a dead launcher's log still ends with a\n  healthy-looking progress line — never infer liveness from log tails\n  or task output files. bench-status checks each run's recorded\n  launcher pid and prints the per-run recovery action (running /\n  collect now / relaunch). Run it at the start of any session that\n  expects work in flight, after any crash, and before telling the user\n  what is or isn't running. Launcher crashes are also recorded in the\n  run's status.json (`phase: \"failed\"` plus the error).\n- **Interrupted local process**: remote VMs keep running detached.\n  `vercel sandbox list` (with the configured team/project) to find\n  them; poll each VM's `/vercel/sandbox/loop.done`, `cp` its\n  `results.jsonl` down when done, then remove the VM and analyze with\n  `bench-analyze.mjs`.\n- **Leaked VMs** after any crash: `node scripts/sandbox-sweep.mjs`\n  lists this skill's VMs (matched by sbench-\\* name AND the\n  purpose=sandbox-bench tag, and only when older than --min-age-hours,\n  default 3, so healthy in-flight runs are never touched); `--yes`\n  removes them by exact listed name.\n- **Flaky uploads/transports**: the harnesses size-check artifacts and\n  abort on truncation. A failed cell is safe to relaunch; caches make\n  the retry cheap. Don't relaunch two cells that need the same uncached\n  arm at the same moment — they'll race to build it; use `--prepare`\n  first instead.\n\n## Cost expectations (set these with the user before big runs)\n\nPer cell at defaults: ~18 VMs (8 measurement + build/snapshot VMs),\n~1-2h wall-clock cold, ~30-60 min warm. A/A calibration and\nconfirmation runs are extra cells. VMs are billed to the configured\nteam — for anything beyond a single PR check, confirm scope first.\n\n## Related Skills\n\n- `$rust-turbopack` (`benchmarking.md`) - local Turbopack / `next build`\n  compile-time, persistent-cache, memory and Criterion benchmarks with\n  locally built native bindings (dirty-tree cache disable, per-arm `.next`,\n  RSS roles)\n", "skills/sandbox-bench/references/methodology.md": "# Statistical methodology\n\nThe design decisions below are what make the numbers trustworthy.\nThey follow standard rigorous-benchmarking practice (Kalibera & Jones,\n\"Rigorous Benchmarking in Reasonable Time\"; Georges et al.,\n\"Statistically Rigorous Java Performance Evaluation\"; JMH's forks\nmodel) — don't relax them to save wall-clock without understanding\nwhat they protect against.\n\n## The VM boot is the unit of replication\n\nJIT state, code layout, GC rhythm, host hardware, and phase order are\nrandom effects fixed at boot time. Iterations within a boot share all\nof them, so they are not independent samples — treating them as\nindependent produces confident nonsense (a p<1e-4 effect in one run\nthat vanishes in the next). The harness therefore:\n\n- computes each metric's delta per boot (mean of that boot's paired\n  within-boot deltas), and\n- runs t-based inference across boots (`bench-stats.mjs`); the CI and\n  p-value you see are boot-level.\n\nThe `within-run p` printed in brackets is a diagnostic only. It tells\nyou the pairing worked; it cannot support a claim.\n\nAllocation follows from this: more boots × fewer runs beats fewer\nboots × more runs at fixed budget, and boots run in parallel — adding\nthem costs money, not wall-clock, so don't be shy with them when\nsensitivity matters (CI shrinks with sqrt of boots). Defaults: e2e 16\nVMs × 1 block × 2\nruns. Both arms always run in the SAME VM, interleaved ABBA, paired\nper (vm, run) — hosts differ by up to ~20%, so cross-VM comparisons\nare meaningless; VMs exist to replicate, not to compare.\n\n## Claims\n\n- A claim requires boot-level p < 0.01, reported with its CI, on a\n  team/config whose boot-level inference an A/A run has validated.\n- Anything that will drive a decision (merge, revert, ship) gets one\n  independent confirmation cell first (standard perf-CI practice —\n  Mozilla/Chrome retrigger, MongoDB change-point detection — nobody\n  alerts off one detection).\n- Everything else is \"noise-compatible\", reported as no detected\n  difference — not as a small effect.\n\n## Percentiles\n\nA per-run p95/p99 from a small load phase is a near-max order\nstatistic, not a distribution estimate. Compare percentiles only at\nboot level; p99 needs ~1k+ samples per boot to mean anything at all.\nTail effects are also where phase carryover lives (a route's serial\ntail depends on the previous route's load phase) — investigate tails\nwith `--isolate-routes`, which restarts the server between routes.\n\n## A/A validation\n\nBefore claiming anything on a new team/config/suite, run an A/A cell\n(same ref as both arms) at default allocation:\n\n```sh\nnode scripts/sandbox-e2e.mjs --arms base=<ref>,cand=<ref> --label aa\nnode scripts/sandbox-ssr.mjs --arms base=<ref>,cand=<ref> --label ssr-aa\n```\n\nThe A/A validates the inference itself. With identical arms, expect\nabout (number of metric-cells x 0.01) cells at p < 0.01 by chance —\nunder 1 for the e2e suite's ~24 cells, roughly 1 for the ssr suite's\n~88. The pass criterion is therefore two runs: a suite fails its A/A\nwhen any cell reaches p < 0.01 with the same sign in both (a bias\ntied to the arm label recurs; chance does not), or when any single\ncell lands beyond the familywise bar (p < 0.01 / number of\nindependent variant-x-phase cells). A failing cell means boots are\nsharing label-correlated conditions and the CIs are too narrow — find\nthe mechanism before claiming; a magnitude gate is not a substitute.\nThe A/A CIs also tell you what effect sizes this config can resolve.\nRe-run the A/A when the platform changes (VM hardware generation,\nnode version, bench app or fixture changes).\n\nValidated so far: e2e (twice, 0/24 cells), ssr (two-run criterion:\none chance cell at p=0.0024 in run 1 dissolved to p=0.86 in run 2,\nnothing recurred; runs ssr-aa2/ssr-aa3 in the results db).\n\n## Interim progress display\n\nThe launcher's progress digest shows, per route/phase, the running rps\neffect and a directional confidence — P(candidate is actually\nfaster/slower | boots so far), the Student-t posterior under a flat\nprior (not a p-value). It appears from 4 completed boots. Display\nonly: runs complete their planned allocation, and claims come only\nfrom the final fixed-n analysis.\n\n## Fingerprints\n\nEvery result row records a build fingerprint (dist-file hash + version\nstring) read from the tree that actually served requests. The analysis\nheader verifies them: inconsistent fingerprints within an arm\ninvalidate the run (a VM measured the wrong build). Identical\nfingerprints across arms with different version strings can be\nlegitimate — the hash covers the compiled server files, so client-only\nchanges don't move it; check the version strings before declaring an\naccidental A/A.\n\n## Honest reporting\n\n- State the platform (e.g. \"x86 Xeon sandbox VMs\") next to any number.\n  Magnitudes are platform-dependent — GC's share of request time\n  scales with CPU speed — so direction and mechanism transfer between\n  platforms, percentages do not.\n- Print per-boot values; if boots disagree in sign, the mean is not a\n  finding, and say so.\n- Never conclude anything from the live streaming estimates. Peeking\n  at sequential results and stopping when p looks good is a classic\n  way to manufacture false positives.\n", "skills/sandbox-bench/scripts/bench-analyze.mjs": "#!/usr/bin/env node\n// Post-hoc (re-)analysis of runs at the boot level. Reads ONLY the\n// results db: a run-dir argument is imported (idempotently) and\n// verified first, a bare run id analyzes what the db already holds.\n//   node bench-analyze.mjs <runDir|runId> [--base <arm>] [--cand <arm>]\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { analyzeE2eRows } from './bench-stats.mjs'\nimport { openDb, importRun, loadRows, runMeta, verify } from './bench-db.mjs'\n\nconst argv = process.argv.slice(2)\nconst target = argv.find((a) => !a.startsWith('--'))\nconst get = (name) => {\n  const i = argv.indexOf(name)\n  return i >= 0 ? argv[i + 1] : undefined\n}\nif (!target) {\n  console.error(\n    'usage: node bench-analyze.mjs <runDir|runId> [--base arm] [--cand arm]'\n  )\n  process.exit(1)\n}\nconst db = openDb()\nlet runId\nif (fs.existsSync(target)) {\n  runId = importRun(db, target).runId\n} else {\n  runId = path.basename(target)\n}\nconst { failures, notes } = verify(db, runId)\nfor (const n of notes) console.log(`note: ${n}`)\nif (failures.length) {\n  console.error(`RESULTS DB VERIFY FAILED:\\n  ${failures.join('\\n  ')}`)\n  process.exit(1)\n}\nconst rows = loadRows(db, runId)\nconst arms = [...new Set(rows.map((r) => r.arm))]\nif (arms.length !== 2) {\n  console.error(`expected exactly 2 arms, found: ${arms.join(', ')}`)\n  process.exit(1)\n}\n// Which arm is base? Row order cannot answer this (ABBA runs the\n// candidate first), so require an explicit source: the run's meta,\n// a conventional name, or the --base flag.\nconst meta = runMeta(db, runId)?.meta\nconst base =\n  get('--base') ??\n  (meta && arms.includes(meta.base) ? meta.base : undefined) ??\n  ['base', 'synced'].find((n) => arms.includes(n))\nif (!base) {\n  console.error(\n    `cannot determine the base arm from {${arms.join(', ')}}: ` +\n      'no meta, no arm named \"base\"/\"synced\" — pass --base <arm>'\n  )\n  process.exit(1)\n}\nconst cand = get('--cand') ?? arms.find((a) => a !== base)\nconst boots = new Set(rows.map((r) => r.vm)).size\nconsole.log(`${runId}  boots=${boots}  arms: ${base} (base) vs ${cand}`)\nif (meta?.pr)\n  console.log(\n    `PR: ${meta.pr.title ? `\"${meta.pr.title}\" — ` : ''}${meta.pr.url}`\n  )\nfor (const a of meta?.arms ?? [])\n  if (a.title) console.log(`  ${a.name}: \"${a.title}\"`)\nif (rows[0].route === '') {\n  // Micro (sandbox-ab) samples: phase holds the payload name.\n  analyzeE2eRows(rows, base, cand, ['mean', 'p50', 'p95', 'p99', 'gcMs'])\n} else if (meta?.suite === 'ssr') {\n  analyzeE2eRows(rows, base, cand, [\n    'rps',\n    'mean',\n    'median',\n    'p95',\n    'p99',\n    'gcMs',\n    'heapMb',\n  ])\n} else {\n  // No p99 for e2e: the load phases are far too small for it.\n  analyzeE2eRows(rows, base, cand, [\n    'rps',\n    'median',\n    'mean',\n    'p95',\n    'ttfb',\n    'docKb',\n    'gzipKb',\n    'flightKb',\n    'rss',\n    'rssHw',\n  ])\n}\n", "skills/sandbox-bench/scripts/bench-collect.mjs": "#!/usr/bin/env node\n// Recover a run whose local launcher died (session teardown, crash):\n// the remote VMs keep executing their detached loops regardless, so the\n// data is usually still there. Reads the run's status.json for the VM\n// names, waits for each VM's loop to finish, downloads its results,\n// removes the VM, and runs the boot-level analysis.\n//\n//   node bench-collect.mjs <runDir> [--deadline-min 280]\nimport { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { loadConfig, sandboxScope } from './config.mjs'\n\nconst execFileP = promisify(execFile)\nconst CONFIG = loadConfig()\nconst SCOPE = sandboxScope(CONFIG)\nconst argv = process.argv.slice(2)\nconst dir = argv.find((a) => !a.startsWith('--'))\nconst deadlineMin = argv.includes('--deadline-min')\n  ? Number(argv[argv.indexOf('--deadline-min') + 1])\n  : 280\nif (!dir || !fs.existsSync(path.join(dir, 'status.json'))) {\n  console.error('usage: node bench-collect.mjs <runDir with status.json>')\n  process.exit(1)\n}\nconst statusPath = path.join(dir, 'status.json')\nconst st = JSON.parse(fs.readFileSync(statusPath, 'utf8'))\nconst vms = Object.keys(st.vms ?? {})\nfunction writeStatus(patch) {\n  Object.assign(st, patch, { updatedAt: new Date().toISOString() })\n  fs.writeFileSync(statusPath, JSON.stringify(st, null, 2))\n}\nwriteStatus({ phase: 'collecting (recovery)', pid: process.pid })\nif (vms.length === 0) {\n  console.error(\n    'status.json lists no VMs — the run died before measurement; nothing to collect. ' +\n      'Check for a leaked snapshot builder with sandbox-sweep.mjs and relaunch the run.'\n  )\n  process.exit(1)\n}\n\nasync function sb(args) {\n  const scoped = ['sandbox', ...args]\n  const sep = scoped.indexOf('--')\n  scoped.splice(sep < 0 ? scoped.length : sep, 0, ...SCOPE)\n  const { stdout } = await execFileP(CONFIG.vercelBin, scoped, {\n    maxBuffer: 1 << 26,\n  })\n  return stdout\n}\n\nconst pending = new Map(vms.map((vm, i) => [vm, i]))\nconst collected = []\nconst deadline = Date.now() + deadlineMin * 60000\nwhile (pending.size > 0 && Date.now() < deadline) {\n  for (const [vm, idx] of [...pending]) {\n    let out\n    try {\n      out = await sb([\n        'exec',\n        vm,\n        '--timeout',\n        '2m',\n        '--',\n        'bash',\n        '-c',\n        'cat /vercel/sandbox/loop.done 2>/dev/null || echo RUNNING',\n      ])\n    } catch (e) {\n      // VM gone (timed out or removed): its data is lost; say so and move on.\n      console.error(\n        `${vm}: unreachable (${e.message.split('\\n')[0].slice(0, 100)}) — boot lost`\n      )\n      st.vms[vm] = { ...st.vms[vm], state: 'lost' }\n      writeStatus({})\n      pending.delete(vm)\n      continue\n    }\n    const state = out.trim().split('\\n').pop()\n    if (state === 'RUNNING') continue\n    if (state === 'LOOPOK') {\n      const local = path.join(dir, `results-vm${idx}.jsonl`)\n      await sb(['cp', `${vm}:/vercel/sandbox/results.jsonl`, local])\n      if (fs.existsSync(local) && fs.statSync(local).size > 500) {\n        collected.push(local)\n        st.vms[vm] = { ...st.vms[vm], state: 'done' }\n        writeStatus({})\n        console.error(`${vm}: collected -> ${local}`)\n      } else {\n        console.error(`${vm}: results too small; keeping VM for inspection`)\n        pending.delete(vm)\n        continue\n      }\n    } else {\n      const tail = await sb([\n        'exec',\n        vm,\n        '--timeout',\n        '2m',\n        '--',\n        'bash',\n        '-c',\n        'tail -c 1500 /vercel/sandbox/loop.log',\n      ])\n      console.error(`${vm}: loop ended ${state}; log tail:\\n${tail}`)\n    }\n    try {\n      await sb(['rm', vm])\n      console.error(`${vm}: removed`)\n    } catch (e) {\n      console.error(\n        `${vm}: rm failed: ${e.message.split('\\n')[0].slice(0, 100)}`\n      )\n    }\n    pending.delete(vm)\n  }\n  if (pending.size > 0) await new Promise((r) => setTimeout(r, 60000))\n}\nfor (const [vm] of pending)\n  console.error(`${vm}: deadline exceeded, left running`)\n\nif (collected.length === 0) {\n  console.error('nothing collected')\n  process.exit(1)\n}\nwriteStatus({\n  phase: `done (recovered ${collected.length}/${vms.length} boots)`,\n})\nconsole.log(`\\ncollected ${collected.length}/${vms.length} boots; analysis:`)\nconst { stdout } = await execFileP(\n  'node',\n  [\n    path.join(\n      path.dirname(new URL(import.meta.url).pathname),\n      'bench-analyze.mjs'\n    ),\n    dir,\n  ],\n  { maxBuffer: 1 << 24 }\n)\nconsole.log(stdout)\n", "skills/sandbox-bench/scripts/bench-common.mjs": "// Shared core for the sandbox-bench launchers (sandbox-e2e.mjs,\n// sandbox-ssr.mjs): config-derived constants, vercel sandbox plumbing\n// (exec, chunked upload, detached loops), PR/arm resolution with the\n// CI-green gate, cached react arm builds, snapshots, the status.json\n// recovery record, and live interim estimates. Workload-specific code\n// (what runs on a measurement VM) stays in each launcher.\nimport { execFile, spawn } from 'child_process'\nimport { promisify } from 'util'\nimport fs from 'fs'\nimport os from 'os'\nimport path from 'path'\nimport crypto from 'crypto'\nimport {\n  loadConfig,\n  sandboxScope,\n  ensureNextRepo,\n  ensureReactRepo,\n} from './config.mjs'\n\nconst execFileP = promisify(execFile)\nexport { execFileP }\n\nexport const DRY_RUN = process.argv.includes('--dry-run')\nexport const CONFIG = loadConfig({ requireScope: !DRY_RUN })\n// Clones happen on first use: the react one only when a react ref is\n// benched or pinned (pure Next A/B uses each ref's vendored React).\nexport let nextRepoResolved\nexport function NEXT_REPO_LAZY() {\n  if (!nextRepoResolved) nextRepoResolved = ensureNextRepo(CONFIG)\n  return nextRepoResolved\n}\nexport let reactRepoResolved\nexport function REACT_REPO_LAZY() {\n  if (!reactRepoResolved) reactRepoResolved = ensureReactRepo(CONFIG)\n  return reactRepoResolved\n}\nexport const VERCEL = CONFIG.vercelBin\nexport const SCOPE = CONFIG.team ? sandboxScope(CONFIG) : []\nexport const CACHE = path.join(CONFIG.cacheDir, 'e2e')\nexport const REACT_SNAP_CACHE = path.join(CONFIG.cacheDir, 'react-snap')\nexport const SETUP_VERSION = 'v1-al2023-node24-jdk21'\n// Targets build-all-release-channels needs for a sync-react-able arm\n// (both channels, oss-stable + oss-experimental).\nexport const E2E_BUILD_TARGETS =\n  'react/,react.react-server,react-dom/,react-dom.,react-dom-server,scheduler/,react-is,react-server-dom-turbopack,react-server-dom-webpack'\n// owner/repo for CI-artifact lookup, from the configured clone URL.\nexport const REACT_GH_REPO =\n  CONFIG.reactRepoUrl.match(/github\\.com[:/]+([^/]+\\/[^/.]+)/)?.[1] ??\n  'react/react'\nexport const NEXT_GH_REPO =\n  CONFIG.nextRepoUrl.match(/github\\.com[:/]+([^/]+\\/.+?)(?:\\.git)?$/)?.[1] ??\n  'vercel/next.js'\n\n// Recovery record for bench-collect.mjs: if a launcher dies, the\n// remote VMs keep executing their detached loops, and this file names\n// them so the results can still be collected.\nexport const status = { file: null, state: {} }\nexport function writeStatus(patch) {\n  if (!status.file) return\n  status.state = {\n    ...status.state,\n    ...patch,\n    updatedAt: new Date().toISOString(),\n  }\n  try {\n    fs.writeFileSync(status.file, JSON.stringify(status.state, null, 2))\n  } catch {}\n}\n\nexport async function sb(args, opts = {}) {\n  const scoped = ['sandbox', ...args]\n  const sep = scoped.indexOf('--')\n  scoped.splice(sep < 0 ? scoped.length : sep, 0, ...SCOPE)\n  const { stdout, stderr } = await execFileP(VERCEL, scoped, {\n    maxBuffer: 64 * 1024 * 1024,\n    ...opts,\n  })\n  // The CLI prints some results (e.g. snapshot ids) on stderr.\n  return `${stdout}\\n${stderr}`\n}\n\n// The platform rejects single `sandbox cp` uploads somewhere above ~128MB\n// (\"Request Entity Too Large\", observed 2026-07-20; 645MB tree tarballs that\n// uploaded fine hours earlier started failing). Upload large files in parts\n// and reassemble on the VM, verifying the sha256 end to end.\nexport const CP_CHUNK_BYTES = 128 * 1024 * 1024\nexport async function sbCpToVm(vm, localPath, vmDest) {\n  const size = fs.statSync(localPath).size\n  if (size <= CP_CHUNK_BYTES) {\n    await sb(['cp', localPath, `${vm}:${vmDest}`])\n    return\n  }\n  const partDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sbcp-'))\n  try {\n    await execFileP('split', [\n      '-b',\n      String(CP_CHUNK_BYTES),\n      localPath,\n      path.join(partDir, 'part-'),\n    ])\n    const parts = fs.readdirSync(partDir).sort()\n    for (const p of parts) {\n      await sb(['cp', path.join(partDir, p), `${vm}:${vmDest}.${p}`])\n    }\n    const localSha = (\n      await execFileP('shasum', ['-a', '256', localPath])\n    ).stdout.split(' ')[0]\n    const catList = parts.map((p) => `'${vmDest}.${p}'`).join(' ')\n    const out = await sbExec(\n      vm,\n      '10m',\n      `cat ${catList} > '${vmDest}' && rm -f ${catList} && sha256sum '${vmDest}' | cut -d' ' -f1`,\n      `cp:${path.basename(vmDest)}`\n    )\n    // sbExec output interleaves stderr (CLI banners); take the last\n    // sha-shaped token rather than the last line.\n    const shaTokens = out.match(/\\b[0-9a-f]{64}\\b/g)\n    const remoteSha = shaTokens ? shaTokens[shaTokens.length - 1] : ''\n    if (remoteSha !== localSha) {\n      throw new Error(\n        `chunked upload of ${localPath} corrupt: local ${localSha} != remote ${remoteSha}`\n      )\n    }\n  } finally {\n    fs.rmSync(partDir, { recursive: true, force: true })\n  }\n}\n\nexport // PR spec (\"37023\" or a github PR URL) -> arms: base = merge-base of the\n// PR head with upstream main, cand = PR head. Fetched into local refs so\n// git archive / yarn.lock reads work as for any other sha.\nasync function resolvePrArms(pr, repo, repoUrl, defaultBranch) {\n  const num = String(pr).match(/(\\d+)\\/?$/)?.[1]\n  if (!num) throw new Error(`cannot parse PR number from \"${pr}\"`)\n  console.error(`fetching ${repoUrl} PR #${num} + ${defaultBranch}...`)\n  // The clone is shared: concurrent launchers fetching the same ref\n  // race the ref lock. Namespace the temp refs by pid and retry the\n  // fetch (pack files still contend occasionally).\n  const ns = `refs/bench-tmp/${process.pid}`\n  for (let attempt = 1; ; attempt++) {\n    try {\n      await execFileP('git', [\n        '-C',\n        repo,\n        'fetch',\n        '-q',\n        repoUrl,\n        `+refs/pull/${num}/head:${ns}/pr-${num}`,\n        `+refs/heads/${defaultBranch}:${ns}/upstream-${defaultBranch}`,\n      ])\n      break\n    } catch (e) {\n      if (attempt >= 3) throw e\n      console.error(\n        `fetch attempt ${attempt} failed (${e.message.split('\\n')[0].slice(0, 80)}); retrying...`\n      )\n      await new Promise((r) =>\n        setTimeout(r, 5000 * attempt + Math.random() * 5000)\n      )\n    }\n  }\n  const cand = (\n    await execFileP('git', ['-C', repo, 'rev-parse', `${ns}/pr-${num}`])\n  ).stdout.trim()\n  const base = (\n    await execFileP('git', [\n      '-C',\n      repo,\n      'merge-base',\n      `${ns}/upstream-${defaultBranch}`,\n      cand,\n    ])\n  ).stdout.trim()\n  await execFileP('git', [\n    '-C',\n    repo,\n    'update-ref',\n    '-d',\n    `${ns}/pr-${num}`,\n  ]).catch(() => {})\n  await execFileP('git', [\n    '-C',\n    repo,\n    'update-ref',\n    '-d',\n    `${ns}/upstream-${defaultBranch}`,\n  ]).catch(() => {})\n  console.error(\n    `PR #${num}: cand=${cand.slice(0, 12)} base=${base.slice(0, 12)} (merge-base with ${defaultBranch})`\n  )\n  return [\n    { name: 'base', ref: base },\n    { name: `pr${num}`, ref: cand },\n  ]\n}\n\n// Green CI on the react repo is the correctness gate for react arms: a\n// perf number from a broken build is worse than no number. Local or\n// unpushed refs have no CI — --allow-ungated skips the check, and\n// sandbox-gate.mjs exists to gate such refs on a VM instead.\nconst ciVerdicts = new Map()\nexport async function assertCiGreen(sha, armName, allowUngated) {\n  if (!ciVerdicts.has(sha)) {\n    let verdict\n    try {\n      const out = (\n        await execFileP(\n          'gh',\n          [\n            'api',\n            '--paginate',\n            `repos/${REACT_GH_REPO}/commits/${sha}/check-runs?per_page=100`,\n            '--jq',\n            '[.check_runs[] | {name, conclusion}]',\n          ],\n          { maxBuffer: 1 << 24 }\n        )\n      ).stdout\n      const checks = out\n        .trim()\n        .split('\\n')\n        .filter(Boolean)\n        .flatMap((page) => JSON.parse(page))\n      if (checks.length === 0) {\n        verdict = 'no CI runs found (unpushed or unbuilt commit)'\n      } else if (checks.some((c) => c.conclusion === null)) {\n        verdict = 'CI still running — retry when it finishes'\n      } else {\n        // Policy: all tests (including build), flow, and lint must be\n        // green. DevTools suites and repo-infra jobs (artifact syncs,\n        // cleanup, staleness) don't gate benching. Ignore-by-name, so\n        // any NEW job blocks by default instead of being skipped.\n        const IGNORED =\n          /devtools|^cleanup$|^stale$|_artifacts$|^sizebot|^dependabot/i\n        const relevant = checks.filter((c) => !IGNORED.test(c.name))\n        const bad = relevant.filter(\n          (c) =>\n            c.conclusion !== 'success' &&\n            c.conclusion !== 'neutral' &&\n            c.conclusion !== 'skipped'\n        )\n        // Name the offenders: the human deciding whether to proceed\n        // ungated needs to see what failed at a glance, not re-query CI.\n        verdict =\n          bad.length === 0\n            ? 'green'\n            : `CI not green (${bad.length}/${relevant.length} relevant checks): ` +\n              [...new Set(bad.map((c) => `${c.name} (${c.conclusion})`))]\n                .slice(0, 8)\n                .join('; ')\n      }\n    } catch (e) {\n      verdict = `could not query CI (${e.message.split('\\n')[0].slice(0, 80)})`\n    }\n    ciVerdicts.set(sha, verdict)\n  }\n  const verdict = ciVerdicts.get(sha)\n  if (verdict === 'green') {\n    console.error(`arm ${armName}: react ${sha.slice(0, 12)} CI green`)\n    return\n  }\n  if (allowUngated) {\n    console.error(\n      `arm ${armName}: react ${sha.slice(0, 12)} UNGATED (${verdict}) — proceeding per --allow-ungated`\n    )\n    return\n  }\n  throw new Error(\n    `arm ${armName}: react ${sha.slice(0, 12)}: ${verdict}.\\n` +\n      'Benching an unverified build produces untrustworthy numbers. Either wait for/fix CI, ' +\n      'gate the ref yourself (node sandbox-gate.mjs --arms ' +\n      armName +\n      '=<ref>), and then ' +\n      're-run with --allow-ungated, or pass --allow-ungated if you accept the risk.'\n  )\n}\n\nexport async function commitTitle(repo, ref) {\n  try {\n    return (\n      await execFileP('git', ['-C', repo, 'log', '-1', '--format=%s', ref])\n    ).stdout.trim()\n  } catch {\n    return undefined\n  }\n}\n\nexport function printRunContext(out, d) {\n  if (!d) return\n  if (d.pr) out(`PR: ${d.pr.title ? `\"${d.pr.title}\" — ` : ''}${d.pr.url}`)\n  for (const a of d.arms ?? []) if (a.title) out(`  ${a.name}: \"${a.title}\"`)\n}\n\n// Live running estimate, printed as pairs complete across all VMs.\nconst T95 = [\n  12.71, 4.3, 3.18, 2.78, 2.57, 2.45, 2.36, 2.31, 2.26, 2.23, 2.2, 2.18, 2.16,\n  2.14, 2.13,\n]\nexport function makeLive(baseName, metrics, keyOf) {\n  const rows = []\n  return (vm, row) => {\n    rows.push({ vmIdx: vm, ...row })\n    const key = keyOf(row)\n    const other = rows.find(\n      (r) =>\n        r.vmIdx === vm &&\n        keyOf(r) === key &&\n        r.block === row.block &&\n        r.run === row.run &&\n        r.arm !== row.arm\n    )\n    if (!other) return\n    const cands = rows.filter((r) => keyOf(r) === key && r.arm !== baseName)\n    const parts = []\n    let n = 0\n    for (const metric of metrics) {\n      const deltas = []\n      for (const c of cands) {\n        const b = rows.find(\n          (r) =>\n            r.vmIdx === c.vmIdx &&\n            keyOf(r) === key &&\n            r.block === c.block &&\n            r.run === c.run &&\n            r.arm === baseName\n        )\n        if (b && b[metric] > 0) deltas.push((c[metric] - b[metric]) / b[metric])\n      }\n      n = deltas.length\n      if (n < 2) return\n      const mean = deltas.reduce((a, b2) => a + b2, 0) / n\n      const sd = Math.sqrt(\n        deltas.reduce((a, b2) => a + (b2 - mean) ** 2, 0) / (n - 1)\n      )\n      const ci = ((T95[n - 2] ?? 2.0) * sd) / Math.sqrt(n)\n      const p = pairedP(deltas)\n      parts.push(\n        `${metric} ${(mean * 100).toFixed(1)}%±${(ci * 100).toFixed(1)} p=${p.toFixed(3)}`\n      )\n    }\n    console.error(`live ${key} n=${n}: ${parts.join('  ')}`)\n  }\n}\n\nexport function pairedP(deltas) {\n  const n = deltas.length\n  if (n < 2) return 1\n  const mean = deltas.reduce((a, b) => a + b, 0) / n\n  const sd = Math.sqrt(\n    deltas.reduce((a, b) => a + (b - mean) ** 2, 0) / (n - 1)\n  )\n  if (sd === 0) return mean === 0 ? 1 : 0\n  const t = Math.abs(mean / (sd / Math.sqrt(n)))\n  const df = n - 1\n  const pdf = (x) => Math.exp(-((df + 1) / 2) * Math.log(1 + (x * x) / df))\n  let integral = 0\n  const STEP = 0.001\n  for (let x = t; x < t + 60; x += STEP) integral += pdf(x + STEP / 2) * STEP\n  let norm = 0\n  for (let x = 0; x < 80; x += STEP) norm += pdf(x + STEP / 2) * STEP\n  return Math.min(1, integral / norm)\n}\n\nexport function sbExec(vm, timeout, script, tag, onRow) {\n  return new Promise((resolve, reject) => {\n    // The CLI does not reliably propagate the remote exit code (observed\n    // exit 0 after a remote `exit 1`, CLI 56.3.x), so the script reports\n    // its own exit through an EXIT-trap marker; no marker means the\n    // transport died mid-run. Both are failures.\n    const wrapped = `trap 'echo \"@@EXEC_EXIT $?\"' EXIT\n${script}`\n    const child = spawn(\n      VERCEL,\n      [\n        'sandbox',\n        'exec',\n        vm,\n        ...SCOPE,\n        '--timeout',\n        timeout,\n        '--',\n        'bash',\n        '-c',\n        wrapped,\n      ],\n      { stdio: ['ignore', 'pipe', 'pipe'] }\n    )\n    let out = ''\n    let buf = ''\n    child.stdout.on('data', (c) => {\n      out += c\n      buf += c\n      const lines = buf.split('\\n')\n      buf = lines.pop()\n      for (const l of lines) {\n        if (!l) continue\n        if (l.startsWith('ROW ') && onRow) {\n          try {\n            onRow(JSON.parse(l.slice(4)))\n          } catch {}\n        } else {\n          process.stderr.write(`[${tag}] ${l}\\n`)\n        }\n      }\n    })\n    child.stderr.on('data', (c) => {\n      out += c\n      process.stderr.write(\n        String(c)\n          .split('\\n')\n          .filter(Boolean)\n          .map((l) => `[${tag}!] ${l}\\n`)\n          .join('')\n      )\n    })\n    child.on('exit', (code) => {\n      const marker = out.match(/@@EXEC_EXIT (\\d+)\\s*$/m)\n      if (code === 0 && marker && marker[1] === '0') {\n        resolve(out)\n      } else {\n        const why =\n          code !== 0\n            ? `cli exit ${code}`\n            : marker\n              ? `remote exit ${marker[1]}`\n              : 'no exit marker (transport died mid-run)'\n        reject(new Error(`${tag}: ${why}\\n${out.slice(-2000)}`))\n      }\n    })\n  })\n}\n\nexport async function rmVm(name) {\n  try {\n    await sb(['rm', name])\n  } catch (e) {\n    process.stderr.write(`warning: could not remove ${name}: ${e.message}\\n`)\n  }\n}\n\n// Long-running remote work detached from the exec stream (streams drop\n// flakily on multi-minute silences): nohup the script on the VM, then\n// poll its log with short execs. Immune to transport hiccups.\nexport async function runDetached(vm, tag, script, onLine, deadlineMin) {\n  let transcript = ''\n  const local = path.join(os.tmpdir(), `loop-${vm}.sh`)\n  // EXIT trap, not ERR: the ERR trap does not fire for several failure\n  // shapes (e.g. `cmd || (tail; exit 1)`), which left loop.done unwritten\n  // and the poll waiting on heartbeats forever.\n  fs.writeFileSync(\n    local,\n    `trap 'code=$?; if [ $code -eq 0 ]; then echo LOOPOK; else echo LOOPFAIL; fi > /vercel/sandbox/loop.done' EXIT\\nset -e\\n${script}\\n`\n  )\n  await sb(['cp', local, `${vm}:/vercel/sandbox/loop.sh`])\n  fs.rmSync(local, { force: true })\n  await sb([\n    'exec',\n    vm,\n    '--timeout',\n    '2m',\n    '--',\n    'bash',\n    '-c',\n    'rm -f /vercel/sandbox/loop.done /vercel/sandbox/loop.log; nohup bash /vercel/sandbox/loop.sh >/vercel/sandbox/loop.log 2>&1 & echo kicked',\n  ])\n  let offset = 0\n  let failures = 0\n  const deadline = Date.now() + deadlineMin * 60_000\n  while (true) {\n    await new Promise((r) => setTimeout(r, 45_000))\n    if (Date.now() > deadline)\n      throw new Error(`${tag}: detached loop deadline exceeded`)\n    let out\n    try {\n      out = await sb([\n        'exec',\n        vm,\n        '--timeout',\n        '2m',\n        '--',\n        'bash',\n        '-c',\n        `tail -c +${offset + 1} /vercel/sandbox/loop.log | head -c 200000; printf '\\\\n@@SIZE %s @@DONE %s\\\\n' \"$(stat -c %s /vercel/sandbox/loop.log 2>/dev/null || echo 0)\" \"$(cat /vercel/sandbox/loop.done 2>/dev/null || echo no)\"`,\n      ])\n      failures = 0\n    } catch (e) {\n      if (++failures >= 6)\n        throw new Error(\n          `${tag}: ${failures} consecutive poll failures: ${e.message.slice(0, 200)}`\n        )\n      continue\n    }\n    const m = out.match(/@@SIZE (\\d+) @@DONE (\\S+)/)\n    const body = out.slice(0, out.lastIndexOf('\\n@@SIZE'))\n    transcript += body\n    for (const l of body.split('\\n')) {\n      if (!l) continue\n      if (l.startsWith('ROW ') && onLine) {\n        try {\n          onLine(JSON.parse(l.slice(4)))\n        } catch {}\n      } else {\n        process.stderr.write(`[${tag}] ${l}\\n`)\n      }\n    }\n    if (m) {\n      offset = Math.min(Number(m[1]), offset + 200000)\n      if (m[2] === 'LOOPOK') return transcript\n      if (m[2] === 'LOOPFAIL')\n        throw new Error(\n          `${tag}: remote loop failed; tail:\\n${body.slice(-1500)}`\n        )\n    }\n  }\n}\n\n// ------------------------------------------------------------ snapshots\n\nexport async function sha256(text) {\n  return crypto.createHash('sha256').update(text).digest('hex').slice(0, 16)\n}\n\nexport async function snapshotIdFor(cacheDir, key) {\n  const file = path.join(cacheDir, `snap-${key}`)\n  if (!fs.existsSync(file)) return undefined\n  const id = fs.readFileSync(file, 'utf8').trim()\n  try {\n    await sb(['snapshots', 'get', id])\n    return id\n  } catch {\n    return undefined\n  }\n}\n\nexport async function takeSnapshot(vm, cacheDir, key) {\n  const out = await sb(['snapshot', vm, '--stop', '--expiration', '30d'])\n  const id = out.match(/snap_[A-Za-z0-9]+/)?.[0]\n  if (!id)\n    throw new Error(`could not parse snapshot id from: ${out.slice(-500)}`)\n  fs.mkdirSync(cacheDir, { recursive: true })\n  fs.writeFileSync(path.join(cacheDir, `snap-${key}`), `${id}\\n`)\n  console.error(`snapshot ${id} cached (${key})`)\n  return id\n}\n\n// React build environment (repo + node_modules + JDK), shared with\n// sandbox-ab.mjs. Keyed on the arm's yarn.lock.\nexport async function ensureReactBuildSnapshot(refSha) {\n  const lock = await execFileP(\n    'git',\n    ['-C', REACT_REPO_LAZY(), 'show', `${refSha}:yarn.lock`],\n    { maxBuffer: 1 << 28 }\n  )\n  const key = await sha256(SETUP_VERSION + lock.stdout)\n  let id = await snapshotIdFor(REACT_SNAP_CACHE, key)\n  if (id) return id\n  const vm = `react-snap-build-${Date.now().toString(36)}`\n  console.error(\n    `creating react build-env snapshot (one-time for this yarn.lock)...`\n  )\n  await sb([\n    'create',\n    '--name',\n    vm,\n    '--runtime',\n    'node24',\n    '--vcpus',\n    '8',\n    '--timeout',\n    '45m',\n    '--non-persistent',\n    '--network-policy',\n    'allow-all',\n    '--tag',\n    'purpose=sandbox-bench',\n    '--silent',\n  ])\n  try {\n    const src = path.join(os.tmpdir(), `react-snap-src-${key}.tgz`)\n    await execFileP('bash', [\n      '-c',\n      `git -C ${REACT_REPO_LAZY()} archive ${refSha} | gzip -1 > ${src}`,\n    ])\n    await sb(['cp', src, `${vm}:/vercel/sandbox/src.tgz`])\n    fs.rmSync(src, { force: true })\n    await sb([\n      'exec',\n      vm,\n      '--timeout',\n      '10m',\n      '--sudo',\n      '--',\n      'dnf',\n      'install',\n      '-y',\n      '-q',\n      'java-21-amazon-corretto-headless',\n    ])\n    await sbExec(\n      vm,\n      '20m',\n      `set -e; mkdir -p /vercel/sandbox/react && cd /vercel/sandbox/react && tar -xzf ../src.tgz && rm -f ../src.tgz && ` +\n        `npm i -g yarn >/dev/null 2>&1 && yarn install --frozen-lockfile --ignore-engines >/dev/null 2>&1 && echo react env ready`,\n      'react-snap'\n    )\n    return await takeSnapshot(vm, REACT_SNAP_CACHE, key)\n  } finally {\n    await rmVm(vm)\n  }\n}\n\n// React CI builds every upstream commit and PR; reuse those artifacts\n// instead of building. Requires gh auth. Returns false -> build remotely.\nexport async function tryCiArtifactArm(sha, cached, pack) {\n  try {\n    const runs = JSON.parse(\n      (\n        await execFileP(\n          'gh',\n          [\n            'api',\n            `repos/${REACT_GH_REPO}/actions/workflows/runtime_build_and_test.yml/runs?head_sha=${sha}&per_page=5`,\n          ],\n          { maxBuffer: 1 << 24 }\n        )\n      ).stdout\n    )\n    const id = runs.workflow_runs?.find((r) => r.head_sha === sha)?.id\n    if (!id) return false\n    const arts = JSON.parse(\n      (\n        await execFileP(\n          'gh',\n          [\n            'api',\n            `repos/${REACT_GH_REPO}/actions/runs/${id}/artifacts?name=artifacts_combined`,\n          ],\n          { maxBuffer: 1 << 24 }\n        )\n      ).stdout\n    )\n    const art = arts.artifacts?.find(\n      (a) => a.name === 'artifacts_combined' && !a.expired\n    )\n    if (!art) return false\n    console.error(\n      `downloading CI artifacts for ${sha.slice(0, 12)} (run ${id})...`\n    )\n    const work = fs.mkdtempSync(path.join(os.tmpdir(), 'ci-arm-'))\n    try {\n      await execFileP(\n        'bash',\n        [\n          '-c',\n          `cd ${work} && gh api repos/${REACT_GH_REPO}/actions/artifacts/${art.id}/zip > a.zip && ` +\n            `unzip -q a.zip && tar -xzf build.tgz && ${pack}`,\n        ],\n        { maxBuffer: 1 << 24 }\n      )\n    } finally {\n      fs.rmSync(work, { recursive: true, force: true })\n    }\n    return fs.existsSync(cached) && fs.statSync(cached).size > 1 << 20\n  } catch (e) {\n    console.error(\n      `CI artifact lookup failed (${e.message.slice(0, 100)}); building remotely`\n    )\n    return false\n  }\n}\n\n// Ref arms build remotely (dual-channel yarn build) and cache by sha.\nexport async function ensureRefArm(arm) {\n  const sha = (\n    await execFileP('git', ['-C', REACT_REPO_LAZY(), 'rev-parse', arm.ref])\n  ).stdout.trim()\n  arm.sha = sha\n  // Key on the build recipe too: a changed target list must not serve\n  // stale artifacts from the shared cache.\n  const recipe = crypto\n    .createHash('sha256')\n    .update(E2E_BUILD_TARGETS)\n    .digest('hex')\n    .slice(0, 6)\n  const cached = path.join(CACHE, `arm-${sha.slice(0, 12)}-${recipe}.tgz`)\n  arm.tgz = cached\n  if (fs.existsSync(cached)) {\n    console.error(`arm ${arm.name}=${sha.slice(0, 12)} (cached build)`)\n    return\n  }\n  fs.mkdirSync(CACHE, { recursive: true })\n  if (\n    await tryCiArtifactArm(\n      sha,\n      cached,\n      `tar -czf ${cached} build/oss-stable build/oss-experimental`\n    )\n  ) {\n    console.error(`arm ${arm.name}=${sha.slice(0, 12)} from CI artifacts`)\n    return\n  }\n  const snap = await ensureReactBuildSnapshot(sha)\n  const vm = `sbench-armbuild-${Date.now().toString(36)}`\n  console.error(\n    `building react arm ${arm.name}=${sha.slice(0, 12)} remotely...`\n  )\n  await sb([\n    'create',\n    '--name',\n    vm,\n    '--snapshot',\n    snap,\n    '--vcpus',\n    '8',\n    '--timeout',\n    '45m',\n    '--non-persistent',\n    '--network-policy',\n    'allow-all',\n    '--tag',\n    'purpose=sandbox-bench',\n    '--silent',\n  ])\n  try {\n    // build-all-release-channels stamps versions from git (sha + commit\n    // date), so the upload must be a real shallow checkout, not a bare\n    // archive.\n    const src = path.join(os.tmpdir(), `arm-src-${sha.slice(0, 12)}.tgz`)\n    const work = fs.mkdtempSync(path.join(os.tmpdir(), 'arm-git-'))\n    const tmpRef = `refs/bench-tmp/${sha.slice(0, 12)}`\n    await execFileP('git', ['-C', REACT_REPO_LAZY(), 'update-ref', tmpRef, sha])\n    try {\n      await execFileP('git', ['init', '-q', work])\n      await execFileP('git', [\n        '-C',\n        work,\n        'fetch',\n        '-q',\n        '--depth',\n        '1',\n        REACT_REPO_LAZY(),\n        tmpRef,\n      ])\n      await execFileP('git', ['-C', work, 'checkout', '-q', 'FETCH_HEAD'])\n      await execFileP('bash', [\n        '-c',\n        `cd ${work} && COPYFILE_DISABLE=1 tar --no-xattrs -czf ${src} .`,\n      ])\n    } finally {\n      await execFileP('git', [\n        '-C',\n        REACT_REPO_LAZY(),\n        'update-ref',\n        '-d',\n        tmpRef,\n      ])\n      fs.rmSync(work, { recursive: true, force: true })\n    }\n    await sb(['cp', src, `${vm}:/vercel/sandbox/src.tgz`])\n    fs.rmSync(src, { force: true })\n    // The exec stream drops on long silent commands; heartbeat keeps it\n    // alive during the ~10min dual-channel build. Newline before the\n    // backgrounded heartbeat: a trailing & after && backgrounds the\n    // whole chain.\n    await sbExec(\n      vm,\n      '40m',\n      `set -e\nls /vercel/sandbox/react/node_modules >/dev/null\ncd /vercel/sandbox/react\nfind . -mindepth 1 -maxdepth 1 ! -name node_modules -exec rm -rf {} +\ntar -xzf ../src.tgz\ngit rev-parse HEAD\n(while true; do echo \"hb mem=$(free -m | awk '/^Mem/{print $3}')MB $(tail -1 /tmp/build.log 2>/dev/null | cut -c1-60)\"; sleep 30; done) & HB=$!\nyarn build \"${E2E_BUILD_TARGETS}\" >/tmp/build.log 2>&1 || (kill $HB; tail -20 /tmp/build.log; exit 1)\nkill $HB\ntar -czf /vercel/sandbox/arm.tgz build/oss-stable build/oss-experimental\necho arm built`,\n      `armbuild:${arm.name}`\n    )\n    fs.mkdirSync(CACHE, { recursive: true })\n    const armTmp = `${cached}.tmp-${process.pid}`\n    await sb(['cp', `${vm}:/vercel/sandbox/arm.tgz`, armTmp])\n    if (fs.existsSync(armTmp)) fs.renameSync(armTmp, cached)\n    // sandbox cp does not reliably fail on missing remote files.\n    if (!fs.existsSync(cached) || fs.statSync(cached).size < 1 << 20) {\n      fs.rmSync(cached, { force: true })\n      throw new Error(\n        `arm ${arm.name}: downloaded artifact missing or too small`\n      )\n    }\n    console.error(`cached ${cached}`)\n  } finally {\n    await rmVm(vm)\n  }\n}\n", "skills/sandbox-bench/scripts/bench-db.mjs": "#!/usr/bin/env node\n// Canonical store for all bench data: one SQLite file holding raw\n// measurements and artifacts, written only by this importer — no\n// derived statistics, no hand-entered numbers. The per-VM JSONL files\n// in a run dir are the wire format; importing is idempotent (a run\n// re-imports as a whole). Stats are a pure function of this DB\n// (bench-analyze.mjs reads it and nothing else).\n//\n//   node bench-db.mjs import <runDir...>\n//   node bench-db.mjs verify [runId]\n//   node bench-db.mjs export <out.db> <runId...>\n//   node bench-db.mjs ls\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport zlib from 'node:zlib'\nimport crypto from 'node:crypto'\nimport { execFileSync } from 'node:child_process'\nimport { DatabaseSync } from 'node:sqlite'\nimport { loadConfig } from './config.mjs'\n\nconst SCHEMA = `\nPRAGMA journal_mode=WAL;\nPRAGMA foreign_keys=ON;\nCREATE TABLE IF NOT EXISTS runs(\n  run_id      TEXT PRIMARY KEY,\n  label       TEXT,\n  kind        TEXT,\n  started_at  TEXT,\n  imported_at TEXT NOT NULL,\n  harness_sha TEXT,\n  meta        TEXT\n);\nCREATE TABLE IF NOT EXISTS samples(\n  sample_id   INTEGER PRIMARY KEY,\n  run_id      TEXT NOT NULL REFERENCES runs(run_id) ON DELETE CASCADE,\n  boot        INTEGER NOT NULL,\n  arm         TEXT NOT NULL,\n  block       INTEGER NOT NULL,\n  run         INTEGER NOT NULL,\n  route       TEXT NOT NULL,\n  phase       TEXT NOT NULL,\n  fingerprint TEXT,\n  version     TEXT,\n  cpu         TEXT,\n  errors      INTEGER NOT NULL DEFAULT 0,\n  UNIQUE(run_id, boot, arm, block, run, route, phase)\n);\nCREATE TABLE IF NOT EXISTS measurements(\n  sample_id   INTEGER NOT NULL REFERENCES samples(sample_id) ON DELETE CASCADE,\n  metric      TEXT NOT NULL,\n  value       REAL NOT NULL,\n  UNIQUE(sample_id, metric)\n);\nCREATE TABLE IF NOT EXISTS artifacts(\n  artifact_id INTEGER PRIMARY KEY,\n  run_id      TEXT NOT NULL REFERENCES runs(run_id) ON DELETE CASCADE,\n  boot        INTEGER,\n  arm         TEXT,\n  name        TEXT NOT NULL,\n  kind        TEXT,\n  sha256      TEXT NOT NULL,\n  bytes       INTEGER NOT NULL,\n  data        BLOB NOT NULL,\n  UNIQUE(run_id, boot, arm, name)\n);\nCREATE TABLE IF NOT EXISTS boots(\n  run_id  TEXT NOT NULL REFERENCES runs(run_id) ON DELETE CASCADE,\n  boot    INTEGER NOT NULL,\n  vm_name TEXT,\n  UNIQUE(run_id, boot)\n);\nCREATE TABLE IF NOT EXISTS source_files(\n  run_id TEXT NOT NULL REFERENCES runs(run_id) ON DELETE CASCADE,\n  name   TEXT NOT NULL,\n  sha256 TEXT NOT NULL,\n  rows   INTEGER NOT NULL,\n  UNIQUE(run_id, name)\n);\nCREATE INDEX IF NOT EXISTS idx_samples_run ON samples(run_id);\nCREATE INDEX IF NOT EXISTS idx_measurements_sample ON measurements(sample_id);\nCREATE INDEX IF NOT EXISTS idx_artifacts_run ON artifacts(run_id);\n`\n\n// Row fields that identify a sample; every OTHER numeric field in a\n// JSONL row is a measurement. New metrics therefore need no schema or\n// importer change.\nconst IDENT = new Set([\n  'vm',\n  'arm',\n  'block',\n  'run',\n  'route',\n  'phase',\n  'fp',\n  'ver',\n  'cpu',\n  'errors',\n  'payload',\n  'round',\n])\n\nexport function dbPath() {\n  return path.join(loadConfig({ requireScope: false }).cacheDir, 'results.db')\n}\n\nexport function openDb(file = dbPath()) {\n  fs.mkdirSync(path.dirname(file), { recursive: true })\n  const db = new DatabaseSync(file)\n  db.exec(SCHEMA)\n  return db\n}\n\nfunction harnessSha() {\n  try {\n    return execFileSync(\n      'git',\n      [\n        '-C',\n        path.dirname(new URL(import.meta.url).pathname),\n        'rev-parse',\n        'HEAD',\n      ],\n      { encoding: 'utf8' }\n    ).trim()\n  } catch {\n    return null\n  }\n}\n\nfunction artifactKind(name) {\n  if (name.endsWith('.cpuprofile')) return 'cpuprofile'\n  if (name.endsWith('.json')) return 'json'\n  if (name.endsWith('.log') || name.endsWith('.txt')) return 'log'\n  return 'file'\n}\n\nfunction walk(dir) {\n  const out = []\n  for (const e of fs.readdirSync(dir, { withFileTypes: true })) {\n    const p = path.join(dir, e.name)\n    if (e.isDirectory()) out.push(...walk(p))\n    else if (e.isFile()) out.push(p)\n  }\n  return out\n}\n\n// Import one run dir: replaces the run's rows wholesale so re-imports\n// (recovery, added boots, new artifacts) converge on the same state.\n// A re-import that would SHRINK a run (fewer boots or samples than the\n// db already holds — e.g. a cleaned-up run dir) is refused without\n// force: claims must never silently lose data underneath them.\nexport function importRun(db, dir, { force = false } = {}) {\n  const runId = path.basename(path.resolve(dir))\n  const files = fs\n    .readdirSync(dir)\n    .filter((f) => /^results-vm\\d+\\.jsonl$/.test(f))\n    .sort()\n    .map((f) => path.join(dir, f))\n  if (files.length === 0) throw new Error(`no results-vm*.jsonl in ${dir}`)\n  const readJson = (f) => {\n    try {\n      return JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8'))\n    } catch {\n      return null\n    }\n  }\n  const meta = readJson('meta.json')\n  const status = readJson('status.json')\n  const prev = db\n    .prepare(\n      'SELECT COUNT(DISTINCT boot) boots, COUNT(*) n FROM samples WHERE run_id = ?'\n    )\n    .get(runId)\n  db.exec('BEGIN')\n  try {\n    db.prepare('DELETE FROM runs WHERE run_id = ?').run(runId)\n    let kind = 'e2e'\n    const insSample = db.prepare(`INSERT INTO samples\n      (run_id, boot, arm, block, run, route, phase, fingerprint, version, cpu, errors)\n      VALUES (?,?,?,?,?,?,?,?,?,?,?)`)\n    const insMeas = db.prepare(\n      'INSERT INTO measurements (sample_id, metric, value) VALUES (?,?,?)'\n    )\n    let samples = 0\n    let pendingRows = []\n    const fileInfos = []\n    for (const [boot, file] of files.entries()) {\n      const content = fs.readFileSync(file, 'utf8')\n      let fileRows = 0\n      for (const line of content.trim().split('\\n')) {\n        if (!line) continue\n        const row = JSON.parse(line)\n        const micro = row.payload !== undefined\n        if (micro) kind = 'micro'\n        pendingRows.push({ boot, row, micro })\n        fileRows++\n      }\n      fileInfos.push({\n        boot,\n        name: path.basename(file),\n        sha256: crypto.createHash('sha256').update(content).digest('hex'),\n        rows: fileRows,\n      })\n    }\n    if (\n      !force &&\n      prev.n > 0 &&\n      (files.length < prev.boots || pendingRows.length < prev.n)\n    ) {\n      throw new Error(\n        `re-import of ${runId} would shrink it ` +\n          `(${prev.boots} boots/${prev.n} samples in db, ` +\n          `${files.length} boots/${pendingRows.length} samples in ${dir}) — ` +\n          'pass --force only if the db copy is known bad'\n      )\n    }\n    db.prepare(\n      `INSERT INTO runs\n      (run_id, label, kind, started_at, imported_at, harness_sha, meta)\n      VALUES (?,?,?,?,?,?,?)`\n    ).run(\n      runId,\n      meta?.label ?? runId.replace(/^run-/, '').replace(/-[a-z0-9]+$/, ''),\n      kind,\n      status?.startedAt ?? null,\n      new Date().toISOString(),\n      harnessSha(),\n      meta ? JSON.stringify(meta) : null\n    )\n    // Provenance: which sandbox VM produced each boot (from\n    // status.json, matched by the index in the VM name), and the exact\n    // bytes each boot's JSONL contributed.\n    const vmByIndex = new Map()\n    for (const name of Object.keys(status?.vms ?? {})) {\n      const idx = name.match(/-(\\d+)-[a-z0-9]+$/)?.[1]\n      if (idx !== undefined) vmByIndex.set(Number(idx), name)\n    }\n    const insBoot = db.prepare(\n      'INSERT INTO boots (run_id, boot, vm_name) VALUES (?,?,?)'\n    )\n    const insFile = db.prepare(\n      'INSERT INTO source_files (run_id, name, sha256, rows) VALUES (?,?,?,?)'\n    )\n    for (const f of fileInfos) {\n      const n = Number(f.name.match(/^results-vm(\\d+)\\.jsonl$/)?.[1])\n      insBoot.run(runId, f.boot, vmByIndex.get(n) ?? null)\n      insFile.run(runId, f.name, f.sha256, f.rows)\n    }\n    for (const { boot, row, micro } of pendingRows) {\n      const { lastInsertRowid: sid } = insSample.run(\n        runId,\n        boot,\n        row.arm,\n        micro ? 0 : (row.block ?? 0),\n        micro ? (row.round ?? 0) : (row.run ?? 0),\n        micro ? '' : (row.route ?? ''),\n        micro ? row.payload : row.phase,\n        row.fp ?? null,\n        row.ver ?? null,\n        row.cpu ?? null,\n        row.errors ?? 0\n      )\n      samples++\n      for (const [k, v] of Object.entries(row)) {\n        if (IDENT.has(k)) continue\n        if (typeof v !== 'number' || !Number.isFinite(v)) continue\n        insMeas.run(sid, k, v)\n      }\n    }\n    // Artifacts: everything under prof-vm<N>/ (CPU profiles etc.),\n    // stored gzipped with the sha256 of the RAW content.\n    const insArt = db.prepare(`INSERT INTO artifacts\n      (run_id, boot, arm, name, kind, sha256, bytes, data) VALUES (?,?,?,?,?,?,?,?)`)\n    let artifacts = 0\n    for (const e of fs.readdirSync(dir)) {\n      const m = e.match(/^prof-vm(\\d+)$/)\n      if (!m) continue\n      const boot = Number(m[1])\n      for (const f of walk(path.join(dir, e))) {\n        const rel = path.relative(path.join(dir, e), f)\n        const arm = rel.match(/^prof-([^/]+)\\//)?.[1] ?? null\n        const raw = fs.readFileSync(f)\n        insArt.run(\n          runId,\n          boot,\n          arm,\n          rel,\n          artifactKind(rel),\n          crypto.createHash('sha256').update(raw).digest('hex'),\n          raw.length,\n          zlib.gzipSync(raw)\n        )\n        artifacts++\n      }\n    }\n    db.exec('COMMIT')\n    return { runId, boots: files.length, samples, artifacts }\n  } catch (e) {\n    db.exec('ROLLBACK')\n    throw e\n  }\n}\n\n// Rows for bench-stats.analyzeE2eRows, reconstructed from the DB —\n// the stats layer never reads run dirs.\nexport function loadRows(db, runId) {\n  const samples = db\n    .prepare('SELECT * FROM samples WHERE run_id = ?')\n    .all(runId)\n  if (samples.length === 0) throw new Error(`no samples for run ${runId}`)\n  const meas = db\n    .prepare(\n      `SELECT m.sample_id, m.metric, m.value FROM measurements m\n    JOIN samples s ON s.sample_id = m.sample_id WHERE s.run_id = ?`\n    )\n    .all(runId)\n  const byId = new Map()\n  for (const s of samples) {\n    byId.set(s.sample_id, {\n      vm: Number(s.boot),\n      arm: s.arm,\n      block: Number(s.block),\n      run: Number(s.run),\n      route: s.route,\n      phase: s.phase,\n      fp: s.fingerprint,\n      ver: s.version,\n      errors: Number(s.errors),\n    })\n  }\n  for (const m of meas) byId.get(m.sample_id)[m.metric] = m.value\n  return [...byId.values()]\n}\n\nexport function runMeta(db, runId) {\n  const r = db.prepare('SELECT * FROM runs WHERE run_id = ?').get(runId)\n  return r ? { ...r, meta: r.meta ? JSON.parse(r.meta) : null } : null\n}\n\n// Integrity checks. Everything here is mechanical: SQLite-level\n// integrity, referential health, per-run shape (one fingerprint per\n// arm, paired sample counts), and artifact hashes. Failures are\n// data-integrity violations; notes are true facts a reader must not\n// gloss over (e.g. a recovered run that is legitimately partial).\nexport function verify(db, runId) {\n  const problems = []\n  const notes = []\n  const ic = db.prepare('PRAGMA integrity_check').all()\n  if (!(ic.length === 1 && ic[0].integrity_check === 'ok')) {\n    problems.push(`sqlite integrity_check: ${JSON.stringify(ic)}`)\n  }\n  const fk = db.prepare('PRAGMA foreign_key_check').all()\n  if (fk.length > 0) problems.push(`foreign_key_check: ${fk.length} violations`)\n  const runs = runId\n    ? db.prepare('SELECT run_id FROM runs WHERE run_id = ?').all(runId)\n    : db.prepare('SELECT run_id FROM runs').all()\n  if (runId && runs.length === 0) problems.push(`run ${runId} not in db`)\n  for (const { run_id } of runs) {\n    const orphanSamples = db\n      .prepare(\n        `SELECT COUNT(*) c FROM samples s\n      WHERE s.run_id = ? AND NOT EXISTS\n      (SELECT 1 FROM measurements m WHERE m.sample_id = s.sample_id)`\n      )\n      .get(run_id).c\n    if (orphanSamples > 0) {\n      problems.push(`${run_id}: ${orphanSamples} samples with no measurements`)\n    }\n    const arms = db\n      .prepare(\n        `SELECT arm, COUNT(DISTINCT COALESCE(fingerprint,'') ||\n      '/' || COALESCE(version,'')) fps, COUNT(*) n\n      FROM samples WHERE run_id = ? GROUP BY arm`\n      )\n      .all(run_id)\n    if (arms.length !== 2) {\n      problems.push(`${run_id}: expected 2 arms, found ${arms.length}`)\n    }\n    for (const a of arms) {\n      if (a.fps > 1) {\n        problems.push(\n          `${run_id}: arm ${a.arm} has ${a.fps} distinct fingerprints`\n        )\n      }\n    }\n    const planned = (() => {\n      try {\n        return JSON.parse(\n          db.prepare('SELECT meta FROM runs WHERE run_id = ?').get(run_id).meta\n        ).vms\n      } catch {\n        return undefined\n      }\n    })()\n    const gotBoots = db\n      .prepare('SELECT COUNT(DISTINCT boot) c FROM samples WHERE run_id = ?')\n      .get(run_id).c\n    if (planned && gotBoots < planned) {\n      notes.push(`${run_id}: partial run (${gotBoots}/${planned} boots)`)\n    }\n    if (arms.length === 2 && arms[0].n !== arms[1].n) {\n      problems.push(\n        `${run_id}: unpaired sample counts ` +\n          `(${arms[0].arm}=${arms[0].n} vs ${arms[1].arm}=${arms[1].n})`\n      )\n    }\n    for (const art of db\n      .prepare(\n        'SELECT artifact_id, name, sha256, bytes, data FROM artifacts WHERE run_id = ?'\n      )\n      .all(run_id)) {\n      const raw = zlib.gunzipSync(art.data)\n      if (\n        raw.length !== Number(art.bytes) ||\n        crypto.createHash('sha256').update(raw).digest('hex') !== art.sha256\n      ) {\n        problems.push(`${run_id}: artifact ${art.name} fails hash/size check`)\n      }\n    }\n  }\n  return { failures: problems, notes }\n}\n\nexport function exportRuns(db, outFile, runIds) {\n  fs.rmSync(outFile, { force: true })\n  const out = openDb(outFile)\n  const copy = (table, cols) => {\n    const ins = out.prepare(`INSERT INTO ${table} (${cols.join(',')})\n      VALUES (${cols.map(() => '?').join(',')})`)\n    return (row) => ins.run(...cols.map((c) => row[c]))\n  }\n  out.exec('BEGIN')\n  const copyRun = copy('runs', [\n    'run_id',\n    'label',\n    'kind',\n    'started_at',\n    'imported_at',\n    'harness_sha',\n    'meta',\n  ])\n  const copySample = copy('samples', [\n    'sample_id',\n    'run_id',\n    'boot',\n    'arm',\n    'block',\n    'run',\n    'route',\n    'phase',\n    'fingerprint',\n    'version',\n    'cpu',\n    'errors',\n  ])\n  const copyMeas = copy('measurements', ['sample_id', 'metric', 'value'])\n  const copyBoot = copy('boots', ['run_id', 'boot', 'vm_name'])\n  const copyFile = copy('source_files', ['run_id', 'name', 'sha256', 'rows'])\n  const copyArt = copy('artifacts', [\n    'run_id',\n    'boot',\n    'arm',\n    'name',\n    'kind',\n    'sha256',\n    'bytes',\n    'data',\n  ])\n  for (const runId of runIds) {\n    const run = db.prepare('SELECT * FROM runs WHERE run_id = ?').get(runId)\n    if (!run) throw new Error(`run ${runId} not in db`)\n    copyRun(run)\n    for (const s of db\n      .prepare('SELECT * FROM samples WHERE run_id = ?')\n      .all(runId)) {\n      copySample(s)\n      for (const m of db\n        .prepare('SELECT * FROM measurements WHERE sample_id = ?')\n        .all(s.sample_id)) {\n        copyMeas(m)\n      }\n    }\n    for (const a of db\n      .prepare('SELECT * FROM artifacts WHERE run_id = ?')\n      .all(runId)) {\n      copyArt(a)\n    }\n    for (const b of db\n      .prepare('SELECT * FROM boots WHERE run_id = ?')\n      .all(runId)) {\n      copyBoot(b)\n    }\n    for (const f of db\n      .prepare('SELECT * FROM source_files WHERE run_id = ?')\n      .all(runId)) {\n      copyFile(f)\n    }\n  }\n  out.exec('COMMIT')\n  out.close()\n}\n\n// ------------------------------------------------------------------ CLI\nfunction isMain() {\n  if (!process.argv[1]) return false\n  try {\n    return (\n      fs.realpathSync(process.argv[1]) ===\n      fs.realpathSync(new URL(import.meta.url).pathname)\n    )\n  } catch {\n    return false\n  }\n}\nif (isMain()) {\n  const [cmd, ...rest] = process.argv.slice(2)\n  const db = openDb()\n  const report = ({ failures, notes }, label) => {\n    for (const n of notes) console.log(`note: ${n}`)\n    if (failures.length) {\n      console.error(`VERIFY FAILED:\\n  ${failures.join('\\n  ')}`)\n      process.exit(1)\n    }\n    console.log(`verify: ok${label ? ` (${label})` : ''}`)\n  }\n  if (cmd === 'import') {\n    const force = rest.includes('--force')\n    const dirs = rest.filter((a) => a !== '--force')\n    if (dirs.length === 0) {\n      console.error('usage: bench-db.mjs import [--force] <runDir...>')\n      process.exit(1)\n    }\n    for (const dir of dirs) {\n      let r\n      try {\n        r = importRun(db, dir, { force })\n      } catch (e) {\n        console.error(`IMPORT REFUSED: ${e.message}`)\n        process.exit(1)\n      }\n      console.log(\n        `${r.runId}: ${r.boots} boots, ${r.samples} samples, ${r.artifacts} artifacts`\n      )\n    }\n    report(verify(db))\n  } else if (cmd === 'verify') {\n    report(verify(db, rest[0]), rest[0] ?? 'all runs')\n  } else if (cmd === 'export') {\n    const [out, ...ids] = rest\n    if (!out || ids.length === 0) {\n      console.error('usage: bench-db.mjs export <out.db> <runId...>')\n      process.exit(1)\n    }\n    exportRuns(db, out, ids)\n    console.log(`${out}: ${ids.length} runs`)\n  } else if (cmd === 'ls') {\n    for (const r of db\n      .prepare(\n        `SELECT r.run_id, r.kind, r.started_at,\n      (SELECT COUNT(DISTINCT boot) FROM samples s WHERE s.run_id = r.run_id) boots,\n      (SELECT COUNT(*) FROM samples s WHERE s.run_id = r.run_id) samples,\n      (SELECT COUNT(*) FROM artifacts a WHERE a.run_id = r.run_id) artifacts\n      FROM runs r ORDER BY r.started_at`\n      )\n      .all()) {\n      console.log(\n        `${r.run_id}  ${r.kind}  boots=${r.boots} samples=${r.samples} artifacts=${r.artifacts}  ${r.started_at ?? ''}`\n      )\n    }\n  } else {\n    console.error('usage: bench-db.mjs import|verify|export|ls')\n    process.exit(1)\n  }\n}\n", "skills/sandbox-bench/scripts/bench-stats.mjs": "// Shared statistics for the sandbox bench harnesses.\n//\n// Unit of analysis: the VM BOOT. Iterations within a boot share JIT\n// state, heap layout, host, and phase-sequence position, so they are\n// not independent samples (Kalibera & Jones, \"Rigorous Benchmarking in\n// Reasonable Time\"; JMH forks). Each boot contributes ONE delta per\n// metric (the mean of its paired within-boot deltas); confidence\n// intervals and p-values are computed across boots. Within-boot\n// statistics are printed as a diagnostic only — never as the claim.\n\n// Two-sided critical values of Student's t at 97.5% (df 1..30).\nconst T975 = [\n  12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201,\n  2.179, 2.16, 2.145, 2.131, 2.12, 2.11, 2.101, 2.093, 2.086, 2.08, 2.074,\n  2.069, 2.064, 2.06, 2.056, 2.052, 2.048, 2.045, 2.042,\n]\n\nfunction tCritical975(df) {\n  if (df < 1) return Infinity\n  if (df <= 30) return T975[df - 1]\n  return 1.96 + 2.4 / df // adequate approximation past df=30\n}\n\n// Two-sided p for a one-sample t test against zero, via numerical\n// integration of the t pdf (small-df accuracy is what matters here —\n// boots are few).\nexport function tTestP(values) {\n  const n = values.length\n  if (n < 2) return 1\n  if (values.some((v) => !Number.isFinite(v))) return 1\n  const mean = values.reduce((a, b) => a + b, 0) / n\n  const sd = Math.sqrt(\n    values.reduce((a, b) => a + (b - mean) ** 2, 0) / (n - 1)\n  )\n  if (sd === 0) return mean === 0 ? 1 : 0\n  const t = Math.abs(mean / (sd / Math.sqrt(n)))\n  const df = n - 1\n  if (df === 1) {\n    // Student t with df=1 is Cauchy; the closed form avoids the fat\n    // tail truncating a numerical integration.\n    return Math.min(1, Math.max(0, 1 - (2 / Math.PI) * Math.atan(t)))\n  }\n  if (!Number.isFinite(t) || t > 45) {\n    // p underflows well past any claim threshold; also guards the\n    // integration loop below, whose step size vanishes against huge t.\n    return 0\n  }\n  const pdf = (x) => Math.exp(-((df + 1) / 2) * Math.log(1 + (x * x) / df))\n  let integral = 0\n  const STEP = 0.001\n  for (let x = t; x < t + 60; x += STEP) integral += pdf(x + STEP / 2) * STEP\n  let norm = 0\n  for (let x = 0; x < 80; x += STEP) norm += pdf(x + STEP / 2) * STEP\n  return Math.min(1, integral / norm)\n}\n\n// Anytime-valid confidence sequence for a running mean (asymptotic CS,\n// Waudby-Smith & Ramdas). Unlike a t-CI, this interval is valid at\n// EVERY peek simultaneously, so interim displays built on it cannot\n// manufacture significance through repeated looking. Tuned to be\n// tightest around ~12 boots.\nexport function confidenceSeq(values, alpha = 0.05) {\n  const n = values.length\n  // Below 6 samples the estimated variance is too unstable for the\n  // asymptotic guarantee; show nothing rather than something wrong.\n  if (n < 6) return null\n  const mean = values.reduce((a, b) => a + b, 0) / n\n  let sd = Math.sqrt(values.reduce((a, b) => a + (b - mean) ** 2, 0) / (n - 1))\n  if (!Number.isFinite(sd)) return null\n  // Small-sample variance inflation (t-style): keeps the sequence\n  // honest at the n this harness actually runs (6..32 boots).\n  sd *= Math.sqrt((n - 1) / Math.max(1, n - 3))\n  const nOpt = 16\n  const rho2 = (2 * Math.log(2 / alpha)) / nOpt\n  const width =\n    sd *\n    Math.sqrt(\n      ((2 * (n * rho2 + 1)) / (n * n * rho2)) *\n        Math.log((Math.sqrt(n * rho2 + 1) * 2) / alpha)\n    )\n  return { mean, lo: mean - width, hi: mean + width, n }\n}\n\n// What each metric measures and which direction is an improvement.\n// Deltas are always relative (%), so the unit answers \"% of what\".\nexport const METRICS = {\n  rps: { unit: 'req/s', better: 'higher' },\n  docKb: { unit: 'KB', better: 'lower' },\n  gzipKb: { unit: 'KB', better: 'lower' },\n  flightKb: { unit: 'KB', better: 'lower' },\n  median: { unit: 'ms', better: 'lower' },\n  mean: { unit: 'ms', better: 'lower' },\n  p95: { unit: 'ms', better: 'lower' },\n  p99: { unit: 'ms', better: 'lower' },\n  ttfb: { unit: 'ms', better: 'lower' },\n  gcMs: { unit: 'ms', better: 'lower' },\n  p50: { unit: 'ms', better: 'lower' },\n  rss: { unit: 'MB', better: 'lower' },\n  heapMb: { unit: 'MB', better: 'lower' },\n  rssHw: { unit: 'MB peak', better: 'lower' },\n}\n\n// One metric in one phase: per-boot arrays of paired deltas in, verdict out.\nexport function bootLevelStats(perBootDeltas) {\n  const boots = perBootDeltas.filter((d) => d.length > 0)\n  const bootMeans = boots.map((d) => d.reduce((a, b) => a + b, 0) / d.length)\n  const n = bootMeans.length\n  if (n === 0) return null\n  const mean = bootMeans.reduce((a, b) => a + b, 0) / n\n  const all = boots.flat()\n  const result = {\n    mean,\n    boots: n,\n    bootMeans,\n    pairs: all.length,\n    withinP: tTestP(all),\n  }\n  if (n >= 2) {\n    const sd = Math.sqrt(\n      bootMeans.reduce((a, b) => a + (b - mean) ** 2, 0) / (n - 1)\n    )\n    result.ci95 = (tCritical975(n - 1) * sd) / Math.sqrt(n)\n    result.p = tTestP(bootMeans)\n  } else {\n    result.ci95 = Infinity\n    result.p = 1\n  }\n  return result\n}\n\nexport function formatStat(name, candName, baseName, s) {\n  if (s === null) return `  ${name.padEnd(6)} (no data)`\n  const pct = (x) => `${(x * 100).toFixed(1)}%`\n  const ci = s.ci95 === Infinity ? '±∞' : `±${(s.ci95 * 100).toFixed(1)}`\n  const m = METRICS[name]\n  const meta = m\n    ? ` [${m.unit}; ${s.mean > 0 === (m.better === 'higher') ? 'IMPROVEMENT' : 'regression'} if real]`\n    : ''\n  // Byte metrics are deterministic per build, so a ±0.0 near-zero cell\n  // with p=0 is normal; the absolute values say whether it matters.\n  const abs =\n    s.absBase !== undefined && m?.unit === 'KB'\n      ? ` [${s.absBase.toFixed(1)}KB -> ${s.absCand.toFixed(1)}KB]`\n      : ''\n  return (\n    `  ${name.padEnd(6)} ${candName} vs ${baseName}: ${pct(s.mean)} ${ci}${meta}${abs} ` +\n    `(boots=${s.boots}${s.boots < 3 ? ' — TOO FEW FOR CLAIMS' : ''}, p=${s.p.toFixed(4)})` +\n    `  perBoot ${s.bootMeans.map((m) => pct(m)).join(' ')}` +\n    `  [pairs=${s.pairs} within-run p=${s.withinP.toFixed(4)} — diagnostic only]`\n  )\n}\n\n// E2e rows: {vm, arm, block, run, route, phase, <metrics...>}. Pairs are\n// (vm, block, run); the boot is the vm. Returns nothing; prints.\nexport function analyzeE2eRows(rows, baseName, candName, metrics) {\n  const fps = {}\n  for (const r of rows)\n    (fps[r.arm] ||= new Set()).add(r.ver ? `${r.fp}/${r.ver}` : `${r.fp}`)\n  console.log(\n    `\\nfingerprints: ${baseName}=${[...(fps[baseName] ?? [])].join(',')} ` +\n      `${candName}=${[...(fps[candName] ?? [])].join(',')}`\n  )\n  if ((fps[baseName]?.size ?? 0) !== 1 || (fps[candName]?.size ?? 0) !== 1) {\n    // A VM measured the wrong build; numbers would look official and be\n    // meaningless. Refuse instead of printing stats with a warning.\n    console.log(\n      '!! inconsistent fingerprints within an arm — RESULTS INVALID, no stats'\n    )\n    process.exitCode = 1\n    return false\n  }\n  const baseFp = [...fps[baseName]][0]?.split('/')[0]\n  const candFp = [...fps[candName]][0]?.split('/')[0]\n  if (baseFp !== undefined && candFp !== undefined) {\n    console.log(\n      baseFp === candFp\n        ? 'fingerprint files byte-identical between arms (A/A for those files; ' +\n            'arms may still differ elsewhere — check version strings)'\n        : 'arms differ (A/B mode)'\n    )\n  }\n\n  // \"Absent\" must be distinguishable from \"identical\": metrics the run\n  // never captured are named at the end instead of silently missing.\n  const captured = new Set()\n  for (const phase of [\n    ...new Set(rows.map((r) => `${r.route ?? ''} ${r.phase}`)),\n  ].sort()) {\n    console.log(`\\n${phase}`)\n    const inPhase = (r) => `${r.route ?? ''} ${r.phase}` === phase\n    for (const metric of metrics) {\n      const perBoot = []\n      const baseVals = []\n      const candVals = []\n      for (const vm of [...new Set(rows.map((r) => r.vm))]) {\n        const deltas = []\n        for (const r of rows.filter(\n          (x) => x.vm === vm && inPhase(x) && x.arm === candName\n        )) {\n          const b = rows.find(\n            (x) =>\n              x.vm === vm &&\n              inPhase(x) &&\n              x.arm === baseName &&\n              x.block === r.block &&\n              x.run === r.run\n          )\n          if (b && b[metric] > 0 && r[metric] > 0) {\n            deltas.push((r[metric] - b[metric]) / b[metric])\n            baseVals.push(b[metric])\n            candVals.push(r[metric])\n          }\n        }\n        perBoot.push(deltas)\n      }\n      const s = bootLevelStats(perBoot)\n      if (s !== null && s.pairs > 0) {\n        captured.add(metric)\n        s.absBase = baseVals.reduce((a, b) => a + b, 0) / baseVals.length\n        s.absCand = candVals.reduce((a, b) => a + b, 0) / candVals.length\n        console.log(formatStat(metric, candName, baseName, s))\n      }\n    }\n  }\n  const absent = metrics.filter((m) => !captured.has(m))\n  if (absent.length > 0) {\n    console.log(`\\nnot captured on this run: ${absent.join(', ')}`)\n  }\n  return true\n}\n", "skills/sandbox-bench/scripts/bench-status.mjs": "#!/usr/bin/env node\n// Usage: node bench-status.mjs [--all]\n//\n// The only reliable way to know what's in flight. Session restarts silently\n// kill background launchers while their detached VMs keep measuring, and a\n// dead launcher's log file still ends with a healthy-looking progress line —\n// never infer liveness from log tails. This reads each run's status.json,\n// checks whether the recorded launcher pid is alive, and prints the recovery\n// action per run.\nimport fs from 'fs'\nimport path from 'path'\nimport { loadConfig } from './config.mjs'\n\nconst CONFIG = loadConfig({ requireScope: false })\nconst E2E = path.join(CONFIG.cacheDir, 'e2e')\nconst all = process.argv.includes('--all')\n\nconst dirs = fs.existsSync(E2E)\n  ? fs\n      .readdirSync(E2E)\n      .filter((d) => d.startsWith('run-'))\n      .map((d) => path.join(E2E, d))\n      .sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs)\n  : []\n\nconst DAY = 24 * 3600 * 1000\nlet shown = 0\nfor (const dir of dirs) {\n  const sf = path.join(dir, 'status.json')\n  if (!fs.existsSync(sf)) continue\n  let st\n  try {\n    st = JSON.parse(fs.readFileSync(sf, 'utf8'))\n  } catch {\n    continue\n  }\n  const fresh = fs.statSync(sf).mtimeMs > Date.now() - DAY\n  let alive = false\n  if (st.pid) {\n    try {\n      process.kill(st.pid, 0)\n      alive = true\n    } catch {}\n  }\n  if (!all && !fresh && !alive) {\n    continue\n  }\n  const ageMin = st.updatedAt\n    ? Math.round((Date.now() - new Date(st.updatedAt).getTime()) / 60000)\n    : null\n  const vms = Object.values(st.vms || {})\n  const rows = vms.reduce((s, v) => s + (v.rows || 0), 0)\n\n  let action\n  if (st.phase === 'done') {\n    action = 'complete — bench-analyze.mjs re-reads it any time'\n  } else if (String(st.phase).startsWith('prepared')) {\n    action =\n      'complete (--prepare: caches only) — launch the real run without --prepare'\n  } else if (alive) {\n    action = 'RUNNING — leave it alone'\n  } else if (\n    (rows > 0 || st.phase === 'measuring') &&\n    ageMin !== null &&\n    ageMin > 290\n  ) {\n    action =\n      'DEAD and its VMs have expired — whatever was collected is in the ' +\n      'run dir/results db; relaunch if more data is needed'\n  } else if (rows > 0 || st.phase === 'measuring') {\n    action =\n      `DEAD but VMs may still hold data — node scripts/bench-collect.mjs ${dir}` +\n      ' (measurement VMs time out ~5h after launch; collect before that)'\n  } else {\n    action =\n      'DEAD before measurement — safe to relaunch (caches make it cheap); ' +\n      'check for leaked builder VMs with sandbox-sweep.mjs'\n  }\n\n  console.log(\n    `${path.basename(dir)}\\n` +\n      `  phase=${st.phase}` +\n      (st.error\n        ? ` error=${JSON.stringify(String(st.error).slice(0, 140))}`\n        : '') +\n      ` pid=${st.pid ?? '?'}(${alive ? 'alive' : 'dead'})` +\n      (ageMin !== null ? ` updated=${ageMin}m ago` : '') +\n      ` rows=${rows}${st.rowsExpected ? `/${st.rowsExpected}` : ''}\\n` +\n      `  -> ${action}`\n  )\n  shown++\n}\nif (!shown) {\n  console.log('no recent runs (use --all to list everything)')\n}\n", "skills/sandbox-bench/scripts/config.mjs": "// Configuration for the sandbox-bench scripts.\n//\n// Everything machine- or team-specific lives in a config file OUTSIDE the\n// repo (never commit team/project names into the repo):\n//   ~/.config/sandbox-bench/config.json\n//\n// Required fields (no defaults — ask the user once, then save):\n//   team     Vercel team slug the sandboxes bill to\n//   project  Vercel project the sandboxes attach to\n// Optional fields:\n//   cacheDir     where clones/artifacts/snapshot-ids live\n//                (default ~/.cache/sandbox-bench)\n//   reactRepo    existing react checkout to use (default: auto-clone\n//                into <cacheDir>/react)\n//   nextRepo     existing next.js checkout to use (default: auto-clone\n//                into <cacheDir>/next)\n//   reactRepoUrl clone/fetch URL (default https://github.com/react/react.git)\n//   nextRepoUrl  clone/fetch URL (default https://github.com/vercel/next.js.git)\n//   vercelBin    vercel CLI binary (default \"vercel\")\n//\n// CLI: node config.mjs show\n//      node config.mjs set team=<slug> project=<name> [key=value...]\nimport fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { execFileSync } from 'node:child_process'\n\nconst CONFIG_DIR = path.join(os.homedir(), '.config', 'sandbox-bench')\nconst CONFIG_FILE = path.join(CONFIG_DIR, 'config.json')\n\nexport function loadConfig({ requireScope = true } = {}) {\n  let cfg = {}\n  if (fs.existsSync(CONFIG_FILE)) {\n    cfg = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'))\n  }\n  // Env overrides for CI or one-off use.\n  cfg.team = process.env.SANDBOX_BENCH_TEAM ?? cfg.team\n  cfg.project = process.env.SANDBOX_BENCH_PROJECT ?? cfg.project\n  cfg.cacheDir = expandHome(\n    process.env.SANDBOX_BENCH_CACHE ?? cfg.cacheDir ?? '~/.cache/sandbox-bench'\n  )\n  cfg.reactRepo = expandHome(\n    process.env.SANDBOX_BENCH_REACT_REPO ?? cfg.reactRepo ?? ''\n  )\n  cfg.nextRepo = expandHome(\n    process.env.SANDBOX_BENCH_NEXT_REPO ?? cfg.nextRepo ?? ''\n  )\n  cfg.reactRepoUrl = cfg.reactRepoUrl ?? 'https://github.com/react/react.git'\n  cfg.nextRepoUrl = cfg.nextRepoUrl ?? 'https://github.com/vercel/next.js.git'\n  cfg.vercelBin = cfg.vercelBin ?? 'vercel'\n  if (requireScope && (!cfg.team || !cfg.project)) {\n    throw new Error(\n      'sandbox-bench is not configured: team and project are required.\\n' +\n        'Ask the user which Vercel team + project the sandbox VMs should ' +\n        'run under, then save them with:\\n' +\n        `  node ${path.relative(process.cwd(), new URL(import.meta.url).pathname)} ` +\n        'set team=<team-slug> project=<project-name>\\n' +\n        '(Stored in ~/.config/sandbox-bench/config.json, not in the repo.)'\n    )\n  }\n  return cfg\n}\n\nexport function saveConfig(patch) {\n  fs.mkdirSync(CONFIG_DIR, { recursive: true })\n  const existing = fs.existsSync(CONFIG_FILE)\n    ? JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'))\n    : {}\n  const merged = { ...existing, ...patch }\n  fs.writeFileSync(CONFIG_FILE, JSON.stringify(merged, null, 2) + '\\n')\n  return merged\n}\n\nfunction expandHome(p) {\n  if (!p) return p\n  return p.startsWith('~/') ? path.join(os.homedir(), p.slice(2)) : p\n}\n\n// Scope flags appended to every `vercel sandbox` call. Never widen scope\n// beyond the configured team/project: the project may be shared.\nexport function sandboxScope(cfg) {\n  return ['--team', cfg.team, '--project', cfg.project]\n}\n\n// Repos: use the configured checkout, else clone lazily into the cache.\nfunction ensureRepo(cfg, checkout, url, name) {\n  if (checkout && fs.existsSync(path.join(checkout, '.git'))) return checkout\n  const dest = path.join(cfg.cacheDir, name)\n  if (fs.existsSync(path.join(dest, '.git'))) return dest\n  fs.mkdirSync(cfg.cacheDir, { recursive: true })\n  console.error(`cloning ${url} into ${dest} (one-time)...`)\n  execFileSync('git', ['clone', '--filter=blob:none', url, dest], {\n    stdio: 'inherit',\n  })\n  return dest\n}\nexport function ensureReactRepo(cfg) {\n  return ensureRepo(cfg, cfg.reactRepo, cfg.reactRepoUrl, 'react')\n}\nexport function ensureNextRepo(cfg) {\n  return ensureRepo(cfg, cfg.nextRepo, cfg.nextRepoUrl, 'next')\n}\n\n// ------------------------------------------------------------------ CLI\n// realpath both sides: /tmp vs /private/tmp (macOS) or any symlinked\n// invocation path must not silently skip the CLI (a no-op \"config set\"\n// would leave stale team/project in effect with exit 0).\nfunction isMain() {\n  if (!process.argv[1]) return false\n  try {\n    return (\n      fs.realpathSync(process.argv[1]) ===\n      fs.realpathSync(new URL(import.meta.url).pathname)\n    )\n  } catch {\n    return false\n  }\n}\nif (isMain()) {\n  const [cmd, ...rest] = process.argv.slice(2)\n  if (cmd === 'show') {\n    let cfg\n    try {\n      cfg = loadConfig({ requireScope: false })\n    } catch (e) {\n      console.error(e.message)\n      process.exit(1)\n    }\n    console.log(JSON.stringify(cfg, null, 2))\n    if (!cfg.team || !cfg.project) {\n      console.error('\\nNOT CONFIGURED: team/project missing (see file header).')\n      process.exit(2)\n    }\n  } else if (cmd === 'set') {\n    const patch = {}\n    for (const kv of rest) {\n      const i = kv.indexOf('=')\n      if (i < 0) {\n        console.error(`bad argument \"${kv}\", want key=value`)\n        process.exit(1)\n      }\n      patch[kv.slice(0, i)] = kv.slice(i + 1)\n    }\n    const merged = saveConfig(patch)\n    console.log(`saved: ${JSON.stringify(merged, null, 2)}`)\n  } else {\n    console.error('usage: node config.mjs show | set key=value [key=value...]')\n    process.exit(1)\n  }\n}\n", "skills/sandbox-bench/scripts/sandbox-e2e.mjs": "// Remote Next.js e2e A/B on Vercel Sandbox: blocks x arms x runs of\n// bench:render-pipeline, both arms always in the SAME VM, paired per\n// (block, run), ABBA order. The VM boot is the unit of replication;\n// see bench-stats.mjs.\n//\n// Arms vary React (--pr / --arms, Next side fixed) or Next\n// (--next-pr / --next-arms, React side fixed). The Next side defaults\n// to canary. Refs resolve in configured/auto-cloned clones of the two\n// repos (config.mjs); branch and tag names resolve against the remote.\n//\n// Usage:\n//   node sandbox-e2e.mjs --pr <react pr url|num> [--vms 16] [--label x]\n//   node sandbox-e2e.mjs --arms base=<ref>,cand=<ref> [--next-ref canary]\n//   node sandbox-e2e.mjs --next-pr <next pr url|num> [--react-ref main]\n//   node sandbox-e2e.mjs --next-arms base=<ref>,cand=<ref> [--react-ref main]\n//   Common: [--blocks 1] [--runs 2] [--vms 16] [--routes /blog,/dashboard,/docs]\n//     [--warmup 200] [--serial 800] [--load-requests 8] [--load-concurrency 8]\n//     [--isolate-routes] [--bench-env K=V] [--profile] [--keep] [--dry-run]\nimport fs from 'fs'\nimport os from 'os'\nimport path from 'path'\nimport { analyzeE2eRows, tTestP } from './bench-stats.mjs'\nimport { openDb, importRun, loadRows, verify as verifyDb } from './bench-db.mjs'\nimport {\n  execFileP,\n  CONFIG,\n  NEXT_REPO_LAZY,\n  REACT_REPO_LAZY,\n  CACHE,\n  SETUP_VERSION,\n  REACT_GH_REPO,\n  NEXT_GH_REPO,\n  status,\n  writeStatus,\n  sb,\n  sbCpToVm,\n  sbExec,\n  rmVm,\n  runDetached,\n  resolvePrArms,\n  assertCiGreen,\n  commitTitle,\n  printRunContext,\n  makeLive,\n  sha256,\n  snapshotIdFor,\n  takeSnapshot,\n  ensureRefArm,\n} from './bench-common.mjs'\n\n// Runtime provenance: the compiled server files prod app-page runtimes\n// are bundled from — BOTH bundlers, so changes touching only one still\n// move the fingerprint. One file per server-side React layer (Flight,\n// Fizz, shared react-server runtime): a change confined to one layer\n// leaves the other layers' files byte-identical.\nconst FP_FILES = [\n  'packages/next/dist/compiled/react-server-dom-turbopack-experimental/cjs/react-server-dom-turbopack-server.node.production.js',\n  'packages/next/dist/compiled/react-server-dom-webpack-experimental/cjs/react-server-dom-webpack-server.node.production.js',\n  'packages/next/dist/compiled/react-dom-experimental/cjs/react-dom-server.node.production.js',\n  'packages/next/dist/compiled/react-experimental/cjs/react.react-server.production.js',\n]\n\nfunction parseArgs() {\n  const a = process.argv.slice(2)\n  const get = (name, dflt) => {\n    const i = a.indexOf(name)\n    return i >= 0 ? a[i + 1] : dflt\n  }\n  // React arms: name=<git ref in the react repo> (built remotely, cached\n  // by sha). Next arms: name=<git ref in this checkout>. Exactly one of\n  // the two sides varies; the other is fixed for both arms.\n  const parseArmSpec = (spec, flag) =>\n    spec\n      .split(',')\n      .filter(Boolean)\n      .map((s) => {\n        const [name, src] = s.split('=')\n        if (!name || !src)\n          throw new Error(`bad arm \"${s}\" in ${flag}, want name=<ref>`)\n        return { name, ref: src }\n      })\n  const arms = parseArmSpec(get('--arms', ''), '--arms')\n  const nextArms = parseArmSpec(get('--next-arms', ''), '--next-arms')\n  const pr = get('--pr', undefined)\n  const nextPr = get('--next-pr', undefined)\n  const reactModes = (arms.length ? 1 : 0) + (pr ? 1 : 0)\n  const nextModes = (nextArms.length ? 1 : 0) + (nextPr ? 1 : 0)\n  if (reactModes + nextModes !== 1) {\n    throw new Error('need exactly one of: --pr, --arms, --next-pr, --next-arms')\n  }\n  // One react arm = \"vs what this Next ships\": base derived as\n  // merge-base(cand, react synced into the Next ref).\n  if (arms.length > 2)\n    throw new Error(\n      '--arms takes one arm (vs synced react) or two (base first)'\n    )\n  if (nextArms.length && nextArms.length !== 2)\n    throw new Error('--next-arms needs exactly two arms (base first)')\n  return {\n    arms,\n    nextArms,\n    pr,\n    nextPr,\n    dryRun: a.includes('--dry-run'),\n    allowUngated: a.includes('--allow-ungated'),\n    // Fixed sides. Next defaults to canary.\n    nextRef: get('--next-ref', 'canary'),\n    // For Next A/B the React side defaults to whatever each Next ref\n    // vendors (that's what would ship); --react-ref pins both arms to\n    // one React build instead.\n    reactRef: get('--react-ref', ''),\n    // The VM boot is the unit of replication (see bench-stats.mjs):\n    // allocate toward more boots with fewer runs each.\n    blocks: Number(get('--blocks', '1')),\n    runs: Number(get('--runs', '2')),\n    vms: Number(get('--vms', '16')),\n    routes: get('--routes', '/blog,/dashboard,/docs'),\n    warmup: Number(get('--warmup', '200')),\n    serial: Number(get('--serial', '800')),\n    loadRequests: Number(get('--load-requests', '8')),\n    loadConcurrency: Number(get('--load-concurrency', '8')),\n    isolateRoutes: a.includes('--isolate-routes'),\n    keep: a.includes('--keep'),\n    prepare: a.includes('--prepare'),\n    // Profiles are captured by default: the pass runs strictly after the\n    // timed runs (never touches the numbers), costs ~10-15 min of VM\n    // wall-clock, and cross-VM profile diffs proved highly stable\n    // (16/16 sign agreement on movers). --no-profile opts out.\n    profile: !a.includes('--no-profile'),\n    // KEY=VALUE env exported around bench:render-pipeline (e.g.\n    // NEXT_FLIGHT_RENDER=0 to force the byte-tee SSR baseline).\n    benchEnv: get('--bench-env', ''),\n    label: get('--label', 'e2e'),\n  }\n}\n\n// Normalize every mode into two arms of {name, ref (react), nextRef};\n// exactly one side differs between the arms.\n// The react commit a Next ref ships: sync-react records it in the root\n// package.json (\"react-builtin\": \"npm:react@19.x.y-canary-<sha>-<date>\").\nasync function syncedReactSha(nextRef) {\n  const pkg = (\n    await execFileP(\n      'git',\n      ['-C', NEXT_REPO_LAZY(), 'show', `${nextRef}:package.json`],\n      { maxBuffer: 1 << 24 }\n    )\n  ).stdout\n  const m = JSON.parse(pkg).devDependencies?.['react-builtin']?.match(\n    /-([0-9a-f]{8,40})-\\d{8}$/\n  )\n  if (!m)\n    throw new Error(\n      `cannot parse synced react sha from ${nextRef}:package.json react-builtin`\n    )\n  return m[1]\n}\n\n// Next refs: shas and refs already fetched this run resolve locally;\n// branch/tag names resolve against the remote. Each ref resolves once\n// per run (memo) and everything downstream uses the sha, so the two\n// arms always get the same tree. The clone is shared between\n// concurrent launchers (pid-namespaced temp refs, fetch retried).\nasync function fetchNextRef(repo, spec, dst) {\n  for (let attempt = 1; ; attempt++) {\n    try {\n      await execFileP('git', [\n        '-C',\n        repo,\n        'fetch',\n        '-q',\n        CONFIG.nextRepoUrl,\n        `+${spec}:${dst}`,\n      ])\n      return\n    } catch (e) {\n      if (attempt >= 3) throw e\n      await new Promise((r) => setTimeout(r, 2000 * attempt))\n    }\n  }\n}\nconst nextShaMemo = new Map()\nasync function nextShaFor(ref) {\n  if (nextShaMemo.has(ref)) return nextShaMemo.get(ref)\n  const repo = NEXT_REPO_LAZY()\n  let sha\n  if (/^[0-9a-f]{7,40}$/i.test(ref) || ref.startsWith('refs/')) {\n    try {\n      sha = (\n        await execFileP('git', [\n          '-C',\n          repo,\n          'rev-parse',\n          '--verify',\n          `${ref}^{commit}`,\n        ])\n      ).stdout.trim()\n    } catch {}\n  }\n  if (!sha) {\n    const dst = `refs/bench-tmp/${process.pid}/next-fixed-${nextShaMemo.size}`\n    // \"canary\" means the latest published canary release, not the\n    // branch head: postinstall downloads the @next/swc binary for\n    // package.json's version, which only exists once that release is\n    // on npm. Between releases this is also a stable sha, so built\n    // snapshots stay warm until a new canary actually ships.\n    let spec = ref\n    let release\n    if (ref === 'canary') {\n      release = `v${(await execFileP('npm', ['view', 'next@canary', 'version'])).stdout.trim()}`\n      spec = `refs/tags/${release}`\n    }\n    await fetchNextRef(repo, spec, dst)\n    sha = (\n      await execFileP('git', ['-C', repo, 'rev-parse', `${dst}^{commit}`])\n    ).stdout.trim()\n    console.error(\n      `next ${ref}: ${release ? `${release} = ` : ''}${sha.slice(0, 12)}`\n    )\n  }\n  nextShaMemo.set(ref, sha)\n  return sha\n}\n\nasync function resolveArms(cfg) {\n  let arms\n  if (cfg.pr) {\n    arms = (\n      await resolvePrArms(\n        cfg.pr,\n        REACT_REPO_LAZY(),\n        CONFIG.reactRepoUrl,\n        'main'\n      )\n    ).map((a) => ({ ...a, nextRef: cfg.nextRef }))\n  } else if (cfg.arms.length === 1) {\n    // Candidate react vs whatever this Next ref ships. merge-base keeps\n    // the base a real commit in the candidate's history even when the\n    // synced version isn't an exact ancestor.\n    const synced = await syncedReactSha(await nextShaFor(cfg.nextRef))\n    const repo = REACT_REPO_LAZY()\n    const base = (\n      await execFileP('git', [\n        '-C',\n        repo,\n        'merge-base',\n        synced,\n        cfg.arms[0].ref,\n      ])\n    ).stdout.trim()\n    console.error(\n      `react base = merge-base(${cfg.arms[0].ref}, synced ${synced}) = ${base.slice(0, 12)}`\n    )\n    arms = [\n      { name: 'synced', ref: base, nextRef: cfg.nextRef },\n      { ...cfg.arms[0], nextRef: cfg.nextRef },\n    ]\n  } else if (cfg.arms.length) {\n    arms = cfg.arms.map((a) => ({ ...a, nextRef: cfg.nextRef }))\n  } else if (cfg.nextPr) {\n    arms = (\n      await resolvePrArms(\n        cfg.nextPr,\n        NEXT_REPO_LAZY(),\n        CONFIG.nextRepoUrl,\n        'canary'\n      )\n    ).map((a) => ({ name: a.name, ref: cfg.reactRef || null, nextRef: a.ref }))\n  } else {\n    arms = cfg.nextArms.map((a) => ({\n      name: a.name,\n      ref: cfg.reactRef || null,\n      nextRef: a.ref,\n    }))\n  }\n  for (const arm of arms) {\n    arm.nextSha = await nextShaFor(arm.nextRef)\n  }\n  return arms\n}\n\n// Human context for reports: PR title/URL and the varying side's\n// commit titles, recorded in meta.json and printed with the analysis\n// so verdicts can link what was measured.\nasync function describeRun(cfg) {\n  const reactVaries = !(cfg.nextPr || cfg.nextArms.length)\n  let pr\n  const num = String(cfg.pr ?? cfg.nextPr ?? '').match(/(\\d+)\\/?$/)?.[1]\n  if (num) {\n    const ghRepo = cfg.pr ? REACT_GH_REPO : NEXT_GH_REPO\n    pr = { url: `https://github.com/${ghRepo}/pull/${num}` }\n    try {\n      pr.title = (\n        await execFileP('gh', [\n          'api',\n          `repos/${ghRepo}/pulls/${num}`,\n          '--jq',\n          '.title',\n        ])\n      ).stdout.trim()\n    } catch {}\n  }\n  const arms = []\n  for (const a of cfg.arms) {\n    arms.push({\n      name: a.name,\n      title: reactVaries\n        ? await commitTitle(REACT_REPO_LAZY(), a.ref)\n        : await commitTitle(NEXT_REPO_LAZY(), a.nextSha),\n    })\n  }\n  return { pr, arms }\n}\n// ------------------------------------------------------------ snapshots\n\n// Experiment snapshot: both arms fully vendored + built as SEPARATE repo\n// trees (/vercel/sandbox/next-<arm>), app .next included, so run VMs\n// boot straight into measurement and arm switching is a cd. Keyed on\n// (next ref, armA, armB); the app build happens once here, so every run\n// VM measures byte-identical artifacts.\nfunction armId(a) {\n  return `${a.sha ? a.sha.slice(0, 12) : 'vendored'}+${a.nextSha.slice(0, 12)}`\n}\n\nasync function ensureExperimentSnapshot(cfg) {\n  // Arm NAMES are part of the key, not just shas: tree paths inside the\n  // snapshot embed the names (/vercel/sandbox/next-<name>), so a snapshot\n  // built for the same sha pair under different names has the wrong trees.\n  const key = await sha256(\n    SETUP_VERSION + 'exp3' + cfg.arms.map((a) => `${a.name}=${armId(a)}`).join()\n  )\n  let id = await snapshotIdFor(CACHE, key)\n  if (id) return id\n  // Built TREES are cached independently of the (pair, names) snapshot:\n  // the base side of a comparison repeats across cells far more often\n  // than the exact pair does, and a cached tree turns a ~15 min\n  // install+build+sync into an upload+extract.\n  for (const arm of cfg.arms) {\n    arm.treeKey = await sha256(SETUP_VERSION + 'tree1' + armId(arm))\n    arm.treeTgz = path.join(CACHE, `tree-${arm.treeKey}.tgz`)\n    arm.treeCached = fs.existsSync(arm.treeTgz)\n  }\n  const vm = `sbench-expsnap-${Date.now().toString(36)}`\n  console.error(\n    `creating experiment snapshot (one-time for arms=${cfg.arms.map(armId).join(',')}; ` +\n      `trees cached: ${\n        cfg.arms\n          .filter((a) => a.treeCached)\n          .map((a) => a.name)\n          .join(',') || 'none'\n      })...`\n  )\n  try {\n    await sb([\n      'create',\n      '--name',\n      vm,\n      '--runtime',\n      'node24',\n      '--vcpus',\n      '16',\n      '--timeout',\n      '1h',\n      '--non-persistent',\n      '--network-policy',\n      'allow-all',\n      '--tag',\n      'purpose=sandbox-bench',\n      '--silent',\n    ])\n  } catch (e) {\n    // Only a genuine capacity/plan rejection falls back to 8 vCPUs;\n    // anything else (auth, quota, network) must surface as itself.\n    if (!/vcpu/i.test(e.message)) throw e\n    console.error('16 vCPUs unavailable, using 8')\n    await sb([\n      'create',\n      '--name',\n      vm,\n      '--runtime',\n      'node24',\n      '--vcpus',\n      '8',\n      '--timeout',\n      '1h',\n      '--non-persistent',\n      '--network-policy',\n      'allow-all',\n      '--tag',\n      'purpose=sandbox-bench',\n      '--silent',\n    ])\n  }\n  try {\n    for (const tgz of new Set(\n      cfg.arms.filter((a) => !a.treeCached).map((a) => a.nextTgz)\n    )) {\n      await sb(['cp', tgz, `${vm}:/vercel/sandbox/${path.basename(tgz)}`])\n    }\n    for (const arm of cfg.arms) {\n      if (arm.treeCached) {\n        console.error(`uploading cached tree for ${arm.name}...`)\n        await sbCpToVm(vm, arm.treeTgz, `/vercel/sandbox/tree-${arm.name}.tgz`)\n      } else if (arm.tgz) {\n        await sb(['cp', arm.tgz, `${vm}:/vercel/sandbox/arm-${arm.name}.tgz`])\n      }\n    }\n    // Cached trees: extract. Missing trees: install sequentially (the\n    // shared pnpm store dislikes concurrent cold installs), then build,\n    // sync, and warm concurrently — the builds dominate and parallelize\n    // across the 16 vCPUs. PHASE lines make the time budget visible.\n    const extractCached = cfg.arms\n      .filter((a) => a.treeCached)\n      .map(\n        (a) => `\necho \"PHASE extract-${a.name} $(date +%s)\"\nmkdir -p /vercel/sandbox/next-${a.name} && tar -xzf /vercel/sandbox/tree-${a.name}.tgz -C /vercel/sandbox/next-${a.name}`\n      )\n      .join('\\n')\n    const installs = cfg.arms\n      .filter((a) => !a.treeCached)\n      .map(\n        (a) => `\necho \"PHASE install-${a.name} $(date +%s)\"\n${a.tgz ? `mkdir -p /vercel/sandbox/arm-${a.name} && tar -xzf /vercel/sandbox/arm-${a.name}.tgz -C /vercel/sandbox/arm-${a.name}` : ':'}\nmkdir -p /vercel/sandbox/next-${a.name} && cd /vercel/sandbox/next-${a.name} && tar -xzf /vercel/sandbox/${path.basename(a.nextTgz)} 2>/dev/null\npnpm install --frozen-lockfile >/tmp/i-${a.name}.log 2>&1 || (tail -10 /tmp/i-${a.name}.log; exit 1)`\n      )\n      .join('\\n')\n    const builds = cfg.arms\n      .filter((a) => !a.treeCached)\n      .map(\n        (a, i) => `\n(\n  set -e\n  cd /vercel/sandbox/next-${a.name}\n  echo \"PHASE build-${a.name} $(date +%s)\"\n  pnpm build >/tmp/b-${a.name}.log 2>&1\n  ${a.tgz ? `pnpm run sync-react --version \"file:///vercel/sandbox/arm-${a.name}/\" >/tmp/s-${a.name}.log 2>&1` : ': # vendored react, no sync'}\n  pnpm --filter=@next/font build >/dev/null 2>&1\n  echo \"PHASE next-build-${a.name} $(date +%s)\"\n  pnpm --filter=next build >/tmp/n-${a.name}.log 2>&1\n) &\nBUILD_${i}=$!`\n      )\n      .join('\\n')\n    const waits = cfg.arms\n      .filter((a) => !a.treeCached)\n      .map(\n        (a, i) =>\n          `wait $BUILD_${i} || (tail -10 /tmp/b-${a.name}.log /tmp/s-${a.name}.log /tmp/n-${a.name}.log; exit 1)`\n      )\n      .join('\\n')\n    // Warm + verify runs per tree, sequential (they bind the same port).\n    const verifies = cfg.arms\n      .map(\n        (a) => `\ncd /vercel/sandbox/next-${a.name}\nVER=$(grep -aom1 \"[0-9.]*-\\\\(canary\\\\|experimental\\\\)-[0-9a-f]*-[0-9]*\" packages/next/dist/compiled/react-experimental/cjs/react.development.js || echo MISSING)\necho \"tree ${a.name} ver=$VER\"\n[ \"$VER\" != MISSING ]\necho \"PHASE warm-${a.name} $(date +%s)\"\npnpm bench:render-pipeline --scenario=e2e --stream-mode=node --build=true --port=3720 --routes=${cfg.routes} --warmup-requests=1 --serial-requests=2 --load-requests=2 --load-concurrency=1 --json-out=/tmp/warm.json --artifact-dir=/tmp/warm-art >/tmp/w.log 2>&1 || (tail -10 /tmp/w.log; exit 1)\nrm -rf /tmp/warm-art /tmp/warm.json\n${a.treeCached ? ':' : `echo \"PHASE pack-${a.name} $(date +%s)\" && tar -czf /vercel/sandbox/tree-${a.name}-out.tgz -C /vercel/sandbox/next-${a.name} .`}\necho \"tree ${a.name} ready\"`\n      )\n      .join('\\n')\n    await sbExec(\n      vm,\n      '55m',\n      `set -e\\nnpm i -g pnpm@12.9.1 >/dev/null 2>&1\\n` +\n        `(while true; do echo \"hb mem=$(free -m | awk '/^Mem/{print $3}')MB\"; sleep 30; done) & HB=$!\\n` +\n        `${extractCached}\\n${installs}\\n${builds}\\n${waits}\\n${verifies}\\nkill $HB\\n` +\n        `echo \"PHASE done $(date +%s)\"\\n` +\n        `find /vercel/sandbox -maxdepth 1 -name '*.tgz' ! -name 'tree-*-out.tgz' -delete\\necho experiment ready`,\n      'expsnap'\n    )\n    // Pull freshly built trees into the cache before snapshotting (the\n    // snapshot must not contain the multi-GB tarballs).\n    for (const arm of cfg.arms) {\n      if (!arm.treeCached) {\n        console.error(`caching built tree for ${arm.name}...`)\n        // Temp + rename: concurrent launchers may cache the same tree.\n        const treeTmp = `${arm.treeTgz}.tmp-${process.pid}`\n        await sb([\n          'cp',\n          `${vm}:/vercel/sandbox/tree-${arm.name}-out.tgz`,\n          treeTmp,\n        ])\n        if (fs.existsSync(treeTmp) && fs.statSync(treeTmp).size >= 50_000_000) {\n          fs.renameSync(treeTmp, arm.treeTgz)\n        } else {\n          fs.rmSync(treeTmp, { force: true })\n          console.error(\n            `tree cache download for ${arm.name} too small; skipping cache (snapshot unaffected)`\n          )\n        }\n      }\n    }\n    await sbExec(\n      vm,\n      '5m',\n      `rm -f /vercel/sandbox/tree-*.tgz /vercel/sandbox/tree-*-out.tgz; echo cleaned`,\n      'expsnap'\n    )\n    return await takeSnapshot(vm, CACHE, key)\n  } finally {\n    await rmVm(vm)\n  }\n}\n\n// ---------------------------------------------------------------- stage\n\nasync function stage(cfg, tmp) {\n  const nextTgzBySha = new Map()\n  for (const arm of cfg.arms) {\n    if (!nextTgzBySha.has(arm.nextSha)) {\n      const tgz = path.join(tmp, `next-src-${arm.nextSha.slice(0, 12)}.tgz`)\n      await execFileP('bash', [\n        '-c',\n        `git -C ${NEXT_REPO_LAZY()} archive ${arm.nextSha} | gzip -1 > ${tgz}`,\n      ])\n      nextTgzBySha.set(arm.nextSha, tgz)\n    }\n    arm.nextTgz = nextTgzBySha.get(arm.nextSha)\n    if (arm.ref) {\n      arm.sha = (\n        await execFileP('git', ['-C', REACT_REPO_LAZY(), 'rev-parse', arm.ref])\n      ).stdout.trim()\n      await assertCiGreen(arm.sha, arm.name, cfg.allowUngated)\n      await ensureRefArm(arm)\n    }\n  }\n}\n\n// ------------------------------------------------------------------ run\n\nasync function runVm(index, cfg, expSnap, outDir) {\n  const vm = `sbench-${cfg.label}-${index}-${Date.now().toString(36)}`\n  const tag = `vm${index}`\n  console.error(`${tag}: creating ${vm} from experiment snapshot`)\n  writeStatus({\n    vms: { ...status.state.vms, [vm]: { state: 'booting', rows: 0 } },\n  })\n  await sb([\n    'create',\n    '--name',\n    vm,\n    '--snapshot',\n    expSnap,\n    '--vcpus',\n    '8',\n    '--timeout',\n    '5h',\n    '--non-persistent',\n    '--network-policy',\n    'allow-all',\n    '--tag',\n    'purpose=sandbox-bench',\n    '--silent',\n  ])\n  try {\n    const [base, cand] = cfg.arms.map((a) => a.name)\n    const total = cfg.blocks * cfg.runs\n    const benchArgs = (extra) =>\n      `--scenario=e2e --stream-mode=node --build=false --port=$PORT ` +\n      `--routes=${cfg.routes} --warmup-requests=${cfg.warmup} --serial-requests=${cfg.serial} ` +\n      `--load-requests=${cfg.loadRequests} --load-concurrency=${cfg.loadConcurrency} ` +\n      `${cfg.isolateRoutes ? '--isolate-routes=true ' : ''}${extra}`\n    // Both trees are pre-built in the snapshot; a run is pure\n    // measurement. ABBA: alternate which arm goes first per run so\n    // linear drift cancels within pairs, not just across them.\n    const loop = `set -e\nVMINDEX=${index}\nCPU=$(grep -m1 'model name' /proc/cpuinfo | cut -d: -f2- | sed 's/^ //')\n: > /vercel/sandbox/results.jsonl\nfor arm in ${base} ${cand}; do\n  V=$(grep -aom1 \"[0-9.]*-\\\\(canary\\\\|experimental\\\\)-[0-9a-f]*-[0-9]*\" /vercel/sandbox/next-$arm/packages/next/dist/compiled/react-experimental/cjs/react.development.js || echo MISSING)\n  for f in ${FP_FILES.map((f) => `/vercel/sandbox/next-$arm/${f}`).join(' ')}; do [ -s \"$f\" ] || { echo \"FP file missing: $f\"; exit 1; }; done\n  F=$(cat ${FP_FILES.map((f) => `/vercel/sandbox/next-$arm/${f}`).join(' ')} | sha256sum | cut -c1-12)\n  echo \"tree $arm ver=$V fp=$F\"; [ \"$V\" != MISSING ]\n  eval \"VER_$arm=$V; FP_$arm=$F\"\ndone\n# Identical fingerprints can be legitimate (arms differing only in\n# files outside FP_FILES, e.g. client-only changes), so warn, not fail.\nif [ \"$FP_${base}\" = \"$FP_${cand}\" ]; then\n  echo \"WARNING: arms fingerprint identically ($FP_${base}) — the hashed server bundles are byte-identical; verify the arms differ where intended\"\nfi\nfor run in $(seq 1 ${total}); do\n  # Alternate within the boot AND stagger by VM index: with an odd run\n  # count, otherwise every boot gives the same arm the cold first slot\n  # and boot-level inference reads that shared bias as signal.\n  if [ $(((run + VMINDEX) % 2)) = 1 ]; then ORDER=\"${cand} ${base}\"; else ORDER=\"${base} ${cand}\"; fi\n  for arm in $ORDER; do\n    # One port per arm: a not-quite-dead server from a previous run can\n    # then never be measured as the other arm.\n    if [ \"$arm\" = \"${base}\" ]; then PORT=3720; else PORT=3721; fi\n    cd /vercel/sandbox/next-$arm\n    ${cfg.benchEnv ? `export ${cfg.benchEnv}` : ':'}\n    pnpm bench:render-pipeline ${benchArgs('')} \\\n      --json-out=/tmp/r.json --artifact-dir=/tmp/art-$arm-r$run >/tmp/bench.log 2>&1 \\\n      || (tail -20 /tmp/bench.log; exit 1)\n    rm -rf /tmp/art-$arm-r$run\n    eval \"FP=\\\\$FP_$arm; VER=\\\\$VER_$arm\"\n    node -e '\n      const [,run,arm,fp,ver,cpu]=process.argv;\n      const j=require(\"/tmp/r.json\");\n      const docs=new Map((j.fullResults[0].routeDocuments??[]).map(d=>[d.route,d]));\n      for (const rr of j.fullResults[0].routeResults) {\n        if (!rr.latency) continue;\n        const row={block:+run,arm,run:1,fp,ver,cpu,route:rr.route,\n          phase:rr.phase,rps:rr.throughputRps,median:rr.latency.median,\n          mean:rr.latency.mean,p95:rr.latency.p95};\n        // Optional metrics are OMITTED when absent — a zero would pair\n        // against a real value as a fabricated -100% claim.\n        if (rr.latency.p99>0) row.p99=rr.latency.p99;\n        if (rr.ttfb&&rr.ttfb.median>0) row.ttfb=rr.ttfb.median;\n        if (rr.serverRssMb>0) row.rss=rr.serverRssMb;\n        if (rr.serverRssHwMb>0) row.rssHw=rr.serverRssHwMb;\n        const d=docs.get(rr.route)??{};\n        if (d.bytes>0) row.docKb=d.bytes/1024;\n        if (d.gzipBytes>0) row.gzipKb=d.gzipBytes/1024;\n        if (d.inlineFlightBytes>0) row.flightKb=d.inlineFlightBytes/1024;\n        // Failed requests inflate rps and vanish from latency: surface.\n        if (rr.errors>0) row.errors=rr.errors;\n        console.log(JSON.stringify(row));\n      }\n    ' \"$run\" \"$arm\" \"$FP\" \"$VER\" \"$CPU\" > /tmp/rows.txt\n    cat /tmp/rows.txt >> /vercel/sandbox/results.jsonl\n    sed 's/^/ROW /' /tmp/rows.txt\n    echo \"run $run $arm done\"\n  done\ndone\nwc -l /vercel/sandbox/results.jsonl`\n    let vmRows = 0\n    const out = await runDetached(\n      vm,\n      tag,\n      loop,\n      (row) => {\n        vmRows++\n        interimRows.push({ vm: index, ...row })\n        writeStatus({\n          vms: {\n            ...status.state.vms,\n            [vm]: { state: 'measuring', rows: vmRows },\n          },\n        })\n        cfg.live(index, row)\n      },\n      110\n    )\n    writeStatus({\n      vms: {\n        ...status.state.vms,\n        [vm]: { ...status.state.vms[vm], state: 'collecting' },\n      },\n    })\n    const local = path.join(outDir, `results-vm${index}.jsonl`)\n    await sb(['cp', `${vm}:/vercel/sandbox/results.jsonl`, local])\n    const remoteCount = Number(\n      out.match(/(\\d+) \\/vercel\\/sandbox\\/results\\.jsonl/)?.[1] ?? NaN\n    )\n    const localCount = fs\n      .readFileSync(local, 'utf8')\n      .trim()\n      .split('\\n')\n      .filter(Boolean).length\n    if (!Number.isFinite(remoteCount) || localCount !== remoteCount) {\n      throw new Error(\n        `${tag}: downloaded ${localCount} rows, remote reported ${remoteCount} — truncated transfer`\n      )\n    }\n\n    if (cfg.profile) {\n      writeStatus({\n        vms: {\n          ...status.state.vms,\n          [vm]: { ...status.state.vms[vm], state: 'profiling' },\n        },\n      })\n      // Profiled passes run strictly AFTER the timed runs — profiling\n      // overhead must never touch the numbers.\n      // Within one VM the second arm runs warmer (page cache, CPU\n      // governor) — a uniform few-percent deflation of every function\n      // in its profile. Alternating order across VMs cancels the drift\n      // in cross-VM aggregates.\n      const profOrder = index % 2 === 1 ? `${cand} ${base}` : `${base} ${cand}`\n      const prof = `set -e\nfor arm in ${profOrder}; do\n  if [ \"$arm\" = \"${base}\" ]; then PORT=3720; else PORT=3721; fi\n  cd /vercel/sandbox/next-$arm\n  pnpm bench:render-pipeline ${benchArgs('--capture-cpu')} \\\n    --json-out=/tmp/pr.json --artifact-dir=/vercel/sandbox/prof-$arm >/tmp/prof.log 2>&1 \\\n    || (tail -10 /tmp/prof.log; exit 1)\n  echo \"profiled $arm\"\ndone\n# Lets profile analysis split by capture order without re-deriving it\n# from VM index parity.\necho \"${profOrder}\" > /vercel/sandbox/prof-order.txt\ncd /vercel/sandbox && tar -czf profiles.tgz prof-*`\n      // Profile capture is best-effort: a failed pass or transfer on one VM\n      // must not kill collection for the whole run (the timed results are\n      // already on disk at this point). Each VM extracts into its own\n      // subdirectory so VMs don't overwrite each other's prof-<arm> dirs.\n      try {\n        await sbExec(vm, '30m', prof, `${tag}:prof`)\n        const profTgz = path.join(outDir, `profiles-vm${index}.tgz`)\n        await sb(['cp', `${vm}:/vercel/sandbox/profiles.tgz`, profTgz])\n        if (!fs.existsSync(profTgz) || fs.statSync(profTgz).size === 0) {\n          throw new Error('profile tarball missing or empty after cp')\n        }\n        const vmProfDir = path.join(outDir, `prof-vm${index}`)\n        fs.mkdirSync(vmProfDir, { recursive: true })\n        await execFileP('tar', ['-xzf', profTgz, '-C', vmProfDir])\n        console.error(`${tag}: profiles in ${vmProfDir}`)\n      } catch (profErr) {\n        console.error(\n          `${tag}: profile capture failed (timed results unaffected): ${profErr.message}`\n        )\n      }\n    }\n    writeStatus({\n      vms: {\n        ...status.state.vms,\n        [vm]: { ...status.state.vms[vm], state: 'done' },\n      },\n    })\n    return local\n  } finally {\n    if (!cfg.keep) await rmVm(vm)\n    else console.error(`${tag}: kept ${vm}`)\n  }\n}\n\n// -------------------------------------------------------------- analyze\n\nfunction analyze(cfg) {\n  // Collected JSONL + profiles land in the results db first; the stats\n  // read the db and nothing else. Import is idempotent, verify is\n  // mechanical (sqlite integrity, pairing shape, artifact hashes).\n  const db = openDb()\n  const { runId, samples, artifacts } = importRun(db, outDir)\n  const { failures, notes } = verifyDb(db, runId)\n  for (const n of notes) console.log(`note: ${n}`)\n  if (failures.length) {\n    throw new Error(`results db verify FAILED:\\n  ${failures.join('\\n  ')}`)\n  }\n  console.error(\n    `results db: ${samples} samples, ${artifacts} artifacts as ${runId} (verify ok)`\n  )\n  const rows = loadRows(db, runId)\n  const [base, cand] = cfg.arms.map((a) => a.name)\n  printRunContext((m) => console.log(m), cfg.runContext)\n  // ttfb/rss/rssHw only exist on next refs carrying the bench-client-\n  // metrics harness; metrics without data are skipped.\n  analyzeE2eRows(rows, base, cand, [\n    'rps',\n    'median',\n    'mean',\n    'p95',\n    'ttfb',\n    'docKb',\n    'gzipKb',\n    'flightKb',\n    'rss',\n    'rssHw',\n  ])\n}\n\n// ----------------------------------------------------------------- main\n\n// Dry-run: resolve as much as possible with local-only operations and\n// print the execution plan instead of touching the sandbox. Degrades\n// gracefully when prerequisites (clones, config) are missing so it can\n// be used to sanity-check a setup before committing to a real run.\nasync function plan(cfg) {\n  const lines = []\n  lines.push(\n    `mode: ${cfg.pr ? `react PR ${cfg.pr}` : cfg.arms.length ? 'react A/B' : cfg.nextPr ? `next PR ${cfg.nextPr}` : 'next A/B'}`\n  )\n  lines.push(\n    `scope: team=${CONFIG.team ?? '<UNSET — ask user, then: node config.mjs set team=... project=...>'} project=${CONFIG.project ?? '<UNSET>'}`\n  )\n  lines.push(`next repo: ${NEXT_REPO_LAZY()}`)\n  if (cfg.pr || cfg.arms.length || cfg.reactRef) {\n    const rr = REACT_REPO_LAZY()\n    lines.push(\n      `react repo: ${rr}${fs.existsSync(path.join(rr, '.git')) ? '' : ' (would clone on real run)'}`\n    )\n  } else {\n    lines.push('react: vendored in each Next ref (no react checkout needed)')\n  }\n  let arms\n  try {\n    arms = await resolveArms(cfg)\n    for (const arm of arms) {\n      if (!arm.ref) {\n        lines.push(\n          `arm ${arm.name}: react=vendored next=${arm.nextSha.slice(0, 12)}`\n        )\n        continue\n      }\n      let reactSha = '?'\n      try {\n        reactSha = (\n          await execFileP('git', [\n            '-C',\n            REACT_REPO_LAZY(),\n            'rev-parse',\n            arm.ref,\n          ])\n        ).stdout\n          .trim()\n          .slice(0, 12)\n      } catch {}\n      const cached =\n        reactSha !== '?' &&\n        fs.existsSync(path.join(CACHE, `arm-${reactSha}.tgz`))\n      lines.push(\n        `arm ${arm.name}: react=${arm.ref} (${reactSha}${cached ? ', build cached' : ', would build remotely ~15m'}) next=${arm.nextSha.slice(0, 12)}`\n      )\n      lines.push(\n        `  CI gate: react commit must be CI-green (or --allow-ungated after sandbox-gate.mjs)`\n      )\n    }\n  } catch (e) {\n    lines.push(\n      `arms: unresolved in dry-run (${e.message.split('\\n')[0].slice(0, 120)})`\n    )\n  }\n  lines.push(\n    `then: experiment snapshot (cached by content key; ~45m if cold) -> ` +\n      `${cfg.vms} VMs x ${cfg.blocks * cfg.runs} paired ABBA runs, routes ${cfg.routes}` +\n      `${cfg.isolateRoutes ? ' (isolated)' : ''}${cfg.benchEnv ? ` env ${cfg.benchEnv}` : ''}`\n  )\n  lines.push(\n    `then: boot-level analysis (n=${cfg.vms} boots) -> claims at p<0.01 on A/A-validated infra`\n  )\n  console.log(lines.map((l) => `[dry-run] ${l}`).join('\\n'))\n}\n\nconst cfg = parseArgs()\nif (cfg.dryRun) {\n  await plan(cfg)\n  process.exit(0)\n}\nfs.mkdirSync(CACHE, { recursive: true })\nconst tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sandbox-e2e-'))\nconst outDir = path.join(CACHE, `run-${cfg.label}-${Date.now().toString(36)}`)\nfs.mkdirSync(outDir, { recursive: true })\n// stdout, not stderr: task UIs preview stdout, and these are the lines\n// a human watching the task needs.\nconsole.log(`run dir: ${outDir}`)\nstatus.file = path.join(outDir, 'status.json')\n// Long phases (remote builds, snapshot assembly) are otherwise silent\n// on stdout, which reads as a hung task in any UI that previews output.\n// A periodic one-line digest keeps the task legible without spam.\nconst interimRows = []\n// Interim display: running effect + directional confidence\n// P(effect > 0 | boots so far) — the Student-t posterior under a flat\n// prior, i.e. \"how sure are we the candidate is actually faster\".\n// Display only; runs complete their allocation and claims come from\n// the final analysis.\nfunction interimSummary() {\n  if (interimRows.length === 0 || !status.state.arms) return ''\n  const [base, cand] = cfg.arms.map((a) => a.name)\n  const cells = []\n  for (const route of cfg.routes.split(',')) {\n    for (const phase of ['single-client', 'under-load']) {\n      const perBoot = []\n      for (const vmIdx of new Set(interimRows.map((r) => r.vm))) {\n        const deltas = []\n        for (const r of interimRows.filter(\n          (x) =>\n            x.vm === vmIdx &&\n            x.route === route &&\n            x.phase === phase &&\n            x.arm === cand\n        )) {\n          const b = interimRows.find(\n            (x) =>\n              x.vm === vmIdx &&\n              x.route === route &&\n              x.phase === phase &&\n              x.arm === base &&\n              x.block === r.block &&\n              x.run === r.run\n          )\n          if (b && b.rps > 0 && r.rps > 0) deltas.push((r.rps - b.rps) / b.rps)\n        }\n        if (deltas.length)\n          perBoot.push(deltas.reduce((a, b) => a + b, 0) / deltas.length)\n      }\n      if (perBoot.length < 4) continue\n      const mean = perBoot.reduce((a, b) => a + b, 0) / perBoot.length\n      const pTwo = tTestP(perBoot)\n      const conf = Math.max(1 - pTwo / 2, pTwo / 2)\n      const confStr = conf >= 0.999 ? '>99.9%' : `${(conf * 100).toFixed(0)}%`\n      const label = `${route} ${phase === 'single-client' ? 'serial' : 'load'}:`\n      cells.push(\n        `    ${label.padEnd(19)} ${mean > 0 ? '+' : ''}${(mean * 100).toFixed(1)}% rps (${confStr} confidence)`\n      )\n    }\n  }\n  if (cells.length === 0) return ''\n  const boots = new Set(interimRows.map((r) => r.vm)).size\n  return `\\n  interim vs base (${boots} boots):\\n` + cells.join('\\n')\n}\nconst digest = setInterval(() => {\n  const vms = Object.values(status.state.vms ?? {})\n  const rows = vms.reduce((a, v) => a + (v.rows ?? 0), 0)\n  const states = {}\n  for (const v of vms) states[v.state] = (states[v.state] ?? 0) + 1\n  const vmSummary = Object.entries(states)\n    .map(([k, n]) => `${n} ${k}`)\n    .join(', ')\n  console.log(\n    `progress: ${status.state.phase}` +\n      (status.state.rowsExpected\n        ? ` — rows ${rows}/${status.state.rowsExpected}`\n        : '') +\n      (vmSummary ? ` (${vmSummary})` : '') +\n      interimSummary()\n  )\n}, 120_000)\ndigest.unref?.()\nwriteStatus({\n  label: cfg.label,\n  phase: 'resolving arms',\n  pid: process.pid,\n  startedAt: new Date().toISOString(),\n  vms: {},\n  rowsExpected: null,\n})\ntry {\n  cfg.arms = await resolveArms(cfg)\n  cfg.runContext = await describeRun(cfg)\n  printRunContext((m) => console.error(m), cfg.runContext)\n  fs.writeFileSync(\n    path.join(outDir, 'meta.json'),\n    JSON.stringify(\n      {\n        base: cfg.arms[0].name,\n        cand: cfg.arms[1].name,\n        label: cfg.label,\n        nextRef: cfg.nextRef,\n        vms: cfg.vms,\n        blocks: cfg.blocks,\n        runs: cfg.runs,\n        routes: cfg.routes,\n        pr: cfg.runContext.pr,\n        arms: cfg.runContext.arms,\n        benchEnv: cfg.benchEnv || undefined,\n      },\n      null,\n      2\n    )\n  )\n  cfg.live = makeLive(\n    cfg.arms[0].name,\n    ['rps', 'median', 'p95'],\n    (r) => `${r.route} ${r.phase}`\n  )\n  await stage(cfg, tmp)\n  console.error(\n    `arms: ${cfg.arms.map((a) => `${a.name}=${armId(a)}`).join(' ')}`\n  )\n  writeStatus({\n    phase: 'building arms + experiment snapshot',\n    arms: cfg.arms.map((a) => `${a.name}=${armId(a)}`),\n  })\n  const expSnap = await ensureExperimentSnapshot(cfg)\n  if (cfg.prepare) {\n    // A prepare run launches no measurement VMs; anything but a\n    // terminal phase here makes bench-status prescribe collecting\n    // data that never existed.\n    writeStatus({ phase: 'prepared (caches only, no measurement)', expSnap })\n    console.error(\n      `prepared: arms + experiment snapshot ${expSnap}; exiting (--prepare)`\n    )\n    process.exit(0)\n  }\n  writeStatus({\n    phase: 'measuring',\n    expSnap,\n    rowsExpected:\n      cfg.vms * cfg.blocks * cfg.runs * 2 * cfg.routes.split(',').length * 2,\n  })\n  await Promise.all(\n    Array.from({ length: cfg.vms }, (_, i) => runVm(i, cfg, expSnap, outDir))\n  )\n  writeStatus({ phase: 'analyzing' })\n  console.error(`results in ${outDir}`)\n  analyze(cfg)\n  writeStatus({ phase: 'done' })\n} catch (err) {\n  // Leave a machine-readable trace: bench-status.mjs reports dead runs\n  // and the right recovery action from this.\n  writeStatus({\n    phase: 'failed',\n    error: String((err && err.message) || err).slice(0, 500),\n  })\n  throw err\n} finally {\n  fs.rmSync(tmp, { recursive: true, force: true })\n}\n", "skills/sandbox-bench/scripts/sandbox-gate.mjs": "#!/usr/bin/env node\n// Correctness gate for React arms before spending bench compute: each\n// arm gets a sandbox VM booted from the shared react build-env snapshot\n// (created lazily if missing), extracts the arm's tree over the\n// snapshot's node_modules, and runs the jest suite in prod mode (the\n// channel the bench measures).\n// A bench number from an arm that fails its tests is meaningless —\n// always gate hand-assembled or conflict-resolved arms.\n//\n// Usage: node sandbox-gate.mjs --arms name=ref[,name=ref...]\n//        [--pattern <jest pattern>, default: full suite] [--extra \"yarn flow dom-node\"]\n//        [--snapshot snap_x] [--dry-run]\nimport { execFile, spawn } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport crypto from 'node:crypto'\nimport { loadConfig, sandboxScope, ensureReactRepo } from './config.mjs'\n\nconst execFileP = promisify(execFile)\nconst DRY_RUN = process.argv.includes('--dry-run')\nconst CONFIG = loadConfig({ requireScope: !DRY_RUN })\nconst REACT = ensureReactRepo(CONFIG)\nconst VERCEL = CONFIG.vercelBin\nconst SCOPE = CONFIG.team ? sandboxScope(CONFIG) : []\nconst SETUP_VERSION = 'v1-al2023-node24-jdk21'\nconst REACT_SNAP_CACHE = path.join(CONFIG.cacheDir, 'react-snap')\n\nfunction parseArgs() {\n  const args = { arms: [], snapshot: undefined, extra: [], pattern: '' }\n  const argv = process.argv.slice(2)\n  for (let i = 0; i < argv.length; i++) {\n    if (argv[i] === '--arms') {\n      for (const spec of argv[++i].split(',')) {\n        const [name, ref] = spec.split('=')\n        if (!name || !ref) throw new Error(`bad arm spec: ${spec}`)\n        args.arms.push({ name, ref })\n      }\n    } else if (argv[i] === '--snapshot') {\n      args.snapshot = argv[++i]\n    } else if (argv[i] === '--extra') {\n      // Extra gate command(s) run in the repo root after the jest gates,\n      // e.g. --extra \"yarn flow dom-node\".\n      args.extra.push(argv[++i])\n    } else if (argv[i] === '--pattern') {\n      args.pattern = argv[++i]\n    } else if (argv[i] === '--dry-run') {\n      // handled globally\n    } else {\n      throw new Error(`unknown arg: ${argv[i]}`)\n    }\n  }\n  if (args.arms.length === 0) throw new Error('need --arms name=ref[,...]')\n  if (args.pattern !== '' && !/^[A-Za-z0-9|_.-]+$/.test(args.pattern)) {\n    // The pattern is interpolated into the remote command line; reject\n    // anything that could smuggle extra jest flags (--passWithNoTests\n    // would turn an empty selection into a PASS).\n    throw new Error(\n      `--pattern must match [A-Za-z0-9|_.-]+, got: ${args.pattern}`\n    )\n  }\n  return args\n}\n\nasync function sb(args, opts = {}) {\n  const scoped = ['sandbox', ...args]\n  const sep = scoped.indexOf('--')\n  scoped.splice(sep < 0 ? scoped.length : sep, 0, ...SCOPE)\n  const { stdout, stderr } = await execFileP(VERCEL, scoped, {\n    maxBuffer: 64 * 1024 * 1024,\n    ...opts,\n  })\n  // The CLI prints some results (e.g. snapshot ids) on stderr; callers\n  // that parse exact values (size checks) must keep stdout-only.\n  return opts.withStderr ? `${stdout}\\n${stderr}` : stdout\n}\n\nasync function git(args) {\n  const { stdout } = await execFileP('git', ['-C', REACT, ...args], {\n    maxBuffer: 256 * 1024 * 1024,\n  })\n  return stdout.trim()\n}\n\nasync function rmVm(name) {\n  try {\n    await sb(['rm', name])\n  } catch (e) {\n    process.stderr.write(`warning: could not remove ${name}: ${e.message}\\n`)\n  }\n}\n\n// Same detached-nohup-and-poll shape as sandbox-e2e.mjs runDetached:\n// exec streams drop flakily on multi-minute silences, so never hold one.\nasync function runDetached(vm, tag, script, deadlineMin) {\n  const local = path.join(os.tmpdir(), `gate-${vm}.sh`)\n  fs.writeFileSync(\n    local,\n    // EXIT trap, not ERR: see sandbox-e2e.mjs runDetached.\n    `trap 'code=$?; if [ $code -eq 0 ]; then echo LOOPOK; else echo LOOPFAIL; fi > /vercel/sandbox/loop.done' EXIT\\nset -e\\n${script}\\n`\n  )\n  await sb(['cp', local, `${vm}:/vercel/sandbox/loop.sh`])\n  fs.rmSync(local, { force: true })\n  await sb([\n    'exec',\n    vm,\n    '--timeout',\n    '2m',\n    '--',\n    'bash',\n    '-c',\n    'rm -f /vercel/sandbox/loop.done /vercel/sandbox/loop.log; nohup bash /vercel/sandbox/loop.sh >/vercel/sandbox/loop.log 2>&1 & echo kicked',\n  ])\n  let offset = 0\n  let failures = 0\n  const deadline = Date.now() + deadlineMin * 60_000\n  while (true) {\n    await new Promise((r) => setTimeout(r, 45_000))\n    if (Date.now() > deadline) throw new Error(`${tag}: deadline exceeded`)\n    let out\n    try {\n      out = await sb([\n        'exec',\n        vm,\n        '--timeout',\n        '2m',\n        '--',\n        'bash',\n        '-c',\n        `tail -c +${offset + 1} /vercel/sandbox/loop.log | head -c 200000; printf '\\\\n@@SIZE %s @@DONE %s\\\\n' \"$(stat -c %s /vercel/sandbox/loop.log 2>/dev/null || echo 0)\" \"$(cat /vercel/sandbox/loop.done 2>/dev/null || echo no)\"`,\n      ])\n      failures = 0\n    } catch (e) {\n      if (++failures >= 6)\n        throw new Error(\n          `${tag}: ${failures} consecutive poll failures: ${e.message.slice(0, 200)}`\n        )\n      continue\n    }\n    const m = out.match(/@@SIZE (\\d+) @@DONE (\\S+)/)\n    const body = out.slice(0, out.lastIndexOf('\\n@@SIZE'))\n    for (const l of body.split('\\n')) {\n      if (l) process.stderr.write(`[${tag}] ${l}\\n`)\n    }\n    if (m) {\n      offset = Math.min(Number(m[1]), offset + 200000)\n      if (m[2] === 'LOOPOK') return\n      if (m[2] === 'LOOPFAIL')\n        throw new Error(\n          `${tag}: remote gate failed; tail:\\n${body.slice(-3000)}`\n        )\n    }\n  }\n}\n\nasync function gateArm(arm, snapshot, tmp, extra = [], pattern = '') {\n  const sha = await git(['rev-parse', arm.ref])\n  const short = sha.slice(0, 12)\n  const vm = `sbench-gate-${arm.name}-${Date.now().toString(36)}`\n  process.stderr.write(`[${arm.name}] vm ${vm} gating ${short}\\n`)\n  try {\n    await sb([\n      'create',\n      '--name',\n      vm,\n      '--snapshot',\n      snapshot,\n      '--vcpus',\n      '16',\n      '--timeout',\n      '2h',\n      '--non-persistent',\n      '--network-policy',\n      'allow-all',\n      '--tag',\n      'purpose=sandbox-bench',\n      '--silent',\n    ])\n  } catch (e) {\n    if (!/vcpu/i.test(e.message)) throw e\n    await sb([\n      'create',\n      '--name',\n      vm,\n      '--snapshot',\n      snapshot,\n      '--vcpus',\n      '8',\n      '--timeout',\n      '2h',\n      '--non-persistent',\n      '--network-policy',\n      'allow-all',\n      '--tag',\n      'purpose=sandbox-bench',\n      '--silent',\n    ])\n  }\n  try {\n    const src = path.join(tmp, `gate-src-${arm.name}.tgz`)\n    await execFileP('bash', [\n      '-c',\n      `git -C ${REACT} archive ${sha} | gzip -1 > ${src}`,\n    ])\n    await sb(['cp', src, `${vm}:/vercel/sandbox/src.tgz`])\n    const srcSize = fs.statSync(src).size\n    fs.rmSync(src, { force: true })\n    // sandbox cp can succeed on missing remote files: size-check remotely.\n    const check = await sb([\n      'exec',\n      vm,\n      '--timeout',\n      '2m',\n      '--',\n      'bash',\n      '-c',\n      `stat -c %s /vercel/sandbox/src.tgz`,\n    ])\n    if (Number(check.trim()) !== srcSize) {\n      throw new Error(\n        `${arm.name}: uploaded src.tgz size ${check.trim()} != local ${srcSize}`\n      )\n    }\n    await runDetached(\n      vm,\n      `gate:${arm.name}`,\n      // pipefail: every gate command is piped through tail, which would\n      // otherwise mask its exit status from set -e (debugged 2026-07-19:\n      // a failing flow run still printed GATE PASS).\n      `set -o pipefail\\n` +\n        `cd /vercel/sandbox/react\\n` +\n        `find . -mindepth 1 -maxdepth 1 ! -name node_modules -exec rm -rf {} +\\n` +\n        `tar -xzf ../src.tgz && rm -f ../src.tgz\\n` +\n        `echo \"== ${arm.name} ${short} prod gate (${pattern || 'full suite'}) ==\"\\n` +\n        `yarn test --prod ${pattern} --ci 2>&1 | tail -40\\n` +\n        extra\n          .map(\n            (cmd) =>\n              `echo \"== ${arm.name} extra: ${cmd} ==\"\\n${cmd} 2>&1 | tail -30\\n`\n          )\n          .join('') +\n        `echo \"== ${arm.name} GATE PASS ==\"\\n`,\n      90\n    )\n    return { arm: arm.name, sha: short, pass: true }\n  } finally {\n    await rmVm(vm)\n  }\n}\n\n// Build-env snapshot: node_modules installed + JDK for the closure\n// compiler, keyed on yarn.lock. Created once per lockfile, reused by\n// every later gate.\nconst snapshotPromises = new Map()\n\nasync function ensureReactBuildSnapshot(refSha) {\n  // Raw bytes, exactly as the e2e harness hashes it: a trim here would\n  // silently fork the cache key and build every snapshot twice.\n  const lock = (\n    await execFileP('git', ['-C', REACT, 'show', `${refSha}:yarn.lock`], {\n      maxBuffer: 256 * 1024 * 1024,\n    })\n  ).stdout\n  const memoKey = crypto.createHash('sha256').update(lock).digest('hex')\n  if (!snapshotPromises.has(memoKey)) {\n    snapshotPromises.set(memoKey, ensureReactBuildSnapshotForLock(refSha, lock))\n  }\n  return snapshotPromises.get(memoKey)\n}\n\nasync function ensureReactBuildSnapshotForLock(refSha, lock) {\n  const key = crypto\n    .createHash('sha256')\n    .update(SETUP_VERSION + lock)\n    .digest('hex')\n    .slice(0, 16)\n  const file = path.join(REACT_SNAP_CACHE, `snap-${key}`)\n  if (fs.existsSync(file)) {\n    const id = fs.readFileSync(file, 'utf8').trim()\n    try {\n      await sb(['snapshots', 'get', id])\n      return id\n    } catch {}\n  }\n  const vm = `sbench-snapbuild-${Date.now().toString(36)}`\n  console.error(\n    'creating react build-env snapshot (one-time for this yarn.lock)...'\n  )\n  await sb([\n    'create',\n    '--name',\n    vm,\n    '--runtime',\n    'node24',\n    '--vcpus',\n    '8',\n    '--timeout',\n    '45m',\n    '--non-persistent',\n    '--network-policy',\n    'allow-all',\n    '--tag',\n    'purpose=sandbox-bench',\n    '--silent',\n  ])\n  try {\n    const src = path.join(os.tmpdir(), `react-snap-src-${key}.tgz`)\n    await execFileP('bash', [\n      '-c',\n      `git -C ${REACT} archive ${refSha} | gzip -1 > ${src}`,\n    ])\n    await sb(['cp', src, `${vm}:/vercel/sandbox/src.tgz`])\n    fs.rmSync(src, { force: true })\n    await sb([\n      'exec',\n      vm,\n      '--timeout',\n      '10m',\n      '--sudo',\n      '--',\n      'dnf',\n      'install',\n      '-y',\n      '-q',\n      'java-21-amazon-corretto-headless',\n    ])\n    await runDetached(\n      vm,\n      'react-snap',\n      `mkdir -p /vercel/sandbox/react && cd /vercel/sandbox/react && tar -xzf ../src.tgz && rm -f ../src.tgz\\n` +\n        `npm i -g yarn >/dev/null 2>&1\\n` +\n        `yarn install --frozen-lockfile --ignore-engines >/dev/null 2>&1\\n` +\n        `echo react env ready\\n`,\n      30\n    )\n    const out = await sb(['snapshot', vm, '--stop', '--expiration', '30d'], {\n      withStderr: true,\n    })\n    const snapId = out.match(/snap_[A-Za-z0-9]+/)?.[0]\n    if (!snapId)\n      throw new Error(`could not parse snapshot id from: ${out.slice(-500)}`)\n    fs.mkdirSync(REACT_SNAP_CACHE, { recursive: true })\n    fs.writeFileSync(file, `${snapId}\\n`)\n    return snapId\n  } finally {\n    await rmVm(vm)\n  }\n}\n\nasync function main() {\n  const args = parseArgs()\n  if (DRY_RUN) {\n    console.log(\n      `[dry-run] gate plan: ${args.arms.map((a) => `${a.name}=${a.ref}`).join(', ')}`\n    )\n    console.log(\n      `[dry-run] per arm: 1 VM from react build-env snapshot (lazy-created), ` +\n        `yarn test --prod ${args.pattern} --ci` +\n        (args.extra.length ? `, extra: ${args.extra.join(' && ')}` : '')\n    )\n    console.log('[dry-run] PASS requires: verified test counts (pipefail on).')\n    process.exit(0)\n  }\n  // Each arm gates against ITS OWN lockfile's environment: arms with\n  // different yarn.locks must not share node_modules.\n  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sandbox-gate-'))\n  try {\n    const results = await Promise.allSettled(\n      args.arms.map(async (arm) => {\n        const sha = await git(['rev-parse', arm.ref])\n        const snapshot = args.snapshot ?? (await ensureReactBuildSnapshot(sha))\n        return gateArm(arm, snapshot, tmp, args.extra, args.pattern)\n      })\n    )\n    let failed = 0\n    for (let i = 0; i < results.length; i++) {\n      const r = results[i]\n      if (r.status === 'fulfilled') {\n        console.log(`GATE ${args.arms[i].name}: PASS (${r.value.sha})`)\n        console.log(\n          `  bench this exact sha: --arms cand=${r.value.sha} (a ref can move between gate and bench)`\n        )\n      } else {\n        failed++\n        console.log(\n          `GATE ${args.arms[i].name}: FAIL — ${r.reason.message.slice(0, 2500)}`\n        )\n      }\n    }\n    process.exit(failed ? 1 : 0)\n  } finally {\n    fs.rmSync(tmp, { recursive: true, force: true })\n  }\n}\n\nmain().catch((e) => {\n  console.error(e)\n  process.exit(1)\n})\n", "skills/sandbox-bench/scripts/sandbox-ssr.mjs": "// Remote React SSR A/B on Vercel Sandbox via the react repo's\n// fixtures/flight-ssr-bench: 8 render variants (Fizz and Flight+Fizz,\n// Node and Edge streams, sync and async), both arms always in the SAME\n// VM, paired per (block, run), ABBA order. The VM boot is the unit of\n// replication; see bench-stats.mjs.\n//\n// This is the Edge-path complement to sandbox-e2e.mjs (which measures\n// the Node path through a real Next.js app). Arms vary React only. The\n// fixture (the workload) is pinned to ONE ref for both arms — default\n// the react main tip — so only the React builds differ.\n//\n// Usage:\n//   node sandbox-ssr.mjs --pr <react pr url|num> [--vms 16] [--label x]\n//   node sandbox-ssr.mjs --arms base=<ref>,cand=<ref>\n//   Common: [--runs 2] [--fixture-ref main] [--no-profile] [--keep]\n//     [--allow-ungated] [--dry-run]\nimport fs from 'fs'\nimport os from 'os'\nimport path from 'path'\nimport { analyzeE2eRows } from './bench-stats.mjs'\nimport { openDb, importRun, loadRows, verify as verifyDb } from './bench-db.mjs'\nimport {\n  execFileP,\n  CONFIG,\n  REACT_REPO_LAZY,\n  CACHE,\n  SETUP_VERSION,\n  REACT_GH_REPO,\n  status,\n  writeStatus,\n  sb,\n  sbExec,\n  rmVm,\n  runDetached,\n  resolvePrArms,\n  assertCiGreen,\n  commitTitle,\n  printRunContext,\n  makeLive,\n  sha256,\n  snapshotIdFor,\n  takeSnapshot,\n  ensureRefArm,\n} from './bench-common.mjs'\n\nconst FIXTURE_DIR = 'fixtures/flight-ssr-bench'\n// Provenance: the Flight server/client files the fixture actually\n// executes — Node and Edge entry points, so changes touching only one\n// stream flavor still move the fingerprint — plus the shared\n// react-server runtime (hooks/cache), which none of the layer files\n// reflect.\nconst FP_FILES = [\n  'react-server-dom-webpack/cjs/react-server-dom-webpack-server.node.production.js',\n  'react-server-dom-webpack/cjs/react-server-dom-webpack-server.edge.production.js',\n  'react-server-dom-webpack/cjs/react-server-dom-webpack-client.edge.production.js',\n  'react-dom/cjs/react-dom-server.node.production.js',\n  'react-dom/cjs/react-dom-server.edge.production.js',\n  'react/cjs/react.react-server.production.js',\n]\n\nfunction parseArgs() {\n  const a = process.argv.slice(2)\n  const get = (name, dflt) => {\n    const i = a.indexOf(name)\n    return i >= 0 ? a[i + 1] : dflt\n  }\n  const arms = get('--arms', '')\n    .split(',')\n    .filter(Boolean)\n    .map((s) => {\n      const [name, src] = s.split('=')\n      if (!name || !src)\n        throw new Error(`bad arm \"${s}\" in --arms, want name=<ref>`)\n      return { name, ref: src }\n    })\n  const pr = get('--pr', undefined)\n  if ((pr ? 1 : 0) + (arms.length ? 1 : 0) !== 1) {\n    throw new Error('need exactly one of: --pr, --arms')\n  }\n  if (arms.length && arms.length !== 2)\n    throw new Error('--arms needs exactly two arms (base first)')\n  return {\n    arms,\n    pr,\n    dryRun: a.includes('--dry-run'),\n    allowUngated: a.includes('--allow-ungated'),\n    // The workload: one fixture tree shared by both arms.\n    fixtureRef: get('--fixture-ref', 'main'),\n    runs: Number(get('--runs', '2')),\n    vms: Number(get('--vms', '16')),\n    keep: a.includes('--keep'),\n    profile: !a.includes('--no-profile'),\n    label: get('--label', 'ssr'),\n  }\n}\n\n// Resolve a react ref: shas and already-fetched refs locally, branch\n// names against the remote (so \"main\" is today's main), pinned once\n// per run.\nconst reactShaMemo = new Map()\nasync function reactShaFor(ref) {\n  if (reactShaMemo.has(ref)) return reactShaMemo.get(ref)\n  const repo = REACT_REPO_LAZY()\n  let sha\n  if (/^[0-9a-f]{7,40}$/i.test(ref)) {\n    try {\n      sha = (\n        await execFileP('git', [\n          '-C',\n          repo,\n          'rev-parse',\n          '--verify',\n          `${ref}^{commit}`,\n        ])\n      ).stdout.trim()\n    } catch {}\n  }\n  if (!sha) {\n    const dst = `refs/bench-tmp/${process.pid}/ssr-${reactShaMemo.size}`\n    for (let attempt = 1; ; attempt++) {\n      try {\n        await execFileP('git', [\n          '-C',\n          repo,\n          'fetch',\n          '-q',\n          CONFIG.reactRepoUrl,\n          `+${ref}:${dst}`,\n        ])\n        break\n      } catch (e) {\n        if (attempt >= 3) throw e\n        await new Promise((r) => setTimeout(r, 2000 * attempt))\n      }\n    }\n    sha = (\n      await execFileP('git', ['-C', repo, 'rev-parse', `${dst}^{commit}`])\n    ).stdout.trim()\n  }\n  reactShaMemo.set(ref, sha)\n  return sha\n}\n\nasync function resolveArms(cfg) {\n  const arms = cfg.pr\n    ? await resolvePrArms(\n        cfg.pr,\n        REACT_REPO_LAZY(),\n        CONFIG.reactRepoUrl,\n        'main'\n      )\n    : cfg.arms\n  for (const arm of arms) {\n    arm.sha = await reactShaFor(arm.ref)\n  }\n  cfg.fixtureSha = await reactShaFor(cfg.fixtureRef)\n  console.error(\n    `fixture: ${FIXTURE_DIR} @ ${cfg.fixtureRef} (${cfg.fixtureSha.slice(0, 12)})`\n  )\n  // The fixture must emit machine-readable results; parsing its human\n  // tables would silently break as it evolves.\n  const benchJs = (\n    await execFileP(\n      'git',\n      [\n        '-C',\n        REACT_REPO_LAZY(),\n        'show',\n        `${cfg.fixtureSha}:${FIXTURE_DIR}/bench.js`,\n      ],\n      { maxBuffer: 1 << 24 }\n    )\n  ).stdout\n  if (!benchJs.includes('--json-out')) {\n    throw new Error(\n      `the fixture at ${cfg.fixtureRef} does not support --json-out; ` +\n        'pass --fixture-ref <ref that does> (see SKILL.md)'\n    )\n  }\n  // The workload is pinned; if the PR itself changes the fixture, this\n  // run will NOT measure those changes. Say so rather than silently\n  // benching something else.\n  const touched = (\n    await execFileP('git', [\n      '-C',\n      REACT_REPO_LAZY(),\n      'diff',\n      '--name-only',\n      `${arms[0].sha}..${arms[1].sha}`,\n      '--',\n      FIXTURE_DIR,\n    ])\n  ).stdout.trim()\n  if (touched) {\n    cfg.fixtureTouchedByPr = true\n    console.error(\n      `NOTE: the candidate changes ${FIXTURE_DIR} itself; the benchmark ` +\n        `uses the pinned fixture (${cfg.fixtureSha.slice(0, 12)}) and does ` +\n        `not measure those fixture changes:\\n${touched}`\n    )\n  }\n  return arms\n}\n\n// Snapshot: fixture installed + both arms' builds staged, so run VMs\n// boot straight into measurement.\nasync function ensureSsrSnapshot(cfg) {\n  const key = await sha256(\n    SETUP_VERSION +\n      'ssr1' +\n      cfg.fixtureSha +\n      cfg.arms.map((a) => `${a.name}=${a.sha}`).join()\n  )\n  let id = await snapshotIdFor(CACHE, key)\n  if (id) return id\n  const vm = `sbench-ssrsnap-${Date.now().toString(36)}`\n  console.error(\n    `creating ssr snapshot (one-time for fixture=${cfg.fixtureSha.slice(0, 12)} ` +\n      `arms=${cfg.arms.map((a) => a.sha.slice(0, 12)).join(',')})...`\n  )\n  await sb([\n    'create',\n    '--name',\n    vm,\n    '--runtime',\n    'node24',\n    '--vcpus',\n    '8',\n    '--timeout',\n    '45m',\n    '--non-persistent',\n    '--network-policy',\n    'allow-all',\n    '--tag',\n    'purpose=sandbox-bench',\n    '--silent',\n  ])\n  try {\n    const fixtureTgz = path.join(\n      os.tmpdir(),\n      `ssr-fixture-${cfg.fixtureSha.slice(0, 12)}.tgz`\n    )\n    await execFileP('bash', [\n      '-c',\n      `git -C ${REACT_REPO_LAZY()} archive ${cfg.fixtureSha} ${FIXTURE_DIR} | gzip -1 > ${fixtureTgz}`,\n    ])\n    await sb(['cp', fixtureTgz, `${vm}:/vercel/sandbox/fixture.tgz`])\n    fs.rmSync(fixtureTgz, { force: true })\n    for (const arm of cfg.arms) {\n      await sb(['cp', arm.tgz, `${vm}:/vercel/sandbox/arm-${arm.name}.tgz`])\n    }\n    const extractArms = cfg.arms\n      .map(\n        (a) =>\n          `mkdir -p /vercel/sandbox/arm-${a.name} && tar -xzf /vercel/sandbox/arm-${a.name}.tgz -C /vercel/sandbox/arm-${a.name}`\n      )\n      .join('\\n')\n    // Smoke: one full bench pass on the base arm proves the fixture\n    // installs, builds its bundle, and emits parseable JSON before 16\n    // VMs boot from this snapshot.\n    await sbExec(\n      vm,\n      '35m',\n      `set -e\nnpm i -g yarn >/dev/null 2>&1\nmkdir -p /vercel/sandbox/fixture\ntar -xzf /vercel/sandbox/fixture.tgz --strip-components=2 -C /vercel/sandbox/fixture\n${extractArms}\ncd /vercel/sandbox/fixture\necho \"PHASE install $(date +%s)\"\nyarn install --ignore-engines >/tmp/install.log 2>&1 || (tail -10 /tmp/install.log; exit 1)\necho \"PHASE smoke $(date +%s)\"\nfor p in /vercel/sandbox/arm-${cfg.arms[0].name}/build/oss-experimental/*; do rm -rf node_modules/$(basename $p); done\ncp -r /vercel/sandbox/arm-${cfg.arms[0].name}/build/oss-experimental/* node_modules/\nNODE_ENV=production node --expose-gc bench.js --json-out=/tmp/smoke.json >/tmp/smoke.log 2>&1 || (tail -20 /tmp/smoke.log; exit 1)\nnode -e 'const j=require(\"/tmp/smoke.json\"); if (!Array.isArray(j.results) || j.results.length < 4) { console.error(\"smoke json bad\"); process.exit(1); }'\nrm -f /tmp/smoke.json /vercel/sandbox/fixture.tgz /vercel/sandbox/arm-*.tgz\necho \"PHASE done $(date +%s)\"\necho ssr env ready`,\n      'ssrsnap'\n    )\n    return await takeSnapshot(vm, CACHE, key)\n  } finally {\n    await rmVm(vm)\n  }\n}\n\n// ------------------------------------------------------------------ run\n\nasync function runVm(index, cfg, snap, outDir) {\n  const vm = `sbench-${cfg.label}-${index}-${Date.now().toString(36)}`\n  const tag = `vm${index}`\n  console.error(`${tag}: creating ${vm} from ssr snapshot`)\n  writeStatus({\n    vms: { ...status.state.vms, [vm]: { state: 'booting', rows: 0 } },\n  })\n  await sb([\n    'create',\n    '--name',\n    vm,\n    '--snapshot',\n    snap,\n    '--vcpus',\n    '8',\n    '--timeout',\n    '5h',\n    '--non-persistent',\n    '--network-policy',\n    'allow-all',\n    '--tag',\n    'purpose=sandbox-bench',\n    '--silent',\n  ])\n  try {\n    const [base, cand] = cfg.arms.map((a) => a.name)\n    // Row emitter: fixture JSON -> one row per (variant, phase), variant\n    // names normalized to the server's kebab keys (\"Flight + Fizz\n    // (Edge, async)\" -> flight-edge-async). Metrics are OMITTED when\n    // absent — a zero would pair against a real value as a fabricated\n    // -100% claim.\n    const emit = `\n      const [,run,arm,fp,ver,cpu]=process.argv;\n      const key=(n)=>n.toLowerCase().replace(\"flight + fizz\",\"flight\")\n        .replace(/[(),]/g,\"\").trim().replace(/\\\\s+/g,\"-\");\n      const rows=[];\n      const inj=require(\"/tmp/inject.json\");\n      for (const r of inj.results) {\n        const row={block:+run,arm,run:1,fp,ver,cpu,route:key(r.name),phase:\"inject\",\n          mean:r.mean,median:r.median,p95:r.p95};\n        if (r.gcTotalMs>0) row.gcMs=r.gcTotalMs/r.iterations;\n        if (r.heapAfter>0) row.heapMb=r.heapAfter/1048576;\n        rows.push(row);\n      }\n      const srv=require(\"/tmp/server.json\");\n      for (const r of srv.results) {\n        const row={block:+run,arm,run:1,fp,ver,cpu,route:key(r.name),\n          phase:\"server-c\"+r.concurrency,rps:r.reqPerSec,median:r.latencyMedian};\n        if (r.latencyP99>0) row.p99=r.latencyP99;\n        if (r.errors>0) row.errors=r.errors;\n        rows.push(row);\n      }\n      console.log(rows.map(r=>JSON.stringify(r)).join(\"\\\\n\"));\n    `\n    const loop = `set -e\nVMINDEX=${index}\nCPU=$(grep -m1 'model name' /proc/cpuinfo | cut -d: -f2- | sed 's/^ //')\n: > /vercel/sandbox/results.jsonl\ncd /vercel/sandbox/fixture\nfor arm in ${base} ${cand}; do\n  V=$(node -e \"console.log(require('/vercel/sandbox/arm-$arm/build/oss-experimental/react/package.json').version)\")\n  F=$(cat ${FP_FILES.map((f) => `/vercel/sandbox/arm-$arm/build/oss-experimental/${f}`).join(' ')} | sha256sum | cut -c1-12)\n  echo \"arm $arm ver=$V fp=$F\"\n  eval \"VER_$arm=$V; FP_$arm=$F\"\ndone\n# Identical fingerprints can be legitimate (arms differing only in\n# files outside FP_FILES), so warn, not fail.\nif [ \"$FP_${base}\" = \"$FP_${cand}\" ]; then\n  echo \"WARNING: arms fingerprint identically ($FP_${base}) — the hashed React builds are byte-identical; verify the arms differ where intended\"\nfi\nfor run in $(seq 1 ${cfg.runs}); do\n  # Alternate within the boot AND stagger by VM index so no arm owns\n  # the cold first slot across the fleet.\n  if [ $(((run + VMINDEX) % 2)) = 1 ]; then ORDER=\"${cand} ${base}\"; else ORDER=\"${base} ${cand}\"; fi\n  for arm in $ORDER; do\n    for p in /vercel/sandbox/arm-$arm/build/oss-experimental/*; do rm -rf node_modules/$(basename $p); done\n    cp -r /vercel/sandbox/arm-$arm/build/oss-experimental/* node_modules/\n    NODE_ENV=production node --expose-gc bench.js --json-out=/tmp/inject.json >/tmp/bench.log 2>&1 \\\n      || (tail -20 /tmp/bench.log; exit 1)\n    NODE_ENV=production node bench-server.js --bench --json-out=/tmp/server.json >/tmp/server.log 2>&1 \\\n      || (tail -20 /tmp/server.log; exit 1)\n    eval \"FP=\\\\$FP_$arm; VER=\\\\$VER_$arm\"\n    node -e '${emit}' \"$run\" \"$arm\" \"$FP\" \"$VER\" \"$CPU\" > /tmp/rows.txt\n    cat /tmp/rows.txt >> /vercel/sandbox/results.jsonl\n    sed 's/^/ROW /' /tmp/rows.txt\n    echo \"run $run $arm done\"\n  done\ndone\nwc -l /vercel/sandbox/results.jsonl`\n    let vmRows = 0\n    const out = await runDetached(\n      vm,\n      tag,\n      loop,\n      (row) => {\n        vmRows++\n        writeStatus({\n          vms: {\n            ...status.state.vms,\n            [vm]: { state: 'measuring', rows: vmRows },\n          },\n        })\n        cfg.live(index, row)\n      },\n      160\n    )\n    writeStatus({\n      vms: {\n        ...status.state.vms,\n        [vm]: { ...status.state.vms[vm], state: 'collecting' },\n      },\n    })\n    const local = path.join(outDir, `results-vm${index}.jsonl`)\n    await sb(['cp', `${vm}:/vercel/sandbox/results.jsonl`, local])\n    const remoteCount = Number(\n      out.match(/(\\d+) \\/vercel\\/sandbox\\/results\\.jsonl/)?.[1] ?? NaN\n    )\n    const localCount = fs\n      .readFileSync(local, 'utf8')\n      .trim()\n      .split('\\n')\n      .filter(Boolean).length\n    if (!Number.isFinite(remoteCount) || localCount !== remoteCount) {\n      throw new Error(\n        `${tag}: downloaded ${localCount} rows, remote reported ${remoteCount} — truncated transfer`\n      )\n    }\n    if (cfg.profile) {\n      writeStatus({\n        vms: {\n          ...status.state.vms,\n          [vm]: { ...status.state.vms[vm], state: 'profiling' },\n        },\n      })\n      // Strictly AFTER the timed runs — profiling never touches the\n      // numbers. Best-effort: a failed pass must not kill collection.\n      // Second-arm-runs-warmer drift cancels across VMs (see\n      // sandbox-e2e.mjs).\n      const profOrder = index % 2 === 1 ? `${cand} ${base}` : `${base} ${cand}`\n      const prof = `set -e\ncd /vercel/sandbox/fixture\nfor arm in ${profOrder}; do\n  for p in /vercel/sandbox/arm-$arm/build/oss-experimental/*; do rm -rf node_modules/$(basename $p); done\n  cp -r /vercel/sandbox/arm-$arm/build/oss-experimental/* node_modules/\n  NODE_ENV=production node --expose-gc bench.js --profile >/tmp/prof.log 2>&1 || (tail -10 /tmp/prof.log; exit 1)\n  mkdir -p /vercel/sandbox/prof-$arm && mv build/profiles/* /vercel/sandbox/prof-$arm/\n  echo \"profiled $arm\"\ndone\n# Lets profile analysis split by capture order (see sandbox-e2e.mjs).\necho \"${profOrder}\" > /vercel/sandbox/prof-order.txt\ncd /vercel/sandbox && tar -czf profiles.tgz prof-*`\n      try {\n        await sbExec(vm, '40m', prof, `${tag}:prof`)\n        const profTgz = path.join(outDir, `profiles-vm${index}.tgz`)\n        await sb(['cp', `${vm}:/vercel/sandbox/profiles.tgz`, profTgz])\n        if (!fs.existsSync(profTgz) || fs.statSync(profTgz).size === 0) {\n          throw new Error('profile tarball missing or empty after cp')\n        }\n        const vmProfDir = path.join(outDir, `prof-vm${index}`)\n        fs.mkdirSync(vmProfDir, { recursive: true })\n        await execFileP('tar', ['-xzf', profTgz, '-C', vmProfDir])\n        console.error(`${tag}: profiles in ${vmProfDir}`)\n      } catch (profErr) {\n        console.error(\n          `${tag}: profile capture failed (timed results unaffected): ${profErr.message}`\n        )\n      }\n    }\n    writeStatus({\n      vms: {\n        ...status.state.vms,\n        [vm]: { ...status.state.vms[vm], state: 'done' },\n      },\n    })\n    return local\n  } finally {\n    if (!cfg.keep) await rmVm(vm)\n    else console.error(`${tag}: kept ${vm}`)\n  }\n}\n\nexport const SSR_METRICS = [\n  'rps',\n  'mean',\n  'median',\n  'p95',\n  'p99',\n  'gcMs',\n  'heapMb',\n]\n\nfunction analyze(cfg, outDir) {\n  const db = openDb()\n  const { runId, samples, artifacts } = importRun(db, outDir)\n  const { failures, notes } = verifyDb(db, runId)\n  for (const n of notes) console.log(`note: ${n}`)\n  if (failures.length) {\n    throw new Error(`results db verify FAILED:\\n  ${failures.join('\\n  ')}`)\n  }\n  console.error(\n    `results db: ${samples} samples, ${artifacts} artifacts as ${runId} (verify ok)`\n  )\n  const rows = loadRows(db, runId)\n  const [base, cand] = cfg.arms.map((a) => a.name)\n  printRunContext((m) => console.log(m), cfg.runContext)\n  console.log(`fixture: ${cfg.fixtureSha.slice(0, 12)} (${cfg.fixtureRef})`)\n  analyzeE2eRows(rows, base, cand, SSR_METRICS)\n}\n\n// ----------------------------------------------------------------- main\n\nasync function plan(cfg) {\n  const lines = []\n  lines.push(\n    `mode: ${cfg.pr ? `react PR ${cfg.pr} (ssr fixture suite)` : 'react A/B (ssr fixture suite)'}`\n  )\n  lines.push(\n    `scope: team=${CONFIG.team ?? '<UNSET — ask user, then: node config.mjs set team=... project=...>'} project=${CONFIG.project ?? '<UNSET>'}`\n  )\n  try {\n    const arms = await resolveArms(cfg)\n    for (const arm of arms) {\n      const cached = fs\n        .readdirSync(CACHE)\n        .some((f) => f.startsWith(`arm-${arm.sha.slice(0, 12)}`))\n      lines.push(\n        `arm ${arm.name}: react=${arm.sha.slice(0, 12)} (${cached ? 'build cached' : 'would build remotely ~15m'})`\n      )\n      lines.push(\n        `  CI gate: react commit must be CI-green (or --allow-ungated after sandbox-gate.mjs)`\n      )\n    }\n    lines.push(\n      `fixture: ${FIXTURE_DIR} @ ${cfg.fixtureSha.slice(0, 12)} (pinned, both arms)`\n    )\n  } catch (e) {\n    lines.push(\n      `arms: unresolved in dry-run (${e.message.split('\\n')[0].slice(0, 120)})`\n    )\n  }\n  lines.push(\n    `then: ssr snapshot (cached by content key; ~20m if cold) -> ` +\n      `${cfg.vms} VMs x ${cfg.runs} paired ABBA runs, 8 variants x (inject + server c=1/c=10)`\n  )\n  lines.push(\n    `then: boot-level analysis (n=${cfg.vms} boots) -> claims at p<0.01 on A/A-validated infra`\n  )\n  console.log(lines.map((l) => `[dry-run] ${l}`).join('\\n'))\n}\n\nconst cfg = parseArgs()\nif (cfg.dryRun) {\n  await plan(cfg)\n  process.exit(0)\n}\nfs.mkdirSync(CACHE, { recursive: true })\nconst outDir = path.join(CACHE, `run-${cfg.label}-${Date.now().toString(36)}`)\nfs.mkdirSync(outDir, { recursive: true })\nconsole.log(`run dir: ${outDir}`)\nstatus.file = path.join(outDir, 'status.json')\nconst digest = setInterval(() => {\n  const vms = Object.values(status.state.vms ?? {})\n  const rows = vms.reduce((a, v) => a + (v.rows ?? 0), 0)\n  const states = {}\n  for (const v of vms) states[v.state] = (states[v.state] ?? 0) + 1\n  const vmSummary = Object.entries(states)\n    .map(([k, n]) => `${n} ${k}`)\n    .join(', ')\n  console.log(\n    `progress: ${status.state.phase}` +\n      (status.state.rowsExpected\n        ? ` — rows ${rows}/${status.state.rowsExpected}`\n        : '') +\n      (vmSummary ? ` (${vmSummary})` : '')\n  )\n}, 120_000)\ndigest.unref?.()\nwriteStatus({\n  label: cfg.label,\n  phase: 'resolving arms',\n  pid: process.pid,\n  startedAt: new Date().toISOString(),\n  vms: {},\n  rowsExpected: null,\n})\ntry {\n  cfg.arms = await resolveArms(cfg)\n  // Human context for the analysis header and meta.json.\n  const num = String(cfg.pr ?? '').match(/(\\d+)\\/?$/)?.[1]\n  let pr\n  if (num) {\n    pr = { url: `https://github.com/${REACT_GH_REPO}/pull/${num}` }\n    try {\n      pr.title = (\n        await execFileP('gh', [\n          'api',\n          `repos/${REACT_GH_REPO}/pulls/${num}`,\n          '--jq',\n          '.title',\n        ])\n      ).stdout.trim()\n    } catch {}\n  }\n  cfg.runContext = {\n    pr,\n    arms: [],\n  }\n  for (const a of cfg.arms) {\n    cfg.runContext.arms.push({\n      name: a.name,\n      title: await commitTitle(REACT_REPO_LAZY(), a.sha),\n    })\n  }\n  printRunContext((m) => console.error(m), cfg.runContext)\n  for (const arm of cfg.arms) {\n    await assertCiGreen(arm.sha, arm.name, cfg.allowUngated)\n    await ensureRefArm(arm)\n  }\n  fs.writeFileSync(\n    path.join(outDir, 'meta.json'),\n    JSON.stringify(\n      {\n        base: cfg.arms[0].name,\n        cand: cfg.arms[1].name,\n        label: cfg.label,\n        suite: 'ssr',\n        fixtureRef: cfg.fixtureRef,\n        fixtureSha: cfg.fixtureSha,\n        fixtureTouchedByPr: cfg.fixtureTouchedByPr || undefined,\n        vms: cfg.vms,\n        blocks: 1,\n        runs: cfg.runs,\n        pr: cfg.runContext.pr,\n        arms: cfg.runContext.arms,\n      },\n      null,\n      2\n    )\n  )\n  cfg.live = makeLive(\n    cfg.arms[0].name,\n    ['median', 'rps'],\n    (r) => `${r.route} ${r.phase}`\n  )\n  writeStatus({\n    phase: 'building ssr snapshot',\n    arms: cfg.arms.map((a) => `${a.name}=${a.sha.slice(0, 12)}`),\n  })\n  const snap = await ensureSsrSnapshot(cfg)\n  writeStatus({ phase: 'measuring', snap })\n  await Promise.all(\n    Array.from({ length: cfg.vms }, (_, i) => runVm(i, cfg, snap, outDir))\n  )\n  writeStatus({ phase: 'analyzing' })\n  console.error(`results in ${outDir}`)\n  analyze(cfg, outDir)\n  writeStatus({ phase: 'done' })\n} catch (err) {\n  writeStatus({\n    phase: 'failed',\n    error: String((err && err.message) || err).slice(0, 500),\n  })\n  throw err\n} finally {\n  clearInterval(digest)\n}\n", "skills/sandbox-bench/scripts/sandbox-sweep.mjs": "// List/remove leaked bench sandboxes. Every VM the skill's scripts\n// create is named sbench-* and tagged purpose=sandbox-bench; the\n// harnesses remove their VMs in finally blocks, but a killed local\n// process leaks them until their timeout.\n//\n// The project may be shared, so removal is deliberately conservative:\n// a VM is only listed when its name matches, its tag matches, AND it is\n// older than --min-age-hours (default 3 — longer than any healthy run),\n// and removal is per exact listed name.\n//\n//   node sandbox-sweep.mjs                     # list what would be removed\n//   node sandbox-sweep.mjs --yes               # remove\n//   node sandbox-sweep.mjs --min-age-hours 0   # include fresh VMs (danger:\n//                                              # only when nothing is active)\nimport { execFile } from 'child_process'\nimport { promisify } from 'util'\nimport { loadConfig, sandboxScope } from './config.mjs'\n\nconst execFileP = promisify(execFile)\nconst CONFIG = loadConfig()\nconst SCOPE = sandboxScope(CONFIG)\nconst argv = process.argv.slice(2)\nconst minAgeHours = argv.includes('--min-age-hours')\n  ? Number(argv[argv.indexOf('--min-age-hours') + 1])\n  : 3\n\n// Age from the CLI's \"CREATED\" column (\"32 minutes ago\", \"2 hours ago\").\nfunction ageHours(words) {\n  const i = words.findIndex((w) => w === 'ago')\n  if (i < 2) return Infinity\n  const n = Number(words[i - 2])\n  const unit = words[i - 1]\n  if (!Number.isFinite(n)) return Infinity\n  if (unit.startsWith('second')) return n / 3600\n  if (unit.startsWith('minute')) return n / 60\n  if (unit.startsWith('hour')) return n\n  return n * 24\n}\n\n// Paginate: the CLI prints a cursor hint line when more pages exist.\nconst found = []\nlet cursor\nfor (let page = 0; page < 50; page++) {\n  const args = ['sandbox', 'list', '--limit', '100', ...SCOPE]\n  if (cursor) args.push('--cursor', cursor)\n  const { stdout, stderr } = await execFileP(CONFIG.vercelBin, args, {\n    maxBuffer: 1 << 24,\n  })\n  for (const line of stdout.split('\\n')) {\n    const words = line.trim().split(/\\s+/)\n    const name = words[0]\n    if (!/^sbench-/.test(name)) continue\n    if (!line.includes('purpose:sandbox-bench')) continue\n    const age = ageHours(words)\n    if (age < minAgeHours) {\n      console.log(\n        `skipping ${name} (${age.toFixed(1)}h old < --min-age-hours ${minAgeHours})`\n      )\n      continue\n    }\n    found.push(name)\n  }\n  cursor = `${stdout}\\n${stderr}`.match(/--cursor\\s+(\\S+)/)?.[1]\n  if (!cursor) break\n}\n\nif (!found.length) {\n  console.log('no leaked bench sandboxes found')\n  process.exit(0)\n}\nconst doIt = argv.includes('--yes')\nlet failures = 0\nfor (const name of found) {\n  if (doIt) {\n    try {\n      await execFileP(CONFIG.vercelBin, ['sandbox', 'rm', name, ...SCOPE])\n      console.log(`removed ${name}`)\n    } catch (e) {\n      failures++\n      console.error(`could not remove ${name}: ${e.message.split('\\n')[0]}`)\n    }\n  } else {\n    console.log(`would remove ${name} (pass --yes)`)\n  }\n}\nprocess.exit(failures ? 1 : 0)\n", "skills/update-docs/SKILL.md": "---\nname: update-docs\ndescription: This skill should be used when the user asks to \"update documentation for my changes\", \"check docs for this PR\", \"what docs need updating\", \"sync docs with code\", \"scaffold docs for this feature\", \"document this feature\", \"review docs completeness\", \"add docs for this change\", \"what documentation is affected\", \"docs impact\", or mentions \"docs/\", \"docs/01-app\", \"docs/02-pages\", \"MDX\", \"documentation update\", \"API reference\", \".mdx files\". Provides guided workflow for updating Next.js documentation based on code changes.\nmetadata:\n  internal: true\n---\n\n# Next.js Documentation Updater\n\nGuides you through updating Next.js documentation based on code changes on the active branch. Designed for maintainers reviewing PRs for documentation completeness.\n\n## Quick Start\n\n1. **Analyze changes**: Run `git diff canary...HEAD --stat` to see what files changed\n2. **Identify affected docs**: Map changed source files to documentation paths\n3. **Review each doc**: Walk through updates with user confirmation\n4. **Validate**: Run `pnpm lint` to check formatting\n5. **Commit**: Stage documentation changes\n\n## Workflow: Analyze Code Changes\n\n### Step 1: Get the diff\n\n```bash\n# See all changed files on this branch\ngit diff canary...HEAD --stat\n\n# See changes in specific areas\ngit diff canary...HEAD -- packages/next/src/\n```\n\n### Step 2: Identify documentation-relevant changes\n\nLook for changes in these areas:\n\n| Source Path                            | Likely Doc Impact           |\n| -------------------------------------- | --------------------------- |\n| `packages/next/src/client/components/` | Component API reference     |\n| `packages/next/src/server/`            | Function API reference      |\n| `packages/next/src/shared/lib/`        | Varies by export            |\n| `packages/next/src/build/`             | Configuration or build docs |\n| `packages/next/src/lib/`               | Various features            |\n\n### Step 3: Map to documentation files\n\nUse the code-to-docs mapping in `references/CODE-TO-DOCS-MAPPING.md` to find corresponding documentation files.\n\nExample mappings:\n\n- `src/client/components/image.tsx` → `docs/01-app/03-api-reference/02-components/image.mdx`\n- `src/server/config-shared.ts` → `docs/01-app/03-api-reference/05-config/`\n\n## Workflow: Update Existing Documentation\n\n### Step 1: Read the current documentation\n\nBefore making changes, read the existing doc to understand:\n\n- Current structure and sections\n- Frontmatter fields in use\n- Whether it uses `<AppOnly>` / `<PagesOnly>` for router-specific content\n\n### Step 2: Identify what needs updating\n\nCommon updates include:\n\n- **New props/options**: Add to the props table and create a section explaining usage\n- **Changed behavior**: Update descriptions and examples\n- **Deprecated features**: Add deprecation notices and migration guidance\n- **New examples**: Add code blocks following conventions\n\n### Step 3: Apply updates with confirmation\n\nFor each change:\n\n1. Show the user what you plan to change\n2. Wait for confirmation before editing\n3. Apply the edit\n4. Move to the next change\n\n### Step 4: Check for shared content\n\nIf the doc uses the `source` field pattern (common for Pages Router docs), the source file is the one to edit. Example:\n\n```yaml\n# docs/02-pages/... file with shared content\n---\nsource: app/building-your-application/optimizing/images\n---\n```\n\nEdit the App Router source, not the Pages Router file.\n\n### Step 5: Validate changes\n\n```bash\npnpm lint          # Check formatting\npnpm prettier-fix  # Auto-fix formatting issues\n```\n\n## Workflow: Scaffold New Feature Documentation\n\nUse this when adding documentation for entirely new features.\n\n### Step 1: Determine the doc type\n\n| Feature Type        | Doc Location                                        | Template         |\n| ------------------- | --------------------------------------------------- | ---------------- |\n| New component       | `docs/01-app/03-api-reference/02-components/`       | API Reference    |\n| New function        | `docs/01-app/03-api-reference/04-functions/`        | API Reference    |\n| New config option   | `docs/01-app/03-api-reference/05-config/`           | Config Reference |\n| New concept/guide   | `docs/01-app/02-guides/`                            | Guide            |\n| New file convention | `docs/01-app/03-api-reference/03-file-conventions/` | File Convention  |\n\n### Step 2: Create the file with proper naming\n\n- Use kebab-case: `my-new-feature.mdx`\n- Add numeric prefix if ordering matters: `05-my-new-feature.mdx`\n- Place in the correct directory based on feature type\n\n### Step 3: Use the appropriate template\n\n**API Reference Template:**\n\n```mdx\n---\ntitle: Feature Name\ndescription: Brief description of what this feature does.\n---\n\n{/* The content of this doc is shared between the app and pages router. You can use the `<PagesOnly>Content</PagesOnly>` component to add content that is specific to the Pages Router. Any shared content should not be wrapped in a component. */}\n\nBrief introduction to the feature.\n\n## Reference\n\n### Props\n\n<div style={{ overflowX: 'auto', width: '100%' }}>\n\n| Prop                    | Example            | Type   | Status   |\n| ----------------------- | ------------------ | ------ | -------- |\n| [`propName`](#propname) | `propName=\"value\"` | String | Required |\n\n</div>\n\n#### `propName`\n\nDescription of the prop.\n\n\\`\\`\\`tsx filename=\"app/example.tsx\" switcher\n// TypeScript example\n\\`\\`\\`\n\n\\`\\`\\`jsx filename=\"app/example.js\" switcher\n// JavaScript example\n\\`\\`\\`\n```\n\n**Guide Template:**\n\n```mdx\n---\ntitle: How to do X in Next.js\nnav_title: X\ndescription: Learn how to implement X in your Next.js application.\n---\n\nIntroduction explaining why this guide is useful.\n\n## Prerequisites\n\nWhat the reader needs to know before starting.\n\n## Step 1: First Step\n\nExplanation and code example.\n\n\\`\\`\\`tsx filename=\"app/example.tsx\" switcher\n// Code example\n\\`\\`\\`\n\n## Step 2: Second Step\n\nContinue with more steps...\n\n## Next Steps\n\nRelated topics to explore.\n```\n\n### Step 4: Add related links\n\nUpdate frontmatter with related documentation:\n\n```yaml\nrelated:\n  title: Next Steps\n  description: Learn more about related features.\n  links:\n    - app/api-reference/functions/related-function\n    - app/guides/related-guide\n```\n\n## Documentation Conventions\n\nSee `references/DOC-CONVENTIONS.md` for complete formatting rules.\n\n### Quick Reference\n\n**Frontmatter (required):**\n\n```yaml\n---\ntitle: Page Title (2-3 words)\ndescription: One or two sentences describing the page.\n---\n```\n\n**Code blocks:**\n\n```\n\\`\\`\\`tsx filename=\"app/page.tsx\" switcher\n// TypeScript first\n\\`\\`\\`\n\n\\`\\`\\`jsx filename=\"app/page.js\" switcher\n// JavaScript second\n\\`\\`\\`\n```\n\n**Router-specific content:**\n\n```mdx\n<AppOnly>Content only for App Router docs.</AppOnly>\n\n<PagesOnly>Content only for Pages Router docs.</PagesOnly>\n```\n\n**Notes:**\n\n```mdx\n> **Good to know**: Single line note.\n\n> **Good to know**:\n>\n> - Multi-line note point 1\n> - Multi-line note point 2\n```\n\n## Validation Checklist\n\nBefore committing documentation changes:\n\n- [ ] Frontmatter has `title` and `description`\n- [ ] Code blocks have `filename` attribute\n- [ ] TypeScript examples use `switcher` with JS variant\n- [ ] Props tables are properly formatted\n- [ ] Related links point to valid paths\n- [ ] `pnpm lint` passes\n- [ ] Changes render correctly (if preview available)\n\n## References\n\n- `references/DOC-CONVENTIONS.md` - Complete frontmatter and formatting rules\n- `references/CODE-TO-DOCS-MAPPING.md` - Source code to documentation mapping\n", "skills/update-docs/references/CODE-TO-DOCS-MAPPING.md": "# Code to Documentation Mapping\n\nMaps Next.js source code directories to their corresponding documentation files.\n\n## Core Mappings\n\n### Components\n\n| Source Path                                      | Documentation Path                                      |\n| ------------------------------------------------ | ------------------------------------------------------- |\n| `packages/next/src/client/components/image.tsx`  | `docs/01-app/03-api-reference/02-components/image.mdx`  |\n| `packages/next/src/client/components/link.tsx`   | `docs/01-app/03-api-reference/02-components/link.mdx`   |\n| `packages/next/src/client/components/script.tsx` | `docs/01-app/03-api-reference/02-components/script.mdx` |\n| `packages/next/src/client/components/form.tsx`   | `docs/01-app/03-api-reference/02-components/form.mdx`   |\n\n### Functions\n\n| Source Path                                          | Documentation Path                                                |\n| ---------------------------------------------------- | ----------------------------------------------------------------- |\n| `packages/next/src/server/request/`                  | `docs/01-app/03-api-reference/04-functions/`                      |\n| `packages/next/src/server/lib/metadata/`             | `docs/01-app/03-api-reference/04-functions/generate-metadata.mdx` |\n| `packages/next/src/client/components/navigation.tsx` | `docs/01-app/03-api-reference/04-functions/use-router.mdx`        |\n| `packages/next/src/client/components/navigation.tsx` | `docs/01-app/03-api-reference/04-functions/use-pathname.mdx`      |\n| `packages/next/src/client/components/navigation.tsx` | `docs/01-app/03-api-reference/04-functions/use-search-params.mdx` |\n\n### File Conventions\n\n| Source Path                                | Documentation Path                                            |\n| ------------------------------------------ | ------------------------------------------------------------- |\n| `packages/next/src/build/webpack/loaders/` | `docs/01-app/03-api-reference/03-file-conventions/`           |\n| `packages/next/src/server/app-render/`     | `docs/01-app/03-api-reference/03-file-conventions/layout.mdx` |\n| `packages/next/src/server/app-render/`     | `docs/01-app/03-api-reference/03-file-conventions/page.mdx`   |\n\n### Configuration\n\n| Source Path                                 | Documentation Path                                          |\n| ------------------------------------------- | ----------------------------------------------------------- |\n| `packages/next/src/server/config-shared.ts` | `docs/01-app/03-api-reference/05-config/01-next-config-js/` |\n| `packages/next/src/server/config.ts`        | `docs/01-app/03-api-reference/05-config/01-next-config-js/` |\n| `packages/next/src/build/webpack-config.ts` | `docs/01-app/03-api-reference/05-config/01-next-config-js/` |\n\n### Directives\n\n| Source Path                              | Documentation Path                                          |\n| ---------------------------------------- | ----------------------------------------------------------- |\n| `packages/next/src/server/use-cache/`    | `docs/01-app/03-api-reference/01-directives/use-cache.mdx`  |\n| `packages/next/src/client/use-client.ts` | `docs/01-app/03-api-reference/01-directives/use-client.mdx` |\n| `packages/next/src/server/use-server.ts` | `docs/01-app/03-api-reference/01-directives/use-server.mdx` |\n\n### Metadata File Conventions\n\n| Source Path                       | Documentation Path                                                                 |\n| --------------------------------- | ---------------------------------------------------------------------------------- |\n| `packages/next/src/lib/metadata/` | `docs/01-app/03-api-reference/03-file-conventions/01-metadata/`                    |\n| Metadata icons handling           | `docs/01-app/03-api-reference/03-file-conventions/01-metadata/app-icons.mdx`       |\n| Open Graph images                 | `docs/01-app/03-api-reference/03-file-conventions/01-metadata/opengraph-image.mdx` |\n| Sitemap generation                | `docs/01-app/03-api-reference/03-file-conventions/01-metadata/sitemap.mdx`         |\n\n## Directory Pattern Mappings\n\n### By Feature Area\n\n| Source Directory                       | Documentation Area                            | Notes                  |\n| -------------------------------------- | --------------------------------------------- | ---------------------- |\n| `packages/next/src/client/`            | `docs/01-app/03-api-reference/02-components/` | Client-side components |\n| `packages/next/src/server/`            | `docs/01-app/03-api-reference/04-functions/`  | Server functions       |\n| `packages/next/src/build/`             | `docs/01-app/03-api-reference/05-config/`     | Build configuration    |\n| `packages/next/src/shared/lib/router/` | `docs/01-app/02-guides/`                      | Routing guides         |\n| `packages/next/src/lib/metadata/`      | `docs/01-app/02-guides/metadata/`             | Metadata guides        |\n\n### CLI Commands\n\n| Source Path                           | Documentation Path                                   |\n| ------------------------------------- | ---------------------------------------------------- |\n| `packages/next/src/cli/next-dev.ts`   | `docs/01-app/03-api-reference/06-cli/next-dev.mdx`   |\n| `packages/next/src/cli/next-build.ts` | `docs/01-app/03-api-reference/06-cli/next-build.mdx` |\n| `packages/next/src/cli/next-start.ts` | `docs/01-app/03-api-reference/06-cli/next-start.mdx` |\n\n## Finding Related Documentation\n\n### Step 1: Identify the changed export\n\nLook at what's exported from the changed file:\n\n- Public API exports → API Reference docs\n- Internal utilities → Usually no docs needed\n- Configuration types → Config docs\n\n### Step 2: Search for existing docs\n\nUse Claude's built-in tools for searching:\n\n- **Find docs mentioning a term**: Use the Grep tool with the pattern and `docs/` as the path\n- **List docs in a directory**: Use the Glob tool with pattern like `docs/01-app/03-api-reference/04-functions/*.mdx`\n\n### Step 3: Check for shared content\n\nIf editing App Router docs, check if Pages Router has a corresponding file with `source` field:\n\n- **Find source references**: Use the Grep tool with pattern `source: app/api-reference` in `docs/02-pages/`\n\n## Common Patterns\n\n### New API Function\n\n1. Export added to `packages/next/src/server/`\n2. Create doc at `docs/01-app/03-api-reference/04-functions/function-name.mdx`\n3. Update index/listing pages if applicable\n\n### New Component Prop\n\n1. Prop added to component in `packages/next/src/client/components/`\n2. Update the props table in corresponding doc\n3. Add a section explaining the new prop with examples\n\n### New Config Option\n\n1. Option added to `packages/next/src/server/config-shared.ts`\n2. Find the relevant config doc in `docs/01-app/03-api-reference/05-config/01-next-config-js/`\n3. Add the option with description and example\n\n### Behavioral Change\n\n1. Logic changed in any source file\n2. Find all docs that describe this behavior\n3. Update descriptions and examples to match new behavior\n4. Add migration notes if breaking change\n\n## Quick Search Commands\n\nUse Claude's built-in tools for efficient searching:\n\n- **Find all docs mentioning a term**: Use the Grep tool with your search pattern and `docs/` as the path, filtering to `*.mdx` files\n- **List all API reference docs**: Use the Glob tool with pattern `docs/01-app/03-api-reference/**/*.mdx`\n- **Find docs by filename pattern**: Use the Glob tool with pattern like `docs/**/*image*.mdx`\n- **Read a doc's frontmatter**: Use the Read tool with a line limit to check the `source` field\n", "skills/update-docs/references/DOC-CONVENTIONS.md": "# Next.js Documentation Conventions\n\nComplete reference for frontmatter schema, code block formatting, and MDX component usage.\n\n## Frontmatter Schema\n\nAll MDX files must start with YAML frontmatter enclosed in `---` delimiters.\n\n### Required Fields\n\n| Field         | Description                                 | Example                                          |\n| ------------- | ------------------------------------------- | ------------------------------------------------ |\n| `title`       | Page title for SEO and headings (2-3 words) | `title: Image Component`                         |\n| `description` | Brief description (1-2 sentences)           | `description: Optimize images using next/image.` |\n\n### Optional Fields\n\n| Field       | Description                                        | Example                                      |\n| ----------- | -------------------------------------------------- | -------------------------------------------- |\n| `nav_title` | Shorter title for navigation sidebar               | `nav_title: Image`                           |\n| `source`    | Pull content from another page (avoid duplication) | `source: app/api-reference/components/image` |\n| `related`   | Next steps section with related links              | See below                                    |\n| `version`   | Development stage indicator                        | `version: experimental`                      |\n\n### Related Links Format\n\n```yaml\n---\ntitle: My Feature\ndescription: Description here.\nrelated:\n  title: Next Steps\n  description: Learn more about related features.\n  links:\n    - app/api-reference/components/image\n    - app/guides/optimizing/images\n---\n```\n\n### Version Field Values\n\n- `experimental` - Experimental feature, may change\n- `legacy` - Legacy feature, consider alternatives\n- `unstable` - Unstable API, not recommended for production\n- `RC` - Release candidate\n\n## Code Block Conventions\n\n### Basic Syntax\n\n````\n```language filename=\"path/to/file.ext\"\ncode here\n```\n````\n\n### Required Attributes\n\n| Attribute   | When to Use                       | Example                   |\n| ----------- | --------------------------------- | ------------------------- |\n| `filename`  | Always for code examples          | `filename=\"app/page.tsx\"` |\n| `switcher`  | When providing TS and JS variants | `switcher`                |\n| `highlight` | To highlight specific lines       | `highlight={1,3-5}`       |\n\n### TypeScript/JavaScript Switcher Pattern\n\nAlways provide TypeScript first, then JavaScript:\n\n````mdx\n```tsx filename=\"app/page.tsx\" switcher\nimport type { Metadata } from 'next'\n\nexport const metadata: Metadata = {\n  title: 'My Page',\n}\n```\n\n```jsx filename=\"app/page.js\" switcher\nexport const metadata = {\n  title: 'My Page',\n}\n```\n````\n\n### Terminal Commands\n\nUse `bash` language without filename:\n\n````mdx\n```bash\nnpm install next\n```\n````\n\n### Highlighting Lines\n\n```\nhighlight={1}        # Single line\nhighlight={1,3}      # Multiple lines\nhighlight={1-5}      # Range\nhighlight={1,3-5,8}  # Combined\n```\n\n## MDX Components\n\n### AppOnly / PagesOnly\n\nUse for router-specific content in shared documentation:\n\n```mdx\n<AppOnly>\n\nThis content only appears in App Router documentation.\n\n</AppOnly>\n\n<PagesOnly>\n\nThis content only appears in Pages Router documentation.\n\n</PagesOnly>\n```\n\n**Important:** Include blank lines inside the components for proper markdown parsing.\n\n### Image Component\n\nFor themed images with light/dark variants:\n\n```mdx\n<Image\n  alt=\"Description of the image\"\n  srcLight=\"/docs/light/image-name.png\"\n  srcDark=\"/docs/dark/image-name.png\"\n  width={1600}\n  height={800}\n/>\n```\n\n### Notes and Callouts\n\n**Single line:**\n\n```mdx\n> **Good to know**: Important information here.\n```\n\n**Multi-line:**\n\n```mdx\n> **Good to know**:\n>\n> - First point\n> - Second point\n> - Third point\n```\n\n## Props Tables\n\nUse HTML table wrapper for horizontal scroll on mobile:\n\n```mdx\n<div style={{ overflowX: 'auto', width: '100%' }}>\n\n| Prop              | Example             | Type    | Status   |\n| ----------------- | ------------------- | ------- | -------- |\n| [`src`](#src)     | `src=\"/image.png\"`  | String  | Required |\n| [`alt`](#alt)     | `alt=\"Description\"` | String  | Required |\n| [`width`](#width) | `width={500}`       | Integer | -        |\n\n</div>\n```\n\n### Status Values\n\n- `Required` - Must be provided\n- `-` - Optional\n- `Deprecated` - Will be removed, use alternative\n\n## Shared Content Pattern\n\nFor Pages Router docs that share content with App Router:\n\n**App Router (source):** `docs/01-app/03-api-reference/02-components/image.mdx`\n\n- Contains the full documentation\n- Uses `<AppOnly>` and `<PagesOnly>` for router-specific sections\n\n**Pages Router (consumer):** `docs/02-pages/03-api-reference/01-components/image.mdx`\n\n```yaml\n---\ntitle: Image Component\ndescription: Optimize images using next/image.\nsource: app/api-reference/components/image\n---\n```\n\nThe `source` field pulls content from the App Router doc.\n\n## Writing Style\n\n### Voice\n\n- **Guides:** Instructional, use \"you\" to address users\n- **API Reference:** Technical, use imperative verbs (\"create\", \"pass\", \"return\")\n\n### Clarity\n\n- Use plain words over complex alternatives\n- Be specific: \"the `src` prop\" not \"this prop\"\n- Avoid jargon unless explaining it\n\n### Structure\n\nTypical page structure:\n\n1. Brief introduction (what and why)\n2. Minimal working example\n3. Detailed reference/options\n4. Examples for different use cases\n5. Related links (via frontmatter)\n\n## File Naming\n\n- Use kebab-case: `generate-metadata.mdx`\n- Add numeric prefix for ordering: `01-installation.mdx`\n- Index pages: `index.mdx`\n\n## Validation Commands\n\n```bash\npnpm lint              # Full lint check\npnpm prettier-fix      # Fix formatting\npnpm types             # TypeScript check\n```\n", "skills/v8-jit/SKILL.md": "---\nname: v8-jit\ndescription: >\n  V8 JIT optimization patterns for writing high-performance JavaScript in\n  Next.js server internals. Use when writing or reviewing hot-path code in\n  app-render, stream-utils, routing, caching, or any per-request code path.\n  Covers hidden classes / shapes, monomorphic call sites, inline caches,\n  megamorphic deopt, closure allocation, array packing, and profiling with\n  --trace-opt / --trace-deopt.\nuser-invocable: false\nmetadata:\n  internal: true\n---\n\n# V8 JIT Optimization\n\nUse this skill when writing or optimizing performance-critical code paths in\nNext.js server internals — especially per-request hot paths like rendering,\nstreaming, routing, and caching.\n\n## Background: V8's Tiered Compilation\n\nV8 compiles JavaScript through multiple tiers:\n\n1. **Ignition** (interpreter) — executes bytecode immediately.\n2. **Sparkplug** — fast baseline compiler (no optimization).\n3. **Maglev** — mid-tier optimizing compiler.\n4. **Turbofan** — full optimizing compiler (speculative, type-feedback-driven).\n\nCode starts in Ignition and is promoted to higher tiers based on execution\nfrequency and collected type feedback. Turbofan produces the fastest machine\ncode but **bails out (deopts)** when assumptions are violated at runtime.\n\nThe key principle: **help V8 make correct speculative assumptions by keeping\ntypes, shapes, and control flow predictable.**\n\n## Hidden Classes (Shapes / Maps)\n\nEvery JavaScript object has an internal \"hidden class\" (V8 calls it a _Map_,\nthe spec calls it a _Shape_). Objects that share the same property names, added\nin the same order, share the same hidden class. This enables fast property\naccess via inline caches.\n\n### Initialize All Properties in Constructors\n\n```ts\n// GOOD — consistent shape, single hidden class transition chain\nclass RequestContext {\n  url: string\n  method: string\n  headers: Record<string, string>\n  startTime: number\n  cached: boolean\n\n  constructor(url: string, method: string, headers: Record<string, string>) {\n    this.url = url\n    this.method = method\n    this.headers = headers\n    this.startTime = performance.now()\n    this.cached = false // always initialize, even defaults\n  }\n}\n```\n\n```ts\n// BAD — conditional property addition creates multiple hidden classes\nclass RequestContext {\n  constructor(url, method, headers, options) {\n    this.url = url\n    this.method = method\n    if (options.timing) {\n      this.startTime = performance.now() // shape fork!\n    }\n    if (options.cache) {\n      this.cached = false // another shape fork!\n    }\n    this.headers = headers\n  }\n}\n```\n\n**Rules:**\n\n- Assign every property in the constructor, in the same order, for every\n  instance. Use `null` / `undefined` / `false` as default values rather than\n  omitting the property.\n- Prefer factory functions when constructing hot-path objects. A single factory\n  makes it harder to accidentally fork shapes in different call sites.\n- Never `delete` a property on a hot object — it forces a transition to\n  dictionary mode (slow properties).\n- Avoid adding properties after construction (`obj.newProp = x`) on objects\n  used in hot paths.\n- Object literals that flow into the same function should have keys in the\n  same order:\n- Use tuples for very small fixed-size records when names are not needed.\n  Tuples avoid key-order pitfalls entirely.\n\n```ts\n// GOOD — same key order, shares hidden class\nconst a = { type: 'static', value: 1 }\nconst b = { type: 'dynamic', value: 2 }\n\n// BAD — different key order, different hidden classes\nconst a = { type: 'static', value: 1 }\nconst b = { value: 2, type: 'dynamic' }\n```\n\n### Real Codebase Example\n\n`Span` in `src/trace/trace.ts` initializes all fields in the constructor in a\nfixed order — `name`, `parentId`, `attrs`, `status`, `id`, `_start`, `now`.\nThis ensures all `Span` instances share one hidden class.\n\n## Monomorphic vs Polymorphic vs Megamorphic\n\nV8's inline caches (ICs) track the types/shapes seen at each call site or\nproperty access:\n\n| IC State        | Shapes Seen | Speed                                 |\n| --------------- | ----------- | ------------------------------------- |\n| **Monomorphic** | 1           | Fastest — single direct check         |\n| **Polymorphic** | 2–4         | Fast — linear search through cases    |\n| **Megamorphic** | 5+          | Slow — hash-table lookup, no inlining |\n\nOnce an IC goes megamorphic it does NOT recover (until the function is\nre-compiled). Megamorphic ICs also **prevent Turbofan from inlining** the\nfunction.\n\n### Keep Hot Call Sites Monomorphic\n\n```ts\n// GOOD — always called with the same argument shape\nfunction processChunk(chunk: Uint8Array): void {\n  // chunk is always Uint8Array → monomorphic\n}\n\n// BAD — called with different types at the same call site\nfunction processChunk(chunk: Uint8Array | Buffer | string): void {\n  // IC becomes polymorphic/megamorphic\n}\n```\n\n**Practical strategies:**\n\n- Normalize inputs at the boundary (e.g. convert `Buffer` → `Uint8Array`\n  once) and keep internal functions monomorphic.\n- Avoid passing both `null` and `undefined` for the same parameter — pick one\n  sentinel value.\n- When a function must handle multiple types, split into separate specialized\n  functions and dispatch once at the entry point:\n\n```ts\n// Entry point dispatches once\nfunction handleStream(stream: ReadableStream | Readable) {\n  if (stream instanceof ReadableStream) {\n    return handleWebStream(stream) // monomorphic call\n  }\n  return handleNodeStream(stream) // monomorphic call\n}\n```\n\nThis is the pattern used in `stream-ops.ts` and throughout the stream-utils\ncode (Node.js vs Web stream split via compile-time switcher).\n\n## Closure and Allocation Pressure\n\nEvery closure captures its enclosing scope. Creating closures in hot loops\nor per-request paths generates GC pressure and can prevent escape analysis.\n\n### Hoist Closures Out of Hot Paths\n\n```ts\n// BAD — closure allocated for every request\nfunction handleRequest(req) {\n  stream.on('data', (chunk) => processChunk(chunk, req.id))\n}\n\n// GOOD — shared listener, request context looked up by stream\nconst requestIdByStream = new WeakMap()\nfunction onData(chunk) {\n  const id = requestIdByStream.get(this)\n  if (id !== undefined) processChunk(chunk, id)\n}\n\nfunction processChunk(chunk, id) {\n  /* ... */\n}\n\nfunction handleRequest(req) {\n  requestIdByStream.set(stream, req.id)\n  stream.on('data', onData)\n}\n```\n\n```ts\n// BEST — pre-allocate the callback as a method on a context object\nclass StreamProcessor {\n  id: string\n  constructor(id: string) {\n    this.id = id\n  }\n  handleChunk(chunk: Uint8Array) {\n    processChunk(chunk, this.id)\n  }\n}\n```\n\n### Avoid Allocations in Tight Loops\n\n```ts\n// BAD — allocates a new object per iteration\nfor (const item of items) {\n  doSomething({ key: item.key, value: item.value })\n}\n\n// GOOD — reuse a mutable scratch object\nconst scratch = { key: '', value: '' }\nfor (const item of items) {\n  scratch.key = item.key\n  scratch.value = item.value\n  doSomething(scratch)\n}\n```\n\n### Real Codebase Example\n\n`node-stream-helpers.ts` hoists `encoder`, `BUFFER_TAGS`, and tag constants to\nmodule scope to avoid re-creating them on every request. The `bufferIndexOf`\nhelper uses `Buffer.indexOf` (C++ native) instead of a per-call JS loop,\neliminating per-chunk allocation.\n\n## Array Optimizations\n\nV8 tracks array \"element kinds\" — an internal type tag that determines how\nelements are stored in memory:\n\n| Element Kind      | Description                   | Speed                       |\n| ----------------- | ----------------------------- | --------------------------- |\n| `PACKED_SMI`      | Small integers only, no holes | Fastest                     |\n| `PACKED_DOUBLE`   | Numbers only, no holes        | Fast                        |\n| `PACKED_ELEMENTS` | Mixed/objects, no holes       | Moderate                    |\n| `HOLEY_*`         | Any of above with holes       | Slower (extra bounds check) |\n\n**Transitions are one-way** — once an array becomes `HOLEY` or `PACKED_ELEMENTS`,\nit never goes back.\n\n### Rules\n\n- Pre-allocate arrays with known size: `new Array(n)` creates a holey array.\n  Prefer `[]` and `push()`, or use `Array.from({ length: n }, initFn)`.\n- Don't create holes: `arr[100] = x` on an empty array creates 100 holes.\n- Don't mix types: `[1, 'two', {}]` immediately becomes `PACKED_ELEMENTS`.\n- Prefer typed arrays only when you need binary interop/contiguous memory or\n  have profiling evidence that they help. For small/short-lived collections,\n  normal arrays can be faster and allocate less.\n\n```ts\n// GOOD — packed SMI array\nconst indices: number[] = []\nfor (let i = 0; i < n; i++) {\n  indices.push(i)\n}\n\n// BAD — holey from the start\nconst indices = new Array(n)\nfor (let i = 0; i < n; i++) {\n  indices[i] = i\n}\n```\n\n### Real Codebase Example\n\n`accumulateStreamChunks` in `app-render.tsx` uses `const staticChunks: Array<Uint8Array> = []` with `push()` — keeping a packed array of a single type\nthroughout its lifetime.\n\n## Function Optimization and Deopts\n\n### Hot-Path Deopt Footguns\n\n- **`arguments` object**: using `arguments` in non-trivial ways (e.g.\n  `arguments[i]` with variable `i`, leaking `arguments`). Use rest params\n  instead.\n- **Type instability at one call site**: same operation sees both numbers and\n  strings (or many object shapes) and becomes polymorphic/megamorphic.\n- **`eval` / `with`**: prevents optimization entirely.\n- **Highly dynamic object iteration**: avoid `for...in` on hot objects; prefer\n  `Object.keys()` / `Object.entries()` when possible.\n\n### Favor Predictable Control Flow\n\n```ts\n// GOOD — predictable: always returns same type\nfunction getStatus(code: number): string {\n  if (code === 200) return 'ok'\n  if (code === 404) return 'not found'\n  return 'error'\n}\n\n// BAD — returns different types\nfunction getStatus(code: number): string | null | undefined {\n  if (code === 200) return 'ok'\n  if (code === 404) return null\n  // implicitly returns undefined\n}\n```\n\n### Watch Shape Diversity in `switch` Dispatch\n\n```ts\n// WATCH OUT — `node.type` IC can go megamorphic if many shapes hit one site\nfunction render(node) {\n  switch (node.type) {\n    case 'div':\n      return { tag: 'div', children: node.children }\n    case 'span':\n      return { tag: 'span', text: node.text }\n    case 'img':\n      return { src: node.src, alt: node.alt }\n    // Many distinct node layouts can make this dispatch site polymorphic\n  }\n}\n```\n\nThis pattern is not always bad. Often the main pressure is at the shared\ndispatch site (`node.type`), while properties used only in one branch stay\nmonomorphic within that branch. Reach for normalization/splitting only when\nprofiles show this site is hot and polymorphic.\n\n## String Operations\n\n- **String concatenation in loops is usually fine in modern V8** (ropes make\n  many concatenations cheap). For binary data, use `Buffer.concat()`.\n- **Template literals vs concatenation**: equivalent performance in modern V8,\n  but template literals are clearer.\n- **`string.indexOf()` > regex** for simple substring checks.\n- **Reuse RegExp objects**: don't create a `new RegExp()` inside a hot\n  function — hoist it to module scope.\n\n```ts\n// GOOD — regex hoisted to module scope\nconst ROUTE_PATTERN = /^\\/api\\//\n\nfunction isApiRoute(path: string): boolean {\n  return ROUTE_PATTERN.test(path)\n}\n\n// BAD — regex recreated on every call\nfunction isApiRoute(path: string): boolean {\n  return /^\\/api\\//.test(path) // V8 may or may not cache this\n}\n```\n\n## `Map` and `Set` vs Plain Objects\n\n- **`Map`** is faster than plain objects for frequent additions/deletions\n  (avoids hidden class transitions and dictionary mode).\n- **`Set`** is faster than `obj[key] = true` for membership checks with\n  dynamic keys.\n- For **static lookups** (known keys at module load), plain objects or\n  `Object.freeze({...})` are fine — V8 optimizes them as constant.\n- Never use an object as a map if keys come from user input (prototype\n  pollution risk + megamorphic shapes).\n\n## Profiling and Verification\n\n### V8 Flags for Diagnosing JIT Issues\n\n```bash\n# Trace which functions get optimized\nnode --trace-opt server.js 2>&1 | grep \"my-function-name\"\n\n# Trace deoptimizations (critical for finding perf regressions)\nnode --trace-deopt server.js 2>&1 | grep \"my-function-name\"\n\n# Combined: see the full opt/deopt lifecycle\nnode --trace-opt --trace-deopt server.js 2>&1 | tee /tmp/v8-trace.log\n\n# Show IC state transitions (verbose)\nnode --trace-ic server.js 2>&1 | tee /tmp/ic-trace.log\n\n# Print optimized code (advanced)\nnode --print-opt-code --code-comments server.js\n```\n\n### Targeted Profiling in Next.js\n\n```bash\n# Profile a production build\nnode --cpu-prof --cpu-prof-dir=/tmp/profiles \\\n  node_modules/.bin/next build\n\n# Profile the server during a benchmark\nnode --cpu-prof --cpu-prof-dir=/tmp/profiles \\\n  node_modules/.bin/next start &\n# ... run benchmark ...\n# Analyze in Chrome DevTools: chrome://inspect → Open dedicated DevTools\n\n# Quick trace-deopt check on a specific test\nnode --trace-deopt $(which jest) --runInBand test/path/to/test.ts \\\n  2>&1 | grep -i \"deopt\" | head -50\n```\n\n### Using `%` Natives (Development/Testing Only)\n\nWith `--allow-natives-syntax`:\n\n```js\nfunction hotFunction(x) {\n  return x + 1\n}\n\n// Force optimization\n%PrepareFunctionForOptimization(hotFunction)\nhotFunction(1)\nhotFunction(2) % OptimizeFunctionOnNextCall(hotFunction)\nhotFunction(3)\n\n// Check optimization status\n// 1 = optimized, 2 = not optimized, 3 = always optimized, 6 = maglev\nconsole.log(%GetOptimizationStatus(hotFunction))\n```\n\n## Checklist for Hot Path Code Reviews\n\n- [ ] All object properties initialized in constructor/literal, same order\n- [ ] No `delete` on hot objects\n- [ ] No post-construction property additions on hot objects\n- [ ] Functions receive consistent types (monomorphic call sites)\n- [ ] Type dispatch happens at boundaries, not deep in hot loops\n- [ ] No closures allocated inside tight loops\n- [ ] Module-scope constants for regex, encoders, tag buffers\n- [ ] Arrays are packed (no holes, no mixed types)\n- [ ] `Map`/`Set` used for dynamic key collections\n- [ ] No `arguments` object — use rest params\n- [ ] `try/catch` at function boundary, not inside tight loops\n- [ ] String building via array + `join()` or `Buffer.concat()`\n- [ ] Return types are consistent (no `string | null | undefined` mixes)\n\n## Related Skills\n\n- `$dce-edge` — DCE-safe require patterns (compile-time dead code)\n- `$runtime-debug` — runtime bundle debugging and profiling workflow\n", "skills/write-api-reference/SKILL.md": "---\nname: write-api-reference\ndescription: |\n  Produces API reference documentation for Next.js APIs: functions, components, file conventions, directives, and config options.\n\n  **Auto-activation:** User asks to write, create, or draft an API reference page. Also triggers on paths like `docs/01-app/03-api-reference/`, or keywords like \"API reference\", \"props\", \"parameters\", \"returns\", \"signature\".\n\n  **Input sources:** Next.js source code, existing API reference pages, or user-provided specifications.\n\n  **Output type:** A markdown (.mdx) API reference page with YAML frontmatter, usage example, reference section, behavior notes, and examples.\nagent: Plan\ncontext: fork\nmetadata:\n  internal: true\n---\n\n# Writing API Reference Pages\n\n## Goal\n\nProduce an API reference page that documents a single API surface (function, component, file convention, directive, or config option). The page should be concise, scannable, and example-driven.\n\nEach page documents **one API**. If the API has sub-methods (like `cookies.set()`), document them on the same page. If two APIs are independent, they get separate pages.\n\n## Structure\n\nIdentify which category the API belongs to, then follow the corresponding template.\n\n### Categories\n\n1. **Function** (`cookies`, `fetch`, `generateStaticParams`): signature, params/returns, methods table, examples\n2. **Component** (`Link`, `Image`, `Script`): props summary table, individual prop docs, examples\n3. **File convention** (`page`, `layout`, `route`): definition, code showing the convention, props, behavior, examples\n4. **Directive** (`use client`, `use cache`): definition, usage, serialization/boundary rules, reference\n5. **Config option** (`basePath`, `images`, etc.): definition, config code, behavioral sections\n\n### Template\n\n````markdown\n---\ntitle: {API name}\ndescription: {API Reference for the {API name} {function|component|file convention|directive|config option}.}\n---\n\n{One sentence defining what it does and where it's used.}\n\n```tsx filename=\"path/to/file.tsx\" switcher\n// Minimal working usage\n```\n\n```jsx filename=\"path/to/file.js\" switcher\n// Same example in JS\n```\n\n## Reference\n\n{For functions: methods/params table, return type.}\n{For components: props summary table, then `#### propName` subsections.}\n{For file conventions: `### Props` with `#### propName` subsections.}\n{For directives: usage rules and serialization constraints.}\n{For config: options table or individual option docs.}\n\n### {Subsection name}\n\n{Description + code example + table of values where applicable.}\n\n## Good to know\n\n- {Default behavior or implicit effects.}\n- {Caveats, limitations, or version-specific notes.}\n- {Edge cases the developer should be aware of.}\n\n## Examples\n\n### {Example name}\n\n{Brief context, 1-2 sentences.}\n\n```tsx filename=\"path/to/file.tsx\" switcher\n// Complete working example\n```\n\n```jsx filename=\"path/to/file.js\" switcher\n// Same example in JS\n```\n\n## Version History\n\n| Version  | Changes         |\n| -------- | --------------- |\n| `vX.Y.Z` | {What changed.} |\n````\n\n**Category-specific notes:**\n\n- **Functions**: Lead with the function signature and `await` if async. Document methods in a table if the return value has methods (like `cookies`). Document options in a separate table if applicable.\n- **Components**: Start with a props summary table (`| Prop | Example | Type | Required |`). Then document each prop under `#### propName` with description, code example, and value table where useful.\n- **File conventions**: Show the default export signature with TypeScript types. Document each prop (`params`, `searchParams`, etc.) under `#### propName` with a route/URL/value example table.\n- **Directives**: No `## Reference` section. Use `## Usage` instead, showing correct placement. Document serialization constraints and boundary rules.\n- **Config options**: Show the `next.config.ts` snippet. Use subsections for each behavioral aspect.\n\n## Rules\n\n1. **Lead with what it does.** First sentence defines the API. No preamble.\n2. **Show working code immediately.** A minimal usage example appears right after the opening sentence, before `## Reference`.\n3. **Use `switcher` for tsx/jsx pairs.** Always include both. Always include `filename=\"path/to/file.ext\"`.\n4. **Use `highlight={n}` for key lines.** Highlight the line that demonstrates the API being documented.\n5. **Tables for simple APIs, subsections for complex ones.** If a prop/param needs only a type and one-line description, use a table row. If it needs a code example or multiple values, use a `####` subsection.\n6. **Behavior section uses `> **Good to know**:`or`## Good to know`.** Use the blockquote format for brief notes (1-3 bullets). Use the heading format for longer sections. Not \"Note:\" or \"Warning:\".\n7. **Examples section uses `### Example Name` subsections.** Each example solves one specific use case.\n8. **Version History table at the end.** Include when the API has changed across versions. Omit for new APIs.\n9. **No em dashes.** Use periods, commas, or parentheses instead.\n10. **Mechanical, observable language.** Describe what happens, not how it feels. \"Returns an object\" not \"gives you an object\".\n11. **Link to related docs with relative paths.** Use `/docs/app/...` format.\n12. **No selling or justifying.** No \"powerful\", \"easily\", \"simply\". State what the API does.\n\n| Don't                                                   | Do                                                                                          |\n| ------------------------------------------------------- | ------------------------------------------------------------------------------------------- |\n| \"This powerful function lets you easily manage cookies\" | \"`cookies` is an async function that reads HTTP request cookies in Server Components\"       |\n| \"You can conveniently access...\"                        | \"Returns an object containing...\"                                                           |\n| \"The best way to handle navigation\"                     | \"`<Link>` extends the HTML `<a>` element to provide prefetching and client-side navigation\" |\n\n13. **Bridge new framework terms with legacy or generic vocabulary.** When the API renames or differentiates from a prior concept (Pages-era term, generic web term, REST vocabulary), include one such synonym in the frontmatter `description` and once in prose. Example: `description: \"Use Dynamic Segments to read URL parameters and generate routes from dynamic data.\"` mentions \"URL parameters\" alongside \"Dynamic Segments\". One synonym, folded into natural prose. No separate \"Synonyms\" or \"Also known as\" section, no keyword stuffing. Goal: preserve discoverability for users still searching the old vocabulary even when the framework has moved on.\n\n| Don't                              | Do                                                                                   |\n| ---------------------------------- | ------------------------------------------------------------------------------------ |\n| \"Learn how to use Route Handlers\"  | \"Build API endpoints with Route Handlers, the App Router replacement for API Routes\" |\n| \"Configure dynamic route segments\" | \"Read URL parameters from dynamic route segments\"                                    |\n\n## Workflow\n\n1. **Ask for reference material.** Ask the user if they have any RFCs, PRs, design docs, or other context that should inform the doc.\n2. **Identify the API category** (function, component, file convention, directive, config).\n3. **Research the implementation.** Read the source code to understand params, return types, edge cases, and defaults.\n4. **Check e2e tests.** Search `test/` for tests exercising the API to find real usage patterns, edge cases, and expected behavior.\n5. **Check existing related docs** for linking opportunities and to avoid duplication.\n6. **Write using the appropriate category template.** Follow the rules above.\n7. **Review against the rules.** Verify: one sentence opener, immediate code example, correct `switcher`/`filename` usage, tables vs subsections, \"Good to know\" format, no em dashes, mechanical language.\n\n## References\n\nRead these pages in `docs/01-app/03-api-reference/` before writing. They demonstrate the patterns above.\n\n- `04-functions/cookies.mdx` - Function with methods table, options table, and behavior notes\n- `03-file-conventions/page.mdx` - File convention with props subsections and route/URL/value tables\n- `02-components/link.mdx` - Component with props summary table and detailed per-prop docs\n- `01-directives/use-client.mdx` - Directive with usage section and serialization rules\n- `04-functions/fetch.mdx` - Function with troubleshooting section and version history\n", "skills/write-guide/SKILL.md": "---\nname: write-guide\ndescription: |\n  Generates technical guides that teach real-world use cases through progressive examples.\n\n  **Auto-activation:** User asks to write, create, or draft a guide or tutorial. Also use when converting feature documentation, API references, or skill knowledge into step-by-step learning content.\n\n  **Input sources:** Feature skills, API documentation, existing code examples, or user-provided specifications.\n\n  **Output type:** A markdown guide with YAML frontmatter, introduction, 2-4 progressive steps, and next steps section.\nagent: Plan\ncontext: fork\nmetadata:\n  internal: true\n---\n\n# Writing Guides\n\n## Goal\n\nProduce a technical guide that teaches a real-world use case through progressive examples. Concepts are introduced only when the reader needs them.\n\nEach guide solves **one specific problem**. Not a category of problems. If the outline has 5+ steps or covers multiple approaches, split it.\n\n## Structure\n\nEvery guide follows this arc: introduction, example setup, 2-5 progressive steps, next steps.\n\nEach step follows this loop: working code → new requirement → friction → explanation → resolution → observable proof.\n\nSections: introduction (no heading, 2 paragraphs max), `## Example` (what we're building + source link), `### Step N` (action-oriented titles, 2-4 steps), `## Next steps` (summary + related links).\n\nHeadings should tell a story on their own. If readers only saw the headings, they'd understand the guide's takeaway.\n\n### Template\n\n````markdown\n---\ntitle: {Action-oriented, e.g., \"Building X\" or \"How to Y\"}\ndescription: {One sentence}\nnav_title: {Short title for navigation}\n---\n\n{What the reader will accomplish and why it matters. The friction and how this approach resolves it. 2 paragraphs max.}\n\n## Example\n\nAs an example, we'll build {what we're building}.\n\nWe'll start with {step 1}, then {step 2}, and {step 3}.\n\n{Source code link.}\n\n### Step 1: {Action-oriented title}\n\n{Brief context, 1-2 sentences.}\n\n```tsx filename=\"path/to/file.tsx\"\n// Minimal working code\n```\n\n{Explain what happens.}\n\n{Introduce friction: warning, limitation, or constraint.}\n\n{Resolution: explain the choice, apply the fix.}\n\n{Verify the fix with observable proof.}\n\n### Step 2: {Action-oriented title}\n\n{Same pattern: context → code → explain → friction → resolution → proof.}\n\n### Step 3: {Action-oriented title}\n\n{Same pattern.}\n\n## Next steps\n\nYou now know how to {summary}.\n\nNext, learn how to:\n\n- [Related guide 1]()\n- [Related guide 2]()\n````\n\n### Workflow\n\n1. **Research**: Check available skills for relevant features. Read existing docs for context and linking opportunities.\n2. **Plan**: Outline sections. Verify scope (one problem, 2-4 steps). Each step needs a friction point and resolution.\n3. **Write**: Follow the template above. Apply the rules below.\n4. **Review**: Re-read the rules, verify, then present.\n\n## Rules\n\n1. **Progressive disclosure.** Start with the smallest working example. Introduce complexity only when the example breaks. Name concepts at the moment of resolution, after the reader has felt the problem. Full loop: working → new requirement → something breaks → explain why → name the fix → apply → verify with proof → move on.\n2. **Show problems visually.** Console errors, terminal output, build warnings, slow-loading pages. \"If we refresh the page, we can see the component blocks the response.\"\n3. **Verify resolutions with observable proof.** Before/after comparisons, browser reloads, terminal output. \"If we refresh the page again, we can see it loads instantly.\"\n4. **One friction point per step.** If a step has multiple friction points, split it.\n5. **Minimal code blocks.** Only the code needed for the current step. Collapse unchanged functions with `function Header() {}`.\n6. **No em dashes.** Use periods, commas, or parentheses instead.\n7. **Mechanical, observable language.** Describe what happens, not how it feels.\n8. **No selling, justifying, or comparing.** No \"the best way,\" no historical context, no framework comparisons.\n\n| Don't                                                | Do                                                       |\n| ---------------------------------------------------- | -------------------------------------------------------- |\n| \"creates friction in the pipeline\"                   | \"blocks the response\"                                    |\n| \"needs dynamic information\"                          | \"depends on request-time data\"                           |\n| \"requires dynamic processing\"                        | \"output can't be known ahead of time\"                    |\n| \"The component blocks the response — causing delays\" | \"The component blocks the response. This causes delays.\" |\n\n9. **Bridge new framework terms with legacy or generic vocabulary in `description` and intro.** Guides win or lose SERPs on the colloquial query (e.g. \"next js form submission\", \"next js api endpoint\", \"next js error page\"), not on the framework's preferred noun. When the guide covers a renamed or differentiated concept, include one synonym (Pages-era term, REST/web term, or industry-standard label) in the frontmatter `description` and once in the introduction. Fold into prose. No separate \"Synonyms\" or \"Also known as\" section.\n\n| Don't                                            | Do                                                                                                            |\n| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- |\n| \"Learn how to use Route Handlers\"                | \"Build API endpoints (formerly API Routes) with Route Handlers\"                                               |\n| \"Learn how to mutate data with Server Functions\" | \"Submit forms and update data with Server Functions, the App Router approach to form posts and API mutations\" |\n\n## References\n\nRead these guides in `docs/01-app/02-guides/` before writing. They demonstrate the patterns above.\n\n- `public-static-pages.mdx` — intro → example → 3 progressive steps → next steps. Concepts named at point of resolution. Problems shown with build output.\n- `forms.mdx` — progressive feature building without explicit \"Step\" labels. Each section adds one capability.\n"}}
