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 = '' +const END = '' +const LEGACY_START = '' +const LEGACY_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 = '' +const end = '' +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) { + 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') + }) +})