@yeison.restrepo.r/code-conductor 1.34.3 → 1.34.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,9 +12,11 @@
12
12
 
13
13
  Three commands, from nothing to a guarded session. The output below is **real**, captured by running exactly these commands in a scratch directory.
14
14
 
15
+ **Minimum safe version: `1.34.4`.** Older versions can strip or damage an existing `CLAUDE.md`: every release before `1.24` overwrote it with no backup, `1.24` through `1.34.3` silently removed your sections whose headings matched the managed block's, and an older pre-sentinel version left at least one field file with damaged lines. Install with `@latest`, as below.
16
+
15
17
  ```bash
16
18
  mkdir demo && cd demo && git init -q && npm init -y >/dev/null
17
- npx @yeison.restrepo.r/code-conductor --project
19
+ npx @yeison.restrepo.r/code-conductor@latest --project
18
20
  ```
19
21
 
20
22
  The installer prints **nothing** and exits 0. That silence is deliberate and is asserted by a test: the stub-detection check runs *before* the seed, so a fresh scaffold cannot warn about the file it was just given (`tests/installer/deploy.test.js`, "says nothing on a fresh scaffold, whose stub it just wrote").
@@ -135,8 +137,10 @@ AI coding assistants are only as good as the structure you put around them. With
135
137
 
136
138
  ## Install
137
139
 
140
+ **Minimum safe version: `1.34.4`.** Older versions can strip or damage an existing `CLAUDE.md`: every release before `1.24` overwrote it with no backup, `1.24` through `1.34.3` silently removed your sections whose headings matched the managed block's, and an older pre-sentinel version left at least one field file with damaged lines. Install with `@latest`, as below.
141
+
138
142
  ```bash
139
- npx @yeison.restrepo.r/code-conductor # one-shot global setup
143
+ npx @yeison.restrepo.r/code-conductor@latest # one-shot global setup
140
144
  # or
141
145
  npm install -g @yeison.restrepo.r/code-conductor && code-conductor
142
146
  ```
@@ -421,15 +425,24 @@ code-conductor/
421
425
 
422
426
  ## .gitignore Note
423
427
 
424
- When installed with `--project`, the installer appends these rules to your project's
425
- `.gitignore`, and only the ones you are missing — your own entries are never touched:
428
+ When installed with `--project`, the installer keeps its rules in one labelled block in
429
+ your project's `.gitignore`:
426
430
 
427
431
  ```
432
+ # Code Conductor (added by the installer; safe to keep)
428
433
  .claude/memory/turn-count.txt
429
434
  *.installer-backup.*
430
435
  *.installer-tmp.*
431
436
  ```
432
437
 
438
+ The block ends at the first blank line. Your own lines are never edited. A line that is
439
+ exactly one of these three rules (earlier versions appended them one at a time) is moved
440
+ into the block, so each rule appears once; a line you changed, such as
441
+ `/.claude/memory/turn-count.txt`, is not an exact match and stays where it is. If your
442
+ `.gitignore` has any `!` line, nothing is moved, because moving a rule past a `!` can
443
+ change what is ignored: the block then holds only the rules you lack, and the installer
444
+ says so. A change to `.gitignore` is backed up and reported exactly as for `CLAUDE.md`.
445
+
433
446
  The last two keep the installer's own backups and crash-stranded temp files out of
434
447
  `git status`. The rules ship inside the package as `project-template/gitignore`
435
448
  (no leading dot) because npm strips any file literally named `.gitignore` from every
@@ -442,28 +455,34 @@ published tarball; the installer restores the dot when it writes to your project
442
455
  `CLAUDE.md` and `.gitignore` are **merged**, never overwritten. Everything else the
443
456
  installer ships (`settings.json`, hooks, commands, `scripts/`) is replaced on every run.
444
457
 
