Commit 955bab7b authored by Jude Gao's avatar Jude Gao

[agents-md] Address review sweep nits

`requireNextProjectDir` JSDoc corrected — the function throws a plain
`Error`, not `BadInput`, because `lib/` can't import `BadInput` from
`bin/shared.ts` without inverting the layering. The codemod `bin/`
callers catch and rethrow as `BadInput`; `bin/upgrade.ts` now wraps
its call too (defense in depth — should never fire in practice, but
keeps a future reorder from leaking a stack trace).

`upsertAgentRulesBlock` now detects the existing file's line-ending
style and matches it when injecting the managed block. Previously,
stomping `\n` into a CRLF file on Windows produced mixed EOLs that
confuse editors and `.gitattributes` normalization. `stripLegacyAgentRulesBlock`
loops until no legacy block remains (defensive — if a file ever
acquired multiple legacy blocks via manual paste, both get stripped)
and takes the same `eol` so the re-joined seam doesn't introduce
mixed EOLs. `writeBundledDocsAgentFiles` doc now notes the
two-file create branch is non-atomic — re-running cleanly recovers,
so we accept the transient inconsistency rather than add cleanup
bookkeeping for a cold-path failure.

Test fixture dirs now use `fs.mkdtempSync` instead of
`Date.now() + Math.random()` so parallel workers can't collide. Two
new e2e tests cover the CRLF preservation path and multi-legacy-block
stripping.
parent 694d0ab8
...@@ -435,7 +435,19 @@ export async function runUpgrade( ...@@ -435,7 +435,19 @@ export async function runUpgrade(
// does for new projects so existing projects pick up the agent // does for new projects so existing projects pick up the agent
// rules as a natural side effect of upgrading. No-op on older // rules as a natural side effect of upgrading. No-op on older
// versions without bundled docs. // versions without bundled docs.
const projectDir = requireNextProjectDir(cwd) //
// `requireNextProjectDir` throws a plain `Error` (it lives in the
// `lib/` layer and can't import `BadInput`), so we wrap it to get
// the clean "print just the message" path in `next-codemod.ts`.
// Should never actually fire here because `getInstalledNextVersion`
// validated the same condition earlier — defense in depth so a
// future reorder doesn't leak a stack trace to users.
let projectDir: string
try {
projectDir = requireNextProjectDir(cwd)
} catch (err) {
throw new BadInput((err as Error).message)
}
if (hasBundledDocs(projectDir)) { if (hasBundledDocs(projectDir)) {
const result = writeBundledDocsAgentFiles(projectDir) const result = writeBundledDocsAgentFiles(projectDir)
const touched: string[] = [] const touched: string[] = []
......
...@@ -52,13 +52,10 @@ describe('agents-md e2e (CLI invocation)', () => { ...@@ -52,13 +52,10 @@ describe('agents-md e2e (CLI invocation)', () => {
let consoleOutput let consoleOutput
beforeEach(() => { beforeEach(() => {
// Create isolated test project directory // Create an isolated test project dir via `mkdtempSync` so parallel
// workers can't collide on the same path.
const tmpBase = process.env.NEXT_TEST_DIR || os.tmpdir() const tmpBase = process.env.NEXT_TEST_DIR || os.tmpdir()
testProjectDir = path.join( testProjectDir = fs.mkdtempSync(path.join(tmpBase, 'agents-md-e2e-'))
tmpBase,
`agents-md-e2e-${Date.now()}-${(Math.random() * 1000) | 0}`
)
fs.mkdirSync(testProjectDir, { recursive: true })
// Mock console.log to capture CLI output // Mock console.log to capture CLI output
originalConsoleLog = console.log originalConsoleLog = console.log
...@@ -331,9 +328,8 @@ This is my project documentation. ...@@ -331,9 +328,8 @@ This is my project documentation.
beforeEach(() => { beforeEach(() => {
const tmpBase = process.env.NEXT_TEST_DIR || os.tmpdir() const tmpBase = process.env.NEXT_TEST_DIR || os.tmpdir()
fixtureProjectDir = path.join( fixtureProjectDir = fs.mkdtempSync(
tmpBase, path.join(tmpBase, 'agents-md-bundled-')
`agents-md-bundled-${Date.now()}-${(Math.random() * 1000) | 0}`
) )
copyFixture(BUNDLED_FIXTURE_DIR, fixtureProjectDir) copyFixture(BUNDLED_FIXTURE_DIR, fixtureProjectDir)
}) })
...@@ -553,6 +549,102 @@ Custom rules below. ...@@ -553,6 +549,102 @@ Custom rules below.
} }
}) })
it('strips multiple legacy NEXT-AGENTS-MD blocks when several coexist', async () => {
// Defensive: if a file somehow acquired two legacy blocks (e.g.
// a manual paste or an interrupted earlier run), both should be
// stripped in a single pass. Surrounding user content is
// preserved.
const originalCwd = process.cwd()
process.chdir(fixtureProjectDir)
const existingClaude = `# My Project
Top section.
<!-- NEXT-AGENTS-MD-START -->first stale payload<!-- NEXT-AGENTS-MD-END -->
Middle section.
<!-- NEXT-AGENTS-MD-START -->second stale payload<!-- NEXT-AGENTS-MD-END -->
Bottom section.
`
fs.writeFileSync(
path.join(fixtureProjectDir, 'CLAUDE.md'),
existingClaude
)
try {
await runUpgradeAgentsMd()
const claudeMdContent = fs.readFileSync(
path.join(fixtureProjectDir, 'CLAUDE.md'),
'utf-8'
)
// All user sections preserved.
expect(claudeMdContent).toContain('# My Project')
expect(claudeMdContent).toContain('Top section.')
expect(claudeMdContent).toContain('Middle section.')
expect(claudeMdContent).toContain('Bottom section.')
// Neither legacy payload survives.
expect(claudeMdContent).not.toContain('<!-- NEXT-AGENTS-MD-START -->')
expect(claudeMdContent).not.toContain('<!-- NEXT-AGENTS-MD-END -->')
expect(claudeMdContent).not.toContain('first stale payload')
expect(claudeMdContent).not.toContain('second stale payload')
// Exactly one canonical block.
const matches = claudeMdContent.match(
new RegExp(AGENT_RULES_START_MARKER, 'g')
)
expect(matches).toHaveLength(1)
} finally {
process.chdir(originalCwd)
}
})
it('preserves CRLF line endings when upserting into a Windows-style file', async () => {
// On Windows, existing `AGENTS.md` / `CLAUDE.md` files commonly
// use CRLF. If the upsert stomps `\n` into a CRLF file, the
// result ends up with mixed EOLs that confuse editors, diffs,
// and `.gitattributes` normalization. The upsert must detect
// the existing EOL style and match it.
const originalCwd = process.cwd()
process.chdir(fixtureProjectDir)
const existingAgents =
'# My Project\r\n\r\nCustom team instructions.\r\n\r\n- Use tabs.\r\n'
fs.writeFileSync(
path.join(fixtureProjectDir, 'AGENTS.md'),
existingAgents
)
try {
await runUpgradeAgentsMd()
const agentsMdContent = fs.readFileSync(
path.join(fixtureProjectDir, 'AGENTS.md'),
'utf-8'
)
// User content preserved verbatim, CRLF and all.
expect(agentsMdContent).toContain('# My Project\r\n')
expect(agentsMdContent).toContain('Custom team instructions.\r\n')
// Canonical block landed.
expect(agentsMdContent).toContain(AGENT_RULES_START_MARKER)
expect(agentsMdContent).toContain('node_modules/next/dist/docs/')
// No lone LFs introduced: every `\n` must be preceded by `\r`.
// `match(/(?<!\r)\n/g)` would catch any LF that isn't part of a
// CRLF pair.
expect(agentsMdContent.match(/(?<!\r)\n/g)).toBeNull()
} finally {
process.chdir(originalCwd)
}
})
it('replaces the agent-rules block in place when the marker is already present', async () => { it('replaces the agent-rules block in place when the marker is already present', async () => {
const originalCwd = process.cwd() const originalCwd = process.cwd()
process.chdir(fixtureProjectDir) process.chdir(fixtureProjectDir)
...@@ -665,9 +757,8 @@ Footer content. ...@@ -665,9 +757,8 @@ Footer content.
beforeEach(() => { beforeEach(() => {
const tmpBase = process.env.NEXT_TEST_DIR || os.tmpdir() const tmpBase = process.env.NEXT_TEST_DIR || os.tmpdir()
monorepoProjectDir = path.join( monorepoProjectDir = fs.mkdtempSync(
tmpBase, path.join(tmpBase, 'agents-md-monorepo-')
`agents-md-monorepo-${Date.now()}-${(Math.random() * 1000) | 0}`
) )
copyFixture(MONOREPO_FIXTURE_DIR, monorepoProjectDir) copyFixture(MONOREPO_FIXTURE_DIR, monorepoProjectDir)
}) })
......
...@@ -58,8 +58,12 @@ export function getNextjsVersion(cwd: string): NextjsVersionResult { ...@@ -58,8 +58,12 @@ export function getNextjsVersion(cwd: string): NextjsVersionResult {
* running from a subdirectory or from the monorepo root will hit * running from a subdirectory or from the monorepo root will hit
* this and get a clear "cd into the app directory" message. * this and get a clear "cd into the app directory" message.
* *
* Returns the resolved `cwd` on success, throws `BadInput` on * Returns the resolved `cwd` on success. Throws a plain `Error` on
* failure. * failure — this module lives in the `lib/` layer and can't import
* `BadInput` from `bin/shared.ts` without inverting the layering, so
* callers in the `bin/` layer are expected to catch and rethrow as
* `BadInput` when they want the root `next-codemod.ts` error handler
* to print just the message instead of a full stack trace.
*/ */
export function requireNextProjectDir(cwd: string): string { export function requireNextProjectDir(cwd: string): string {
const resolved = path.resolve(cwd) const resolved = path.resolve(cwd)
...@@ -180,6 +184,14 @@ export interface BundledDocsWriteResult { ...@@ -180,6 +184,14 @@ export interface BundledDocsWriteResult {
* Upserts are non-destructive: existing content outside the marker * Upserts are non-destructive: existing content outside the marker
* block is preserved. If the canonical block is already present * block is preserved. If the canonical block is already present
* verbatim, the file is reported as `unchanged` and not rewritten. * verbatim, the file is reported as `unchanged` and not rewritten.
*
* Not atomic across the two-file create branch: if `AGENTS.md` writes
* successfully and `CLAUDE.md` then throws (ENOSPC, permissions), the
* process leaves the freshly-created `AGENTS.md` behind and bubbles
* the error. Re-running cleanly recovers — the next invocation takes
* the `agentsMdExists` branch and no-ops on the already-present
* canonical block — so we accept the transient inconsistency rather
* than add cleanup bookkeeping for a cold-path failure mode.
*/ */
export function writeBundledDocsAgentFiles( export function writeBundledDocsAgentFiles(
projectDir: string projectDir: string
...@@ -234,6 +246,20 @@ function upsertFile(filePath: string, block: string): BundledDocsFileAction { ...@@ -234,6 +246,20 @@ function upsertFile(filePath: string, block: string): BundledDocsFileAction {
return 'updated' return 'updated'
} }
/**
* Detect the predominant line-ending style in `content`. Returns
* `'\r\n'` if any CRLF is present, `'\n'` otherwise. Used to keep
* upserts from introducing mixed EOLs into Windows CRLF files.
*/
function detectEol(content: string): '\r\n' | '\n' {
return /\r\n/.test(content) ? '\r\n' : '\n'
}
/** Convert all line endings in `s` to `eol`. */
function normalizeEol(s: string, eol: '\r\n' | '\n'): string {
return s.replace(/\r?\n/g, eol)
}
/** /**
* Given the current contents of an AGENTS.md file and a rendered agent-rules * Given the current contents of an AGENTS.md file and a rendered agent-rules
* block, return a version that contains the block exactly once. If the * block, return a version that contains the block exactly once. If the
...@@ -246,15 +272,22 @@ function upsertFile(filePath: string, block: string): BundledDocsFileAction { ...@@ -246,15 +272,22 @@ function upsertFile(filePath: string, block: string): BundledDocsFileAction {
* so projects that ran the pre-bundled-docs version of this codemod end up * so projects that ran the pre-bundled-docs version of this codemod end up
* with a single, current block instead of two stale-and-current blocks * with a single, current block instead of two stale-and-current blocks
* coexisting in the same file. * coexisting in the same file.
*
* Preserves the existing file's line-ending style (CRLF or LF) — important
* on Windows where stomping `\n` into a CRLF file produces mixed EOLs that
* confuse editors, diffs, and `.gitattributes` normalization.
*/ */
function upsertAgentRulesBlock(existing: string, block: string): string { function upsertAgentRulesBlock(existing: string, block: string): string {
const eol = detectEol(existing)
const normalizedBlock = normalizeEol(block, eol)
// Migration step: drop the legacy block first. Older projects that ran // Migration step: drop the legacy block first. Older projects that ran
// `agents-md` against a pre-16.2 Next.js still have a `NEXT-AGENTS-MD-*` // `agents-md` against a pre-16.2 Next.js still have a `NEXT-AGENTS-MD-*`
// wrapper around a `.next-docs/`-style doc index. The legacy block points // wrapper around a `.next-docs/`-style doc index. The legacy block points
// at a directory that probably doesn't exist anymore (or has gone stale // at a directory that probably doesn't exist anymore (or has gone stale
// versus the bundled docs), so we remove it before injecting the new // versus the bundled docs), so we remove it before injecting the new
// canonical block. Surrounding content is preserved. // canonical block. Surrounding content is preserved.
existing = stripLegacyAgentRulesBlock(existing) existing = stripLegacyAgentRulesBlock(existing, eol)
const startIdx = existing.indexOf(AGENT_RULES_START_MARKER) const startIdx = existing.indexOf(AGENT_RULES_START_MARKER)
const endIdx = existing.indexOf(AGENT_RULES_END_MARKER) const endIdx = existing.indexOf(AGENT_RULES_END_MARKER)
...@@ -262,20 +295,22 @@ function upsertAgentRulesBlock(existing: string, block: string): string { ...@@ -262,20 +295,22 @@ function upsertAgentRulesBlock(existing: string, block: string): string {
if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) { if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {
const before = existing.slice(0, startIdx) const before = existing.slice(0, startIdx)
const after = existing.slice(endIdx + AGENT_RULES_END_MARKER.length) const after = existing.slice(endIdx + AGENT_RULES_END_MARKER.length)
const replaced = before + block + after const replaced = before + normalizedBlock + after
return replaced === existing ? existing : replaced return replaced === existing ? existing : replaced
} }
const separator = const separator =
existing.length === 0 || existing.endsWith('\n') ? '\n' : '\n\n' existing.length === 0 || /\r?\n$/.test(existing) ? eol : eol + eol
return existing + separator + block + '\n' return existing + separator + normalizedBlock + eol
} }
/** /**
* Strip the legacy `<!-- NEXT-AGENTS-MD-START -->...<!-- NEXT-AGENTS-MD-END -->` * Strip any `<!-- NEXT-AGENTS-MD-START -->...<!-- NEXT-AGENTS-MD-END -->`
* block from a file's contents, including any whitespace immediately * blocks from a file's contents, including any whitespace immediately
* surrounding it so we don't leave a stray blank line behind. If no legacy * surrounding each block so we don't leave stray blank lines behind. If no
* block is present, returns the input unchanged. * legacy block is present, returns the input unchanged. Loops until every
* occurrence is stripped (defensive against a file that somehow acquired
* more than one, e.g. via manual edits).
* *
* The legacy block was written by the pre-bundled-docs version of the * The legacy block was written by the pre-bundled-docs version of the
* `agents-md` codemod, which generated a custom doc index pointing at a * `agents-md` codemod, which generated a custom doc index pointing at a
...@@ -283,33 +318,42 @@ function upsertAgentRulesBlock(existing: string, block: string): string { ...@@ -283,33 +318,42 @@ function upsertAgentRulesBlock(existing: string, block: string): string {
* were tied to a specific Next.js version and almost certainly no longer * were tied to a specific Next.js version and almost certainly no longer
* match the project's current install, so we drop the entire block when * match the project's current install, so we drop the entire block when
* we install the new managed block. * we install the new managed block.
*
* `eol` is the detected line-ending style of the surrounding file, used
* when re-joining the two halves so the re-joined seam doesn't introduce
* mixed CRLF/LF into a Windows file.
*/ */
function stripLegacyAgentRulesBlock(existing: string): string { function stripLegacyAgentRulesBlock(
const startIdx = existing.indexOf(LEGACY_AGENT_RULES_START_MARKER) existing: string,
if (startIdx === -1) return existing eol: '\r\n' | '\n' = '\n'
const endIdx = existing.indexOf(LEGACY_AGENT_RULES_END_MARKER, startIdx) ): string {
if (endIdx === -1) return existing while (true) {
const startIdx = existing.indexOf(LEGACY_AGENT_RULES_START_MARKER)
if (startIdx === -1) return existing
const endIdx = existing.indexOf(LEGACY_AGENT_RULES_END_MARKER, startIdx)
if (endIdx === -1) return existing
// Expand the slice outward to swallow leading/trailing whitespace so we // Expand the slice outward to swallow leading/trailing whitespace so
// don't leave a stray blank line where the block used to be. // we don't leave a stray blank line where the block used to be.
let cutStart = startIdx let cutStart = startIdx
while (cutStart > 0 && /\s/.test(existing[cutStart - 1])) { while (cutStart > 0 && /\s/.test(existing[cutStart - 1])) {
cutStart-- cutStart--
} }
let cutEnd = endIdx + LEGACY_AGENT_RULES_END_MARKER.length let cutEnd = endIdx + LEGACY_AGENT_RULES_END_MARKER.length
while (cutEnd < existing.length && /\s/.test(existing[cutEnd])) { while (cutEnd < existing.length && /\s/.test(existing[cutEnd])) {
cutEnd++ cutEnd++
} }
const before = existing.slice(0, cutStart) const before = existing.slice(0, cutStart)
const after = existing.slice(cutEnd) const after = existing.slice(cutEnd)
// Re-join with a single newline if both sides have content, so we don't // Re-join with a single blank line if both sides have content, so we
// accidentally fuse the surrounding paragraphs. // don't accidentally fuse the surrounding paragraphs.
if (before.length > 0 && after.length > 0) { existing =
return before + '\n\n' + after before.length > 0 && after.length > 0
? before + eol + eol + after
: before + after
} }
return before + after
} }
function versionToGitHubTag(version: string): string { function versionToGitHubTag(version: string): string {
......
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