1. 22 Sep, 2026 26 commits
    • next-js-bot[bot]'s avatar
      v16.4.0-canary.39 · 12374810
      next-js-bot[bot] authored
      12374810
    • Janka Uryga's avatar
      [PPF] Scaffold `unstable_ensureStatic` segment config (#98190) · c6f9d9c8
      Janka Uryga authored
      Adds the necessary plumbing and validation for a `unstable_ensureStatic`
      segment config, allowing `"auto" | "shell" | "prefetch" | "navigation" |
      false`
      
      Also dedupes some checks that we were doing for `instant` and
      `prefetch`, because `requireStatic` needs them too:
      - is not exported from a client module
      - is not used without Cache Components
      c6f9d9c8
    • Aurora Scharff's avatar
      [agent-feedback] Respect CI and telemetry opt-out (#99062) · a2470dbd
      Aurora Scharff authored
      ### What?
      
      Make automatic agent feedback respect CI, the user's Next.js Telemetry
      preference, and the existing remote kill switch. The managed
      instructions are omitted in CI or when telemetry is disabled, and the
      internal reporting command fails closed before returning the protocol.
      
      ### Why?
      
      Agent feedback should never open from CI and should share the user's
      telemetry opt-out. The existing Playground gate remains the remote
      emergency switch; this change makes the local entry points consistently
      honor the other safety conditions.
      
      ### How?
      
      - Gate managed feedback instructions on non-CI execution and enabled
      telemetry.
      - Gate the internal feedback command locally before checking the remote
      switch.
      - Preserve explicit `--dry-run` diagnostics without opening a browser.
      - Document the CI and telemetry behavior and cover it with focused
      tests.
      
      <!-- NEXT_JS_LLM -->
      a2470dbd
    • Andrew Clark's avatar
      Fix prefetch loop when a predicted route redirects (#98998) · fdcb7386
      Andrew Clark authored
      A full or runtime prefetch (e.g. `router.prefetch(url, { kind: 'full'
      })` or `<Link prefetch={true}>`) of a URL that matched a learned route
      pattern but is redirected by the server (e.g. `/docs/changelog` →
      `/changelog` while `/docs/alpha` renders `[collection]/[...slug]`)
      caused the client to re-issue the same prefetch indefinitely, at
      whatever rate the network allowed, until the tab was closed.
      
      When the server contradicts a route prediction, the client is supposed
      to remember that the URL shape can't be predicted and resolve it on the
      server from then on. We were storing this information
      (`hasDynamicRewrite`) in the wrong place: on the predicted route cache
      entry, rather than the optimistic routing table that's used to generate
      predictions.
      
      The fix moves the `hasDynamicRewrite` flag to the optimistic routing
      table so it applies to all subsequent optimistic routing predictions.
      
      Fixes #98345.
      
      <!-- NEXT_JS_LLM -->
      fdcb7386
    • Aurora Scharff's avatar
      Fix dev overlay header layout on small screens (#99049) · a18b9a58
      Aurora Scharff authored
      ## Summary
      
      On narrow screens, the dev overlay header clips the version/bundler
      badge and wraps “No issues” while hiding its horizontal scrollbar. Below
      768px, the header now wraps its items onto a second row when needed. The
      empty Issues tab stays visible, the version pill keeps its desktop
      dimensions and rounded shape, and the mobile header has balanced spacing
      above the tabs and below the pill. The wide-screen layout is unchanged.
      
      This changes the shared overlay header independently of #99002.
      
      ## Before / after
      
      Both images use the same /insight-only route at a 390 CSS-pixel
      viewport, captured directly in Chrome as PNGs. The empty Issues tab
      remains visible, and the version and bundler metadata move to a balanced
      second row.
      
      <table>
        <thead>
          <tr>
            <th>Before</th>
            <th>After</th>
          </tr>
        </thead>
        <tbody>
          <tr>
      <td><img width="390" height="300" alt="Before: clipped version badge and
      wrapped empty Issues label at 390px"
      src="https://github.com/user-attachments/assets/a5e21308-0be1-4cb3-b4a8-101b3b793ff3"
      /></td>
      <td><img width="390" height="300" alt="After: balanced wrapped header
      and fully visible rounded version pill at 390px"
      src="https://github.com/user-attachments/assets/9bcd65cf-bdf3-402e-b121-0c66f0d63800"
      /></td>
          </tr>
        </tbody>
      </table>
      
      ## Wider screens — after
      
      The header stays on one row at both widths, with no horizontal overflow.
      The version pill retains its desktop dimensions and styling.
      
      **768px viewport**
      
      <img width="768" height="300" alt="After at 768px: navigation and
      version pill fit on one row"
      src="https://github.com/user-attachments/assets/f8994ca2-6d90-469a-b0df-a9d37165d838"
      />
      
      **1280px viewport** (cropped to the overlay)
      
      <img width="1000" height="300" alt="After at 1280px: unchanged desktop
      header layout"
      src="https://github.com/user-attachments/assets/e27eef41-d477-42f7-bcf3-224a1675e919"
      />
      
      ## Verification
      
      - `pnpm test-dev-turbo
      test/development/app-dir/instant-insights-tab-overlay/instant-insights-tab-overlay.test.ts`
      — all 5 tests passed.
      - Browser checks at 390, 768, and 1280 CSS-pixel widths confirm that the
      empty Issues tab remains visible, the pill keeps its 230.96 × 24px
      desktop dimensions and rounding, the mobile header has balanced spacing,
      and the wide-screen header remains on one row.
      - JavaScript build, formatting, and ESLint passed. Full `pnpm build-all`
      was attempted but blocked by the existing Rust workspace manifest error:
      `default-features = false` cannot override the workspace's
      `turbo-persistence` default features. Runtime verification used the
      published canary.38 native binary.
      
      <!-- NEXT_JS_LLM -->
      a18b9a58
    • Janka Uryga's avatar
      [PPF] Separate tracking of runtime data accesses for shells and prefetches (#98129) · e1131ee7
      Janka Uryga authored
      Expands the static tracking from #96095 to track shells and prefetches
      separately. We split the `ShouldAttemptStaticPrefetch` hint into
      `ShouldAttemptStaticShell` and `ShouldAttemptStaticPrefetch`, which the
      client router considers separately depending on whether we need a shell
      or a prefetch.
      
      The server-side tracking of `needsRuntimeRequest` becomes a bit more
      subtle.
      
      First, a runtime data access should only affect the shell if we're in
      the `ShellStatic` render stage. If we're already in the `PrefetchStatic`
      stage, then that content is not conceptually part of the shell, and
      should not deopt the shell to runtime, so we only unset
      `shouldAttemptStaticShell` if we're still in the shell stage.
      
      Second, accessing data that would only resolve in the prefetch (params,
      search params, short-stale caches) should **not** affect whether the
      shell can be static. `makeRuntimeDataHangingPromise` has been split into
      variants that match this:
      - `makeSessionDataHangingPromise` - data that affects the shell (and the
      prefetch), e.g. `cookies()`
      - `makeURLDataHangingPromise` - data that only affects the prefetch,
      e.g. `params`
      - `makeUnknownRuntimeDataHangingPromise`, used for private caches -- we
      omit these during build so we don't know whether they should affect the
      shell or only the prefetch, so we conservatively affect both (unless a
      private cache is only used in the prefetch stage)
        
      The server-side `needsRuntimeRequest` promise is now resolved such that
      data that only resolves in the prefetch does not affect the shell. If
      we're accessing data that only resolves in the prefetch, we will delay
      the promise's resolution to the `PrefetchStatic` stage, which means that
      when the client rewinds the static response to a shell, it will see an
      unresolved promise and consider the response as not having used runtime
      data. (see `markRuntimeDataAccessWhenStageReached`)
      e1131ee7
    • Sebastian "Sebbie" Silbermann's avatar
    • Jamiboy Mohammad's avatar
      test: clarify dev-only intent of duplicate Sass warning test (#98917) · 94eb1376
      Jamiboy Mohammad authored
      ## Summary
      
      Clarify that the duplicate Sass dependency warning test belongs in
      dev-mode coverage. The warning is emitted by `next dev`, which the test
      explicitly launches, but the test was previously scheduled only in
      production/start-mode jobs.
      
      Use a suite-level `@force-gate dev` in place of the start-mode guards
      and deployment skip. This is a test-organization cleanup: the previous
      arrangement could exercise the warning correctly, and this change adds
      no coverage or Next.js behavior changes. Fixture preparation, warning
      assertions, and process cleanup remain unchanged.
      
      ## Verification
      
      - Formatting, ESLint, and whitespace checks passed.
      - Focused Jest collection confirmed the scope is skipped in start and
      deploy modes.
      - Dev runtime verification and bootstrap build remain unverified: local
      pnpm commands stalled before producing output, including `pnpm
      --version`. Direct Jest collection also reported an existing SWC/package
      version mismatch. CI must validate the dev-mode execution.
      
      <!-- NEXT_JS_LLM -->
      94eb1376
    • Jamiboy Mohammad's avatar
      test: enable upward distDir deployment coverage (#98886) · 627dcba1
      Jamiboy Mohammad authored
      ## Summary
      
      Enable deploy coverage for the nested `upward-distdir` fixture while
      preserving its `distDir: '../.next'` configuration and existing
      rendering assertion. Configure Vercel to consume `apps/.next`, and reuse
      the fixture's `vercel.json` outputDirectory when collecting deployment
      metadata.
      
      The metadata script falls back to the existing output path when
      vercel.json or its outputDirectory override is absent. No new
      nextTestSetup option is needed.
      
      ## Verification
      
      - Prettier and ESLint passed.
      - Ten executions of the generated metadata command passed: absent
      config, absent/null outputDirectory, nested paths and paths containing
      spaces, with adapter mode enabled and disabled. Each case also confirmed
      that a missing BUILD_ID fails.
      - Local bootstrap build blocked by missing package-level dependencies in
      the isolated worktree.
      - The previous revision passed both normal and cache-components deploy
      CI. Deploy validation of this revision is pending CI; no local
      deployment was run.
      
      <!-- NEXT_JS_LLM -->
      627dcba1
    • Jamiboy Mohammad's avatar
      test: remove redundant deployment skips from mode-guarded suites (#98908) · 09b98c73
      Jamiboy Mohammad authored
      ## Summary
      
      Remove 28 redundant `skipDeployment` options across 16 e2e test files
      whose existing mode guards already exclude deploy. Preserve the original
      tests, fixtures, assertions, and outer mode guards. Remove the redundant
      inner deploy return in Custom routes export so Jest still registers its
      skipped test instead of rejecting an empty suite with setup hooks.
      
      This includes the loader-file error suite: its dev and local build/start
      sections have no enabled descendant tests in deploy mode, so Jest does
      not run their enclosing setup hooks. Removing these options does not
      enable new deployment coverage.
      
      Stacks on #98842, which contains the whole-suite moves.
      
      ## Verification
      
      - Verified the 28 option removals; the custom-routes collection fix
      additionally removes the redundant inner return and unused destructured
      mode flag.
      - A focused Jest Circus reproduction using the affected describe block
      reproduced both empty-suite hook errors before the fix; afterward it
      collected one skipped test, ran no setup or teardown hooks, and reported
      no errors.
      - Formatting, ESLint, and whitespace checks passed for the constituent
      changes.
      - Verified with Jest Circus that an outer `beforeAll` does not execute
      when all descendant tests are skipped.
      - Runtime tests were not rerun locally for this fold; CI runs on the
      updated branch.
      
      <!-- NEXT_JS_LLM -->
      09b98c73
    • Tobias Koppers's avatar
      Turbopack: trace static project files referenced by packages (#98712) · bf53f53c
      Tobias Koppers authored
      ### What?
      
      Allow Turbopack's native asset tracer to follow fully static
      application-root file references originating in packages, while
      continuing to block dynamic package references from traversing the
      application.
      
      Patterns containing alternatives retain only their fully static branches
      for project-root tracing. Branches containing any dynamic segment are
      discarded. A focused node-file-trace fixture covers a package loading an
      application-owned config through `path.resolve()` and `fs.existsSync()`.
      
      ### Why?
      
      Turbopack currently redirects every working-directory-relative reference
      from `node_modules` to the package directory. This protects builds from
      dynamic package expressions accidentally tracing much or all of the
      application, but it also prevents safe static configuration lookups such
      as `next-i18next.config.js` from reaching standalone output.
      
      The dynamic safeguard should remain, but known static files do not carry
      the same risk and should follow runtime working-directory semantics.
      
      Related to #98628.
      
      ### How?
      
      Add a pattern-level operation that extracts fully static alternatives
      from a normalized reference pattern. The tracing root selection uses
      that filtered pattern to choose the configured project working
      directory; dynamic-only patterns retain the existing package-directory
      fallback.
      
      The shared root-selection path applies this consistently to filesystem,
      path, worker, child-process, and specialized traced references. Existing
      outside-base and `node_modules` filtering tests continue to cover the
      safeguard.
      
      ### Verification
      
      - `cargo fmt -- --check`
      - `cargo test -p turbopack-core resolve::pattern`
      - `cargo test -p turbopack-tracing --test unit`
      - `git diff --check`
      
      <!-- NEXT_JS_LLM -->
      
      
      <!-- fleet fe000a60-fbb8-4835-b6ef-38d5684822a9 -->
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      bf53f53c
    • Niklas Mischkulnig's avatar
      Durable use cache: fix next/image pulling in NEXT_DEPLOYMENT_ID (#98739) · 28f84cea
      Niklas Mischkulnig authored
      If you do
      ```js
      import Image from "next/image";
      
      export function data(){
      	"use cache: remote";
      	return <Image .../>
      }
      ```
      then this previously ended up pulling in
      `process.env.NEXT_DEPLOYMENT_ID` via
      ```
      app/user-code.js
      node_modules/next/image.js
      node_modules/next/dist/shared/lib/image-external.js
      node_modules/next/dist/shared/lib/get-img-props.js
      node_modules/next/dist/shared/lib/deployment-id.js
      ```
      
      But actually making `image-external.js` a barrel file ensures that we
      don't pull in `get-img-props.js` when just importing the `Image` client
      component. Then `NEXT_DEPLOYMENT_ID` isn't referenced anymore.
      28f84cea
    • Aurora Scharff's avatar
      Unify hydration error tree details (#99008) · 3204d86c
      Aurora Scharff authored
      ## Summary
      
      Unifies hydration error details in the development overlay:
      
      - renders invalid HTML as a compact `Rendered tree` and mismatches as a
      compact `client/server diff`
      - keeps the nearest relevant user component and affected rows visible by
      default, with a disclosure control to expand the complete React-rendered
      tree
      - keeps neutral markers for invalid HTML and the `+ Client` / `- Server`
      legend only for actual mismatches
      - uses the same frame, spacing, typography, and overflow behavior for
      both variants
      
      ## Visual changes
      
      ### Invalid HTML
      
      | Before | After |
      | --- | --- |
      | ![Invalid HTML shown with ambiguous diff
      styling](https://github.com/user-attachments/assets/3ab72f7a-beac-4081-a91b-c0ebfa37027e)
      | ![Invalid HTML shown as a compact, expandable rendered
      tree](https://github.com/user-attachments/assets/1fcaa5ad-bdb6-4082-ba00-71bab8ab4466)
      |
      
      ### Client/server mismatch
      
      | Before | After |
      | --- | --- |
      | ![Client/server mismatch with an oversized collapsed
      tree](https://github.com/user-attachments/assets/176b77a2-bad6-41d2-9f16-96d125f31048)
      | ![Client/server mismatch shown as a compact, expandable diff with a
      client and server
      legend](https://github.com/user-attachments/assets/8d163768-4899-47bb-8155-67934a1c3e98)
      |
      
      ## Verification
      
      - App Router hydration acceptance tests with Turbopack and webpack
      - Pages Router hydration acceptance tests with Turbopack and webpack
      - focused hydration error count tests with and without Cache Components
      - Next.js type checking, ESLint, and Prettier
      - manual verification of invalid HTML and client/server mismatch
      overlays
      
      <!-- NEXT_JS_LLM -->
      3204d86c
    • Niklas Mischkulnig's avatar
      Turbopack: forward module graph, entrypoint write, and emit spans to the JS trace (#98408) · 9b96a51b
      Niklas Mischkulnig authored
      <img width="1273" height="207" alt="Bildschirmfoto 2026-09-09 um 16 32
      57"
      src="https://github.com/user-attachments/assets/849e55d4-bf3f-4ef0-bf0d-bd2879f89e25"
      />
      
      
      
      ## Summary
      
      Adds three Turbopack build-phase spans to the JS-side trace
      (`.next/trace`, `.next/trace-build`, and trace uploads), forwarded from
      Rust via `turbo_tasks.send_compilation_event` like the existing
      `turbopack-persistence` span:
      
      - `turbopack-module-graph` — whole-app module graph computation
      (`whole_app_module_graph_operation`)
      - `turbopack-write-entrypoints` — computing all output assets for the
      entrypoints write phase (`all_entrypoints_write_to_disk_operation`)
      - `turbopack-emit` — writing all output assets to disk
      (`emit_all_output_assets_once_with_issues_operation`)
      
      ---------
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      9b96a51b
    • Niklas Mischkulnig's avatar
      Fix startTime and shutdown delivery of forwarded Turbopack trace spans (#98426) · 719d7cea
      Niklas Mischkulnig authored
      before:
      <img width="1358" height="313" alt="Bildschirmfoto 2026-09-09 um 14 33
      59"
      src="https://github.com/user-attachments/assets/69c2dc9c-06f1-4df1-b5eb-e6878f2abe32"
      />
      
      after:
      <img width="1273" height="207" alt="Bildschirmfoto 2026-09-09 um 16 32
      57"
      src="https://github.com/user-attachments/assets/a601e1c6-c0b8-425f-b977-b58d92289ab6"
      />
      
      
      ## Summary
      
      Two fixes for Turbopack compilation events forwarded to the JS trace
      (`.next/trace`). The span-forwarding work stacks on top of this PR.
      
      - **`Span.manualTraceChild` serialized the event recording time as
      `startTime`** instead of the supplied epoch start, so forwarded spans
      rendered shifted forward by their own duration and overflowed their
      parent span. `startTime` now reflects the supplied start.
      - **Compilation events were lost at build shutdown**:
      `CompilationEventQueue` delivered events via an untracked
      `tokio::spawn`, and the build teardown aborted the events subscription
      right after `project.shutdown()` resolved, so shutdown-time events (e.g.
      `turbopack-persistence` on cold builds, where it is the only persistence
      event since builds use `ReadWriteOnShutdown`) were discarded whenever
      delivery lost the race. The queue now tracks in-flight deliveries and
      flushes/closes subscriber channels at the end of `stop_and_wait`, and
      the build waits for the subscription to drain before aborting it.
      
      ## Verification
      
      - New `trace.test.ts` unit test: a `manualTraceChild` span started in
      the past keeps its own start time (fails before the fix, passes after).
      - New `message_queue::test_flush_and_close` unit test: events are
      delivered before the channel closes; post-close subscriptions replay
      history and close.
      - `cargo check` / `cargo test -p turbo-tasks --lib message_queue`, root
      `pnpm typescript`.
      - The stacked PR on top verifies end-to-end that `turbopack-persistence`
      is now emitted on every cold build.
      
      <!-- NEXT_JS_LLM -->
      
      
      <!-- fleet 107de4c7-6206-422b-a422-9cc8d7047774 -->
      
      ---------
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      719d7cea
    • Niklas Mischkulnig's avatar
      Turbopack: loader change invalidation (#95732) · f80a4b4d
      Niklas Mischkulnig authored
      We apparently never invalidated when the loader source code changed.
      This now uses the same mechanism we already use for watching
      postcss/tailwind config files
      
      This also required changing the tracing mode of configs (and now
      loaders) to only care about imports, not FS file references to prevent
      infinite loops.
      f80a4b4d
    • Tobias Koppers's avatar
      perf: optimize CSS graph cycle removal (#98860) · 86d3d61e
      Tobias Koppers authored
      ### What?
      
      This PR changes how the graph-based CSS chunker resolves contradictory
      stylesheet ordering constraints.
      
      The previous implementation repeatedly found one cycle, removed one edge
      from it, and searched again. On dense graphs this could repeat thousands
      of expensive searches over almost the same data.
      
      The new implementation handles each cyclic region as a whole:
      
      1. Compute a good global order for the modules in that region.
      2. Improve that order with a small, bounded local search.
      3. Remove every edge that disagrees with the chosen order in one pass.
      
      This preserves the existing chunking pipeline and its hard constraints
      while making cycle removal much faster.
      
      ### Why?
      
      A production reproduction contained:
      
      - 499 CSS modules
      - 104,473 directed ordering edges
      - one cyclic region containing 475 modules
      - 9,574 edges removed one at a time
      
      `make_acyclic` alone took **9.61 seconds**. Each removed edge caused
      several weighted bidirectional shortest-path searches over nearly the
      same dense graph.
      
      With this PR, the same reproduction spends **73.5 ms** in `make_acyclic`
      under full turbo-tasks tracing, approximately **131× faster** than the
      original measured phase.
      
      ### How does the CSS graph work?
      
      This section intentionally avoids assuming graph-theory knowledge.
      
      Suppose two routes import CSS in these orders:
      
      ```text
      route A: reset.css, button.css, page-a.css
      route B: reset.css, card.css, page-b.css
      ```
      
      The chunker creates one node for each CSS file. For every ordered pair
      in a route, it records an arrow from the later file to the earlier file:
      
      ```text
      button.css → reset.css
      page-a.css → button.css
      page-a.css → reset.css
      ```
      
      An arrow means “the file on the left must come after the file on the
      right.” If several routes agree on the same relationship, the arrow gets
      a larger weight. The weight is therefore a vote count: a heavier arrow
      represents an ordering preference supported by more routes.
      
      #### Why cycles appear
      
      Different routes can disagree:
      
      ```text
      route A: a.css, b.css
      route B: b.css, a.css
      ```
      
      That creates both:
      
      ```text
      b.css → a.css
      a.css → b.css
      ```
      
      There is no global order that satisfies both. This is a cycle: following
      the arrows eventually returns to the starting node.
      
      Before the graph can be converted into one linear CSS order, some
      contradictory arrows must be discarded. There is no universally correct
      choice in this situation because the input itself asks for mutually
      incompatible orders. The goal is to preserve as much heavily-supported
      ordering information as possible.
      
      ### Previous algorithm
      
      The previous implementation:
      
      1. Found a short cycle using weighted bidirectional Dijkstra searches.
      2. Removed the lightest edge on that cycle.
      3. Repeated until no cycle remained.
      
      This makes intuitive sense for small graphs, but it is expensive when a
      dense cyclic region needs thousands of cuts: almost the same graph is
      searched again after every single removal.
      
      ### New algorithm
      
      #### 1. Find independent cyclic regions
      
      The code first finds **strongly connected components** (SCCs). An SCC is
      simply a group of nodes where every node can eventually reach every
      other node by following arrows.
      
      Only SCCs with more than one node can contain multi-node cycles. Acyclic
      parts of the graph are not changed.
      
      #### 2. Build a candidate order for each SCC
      
      The algorithm constructs an order using a weighted feedback-arc
      heuristic:
      
      - A node with no remaining prerequisites can safely go at one end.
      - A node that nothing else depends on can safely go at the other end.
      - If neither exists, choose the node whose outgoing-arrow weight most
      exceeds its incoming-arrow weight. Informally, place the node where it
      satisfies the largest net number of weighted ordering votes.
      
      Node indices break ties, so identical inputs always produce identical
      output.
      
      This produces a complete ordering of the SCC without deleting edges
      during the search.
      
      #### 3. Improve the candidate order
      
      The initial heuristic is fast but can miss simple improvements. The code
      therefore runs at most ten deterministic insertion sweeps:
      
      1. Temporarily remove one node from the order.
      2. Score every place where it could be inserted.
      3. Move it only if the move strictly increases the total weight of
      satisfied arrows.
      
      Equal scores keep the existing order. The strict-improvement rule stops
      as soon as a sweep makes no changes; ten is only a safety limit. In a
      deterministic 5,000-case corpus every SCC converged within four sweeps,
      while the supplied reproduction converged after six.
      
      Two-node SCCs skip this refinement because their heavier direction is
      already the optimal choice and no non-adjacent move is possible.
      
      #### 4. Remove contradictory edges in bulk
      
      Once the SCC has an order, every arrow can be classified:
      
      - Forward arrow: agrees with the order, so keep it.
      - Backward arrow: contradicts the order, so remove it.
      
      After all backward arrows are removed, following arrows can never return
      to an earlier position. Therefore the component cannot contain a cycle.
      
      The collected petgraph edge indices are removed in descending order
      because petgraph uses swap-removal; descending order keeps indices that
      have not yet been removed valid.
      
      #### 5. Continue the existing pipeline
      
      The rest of the chunker is unchanged:
      
      - `linearize` performs a topological sort and uses original route
      co-occurrence data to keep frequently co-loaded modules adjacent.
      - `split_into_chunks` balances downloaded bytes against request cost.
      - Global CSS containment and maximum chunk-size constraints are still
      enforced downstream.
      
      ### Correctness properties
      
      The implementation preserves these hard properties:
      
      - Consistent/acyclic input graphs are unchanged.
      - Every multi-node SCC becomes acyclic.
      - Edges outside cyclic SCCs are unchanged.
      - Output is deterministic.
      - Valid production input lets `linearize` emit every CSS module.
      - Global CSS cannot leak into a route that did not already load it.
      - Maximum chunk size remains enforced.
      
      The acyclicity argument does not depend on the heuristic finding a
      perfect order. Any total order becomes a DAG after every backward edge
      is removed; the heuristic only determines which valid compromise is
      preferred.
      
      Production chunk groups deduplicate module ids before graph
      construction, so they cannot create self-loops. `make_acyclic`
      deliberately does not remove hand-built self-loops; that is outside the
      production input contract.
      
      ### Ordering quality and compatibility
      
      Conflicting route orders have no solution that satisfies every route.
      This PR intentionally chooses a different compromise from the previous
      cycle-by-cycle algorithm.
      
      Quality was evaluated on the **final order after `make_acyclic` and
      `linearize`**, not merely by counting graph edges that survived:
      
      | Quality check | Previous | This PR |
      |---|---:|---:|
      | Exhaustive three-module cases reaching optimum | 3,375 / 3,375 |
      **3,375 / 3,375** |
      | Satisfied observations across 5,000 random cases | 142,190 |
      **143,010** |
      | Satisfied observations in the supplied reproduction | 103,483 |
      **105,302** |
      | Reproduction chunks | 1 × 499 modules | **1 × 499 modules** |
      | Reproduction requests per group | 1 | **1** |
      
      On the 5,000-case corpus, ordering quality was better in 570 cases,
      equal in 4,388, and worse in 42.
      
      There is a measured downstream trade-off: total requests increased from
      25,518 to 25,646 (**+0.50%**). Requests were better in 153 cases, equal
      in 4,699, and worse in 148. The implementation prioritizes aggregate
      import-order satisfaction while keeping that request increase bounded.
      
      Applications that accidentally depended on the previous arbitrary
      compromise for contradictory imports can observe a different CSS
      cascade. Consistent import orders are unaffected.
      
      ### Performance
      
      #### Reported reproduction and regression fixtures
      
      | Fixture | Previous | This PR | Improvement |
      |---|---:|---:|---:|
      | Supplied 499-module reproduction (full tracing) | 9.61 s | **73.5 ms**
      | ~131× |
      | Dense synthetic fixture | 2.248 s | **24.0 ms** | ~94× |
      | 25,600-node fragmented graph | 86.4 ms | **5.69 ms** | ~15× |
      
      Scratch arrays are reused across SCCs. The two-node fast path is
      important for fragmented graphs, where allocating refinement state for
      thousands of tiny SCCs would otherwise dominate runtime. Refinement
      scores candidate positions through slices and moves an accepted node
      with an in-place rotation, avoiding a full vector clone/removal for
      every node.
      
      #### Large sparse SCC comparison
      
      A second review tested a true sparse directed ring: `n` nodes, exactly
      `n` input edges, and one edge that must be removed.
      
      | Ring nodes | This PR | Previous |
      |---:|---:|---:|
      | 1,000 | **13.8 ms** | 103 ms |
      | 5,000 | **366 ms** | 2.69 s |
      | 10,000 | **1.47 s** | 10.87 s |
      | 20,000 | **5.79 s** | 50.50 s |
      
      The new algorithm is approximately 7–9× faster at every measured size on
      this sparse shape.
      
      #### Very large dense SCC scaling
      
      A synthetic dense fixture was also tested beyond the production
      reproduction's 454-node SCC:
      
      | Modules | SCC size | This PR |
      |---:|---:|---:|
      | 500 | 496 | 34 ms |
      | 1,000 | 1,000 | 203 ms |
      | 1,500 | 1,498 | 491 ms |
      | 2,000 | 1,999 | 1.45 s |
      
      There was no paired previous-algorithm baseline for this exact large
      fixture. These single-run synthetic measurements show that a
      sufficiently large dense SCC can still take seconds. The graph itself
      contains roughly a quadratic number of pairwise edges, so both graph
      construction and cycle resolution become expensive at that scale.
      
      Whether real applications produce single SCCs this large is unknown. A
      possible future mitigation is to evaluate skipping insertion refinement
      above a size threshold, but its ordering-quality impact has not been
      measured and is not part of this PR.
      
      ### Why ten refinement sweeps?
      
      The initial implementation used a maximum of three. Reviewer feedback
      asked whether ten would improve quality and how quickly the search
      normally converges, so both limits were measured with identical inputs:
      
      | Measurement | Maximum 3 | Maximum 10 |
      |---|---:|---:|
      | 5,000-case corpus satisfied observations | 310,759 | 310,759 |
      | 5,000-case corpus requests | 51,617 | 51,617 |
      | Corpus SCCs needing more than 3 sweeps | capped | 2 |
      | Reproduction satisfied observations | 105,300 | **105,302** |
      | Reproduction convergence | capped at 3 | stopped after 6 |
      | Reproduction full-evaluation probe | 57.4 ms | 65.8 ms |
      
      Ten was selected because three was actively truncating improvements in
      the reproduction, while ten allowed every measured input to stop
      naturally. The quality gain is intentionally described as small: +2 of
      105,300 observations and no change across the random corpus. The
      slice/in-place refactor offsets the extra sweeps on the release fixtures
      (dense: 26.9 → 24.0 ms; fragmented: 6.36–6.69 → 5.69 ms).
      
      ### Verification
      
      - Focused `style_groups_graph` suite: **59 passed, 0 failed**, 2
      benchmarks ignored
      - `cargo fmt --all -- --check`
      - `cargo check -p turbopack-core`
      - `cargo clippy -p turbopack-core --tests -- -D warnings`
      - CSS-order E2E: **291 passed, 0 failed**, 12 existing todos
      - Exhaustive three-module corpus: **3,375/3,375 optimal**
      - Deterministic 5,000-case corpus and supplied reproduction replay
      - Dense, fragmented, and sparse release performance fixtures
      
      <!-- NEXT_JS_LLM -->
      
      
      <!-- fleet 0ed38506-67e1-4bbf-9eab-5a809a529df4 -->
      
      ---------
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      86d3d61e
    • Aurora Scharff's avatar
      Use AGENTS.md for managed agent instructions (#99043) · 43f54d52
      Aurora Scharff authored
      ## Summary
      
      Use `AGENTS.md` as the single instruction file across Next.js agent
      tooling. `next dev`, `create-next-app`, upgrades, the legacy docs-index
      codemod, and eval fixtures no longer create, discover, or update
      `CLAUDE.md`.
      
      This also removes the repository's compatibility symlink and updates the
      documentation and tests around generated agent instructions. Claude Code
      now reads `AGENTS.md` directly, so the additional alias is no longer
      needed.
      
      ## Verification
      
      - 10 managed-file unit tests pass.
      - 12 dev-server integration tests pass, including `agentRules: false`
      with agent feedback enabled.
      - 12 `agents-md` codemod tests pass.
      - 2 focused `create-next-app` tests pass for `--agents-md` and
      `--no-agents-md`.
      - The `next`, `create-next-app`, and `@next/codemod` package builds
      pass.
      - Focused ESLint passes.
      - Full `pnpm build-all` remains blocked by Cargo workspace inheritance
      for `turbo-persistence` (`default-features`). Root `pnpm typescript`
      fails in the unchanged `evals/next-upgrade/lib/experiment.ts` setup
      callback.
      
      <!-- NEXT_JS_LLM -->
      43f54d52
    • Niklas Mischkulnig's avatar
      Turbopack: analyze mode tracing imports only (#98825) · 2f3e77f5
      Niklas Mischkulnig authored
      We had 3 modes, now we just have 2 boolean for all possible 2*2 = 4
      modes
      2f3e77f5
    • Tobias Koppers's avatar
      Turbopack: compact re-export registration (#98617) · 812c88f3
      Tobias Koppers authored
      ## Summary
      
      Adds a compact Turbopack runtime path for modules whose exports are
      entirely forwarded from other modules. It replaces one generated wrapper
      getter per binding with a flat re-export description, while preserving
      live-binding semantics and source evaluation order.
      
      This revision also makes the optimization generic for synthetic
      re-export facades, rather than leaving facade integration in the stacked
      export-mangling PR:
      
      - synthetic facades use `ExportRegistrationMode::Reexport`;
      - their explicit reference list supplies ordering because they have no
      source `ImportMap`;
      - an evaluation-only locals reference can be represented as an empty
      group;
      - references whose import is performed by the compact registration do
      not emit it twice;
      - pruned references and merged evaluation-only references are omitted,
      because they deliberately produce no namespace binding and may have no
      module factory in the chunk;
      - async modules and known export-cycle circuit breakers retain the
      general registration path.
      
      The runtime now inspects source property descriptors. Constant exports
      reuse the source value, live exports reuse the exact
      receiver-independent Turbopack namespace getter, and
      dynamic/proxy/missing properties fall back to a wrapper getter.
      Destination descriptors remain enumerable, non-configurable, read-only
      ESM namespace properties; setters are never forwarded.
      
      ## Output examples
      
      A re-export-only module can suppress its redundant import and use a
      module-id group:
      
      ```js
      // before
      var ns = __turbopack_context__.i("a.js")
      __turbopack_context__.s(["a", () => ns.a, "b", () => ns.b])
      
      // after
      __turbopack_context__.S(["a.js", "a,a,b,b"])
      ```
      
      Two source modules become groups separated by `0`:
      
      ```js
      __turbopack_context__.S([
        "first.js", "a,a,b,b",
        0,
        "second.js", "c,c",
      ])
      ```
      
      Encoding is selected independently per group. A comma-containing name
      uses explicit pairs while another group can remain packed:
      
      ```js
      __turbopack_context__.S([
        "first.js", "b", "b", "has,comma", "has,comma",
        0,
        "second.js", "c,c",
      ])
      ```
      
      A synthetic facade includes its evaluation-only locals part as an empty
      group, then its forwarded bindings in reference order:
      
      ```js
      __turbopack_context__.S([
        "reexports.js <locals>",
        0,
        "x.js", "x,x",
        0,
        "y.js", "y,y",
      ])
      ```
      
      Inside a scope-hoisted factory, imports are retained and existing
      namespace objects are used as heads because another logical module in
      the merged factory may read them:
      
      ```js
      var locals = __turbopack_context__.i("reexports.js <locals>")
      var x = __turbopack_context__.i("x.js")
      __turbopack_context__.S([locals, 0, x, "x,x"], facadeId)
      ```
      
      A merged evaluation-only locals reference is omitted from that list:
      scope hoisting supplies only an in-factory ordering placeholder, not a
      namespace variable that `S` could read.
      
      ## Runtime representation
      
      For each forwarded property, `S` reads the source descriptor:
      
      - data descriptor → capture the value with the runtime's value tag;
      - getter descriptor → reuse that exact getter (Turbopack-generated
      namespace getters are receiver-independent);
      - no usable own descriptor → use `() => namespace[name]` as a defensive
      fallback.
      
      Tests pin constant primitives, frozen objects, function values, live
      updates, exact getter identity, receiver independence, destination
      descriptor flags, omitted setters, and the fallback path.
      
      ## Verification
      
      - `cargo test -p turbopack-ecmascript -p turbopack-tests` — **590 unit,
      302 execution, 3 auxiliary, 131 snapshot** tests passed on this layer
      - Full stacked #97770 verification — **590 unit, 303 execution, 3
      auxiliary, 131 snapshot** tests passed
      - `cargo clippy -p turbopack-ecmascript -p turbopack-core -- -D
      warnings`
      - `cargo fmt --all -- --check`
      - Runtime TypeScript check (`pnpm check` in
      `turbopack-ecmascript-runtime/js`)
      - `pnpm build-all`
      - Dedicated coverage for ordinary import/re-export ordering, transformed
      `DUMMY_SP` declarations, callable CommonJS namespaces, synthetic facade
      ordering, scope-hoisted retained imports, pruned and merged evaluation
      references, async fallback, and export-cycle circuit breakers
      
      ## Incremental size on top of #98932
      
      Scratch comparison only, as requested: #98617 stayed based on `canary`.
      Three apps were built with scope hoisting both disabled and enabled.
      Client reports raw and deterministic gzip (`gzip -9 -n`, sorted JS
      files); server reports raw only. Every row was repeated byte-for-byte.
      
      | benchmark | scope hoisting | client raw | client gzip | server raw |
      real `S` sites (client/server) |
      | --- | --- | ---: | ---: | ---: | ---: |
      | `basic-app` | off | +510 B | +214 B | **−6,114 B** | 0 / 56 |
      | `basic-app` | on | +510 B | +164 B | +8,618 B | 0 / 0 |
      | `heavy-npm-deps` *(lodash + Mantine + Mermaid)* | off | **−2,268 B** |
      **−432 B** | +4,680 B | 3 / 8 |
      | `heavy-npm-deps` *(lodash + Mantine + Mermaid)* | on | +522 B | +191 B
      | +8,630 B | 2 / 2 |
      | `module-cost` | off | +510 B | +263 B | +7,432 B | 0 / 6 |
      | `module-cost` | on | +510 B | +265 B | +8,624 B | 0 / 1 |
      
      Aggregate raw movement across the six rows is **+32,164 B**. The shared
      helper is only amortized in configurations with many eligible facade
      calls; scope hoisting commonly resolves forwarded bindings to locals,
      leaving few calls while every runtime copy still carries the helper.
      
      Descriptor reuse does **not** change generated module code or call-site
      counts. Compared with the same facade integration using wrapper getters,
      it adds **155 B client raw** and **527 B per runtime copy** (**1,054 B
      server raw** in these apps). Its purpose is avoiding per-binding wrapper
      allocation / access indirection where a source value or getter already
      exists, not reducing bundle bytes. The size result was reported before
      continuing, and descriptor work proceeded by explicit maintainer
      direction.
      
      <!-- NEXT_JS_LLM -->
      
      <!-- fleet ecdfa248-cd54-41ac-b4a2-c9d49e2a67ee -->
      
      ---------
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      Co-authored-by: 's avatarLuke Sandberg <210140+lukesandberg@users.noreply.github.com>
      812c88f3
    • Niklas Mischkulnig's avatar
      test: Add test for ESM and CJS exports of `next/*` APIs (#98882) · 17e0dab0
      Niklas Mischkulnig authored
      Assert the shape of those across ESM and CJS to prevent regressions in
      the future
      17e0dab0
    • next-js-bot[bot]'s avatar
      v16.4.0-canary.38 · 2861a364
      next-js-bot[bot] authored
      2861a364
    • Tobias Koppers's avatar
      feat(turbopack): support `false` values for `resolveAlias` config (#93331) · 95c5e390
      Tobias Koppers authored
      ### What?
      
      Adds support for `false` as a value in
      `experimental.turbopack.resolveAlias`, which resolves the aliased module
      to an empty stub — matching webpack's long-standing behavior.
      
      ```js
      // next.config.js
      module.exports = {
        experimental: {
          turbopack: {
            resolveAlias: {
              'some-server-only-module': false,
            },
          },
        },
      }
      ```
      
      With this alias in place:
      - `import * as ns from 'some-server-only-module'` → `ns` is `{}`
      - `import { foo } from 'some-server-only-module'` → `foo` is `undefined`
      - `import def from 'some-server-only-module'` → `def` is `undefined`
      - `await import('some-server-only-module')` → resolves to `{}`
      - `require('some-server-only-module')` → returns `{}`
      
      ### Why?
      
      Webpack supports `false` as an alias target to stub out modules (e.g. to
      exclude Node-only packages from client/edge bundles). Turbopack did not,
      causing migration friction for projects that rely on this pattern.
      
      ### How?
      
      Threads the `false` sentinel through the full resolution pipeline as a
      new `Empty` variant:
      
      ```
      false (config)
        → SubpathValue::Empty      (next-core import map)
        → ImportMapping::Empty     (turbopack-core remap)
        → ReplacedImportMapping::Empty
        → ResolveResultItem::Empty
        → ModuleResolveResultItem::Empty
        → ReferencedAsset::Empty   (ESM static imports)
        → SinglePatternMapping::Ignored  (CJS require / dynamic import)
      ```
      
      For static ESM imports, `ReferencedAsset::Empty` is kept as a distinct
      variant so that `binding.rs` can distinguish a namespace import (yields
      `{}`) from a named/default import (yields `undefined`).
      
      For CJS `require()` and dynamic `import()`,
      `ModuleResolveResultItem::Empty` maps to the existing
      `SinglePatternMapping::Ignored`, which already generates the correct
      `{}` / `Promise.resolve({})` stubs — so no new code-generation path was
      needed there (the redundant `Empty` variant introduced during
      development was removed in a follow-up cleanup commit).
      
      **Files changed:**
      - `packages/next/src/server/config-shared.ts` — add `false` to
      `resolveAlias` type
      - `packages/next/src/server/config-schema.ts` — add `z.literal(false)`
      to schema
      - `crates/next-core/src/next_import_map.rs` — map `false` →
      `SubpathValue::Empty`
      - `turbopack/crates/turbopack-core/src/resolve/remap.rs` — handle
      `ImportMapping::Empty`
      - `turbopack/crates/turbopack-core/src/resolve/mod.rs` — propagate
      `ModuleResolveResultItem::Empty`
      - `turbopack/crates/turbopack-ecmascript/src/references/esm/base.rs` —
      `ReferencedAsset::Empty`
      - `turbopack/crates/turbopack-ecmascript/src/references/esm/binding.rs`
      — empty-module binding code-gen
      - `turbopack/crates/turbopack-ecmascript/src/references/esm/url.rs` —
      handle Empty in URL refs
      - `turbopack/crates/turbopack-ecmascript/src/references/async_module.rs`
      — skip Empty in async module analysis
      -
      `turbopack/crates/turbopack-ecmascript/src/references/pattern_mapping.rs`
      — map Empty → Ignored
      
      **Tests:** `test/e2e/turbopack-resolve-alias-false/` covers all five
      import styles (namespace, named, default, dynamic, CJS).
      
      ---------
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      95c5e390
    • Jiwon Choi's avatar
      Enable AI upgrade for canary (#99001) · 7353da4c
      Jiwon Choi authored
      > [!TIP]
      > Recommended to review commit by commit.
      
      ### Why?
      
      Support `canary` releases for agentic upgrade so the workflow is
      available for the dogfooders. Startup reminders also need to check
      target eligibility before offering an upgrade that the configured policy
      cannot perform.
      
      ### How?
      
      Enable latest and Future upgrades on the canary channel while keeping
      stable installations on stable releases. Security upgrades and advisory
      checks remain stable-only; canary version ordering is not used to infer
      security fixes. Share policy-aware advisory and target assessment
      between startup reminders and explicit upgrades, retaining security
      warnings when no eligible target is available and offering bare `--ai`
      only when the configured policy can proceed.
      
      Explicit stable `latest` upgrades also check target advisories, after
      treating strictly older targets as a no-op; equal affected targets
      remain blocked. Canary latest and Future upgrades skip advisory
      assessment. Version reminders keep their major/minor threshold, and
      Future Defaults retain their full-version availability checks.
      Assessment caching is left as a TODO.
      
      The agentic upgrade guide remains a bundled, agent-consumed workflow
      marked `version: draft`; public-facing documentation will be handled
      separately.
      7353da4c
    • Tobias Koppers's avatar
      fix(turbo-persistence): preserve write errors on writer drop (#98840) · becee66e
      Tobias Koppers authored
      ### What?
      
      Preserve write failures from streaming SST construction instead of
      replacing them with debug-only writer lifecycle assertions. This adds
      explicit cancellation, immediate best-effort cleanup of incomplete SSTs,
      and focused coverage for failed writes and finalization.
      
      ### Why?
      
      `std::thread::panicking()` is false while an error is propagated through
      `Result`. On disk-full and similar failures, writers and their owning
      collectors are therefore dropped before a caller begins panic unwinding,
      allowing lifecycle assertions to obscure the original I/O error. Leaving
      partial files until startup recovery also delays reclaiming scarce disk
      space.
      
      ### How?
      
      `StreamingSstWriter::cancel()` consumes an incomplete writer, discards
      buffered bytes without flushing or finalizing, closes the raw handle,
      and best-effort removes the partial SST. Failed close attempts and
      unfinished Drop paths use the same cleanup, while deletion failures are
      ignored so they cannot replace the root error; existing startup recovery
      remains the fallback.
      
      Writer-owning scopes preserve the original error, explicitly cancel
      their writers, and then return that error. The compaction merge scope
      cancels both collectors on every error exit so a sibling collector
      cannot mask the failure. Successful close marks the finalized SST for
      preservation, and healthy writers still have to call `close()` or
      `cancel()` to satisfy the debug lifecycle invariant.
      
      The regression tests substitute an unbuffered read-only output handle to
      force deterministic add and close failures without requiring disk
      pressure.
      
      ### Verification
      
      - `cargo test -p turbo-persistence` (114 passed)
      - `cargo check --release -p turbo-persistence`
      - `cargo fmt --package turbo-persistence -- --check`
      
      <!-- NEXT_JS_LLM -->
      
      <!-- fleet da0c4e98-b86a-4c93-a519-8a63147e3f5c -->
      
      ---------
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      becee66e
    • Tobias Koppers's avatar
      Skip slow valued tombstone test under Miri (#98992) · cdecbe09
      Tobias Koppers authored
      ### What?
      
      Exclude `valued_tombstone_survives_partial_compaction` from Miri test
      builds while keeping the test enabled for normal Rust test runs.
      
      ### Why?
      
      The test takes about 16 minutes under Miri and is the sole long-tail
      test after the rest of the suite finishes. Since nextest runs tests
      concurrently, this one outlier determines most of the job's wall-clock
      time. The next-slowest tests finish around 400 seconds, so excluding
      this case should reduce the Miri job by roughly nine minutes without
      removing the remaining tombstone-compaction coverage.
      
      ### How?
      
      Gate only this test with `cfg(not(miri))` and document its measured CI
      runtime next to the gate. The test body and its native behavior remain
      unchanged.
      
      Verification:
      
      - Focused native test passes.
      - The test is absent from the no-default-features Miri test inventory.
      - Rust formatting and the no-default-features persistence check pass.
      
      
      <!-- fleet fb42942f-173a-484c-b4de-4e18354834c6 -->
      Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
      Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
      Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
      cdecbe09
  2. 21 Sep, 2026 12 commits
    • Aurora Scharff's avatar
      Improve the agent feedback review flow (#98937) · 7516b200
      Aurora Scharff authored
      ## Summary
      
      - review queued feedback immediately before the final response, after
      requested work and tool calls are complete
      - run the feedback command only when candidates exist, preserve them
      when reporting is unavailable, and clear them after each qualifying
      review form is opened or returned as a fallback URL
      - add an internal `--dry-run` mode that returns the bundled preview
      protocol without opening forms or clearing the queue
      - align the managed instructions, reporting protocol, evals, tests, AI
      agents guide, and API reference
      
      ## Verification
      
      - `pnpm --filter=next types`
      - focused `agent-feedback-instructions` unit tests
      - `node packages/next/dist/bin/next internal agent-feedback-instructions
      --dry-run`
      - targeted Prettier, ESLint, and language checks
      
      <!-- NEXT_JS_LLM -->
      7516b200
    • Jiwon Choi's avatar
      Run AI upgrades with the latest official canary (#98870) · a030ddc7
      Jiwon Choi authored
      ### Why?
      
      `next@canary` can reuse a cached `canary.33` even after `canary.35` is
      published, causing `next upgrade --ai` to run outdated upgrade logic.
      
      ### How?
      
      Resolve the latest official canary from public npm, then reuse the
      running CLI if it matches or launch and verify that exact version. Keep
      pnpm installation errors visible so failed launches are diagnosable.
      
      The lookup does not use package-manager registry, proxy, or CA settings:
      public npm must be reachable, and installation can fail if a configured
      mirror lacks the selected version.
      
      <!-- NEXT_JS_LLM -->
      a030ddc7
    • Jamiboy Mohammad's avatar
      test: move whole development-only suites out of e2e (#98842) · 55b20af2
      Jamiboy Mohammad authored
      ## Summary
      
      Move whole development-only suites from `test/e2e` to
      `test/development`: instant-validation-causes (including its
      partial-prefetching variant), webpack-loader-errors,
      use-cache-deadlock-probe, and next-image-https. Update the corresponding
      test manifests and remove redundant mode checks.
      
      Existing disabled coverage remains disabled. The HTTPS image test
      continues to use its shared e2e fixture. Mixed-suite extractions are
      reviewed separately in the next PR in the stack.
      
      ## Verification
      
      - Formatting, ESLint, and whitespace checks passed.
      - Verified that the two-PR stack's final tree is identical to the
      previously published combined change.
      - Runtime tests were not rerun locally for this history-only split; CI
      runs on both layers.
      
      <!-- NEXT_JS_LLM -->
      55b20af2
    • Jiwon Choi's avatar
      Fix `instant-false` codemod to run on route segment filenames (#98880) · 9b16af81
      Jiwon Choi authored
      ### Why?
      
      The codemod incorrectly adds `instant = false` to helper files because
      its matcher matches `layout.ts` within `custom-layout.ts` and `page.tsx`
      within `homepage.tsx`.
      
      ### How?
      
      Require filenames to start with `page.`, `layout.`, or `default.`, while
      preserving compound extensions. The codemod does not consult
      `pageExtensions`, so files such as `page.test.tsx` remain eligible.
      
      <!-- NEXT_JS_LLM -->
      9b16af81
    • Jamiboy Mohammad's avatar
      test: migrate legacy deployment exclusion callers (#98473) · 0f3a2bef
      Jamiboy Mohammad authored
      ## Summary
      
      Migrate the shared cache-components error tests and two additional
      legacy deployment exclusions from `skipDeployment`/`skipped` to test
      gates, so these callers can land on canary before the API is removed.
      
      Place the cache-error gate on the existing named `describe` boundary in
      each of the 12 `.test.ts` entry files. Jest transforms gate pragmas in
      test files; a gate in the shared utility would be inert. The helper
      continues registering the same tests inside those entry-level suites,
      preserving their names and snapshots. These tests inspect local
      prerender builds and cannot run against a deployment.
      
      The other two callers cover segment-cache fixture mutation and
      production output-file tracing. This is a standalone preparatory
      migration, not the removal of the legacy API itself.
      
      ## Verification
      
      - Rebased onto canary at `ccef3db5`; the stable patch ID matches the
      original migration exactly.
      - On the rebased tree, all 77 gate infrastructure unit tests passed.
      - Deploy-mode Jest collection of all 12 cache-error entry files: 236
      skipped, zero executed, and no deployment started.
      - Prettier, ESLint, and diff whitespace checks passed.
      - Full bootstrap attempted but blocked by missing package-level
      dependencies (`microbundle`) in the temporary worktree; no full
      dev/start integration run is claimed.
      
      <!-- NEXT_JS_LLM -->
      0f3a2bef
    • Josh Story's avatar
      Split revalidation errors by execution context (#98993) · 72858d71
      Josh Story authored
      ## Summary
      
      - Narrow build-time generator names to a literal type that can be
      extended as new generators are added.
      - Split the combined revalidation diagnostic into render,
      cached-function, and build-time-generator errors so each failure reports
      only its actual context and never needs a fallback generator name.
      - Cover all three contexts in the existing development and production
      test suites.
      
      Follow-up to the review feedback on #98891.
      
      ## Verification
      
      - `HEADLESS=true pnpm test-dev-webpack
      test/e2e/app-dir/revalidatetag-rsc/revalidatetag-rsc.test.ts` (3 tests)
      - `HEADLESS=true pnpm test-start-webpack
      test/e2e/app-dir/revalidatetag-rsc/revalidatetag-rsc.test.ts` (3 tests)
      - Production Webpack `generate-static-params-errors` suite (6 tests)
      - `pnpm --filter=next types`
      
      <!-- NEXT_JS_LLM -->
      72858d71
    • Josh Story's avatar
      Enable strict route matching by default (#97397) · 26bf404d
      Josh Story authored
      ## Summary
      
      This enables strict route matching by default. App Router URLs that
      cannot construct a complete route tree are rejected, unreachable pages
      are reported, and incomplete catch-all matchers are pruned.
      
      If strict route matching finds one of these invalid route structures,
      Next.js warns that the validation implies a bug in the app and points to
      `deprecated.looseRouteMatching: true` as a temporary escape hatch. The
      deprecated option only accepts `true`; strict matching remains the
      normalized internal behavior when the option is absent.
      
      For example, this layout cannot render either URL as a complete route
      because neither named slot has a page or default for the URL matched by
      its sibling:
      
      ```text
      app/
      ├── layout.tsx
      ├── @left/foo/page.tsx
      └── @right/bar/page.tsx
      ```
      
      Previously the app could depend on soft navigation preserving stale slot
      state even though `/foo` and `/bar` could not be loaded directly. With
      strict route matching enabled, the build reports the incompatible slots
      and the two unreachable pages. Adding explicit defaults makes the
      intended fallback behavior valid again.
      
      ## Verification
      
      - `pnpm build-all`
      - `pnpm exec jest packages/next/src/server/config.test.ts --runInBand`
      - `parallel-routes-pruned-matchers` in production with Turbopack and
      Webpack
      - `parallel-routes-leaf-segments` in production with Turbopack
      - strict diagnostic fixtures in production with Turbopack
      
      <!-- NEXT_JS_LLM -->
      26bf404d
    • Aurora Scharff's avatar
      Surface agent feedback gate connection failures (#98991) · e7d9685d
      Aurora Scharff authored
      ## Summary
      
      - Distinguish an unreachable agent-feedback rollout gate from an
      explicitly disabled rollout.
      - Exit the internal feedback-instructions command with actionable retry
      guidance so sandboxed agents can request network access instead of
      silently skipping reports.
      
      ## Verification
      
      - `pnpm exec jest
      packages/next/src/cli/internal/agent-feedback-status.test.ts
      packages/next/src/cli/internal/agent-feedback-instructions.test.ts
      --runInBand`
      - `pnpm --filter=next types`
      - `pnpm --filter=next build`
      - Verified the built CLI exits 1 with retry guidance without network
      access and returns the protocol with network access.
      
      <!-- NEXT_JS_LLM -->
      e7d9685d
    • Josh Story's avatar
      Generalize the build-time generator work-unit store name (#98891) · 192fcaf7
      Josh Story authored
      ## Summary
      
      Rename the internal `GenerateStaticParamsStore` work-unit context to
      `BuildTimeGeneratorStore`, with discriminant `build-time-generator`.
      Carry the public export name in a required `functionName` field so
      shared error paths identify the generator that is actually running.
      
      This is a behavior-preserving preparatory refactor.
      `generateStaticParams` remains the only producer. Every consumer retains
      the same branch, so public-cache support, unavailable request APIs,
      inherited root parameters, and existing error messages are unchanged.
      
      The name describes a build-time generator's execution context rather
      than one function. For example, another generator that loads
      configuration through a cached helper should be able to reuse this
      context without introducing another work-unit variant throughout the
      framework. Function-specific contexts can be added later if their
      semantics actually diverge.
      
      For example, a generator that calls `headers()` needs an error naming
      that generator, not an error that always says `generateStaticParams`.
      The field is set explicitly rather than read from `Function.name`, which
      may change during bundling. Request APIs, private-cache rejection,
      revalidation, and rendering invariants use this name. Missing-root-param
      advice about parent gSP calls remains specific to gSP; other generators
      report that the value is unavailable in their own scope.
      
      This independent prerequisite for #97393 introduces no API or feature
      flag. The API-specific initializer and its error fixtures live in
      #97393, so this PR remains independently landable and
      behavior-preserving for existing gSP users.
      
      ## Verification
      
      - Existing `generate-static-params-errors`,
      `app-root-params-getters/generate-static-params`, and
      `generate-static-params-error` fixtures: all ten production Webpack
      tests pass, including unchanged error strings and parent root-param
      behavior.
      - Existing `use-cache/use-cache.test.ts` static-HTML assertion passes,
      exercising cached helpers called from gSP in both a page and route
      handler.
      - Full bootstrap and TypeScript declaration build pass.
      
      <!-- NEXT_JS_LLM -->
      192fcaf7
    • Josh Story's avatar
      Use structural React keys during server rendering (#98944) · c20c1d41
      Josh Story authored
      ## Summary
      
      Use structural React keys during server rendering so an HTML prerender
      can resume without rewriting React's postponed state when route params
      become known. Browser keys and router-cache identity are unchanged.
      
      For example, `/products/[slug]` previously prerendered layout boundaries
      with a key containing an opaque slug placeholder. Resuming
      `/products/shoe` produced a different key, so Next.js substituted `shoe`
      into the serialized React state before handing it back to React. Both
      server passes now use `slug|d`. The browser still uses `slug|shoe|d`,
      preserving template remounts and back/forward state behavior.
      
      The server only renders the active entry at each layout-router position,
      so it does not need parameter values to distinguish cached browser
      entries. React keys are not embedded in the HTML; hydration derives its
      concrete keys from the request's route state.
      
      - Use segment name/type for server layout keys and structural route
      paths for the server head key. Server keys always omit search params.
      The existing browser-module variant mechanism selects the concrete key
      implementation for browser bundles in both Webpack and Turbopack.
      - Remove placeholder substitution and the request-params argument from
      postponed-state parsing. Persist only fallback param names for render
      staging; React's postponed state no longer needs to be searched or
      rewritten.
      - Simplify the remaining opaque fallback map to param name →
      placeholder. Its dynamic-param type slot is unused after removing
      interpolation. Parameter wrappers still control suspension; this does
      not make unknown params available to application code.
      - Test server and browser keys directly, including catch-all/intercepted
      segments and search params. Update the action-only resume fixture's
      single assertion on the resume-metadata format so its three cases reach
      their behavioral checks for action execution, revalidation, and
      `notFound()` with names-only metadata.
      
      This refactor is independently landable against `canary` and is now the
      base of the parameter-matching stack: #98944 → #98891 → #98892 → #98893
      → #97393. It supersedes #98890. It retains internal opaque placeholders
      but removes their role in matching React's postponed state. No new
      integration fixtures are needed.
      
      ## Verification
      
      Latest cleanup:
      
      - 126 focused unit tests and 4 snapshots pass in both default and Cache
      Components/Webpack configurations.
      - 34 production Webpack tests pass across `fallback-shells`,
      `partial-fallback-shell-upgrade`,
      `action-only-fallback-resume-data-cache`, and
      `resuming-head-runtime-search-param`; 4 existing tests remain skipped.
      The three action-only resume cases now reach and pass their behavioral
      assertions.
      
      Earlier commits also passed existing production and dev Webpack coverage
      for back/forward state, template remounts, base-path params,
      nested/parallel/intercepted routes, form-state hydration, and
      standalone/edge output.
      
      A reviewer verified this head under Turbopack using a native binary
      built from the same commit: a broader unit selection passed (144 tests,
      the focused set above plus the remaining router-reducer suites), the
      `packages/next` type check was clean, and 33 production e2e tests passed
      across `fallback-shells`, `partial-fallback-shell-upgrade`, and
      `action-only-fallback-resume-data-cache`.
      
      <!-- NEXT_JS_LLM -->
      c20c1d41
    • next-js-bot[bot]'s avatar
    • François Martin's avatar
      Remove unused `hasWarnings` and `warnings` (#96956) · 57eb2b34
      François Martin authored
      ### Fixing a bug
      
      Nothing reads the two fields `hasWarnings` and `warnings` on
      `TypeCheckResult`.
      
      `verifyAndRunTypeScript` has four callers:
      
      - `build/type-check.ts` only reads `inputFilesCount`, `totalFilesCount`
      and `incremental`
      - `next-test` only reads `version`
      - `setup-dev-bundler` only reads `version`
      - `next-typegen` throws the result away
      
      `warnings` is also always empty. It looks for diagnostics with the
      `Warning` category, but I checked, and TypeScript 6.0.2 has no messages
      in that category. Deprecation messages use `Suggestion` instead.
      
      So on every build, we filtered and formatted every diagnostic to build a
      list that was always empty, and that nobody read.
      
      So I'm suggesting removing it instead, as it is clearly not being used.
      I also checked the GitHub code search across all public repositories and
      couldn't find anyone using either of them. That aside, it also never
      really worked correctly, as it would always return `hasWarnings: true`
      even if `warnings` was empty.
      
      No test added since the fields are being removed. Also since this is
      such a small change I didn't create an issue to link here, I'd be happy
      to file one if you prefer me to.
      
      Thanks for the hard work and taking the time for reviewing this PR! 😊
      57eb2b34
  3. 19 Sep, 2026 2 commits
    • next-js-bot[bot]'s avatar
      v16.4.0-canary.37 · 34433fd1
      next-js-bot[bot] authored
      34433fd1
    • Josh Story's avatar
      Preserve closed-parameter restrictions in client route prediction (#98889) · 59ad3de6
      Josh Story authored
      ## Summary
      
      Preserve the restrictions of `dynamicParams = false` in client route
      prediction, independently of the proposed parameter-matching API.
      
      For `/products/[slug]` with only `allowed` generated during the build,
      learning `/products/allowed` must not imply that `/products/rejected`
      exists. This remains true when the page never reads `slug`. The
      transport-tree builder now attaches `PrefetchHint.IsClosedParam` to the
      affected dynamic node, rather than putting a route-level bit on the
      response root or copying it to every prefetch node. Live rendering,
      error trees, and prefetch-hint collection preserve that placement.
      
      Legacy `dynamicParams = false` closes the entire parameter tuple. For
      `/catalog/[lang]/products/[slug]/details`, both `[lang]` and `[slug]`
      receive the hint; the static segments do not. Shared ancestors refresh
      their hints even when their UI is reused: navigating between open and
      closed pages under the same `[slug]` must add or clear the restriction.
      
      Client behavior remains conservative: optimistic route prediction
      declines a tree containing any closed parameter and asks the server to
      resolve the destination. Existing apps combining `dynamicParams = false`
      with `experimental.optimisticRouting` therefore lose prediction for
      those routes. Sending allowed parameter values to the client and
      predicting valid destinations from that list is future work, not part of
      this change.
      
      This PR is an independent prerequisite extracted from #97393. It does
      not enable Cache Components, introduce parameter-matching configuration,
      or change which parameter values are allowed. The later API layer
      supplies exact closed-parameter names for routes with a closed prefix
      and an open suffix.
      
      ## Verification
      
      - The legacy routing/navigation fixture runs with Cache Components
      disabled. Revised node-placement assertions fail against the old
      response-root representation. The shared-sibling navigation test also
      reproduced stale hints before the skipped-ancestor refresh was added.
      - Initial documents and live client navigations with `prefetch={false}`
      place the hint on `[slug]`; open routes carry no closure hint. A nested
      legacy route marks both dynamic parameters, and open/closed sibling
      navigation updates a reused ancestor.
      - Five tests pass in development with both Turbopack and Webpack. The
      three existing prefetch-dependent scenarios retain their production-only
      gates; all eight tests pass in production with both bundlers.
      - The seven production scenarios present before adding shared-sibling
      navigation also passed with optimistic routing disabled in the Webpack
      axis-A configuration.
      - Existing config and transport-tree helper unit suites pass (22 tests
      and one snapshot), and repository TypeScript checks pass.
      - The eight-test legacy fixture also passes on the integrated API head.
      
      An exploratory dev run of the combined routing-404 scenario encountered
      an intermittent Turbopack `NoFallbackError`/500; a subsequent run
      returned the expected 404. This PR does not fix that observation or
      claim dev coverage for that production-only scenario.
      
      <!-- NEXT_JS_LLM -->
      59ad3de6