Commit 455210e6 authored by Jude Gao's avatar Jude Gao

[agents-md] Drop the fatal dev gate

The codemod path (`upgrade agents-md` and the post-upgrade scaffold)
is sufficient for existing projects. Follow-up PR will handle
`next dev` auto-generation separately.
parent 83e515c8
import fs from 'fs'
import os from 'os'
import path from 'path'
import { checkAgentRulesForDev } from './app-info-log'
const AGENT_RULES_MARKER = '<!-- BEGIN:nextjs-agent-rules -->'
// Clear every env var `detectAgent()` inspects so the base state is
// "no agent detected" regardless of what the host has set.
function clearAgentEnv() {
delete process.env.AI_AGENT
delete process.env.CURSOR_TRACE_ID
delete process.env.CURSOR_AGENT
delete process.env.GEMINI_CLI
delete process.env.CODEX_SANDBOX
delete process.env.CODEX_CI
delete process.env.CODEX_THREAD_ID
delete process.env.ANTIGRAVITY_AGENT
delete process.env.AUGMENT_AGENT
delete process.env.OPENCODE_CLIENT
delete process.env.CLAUDECODE
delete process.env.CLAUDE_CODE
delete process.env.CLAUDE_CODE_IS_COWORK
delete process.env.REPL_ID
delete process.env.COPILOT_MODEL
delete process.env.COPILOT_ALLOW_ALL
delete process.env.COPILOT_GITHUB_TOKEN
delete process.env.NEXT_DISABLE_AGENT_RULE_CHECK
}
describe('checkAgentRulesForDev (dev-side fatal gate)', () => {
let tmpDir: string
let originalEnv: NodeJS.ProcessEnv
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-rules-dev-'))
// `package.json` at the fixture root defines the Next.js project
// root the gate anchors on. `next dev` resolves this via
// `getProjectDir` before calling the gate.
fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name": "fixture"}')
originalEnv = { ...process.env }
clearAgentEnv()
})
afterEach(() => {
fs.rmSync(tmpDir, { recursive: true, force: true })
process.env = originalEnv
})
it('returns null when no agent is detected', () => {
expect(checkAgentRulesForDev(tmpDir)).toBeNull()
})
it('returns null when the managed block is installed in AGENTS.md', () => {
process.env.CLAUDECODE = '1'
fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), `${AGENT_RULES_MARKER}\n`)
expect(checkAgentRulesForDev(tmpDir)).toBeNull()
})
it('returns null when the managed block is installed in CLAUDE.md', () => {
process.env.CLAUDECODE = '1'
fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), `${AGENT_RULES_MARKER}\n`)
expect(checkAgentRulesForDev(tmpDir)).toBeNull()
})
it('returns null when NEXT_DISABLE_AGENT_RULE_CHECK is set', () => {
process.env.CLAUDECODE = '1'
process.env.NEXT_DISABLE_AGENT_RULE_CHECK = '1'
// Neither AGENTS.md nor CLAUDE.md exists — but the bypass env var
// is set, so the gate must respect it and stay silent.
expect(checkAgentRulesForDev(tmpDir)).toBeNull()
})
it('fires when AGENTS.md exists without the managed block', () => {
// File existence alone isn't enough — we care specifically about
// the Next.js directive, so a custom AGENTS.md without the marker
// still counts as "not installed".
process.env.CLAUDECODE = '1'
fs.writeFileSync(
path.join(tmpDir, 'AGENTS.md'),
'# Team rules\n\nUse tabs, not spaces.\n'
)
expect(checkAgentRulesForDev(tmpDir)).not.toBeNull()
})
it('only checks the Next.js project directory — a marker in an ancestor does not count', () => {
// The gate is strictly anchored on `dir` (the Next.js project
// directory). 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"}')
// Marker at the monorepo root — wrong place for an `apps/web/`
// invocation.
fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), `${AGENT_RULES_MARKER}\n`)
expect(checkAgentRulesForDev(appDir)).not.toBeNull()
})
it('respects the marker when it is in the sub-package, not the monorepo root', () => {
// Same monorepo layout, but the marker is now in the sub-package
// (where it belongs). The gate must find it.
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"}')
fs.writeFileSync(path.join(appDir, 'AGENTS.md'), `${AGENT_RULES_MARKER}\n`)
expect(checkAgentRulesForDev(appDir)).toBeNull()
})
it('fires with a `Fatal: Dev Server exited.`-prefixed rationale message', () => {
process.env.CLAUDECODE = '1'
const message = checkAgentRulesForDev(tmpDir)
expect(message).not.toBeNull()
// Leads with title-cased `Fatal: Dev Server exited.` — the
// caller will `process.exit(1)` right after, and this wording
// makes it clear in the log that the process terminated
// intentionally.
expect(message!.startsWith('Fatal: Dev Server exited.')).toBe(true)
// States the cause.
expect(message).toContain('AI coding agent')
expect(message).toContain('AGENTS.md')
expect(message).toContain('CLAUDE.md')
// Explains WHY the rules matter in concrete terms. These
// specific phrases are what agents weigh heavily when deciding
// whether to take the codemod path vs the escape path — losing
// any of them significantly weakens the discouragement.
expect(message).toContain('trained on older Next.js versions')
expect(message).toContain('breaking changes')
expect(message).toContain('deprecated APIs')
expect(message).toContain('outdated patterns')
expect(message).toContain('fail at runtime')
// Primary fix — the codemod command.
expect(message).toContain('npx @next/codemod@canary upgrade agents-md')
// Escape hatch — disclosed as an env var (not a CLI flag, since
// agents grab CLI flags more readily), and explicitly framed as
// "Strongly discouraged" with a concrete negative consequence
// attached.
expect(message).toContain('NEXT_DISABLE_AGENT_RULE_CHECK=1')
expect(message).toContain('Strongly discouraged')
expect(message).toContain('last-resort')
expect(message).toContain('far more time than the codemod takes to run')
})
})
import { loadEnvConfig } from '@next/env' import { loadEnvConfig } from '@next/env'
import fs from 'fs'
import * as inspector from 'inspector' import * as inspector from 'inspector'
import path from 'path'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import { bold, cyan, purple, strikethrough } from '../../lib/picocolors' import { bold, purple, strikethrough } from '../../lib/picocolors'
import type { ConfiguredExperimentalFeature } from '../config' import type { ConfiguredExperimentalFeature } from '../config'
import { experimentalSchema } from '../config-schema' import { experimentalSchema } from '../config-schema'
import { detectAgent } from '../../telemetry/detect-agent'
// Re-export the type for consumers // Re-export the type for consumers
export type { ConfiguredExperimentalFeature } export type { ConfiguredExperimentalFeature }
...@@ -116,83 +113,6 @@ export function logExperimentalInfo({ ...@@ -116,83 +113,6 @@ export function logExperimentalInfo({
Log.info('') Log.info('')
} }
/**
* Keep in sync with the marker written by `create-next-app` in
* packages/create-next-app/helpers/generate-agent-files.ts and with the
* codemod in packages/next-codemod/lib/agents-md.ts.
*/
const AGENT_RULES_MARKER = '<!-- BEGIN:nextjs-agent-rules -->'
function tryReadFile(filePath: string): string | null {
try {
return fs.readFileSync(filePath, 'utf-8')
} catch {
return 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 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'))
if (agentsMdContents?.includes(AGENT_RULES_MARKER)) return true
const claudeMdContents = tryReadFile(path.join(dir, 'CLAUDE.md'))
if (claudeMdContents?.includes(AGENT_RULES_MARKER)) return true
return false
}
/**
* 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'
/**
* 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.
*
* 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
if (hasAgentRulesInstalled(dir)) return null
if (process.env[BYPASS_ENV_VAR]) return null
const command = cyan(AGENTS_MD_INSTALL_COMMAND)
const bypass = cyan(`${BYPASS_ENV_VAR}=1`)
return (
`Fatal: Dev Server exited. We detected you're running Next.js ` +
`inside an AI coding agent but the managed agent-rules block is ` +
`not installed in AGENTS.md or CLAUDE.md.\n\n` +
`Why this matters: AI coding agents are trained on older Next.js ` +
`versions and don't know about breaking changes, deprecated APIs, ` +
`or new features in your installed version. Without the managed ` +
`block pointing them at the version-matched docs bundled with ` +
`your install, they will write code using outdated patterns that ` +
`fail at runtime or are silently incorrect.\n\n` +
`Run ${command} to install it.\n\n` +
`As a last-resort escape hatch, setting ${bypass} bypasses this ` +
`check. Strongly discouraged — agents will still produce broken ` +
`code, and fixing that will cost far more time than the codemod ` +
`takes to run.`
)
}
/** /**
* Gets environment info for logging. Fast operation that doesn't require config. * Gets environment info for logging. Fast operation that doesn't require config.
*/ */
......
...@@ -26,12 +26,7 @@ import { ...@@ -26,12 +26,7 @@ import {
CONFIG_FILES, CONFIG_FILES,
PHASE_DEVELOPMENT_SERVER, PHASE_DEVELOPMENT_SERVER,
} from '../../shared/lib/constants' } from '../../shared/lib/constants'
import { import { getEnvInfo, logExperimentalInfo, logStartInfo } from './app-info-log'
checkAgentRulesForDev,
getEnvInfo,
logExperimentalInfo,
logStartInfo,
} from './app-info-log'
import { validateTurboNextConfig } from '../../lib/turbopack-warning' import { validateTurboNextConfig } from '../../lib/turbopack-warning'
import { import {
type Span, type Span,
...@@ -374,23 +369,6 @@ export async function startServer( ...@@ -374,23 +369,6 @@ export async function startServer(
// Get env info first (fast, doesn't require config) // Get env info first (fast, doesn't require config)
const envInfo = isDev ? getEnvInfo(dir) : undefined const envInfo = isDev ? getEnvInfo(dir) : undefined
// Agent-rules gate: hard-fail dev startup when an AI coding
// agent is driving but the managed block isn't installed in
// AGENTS.md/CLAUDE.md. Fires BEFORE the banner and Ready line so
// we never print a success signal the agent could latch onto —
// a non-zero exit is the only signal empirically strong enough
// to override agents' "Ready + exit 0 = succeeded" pattern
// match. The error message itself explains the rationale at
// length and surfaces a last-resort `NEXT_DISABLE_AGENT_RULE_CHECK`
// env var for locked-down environments.
if (isDev) {
const agentRulesError = checkAgentRulesForDev(dir)
if (agentRulesError !== null) {
Log.error(agentRulesError)
process.exit(1)
}
}
// Log basic startup info immediately (before loading config) // Log basic startup info immediately (before loading config)
logStartInfo({ logStartInfo({
networkUrl, networkUrl,
......
// NOTE: This file duplicates the detection helper added in
// https://github.com/vercel/next.js/pull/91854 (branch: imm/agent-telemetry).
// When that PR lands, whichever branch merges second should collapse the
// duplicate — the contents are intentionally identical so the merge is a
// no-op. The env variable checks mirror the same functionality in the
// `vercel` CLI.
export type AgentName =
| 'cursor'
| 'cursor-cli'
| 'claude'
| 'cowork'
| 'devin'
| 'replit'
| 'gemini'
| 'codex'
| 'antigravity'
| 'augment-cli'
| 'opencode'
| 'github-copilot'
export function detectAgent(): AgentName | null {
if (process.env.AI_AGENT) {
const name = process.env.AI_AGENT.trim()
if (name) {
const normalized = name === 'github-copilot-cli' ? 'github-copilot' : name
return normalized as AgentName
}
}
if (process.env.CURSOR_TRACE_ID) {
return 'cursor'
}
if (process.env.CURSOR_AGENT) {
return 'cursor-cli'
}
if (process.env.GEMINI_CLI) {
return 'gemini'
}
if (
process.env.CODEX_SANDBOX ||
process.env.CODEX_CI ||
process.env.CODEX_THREAD_ID
) {
return 'codex'
}
if (process.env.ANTIGRAVITY_AGENT) {
return 'antigravity'
}
if (process.env.AUGMENT_AGENT) {
return 'augment-cli'
}
if (process.env.OPENCODE_CLIENT) {
return 'opencode'
}
if (process.env.CLAUDECODE || process.env.CLAUDE_CODE) {
if (process.env.CLAUDE_CODE_IS_COWORK) {
return 'cowork'
}
return 'claude'
}
if (process.env.REPL_ID) {
return 'replit'
}
if (
process.env.COPILOT_MODEL ||
process.env.COPILOT_ALLOW_ALL ||
process.env.COPILOT_GITHUB_TOKEN
) {
return 'github-copilot'
}
return null
}
...@@ -355,7 +355,6 @@ async function readNormalizedNFT(next, name) { ...@@ -355,7 +355,6 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/shared/*", "/node_modules/next/dist/shared/*",
"/node_modules/next/dist/telemetry/anonymous-meta.js", "/node_modules/next/dist/telemetry/anonymous-meta.js",
"/node_modules/next/dist/telemetry/detached-flush.js", "/node_modules/next/dist/telemetry/detached-flush.js",
"/node_modules/next/dist/telemetry/detect-agent.js",
"/node_modules/next/dist/telemetry/events/build.js", "/node_modules/next/dist/telemetry/events/build.js",
"/node_modules/next/dist/telemetry/events/index.js", "/node_modules/next/dist/telemetry/events/index.js",
"/node_modules/next/dist/telemetry/events/plugins.js", "/node_modules/next/dist/telemetry/events/plugins.js",
......
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