File size: 7,950 Bytes
b2cad4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
diff --git a/packages/next-codemod/bin/upgrade.ts b/packages/next-codemod/bin/upgrade.ts
index d33372bb53..a1b83f2bd9 100644
--- a/packages/next-codemod/bin/upgrade.ts
+++ b/packages/next-codemod/bin/upgrade.ts
@@ -18,6 +18,7 @@ import {
 } from '../lib/handle-package'
 import { runTransform } from './transform'
 import { onCancel, TRANSFORMER_INQUIRER_CHOICES } from '../lib/utils'
+import { refreshAgentRulesBlock } from '../lib/agents-md'
 import { BadInput } from './shared'
 
 type PackageManager = 'pnpm' | 'npm' | 'yarn' | 'bun'
@@ -476,6 +477,16 @@ export async function runUpgrade(
     console.log(`${pc.green('✔')} Codemods have been applied successfully.`)
   }
 
+  try {
+    if (refreshAgentRulesBlock(cwd) === 'refreshed') {
+      console.log(
+        `${pc.green('✔')} Refreshed the managed agent-rules block in AGENTS.md / CLAUDE.md to match the upgraded Next.js.`
+      )
+    }
+  } catch {
+    // The block refresh is best-effort — never fail the upgrade over it.
+  }
+
   warnDependenciesOutOfRange(appPackageJson, versionMapping)
 
   endMessage(targetNextVersion)
diff --git a/packages/next-codemod/lib/agents-md.ts b/packages/next-codemod/lib/agents-md.ts
index 1e816a0284..18eacfb406 100644
--- a/packages/next-codemod/lib/agents-md.ts
+++ b/packages/next-codemod/lib/agents-md.ts
@@ -15,6 +15,54 @@ interface NextjsVersionResult {
   error?: string
 }
 
