Commit f127a074 authored by Jude Gao's avatar Jude Gao

[agents-md] Dedup `upgrade`'s cwd check and trim verbose comments

`runUpgrade` now calls `requireNextProjectDir(cwd)` once at the top
and threads the resolved dir through `getInstalledNextVersion` and
the post-scaffold hook, replacing the duplicated
`require.resolve('next/package.json', { paths: [cwd] })` that was
happening in both places. `getInstalledNextVersion` collapses to
a two-line version read now that validation is a separate step.

Verbose JSDoc compressed across `lib/agents-md.ts`, `bin/upgrade-agents-md.ts`,
and `app-info-log.ts`. The docs/01-app/02-guides/ai-agents.mdx
`Existing projects` section collapses the monorepo note, the
post-upgrade note, and the upsert bullet list into a single
two-sentence lead — readers can grok the command without wading
through the fork logic.
parent 955bab7b
......@@ -59,21 +59,13 @@ npx create-next-app@canary --no-agents-md
### Existing projects
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:
On Next.js `v16.2.0-canary.37` or later, run the codemod from your Next.js app directory (in a monorepo, the sub-package that declares `next`):
```bash
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. The command 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`.
- Otherwise, if `CLAUDE.md` exists, the block is upserted into `CLAUDE.md`.
- Otherwise, a new `AGENTS.md` is created with the block and a new `CLAUDE.md` is created that imports it via the `@` syntax.
`codemod upgrade` also runs this scaffold as a post-upgrade step. The codemod upserts into an existing `AGENTS.md` or `CLAUDE.md`, or creates both if neither exists:
```md filename="AGENTS.md"
<!-- BEGIN:nextjs-agent-rules -->
......@@ -89,12 +81,12 @@ This version has breaking changes — APIs, conventions, and file structure may
@AGENTS.md
```
`CLAUDE.md` uses the `@` import syntax to include `AGENTS.md`, so [Claude Code](https://docs.anthropic.com/en/docs/claude-code) users get the same instructions without duplicating content. Upserts preserve existing content outside the marker block, and running the codemod again is a no-op when the block is already up to date. You can also add the block by hand with the exact content above.
You can also add the block by hand with the exact content above.
<details>
<summary>For earlier versions</summary>
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:
On version 16.1 and earlier, use the legacy `agents-md` command, which downloads the docs to `.next-docs/` in the project root:
```bash
npx @next/codemod@canary agents-md
......
/**
* CLI handler for `npx @next/codemod upgrade agents-md` — the
* `agents-md` subcommand nested under `upgrade`.
*
* 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.
* CLI handler for `npx @next/codemod upgrade agents-md`. Upserts the
* create-next-app agent-rules block into `AGENTS.md` / `CLAUDE.md`
* using the docs bundled at `node_modules/next/dist/docs/`. Anchors
* strictly on `cwd` — same contract as `codemod upgrade`.
*/
import pc from 'picocolors'
......
......@@ -119,10 +119,22 @@ export async function runUpgrade(
options: { verbose: boolean }
): Promise<void> {
const { verbose } = options
const appPackageJsonPath = path.resolve(cwd, 'package.json')
// Validate `cwd` once at the top: must have `package.json` and a
// resolvable `next` install. Shared with `upgrade agents-md` via
// `requireNextProjectDir`, which throws a plain `Error` that we
// rewrap as `BadInput` for clean CLI formatting.
let projectDir: string
try {
projectDir = requireNextProjectDir(cwd)
} catch (err) {
throw new BadInput((err as Error).message)
}
const appPackageJsonPath = path.join(projectDir, 'package.json')
let appPackageJson = JSON.parse(fs.readFileSync(appPackageJsonPath, 'utf8'))
const installedNextVersion = getInstalledNextVersion()
const installedNextVersion = getInstalledNextVersion(projectDir)
// Resolve semantic keywords to npm version queries
const resolvedRevision = resolveSemanticRevision(
......@@ -427,27 +439,9 @@ export async function runUpgrade(
warnDependenciesOutOfRange(appPackageJson, versionMapping)
// 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.
//
// `requireNextProjectDir` throws a plain `Error` (it lives in the
// `lib/` layer and can't import `BadInput`), so we wrap it to get
// the clean "print just the message" path in `next-codemod.ts`.
// Should never actually fire here because `getInstalledNextVersion`
// validated the same condition earlier — defense in depth so a
// future reorder doesn't leak a stack trace to users.
let projectDir: string
try {
projectDir = requireNextProjectDir(cwd)
} catch (err) {
throw new BadInput((err as Error).message)
}
// Scaffold `AGENTS.md` + `CLAUDE.md` when the upgraded Next.js
// ships bundled docs. Same fast path `upgrade agents-md` runs, so
// upgrading picks up the agent rules as a side effect.
if (hasBundledDocs(projectDir)) {
const result = writeBundledDocsAgentFiles(projectDir)
const touched: string[] = []
......@@ -467,21 +461,12 @@ export async function runUpgrade(
endMessage(targetNextVersion)
}
function getInstalledNextVersion(): string {
try {
return require(
require.resolve('next/package.json', {
paths: [cwd],
})
).version
} catch (error) {
throw new BadInput(
`Failed to get the installed Next.js version at "${cwd}".\nIf you're using a monorepo, please run this command from the Next.js app directory.`,
{
cause: error,
}
)
}
function getInstalledNextVersion(projectDir: string): string {
// `projectDir` has already been validated by `requireNextProjectDir`,
// so the resolve is guaranteed to succeed — this is just the version
// read.
return require(require.resolve('next/package.json', { paths: [projectDir] }))
.version
}
function getInstalledReactVersion(): string {
......
This diff is collapsed.
......@@ -134,14 +134,8 @@ function tryReadFile(filePath: string): string | null {
/**
* 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 upgrade agents-md`, which writes the
* managed block to the same project directory — keeping the check and
* the codemod anchored on the same location.
* (the package.json level) — the same location `upgrade agents-md`
* writes to, so check and codemod stay anchored together.
*/
function hasAgentRulesInstalled(dir: string): boolean {
const agentsMdContents = tryReadFile(path.join(dir, 'AGENTS.md'))
......@@ -154,52 +148,24 @@ function hasAgentRulesInstalled(dir: string): boolean {
}
/**
* The env var an intentional user can set to bypass the agent-rules
* hard-exit. Named with `DISABLE` rather than `SKIP` so the word
* itself carries some behavioral friction — setting this is a
* deliberate acknowledgement that Next.js is running in a
* knowingly-degraded state for agent-driven workflows.
*
* Not documented in any `--help` output and not mentioned as a CLI
* flag. The only place it's surfaced is inside the fatal error
* message itself, framed as an explicit "strongly discouraged" escape
* hatch for cases where the user genuinely can't run the codemod
* (e.g. locked-down CI, air-gapped environments).
* Escape hatch for the agent-rules hard-exit. Disclosed only inside
* the fatal message itself (not in `--help`) and framed as "strongly
* discouraged" so agents don't grab it off surface area.
*/
const BYPASS_ENV_VAR = 'NEXT_DISABLE_AGENT_RULE_CHECK'
const AGENTS_MD_INSTALL_COMMAND = 'npx @next/codemod@canary upgrade agents-md'
/**
* Check the Next.js agent-rules gate for `next dev`.
*
* Returns `null` when the caller should proceed normally: no AI
* coding agent is driving, OR the managed agent-rules block is
* already installed in `AGENTS.md`/`CLAUDE.md`, OR the user has
* explicitly set the `NEXT_DISABLE_AGENT_RULE_CHECK` env-var escape
* hatch.
*
* Returns a fatal error message string when an agent is driving and
* none of the above apply. The caller should print the message and
* `process.exit(1)` — warnings attached to a successful process are
* empirically ignored by agents, so the only reliable way to make
* them act on this is to prevent the `Ready` / success signal from
* firing at all.
*
* Only `next dev` runs this gate. `next build` deliberately does
* nothing: failing a build mid-pipeline feels wrong even when an
* agent is driving, and the dev-server gate already catches
* agent-driven projects at the first iteration.
* Returns a fatal message string when `next dev` should exit instead
* of starting — AI coding agent detected, managed block missing, and
* no bypass env var set. Returns `null` when the caller should
* proceed. The caller prints and `process.exit(1)`; anything short
* of a non-zero exit is empirically ignored by agents.
*
* The message is deliberately long and rationale-heavy. Agents
* processing tool output weigh concrete negative consequences ("will
* suggest wrong APIs that fail at runtime") far more than abstract
* ones ("improves accuracy"), so spelling out exactly what goes wrong
* without the managed block is the single most effective way to
* discourage them from grabbing the escape hatch. The bypass env var
* is disclosed, but framed as a last resort with a concrete negative
* consequence attached ("agents will continue producing broken code
* that takes more time to fix than the codemod takes to run").
* Message length is deliberate: concrete negative consequences and a
* last-resort bypass with stick framing are what actually move agent
* behavior, validated against live Claude Code.
*/
export function checkAgentRulesForDev(dir: string): string | null {
if (detectAgent() === null) return null
......
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