Commit 8f412935 authored by Jude Gao's avatar Jude Gao

[agents-md] Split bundled-docs fast path into `upgrade-agents-md` command

`codemod agents-md` now stays on its original git-clone behavior for
older Next.js versions. The bundled-docs fast path moves to a new
`codemod upgrade-agents-md` command that anchors strictly on `cwd` —
same contract as `codemod upgrade` — so in a monorepo you run it from
the app package (`apps/web/`), not the monorepo root. The
post-upgrade hook in `codemod upgrade` also uses the strict-cwd
helper. Running `upgrade-agents-md` outside a Next.js app directory
or on a pre-16.2 install aborts with an actionable error.

The runtime dev gate in `app-info-log.ts` drops its walk-up
package.json search and now checks `dir` directly (which `next dev`
already resolves via `getProjectDir`). The fatal dev error and build
warning both point at the new `upgrade-agents-md` command. Legacy
`<!-- NEXT-AGENTS-MD-* -->` marker cleanup is preserved so projects
that ran the pre-bundled-docs codemod still get their stale block
stripped when the new block is upserted.
parent 18038528
......@@ -59,12 +59,16 @@ npx create-next-app@canary --no-agents-md
### Existing projects
On Next.js `v16.2.0-canary.37` or later, run the codemod to install the agent rules automatically:
On Next.js `v16.2.0-canary.37` or later, run the codemod from your Next.js app directory to install the agent rules automatically:
```bash
npx @next/codemod@canary agents-md
npx @next/codemod@canary upgrade-agents-md
```
In a monorepo, run the command from inside the app package (e.g. `apps/web/`), not the monorepo root. `AGENTS.md` belongs next to the `package.json` that declares `next`, because that's where AI coding agents look for it. `upgrade-agents-md` aborts with an actionable error if it can't resolve `next` from the current directory.
`codemod upgrade` also runs this scaffold automatically as a post-upgrade step, so upgrading Next.js in an existing project picks up the agent rules for free.
The codemod writes the following managed block into whichever agent file your project already uses:
- If `AGENTS.md` exists, the block is upserted into `AGENTS.md`.
......@@ -90,7 +94,7 @@ This version has breaking changes — APIs, conventions, and file structure may
<details>
<summary>For earlier versions</summary>
On version 16.1 and earlier, the codemod downloads the docs to `.next-docs/` in the project root instead of using the bundled `node_modules/next/dist/docs/`, and the generated agent files will point at that directory:
On version 16.1 and earlier, bundled docs aren't shipped with the `next` package. Use the legacy `agents-md` command instead, which downloads the docs to `.next-docs/` in the project root:
```bash
npx @next/codemod@canary agents-md
......
......@@ -10,16 +10,12 @@ import pc from 'picocolors'
import { BadInput } from './shared'
import {
getNextjsVersion,
findNextProjectDir,
hasBundledDocs,
writeBundledDocsAgentFiles,
pullDocs,
collectDocFiles,
buildDocTree,
generateClaudeMdIndex,
injectIntoClaudeMd,
ensureGitignoreEntry,
type BundledDocsFileAction,
} from '../lib/agents-md'
import { onCancel } from '../lib/utils'
......@@ -41,39 +37,6 @@ function formatSize(bytes: number): string {
export async function runAgentsMd(options: AgentsMdOptions): Promise<void> {
const cwd = process.cwd()
// Locate the Next.js project dir — the nearest `package.json`
// walking up from `cwd` that declares `next` as a dependency, or a
// workspace sub-package for monorepo-root invocations. This is the
// canonical anchor for AGENTS.md / CLAUDE.md. Skipped when
// `--version` is explicitly passed, since that signals the user
// wants to pull docs for a specific (potentially not-yet-installed)
// version via the legacy git-clone flow.
if (!options.version) {
const projectDir = findNextProjectDir(cwd)
if (projectDir === null) {
// No Next.js project found anywhere above `cwd` and no
// workspace sub-package declares `next`. Running the
// agent-rules codemod here doesn't mean anything — there's no
// Next.js install to point agents at. Abort with a clear
// message instead of silently falling through to the
// interactive legacy flow (which would prompt for a version
// and git-clone docs for a project that doesn't exist).
throw new BadInput(
`No Next.js project found at ${pc.cyan(cwd)} or any ancestor directory. ` +
`Run this codemod from a directory whose \`package.json\` declares \`next\` as a dependency, ` +
`or cd into the Next.js app's sub-package in a monorepo.`
)
}
if (hasBundledDocs(projectDir)) {
runBundledDocsFastPath(projectDir)
return
}
// `projectDir` is a valid Next.js project but on an older
// version without bundled docs — fall through to the legacy
// git-clone flow below, which will auto-detect the installed
// version via `getNextjsVersion(cwd)` downstream.
}
// Mode logic:
// 1. No flags → interactive mode (prompts for version + target file)
// 2. --version provided → --output is REQUIRED (error if missing)
......@@ -168,41 +131,6 @@ export async function runAgentsMd(options: AgentsMdOptions): Promise<void> {
console.log('')
}
function runBundledDocsFastPath(projectDir: string): void {
const detectedVersion = getNextjsVersion(projectDir).version
const versionLabel = detectedVersion
? pc.cyan(detectedVersion)
: pc.cyan('next')
console.log(
`\nDetected bundled docs for Next.js ${versionLabel} in ${pc.cyan(projectDir)}.`
)
console.log(
pc.gray(
' Skipping git clone — writing the agent rules into the existing AGENTS.md or CLAUDE.md.\n'
)
)
const result = writeBundledDocsAgentFiles(projectDir)
const describe = (file: string, action: BundledDocsFileAction) => {
// Don't list files we didn't touch at all.
if (action === 'skipped') return
const symbol = action === 'unchanged' ? pc.gray('•') : pc.green('✓')
const verb =
action === 'created'
? 'Created'
: action === 'updated'
? 'Updated'
: 'Up to date:'
console.log(`${symbol} ${verb} ${pc.bold(file)}`)
}
describe('AGENTS.md', result.agentsMd)
describe('CLAUDE.md', result.claudeMd)
console.log('')
}
async function promptForOptions(
cwd: string
): Promise<{ nextVersion: string; targetFile: string }> {
......
......@@ -12,6 +12,7 @@
import { Command } from 'commander'
import { runUpgrade } from './upgrade'
import { runAgentsMd } from './agents-md'
import { runUpgradeAgentsMd } from './upgrade-agents-md'
import { runTransform } from './transform'
import { BadInput } from './shared'
......@@ -101,4 +102,22 @@ program
}
})
program
.command('upgrade-agents-md')
.description(
'Scaffold AGENTS.md / CLAUDE.md from the bundled Next.js docs (Next.js 16.2+). Must be run from the Next.js app directory.'
)
.action(async () => {
try {
await runUpgradeAgentsMd()
} catch (error) {
if (error instanceof BadInput) {
console.error(error.message)
} else {
console.error(error)
}
process.exit(1)
}
})
program.parse(process.argv)
/**
* CLI handler for `npx @next/codemod upgrade-agents-md`.
*
* This is the "fast path" variant of the `agents-md` codemod. It
* upserts the canonical create-next-app-style agent-rules block into
* the project's `AGENTS.md` / `CLAUDE.md` using the version-matched
* docs bundled at `node_modules/next/dist/docs/`. No git clone, no
* `.next-docs/` scratch directory.
*
* Anchors strictly on `cwd`: the caller must already be inside a
* Next.js app directory (the `package.json` that declares `next`).
* This mirrors `upgrade.ts`'s own cwd contract — running either
* command from a monorepo root is an error, not a silent fallback.
*/
import pc from 'picocolors'
import { BadInput } from './shared'
import {
getNextjsVersion,
requireNextProjectDir,
hasBundledDocs,
writeBundledDocsAgentFiles,
type BundledDocsFileAction,
} from '../lib/agents-md'
export async function runUpgradeAgentsMd(): Promise<void> {
const cwd = process.cwd()
let projectDir: string
try {
projectDir = requireNextProjectDir(cwd)
} catch (err) {
throw new BadInput((err as Error).message)
}
if (!hasBundledDocs(projectDir)) {
throw new BadInput(
`The Next.js install at ${pc.cyan(projectDir)} does not ship bundled docs. ` +
`Upgrade to Next.js 16.2 or newer, or run \`npx @next/codemod agents-md\` ` +
`to pull docs for an older version via git.`
)
}
const detectedVersion = getNextjsVersion(projectDir).version
const versionLabel = detectedVersion
? pc.cyan(detectedVersion)
: pc.cyan('next')
console.log(
`\nScaffolding agent rules for Next.js ${versionLabel} in ${pc.cyan(projectDir)}.`
)
const result = writeBundledDocsAgentFiles(projectDir)
const describe = (file: string, action: BundledDocsFileAction) => {
// Don't list files we didn't touch at all.
if (action === 'skipped') return
const symbol = action === 'unchanged' ? pc.gray('•') : pc.green('✓')
const verb =
action === 'created'
? 'Created'
: action === 'updated'
? 'Updated'
: 'Up to date:'
console.log(`${symbol} ${verb} ${pc.bold(file)}`)
}
describe('AGENTS.md', result.agentsMd)
describe('CLAUDE.md', result.claudeMd)
console.log('')
}
......@@ -18,7 +18,7 @@ import {
import { runTransform } from './transform'
import { onCancel, TRANSFORMER_INQUIRER_CHOICES } from '../lib/utils'
import {
findNextProjectDir,
requireNextProjectDir,
hasBundledDocs,
writeBundledDocsAgentFiles,
} from '../lib/agents-md'
......@@ -427,15 +427,16 @@ export async function runUpgrade(
warnDependenciesOutOfRange(appPackageJson, versionMapping)
// Scaffold `AGENTS.md` + `CLAUDE.md` at the Next.js project dir
// (the package.json that declares `next`, never the monorepo root)
// if the upgraded Next.js ships version-matched bundled docs.
// Mirrors what `create-next-app` does for new projects so existing
// projects pick up the agent rules as a natural side effect of
// upgrading. No-op on older versions or hoisted layouts where
// `node_modules/next/dist/docs/` isn't at the project dir.
const projectDir = findNextProjectDir(cwd)
if (projectDir !== null && hasBundledDocs(projectDir)) {
// Scaffold `AGENTS.md` + `CLAUDE.md` at the Next.js project dir if
// the upgraded Next.js ships version-matched bundled docs. `upgrade`
// already anchors on `cwd` (see `getInstalledNextVersion` above), so
// we reuse the same strict-cwd check here instead of walking up —
// the project dir is always `cwd`. Mirrors what `create-next-app`
// does for new projects so existing projects pick up the agent
// rules as a natural side effect of upgrading. No-op on older
// versions without bundled docs.
const projectDir = requireNextProjectDir(cwd)
if (hasBundledDocs(projectDir)) {
const result = writeBundledDocsAgentFiles(projectDir)
const touched: string[] = []
if (result.agentsMd === 'created' || result.agentsMd === 'updated') {
......
......@@ -44,82 +44,61 @@ export function getNextjsVersion(cwd: string): NextjsVersionResult {
}
/**
* Find the Next.js project directory — the canonical location for
* AGENTS.md / CLAUDE.md. This is the nearest ancestor directory with
* a `package.json` that declares `next` as a dependency.
* Assert that `cwd` is a valid Next.js project directory, matching
* the same strict check `@next/codemod upgrade` uses:
*
* In a monorepo, this resolves to the *sub-package* that actually
* uses Next.js (e.g. `apps/web/`), never the monorepo root that
* wraps it. That's because AI coding agents locate agent-rules files
* by reading from the package they're currently working in — so
* AGENTS.md must be co-located with the package.json that declares
* the dependency.
* 1. `cwd/package.json` must exist directly (no walk-up).
* 2. `next` must be resolvable from `cwd` via Node's module
* resolution (walks up through parent `node_modules/`).
*
* Resolution order:
* 1. Walk up from `cwd` looking for a `package.json` that has
* `next` in `dependencies` / `devDependencies` / `peerDependencies`.
* Covers the common case (user `cd`'d into the package).
* 2. If nothing found walking up, fall back to walking the detected
* workspace packages from `cwd`. Covers the less-common case
* where the user runs the codemod from the monorepo root without
* cd'ing into the sub-package first.
* Both `upgrade-agents-md` and the `upgrade` post-scaffold hook
* require running from the Next.js app directory for this reason —
* the AGENTS.md location must be co-located with `package.json`, and
* the bundled docs must be resolvable from that same location. Users
* running from a subdirectory or from the monorepo root will hit
* this and get a clear "cd into the app directory" message.
*
* Returns `null` if no Next.js project is found anywhere in the walk.
* Returns the resolved `cwd` on success, throws `BadInput` on
* failure.
*/
export function findNextProjectDir(cwd: string): string | null {
let currentDir = path.resolve(cwd)
while (true) {
if (packageJsonHasNext(currentDir)) return currentDir
const parent = path.dirname(currentDir)
if (parent === currentDir) break
currentDir = parent
}
// Fallback for monorepo-root invocations: walk the workspace
// packages and find the first one that declares next.
const workspace = detectWorkspace(cwd)
if (workspace.isMonorepo && workspace.packages.length > 0) {
for (const pkgPath of expandWorkspacePatterns(cwd, workspace.packages)) {
if (packageJsonHasNext(pkgPath)) return pkgPath
}
export function requireNextProjectDir(cwd: string): string {
const resolved = path.resolve(cwd)
const pkgJsonPath = path.join(resolved, 'package.json')
if (!fs.existsSync(pkgJsonPath)) {
throw new Error(
`No package.json found at ${resolved}. Run this command from the Next.js app directory.`
)
}
return null
}
function packageJsonHasNext(dir: string): boolean {
try {
const content = fs.readFileSync(path.join(dir, 'package.json'), 'utf-8')
const pkg = JSON.parse(content)
return Boolean(
pkg.dependencies?.next ||
pkg.devDependencies?.next ||
pkg.peerDependencies?.next
)
require.resolve('next/package.json', { paths: [resolved] })
} catch {
return false
throw new Error(
`Failed to resolve next from ${resolved}. If you're using a monorepo, run this command from the Next.js app directory.`
)
}
return resolved
}
/**
* Returns true when the Next.js install in `projectDir` ships
* version-matched bundled docs at `node_modules/next/dist/docs/`.
* Used to decide between the fast path (which only writes AGENTS.md)
* and the legacy git-clone flow.
* Returns true when the Next.js install resolvable from `projectDir`
* ships version-matched bundled docs at `node_modules/next/dist/docs/`.
*
* Checked directly at `projectDir/node_modules/next/...` — no Node-
* resolution walk-up — because that's the only layout where the
* `node_modules/next/dist/docs/` string we bake into the managed
* block is guaranteed to resolve correctly from the AGENTS.md
* location. pnpm's symlinked `node_modules/next` at the sub-package
* satisfies this. Hoisted `node_modules` layouts that only have
* `next` at the monorepo root won't match here and will cleanly
* fall back to the legacy git-clone flow.
* Uses `require.resolve` so it correctly finds next in both flat
* layouts and hoisted monorepos — then checks whether `dist/docs/`
* is present in that install. The managed block always writes the
* path as `node_modules/next/dist/docs/` because at a valid
* Next.js project dir that string will resolve correctly via Node's
* parent-directory `node_modules` walk-up.
*/
export function hasBundledDocs(projectDir: string): boolean {
return isDirectory(
path.join(projectDir, 'node_modules', 'next', 'dist', 'docs')
)
try {
const nextPkgPath = require.resolve('next/package.json', {
paths: [projectDir],
})
return isDirectory(path.join(path.dirname(nextPkgPath), 'dist', 'docs'))
} catch {
return false
}
}
/**
......
......@@ -92,7 +92,9 @@ describe('warnIfMissingAgentRules', () => {
const loggedMessage = warnSpy.mock.calls[0].join(' ')
// Install command + both filenames.
expect(loggedMessage).toContain('npx @next/codemod@canary agents-md')
expect(loggedMessage).toContain(
'npx @next/codemod@canary upgrade-agents-md'
)
expect(loggedMessage).toContain('AGENTS.md')
expect(loggedMessage).toContain('CLAUDE.md')
......@@ -120,33 +122,20 @@ describe('warnIfMissingAgentRules', () => {
expect(loggedMessage).not.toContain('strongly discouraged')
})
it('anchors the check at the nearest package.json walking up from a subdirectory', () => {
// Simulates running `next dev` from a nested source directory.
// The check anchors on the nearest `package.json` walking up,
// so AGENTS.md at the fixture root (which has package.json)
// is the file we check. AGENTS.md at the subdir itself would
// NOT be checked because it's "below" the package.json level.
process.env.CLAUDECODE = '1'
const subDir = path.join(tmpDir, 'src', 'app')
fs.mkdirSync(subDir, { recursive: true })
fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), `${AGENT_RULES_MARKER}\n`)
warnIfMissingAgentRules(subDir)
expect(warnSpy).not.toHaveBeenCalled()
})
it('anchors on the nearest package.json, not the monorepo root', () => {
// Monorepo layout: package.json at both the root and at
// `apps/web/`. The check from `apps/web/` must anchor on
// `apps/web/package.json` — the *nearest* one — and look for
// AGENTS.md there, NOT at the monorepo root. A marker at the
// monorepo root must not count.
it('only checks the Next.js project directory — a marker in an ancestor does not count', () => {
// The check is strictly anchored on `dir` (the Next.js project
// directory — `next dev` already resolves this via
// `getProjectDir` before calling into the gate). A marker
// dropped at a parent directory is irrelevant: AI agents read
// agent-rules files from the package they're working in, not
// from some ancestor. In a monorepo this means the marker must
// live in the app sub-package, never at the monorepo root.
process.env.CLAUDECODE = '1'
const appDir = path.join(tmpDir, 'apps', 'web')
fs.mkdirSync(appDir, { recursive: true })
fs.writeFileSync(path.join(appDir, 'package.json'), '{"name": "web"}')
// Put the marker at the monorepo root (wrong place for an
// `apps/web/` invocation).
// Marker at the monorepo root — wrong place for an
// `apps/web/` invocation.
fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), `${AGENT_RULES_MARKER}\n`)
warnIfMissingAgentRules(appDir)
......@@ -154,7 +143,7 @@ describe('warnIfMissingAgentRules', () => {
})
it('respects the marker when it is in the sub-package, not the monorepo root', () => {
// Same monorepo layout as above, but the marker is now in the
// Same monorepo layout, but the marker is now in the
// sub-package (where it belongs). The check must find it.
process.env.CLAUDECODE = '1'
const appDir = path.join(tmpDir, 'apps', 'web')
......@@ -237,7 +226,7 @@ describe('checkAgentRulesForDev (dev-side fatal gate)', () => {
expect(message).toContain('fail at runtime')
// Primary fix — the codemod command.
expect(message).toContain('npx @next/codemod@canary agents-md')
expect(message).toContain('npx @next/codemod@canary upgrade-agents-md')
// Escape hatch — disclosed, but env var not a CLI flag (agents
// grab CLI flags more readily than env vars), and explicitly
......
......@@ -132,53 +132,22 @@ function tryReadFile(filePath: string): string | null {
}
/**
* Walk up from `startDir` to the nearest directory containing
* `package.json` — that's the canonical "Next.js project root" and
* the single authoritative location for `AGENTS.md` / `CLAUDE.md`.
*
* In a monorepo this resolves to the *sub-package* (e.g.
* `apps/web/`), never the monorepo root, because the sub-package's
* `package.json` is strictly closer to wherever `next dev` was
* invoked. This matches how AI coding agents locate agent-rules
* files by default: they read from the project root, which for them
* is the package they're currently working in.
*
* Returns `null` when no `package.json` exists in any ancestor
* directory (a degenerate setup where running `next dev` would also
* fail for other reasons).
*/
function findProjectDir(startDir: string): string | null {
let currentDir = path.resolve(startDir)
while (true) {
if (fs.existsSync(path.join(currentDir, 'package.json'))) {
return currentDir
}
const parent = path.dirname(currentDir)
if (parent === currentDir) return null
currentDir = parent
}
}
/**
* Returns true when `AGENTS.md` or `CLAUDE.md` at the Next.js project
* root (nearest `package.json` walking up from `dir`) contains the
* managed agent-rules marker. Anchored to the project root rather
* than walking recursively because that's the only location agents
* natively look for the files.
* Returns true when `AGENTS.md` or `CLAUDE.md` at `dir` contains the
* managed agent-rules marker. `dir` is the Next.js project directory
* — the same level as `package.json` and the only place AI coding
* agents natively look for agent-rules files. In a monorepo that's
* the sub-package (e.g. `apps/web/`), never the monorepo root.
*
* The only supported way to install the marker is via
* `npx @next/codemod@canary agents-md`, which writes the managed
* block to the same project-root directory, keeping the check and
* the codemod perfectly consistent.
* `npx @next/codemod@canary upgrade-agents-md`, which writes the
* managed block to the same project directory — keeping the check and
* the codemod anchored on the same location.
*/
function hasAgentRulesInstalled(dir: string): boolean {
const projectDir = findProjectDir(dir)
if (projectDir === null) return false
const agentsMdContents = tryReadFile(path.join(projectDir, 'AGENTS.md'))
const agentsMdContents = tryReadFile(path.join(dir, 'AGENTS.md'))
if (agentsMdContents?.includes(AGENT_RULES_MARKER)) return true
const claudeMdContents = tryReadFile(path.join(projectDir, 'CLAUDE.md'))
const claudeMdContents = tryReadFile(path.join(dir, 'CLAUDE.md'))
if (claudeMdContents?.includes(AGENT_RULES_MARKER)) return true
return false
......@@ -199,7 +168,7 @@ function hasAgentRulesInstalled(dir: string): boolean {
*/
const BYPASS_ENV_VAR = 'NEXT_DISABLE_AGENT_RULE_CHECK'
const AGENTS_MD_INSTALL_COMMAND = 'npx @next/codemod@canary agents-md'
const AGENTS_MD_INSTALL_COMMAND = 'npx @next/codemod@canary upgrade-agents-md'
/**
* Print a yellow `⚠` warning at the end of `next build` when an AI
......
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