File size: 12,295 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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
diff --git a/test/development/app-dir/agent-rules-refresh/agent-rules-refresh.test.ts b/test/development/app-dir/agent-rules-refresh/agent-rules-refresh.test.ts
new file mode 100644
index 00000000..1766e950
--- /dev/null
+++ b/test/development/app-dir/agent-rules-refresh/agent-rules-refresh.test.ts
@@ -0,0 +1,337 @@
+import execa from 'execa'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { ensureAgentRulesForDev } from '../../../../packages/next/src/server/lib/app-info-log'
+
+const START = '<!-- BEGIN:nextjs-agent-rules -->'
+const END = '<!-- END:nextjs-agent-rules -->'
+const LEGACY_START = '<!-- NEXT-AGENTS-MD-START -->'
+const LEGACY_END = '<!-- NEXT-AGENTS-MD-END -->'
+const REPO_ROOT = path.resolve(__dirname, '../../../..')
+const CODEMOD_CLI = path.join(
+  REPO_ROOT,
+  'packages/next-codemod/bin/next-codemod.ts'
+)
+const TSX_CLI = require.resolve('tsx/cli')
+
+function occurrences(content: string, value: string) {
+  return content.split(value).length - 1
+}
+
+describe('next dev refreshes managed agent rules from its running sources', () => {
+  const projects: string[] = []
+  const originalClaudeCode = process.env.CLAUDECODE
+
+  function createProject() {
+    const project = fs.mkdtempSync(path.join(os.tmpdir(), 'dev-agent-rules-'))
+    projects.push(project)
+    return project
+  }
+
+  beforeAll(() => {
+    process.env.CLAUDECODE = '1'
+  })
+
+  afterAll(() => {
+    if (originalClaudeCode === undefined) delete process.env.CLAUDECODE
+    else process.env.CLAUDECODE = originalClaudeCode
+    for (const project of projects) {
+      fs.rmSync(project, { recursive: true, force: true })
+    }
+  })
+
+  it('updates in place, preserves adjacent content and CRLF, and is idempotent', () => {
+    const project = createProject()
+    const file = path.join(project, 'AGENTS.md')
+    fs.writeFileSync(
+      file,
+      `# Team rules\r\n\r\nKeep this paragraph.\r\n\r\n${START}\r\nstale rules\r\n${END}\r\n\r\n# Footer\r\nKeep this too.\r\n`
+    )
+
+    ensureAgentRulesForDev(project)
+    const first = fs.readFileSync(file, 'utf8')
+
+    expect(first).toContain('# Team rules\r\n')
+    expect(first).toContain('Keep this paragraph.\r\n')
+    expect(first).toContain('# Footer\r\nKeep this too.\r\n')
+    expect(first).not.toContain('stale rules')
+    expect(first).toContain('node_modules/next/dist/docs/')
+    expect(occurrences(first, START)).toBe(1)
+    expect(occurrences(first, END)).toBe(1)
+    expect(first.replace(/\r\n/g, '')).not.toContain('\n')
+    expect(fs.existsSync(path.join(project, 'CLAUDE.md'))).toBe(false)
+
+    ensureAgentRulesForDev(project)
+    expect(fs.readFileSync(file, 'utf8')).toBe(first)
+  })
+
+  it('rewrites the file hosting the block instead of another agent file', () => {
+    const project = createProject()
+    fs.writeFileSync(
+      path.join(project, 'AGENTS.md'),
+      '# Agent-independent team notes\n'
+    )
+    fs.writeFileSync(
+      path.join(project, 'CLAUDE.md'),
+      `# Claude notes\n\n${START}\nold installed rules\n${END}\n`
+    )
+
+    ensureAgentRulesForDev(project)
+    const agents = fs.readFileSync(path.join(project, 'AGENTS.md'), 'utf8')
+    const claude = fs.readFileSync(path.join(project, 'CLAUDE.md'), 'utf8')
+
+    expect(agents).toBe('# Agent-independent team notes\n')
+    expect(claude).toContain('# Claude notes')
+    expect(claude).not.toContain('old installed rules')
+    expect(claude).toContain('node_modules/next/dist/docs/')
+    expect(occurrences(claude, START)).toBe(1)
+    expect(occurrences(claude, END)).toBe(1)
+  })
+
+  it('migrates a legacy block while preserving user-authored content', () => {
+    const project = createProject()
+    const file = path.join(project, 'AGENTS.md')
+    fs.writeFileSync(
+      file,
+      `# Before\n\n${LEGACY_START}\nlegacy index\n${LEGACY_END}\n\n# After\n`
+    )
+
+    ensureAgentRulesForDev(project)
+    const content = fs.readFileSync(file, 'utf8')
+    expect(content).toContain('# Before')
+    expect(content).toContain('# After')
+    expect(content).not.toContain('legacy index')
+    expect(content).not.toContain(LEGACY_START)
+    expect(content).not.toContain(LEGACY_END)
+    expect(occurrences(content, START)).toBe(1)
+    expect(occurrences(content, END)).toBe(1)
+  })
+
+  it('converges an unterminated current block within two starts', () => {
+    const project = createProject()
+    const file = path.join(project, 'AGENTS.md')
+    fs.writeFileSync(file, `# Keep me\n\n${START}\nunterminated stale rules\n`)
+
+    ensureAgentRulesForDev(project)
+    ensureAgentRulesForDev(project)
+
+    const content = fs.readFileSync(file, 'utf8')
+    expect(content).toContain('# Keep me')
+    expect(content).not.toContain('unterminated stale rules')
+    expect(content).toContain('node_modules/next/dist/docs/')
+    expect(occurrences(content, START)).toBe(1)
+    expect(occurrences(content, END)).toBe(1)
+
+    ensureAgentRulesForDev(project)
+    expect(fs.readFileSync(file, 'utf8')).toBe(content)
+  })
+})
+
+describe('@next/codemod upgrade refreshes adopted rules from upgraded Next.js', () => {
+  type GeneratorMode = 'canonical' | 'missing' | 'throws'
+  const projects: string[] = []
+
+  function createProject({
+    installed,
+    target,
+    generator,
+    agents,
+  }: {
+    installed: string
+    target: string
+    generator: GeneratorMode
+    agents?: string
+  }) {
+    const project = fs.mkdtempSync(path.join(os.tmpdir(), 'rules-upgrade-'))
+    projects.push(project)
+    const bin = path.join(project, 'fake-bin')
+    const nextDir = path.join(project, 'node_modules', 'next')
+    const reactDir = path.join(project, 'node_modules', 'react')
+    fs.mkdirSync(bin, { recursive: true })
+    fs.mkdirSync(nextDir, { recursive: true })
+    fs.mkdirSync(reactDir, { recursive: true })
+    fs.writeFileSync(
+      path.join(project, 'package.json'),
+      JSON.stringify({
+        name: 'upgrade-fixture',
+        private: true,
+        dependencies: {
+          next: installed,
+          react: '19.2.0',
+          'react-dom': '19.2.0',
+        },
+      })
+    )
+    fs.writeFileSync(
+      path.join(nextDir, 'package.json'),
+      JSON.stringify({ name: 'next', version: installed })
+    )
+    fs.writeFileSync(
+      path.join(reactDir, 'package.json'),
+      JSON.stringify({ name: 'react', version: '19.2.0' })
+    )
+    if (agents !== undefined) {
+      fs.writeFileSync(path.join(project, 'AGENTS.md'), agents)
+    }
+
+    const npmShim = path.join(bin, 'npm')
+    fs.writeFileSync(
+      npmShim,
+      `#!/usr/bin/env node
+const fs = require('fs')
+const path = require('path')
+const args = process.argv.slice(2)
+const target = process.env.FAKE_NEXT_TARGET
+if (args[0] === '--silent' && args[1] === 'view') {
+  const query = args[2]
+  if (query.startsWith('next@')) {
+    if (args.includes('--field')) console.log(JSON.stringify(target))
+    else console.log(JSON.stringify({ version: target, peerDependencies: { react: '19.2.0', 'react-dom': '19.2.0' } }))
+  } else if (query.startsWith('react@') || query.startsWith('@types/react@') || query.startsWith('@types/react-dom@')) {
+    console.log(JSON.stringify('19.2.0'))
+  } else {
+    throw new Error('Unexpected npm view: ' + query)
+  }
+} else if (args[0] === 'install') {
+  const nextDir = path.join(process.cwd(), 'node_modules', 'next')
+  fs.writeFileSync(path.join(nextDir, 'package.json'), JSON.stringify({ name: 'next', version: target }))
+  const generatorDir = path.join(nextDir, 'dist', 'server', 'lib')
+  fs.rmSync(path.join(nextDir, 'dist'), { recursive: true, force: true })
+  if (process.env.FAKE_GENERATOR_MODE !== 'missing') {
+    fs.mkdirSync(generatorDir, { recursive: true })
+    const source = process.env.FAKE_GENERATOR_MODE === 'throws'
+      ? "exports.writeAgentFiles = () => { throw new Error('generator failed') }"
+      : ${JSON.stringify(`
+const fs = require('fs')
+const path = require('path')
+const start = '<!-- BEGIN:nextjs-agent-rules -->'
+const end = '<!-- END:nextjs-agent-rules -->'
+const block = start + '\\ncanonical rules supplied by upgraded Next.js\\n' + end
+function update(dir, name) {
+  const file = path.join(dir, name)
+  if (!fs.existsSync(file)) return 'skipped'
+  const content = fs.readFileSync(file, 'utf8')
+  const from = content.indexOf(start)
+  if (from < 0) return 'skipped'
+  const markerEnd = content.indexOf(end, from)
+  const after = markerEnd < 0 ? content.length : markerEnd + end.length
+  const updated = content.slice(0, from) + block + content.slice(after)
+  if (updated === content) return 'unchanged'
+  fs.writeFileSync(file, updated)
+  return 'updated'
+}
+exports.writeAgentFiles = (dir) => {
+  const changed = [update(dir, 'AGENTS.md'), update(dir, 'CLAUDE.md')].includes('updated')
+  return new Proxy({}, { get: () => changed ? 'updated' : 'unchanged' })
+}
+`)}
+    fs.writeFileSync(path.join(generatorDir, 'generate-agent-files.js'), source)
+  }
+} else {
+  throw new Error('Unexpected npm command: ' + args.join(' '))
+}
+`
+    )
+    fs.chmodSync(npmShim, 0o755)
+
+    return {
+      project,
+      target,
+      env: {
+        PATH: `${bin}${path.delimiter}${process.env.PATH}`,
+        FAKE_NEXT_TARGET: target,
+        FAKE_GENERATOR_MODE: generator,
+      },
+    }
+  }
+
+  async function upgrade(fixture: ReturnType<typeof createProject>) {
+    const result = await execa(
+      process.execPath,
+      [TSX_CLI, CODEMOD_CLI, 'upgrade', fixture.target, '--yes'],
+      {
+        cwd: fixture.project,
+        env: { ...process.env, ...fixture.env },
+        reject: false,
+      }
+    )
+    if (result.exitCode !== 0) {
+      throw new Error(`codemod failed:
+${result.stdout}
+${result.stderr}`)
+    }
+  }
+
+  afterAll(() => {
+    for (const project of projects) {
+      fs.rmSync(project, { recursive: true, force: true })
+    }
+  })
+
+  it('uses the newly installed package as source of truth', async () => {
+    const adopted = createProject({
+      installed: '16.3.0-canary.80',
+      target: '16.3.0-canary.99',
+      generator: 'canonical',
+      agents: `# Local rules\n\n${START}\nstale package rules\n${END}\n\n# Tail\n`,
+    })
+
+    await upgrade(adopted)
+    const refreshed = fs.readFileSync(
+      path.join(adopted.project, 'AGENTS.md'),
+      'utf8'
+    )
+    expect(refreshed).toContain('# Local rules')
+    expect(refreshed).toContain('# Tail')
+    expect(refreshed).toContain('canonical rules supplied by upgraded Next.js')
+    expect(refreshed).not.toContain('stale package rules')
+    expect(occurrences(refreshed, START)).toBe(1)
+    expect(fs.existsSync(path.join(adopted.project, 'CLAUDE.md'))).toBe(false)
+  })
+
+  it('does not create agent files for projects that have not adopted a block', async () => {
+    const unadopted = createProject({
+      installed: '16.3.0-canary.80',
+      target: '16.3.0-canary.99',
+      generator: 'canonical',
+    })
+
+    await upgrade(unadopted)
+    expect(fs.existsSync(path.join(unadopted.project, 'AGENTS.md'))).toBe(false)
+    expect(fs.existsSync(path.join(unadopted.project, 'CLAUDE.md'))).toBe(false)
+  })
+
+  it('no-ops when the upgraded package predates the generator', async () => {
+    const oldPackage = createProject({
+      installed: '16.2.0',
+      target: '16.2.9',
+      generator: 'missing',
+      agents: `# Local rules\n\n${START}\nstale package rules\n${END}\n`,
+    })
+
+    await upgrade(oldPackage)
+    expect(
+      fs.readFileSync(path.join(oldPackage.project, 'AGENTS.md'), 'utf8')
+    ).toContain('stale package rules')
+  })
+
+  it('keeps a successful upgrade successful if refreshing fails', async () => {
+    const brokenGenerator = createProject({
+      installed: '16.3.0-canary.80',
+      target: '16.3.0-canary.99',
+      generator: 'throws',
+      agents: `# Local rules\n\n${START}\nstale package rules\n${END}\n`,
+    })
+
+    await expect(upgrade(brokenGenerator)).resolves.toBeUndefined()
+    expect(
+      JSON.parse(
+        fs.readFileSync(
+          path.join(brokenGenerator.project, 'package.json'),
+          'utf8'
+        )
+      ).dependencies.next
+    ).toBe('16.3.0-canary.99')
+  })
+})