445
- - **Managed sections** live between `<!-- cc:managed:start -->` and `<!-- cc:managed:end -->`.
446
- Code Conductor owns that block and replaces its contents wholesale on every upgrade, so
447
- released improvements reach existing installs. Edits inside the block are lost.
448
- - **Everything outside the block is yours.** Existing sections are preserved byte-for-byte;
449
- sections the template has and your file lacks are appended once, immediately above the
450
- managed block. Sections you wrote that the template has never heard of are never touched.
458
+ - **Code Conductor owns one block and nothing else.** Its content lives between
459
+ `<!-- cc:managed:start -->` and `<!-- cc:managed:end -->`, and those two markers alone
460
+ decide ownership; a heading's name never does. Every upgrade replaces the block's
461
+ contents wholesale, so released improvements reach existing installs. Edits inside the
462
+ block are lost, and recoverable from the backup.
463
+ - **Everything outside the block is yours, byte for byte.** Nothing outside it is
464
+ removed, rewritten, reordered or added.
465
+ - **A file without the markers gets the block appended at the end**, after one blank
466
+ line and in your file's line endings, and nothing else changes. If your file already
467
+ has sections named like the block's (`## Agent Identity`, `## Hard Constraints`, …),
468
+ you will see both: yours above, Code Conductor's inside the block. That is deliberate.
469
+ The installer never decides which of your sections are really its own; reconciling
470
+ them is planned for `/cc-stack` as `[FEAT-040]`.
451
471
  - **Before any change, the installer copies your file to
452
- `CLAUDE.md.installer-backup.<UTC timestamp>`** and keeps the five most recent.
453
-
454
- > **One-time migration on your first 1.24 install.** If your `CLAUDE.md` predates the
455
- > sentinel markers and already contains sections that the managed block also defines
456
- > (`## Agent Identity`, `## Hard Constraints`, …), **those sections are removed** and
457
- > replaced by the managed block, so you do not end up with two copies of each. This is the
458
- > only path that discards content you wrote. **Your pre-migration file is preserved in the
459
- > `.installer-backup.` copy beside it** — diff it after upgrading and move anything you
460
- > want to keep into a section outside the managed block.
461
-
462
- > **A cosmetic wart of that same migration, in `~/.claude/CLAUDE.md` only.** The managed
463
- > block carries the file's intro sentence ("Applies to every project on this machine…"),
464
- > and your pre-sentinel copy keeps its own above the block, so you will see that one
465
- > sentence twice after the first upgrade. Delete the copy above the block — it is outside
466
- > the managed region, so your deletion sticks.
472
+ `CLAUDE.md.installer-backup.<UTC timestamp>`**, keeps the five most recent, and prints
473
+ where it put it:
474
+
475
+ ```
476
+ code-conductor: backed up CLAUDE.md to CLAUDE.md.installer-backup.20260930T120000Z before merging (git-ignored by design)
477
+ ```
478
+
479
+ Backups are git-ignored so nobody commits one by accident and they stay out of every
480
+ teammate's `git status`; the printed line is how you find yours. A fresh install, and a
481
+ re-run that changes nothing, print nothing.
482
+
483
+ The same rules apply to `~/.claude/CLAUDE.md`, whose backup line names the `~/.claude/`
484
+ path. If your file ends inside a code fence that is never closed, the installer leaves it
485
+ untouched with a warning, because a block appended there would be hidden inside the fence.
467
486
 
468
487
  If the markers in your file are damaged — a `start` with no `end`, two blocks, an `end`
469
488
  before its `start` — the installer prints a warning, leaves the file completely untouched,
@@ -91,7 +91,7 @@ export function run(argv, env = process.env, { cwd = process.cwd(), log } = {})
91
91
  assertAssets(assetRoot, ['global', 'skills', 'scripts', 'project-template']); // pre-flight
92
92
  assertMergeTargets(home, cwd, opts.project); // pre-flight
93
93
  writing = true; // copy phase begins
94
- const claudeDir = deployGlobal(assetRoot, home);
94
+ const claudeDir = deployGlobal(assetRoot, home, { warn: (m) => emit('stderr', m), report: (m) => emit('stdout', m) });
95
95
  chmodHooks(claudeDir);
96
96
  const v = writeVerbosity(home, assetRoot, opts.verbosity, opts.verbosityGiven);
97
97
  if (v.warn) emit('stderr', v.warn);
@@ -101,7 +101,7 @@ export function run(argv, env = process.env, { cwd = process.cwd(), log } = {})
101
101
  if (heal.status === 'removed') emit('stdout', 'code-conductor: removed the retired graphify-ast-refresh hook from settings.json (backup written beside it)');
102
102
  for (const line of heal.lines) emit('stderr', `code-conductor: ${line}`);
103
103
  writeVersionFile(home, pkgVersion(assetRoot));
