Unverified Commit 83576151 authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Bundle Analyzer Agent Skill: Add analyzer skill (#99169)

## Summary

Add a model-discoverable browser initial-load optimizer for slow route
startup, oversized client bundles, duplicate browser dependencies and
interaction-gated features. The skill follows six ordered steps with
observable completion gates: scope, baseline, validation, candidate, one
verified fix, report. Audit is the default and leaves app
source/dependencies/lockfiles unchanged; fixing requires an explicit
request.

The shared workflow keeps capture/replay (including saved-snapshot
reuse), a complete `--route` command, installed-schema validation and
evidence-qualified reporting visible. The v1 schema in the app's
installed `next` package remains the field/record authority; the skill
covers complete-stream, join and source checks that per-record
validation cannot establish. Optional CLI choices defer to installed
`next analyze --help`.

Conditional plain references carry graph clustering/min-cut procedures
and lazy-feature/package-dedupe/server-display checks. Agents load them
only when the candidate reaches that branch. The main skill is 49%
shorter by character count, preserving authorization, graph completeness
and behavior safeguards. Related-skill pointers sit beside their
triggering branches. This PR owns the skill and AI-agent guide entry;
the root/producer PRs own CLI/schema/data contracts.

## Verification

- Prettier, skill/reference language lint, frontmatter/invocation
checks, six completion gates, relative-pointer checks and installed-like
recursive file discovery pass. Static scenario walkthroughs cover
audit/fix, saved replay, custom directories, blocked/corrupt exports,
incomplete graph evidence and each fix branch. The existing eval
installer copies skill reference files recursively.
- This writing-only pass changes four Markdown files across the eight
skill-bearing layers; the root, installed schema, runtime/Rust, evals,
tests and executable modes are unchanged. No removed unit suite is
reintroduced. Earlier no-emit/runtime-probe/package checks are separate
evidence, not rerun for prose.
- Full model-driven evals and native e2e were not run locally. Shorter
text and static checks are not evidence of better agent outcomes.
New-head CI must establish its own status.

<!-- NEXT_JS_LLM -->

<!-- fleet d7bdbc2b-b0bc-4591-99eb-dccb0fa49c73 -->

---------
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent 27ee7212
...@@ -191,6 +191,14 @@ Then give the agent this prompt: ...@@ -191,6 +191,14 @@ Then give the agent this prompt:
After every edit, verify the page still works at runtime using the next-dev-loop Skill. After every edit, verify the page still works at runtime using the next-dev-loop Skill.
``` ```
### `next-browser-initial-load-optimizer`
For slow route startup, oversized client bundles, duplicate browser dependencies, or features that can wait for interaction, use [`next-browser-initial-load-optimizer`](https://www.skills.sh/vercel/next.js/next-browser-initial-load-optimizer). It audits a route by default; explicitly request fixes to enter its edit, measure, and verify loop.
```bash filename="Terminal"
npx skills add vercel/next.js --skill next-browser-initial-load-optimizer
```
### `next-cache-components-adoption` ### `next-cache-components-adoption`
The [`next-cache-components-adoption`](https://www.skills.sh/vercel/next.js/next-cache-components-adoption) Skill migrates an app to [Cache Components](/docs/app/getting-started/caching): The [`next-cache-components-adoption`](https://www.skills.sh/vercel/next.js/next-cache-components-adoption) Skill migrates an app to [Cache Components](/docs/app/getting-started/caching):
......
---
name: next-browser-initial-load-optimizer
description: >
Audit and reduce Next.js browser initial-load work. Use for slow route startup,
oversized client bundles, duplicate browser dependencies, or features that can
wait for interaction.
---
# Browser initial-load optimizer
## 1. Set the scope
Choose a route and **audit** or **fix** mode. Audit is the default: generate analyzer artifacts and report candidates while leaving application source, dependencies and lockfiles unchanged. Fix mode requires an explicit request to change the app. Ask before changing visible behavior, timing, compatibility or a trust boundary. For a route's static App Shell, use `next-cache-components-optimizer`; for navigation prefetch work, use `next-partial-prefetching-optimizer`.
**Done:** the route, mode and intended behavior are recorded. A request to capture or export data is audit mode, not permission to fix.
## 2. Capture and export a baseline
Run from the app directory with its package manager. Read `next analyze --help` for capture options and `next analyze export --help` for replay options in the installed CLI. Reuse a selected saved snapshot, or capture with a distinctive name first; then export it through gzip at its default compression level. Keep before/after `.jsonl.gz` files separate.
**Sandbox requirement:** If the agent’s sandbox blocks TCP port binding (as Codex’s does), it MUST run the `next analyze --output` capture outside the sandbox. Do not attempt the capture inside that sandbox, even though `--output` does not serve the analyzer UI.
Run the pipeline in Bash:
```bash
set -o pipefail
# Capture only when a new baseline is needed
pnpm exec next analyze --output --snapshot 'audit-before-unique-1'
pnpm exec next analyze export --snapshot 'audit-before-unique-1' --route '/dashboard' | gzip > /tmp/analyze-dashboard-before.jsonl.gz
```
`--output` builds and saves binary/UI artifacts without serving. `next analyze export` reads a saved snapshot without building; stdout is one typed JSON record per line, with errors on stderr. The route filter keeps the whole-app module graph, so scope it in the next step.
For a custom `distDir`, replay with `--dist-dir <configured-directory>` (relative or absolute): capture loads the app config, replay does not. `--snapshot <name>` selects a retained name; omission selects the newest snapshot. Capture generates a unique timestamp name when omitted, and **replaces** an existing capture when an explicit name is reused. Use distinct before/after names, including names with spaces, to preserve both baselines. For interactive exploration, capture without `--output` to serve the UI; `next build --analyze` also produces replayable data.
**Done:** the chosen capture is identified, export succeeded, and the baseline file, snapshot name and selected route are recorded. Check the whole pipeline's exit status before processing the compressed file: `pipefail` prevents gzip from hiding a failed export. Export validates one route at a time, so a failure can leave a partial archive even if `gzip -t` accepts it. Discard output when export or gzip fails.
## 3. Interpret the evidence
Resolve the schema from the app's **installed Next.js**, using its Node launcher:
```bash
pnpm exec node -p "require.resolve('next/analyze/graph-v1.schema.json')"
```
Read its descriptions for record meanings, joins, attribution and coverage. Stream decompression with `gzip -dc /tmp/analyze-dashboard-before.jsonl.gz` into a line-oriented analysis script rather than loading the whole dump into context. Use the schema to interpret the selected route's client/server contributions and choose the metric.
**Done:** the baseline's route-attributed client/server contributions and the metric are identified. Treat this as **build evidence**: claims about observed browser requests, timing or transfer savings need separate evidence.
## 4. Explain a candidate
Inspect actual project source and exact importers. Start with the named route or rank scoped client-output contributions by attributed size, repetition, likely runtime cost, need before interaction and correctness risk.
### Community → min-cut pass
For broad audits seeking opportunities across multiple features or a large contributor list, run **community detection → target selection → directed min-cut → source validation** after the initial ranking. Read [Graph methods](references/graph-methods.md) before constructing the graph or running solvers.
1. Rank detected communities by scoped client-output attribution and inspect their inbound importers.
2. Select large communities, or optional feature regions within them, that can plausibly wait for interaction. Record why each selected region is optional under the route's render conditions.
3. Run directed min-cuts from the verified client roots to those targets to find small sets of importer changes that could detach them.
4. Validate the cut edges against source and behavior constraints; account for each investigated target as a candidate, rejected cut or evidence gap.
For a narrow audit of a named dependency or feature, use direct importer reasoning when it fully accounts for the relevant paths and proposed boundary; record why the paired pass adds no useful target discovery. If graph evidence or tooling blocks the pass, record the blocker and limit the conclusions accordingly.
### Graph-evidence checklist
Before proposing an edit, record these items for each candidate. Mark an inapplicable item with its reason; give missing evidence an explicit gap.
- **Scope:** name the route, snapshot, render conditions, client/server output class, exact target identities and metric. For reachability claims, identify every selected client root, including applicable client references.
- **Coverage:** summarize relevant unsupported outputs and unresolved references, with available reasons and their effect on the claim. Scope conclusions to the known subgraph when completeness is uncertain.
- **Attribution:** count each selected output contribution once. Record repeated-record handling and distinguish source paths from module identities; explain any mapping used for solver weights and preserve unknown weights as gaps.
- **Reachability:** for a lazy boundary, check **all** synchronous root-to-target paths, alternate importers and cycles, including a target that is itself a root. Record which paths the proposed boundary severs and which stay reachable. Verify async and erased type-only imports against source.
- **Source checks:** inspect import triggers, mount-time preloading, module side effects and shared routes. Record the conditions under which an async import executes. The graph establishes indexed reachability; an after snapshot verifies emitted outputs and attribution changes.
- **Method:** record the chosen method, its parameters and why it fits the candidate.
For lazy interaction features, duplicate packages, server-rendered display work or other attributed assets, read the matching section in [Fix patterns](references/fix-patterns.md) before proposing an edit.
**Done:** the paired pass and its target dispositions are recorded, or the narrow-scope skip reason or blocker is explicit. Every candidate has a completed checklist, exact source/importer, proposed edit and named behavior checks. Label heuristics as heuristics and qualify conclusions affected by evidence gaps; the report step completes **audit** mode.
## 5. Verify one change — fix mode only
Make one small, cohesive change. Capture/export an after snapshot with a new name and compare the **same route, output class and metric** with the baseline. Run relevant behavior tests and type-check; use `next-dev-loop` when verifying the edit in the running app.
**Done:** retain the change only when the scoped metric improves and the intended behavior passes its checks. Revert a change that fails either condition. If checks are blocked, report the unverified edit and blocker rather than accepting it. Record the accepted after snapshot as the next baseline before another edit.
## 6. Report and stop
Audit reports candidates; fix reports accepted edits and any reverted or unverified attempts. Include snapshot names, scoped attribution/deltas, exact source/importer, behavior-check results and blockers. For a graph cut, include its route/render conditions, roots/target and unknowns. Distinguish source facts, build evidence, heuristics and separately observed runtime facts.
**Done:** every scoped candidate or attempted edit is accounted for, with evidence or a stated gap.
# Fix patterns
Read the section matching the candidate before proposing a change. Each section ends with the evidence needed to take that candidate into the main workflow's edit/measure/behavior loop.
## Lazy interaction feature
For an editor, chart or dialog needed after interaction, inspect its actual importer and confirm the feature is not already async. Add one lazy boundary with a stable placeholder, preserving loading/error states, keyboard/focus, direct visits and client/server behavior.
Preload on intent only after measuring its benefit. Idle preloading can waste data/battery and compete with important requests.
**Ready to test:** the synchronous paths that keep the feature reachable are accounted for, and each preserved behavior has a named check.
## Duplicate browser dependency
Verify the shipped browser versions and inspect the package-manager graph (`pnpm why` or `npm ls`). Distinguish duplicate shipped JavaScript from module variants and server/client copies. Prefer compatible direct-range or parent upgrades and dedupe before overrides. If resolving duplicates requires a major-version upgrade, verify API compatibility and behavior for every affected consumer.
Check React/singleton peer constraints and hydration behavior. Recheck the resolved dependency graph and shipped browser code to ensure the change reduces duplication rather than introducing more duplicates through dependencies.
**Ready to test:** the duplicated browser code is evidenced, the resolution change is compatible with every affected consumer, and checks cover peer/hydration behavior and the resulting shipped duplication.
## Server-rendered display work
For Markdown/MDX, parsers, registries or display-only work in a Client Component, establish whether it needs live editing, offline use or browser-only inputs. Move eligible display work to server rendering with a small interactive island, or keep a lazy parser for editing. Preserve sanitizer and authorization boundaries and verify hydration.
**Ready to test:** the source work selected for relocation has no required browser-only behavior, and rendering, interaction, hydration and trust-boundary checks are named.
## Other attributed assets
Inspect polyfills, barrels, layout imports, CSS/fonts/media/WASM when the scoped attribution warrants it. Keep source/build attribution separate from observed requests: a generic asset source alone does not establish a browser request.
**Ready to test:** the exact source/importer and output contribution explain the proposed edit, and its effects on shared routes and runtime side effects are covered.
# Graph methods
Use these methods for the main workflow's community → min-cut pass or when direct importer inspection needs graph analysis. Read the installed schema for field meanings; construct a route-scoped graph from exact identities and verified client roots. Missing or unknown evidence stays an explicit gap.
## Clustering — find logical communities
Use Louvain/Leiden or another community algorithm on the scoped, deduplicated ordinary import graph. Keep synchronous, asynchronous and traced relationships distinct. If symmetrizing direction, record the weights, resolution, seed and stability across runs.
**Prioritize deferral candidates:** use scoped client-output attribution to rank communities whose features are optional for the selected route or needed only after interaction. Inspect their actual importers and behavior constraints before proposing a cut.
**Done:** each proposed community has reproducible parameters, scoped attributed contributions and inspected project importers. Treat it as a candidate to investigate, not an emitted chunk or a valid client/server boundary.
## Conditional min cut — detach a target
1. **Define the scenario:** record the route/render conditions, verified client roots and heavy target. Use directed synchronous importer→imported edges and exact output→module memberships.
2. **Establish completeness:** check every relevant output's coverage and unjoined/unresolved evidence. Account for positive or unknown unresolved-reference counts, unknown client roles, uncertain triggers and overlapping/cumulative group memberships. A group that cannot isolate one reference or an unsupported membership may supply another path. Output membership and group role establish build provenance, not cold-request scope.
3. **Choose the claim:** make a definitive cut only if every possibly relevant root→target path is accounted for. Otherwise report a cut of the **known subgraph** as provisional, identify the missing evidence and give a verification plan.
4. **Solve and check:** connect selected roots to a super-source and targets to a sink. Choose unit-edge or size/edit-cost capacities deliberately. Protect shared runtime and required initial UI edges with uncuttable capacities or equivalent constraints; record the protected edges and reasons. If no feasible cut remains, report that result. Condense strongly connected components if needed. Check that every synchronous path in the claimed scenario is severed, including alternate roots and cycles.
**Done:** the cut records its scenario, graph scope, capacities, inspected importer edges and completeness limits. A mathematical cut is a proposed source change, not automatically a safe `import()` or a measured browser saving. Return to the main workflow's behavior checks before accepting a fix.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment