diff --git a/codev-skeleton/resources/commands/codev.md b/codev-skeleton/resources/commands/codev.md index 268df7acf..3753c9fe1 100644 --- a/codev-skeleton/resources/commands/codev.md +++ b/codev-skeleton/resources/commands/codev.md @@ -205,6 +205,8 @@ If you've customized a file locally, the update creates a `.codev-new` file with Shipped Claude and Codex skills (`.claude/skills/`, `.codex/skills/`) are refreshed too. A missing skill is added. A skill you never edited, one whose content matches a version Codev shipped, is replaced with the package's version. An edited skill is kept, and each of its files that differs gets a `.codev-new` copy of the new version for the merge, on every update while it differs. A file the package adds to an edited skill arrives as `.codev-new` too. `--force` overwrites an edited skill's packaged files as well, keeping any file the package does not ship. A symlinked skill directory, one holding a symlink, or a symlinked `.claude/`, `.codex/` or skills root is left alone. `--dry-run` reports all of this without writing. +CLAUDE.md and AGENTS.md are compared with the package's template everywhere outside the generated hot-context block (between the `CODEV HOT CONTEXT` markers). One that matches, whatever project name its heading carries and in either line ending, is up to date and left alone, and a `.codev-new` beside it that matches the template the same way is removed. One edited outside the block is kept, and the template is written beside it as `.codev-new` for the merge. The block is regenerated from `codev/resources/{arch,lessons}-critical.md` on every update, so an edit inside it is replaced and reported as a block refresh, never a conflict: edit the hot files instead. A doc an older release wrote is a conflict too when the template has since changed outside the block, even if you never edited it. `--dry-run` prints the lines the real run would print, writing nothing. + When a governance file is still a starter on a project with code, `codev update` prints one line pointing at `codev bootstrap-docs` (in `--agent` mode it is the `instructions.bootstrapDocs` string instead; never on `--dry-run`). **Examples:** diff --git a/codev/projects/bugfix-1982-codev-update-reports-false-con/status.yaml b/codev/projects/bugfix-1982-codev-update-reports-false-con/status.yaml new file mode 100644 index 000000000..2abc66102 --- /dev/null +++ b/codev/projects/bugfix-1982-codev-update-reports-false-con/status.yaml @@ -0,0 +1,21 @@ +id: bugfix-1982 +title: codev-update-reports-false-con +protocol: bugfix +phase: pr +plan_phases: [] +current_plan_phase: null +gates: + pr: + status: pending + requested_at: '2026-11-25T07:51:14.305Z' +iteration: 1 +build_complete: false +history: [] +started_at: '2026-11-25T07:17:15.639Z' +updated_at: '2026-11-25T07:51:14.306Z' +pr_history: + - phase: pr + pr_number: 1984 + branch: builder/bugfix-1982 + created_at: '2026-11-25T07:33:49.202Z' +pr_ready_for_human: true diff --git a/codev/resources/commands/codev.md b/codev/resources/commands/codev.md index cfb5acb36..ae0d1e272 100644 --- a/codev/resources/commands/codev.md +++ b/codev/resources/commands/codev.md @@ -206,6 +206,8 @@ If you've customized a file locally, the update creates a `.codev-new` file with Shipped Claude and Codex skills (`.claude/skills/`, `.codex/skills/`) are refreshed too. A missing skill is added. A skill you never edited, one whose content matches a version Codev shipped, is replaced with the package's version. An edited skill is kept, and each of its files that differs gets a `.codev-new` copy of the new version for the merge, on every update while it differs. A file the package adds to an edited skill arrives as `.codev-new` too. `--force` overwrites an edited skill's packaged files as well, keeping any file the package does not ship. A symlinked skill directory, one holding a symlink, or a symlinked `.claude/`, `.codex/` or skills root is left alone. `--dry-run` reports all of this without writing. +CLAUDE.md and AGENTS.md are compared with the package's template everywhere outside the generated hot-context block (between the `CODEV HOT CONTEXT` markers). One that matches, whatever project name its heading carries and in either line ending, is up to date and left alone, and a `.codev-new` beside it that matches the template the same way is removed. One edited outside the block is kept, and the template is written beside it as `.codev-new` for the merge. The block is regenerated from `codev/resources/{arch,lessons}-critical.md` on every update, so an edit inside it is replaced and reported as a block refresh, never a conflict: edit the hot files instead. A doc an older release wrote is a conflict too when the template has since changed outside the block, even if you never edited it. `--dry-run` prints the lines the real run would print, writing nothing. + When a governance file is still a starter on a project with code, `codev update` prints one line pointing at `codev bootstrap-docs` (in `--agent` mode it is the `instructions.bootstrapDocs` string instead; never on `--dry-run`). In agent mode (`--agent`), human-readable output goes to stderr and structured JSON is written to stdout. The JSON includes file lists, conflict details, and merge instructions. The interactive Claude merge is skipped. diff --git a/codev/state/bugfix-1982_thread.md b/codev/state/bugfix-1982_thread.md new file mode 100644 index 000000000..69a29e496 --- /dev/null +++ b/codev/state/bugfix-1982_thread.md @@ -0,0 +1,74 @@ +# bugfix-1982 thread + +## 2026-11-24 — investigate + +Reproduced with a build of this branch (`packages/codev/bin/codev.js`) in the session +scratchpad, outside any repository: `codev init fresh --yes && cd fresh && codev update +--dry-run` prints the issue's output exactly (2 root-doc conflicts, plus unconditional +hot-tier / cold-tier / managed-block lines). A real `codev update --agent` on a freshly +initialized project writes `CLAUDE.md.codev-new` and `AGENTS.md.codev-new`, and `cmp` +reports both byte-identical to the files beside them. + +Root cause: + +1. **False conflicts.** `copyRootFiles` (`packages/codev/src/lib/scaffold.ts`), which + update calls with `handleConflicts: true`, makes no comparison at all: any existing + CLAUDE.md / AGENTS.md is a conflict, and the template is written beside it. The + identical-content check update.ts had at first (3cb623203, Dec 2025) was lost when + Spec 618 (e66a014f6, Mar 2026) moved update onto `copyRootFiles`, a helper written for + adopt. The issue's guess (comparison made before the block is rendered) is wrong: the + templates already carry the rendered managed block, which is why the `.codev-new` is + byte-identical. The "second update" test only checks `result.conflicts` (skills), never + `rootConflicts`, so it never caught this. +2. **Dry run disagrees.** `update.ts` prints the hot-tier, cold-tier and managed-block + lines unconditionally under `--dry-run`; the real run prints only what + `copyHotTierDefaults` / `copyColdTierDefaults` copied and what `syncHotContextBlock` + changed. + +Decision on edits INSIDE the managed block: not adopter content. The block is regenerated +from the hot files on every update (`syncHotContextBlock` already replaces it; the BEGIN +marker says do not edit), so such an edit is neither a conflict nor kept; update reports it +as a block refresh. Hot context is changed in `codev/resources/{arch,lessons}-critical.md`. + +Known limit, left as is: a doc an adopter never edited, written by an older release whose +template has since changed outside the block, is still a conflict. There is no record of the +installed version for root docs (skills have `SHIPPED_SKILL_HASHES`). Flagged to the architect. + +## 2026-11-24 — fix + +Architect accepted the root cause and decisions; asked that the known limit be pinned by a +test (done) and given its own PR paragraph, and that the dry-run test compare dry and real +reports on the same project (done, three scenarios). + +- `sameOutsideHotBlock` (managed-block.ts) compares two docs as the block refresh leaves + them (both upserted with the same empty block), so content inside the block, or a + missing block, never counts as an edit. +- `copyRootFiles` uses it: up to date → no conflict, and a `.codev-new` holding exactly the + template is removed (the skills' `removeResolvedCodevNew` precedent; cleans up leftovers + this bug wrote in adopters' projects). +- Hot-tier, cold-tier and block steps take `dryRun` and run one code path; a dry run counts + the hot files it would create as present when rendering the block. Real-run block line + is now `~ (hot-tier block refreshed)` so the two modes differ only by "would be". +- Regression test `bugfix-1982-update-root-docs.test.ts` (real `init()` then `update()`, + execSync stubbed for git init / codev doctor): 10/10 fail on the pre-fix source, 10/10 + pass with the fix. +- Verified on an installed build: packed the four tarballs and `npm install -g --prefix` + into the scratchpad (no global install, no Tower restart). The issue's three commands + give "Already up to date!" in both modes and no `.codev-new`; edits outside the block and + to a skill are kept as conflicts; an in-block edit is a block refresh; missing + governance files print identical per-file lines in dry and real runs. + +## 2026-11-24 — pr (PR #1984) + +CMAP round 1: codex REQUEST_CHANGES (only porch's own `chore(porch)` commit subjects; +rebutted: 78 of the last 200 main commits are porch's, merged unchanged); claude APPROVE +with notes. Folded in: `{{PROJECT_NAME}}` matched as any name (a clone under another +directory name was a false conflict); the leftover-`.codev-new` removal is logged in both +modes and in adopt. Round 2: codex same objection plus a stale name in the PR body (fixed); +claude COMMENT. Folded in: CRLF normalisation (skills already do it), and a leftover is +judged with the same match as the doc so a renamed checkout's leftover is resolved. +Not taken: an unreadable root doc fails loudly (fail-fast), not treated as a conflict. + +Full suite green after each round; installed build (scratch prefix) re-verified on the final +code: issue's commands up to date in both modes; edits kept as conflicts; in-block edit is a +block refresh; renamed checkout plus a CRLF doc is up to date. diff --git a/packages/codev/src/__tests__/bugfix-1982-update-root-docs.test.ts b/packages/codev/src/__tests__/bugfix-1982-update-root-docs.test.ts new file mode 100644 index 000000000..e32c1ce79 --- /dev/null +++ b/packages/codev/src/__tests__/bugfix-1982-update-root-docs.test.ts @@ -0,0 +1,264 @@ +/** + * Issue #1982 — `codev update` reported CLAUDE.md and AGENTS.md as conflicts on a project + * nobody had edited, and wrote `.codev-new` copies byte-identical to them: `copyRootFiles` + * treated any existing root doc as a conflict, comparing nothing. Its `--dry-run` also + * printed hot-tier, cold-tier and managed-block lines the real run did not. + * + * A root doc is now compared with the template as the managed-block refresh would leave + * both; and a dry run computes the same result as the real run, writing nothing. + */ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { init } from '../commands/init.js'; +import { update, type UpdateResult } from '../commands/update.js'; +import { HOT_BLOCK_BEGIN, HOT_BLOCK_END } from '../lib/managed-block.js'; + +// init shells out to `git init` and `codev doctor`; neither bears on the files compared here. +vi.mock('node:child_process', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + execSync: vi.fn((command: string, options?: object) => { + if (command === 'git init' || command === 'codev doctor') return Buffer.from(''); + return actual.execSync(command, options); + }), + }; +}); + +vi.mock('chalk', () => { + const plain = () => (s: string) => s; + return { + default: { + bold: plain(), + green: Object.assign(plain(), { bold: plain() }), + yellow: plain(), + red: plain(), + blue: plain(), + dim: plain(), + cyan: plain(), + }, + }; +}); + +const ROOT_DOCS = ['CLAUDE.md', 'AGENTS.md']; + +function codevNewFiles(dir: string): string[] { + const found: string[] = []; + const walk = (current: string): void => { + for (const entry of fs.readdirSync(current, { withFileTypes: true })) { + const full = path.join(current, entry.name); + if (entry.isDirectory()) walk(full); + else if (entry.name.endsWith('.codev-new')) found.push(path.relative(dir, full)); + } + }; + walk(dir); + return found.sort(); +} + +describe('issue #1982 — codev update on root docs', () => { + let originalCwd: string; + let baseDir: string; + let projectDir: string; + let logged: string[]; + + const read = (rel: string): string => fs.readFileSync(path.join(projectDir, rel), 'utf-8'); + const write = (rel: string, content: string): void => fs.writeFileSync(path.join(projectDir, rel), content); + + /** Run update in agent mode and return its result with the lines it logged. */ + async function runUpdate(options: { dryRun?: boolean } = {}): Promise<{ result: UpdateResult; report: string[] }> { + logged = []; + const result = await update({ agent: true, ...options }); + expect(result.error).toBeUndefined(); + return { result, report: logged }; + } + + beforeEach(async () => { + originalCwd = process.cwd(); + baseDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bugfix-1982-')); + logged = []; + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => { + logged.push(args.join(' ')); + }); + process.chdir(baseDir); + await init('fresh', { yes: true }); + projectDir = path.join(baseDir, 'fresh'); + process.chdir(projectDir); + }); + + afterEach(() => { + process.chdir(originalCwd); + vi.restoreAllMocks(); + fs.rmSync(baseDir, { recursive: true, force: true }); + }); + + it('init then update on an untouched project: zero conflicts, zero .codev-new, docs unchanged', async () => { + const before = ROOT_DOCS.map(read); + + const { result, report } = await runUpdate(); + + expect(result.rootConflicts).toEqual([]); + expect(result.conflicts).toEqual([]); + expect(codevNewFiles(projectDir)).toEqual([]); + expect(ROOT_DOCS.map(read)).toEqual(before); + expect(report).toContain(' Already up to date!'); + }); + + it('an edit outside the managed block is one conflict, and the edit is kept', async () => { + const template = read('CLAUDE.md'); + const edited = `${template}\n## Our house rules\n\nMY_RULE\n`; + write('CLAUDE.md', edited); + + const { result } = await runUpdate(); + + expect(result.rootConflicts.map((c) => c.file)).toEqual(['CLAUDE.md']); + expect(result.conflicts).toEqual([]); + expect(read('CLAUDE.md')).toBe(edited); + expect(read('CLAUDE.md.codev-new')).toBe(template); + expect(codevNewFiles(projectDir)).toEqual(['CLAUDE.md.codev-new']); + }); + + it('an edit inside the managed block is regenerated and reported as a block refresh, never a conflict', async () => { + const template = read('CLAUDE.md'); + write('CLAUDE.md', template.replace(HOT_BLOCK_END, `MY_LINE_INSIDE_THE_BLOCK\n${HOT_BLOCK_END}`)); + + const { result, report } = await runUpdate(); + + expect(result.rootConflicts).toEqual([]); + expect(codevNewFiles(projectDir)).toEqual([]); + expect(read('CLAUDE.md')).toBe(template); + expect(report).toContain(' ~ (hot-tier block refreshed) CLAUDE.md'); + }); + + it('a doc whose managed block is missing altogether is not a conflict; the block is put back', async () => { + const template = read('AGENTS.md'); + const begin = template.indexOf(HOT_BLOCK_BEGIN); + const end = template.indexOf(HOT_BLOCK_END) + HOT_BLOCK_END.length; + // The block and the blank line after it, as in a doc written before Spec 987. + write('AGENTS.md', template.slice(0, begin) + template.slice(end + 2)); + + const { result, report } = await runUpdate(); + + expect(result.rootConflicts).toEqual([]); + expect(codevNewFiles(projectDir)).toEqual([]); + expect(read('AGENTS.md')).toBe(template); + expect(report).toContain(' ~ (hot-tier block refreshed) AGENTS.md'); + }); + + it('removes a leftover .codev-new that holds exactly the template, beside an up-to-date doc', async () => { + const template = read('CLAUDE.md'); + write('CLAUDE.md.codev-new', template); + write('AGENTS.md.codev-new', 'an earlier version, not yet merged\n'); + + const { result, report } = await runUpdate(); + + expect(result.rootConflicts).toEqual([]); + expect(codevNewFiles(projectDir)).toEqual(['AGENTS.md.codev-new']); + expect(read('AGENTS.md.codev-new')).toBe('an earlier version, not yet merged\n'); + expect(report).toContain(' - (removed, nothing left to merge) CLAUDE.md.codev-new'); + }); + + it('a checkout whose directory is not the name init saw is still up to date; its leftover is resolved', async () => { + const before = ROOT_DOCS.map(read); + // A leftover this bug wrote while the checkout still had init's name. + write('CLAUDE.md.codev-new', before[0]); + process.chdir(baseDir); + const renamed = path.join(baseDir, 'cloned-elsewhere'); + fs.renameSync(projectDir, renamed); + projectDir = renamed; + process.chdir(projectDir); + + const { result } = await runUpdate(); + + expect(result.rootConflicts).toEqual([]); + expect(codevNewFiles(projectDir)).toEqual([]); + expect(ROOT_DOCS.map(read)).toEqual(before); + }); + + it('a CRLF checkout of an unedited doc is up to date', async () => { + const crlf = read('CLAUDE.md').replace(/\n/g, '\r\n'); + write('CLAUDE.md', crlf); + + const { result } = await runUpdate(); + + expect(result.rootConflicts).toEqual([]); + expect(codevNewFiles(projectDir)).toEqual([]); + }); + + it('an edited skill is still kept, with its new version as .codev-new beside it', async () => { + const skill = path.join('.claude', 'skills', 'arch-init', 'SKILL.md'); + const shipped = read(skill); + const edited = `${shipped}\nMY_SKILL_NOTE\n`; + write(skill, edited); + + const { result } = await runUpdate(); + + expect(result.rootConflicts).toEqual([]); + expect(result.conflicts.map((c) => c.file)).toEqual([skill.split(path.sep).join('/')]); + expect(read(skill)).toBe(edited); + expect(read(`${skill}.codev-new`)).toBe(shipped); + }); + + // Known limit, decided out of scope for #1982: root docs carry no record of the version + // a release installed (skills have SHIPPED_SKILL_HASHES), so a doc an adopter never + // edited, written by an older release whose template has since changed outside the + // managed block, cannot be told from an edit. It stays a conflict and the doc is kept. + it('known limit: an unedited doc from an older template that changed outside the block is still a conflict', async () => { + const current = read('CLAUDE.md'); + const lastSection = current.lastIndexOf('\n## '); + expect(lastSection).toBeGreaterThan(current.indexOf(HOT_BLOCK_END)); + // The older release's template: the current one before its last section was added. + const olderTemplate = `${current.slice(0, lastSection)}\n`; + write('CLAUDE.md', olderTemplate); + + const { result } = await runUpdate(); + + expect(result.rootConflicts.map((c) => c.file)).toEqual(['CLAUDE.md']); + expect(read('CLAUDE.md')).toBe(olderTemplate); + expect(read('CLAUDE.md.codev-new')).toBe(current); + }); + + describe('--dry-run reports exactly what the real run then does, on the same project', () => { + const DRY_RUN_FOOTER = ['', 'Dry run complete. Run without --dry-run to apply changes.']; + + /** The report with its dry-run-only lines dropped and its preview wording made plain. */ + const asRealRun = (report: string[]): string[] => { + expect(report.slice(-DRY_RUN_FOOTER.length)).toEqual(DRY_RUN_FOOTER); + return report + .slice(0, -DRY_RUN_FOOTER.length) + .filter((line) => line !== '(dry run - no files will be changed)') + .map((line) => line.replace(/would be /g, '')); + }; + + const scenarios: Array<[string, () => void]> = [ + ['an untouched project', () => {}], + ['a project edited outside and inside the managed block', () => { + write('CLAUDE.md', `${read('CLAUDE.md')}\nMY_RULE\n`); + write('AGENTS.md', read('AGENTS.md').replace(HOT_BLOCK_END, `MY_LINE\n${HOT_BLOCK_END}`)); + }], + ['a project with a leftover .codev-new beside an up-to-date doc', () => { + write('CLAUDE.md.codev-new', read('CLAUDE.md')); + }], + ['a project missing one hot file, the cold files and AGENTS.md', () => { + fs.rmSync(path.join(projectDir, 'codev', 'resources', 'lessons-critical.md')); + fs.rmSync(path.join(projectDir, 'codev', 'resources', 'arch.md')); + fs.rmSync(path.join(projectDir, 'codev', 'resources', 'lessons-learned.md')); + fs.rmSync(path.join(projectDir, 'AGENTS.md')); + }], + ]; + + it.each(scenarios)('%s', async (_name, prepare) => { + prepare(); + + const dry = await runUpdate({ dryRun: true }); + const real = await runUpdate(); + + expect(asRealRun(dry.report)).toEqual(real.report); + for (const key of ['newFiles', 'updated', 'conflicts', 'rootConflicts'] as const) { + expect(dry.result[key], key).toEqual(real.result[key]); + } + }); + }); +}); diff --git a/packages/codev/src/commands/adopt.ts b/packages/codev/src/commands/adopt.ts index 53107a58b..6971d96b3 100644 --- a/packages/codev/src/commands/adopt.ts +++ b/packages/codev/src/commands/adopt.ts @@ -183,6 +183,9 @@ export async function adopt(options: AdoptOptions = {}, overrides: Partial = * that with Claude Code `@import` lines so the hot files stay the single source of * truth — no copy to drift. Claude Code expands `@path` imports into context at * session launch (always-on, transcluded — not lazy), giving the same guarantee as - * inlining minus the drift footgun. A line is emitted only if its hot file is on disk. + * inlining minus the drift footgun. A line is emitted only if its hot file is on disk, or + * is in `pendingHotFiles`: hot files a dry run would have created by now (#1982). */ -export function renderHotContextBlock(workspaceRoot: string): string { +export function renderHotContextBlock(workspaceRoot: string, pendingHotFiles: readonly string[] = []): string { const imports = HOT_IMPORTS - .filter((h) => fs.existsSync(path.join(workspaceRoot, h.diskRelPath))) + .filter((h) => pendingHotFiles.includes(h.diskRelPath) || fs.existsSync(path.join(workspaceRoot, h.diskRelPath))) .map((h) => h.importLine); if (imports.length === 0) return ''; return [ @@ -116,14 +117,37 @@ export function upsertHotContextBlock(docContent: string, block: string): string return `${head}\n\n${block}\n${tail}`; } +/** + * A root doc as the block refresh leaves it, with the block emptied (#1982). The block is + * regenerated from the hot files on every update, so what sits inside it, or whether it + * is there at all, is never the adopter's edit: two docs in this form differ only where + * they differ outside the block. + */ +export function withEmptyHotBlock(doc: string): string { + return upsertHotContextBlock(doc, `${HOT_BLOCK_BEGIN}\n${HOT_BLOCK_END}`); +} + +export interface SyncHotContextOptions { + /** Report the docs that would change, writing nothing. */ + dryRun?: boolean; + /** Hot files (workspace-relative) a dry run would have created by now. */ + pendingHotFiles?: readonly string[]; +} + /** * Write/refresh the managed block in CLAUDE.md and AGENTS.md under `targetDir`, * resolving hot files from `workspaceRoot` (four-tier). Non-clobbering: only the * managed block changes. A root doc that doesn't exist is skipped (init/adopt - * create them via copyRootFiles first). Returns the names of the files changed. + * create them via copyRootFiles first). Returns the names of the files changed, or + * under `dryRun` the names that would change. */ -export function syncHotContextBlock(targetDir: string, workspaceRoot: string = targetDir): string[] { - const block = renderHotContextBlock(workspaceRoot); +export function syncHotContextBlock( + targetDir: string, + workspaceRoot: string = targetDir, + options: SyncHotContextOptions = {}, +): string[] { + const { dryRun = false, pendingHotFiles = [] } = options; + const block = renderHotContextBlock(workspaceRoot, pendingHotFiles); if (block === '') return []; const changed: string[] = []; @@ -133,7 +157,7 @@ export function syncHotContextBlock(targetDir: string, workspaceRoot: string = t const before = fs.readFileSync(p, 'utf-8'); const after = upsertHotContextBlock(before, block); if (after !== before) { - fs.writeFileSync(p, after); + if (!dryRun) fs.writeFileSync(p, after); changed.push(name); } } diff --git a/packages/codev/src/lib/scaffold.ts b/packages/codev/src/lib/scaffold.ts index cc8308abc..e94b719d1 100644 --- a/packages/codev/src/lib/scaffold.ts +++ b/packages/codev/src/lib/scaffold.ts @@ -8,6 +8,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { isEmptySkillDir } from './skill-refresh.js'; +import { withEmptyHotBlock } from './managed-block.js'; interface CreateUserDirsOptions { skipExisting?: boolean; @@ -145,6 +146,11 @@ export function copyResourceTemplates( return { copied, skipped }; } +interface CopyTierDefaultsOptions extends CopyResourceTemplatesOptions { + /** Report what would be copied, writing nothing (#1982). */ + dryRun?: boolean; +} + /** The capped hot-tier files materialized into a project's codev/resources/ (Spec 987). */ export const HOT_TIER_FILES = ['arch-critical.md', 'lessons-critical.md'] as const; @@ -162,14 +168,14 @@ export const HOT_TIER_FILES = ['arch-critical.md', 'lessons-critical.md'] as con export function copyHotTierDefaults( targetDir: string, skeletonDir: string, - options: CopyResourceTemplatesOptions = {} + options: CopyTierDefaultsOptions = {} ): CopyResourceTemplatesResult { - const { skipExisting = false } = options; + const { skipExisting = false, dryRun = false } = options; const resourcesDir = path.join(targetDir, 'codev', 'resources'); const copied: string[] = []; const skipped: string[] = []; - if (!fs.existsSync(resourcesDir)) { + if (!dryRun && !fs.existsSync(resourcesDir)) { fs.mkdirSync(resourcesDir, { recursive: true }); } @@ -182,7 +188,7 @@ export function copyHotTierDefaults( continue; } if (fs.existsSync(srcPath)) { - fs.copyFileSync(srcPath, destPath); + if (!dryRun) fs.copyFileSync(srcPath, destPath); copied.push(file); } } @@ -218,14 +224,14 @@ export const COLD_TIER_FILES = [ export function copyColdTierDefaults( targetDir: string, skeletonDir: string, - options: CopyResourceTemplatesOptions = {} + options: CopyTierDefaultsOptions = {} ): CopyResourceTemplatesResult { - const { skipExisting = false } = options; + const { skipExisting = false, dryRun = false } = options; const resourcesDir = path.join(targetDir, 'codev', 'resources'); const copied: string[] = []; const skipped: string[] = []; - if (!fs.existsSync(resourcesDir)) { + if (!dryRun && !fs.existsSync(resourcesDir)) { fs.mkdirSync(resourcesDir, { recursive: true }); } @@ -238,7 +244,7 @@ export function copyColdTierDefaults( continue; } if (fs.existsSync(srcPath)) { - fs.copyFileSync(srcPath, destPath); + if (!dryRun) fs.copyFileSync(srcPath, destPath); copied.push(dest); } } @@ -257,6 +263,8 @@ interface CopyRootFilesResult { conflicts: string[]; /** Root files left alone because the path to write is a symlink or otherwise irregular. */ notRegular: string[]; + /** Pending `.codev-new` copies removed (or, under `dryRun`, to remove): nothing left to merge. */ + resolved: string[]; } /** Something other than a regular file sits at `p` (a symlink, dangling or not; a directory). */ @@ -268,8 +276,28 @@ function isIrregularPath(p: string): boolean { } } +const PROJECT_NAME_PLACEHOLDER = '{{PROJECT_NAME}}'; + +/** + * A root doc the adopter never edited: a regular file that matches the template outside + * the managed block, whatever project name it was written with and in either line ending. + * A checkout's directory need not carry the name `init` saw (the name is all the template + * varies by), and a Windows checkout may turn LF into CRLF, as skills already allow for. + */ +function matchesTemplate(filePath: string, template: string): boolean { + if (!fs.statSync(filePath).isFile()) return false; + const pattern = withEmptyHotBlock(template.replace(/\r\n/g, '\n')) + .split(PROJECT_NAME_PLACEHOLDER) + .map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) + .join('[^\\n]*'); + const doc = fs.readFileSync(filePath, 'utf-8').replace(/\r\n/g, '\n'); + return new RegExp(`^${pattern}$`).test(withEmptyHotBlock(doc)); +} + /** - * Copy root files (CLAUDE.md, AGENTS.md) with project name substitution + * Copy root files (CLAUDE.md, AGENTS.md) with project name substitution. With + * `handleConflicts`, an existing doc that differs from the template outside the managed + * block keeps its content and gets the template beside it as `.codev-new`. */ export function copyRootFiles( targetDir: string, @@ -281,6 +309,7 @@ export function copyRootFiles( const copied: string[] = []; const conflicts: string[] = []; const notRegular: string[] = []; + const resolved: string[] = []; const rootFiles = ['CLAUDE.md', 'AGENTS.md']; for (const file of rootFiles) { @@ -291,8 +320,8 @@ export function copyRootFiles( continue; } - const content = fs.readFileSync(srcPath, 'utf-8') - .replace(/\{\{PROJECT_NAME\}\}/g, projectName); + const template = fs.readFileSync(srcPath, 'utf-8'); + const content = template.replace(/\{\{PROJECT_NAME\}\}/g, projectName); // Never write through a symlink, which may point outside the project: not the // `.codev-new` copy, and not a dangling link where a missing file would be created. A @@ -306,7 +335,15 @@ export function copyRootFiles( } if (fs.existsSync(destPath)) { - if (handleConflicts) { + if (handleConflicts && matchesTemplate(destPath, template)) { + // Up to date: the managed block is refreshed by syncHotContextBlock (#1982). A pending + // copy that is the template too leaves nothing to merge (a symlinked one was skipped above). + const pendingPath = destPath + '.codev-new'; + if (fs.existsSync(pendingPath) && matchesTemplate(pendingPath, template)) { + if (!dryRun) fs.rmSync(pendingPath); + resolved.push(file + '.codev-new'); + } + } else if (handleConflicts) { // Create .codev-new for merge if (!dryRun) fs.writeFileSync(destPath + '.codev-new', content); conflicts.push(file); @@ -318,7 +355,7 @@ export function copyRootFiles( } } - return { copied, conflicts, notRegular }; + return { copied, conflicts, notRegular, resolved }; } interface CreateProjectsDirOptions {