104
- if (opts.project) deployProject(assetRoot, cwd, { warn: (m) => emit('stderr', m) });
104
+ if (opts.project) deployProject(assetRoot, cwd, { warn: (m) => emit('stderr', m), report: (m) => emit('stdout', m) });
105
105
  return 0;
106
106
  } catch (err) {
107
107
  // Pre-flight failures (nothing written yet) → exit 1.
@@ -1,7 +1,7 @@
1
1
  import { cpSync, mkdirSync, chmodSync, existsSync, lstatSync, readdirSync, readFileSync, statSync, rmSync, unlinkSync } from 'node:fs';
2
- import { join } from 'node:path';
2
+ import { join, relative, isAbsolute, sep } from 'node:path';
3
3
  import { mergeFileInto, resolveRealTarget } from './file-merge.mjs';
4
- import { mergeClaudeMdText, appendMissingLinesText } from './merge-md.mjs';
4
+ import { mergeClaudeMdText, mergeGitignoreText } from './merge-md.mjs';
5
5
  import { GLOBAL_HOST_OWNED, PROJECT_HOST_OWNED, GLOBAL_SETTINGS_FINGERPRINTS, PROJECT_SETTINGS_FINGERPRINTS, hostOwnedFilter, seedHostOwned } from './host-owned.mjs';
6
6
  import { mergeSettingsFile } from './settings-merge.mjs';
7
7
 
@@ -14,7 +14,7 @@ import { mergeSettingsFile } from './settings-merge.mjs';
14
14
  // target name instead would let cpSync drop a stray `gitignore` at the project root.
15
15
  const MERGED_ROOT_FILES = new Map([
16
16
  ['CLAUDE.md', { target: 'CLAUDE.md', merge: mergeClaudeMdText }],
17
- ['gitignore', { target: '.gitignore', merge: appendMissingLinesText }],
17
+ ['gitignore', { target: '.gitignore', merge: mergeGitignoreText }],
18
18
  ]);
19
19
 
20
20
  // Verified at plan time: `find global skills project-template -type l` returns
@@ -24,6 +24,22 @@ const MERGED_ROOT_FILES = new Map([
24
24
  // later is copied as a link (never followed into user content), not resolved.
25
25
  const CP_OPTS = { recursive: true, force: true, dereference: false };
26
26
 
27
+ // One stdout line per backup, because the backup is git-ignored by the managed
28
+ // block and would otherwise be invisible (BUG-049). A backup outside `root` (a
29
+ // symlinked target resolved into a dotfiles checkout) prints absolute, and only a
30
+ // backup inside a --project root claims the ignore rule covers it.
31
+ function backupReporter(report, { root, rootLabel, file, ignoredByDesign }) {
32
+ return (backupPath) => {
33
+ const rel = relative(root, backupPath);
34
+ const inside = rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
35
+ const shown = inside ? rootLabel + rel.split(sep).join('/') : backupPath;
36
+ const suffix = inside && ignoredByDesign ? ' (git-ignored by design)' : '';
37
+ report(`code-conductor: backed up ${rootLabel}${file} to ${shown} before merging${suffix}`);
38
+ };
39
+ }
40
+ const toStdout = (m) => process.stdout.write(`${m}\n`);
41
+ const toStderr = (m) => process.stderr.write(`${m}\n`);
42
+
27
43
  // Pure guard: throws ONLY, emits nothing. It does not write a stderr diagnostic
28
44
  // before throwing — run() surfaces the error's message exactly once
29
45
  // (`code-conductor: missing bundled asset dir: <path>`), so warning here too would
@@ -92,12 +108,15 @@ export function assertMergeTargets(home, cwd, project) {
92
108
  }
93
109
  }
94
110
 
95
- export function deployGlobal(assetRoot, home) {
111
+ export function deployGlobal(assetRoot, home, { warn = toStderr, report = toStdout } = {}) {
96
112
  const target = join(home, '.claude');
97
113
  const globalDir = join(assetRoot, 'global');
98
114
  mkdirSync(target, { recursive: true });
99
115
  cpSync(globalDir, target, { ...CP_OPTS, filter: hostOwnedFilter(globalDir, GLOBAL_HOST_OWNED) });
100
- mergeFileInto(join(globalDir, 'CLAUDE.md'), join(target, 'CLAUDE.md'), mergeClaudeMdText);
116
+ mergeFileInto(join(globalDir, 'CLAUDE.md'), join(target, 'CLAUDE.md'), mergeClaudeMdText, {
117
+ warn,
118
+ onBackup: backupReporter(report, { root: target, rootLabel: '~/.claude/', file: 'CLAUDE.md', ignoredByDesign: false }),
119
+ });
101
120
  const skillsDir = join(target, 'skills');
102
121
  unblockSkillPaths(assetRoot, skillsDir);
103
122
  cpSync(join(assetRoot, 'skills'), skillsDir, CP_OPTS);
@@ -149,8 +168,8 @@ function warnIfProjectMemoryIsStub(templateClaude, target, emit) {
149
168
  return true;
150
169
  }
151
170
 
152
- export function deployProject(assetRoot, cwd, { warn } = {}) {
153
- const emit = warn || ((m) => process.stderr.write(`${m}\n`));
171
+ export function deployProject(assetRoot, cwd, { warn = toStderr, report = toStdout } = {}) {
172
+ const emit = warn;
154
173
  const target = join(cwd, '.claude');
155
174
  const templateRoot = join(assetRoot, 'project-template');
156
175
  // If something already occupies ./.claude and it is NOT a directory, this is a
@@ -172,7 +191,10 @@ export function deployProject(assetRoot, cwd, { warn } = {}) {
172
191
  cpSync(join(templateRoot, name), join(cwd, name), CP_OPTS);
173
192
  }
174
193
  for (const [source, { target: dest, merge }] of MERGED_ROOT_FILES) {
175
- mergeFileInto(join(templateRoot, source), join(cwd, dest), merge);
194
+ mergeFileInto(join(templateRoot, source), join(cwd, dest), merge, {
195
+ warn: emit,
196
+ onBackup: backupReporter(report, { root: cwd, rootLabel: '', file: dest, ignoredByDesign: true }),
197
+ });
176
198
  }
177
199
  // BEFORE the seed on purpose: running it after would make every fresh
178
200
  // scaffold warn about the stub it was just given.
@@ -6,6 +6,10 @@ import { utcStamp, pruneBackups } from './settings.mjs';
6
6
 
7
7
  const BACKUP_SUFFIX = '.installer-backup.';
8
8
  const MAX_BACKUPS = 5;
9
+ // Advice per warning code; the default fits every sentinel-count warning.
10
+ const WARNING_ADVICE = {
11
+ CLAUDE_MD_UNCLOSED_FENCE: 'close the code fence that runs to the end of the file and re-run',
12
+ };
9
13
 
10
14
  // Symlinked CLAUDE.md into a dotfiles repo is a legitimate setup, so the writer
11
15
  // works on the RESOLVED path: renameSync over the link itself would replace it
@@ -27,7 +31,9 @@ export function backupFile(realPath, now = new Date()) {
27
31
  let dst = base;
28
32
  for (let i = 1; existsSync(dst); i++) dst = `${base}-${i}`;
29
33
  copyFileSync(realPath, dst);
30
- pruneBackups(realPath, BACKUP_SUFFIX, MAX_BACKUPS);
34
+ // Retention is best effort: once the copy exists, a failed prune must not make the
35
+ // caller report "could not back it up" for a backup that is sitting on disk.
36
+ try { pruneBackups(realPath, BACKUP_SUFFIX, MAX_BACKUPS); } catch { /* best effort */ }
31
37
  return dst;
32
38
  }
33
39
 
@@ -44,7 +50,7 @@ export function writeAtomic(realPath, text) {
44
50
  }
45
51
  }
46
52
 
47
- export function mergeFileInto(templatePath, targetPath, mergeFn, { now = new Date(), warn } = {}) {
53
+ export function mergeFileInto(templatePath, targetPath, mergeFn, { now = new Date(), warn, onBackup } = {}) {
48
54
  const emit = warn || ((m) => process.stderr.write(`${m}\n`));
49
55
  const target = resolveRealTarget(targetPath);
50
56
  if (target.isDir) {
@@ -73,15 +79,32 @@ export function mergeFileInto(templatePath, targetPath, mergeFn, { now = new Dat
73
79
  return 'created';
74
80
  }
75
81
  const hostText = readFileSync(target.realPath, 'utf8');
76
- const { text, changed, warning } = mergeFn(templateText, hostText);
82
+ const { text, changed, warning, notice } = mergeFn(templateText, hostText);
77
83
  if (warning) {
78
- emit(`code-conductor: skipping ${targetPath} — ${warning}; fix the cc:managed markers and re-run`);
84
+ emit(`code-conductor: skipping ${targetPath} — ${warning}; ${WARNING_ADVICE[warning] || 'fix the cc:managed markers and re-run'}`);
79
85
  return 'skipped-warning';
80
86
  }
81
87
  if (!changed) return 'unchanged';
82
- // Backup BEFORE the rewrite and let a backup/prune failure propagate: an
83
- // unrecoverable overwrite is worse than a failed install.
84
- if (hostText.trim() !== '') backupFile(target.realPath, now);
85
- writeAtomic(target.realPath, text);
88
+ const status = backupThenWrite(target.realPath, targetPath, text, hostText.trim() !== '', { now, emit, onBackup });
89
+ if (status === 'merged' && notice) emit(`code-conductor: ${notice}`);
90
+ return status;
91
+ }
92
+
93
+ // Backup first, and a failed backup stops the write: an unrecoverable overwrite is
94
+ // worse than a skipped file. The path is reported the moment the copy exists, so the
95
+ // person running the installer learns where it is even if the write then fails.
96
+ function backupThenWrite(realPath, targetPath, text, needsBackup, { now, emit, onBackup }) {
97
+ let backup = null;
98
+ if (needsBackup) {
99
+ try { backup = backupFile(realPath, now); } catch (err) {
100
+ emit(`code-conductor: skipping ${targetPath} — could not back it up (${err.code || err.message}); nothing was written`);
101
+ return 'skipped-backup-failed';
102
+ }
103
+ if (onBackup) onBackup(backup);
104
+ }
105
+ try { writeAtomic(realPath, text); } catch (err) {
106
+ emit(`code-conductor: could not write ${targetPath} (${err.code || err.message}); it is unchanged${backup ? `, and its backup is ${backup}` : ''}`);
107
+ return 'write-failed';
108
+ }
86
109
  return 'merged';
87
110
  }
@@ -5,6 +5,10 @@
5
5
 
6
6
  export const SENTINEL_START = '<!-- cc:managed:start -->';
7
7
  export const SENTINEL_END = '<!-- cc:managed:end -->';
8
+ // Opens the installer's labelled block in a host .gitignore. The shipped template
9
+ // starts with it (templates.test.js) and the merge finds the block by it.
10
+ export const GITIGNORE_HEADER = '# Code Conductor (added by the installer; safe to keep)';
11
+ const NEGATION_NOTICE = 'left the existing Code Conductor entries in .gitignore where they are, because the file has a "!" line and moving them could change what it ignores';
8
12
 
9
13
  const toLf = (t) => t.replace(/\r\n/g, '\n');
10
14
 
@@ -28,25 +32,27 @@ export function normalizeHeading(line) {
28
32
  .toLowerCase();
29
33
  }
30
34
 
31
- // One fence-aware pass over LF-normalized text. Returns line INDICES only, so
32
- // callers slice `lines` themselves and no substring arithmetic is needed.
33
- // A fence opens on ``` or ~~~ at column 0 (info string allowed) and closes on a
34
- // bare run of the SAME marker char. An unclosed fence runs to EOF, so everything
35
- // after it is body text — never a heading, never a sentinel.
36
- export function scanLines(lfText) {
37
- const lines = lfText.split('\n');
35
+ // One fence-aware pass. Takes raw text: each element of `lines` keeps its own CR,
36
+ // so a caller that splices `lines` and rejoins on '\n' reproduces every untouched
37
+ // byte. Returns line INDICES only. Fences follow CommonMark: one opens on ``` or ~~~
38
+ // indented up to three spaces (info string allowed), and closes only on a bare run of
39
+ // the SAME char at least as long as the opener, so a ```` block can quote ``` ones.
40
+ // An unclosed fence runs to EOF, so everything after it is body text — never a
41
+ // heading, never a sentinel — and `openFence` says so.
42
+ export function scanLines(text) {
43
+ const lines = text.split('\n');
38
44
  const headings = [];
39
45
  const starts = [];
40
46
  const ends = [];
41
47
  let fence = null;
42
48
  for (let i = 0; i < lines.length; i++) {
43
49
  const line = lines[i].replace(/\r$/, '');
44
- const marker = line.match(/^(`{3,}|~{3,})/);
50
+ const marker = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
45
51
  if (fence) {
46
- if (marker && marker[1][0] === fence && /^(`{3,}|~{3,})\s*$/.test(line)) fence = null;
52
+ if (closesFence(marker, fence)) fence = null;
47
53
  continue;
48
54
  }
49
- if (marker) { fence = marker[1][0]; continue; }
55
+ if (marker) { fence = marker[1]; continue; }
50
56
  const trimmed = line.trim();
51
57
  if (trimmed === SENTINEL_START) { starts.push(i); continue; }
52
58
  if (trimmed === SENTINEL_END) { ends.push(i); continue; }
@@ -56,113 +62,112 @@ export function scanLines(lfText) {
56
62
  starts.length === 0 && ends.length === 0 ? 'none'
57
63
  : starts.length === 1 && ends.length === 1 && starts[0] < ends[0] ? 'balanced'
58
64
  : 'unbalanced';
59
- return { lines, headings, start: starts[0], end: ends[0], status };
65
+ return { lines, headings, start: starts[0], end: ends[0], status, openFence: fence !== null };
60
66
  }
61
67
 
62
- // A section runs from its `## ` line to the line before the next heading, or to
63
- // `limit` (the sentinel start, or EOF) — whichever comes first.
64
- function sectionRange(scan, n, limit) {
65
- const from = scan.headings[n].index;
66
- const next = scan.headings[n + 1];
67
- return [from, Math.min(next ? next.index : limit, limit)];
68
+ const closesFence = (marker, opener) =>
69
+ marker !== null && marker[1][0] === opener[0] && marker[1].length >= opener.length && marker[2].trim() === '';
70
+
71
+ const unchanged = (hostText, warning) => ({ text: hostText, changed: false, warning });
72
+
73
+ // The host's bytes, one blank separator line, then `added` in the host's EOL. A host
74
+ // with no final newline gets one first, so its last line never fuses with ours.
75
+ function appendLines(hostText, added, eol) {
76
+ if (hostText === '') return added.join(eol) + eol;
77
+ const separator = hostText.endsWith('\n') ? eol : eol + eol;
78
+ return hostText + separator + added.join(eol) + eol;
68
79
  }
69
80
 
70
- // Append `block` at EOF with exactly one blank separator line and exactly one
71
- // trailing newline, collapsing whatever trailing blank lines the host had.
72
- function appendBlock(lines, block) {
73
- const out = lines.slice();
74
- while (out.length && out[out.length - 1].trim() === '') out.pop();
75
- if (out.length) out.push('');
76
- out.push(...block);
77
- if (out[out.length - 1] !== '') out.push('');
78
- return out;
81
+ // Only the lines strictly between the sentinels are replaced. The sentinel lines and
82
+ // every byte outside them are the host's raw lines, rejoined exactly as they were split.
83
+ function refreshInterior(host, interior, eol) {
84
+ const current = host.lines.slice(host.start + 1, host.end).map((l) => l.replace(/\r$/, ''));
85
+ if (current.join('\n') === interior.join('\n')) return host.lines.join('\n');
86
+ const cr = eol === '\r\n' ? '\r' : '';
87
+ return [
88
+ ...host.lines.slice(0, host.start + 1),
89
+ ...interior.map((l) => l + cr),
90
+ ...host.lines.slice(host.end),
91
+ ].join('\n');
79
92
  }
80
93
 
94
+ // Ownership is the sentinels' alone (BUG-049). A heading's name decides nothing: a
95
+ // sentinel-less host keeps every byte and gets the block appended, and a balanced
96
+ // host has only its block interior refreshed.
81
97
  export function mergeClaudeMdText(templateText, hostText) {
82
98
  const tpl = scanLines(toLf(templateText));
83
99
  // Never mutate host content on the authority of a broken shipped template.
84
- if (tpl.status !== 'balanced') {
85
- return { text: hostText, changed: false, warning: 'TEMPLATE_SENTINEL_UNBALANCED' };
86
- }
100
+ if (tpl.status !== 'balanced') return unchanged(hostText, 'TEMPLATE_SENTINEL_UNBALANCED');
87
101
  if (hostText.trim() === '') {
88
102
  return { text: templateText, changed: templateText !== hostText, warning: null };
89
103
  }
90
- const host0 = scanLines(toLf(hostText));
104
+ const host = scanLines(hostText);
91
105
  // Guessing the intended block risks eating host content, so every malformed
92
- // count takes the same path: touch nothing at all, not even a section append.
93
- if (host0.status === 'unbalanced') {
94
- return { text: hostText, changed: false, warning: 'CLAUDE_MD_SENTINEL_UNBALANCED' };
95
- }
96
-
106
+ // count takes the same path: touch nothing at all.
107
+ if (host.status === 'unbalanced') return unchanged(hostText, 'CLAUDE_MD_SENTINEL_UNBALANCED');
108
+ // A block appended after an unclosed fence would sit inside it, invisible to the
109
+ // next run, which would append another. Writing nothing is the only idempotent move.
110
+ if (host.status === 'none' && host.openFence) return unchanged(hostText, 'CLAUDE_MD_UNCLOSED_FENCE');
97
111
  const eol = detectEol(hostText);
98
- const block = tpl.lines.slice(tpl.start, tpl.end + 1); // sentinels included
99
- const interior = tpl.lines.slice(tpl.start + 1, tpl.end); // sentinels excluded
100
- const managedKeys = new Set(
101
- tpl.headings.filter((h) => h.index > tpl.start && h.index < tpl.end).map((h) => h.key),
102
- );
103
-
104
- let lines = host0.lines.slice();
105
- if (host0.status === 'balanced') {
106
- // Both sides are already LF here, so this comparison is EOL-normalized by
107
- // construction — without that a CRLF host would "change" on every run.
108
- const current = lines.slice(host0.start + 1, host0.end);
109
- if (current.join('\n') !== interior.join('\n')) {
110
- lines.splice(host0.start + 1, host0.end - host0.start - 1, ...interior);
111
- }
112
- } else {
113
- // Migration — the ONE path that discards host content. Host sections whose
114
- // heading matches a managed heading are dropped so the appended block does
115
- // not duplicate them. The caller's backup file is the recovery.
116
- const drop = [];
117
- for (let n = 0; n < host0.headings.length; n++) {
118
- if (managedKeys.has(host0.headings[n].key)) drop.push(sectionRange(host0, n, lines.length));
119
- }
120
- for (const [from, to] of drop.reverse()) lines.splice(from, to - from);
121
- lines = appendBlock(lines, block);
122
- }
112
+ const text = host.status === 'balanced'
113
+ ? refreshInterior(host, tpl.lines.slice(tpl.start + 1, tpl.end), eol)
114
+ : appendLines(hostText, tpl.lines.slice(tpl.start, tpl.end + 1), eol);
115
+ return { text, changed: text !== hostText, warning: null };
116
+ }
123
117
 
124
- // Host-owned template sections the host lacks, in template order, inserted
125
- // immediately before the sentinel start so the block stays last across releases.
126
- const host1 = scanLines(lines.join('\n'));
127
- const have = new Set(host1.headings.map((h) => h.key));
128
- const additions = [];
129
- for (let n = 0; n < tpl.headings.length; n++) {
130
- const h = tpl.headings[n];
131
- if (h.index > tpl.start || have.has(h.key)) continue;
132
- const [from, to] = sectionRange(tpl, n, tpl.start);
133
- additions.push(...tpl.lines.slice(from, to));
134
- }
135
- if (additions.length) {
136
- lines = host1.status === 'balanced'
137
- ? [...lines.slice(0, host1.start), ...additions, ...lines.slice(host1.start)]
138
- : appendBlock(lines, additions);
139
- }
118
+ const keyOf = (line) => line.replace(/\r$/, '').trim();
140
119
 
141
- const text = lines.join(eol);
142
- return { text, changed: text !== hostText, warning: null };
120
+ // The installer's own entries are the template's non-blank, non-comment lines.
121
+ function managedEntries(templateText) {
122
+ return toLf(templateText).split('\n').map(keyOf).filter((k) => k && !k.startsWith('#'));
143
123
  }
144
124
 
145
- // .gitignore is line-oriented, not section-oriented: compare trimmed, CR-stripped,
146
- // non-empty lines and append the template lines the host lacks. Blank and
147
- // comment-only template lines are never appended.
148
- export function appendMissingLinesText(templateText, hostText) {
149
- if (hostText.trim() === '') {
150
- return { text: templateText, changed: templateText !== hostText, warning: null };
125
+ // The block runs from the header to the first blank line or EOF; `end` is exclusive.
126
+ function findBlock(lines) {
127
+ const header = lines.findIndex((l) => keyOf(l) === GITIGNORE_HEADER);
128
+ if (header === -1) return null;
129
+ let end = header + 1;
130
+ while (end < lines.length && keyOf(lines[end]) !== '') end++;
131
+ return { header, end };
132
+ }
133
+
134
+ // Exact copies of a managed entry outside the block: the lines gathering would move.
135
+ function strayEntryIndices(lines, block, entries) {
136
+ const inBlock = (i) => block !== null && i > block.header && i < block.end;
137
+ return lines.flatMap((l, i) => (!inBlock(i) && entries.includes(keyOf(l)) ? [i] : []));
138
+ }
139
+
140
+ // Missing entries go at the end of an existing block, or into a new block appended
141
+ // after one blank line. Every other host line keeps its bytes and its place.
142
+ function insertEntries(lines, block, missing, eol) {
143
+ if (!block) return appendLines(lines.join('\n'), [GITIGNORE_HEADER, ...missing], eol);
144
+ const cr = eol === '\r\n' ? '\r' : '';
145
+ const out = lines.slice();
146
+ if (block.end === out.length) {
147
+ out[out.length - 1] = out[out.length - 1].replace(/\r$/, '') + cr;
148
+ out.push('');
151
149
  }
152
- const eol = detectEol(hostText);
153
- const lines = toLf(hostText).split('\n');
154
- const have = new Set(lines.map((l) => l.replace(/\r$/, '').trim()).filter(Boolean));
155
- const additions = [];
156
- for (const raw of toLf(templateText).split('\n')) {
157
- const t = raw.replace(/\r$/, '').trim();
158
- if (!t || t.startsWith('#') || have.has(t)) continue;
159
- have.add(t);
160
- additions.push(t);
150
+ out.splice(block.end, 0, ...missing.map((e) => e + cr));
151
+ return out.join('\n');
152
+ }
153
+
154
+ export function mergeGitignoreText(templateText, hostText) {
155
+ if (hostText.trim() === '') {
156
+ return { text: templateText, changed: templateText !== hostText, warning: null, notice: null };
161
157
  }
162
- if (!additions.length) return { text: hostText, changed: false, warning: null };
163
- const out = lines.slice();
164
- while (out.length && out[out.length - 1].trim() === '') out.pop();
165
- out.push(...additions, '');
166
- const text = out.join(eol);
167
- return { text, changed: text !== hostText, warning: null };
158
+ const entries = managedEntries(templateText);
159
+ const lines = hostText.split('\n');
160
+ const strays = strayEntryIndices(lines, findBlock(lines), entries);
161
+ // Moving an ignore line past a later `!` re-include can change what the file
162
+ // ignores, so a host with any negation keeps every line exactly where it is.
163
+ const negated = lines.some((l) => keyOf(l).startsWith('!'));
164
+ const kept = negated || !strays.length ? lines : lines.filter((_, i) => !strays.includes(i));
165
+ // A gathered line 0 must not take the file's byte-order mark with it.
166
+ if (kept !== lines && lines[0].startsWith('') && !kept[0].startsWith('')) kept[0] = `${kept[0]}`;
167
+ const present = new Set(kept.map(keyOf));
168
+ const missing = entries.filter((e) => !present.has(e));
169
+ if (kept === lines && !missing.length) return { text: hostText, changed: false, warning: null, notice: null };
170
+ const text = insertEntries(kept, findBlock(kept), missing, detectEol(hostText));
171
+ const notice = negated && strays.length ? NEGATION_NOTICE : null;
172
+ return { text, changed: text !== hostText, warning: null, notice };
168
173
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yeison.restrepo.r/code-conductor",
3
- "version": "1.34.3",
3
+ "version": "1.34.4",
4
4
  "description": "A governance layer for Claude Code sessions: hooks that check an agent's commands before they run, a spec-first workflow, and project memory the next session reads.",
5
5
  "keywords": [
6
6
  "agentic-development",
@@ -1,3 +1,4 @@
1
+ # Code Conductor (added by the installer; safe to keep)
1
2
  .claude/memory/turn-count.txt
2
3
  *.installer-backup.*
3
4
  *.installer-tmp.*