+const AGENT_RULES_START_MARKER = '<!-- BEGIN:nextjs-agent-rules -->'
+
+/**
+ * After an upgrade, refresh the managed agent-rules block in
+ * AGENTS.md / CLAUDE.md so its content matches the Next.js version
+ * that is now installed.
+ *
+ * Delegates to the installed package's own generator
+ * (`next/dist/server/lib/generate-agent-files`), so the block text is
+ * always the one shipped with that version — this codemod never
+ * carries its own copy. Returns `'refreshed'` when a file was
+ * rewritten, `'current'` when the block was already up to date, and
+ * `'skipped'` when there is nothing to do: the project never adopted
+ * the managed block, or the installed Next.js predates the generator
+ * (< 16.3).
+ */
+export function refreshAgentRulesBlock(
+  cwd: string
+): 'refreshed' | 'current' | 'skipped' {
+  const hostsBlock = ['AGENTS.md', 'CLAUDE.md'].some((file) => {
+    try {
+      return fs
+        .readFileSync(path.join(cwd, file), 'utf-8')
+        .includes(AGENT_RULES_START_MARKER)
+    } catch {
+      return false
+    }
+  })
+  if (!hostsBlock) return 'skipped'
+
+  let writeAgentFiles: (dir: string) => { agentsMd: string; claudeMd: string }
+  try {
+    const generatorPath = require.resolve(
+      'next/dist/server/lib/generate-agent-files',
+      { paths: [cwd] }
+    )
+    writeAgentFiles = require(generatorPath).writeAgentFiles
+    if (typeof writeAgentFiles !== 'function') return 'skipped'
+  } catch {
+    return 'skipped'
+  }
+
+  const result = writeAgentFiles(cwd)
+  return result.agentsMd === 'updated' || result.claudeMd === 'updated'
+    ? 'refreshed'
+    : 'current'
+}
+
 export function getNextjsVersion(cwd: string): NextjsVersionResult {
   try {
     const nextPkgPath = require.resolve('next/package.json', { paths: [cwd] })
diff --git a/packages/next/src/server/lib/app-info-log.ts b/packages/next/src/server/lib/app-info-log.ts
index 70eab53c8c..175c88eb73 100644
--- a/packages/next/src/server/lib/app-info-log.ts
+++ b/packages/next/src/server/lib/app-info-log.ts
@@ -7,7 +7,7 @@ import { experimentalSchema } from '../config-schema'
 import { detectAgent } from '../../telemetry/detect-agent'
 import { bundlerName, getBundlerFromEnv } from '../../lib/bundler'
 import {
-  hasAgentRulesInstalled,
+  hasCurrentAgentRules,
   writeAgentFiles,
   type AgentFilesResult,
 } from './generate-agent-files'
@@ -117,17 +117,18 @@ export function logExperimentalInfo({
 
 /**
  * When `next dev` detects an AI coding agent but the managed
- * agent-rules block is missing from AGENTS.md / CLAUDE.md,
- * auto-generate the files so the agent has access to version-matched
- * docs. Returns the write result when files were generated, or `null`
- * when no action was needed.
+ * agent-rules block is missing from AGENTS.md / CLAUDE.md — or an
+ * outdated version of it is installed — auto-generate or refresh the
+ * files so the agent has access to version-matched docs. Returns the
+ * write result when files were touched, or `null` when no action was
+ * needed.
  *
  * Callers gate this on `config.agentRules !== false` — opt-out is
  * declarative in next.config, not inside this function.
  */
 export function ensureAgentRulesForDev(dir: string): AgentFilesResult | null {
   if (detectAgent() === null) return null
-  if (hasAgentRulesInstalled(dir)) return null
+  if (hasCurrentAgentRules(dir)) return null
 
   return writeAgentFiles(dir)
 }
diff --git a/packages/next/src/server/lib/generate-agent-files.ts b/packages/next/src/server/lib/generate-agent-files.ts
index c3f1f70886..12618c6f53 100644
--- a/packages/next/src/server/lib/generate-agent-files.ts
+++ b/packages/next/src/server/lib/generate-agent-files.ts
@@ -41,16 +41,33 @@ export interface AgentFilesResult {
 }
 
 /**
- * Returns true when `AGENTS.md` or `CLAUDE.md` at `dir` contains the
- * managed agent-rules marker.
+ * Returns the managed block (markers included) found in `content`, or
+ * `null` when the markers are absent or malformed.
  */
-export function hasAgentRulesInstalled(dir: string): boolean {
-  const agentsContent = tryReadFile(path.join(dir, 'AGENTS.md'))
-  if (agentsContent?.includes(AGENT_RULES_START_MARKER)) return true
-
-  const claudeContent = tryReadFile(path.join(dir, 'CLAUDE.md'))
-  if (claudeContent?.includes(AGENT_RULES_START_MARKER)) return true
+function extractAgentRulesBlock(content: string): string | null {
+  const start = content.indexOf(AGENT_RULES_START_MARKER)
+  if (start === -1) return null
+  const end = content.indexOf(AGENT_RULES_END_MARKER, start)
+  if (end === -1) return null
+  return content.slice(start, end + AGENT_RULES_END_MARKER.length)
+}
 
+/**
+ * Returns true when `AGENTS.md` or `CLAUDE.md` at `dir` already
+ * contains the current agent-rules block. A block from an earlier
+ * Next.js version (older wording, legacy markers) returns false so
+ * callers know to upsert the current one over it.
+ */
+export function hasCurrentAgentRules(dir: string): boolean {
+  const block = buildAgentRulesBlock()
+  for (const file of ['AGENTS.md', 'CLAUDE.md']) {
+    const content = tryReadFile(path.join(dir, file))
+    if (!content) continue
+    const installed = extractAgentRulesBlock(content)
+    if (installed !== null && normalizeEol(installed, '\n') === block) {
+      return true
+    }
+  }
   return false
 }
 
@@ -58,6 +75,8 @@ export function hasAgentRulesInstalled(dir: string): boolean {
  * Write the agent-rules block into `projectDir`, respecting whichever
  * file the user already uses:
  *
+ *   - A file already hosting the managed block → upsert into it, so
+ *     upgrades rewrite the block in place instead of adding a copy.
  *   - `AGENTS.md` exists → upsert into it, leave `CLAUDE.md` alone.
  *   - `CLAUDE.md` exists (but not `AGENTS.md`) → upsert into it.
  *   - Neither exists → create both (`AGENTS.md` + `CLAUDE.md` with
@@ -74,7 +93,14 @@ export function writeAgentFiles(projectDir: string): AgentFilesResult {
   const agentsMdExists = fs.existsSync(agentsMdPath)
   const claudeMdExists = fs.existsSync(claudeMdPath)
 
-  if (agentsMdExists) {
+  const claudeMdHostsBlock =
+    claudeMdExists &&
+    (tryReadFile(claudeMdPath)?.includes(AGENT_RULES_START_MARKER) ?? false)
+  const agentsMdHostsBlock =
+    agentsMdExists &&
+    (tryReadFile(agentsMdPath)?.includes(AGENT_RULES_START_MARKER) ?? false)
+
+  if (agentsMdExists && (agentsMdHostsBlock || !claudeMdHostsBlock)) {
     return {
       agentsMd: upsertFile(agentsMdPath, block),
       claudeMd: 'skipped',