Unverified Commit 8a63e04f authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

fix(codemod): make agents-md docs root relative to the output file (#100016)

### What?

`npx @next/codemod agents-md` now writes every path in the generated
docs index relative to the directory of the `--output` file, not the
current working directory. Part 1 of 2 for #99771; the stacked follow-up
handles running from a monorepo root.

- **`root`**:
- **Bundled docs:** links the install that was actually indexed, through
its stable `node_modules/next` symlink path, relative to the output
file. Example: running from `apps/web` with `--output ../../AGENTS.md`
now writes `root: ./apps/web/node_modules/next/dist/docs` instead of a
broken `./node_modules/next/dist/docs`.
- **Downloaded docs:** `.next-docs` is linked the same way
(`./apps/web/.next-docs`).
- **Regeneration hint**: now `run this command from this file's
directory: … --output AGENTS.md`. It used to embed the raw cwd-relative
`--output ../../AGENTS.md`.
- **Absolute `--output`**: now resolved with `path.resolve`. Previously
`path.join` appended it to the cwd.
- **Prefixes**: links always start with `./` or `../`. The old
`startsWith('.')` check would have emitted `.next-docs`.

### Why?

Agents resolve `root` from the `AGENTS.md` file's location, the same
convention as the `agentRules` block ("resolved from this file's
directory"). Monorepos that keep a single root `AGENTS.md` had to run
the codemod from the app, and that produced a `root` that doesn't exist
from the repo root.

Simply switching the base to the output directory isn't enough. The
conventional-path shortcut would then check the output directory's
`node_modules`. If the root hoists a different `next` (e.g. 16.3.0 while
the app has 16.4.0), the link would point at a different version's docs
than the one indexed. That case is covered by a test.

### How?

- `getBundledDocsInfo` now returns `resolvedFrom`, the directory `next`
was resolved from.
- `getBundledDocsLinkPath(fromDir, docsPath, resolvedFrom)` prefers
`<resolvedFrom>/node_modules/next/dist/docs`, but only if it is the same
install. Otherwise it falls back to the realpath.
- A new `getRelativeLinkPath` helper builds the `./`/`../`-prefixed,
forward-slash link for both branches.
- Paths are compared and related in canonical form
(`fs.realpathSync.native`). On Windows, `process.cwd()` can keep an 8.3
short name (`C:\Users\RUNNER~1\…`) while module resolution returns the
long name; mixing the two produced a broken root. The parent directory
is canonicalized before `node_modules/next/dist/docs` is appended, so
the stable symlink path is kept.

### Verification

- New offline e2e tests in `lib/__tests__/agents-md-e2e.test.js`, using
a pnpm-style isolated fixture and a stubbed `pullDocs`:
  - output outside the cwd (bundled and downloaded);
  - mixed hoisted versions;
  - the hint;
  - absolute `--output`;
  - `./` and `../` boundaries;
- a cwd spelled differently from the realpath: a symlinked alias, and a
mock in which only the native realpath canonicalizes, as with Windows
8.3 names. Both failed before the canonical-path change.
- The existing agents-md e2e suite passes, including its network
download tests: 22/22.
- Manually reproduced both of the issue's scenarios against a simulated
pnpm workspace:
  - Running from the app now writes a `root` that resolves.
- Running from the root still downloads; the stacked follow-up fixes
that.

Part of #99771

<!-- NEXT_JS_LLM -->


<!-- fleet c69f306a-7676-4b84-8d3a-927ca1ab5f43 -->

---------
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>
parent f4d1b064
...@@ -12,6 +12,7 @@ import { ...@@ -12,6 +12,7 @@ import {
getNextjsVersion, getNextjsVersion,
getBundledDocsInfo, getBundledDocsInfo,
getBundledDocsLinkPath, getBundledDocsLinkPath,
getRelativeLinkPath,
pullDocs, pullDocs,
collectDocFiles, collectDocFiles,
buildDocTree, buildDocTree,
...@@ -75,7 +76,10 @@ export async function runAgentsMd(options: AgentsMdOptions): Promise<void> { ...@@ -75,7 +76,10 @@ export async function runAgentsMd(options: AgentsMdOptions): Promise<void> {
targetFile = promptedOptions.targetFile targetFile = promptedOptions.targetFile
} }
const agentsMdPath = path.join(cwd, targetFile) const agentsMdPath = path.resolve(cwd, targetFile)
// Agents resolve paths in the index from the directory of the output file,
// so every link written into it is relative to that directory, not the cwd.
const outputDir = path.dirname(agentsMdPath)
// Next.js >= 16.2.0 ships its docs inside the published package. When the // Next.js >= 16.2.0 ships its docs inside the published package. When the
// installed version matches the requested one, index the bundled docs // installed version matches the requested one, index the bundled docs
...@@ -88,8 +92,12 @@ export async function runAgentsMd(options: AgentsMdOptions): Promise<void> { ...@@ -88,8 +92,12 @@ export async function runAgentsMd(options: AgentsMdOptions): Promise<void> {
? bundledDocs.docsPath ? bundledDocs.docsPath
: path.join(cwd, DOCS_DIR_NAME) : path.join(cwd, DOCS_DIR_NAME)
const docsLinkPath = useBundledDocs const docsLinkPath = useBundledDocs
? getBundledDocsLinkPath(cwd, bundledDocs.docsPath) ? getBundledDocsLinkPath(
: `./${DOCS_DIR_NAME}` outputDir,
bundledDocs.docsPath,
bundledDocs.resolvedFrom
)
: getRelativeLinkPath(outputDir, docsPath)
let sizeBefore = 0 let sizeBefore = 0
let isNewFile = true let isNewFile = true
...@@ -127,7 +135,8 @@ export async function runAgentsMd(options: AgentsMdOptions): Promise<void> { ...@@ -127,7 +135,8 @@ export async function runAgentsMd(options: AgentsMdOptions): Promise<void> {
const indexContent = generateAgentsMdIndex({ const indexContent = generateAgentsMdIndex({
docsPath: docsLinkPath, docsPath: docsLinkPath,
sections, sections,
outputFile: targetFile, // The regeneration hint is run from the output file's directory.
outputFile: path.relative(outputDir, agentsMdPath).replace(/\\/g, '/'),
}) })
const newContent = injectIntoAgentsMd(existingContent, indexContent) const newContent = injectIntoAgentsMd(existingContent, indexContent)
......
...@@ -88,6 +88,8 @@ export function getNextjsVersion(cwd: string): NextjsVersionResult { ...@@ -88,6 +88,8 @@ export function getNextjsVersion(cwd: string): NextjsVersionResult {
interface BundledDocsInfo { interface BundledDocsInfo {
docsPath: string docsPath: string
version: string version: string
/** Directory `next` was resolved from. */
resolvedFrom: string
} }
/** /**
...@@ -104,21 +106,74 @@ export function getBundledDocsInfo(cwd: string): BundledDocsInfo | null { ...@@ -104,21 +106,74 @@ export function getBundledDocsInfo(cwd: string): BundledDocsInfo | null {
if (!pkg.version || collectDocFiles(docsPath).length === 0) { if (!pkg.version || collectDocFiles(docsPath).length === 0) {
return null return null
} }
return { docsPath, version: pkg.version } return { docsPath, version: pkg.version, resolvedFrom: cwd }
} catch { } catch {
return null return null
} }
} }
export function getBundledDocsLinkPath(cwd: string, docsPath: string): string { /**
// Prefer the conventional path when it resolves from the project * Returns `target` as a `./`- or `../`-prefixed, forward-slash path relative
// (covers hoisted installs; pnpm exposes next via a node_modules symlink). * to `fromDir`. Agents resolve paths in the index from the directory of the
const conventional = path.join(cwd, 'node_modules', 'next', 'dist', 'docs') * output file, so `fromDir` must be that directory, not the cwd.
if (fs.existsSync(conventional)) { */
return './node_modules/next/dist/docs' export function getRelativeLinkPath(fromDir: string, target: string): string {
const relative = path.relative(fromDir, target).replace(/\\/g, '/')
if (relative === '') return './'
if (relative === '..') return '../'
// A dot-directory such as `.next-docs` still needs the `./` prefix.
return relative.startsWith('../') ? relative : `./${relative}`
}
/**
* Canonical spelling of `p`: symlinks resolved and, on Windows, 8.3 short
* names (e.g. `C:\Users\RUNNER~1`) expanded. `process.cwd()` can keep a
* non-canonical spelling while module resolution returns the canonical one,
* so compare and relate paths only in this form. Falls back to the resolved
* path when `p` cannot be canonicalized (e.g. it does not exist).
*/
function canonicalPath(p: string): string {
try {
return fs.realpathSync.native(p)
} catch {
return path.resolve(p)
}
}
/**
* Link to the bundled docs of the install resolved from `resolvedFrom`,
* relative to `fromDir` (the directory of the output file).
*/
export function getBundledDocsLinkPath(
fromDir: string,
docsPath: string,
resolvedFrom: string
): string {
// Prefer the conventional path of the resolved install over its realpath:
// pnpm's `.pnpm/next@x.y.z/...` realpath changes on every upgrade, while
// the `node_modules/next` symlink stays stable. Check it under the
// directory `next` was resolved from, not under `fromDir`, which may see a
// different `next` install.
//
// Paths are related in canonical form (see canonicalPath) so a cwd or
// --output spelled differently than the resolved install still produces a
// clean link. Only the parent of the `node_modules/next` symlink is
// canonicalized, never the symlink itself, so the stable path is kept.
const outputDir = canonicalPath(fromDir)
const conventional = path.join(
canonicalPath(resolvedFrom),
'node_modules',
'next',
'dist',
'docs'
)
if (
fs.existsSync(conventional) &&
canonicalPath(conventional) === canonicalPath(docsPath)
) {
return getRelativeLinkPath(outputDir, conventional)
} }
const relative = path.relative(cwd, docsPath).replace(/\\/g, '/') return getRelativeLinkPath(outputDir, canonicalPath(docsPath))
return relative.startsWith('.') ? relative : `./${relative}`
} }
function versionToGitHubTag(version: string): string { function versionToGitHubTag(version: string): string {
...@@ -337,7 +392,7 @@ export function generateAgentsMdIndex(data: AgentsMdIndexData): string { ...@@ -337,7 +392,7 @@ export function generateAgentsMdIndex(data: AgentsMdIndexData): string {
) )
const targetFile = outputFile || 'AGENTS.md' const targetFile = outputFile || 'AGENTS.md'
parts.push( parts.push(
`If docs missing, run this command first: npx @next/codemod agents-md --output ${targetFile}` `If docs missing, run this command from this file's directory: npx @next/codemod agents-md --output ${targetFile}`
) )
const allFiles = collectAllFilesFromSections(sections) const allFiles = collectAllFilesFromSections(sections)
......
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