Commit 694d0ab8 authored by Jude Gao's avatar Jude Gao

[agents-md] Drop `next build` agent-rules gate

Reverts the build-side hard-fail. `next build` no longer checks for
the managed agent-rules block — 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. `checkAgentRules`
collapses back to `checkAgentRulesForDev` with the `Dev Server exited.`
label hardcoded.
parent bd2383f6
...@@ -4,8 +4,7 @@ import { saveCpuProfile } from '../server/lib/cpu-profile' ...@@ -4,8 +4,7 @@ import { saveCpuProfile } from '../server/lib/cpu-profile'
import { existsSync } from 'fs' import { existsSync } from 'fs'
import { italic } from '../lib/picocolors' import { italic } from '../lib/picocolors'
import build from '../build' import build from '../build'
import { warn, error as logError } from '../build/output/log' import { warn } from '../build/output/log'
import { checkAgentRules } from '../server/lib/app-info-log'
import { printAndExit } from '../server/lib/utils' import { printAndExit } from '../server/lib/utils'
import isError from '../lib/is-error' import isError from '../lib/is-error'
import { getProjectDir } from '../lib/get-project-dir' import { getProjectDir } from '../lib/get-project-dir'
...@@ -104,19 +103,6 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => { ...@@ -104,19 +103,6 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => {
printAndExit(`> No such directory exists as the project root: ${dir}`) printAndExit(`> No such directory exists as the project root: ${dir}`)
} }
// Agent-rules gate: hard-fail `next build` when an AI coding agent
// is driving the build and the managed block isn't installed in
// AGENTS.md/CLAUDE.md. Fires before any bundling work so the
// developer doesn't burn minutes on a build they're about to throw
// away. Safe to fail hard here because `detectAgent()` only
// inspects env vars set by AI coding tools — CI pipelines don't
// set them, so this gate never fires on a real build server.
const agentRulesError = checkAgentRules(dir, 'build')
if (agentRulesError !== null) {
logError(agentRulesError)
process.exit(1)
}
// Resolve selective build paths // Resolve selective build paths
let resolvedBuildPaths: { app: string[]; pages: string[] } | undefined let resolvedBuildPaths: { app: string[]; pages: string[] } | undefined
......
import fs from 'fs' import fs from 'fs'
import os from 'os' import os from 'os'
import path from 'path' import path from 'path'
import { checkAgentRules } from './app-info-log' import { checkAgentRulesForDev } from './app-info-log'
const AGENT_RULES_MARKER = '<!-- BEGIN:nextjs-agent-rules -->' const AGENT_RULES_MARKER = '<!-- BEGIN:nextjs-agent-rules -->'
...@@ -28,15 +28,15 @@ function clearAgentEnv() { ...@@ -28,15 +28,15 @@ function clearAgentEnv() {
delete process.env.NEXT_DISABLE_AGENT_RULE_CHECK delete process.env.NEXT_DISABLE_AGENT_RULE_CHECK
} }
describe('checkAgentRules (shared dev + build fatal gate)', () => { describe('checkAgentRulesForDev (dev-side fatal gate)', () => {
let tmpDir: string let tmpDir: string
let originalEnv: NodeJS.ProcessEnv let originalEnv: NodeJS.ProcessEnv
beforeEach(() => { beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-rules-')) tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-rules-dev-'))
// `package.json` at the fixture root defines the Next.js project // `package.json` at the fixture root defines the Next.js project
// root the check anchors on. `next dev` / `next build` both // root the gate anchors on. `next dev` resolves this via
// resolve this via `getProjectDir` before calling the gate. // `getProjectDir` before calling the gate.
fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name": "fixture"}') fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name": "fixture"}')
originalEnv = { ...process.env } originalEnv = { ...process.env }
clearAgentEnv() clearAgentEnv()
...@@ -47,129 +47,93 @@ describe('checkAgentRules (shared dev + build fatal gate)', () => { ...@@ -47,129 +47,93 @@ describe('checkAgentRules (shared dev + build fatal gate)', () => {
process.env = originalEnv process.env = originalEnv
}) })
// Each bypass condition is tested in both modes so neither mode can
// silently drift off the shared gate.
describe.each(['dev', 'build'] as const)('mode=%s', (mode) => {
it('returns null when no agent is detected', () => { it('returns null when no agent is detected', () => {
expect(checkAgentRules(tmpDir, mode)).toBeNull() expect(checkAgentRulesForDev(tmpDir)).toBeNull()
}) })
it('returns null when the managed block is installed in AGENTS.md', () => { it('returns null when the managed block is installed in AGENTS.md', () => {
process.env.CLAUDECODE = '1' process.env.CLAUDECODE = '1'
fs.writeFileSync( fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), `${AGENT_RULES_MARKER}\n`)
path.join(tmpDir, 'AGENTS.md'), expect(checkAgentRulesForDev(tmpDir)).toBeNull()
`${AGENT_RULES_MARKER}\n`
)
expect(checkAgentRules(tmpDir, mode)).toBeNull()
}) })
it('returns null when the managed block is installed in CLAUDE.md', () => { it('returns null when the managed block is installed in CLAUDE.md', () => {
process.env.CLAUDECODE = '1' process.env.CLAUDECODE = '1'
fs.writeFileSync( fs.writeFileSync(path.join(tmpDir, 'CLAUDE.md'), `${AGENT_RULES_MARKER}\n`)
path.join(tmpDir, 'CLAUDE.md'), expect(checkAgentRulesForDev(tmpDir)).toBeNull()
`${AGENT_RULES_MARKER}\n`
)
expect(checkAgentRules(tmpDir, mode)).toBeNull()
}) })
it('returns null when NEXT_DISABLE_AGENT_RULE_CHECK is set', () => { it('returns null when NEXT_DISABLE_AGENT_RULE_CHECK is set', () => {
process.env.CLAUDECODE = '1' process.env.CLAUDECODE = '1'
process.env.NEXT_DISABLE_AGENT_RULE_CHECK = '1' process.env.NEXT_DISABLE_AGENT_RULE_CHECK = '1'
// Neither AGENTS.md nor CLAUDE.md exists — but the bypass env // Neither AGENTS.md nor CLAUDE.md exists — but the bypass env var
// var is set, so the gate must respect it and stay silent. // is set, so the gate must respect it and stay silent.
expect(checkAgentRules(tmpDir, mode)).toBeNull() expect(checkAgentRulesForDev(tmpDir)).toBeNull()
}) })
it('fires when AGENTS.md exists without the managed block', () => { it('fires when AGENTS.md exists without the managed block', () => {
// File existence alone isn't enough — we care specifically // File existence alone isn't enough — we care specifically about
// about the Next.js directive, so a custom AGENTS.md without // the Next.js directive, so a custom AGENTS.md without the marker
// the marker still counts as "not installed". // still counts as "not installed".
process.env.CLAUDECODE = '1' process.env.CLAUDECODE = '1'
fs.writeFileSync( fs.writeFileSync(
path.join(tmpDir, 'AGENTS.md'), path.join(tmpDir, 'AGENTS.md'),
'# Team rules\n\nUse tabs, not spaces.\n' '# Team rules\n\nUse tabs, not spaces.\n'
) )
expect(checkAgentRules(tmpDir, mode)).not.toBeNull() expect(checkAgentRulesForDev(tmpDir)).not.toBeNull()
})
}) })
it('only checks the Next.js project directory — a marker in an ancestor does 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 // The gate is strictly anchored on `dir` (the Next.js project
// directory). A marker dropped at a parent directory is // directory). A marker dropped at a parent directory is
// irrelevant: AI agents read agent-rules files from the package // irrelevant: AI agents read agent-rules files from the package
// they're working in, not from some ancestor. In a monorepo // they're working in, not from some ancestor. In a monorepo this
// this means the marker must live in the app sub-package, never // means the marker must live in the app sub-package, never at
// at the monorepo root. // the monorepo root.
process.env.CLAUDECODE = '1' process.env.CLAUDECODE = '1'
const appDir = path.join(tmpDir, 'apps', 'web') const appDir = path.join(tmpDir, 'apps', 'web')
fs.mkdirSync(appDir, { recursive: true }) fs.mkdirSync(appDir, { recursive: true })
fs.writeFileSync(path.join(appDir, 'package.json'), '{"name": "web"}') fs.writeFileSync(path.join(appDir, 'package.json'), '{"name": "web"}')
// Marker at the monorepo root — wrong place for an // Marker at the monorepo root — wrong place for an `apps/web/`
// `apps/web/` invocation. // invocation.
fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), `${AGENT_RULES_MARKER}\n`) fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), `${AGENT_RULES_MARKER}\n`)
expect(checkAgentRules(appDir, 'dev')).not.toBeNull() expect(checkAgentRulesForDev(appDir)).not.toBeNull()
}) })
it('respects the marker when it is in the sub-package, not the monorepo root', () => { 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 // Same monorepo layout, but the marker is now in the sub-package
// sub-package (where it belongs). The check must find it. // (where it belongs). The gate must find it.
process.env.CLAUDECODE = '1' process.env.CLAUDECODE = '1'
const appDir = path.join(tmpDir, 'apps', 'web') const appDir = path.join(tmpDir, 'apps', 'web')
fs.mkdirSync(appDir, { recursive: true }) fs.mkdirSync(appDir, { recursive: true })
fs.writeFileSync(path.join(appDir, 'package.json'), '{"name": "web"}') fs.writeFileSync(path.join(appDir, 'package.json'), '{"name": "web"}')
fs.writeFileSync(path.join(appDir, 'AGENTS.md'), `${AGENT_RULES_MARKER}\n`) fs.writeFileSync(path.join(appDir, 'AGENTS.md'), `${AGENT_RULES_MARKER}\n`)
expect(checkAgentRules(appDir, 'dev')).toBeNull() expect(checkAgentRulesForDev(appDir)).toBeNull()
}) })
it('returns a `Fatal: Dev Server exited.`-prefixed message in dev mode', () => { it('fires with a `Fatal: Dev Server exited.`-prefixed rationale message', () => {
process.env.CLAUDECODE = '1' process.env.CLAUDECODE = '1'
const message = checkAgentRules(tmpDir, 'dev') const message = checkAgentRulesForDev(tmpDir)
expect(message).not.toBeNull() expect(message).not.toBeNull()
// Leads with the dev-specific exit label. The caller will // Leads with title-cased `Fatal: Dev Server exited.` — the
// `process.exit(1)` right after, and this wording makes it // caller will `process.exit(1)` right after, and this wording
// clear in the log that the process terminated intentionally. // makes it clear in the log that the process terminated
// intentionally.
expect(message!.startsWith('Fatal: Dev Server exited.')).toBe(true) expect(message!.startsWith('Fatal: Dev Server exited.')).toBe(true)
// Build label must NOT leak into dev output.
expect(message).not.toContain('Build aborted.')
assertSharedRationale(message!)
})
it('returns a `Fatal: Build aborted.`-prefixed message in build mode', () => {
process.env.CLAUDECODE = '1'
const message = checkAgentRules(tmpDir, 'build')
expect(message).not.toBeNull()
// Build gets its own exit label so the lead sentence matches the
// command the developer ran. Agents pattern-match both labels as
// terminal failures — which is exactly what we want.
expect(message!.startsWith('Fatal: Build aborted.')).toBe(true)
// Dev label must NOT leak into build output.
expect(message).not.toContain('Dev Server exited.')
assertSharedRationale(message!)
})
})
/**
* Shared rationale assertions used by both the dev and build
* messages. 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, so both modes must carry all of them.
*/
function assertSharedRationale(message: string): void {
// States the cause. // States the cause.
expect(message).toContain('AI coding agent') expect(message).toContain('AI coding agent')
expect(message).toContain('AGENTS.md') expect(message).toContain('AGENTS.md')
expect(message).toContain('CLAUDE.md') expect(message).toContain('CLAUDE.md')
// Explains WHY the rules matter in concrete terms. // 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('trained on older Next.js versions')
expect(message).toContain('breaking changes') expect(message).toContain('breaking changes')
expect(message).toContain('deprecated APIs') expect(message).toContain('deprecated APIs')
...@@ -187,4 +151,5 @@ function assertSharedRationale(message: string): void { ...@@ -187,4 +151,5 @@ function assertSharedRationale(message: string): void {
expect(message).toContain('Strongly discouraged') expect(message).toContain('Strongly discouraged')
expect(message).toContain('last-resort') expect(message).toContain('last-resort')
expect(message).toContain('far more time than the codemod takes to run') expect(message).toContain('far more time than the codemod takes to run')
} })
})
...@@ -171,7 +171,7 @@ const BYPASS_ENV_VAR = 'NEXT_DISABLE_AGENT_RULE_CHECK' ...@@ -171,7 +171,7 @@ const BYPASS_ENV_VAR = 'NEXT_DISABLE_AGENT_RULE_CHECK'
const AGENTS_MD_INSTALL_COMMAND = 'npx @next/codemod@canary upgrade agents-md' const AGENTS_MD_INSTALL_COMMAND = 'npx @next/codemod@canary upgrade agents-md'
/** /**
* Check the Next.js agent-rules gate for `next dev` and `next build`. * Check the Next.js agent-rules gate for `next dev`.
* *
* Returns `null` when the caller should proceed normally: no AI * Returns `null` when the caller should proceed normally: no AI
* coding agent is driving, OR the managed agent-rules block is * coding agent is driving, OR the managed agent-rules block is
...@@ -183,11 +183,13 @@ const AGENTS_MD_INSTALL_COMMAND = 'npx @next/codemod@canary upgrade agents-md' ...@@ -183,11 +183,13 @@ const AGENTS_MD_INSTALL_COMMAND = 'npx @next/codemod@canary upgrade agents-md'
* none of the above apply. The caller should print the message and * none of the above apply. The caller should print the message and
* `process.exit(1)` — warnings attached to a successful process are * `process.exit(1)` — warnings attached to a successful process are
* empirically ignored by agents, so the only reliable way to make * empirically ignored by agents, so the only reliable way to make
* them act on this is to prevent the success signal from firing at * them act on this is to prevent the `Ready` / success signal from
* all. Build is safe to hard-fail alongside dev because CI * firing at all.
* environments don't set the env vars that `detectAgent()` inspects, *
* so this gate never fires in automated pipelines — only when a * Only `next dev` runs this gate. `next build` deliberately does
* developer is running `next build` from inside an agent session. * 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.
* *
* The message is deliberately long and rationale-heavy. Agents * The message is deliberately long and rationale-heavy. Agents
* processing tool output weigh concrete negative consequences ("will * processing tool output weigh concrete negative consequences ("will
...@@ -198,26 +200,17 @@ const AGENTS_MD_INSTALL_COMMAND = 'npx @next/codemod@canary upgrade agents-md' ...@@ -198,26 +200,17 @@ const AGENTS_MD_INSTALL_COMMAND = 'npx @next/codemod@canary upgrade agents-md'
* is disclosed, but framed as a last resort with a concrete negative * is disclosed, but framed as a last resort with a concrete negative
* consequence attached ("agents will continue producing broken code * consequence attached ("agents will continue producing broken code
* that takes more time to fix than the codemod takes to run"). * that takes more time to fix than the codemod takes to run").
*
* `mode` picks the "Fatal: X" label so the lead sentence matches the
* command the user invoked. `Dev Server exited.` and `Build aborted.`
* are both pattern-matched by agents as terminal failures, which is
* exactly the framing we want.
*/ */
export function checkAgentRules( export function checkAgentRulesForDev(dir: string): string | null {
dir: string,
mode: 'dev' | 'build'
): string | null {
if (detectAgent() === null) return null if (detectAgent() === null) return null
if (hasAgentRulesInstalled(dir)) return null if (hasAgentRulesInstalled(dir)) return null
if (process.env[BYPASS_ENV_VAR]) return null if (process.env[BYPASS_ENV_VAR]) return null
const command = cyan(AGENTS_MD_INSTALL_COMMAND) const command = cyan(AGENTS_MD_INSTALL_COMMAND)
const bypass = cyan(`${BYPASS_ENV_VAR}=1`) const bypass = cyan(`${BYPASS_ENV_VAR}=1`)
const exitLabel = mode === 'dev' ? 'Dev Server exited.' : 'Build aborted.'
return ( return (
`Fatal: ${exitLabel} We detected you're running Next.js ` + `Fatal: Dev Server exited. We detected you're running Next.js ` +
`inside an AI coding agent but the managed agent-rules block is ` + `inside an AI coding agent but the managed agent-rules block is ` +
`not installed in AGENTS.md or CLAUDE.md.\n\n` + `not installed in AGENTS.md or CLAUDE.md.\n\n` +
`Why this matters: AI coding agents are trained on older Next.js ` + `Why this matters: AI coding agents are trained on older Next.js ` +
......
...@@ -27,7 +27,7 @@ import { ...@@ -27,7 +27,7 @@ import {
PHASE_DEVELOPMENT_SERVER, PHASE_DEVELOPMENT_SERVER,
} from '../../shared/lib/constants' } from '../../shared/lib/constants'
import { import {
checkAgentRules, checkAgentRulesForDev,
getEnvInfo, getEnvInfo,
logExperimentalInfo, logExperimentalInfo,
logStartInfo, logStartInfo,
...@@ -384,7 +384,7 @@ export async function startServer( ...@@ -384,7 +384,7 @@ export async function startServer(
// length and surfaces a last-resort `NEXT_DISABLE_AGENT_RULE_CHECK` // length and surfaces a last-resort `NEXT_DISABLE_AGENT_RULE_CHECK`
// env var for locked-down environments. // env var for locked-down environments.
if (isDev) { if (isDev) {
const agentRulesError = checkAgentRules(dir, 'dev') const agentRulesError = checkAgentRulesForDev(dir)
if (agentRulesError !== null) { if (agentRulesError !== null) {
Log.error(agentRulesError) Log.error(agentRulesError)
process.exit(1) process.exit(1)
......
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