@yeison.restrepo.r/code-conductor 1.23.3 → 1.30.0
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/LICENSE +21 -185
- package/README.md +72 -15
- package/bin/code-conductor.mjs +6 -5
- package/global/CLAUDE.md +2 -0
- package/global/hooks/graphify-ast-refresh.mjs +91 -0
- package/global/settings.json +0 -13
- package/lib/installer/config.mjs +0 -8
- package/lib/installer/deploy.mjs +120 -19
- package/lib/installer/file-merge.mjs +87 -0
- package/lib/installer/host-owned.mjs +94 -0
- package/lib/installer/merge-md.mjs +168 -0
- package/lib/installer/settings-merge.mjs +118 -0
- package/lib/installer/settings.mjs +46 -11
- package/package.json +1 -1
- package/project-template/.claude/commands/cc-init.md +50 -18
- package/project-template/.claude/commands/cc-plan.md +114 -1
- package/project-template/.claude/hooks/pre-tool-use.mjs +509 -0
- package/project-template/.claude/settings.json +2 -2
- package/project-template/CLAUDE.md +5 -1
- package/project-template/gitignore +3 -0
- package/scripts/claude-md-fields.mjs +42 -0
- package/scripts/conductor-db.mjs +92 -0
- package/scripts/detect-stack.mjs +5 -1
- package/scripts/init-wizard.mjs +195 -0
- package/skills/{code-simplifier.md → code-simplifier/SKILL.md} +6 -0
- package/skills/{verbosity.md → verbosity/SKILL.md} +6 -0
- package/project-template/.claude/hooks/pre-tool-use.sh +0 -81
- /package/skills/{agent-delegation.md → agent-delegation/SKILL.md} +0 -0
- /package/skills/{critical-review.md → critical-review/SKILL.md} +0 -0
- /package/skills/{memory-first.md → memory-first/SKILL.md} +0 -0
package/lib/installer/deploy.mjs
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
|
-
import { cpSync, mkdirSync, chmodSync, existsSync, readdirSync, statSync, rmSync } from 'node:fs';
|
|
2
|
-
import { join
|
|
1
|
+
import { cpSync, mkdirSync, chmodSync, existsSync, lstatSync, readdirSync, readFileSync, statSync, rmSync, unlinkSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { mergeFileInto, resolveRealTarget } from './file-merge.mjs';
|
|
4
|
+
import { mergeClaudeMdText, appendMissingLinesText } from './merge-md.mjs';
|
|
5
|
+
import { GLOBAL_HOST_OWNED, PROJECT_HOST_OWNED, GLOBAL_SETTINGS_FINGERPRINTS, PROJECT_SETTINGS_FINGERPRINTS, hostOwnedFilter, seedHostOwned } from './host-owned.mjs';
|
|
6
|
+
import { mergeSettingsFile } from './settings-merge.mjs';
|
|
7
|
+
|
|
8
|
+
// Host-authored data, not managed assets: these are merged, never force-copied —
|
|
9
|
+
// everything else in the template keeps its overwrite. Keyed by the name the file
|
|
10
|
+
// carries INSIDE project-template/ and valued by the name the host project uses:
|
|
11
|
+
// npm strips any file literally called `.gitignore` from every published tarball,
|
|
12
|
+
// so the template ships it undotted and this map restores the dot on deploy.
|
|
13
|
+
// Keying on the source name is load-bearing — skipping the copy loop on the
|
|
14
|
+
// target name instead would let cpSync drop a stray `gitignore` at the project root.
|
|
15
|
+
const MERGED_ROOT_FILES = new Map([
|
|
16
|
+
['CLAUDE.md', { target: 'CLAUDE.md', merge: mergeClaudeMdText }],
|
|
17
|
+
['gitignore', { target: '.gitignore', merge: appendMissingLinesText }],
|
|
18
|
+
]);
|
|
3
19
|
|
|
4
20
|
// Verified at plan time: `find global skills project-template -type l` returns
|
|
5
21
|
// nothing — the bundled asset tree contains ZERO symlinks. `dereference: false`
|
|
@@ -23,27 +39,79 @@ export function assertAssets(assetRoot, dirs) {
|
|
|
23
39
|
}
|
|
24
40
|
}
|
|
25
41
|
|
|
26
|
-
//
|
|
27
|
-
//
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
42
|
+
// Derived from the shipped tree rather than a constant list: a hardcoded list
|
|
43
|
+
// silently drifts the day a skill is added or renamed.
|
|
44
|
+
function bundledSkillNames(assetRoot) {
|
|
45
|
+
return readdirSync(join(assetRoot, 'skills'), { withFileTypes: true })
|
|
46
|
+
.filter((e) => e.isDirectory())
|
|
47
|
+
.map((e) => e.name);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// MUST run before the skills cpSync: a plain file sitting at skills/<name> makes
|
|
51
|
+
// the directory copy throw mid-deploy. Deliberately NOT suppressed — if the
|
|
52
|
+
// unlink fails, the cpSync error that follows carries the real diagnosis.
|
|
53
|
+
function unblockSkillPaths(assetRoot, skillsDir) {
|
|
54
|
+
for (const name of bundledSkillNames(assetRoot)) {
|
|
55
|
+
const p = join(skillsDir, name);
|
|
56
|
+
let st;
|
|
57
|
+
try { st = lstatSync(p); } catch { continue; }
|
|
58
|
+
if (!st.isDirectory()) unlinkSync(p);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Pre-1.24 installs left skills/<name>.md flat files that Claude Code never reads.
|
|
63
|
+
// Remove one only when its bytes are still the bundled content — with OR without
|
|
64
|
+
// the frontmatter block, since 1.24 added frontmatter to two of them and a
|
|
65
|
+
// single comparison would leave those shadow files behind forever.
|
|
66
|
+
function sweepStaleFlatSkills(assetRoot, skillsDir) {
|
|
67
|
+
for (const name of bundledSkillNames(assetRoot)) {
|
|
68
|
+
const flat = join(skillsDir, `${name}.md`);
|
|
69
|
+
if (!existsSync(flat) || !statSync(flat).isFile()) continue;
|
|
70
|
+
const bundled = readFileSync(join(assetRoot, 'skills', name, 'SKILL.md'), 'utf8');
|
|
71
|
+
const body = bundled.replace(/^---\n[\s\S]*?\n---\n\n?/, '');
|
|
72
|
+
const current = readFileSync(flat, 'utf8');
|
|
73
|
+
if (current !== bundled && current !== body) continue;
|
|
74
|
+
try { unlinkSync(flat); } catch { /* cosmetic leftover, never fatal */ }
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Pre-flight (run from bin/ BEFORE the first write): a directory or a dangling
|
|
79
|
+
// symlink at either CLAUDE.md target is unusable, and discovering that mid-copy
|
|
80
|
+
// would report a partial write (exit 2) for what is really a precondition failure.
|
|
81
|
+
export function assertMergeTargets(home, cwd, project) {
|
|
82
|
+
const targets = [join(home, '.claude', 'CLAUDE.md')];
|
|
83
|
+
if (project) targets.push(join(cwd, 'CLAUDE.md'));
|
|
84
|
+
for (const p of targets) {
|
|
85
|
+
const t = resolveRealTarget(p);
|
|
86
|
+
if (!t.exists) continue;
|
|
87
|
+
if (t.isDir || t.dangling) {
|
|
88
|
+
const err = new Error(`cannot merge ${p}: the target is ${t.isDir ? 'a directory' : 'a dangling symlink'}`);
|
|
89
|
+
err.code = 'CLAUDE_MD_NOT_FILE';
|
|
90
|
+
throw err;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
35
93
|
}
|
|
36
94
|
|
|
37
95
|
export function deployGlobal(assetRoot, home) {
|
|
38
96
|
const target = join(home, '.claude');
|
|
39
97
|
const globalDir = join(assetRoot, 'global');
|
|
40
98
|
mkdirSync(target, { recursive: true });
|
|
41
|
-
cpSync(globalDir, target, { ...CP_OPTS, filter:
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
99
|
+
cpSync(globalDir, target, { ...CP_OPTS, filter: hostOwnedFilter(globalDir, GLOBAL_HOST_OWNED) });
|
|
100
|
+
mergeFileInto(join(globalDir, 'CLAUDE.md'), join(target, 'CLAUDE.md'), mergeClaudeMdText);
|
|
101
|
+
const skillsDir = join(target, 'skills');
|
|
102
|
+
unblockSkillPaths(assetRoot, skillsDir);
|
|
103
|
+
cpSync(join(assetRoot, 'skills'), skillsDir, CP_OPTS);
|
|
104
|
+
sweepStaleFlatSkills(assetRoot, skillsDir);
|
|
105
|
+
// The filter excludes both files under global/memory, so a host that has
|
|
106
|
+
// neither gets the directory from here rather than from cpSync. config.mjs's
|
|
107
|
+
// version and verbosity writes both assume the parent dir exists.
|
|
46
108
|
mkdirSync(join(target, 'memory'), { recursive: true });
|
|
109
|
+
seedHostOwned(globalDir, target, GLOBAL_HOST_OWNED);
|
|
110
|
+
// global/settings.json ships permissions and no hooks, so on an existing
|
|
111
|
+
// install this is a no-op that exists to stop the force-copy; on a fresh one
|
|
112
|
+
// it writes the template whole, which is the only time permissions is written.
|
|
113
|
+
// The two synthesized global hook entries are merged afterwards by bin/.
|
|
114
|
+
mergeSettingsFile(join(globalDir, 'settings.json'), join(target, 'settings.json'), GLOBAL_SETTINGS_FINGERPRINTS);
|
|
47
115
|
return target;
|
|
48
116
|
}
|
|
49
117
|
|
|
@@ -61,7 +129,28 @@ function sweepStaleRootScripts(assetRoot, cwd) {
|
|
|
61
129
|
if (matches) rmSync(staleDir, { recursive: true, force: true });
|
|
62
130
|
}
|
|
63
131
|
|
|
64
|
-
|
|
132
|
+
// 1.28.0 and 1.29.0 both told users to re-run the installer, and that re-run
|
|
133
|
+
// force-copied the template stub over the host's project.md. Detection only:
|
|
134
|
+
// restoring from git would mean the installer writing host files out of the
|
|
135
|
+
// host's own history, with new failure modes (detached HEAD, shallow clone,
|
|
136
|
+
// submodule, dirty index, no git at all) for a path that fires in one narrow
|
|
137
|
+
// case. Print the two commands and write nothing.
|
|
138
|
+
function warnIfProjectMemoryIsStub(templateClaude, target, emit) {
|
|
139
|
+
const rel = '.claude/memory/project.md';
|
|
140
|
+
const stub = join(templateClaude, 'memory', 'project.md');
|
|
141
|
+
const host = join(target, 'memory', 'project.md');
|
|
142
|
+
if (!existsSync(stub) || !existsSync(host)) return false;
|
|
143
|
+
if (readFileSync(host, 'utf8') !== readFileSync(stub, 'utf8')) return false;
|
|
144
|
+
emit([
|
|
145
|
+
`code-conductor: ${rel} matches the bundled stub; it may have been overwritten by an installer re-run before 1.30.0.`,
|
|
146
|
+
` Find a committed copy: git log --oneline -- ${rel}`,
|
|
147
|
+
` Restore it: git checkout <commit> -- ${rel}`,
|
|
148
|
+
].join('\n'));
|
|
149
|
+
return true;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function deployProject(assetRoot, cwd, { warn } = {}) {
|
|
153
|
+
const emit = warn || ((m) => process.stderr.write(`${m}\n`));
|
|
65
154
|
const target = join(cwd, '.claude');
|
|
66
155
|
const templateRoot = join(assetRoot, 'project-template');
|
|
67
156
|
// If something already occupies ./.claude and it is NOT a directory, this is a
|
|
@@ -76,11 +165,23 @@ export function deployProject(assetRoot, cwd) {
|
|
|
76
165
|
// project-template mirrors the project root layout (a .claude/ subdir plus
|
|
77
166
|
// root files like CLAUDE.md/.gitignore) — copy each half to its matching
|
|
78
167
|
// destination instead of nesting the whole tree under target.
|
|
79
|
-
|
|
168
|
+
const templateClaude = join(templateRoot, '.claude');
|
|
169
|
+
cpSync(templateClaude, target, { ...CP_OPTS, filter: hostOwnedFilter(templateClaude, PROJECT_HOST_OWNED) });
|
|
80
170
|
for (const name of readdirSync(templateRoot)) {
|
|
81
|
-
if (name === '.claude') continue;
|
|
171
|
+
if (name === '.claude' || MERGED_ROOT_FILES.has(name)) continue;
|
|
82
172
|
cpSync(join(templateRoot, name), join(cwd, name), CP_OPTS);
|
|
83
173
|
}
|
|
174
|
+
for (const [source, { target: dest, merge }] of MERGED_ROOT_FILES) {
|
|
175
|
+
mergeFileInto(join(templateRoot, source), join(cwd, dest), merge);
|
|
176
|
+
}
|
|
177
|
+
// BEFORE the seed on purpose: running it after would make every fresh
|
|
178
|
+
// scaffold warn about the stub it was just given.
|
|
179
|
+
warnIfProjectMemoryIsStub(templateClaude, target, emit);
|
|
180
|
+
// The filter excludes both shipped memory files, so a host with neither gets
|
|
181
|
+
// the directory from here. Same reason as deployGlobal's.
|
|
182
|
+
mkdirSync(join(target, 'memory'), { recursive: true });
|
|
183
|
+
seedHostOwned(templateClaude, target, PROJECT_HOST_OWNED);
|
|
184
|
+
mergeSettingsFile(join(templateClaude, 'settings.json'), join(target, 'settings.json'), PROJECT_SETTINGS_FINGERPRINTS);
|
|
84
185
|
// scripts/ is a sibling of project-template/ under assetRoot (source layout),
|
|
85
186
|
// but is deployed as a CHILD of .claude/ (target) - it must stay inside the
|
|
86
187
|
// project's self-contained .claude footprint, not spill into the host's own
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import {
|
|
2
|
+
existsSync, lstatSync, statSync, realpathSync, readFileSync,
|
|
3
|
+
writeFileSync, copyFileSync, renameSync, unlinkSync,
|
|
4
|
+
} from 'node:fs';
|
|
5
|
+
import { utcStamp, pruneBackups } from './settings.mjs';
|
|
6
|
+
|
|
7
|
+
const BACKUP_SUFFIX = '.installer-backup.';
|
|
8
|
+
const MAX_BACKUPS = 5;
|
|
9
|
+
|
|
10
|
+
// Symlinked CLAUDE.md into a dotfiles repo is a legitimate setup, so the writer
|
|
11
|
+
// works on the RESOLVED path: renameSync over the link itself would replace it
|
|
12
|
+
// with a regular file and silently detach the dotfiles checkout.
|
|
13
|
+
export function resolveRealTarget(p) {
|
|
14
|
+
let st;
|
|
15
|
+
try { st = lstatSync(p); } catch { return { realPath: p, exists: false, isDir: false, dangling: false }; }
|
|
16
|
+
if (!st.isSymbolicLink()) return { realPath: p, exists: true, isDir: st.isDirectory(), dangling: false };
|
|
17
|
+
let real;
|
|
18
|
+
try { real = realpathSync(p); } catch { return { realPath: p, exists: true, isDir: false, dangling: true }; }
|
|
19
|
+
return { realPath: real, exists: true, isDir: statSync(real).isDirectory(), dangling: false };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Two installs inside the same UTC second would make copyFileSync silently
|
|
23
|
+
// overwrite the earlier backup, so collisions get a -1/-2 suffix. The suffix
|
|
24
|
+
// sorts AFTER the bare stamp, keeping pruneBackups' lexical order chronological.
|
|
25
|
+
export function backupFile(realPath, now = new Date()) {
|
|
26
|
+
const base = `${realPath}${BACKUP_SUFFIX}${utcStamp(now)}`;
|
|
27
|
+
let dst = base;
|
|
28
|
+
for (let i = 1; existsSync(dst); i++) dst = `${base}-${i}`;
|
|
29
|
+
copyFileSync(realPath, dst);
|
|
30
|
+
pruneBackups(realPath, BACKUP_SUFFIX, MAX_BACKUPS);
|
|
31
|
+
return dst;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// The rename is the ONLY mutation of the target, so a crash mid-write leaves the
|
|
35
|
+
// host file untouched. The temp file lives in the target's own directory because
|
|
36
|
+
// a cross-device rename would throw.
|
|
37
|
+
export function writeAtomic(realPath, text) {
|
|
38
|
+
const tmp = `${realPath}.installer-tmp.${process.pid}`;
|
|
39
|
+
try {
|
|
40
|
+
writeFileSync(tmp, text, 'utf8');
|
|
41
|
+
renameSync(tmp, realPath);
|
|
42
|
+
} finally {
|
|
43
|
+
try { if (existsSync(tmp)) unlinkSync(tmp); } catch { /* best effort */ }
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function mergeFileInto(templatePath, targetPath, mergeFn, { now = new Date(), warn } = {}) {
|
|
48
|
+
const emit = warn || ((m) => process.stderr.write(`${m}\n`));
|
|
49
|
+
const target = resolveRealTarget(targetPath);
|
|
50
|
+
if (target.isDir) {
|
|
51
|
+
emit(`code-conductor: skipping ${targetPath} — the target is a directory`);
|
|
52
|
+
return 'skipped-dir';
|
|
53
|
+
}
|
|
54
|
+
// Ruling R6: writing through a dangling link would renameSync a regular file
|
|
55
|
+
// over it, destroying the link. Leave it exactly as the user left it.
|
|
56
|
+
if (target.dangling) {
|
|
57
|
+
emit(`code-conductor: skipping ${targetPath} — it is a dangling symlink`);
|
|
58
|
+
return 'skipped-dangling';
|
|
59
|
+
}
|
|
60
|
+
// Defence in depth for a damaged or hand-edited package. The bundled ignore
|
|
61
|
+
// template used to vanish here for real — npm strips any file named
|
|
62
|
+
// `.gitignore` from a tarball — which is why it now ships undotted and is
|
|
63
|
+
// mapped on deploy. Nothing bundled is expected to be absent any more; an
|
|
64
|
+
// absent template is skipped rather than aborting the whole install.
|
|
65
|
+
if (!existsSync(templatePath)) {
|
|
66
|
+
return 'skipped-missing';
|
|
67
|
+
}
|
|
68
|
+
const templateText = readFileSync(templatePath, 'utf8');
|
|
69
|
+
// Ruling R7: a fresh target gets the template verbatim; mergeFn never runs, so
|
|
70
|
+
// the template's own sentinels are validated by templates.test.js, not here.
|
|
71
|
+
if (!target.exists) {
|
|
72
|
+
writeAtomic(target.realPath, templateText);
|
|
73
|
+
return 'created';
|
|
74
|
+
}
|
|
75
|
+
const hostText = readFileSync(target.realPath, 'utf8');
|
|
76
|
+
const { text, changed, warning } = mergeFn(templateText, hostText);
|
|
77
|
+
if (warning) {
|
|
78
|
+
emit(`code-conductor: skipping ${targetPath} — ${warning}; fix the cc:managed markers and re-run`);
|
|
79
|
+
return 'skipped-warning';
|
|
80
|
+
}
|
|
81
|
+
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);
|
|
86
|
+
return 'merged';
|
|
87
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { copyFileSync, existsSync, mkdirSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, relative, sep } from 'node:path';
|
|
3
|
+
|
|
4
|
+
// One policy per host-owned path, keyed by the path RELATIVE to that surface's
|
|
5
|
+
// copy source and always spelled with forward slashes. The audit behind BUG-039
|
|
6
|
+
// found three distinct required behaviors, which is why this is a table and not
|
|
7
|
+
// a skip list:
|
|
8
|
+
// 'skip' never written by the installer, and no template copy exists
|
|
9
|
+
// 'seed' written from the template only when the target is absent
|
|
10
|
+
// 'merge' host content combined with the installer-owned parts
|
|
11
|
+
// There is no fourth policy and no default: a path absent from the table keeps
|
|
12
|
+
// the force-copy, and the coverage tests in templates.test.js are what stop that
|
|
13
|
+
// default from silently swallowing a newly shipped host-owned file.
|
|
14
|
+
|
|
15
|
+
// ~/.claude/. Only personal.md and verbosity.md ship under global/memory/;
|
|
16
|
+
// conductor-version.md is written there by writeVersionFile, is installer-owned,
|
|
17
|
+
// and needs no entry because nothing ships that filename.
|
|
18
|
+
export const GLOBAL_HOST_OWNED = new Map([
|
|
19
|
+
['memory/personal.md', 'seed'],
|
|
20
|
+
['memory/verbosity.md', 'seed'],
|
|
21
|
+
['CLAUDE.md', 'merge'],
|
|
22
|
+
['settings.json', 'merge'],
|
|
23
|
+
['settings.local.json', 'skip'],
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
// <cwd>/.claude/. Only project.md and context-threshold.txt ship. Every 'skip'
|
|
27
|
+
// below is a file the host or a conductor command writes at runtime and the
|
|
28
|
+
// template must never start shipping; each is protected today only by its
|
|
29
|
+
// absence from the template, which is exactly what this table replaces.
|
|
30
|
+
export const PROJECT_HOST_OWNED = new Map([
|
|
31
|
+
['memory/project.md', 'seed'],
|
|
32
|
+
['memory/context-threshold.txt', 'seed'],
|
|
33
|
+
['memory/personal.md', 'skip'],
|
|
34
|
+
['memory/bash-scan-allowlist.txt', 'skip'],
|
|
35
|
+
['memory/session-snapshot.json', 'skip'],
|
|
36
|
+
['memory/session-snapshot.md', 'skip'],
|
|
37
|
+
['memory/turn-count.txt', 'skip'],
|
|
38
|
+
['settings.json', 'merge'],
|
|
39
|
+
['settings.local.json', 'skip'],
|
|
40
|
+
]);
|
|
41
|
+
|
|
42
|
+
// The ONLY top-level settings.json keys the merge may write into an existing
|
|
43
|
+
// host file. Declared rather than implied: permissions, env, statusLine, model
|
|
44
|
+
// and every key a future Claude Code adds are host-owned by construction, and
|
|
45
|
+
// a test asserts the merge writes nothing outside this list. Unioning a
|
|
46
|
+
// template's permissions into a host's file would silently restore a grant the
|
|
47
|
+
// operator deliberately revoked, which is a ratchet that only loosens.
|
|
48
|
+
export const MERGE_OWNED_KEYS = ['hooks'];
|
|
49
|
+
|
|
50
|
+
// global/settings.json ships no hooks: its two entries are synthesized from the
|
|
51
|
+
// host's absolute home by settings.mjs and merged there. Empty is the correct
|
|
52
|
+
// value, and the forward-coverage test is what will catch the day that changes.
|
|
53
|
+
export const GLOBAL_SETTINGS_FINGERPRINTS = [];
|
|
54
|
+
|
|
55
|
+
// One fingerprint per shipped entry in project-template/.claude/settings.json,
|
|
56
|
+
// and exactly one: the UserPromptSubmit entry carries three commands in a single
|
|
57
|
+
// entry, so fingerprinting context-guard.sh as well would make that entry match
|
|
58
|
+
// two, which the forward-coverage test rejects by design.
|
|
59
|
+
export const PROJECT_SETTINGS_FINGERPRINTS = [
|
|
60
|
+
'pre-tool-use.mjs',
|
|
61
|
+
'post-compact.sh',
|
|
62
|
+
'verbosity-remind.sh',
|
|
63
|
+
];
|
|
64
|
+
|
|
65
|
+
// cpSync filter: exclude exactly the table's own paths, nothing more. A parent
|
|
66
|
+
// directory is never excluded, so cpSync still creates it and a sibling managed
|
|
67
|
+
// file inside it is still copied. Matching on the path RELATIVE to the copy
|
|
68
|
+
// source is load-bearing: matching on the absolute path would let a host whose
|
|
69
|
+
// home happens to contain "/memory/" exclude the whole tree.
|
|
70
|
+
export function hostOwnedFilter(sourceRoot, table) {
|
|
71
|
+
return (src) => {
|
|
72
|
+
const rel = relative(sourceRoot, src);
|
|
73
|
+
if (rel === '') return true;
|
|
74
|
+
return !table.has(rel.split(sep).join('/'));
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Write-if-absent for every 'seed' entry. A template source that does not exist
|
|
79
|
+
// is skipped rather than throwing: a damaged or hand-edited package should not
|
|
80
|
+
// abort a deploy whose managed assets have already landed.
|
|
81
|
+
export function seedHostOwned(sourceRoot, targetRoot, table) {
|
|
82
|
+
const seeded = [];
|
|
83
|
+
for (const [rel, policy] of table) {
|
|
84
|
+
if (policy !== 'seed') continue;
|
|
85
|
+
const parts = rel.split('/');
|
|
86
|
+
const src = join(sourceRoot, ...parts);
|
|
87
|
+
const dst = join(targetRoot, ...parts);
|
|
88
|
+
if (existsSync(dst) || !existsSync(src)) continue;
|
|
89
|
+
mkdirSync(dirname(dst), { recursive: true });
|
|
90
|
+
copyFileSync(src, dst);
|
|
91
|
+
seeded.push(rel);
|
|
92
|
+
}
|
|
93
|
+
return seeded;
|
|
94
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// Pure text engine for the CLAUDE.md / .gitignore merge. Deliberately imports
|
|
2
|
+
// nothing from node:fs — every function here is a string -> string transform, so
|
|
3
|
+
// the fence, sentinel and EOL rules are unit-testable without touching disk.
|
|
4
|
+
// The I/O half (backups, atomic write, symlinks) lives in file-merge.mjs.
|
|
5
|
+
|
|
6
|
+
export const SENTINEL_START = '<!-- cc:managed:start -->';
|
|
7
|
+
export const SENTINEL_END = '<!-- cc:managed:end -->';
|
|
8
|
+
|
|
9
|
+
const toLf = (t) => t.replace(/\r\n/g, '\n');
|
|
10
|
+
|
|
11
|
+
// Host EOL wins for everything this writer emits. A file with no terminator at
|
|
12
|
+
// all (one line, no trailing newline) offers no evidence either way -> LF.
|
|
13
|
+
export function detectEol(text) {
|
|
14
|
+
const i = text.indexOf('\n');
|
|
15
|
+
if (i === -1) return '\n';
|
|
16
|
+
return i > 0 && text[i - 1] === '\r' ? '\r\n' : '\n';
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Comparison key for a `## ` heading: case, inner whitespace, a trailing CR and
|
|
20
|
+
// trailing #'s are all noise, so `## Conventions` matches `## conventions ##`.
|
|
21
|
+
export function normalizeHeading(line) {
|
|
22
|
+
return line
|
|
23
|
+
.replace(/\r$/, '')
|
|
24
|
+
.replace(/^##\s+/, '')
|
|
25
|
+
.replace(/\s*#*\s*$/, '')
|
|
26
|
+
.replace(/\s+/g, ' ')
|
|
27
|
+
.trim()
|
|
28
|
+
.toLowerCase();
|
|
29
|
+
}
|
|
30
|
+
|
|
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');
|
|
38
|
+
const headings = [];
|
|
39
|
+
const starts = [];
|
|
40
|
+
const ends = [];
|
|
41
|
+
let fence = null;
|
|
42
|
+
for (let i = 0; i < lines.length; i++) {
|
|
43
|
+
const line = lines[i].replace(/\r$/, '');
|
|
44
|
+
const marker = line.match(/^(`{3,}|~{3,})/);
|
|
45
|
+
if (fence) {
|
|
46
|
+
if (marker && marker[1][0] === fence && /^(`{3,}|~{3,})\s*$/.test(line)) fence = null;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (marker) { fence = marker[1][0]; continue; }
|
|
50
|
+
const trimmed = line.trim();
|
|
51
|
+
if (trimmed === SENTINEL_START) { starts.push(i); continue; }
|
|
52
|
+
if (trimmed === SENTINEL_END) { ends.push(i); continue; }
|
|
53
|
+
if (/^## /.test(line)) headings.push({ index: i, key: normalizeHeading(line) });
|
|
54
|
+
}
|
|
55
|
+
const status =
|
|
56
|
+
starts.length === 0 && ends.length === 0 ? 'none'
|
|
57
|
+
: starts.length === 1 && ends.length === 1 && starts[0] < ends[0] ? 'balanced'
|
|
58
|
+
: 'unbalanced';
|
|
59
|
+
return { lines, headings, start: starts[0], end: ends[0], status };
|
|
60
|
+
}
|
|
61
|
+
|
|
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
|
+
}
|
|
69
|
+
|
|
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;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function mergeClaudeMdText(templateText, hostText) {
|
|
82
|
+
const tpl = scanLines(toLf(templateText));
|
|
83
|
+
// 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
|
+
}
|
|
87
|
+
if (hostText.trim() === '') {
|
|
88
|
+
return { text: templateText, changed: templateText !== hostText, warning: null };
|
|
89
|
+
}
|
|
90
|
+
const host0 = scanLines(toLf(hostText));
|
|
91
|
+
// 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
|
+
|
|
97
|
+
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
|
+
}
|
|
123
|
+
|
|
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
|
+
}
|
|
140
|
+
|
|
141
|
+
const text = lines.join(eol);
|
|
142
|
+
return { text, changed: text !== hostText, warning: null };
|
|
143
|
+
}
|
|
144
|
+
|
|
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 };
|
|
151
|
+
}
|
|
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);
|
|
161
|
+
}
|
|
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 };
|
|
168
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
// This merger lives in its own module for one structural reason: file-merge.mjs
|
|
3
|
+
// already imports utcStamp and pruneBackups from settings.mjs, so putting a
|
|
4
|
+
// function that needs resolveRealTarget into settings.mjs would close an import
|
|
5
|
+
// cycle. Sitting downstream of both keeps the graph acyclic.
|
|
6
|
+
import { backupMalformed } from './settings.mjs';
|
|
7
|
+
import { resolveRealTarget, writeAtomic } from './file-merge.mjs';
|
|
8
|
+
import { MERGE_OWNED_KEYS } from './host-owned.mjs';
|
|
9
|
+
|
|
10
|
+
// An entry is one { matcher, hooks: [...] } object inside a hook-event array.
|
|
11
|
+
// It belongs to the conductor when ANY of its commands carries the fingerprint,
|
|
12
|
+
// because a single shipped entry can hold several commands (the template's
|
|
13
|
+
// UserPromptSubmit entry holds three). Substring matching is deliberate and its
|
|
14
|
+
// limitation is recorded in the spec: a host command that merely mentions a
|
|
15
|
+
// conductor hook's filename is captured as owned. Narrowing that would need a
|
|
16
|
+
// marker written into every existing install.
|
|
17
|
+
export function entryMatches(entry, fingerprint) {
|
|
18
|
+
if (!entry || typeof entry !== 'object' || !Array.isArray(entry.hooks)) return false;
|
|
19
|
+
return entry.hooks.some((h) => h && typeof h.command === 'string' && h.command.includes(fingerprint));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function matchingFingerprints(entry, fingerprints) {
|
|
23
|
+
return fingerprints.filter((fp) => entryMatches(entry, fp));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function isPlainObject(v) {
|
|
27
|
+
return v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Replace the FIRST host entry carrying this fingerprint where it already sits,
|
|
31
|
+
// and drop any later duplicate. In-place replacement is what makes a re-run's
|
|
32
|
+
// diff read as restraint rather than as the installer having rearranged a file
|
|
33
|
+
// it does not own. Dropping later duplicates repairs a file an older merge
|
|
34
|
+
// duplicated; without it a stale copy would survive forever.
|
|
35
|
+
function upsertEntry(arr, tplEntry, fingerprint) {
|
|
36
|
+
const idx = arr.findIndex((e) => entryMatches(e, fingerprint));
|
|
37
|
+
if (idx === -1) return [...arr, tplEntry];
|
|
38
|
+
return arr
|
|
39
|
+
.map((e, i) => (i === idx ? tplEntry : e))
|
|
40
|
+
.filter((e, i) => i === idx || !entryMatches(e, fingerprint));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Merge the template's hook events into the host's, event by event. A host event
|
|
44
|
+
// the template does not ship is carried through untouched.
|
|
45
|
+
function mergeHookTree(hostHooks, tplHooks, fingerprints) {
|
|
46
|
+
const next = { ...hostHooks };
|
|
47
|
+
for (const [event, tplEntries] of Object.entries(tplHooks)) {
|
|
48
|
+
if (!Array.isArray(tplEntries)) continue;
|
|
49
|
+
let arr = Array.isArray(hostHooks[event]) ? [...hostHooks[event]] : [];
|
|
50
|
+
for (const tplEntry of tplEntries) {
|
|
51
|
+
const fps = matchingFingerprints(tplEntry, fingerprints);
|
|
52
|
+
// A shipped entry matching zero or several fingerprints cannot be paired
|
|
53
|
+
// with a host entry safely: appending it blindly would duplicate it on
|
|
54
|
+
// every re-run. Skip it, and let the forward-coverage test in
|
|
55
|
+
// templates.test.js be the thing that fails loudly.
|
|
56
|
+
if (fps.length !== 1) continue;
|
|
57
|
+
arr = upsertEntry(arr, tplEntry, fps[0]);
|
|
58
|
+
}
|
|
59
|
+
next[event] = arr;
|
|
60
|
+
}
|
|
61
|
+
return next;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Merge the template's hook entries into the host's settings.json, touching no
|
|
65
|
+
// top-level key outside MERGE_OWNED_KEYS. `fingerprints` names the entries this
|
|
66
|
+
// installer OWNS on that surface; an entry matching none of them is host-owned
|
|
67
|
+
// and is never read, moved or rewritten.
|
|
68
|
+
export function mergeSettingsFile(templatePath, settingsPath, fingerprints, { now = new Date() } = {}) {
|
|
69
|
+
if (!existsSync(templatePath)) return 'skipped-missing-template';
|
|
70
|
+
const templateText = readFileSync(templatePath, 'utf8');
|
|
71
|
+
|
|
72
|
+
// Writing through the resolved path keeps a settings.json symlinked into a
|
|
73
|
+
// dotfiles repo a symlink, exactly as the CLAUDE.md merge already does.
|
|
74
|
+
const target = resolveRealTarget(settingsPath);
|
|
75
|
+
if (target.isDir) return 'skipped-dir';
|
|
76
|
+
if (target.dangling) return 'skipped-dangling';
|
|
77
|
+
|
|
78
|
+
// A fresh install takes the template verbatim. This is the ONLY moment the
|
|
79
|
+
// permissions block is ever written; after it, permissions is host-owned
|
|
80
|
+
// forever, including a grant the operator removed.
|
|
81
|
+
if (!target.exists) {
|
|
82
|
+
writeAtomic(target.realPath, templateText);
|
|
83
|
+
return 'created';
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const raw = readFileSync(target.realPath, 'utf8');
|
|
87
|
+
// A zero-byte or whitespace-only file is an uninitialized config, not a
|
|
88
|
+
// malformed one, matching what mergeHook already does.
|
|
89
|
+
let host = {};
|
|
90
|
+
if (raw.trim() !== '') {
|
|
91
|
+
try { host = JSON.parse(raw); } catch { host = undefined; }
|
|
92
|
+
}
|
|
93
|
+
// Genuine invalid JSON, or a valid non-object root: back it up, then write the
|
|
94
|
+
// template so the host is never left without a working settings file.
|
|
95
|
+
if (host === undefined || !isPlainObject(host)) {
|
|
96
|
+
backupMalformed(target.realPath, now);
|
|
97
|
+
writeAtomic(target.realPath, templateText);
|
|
98
|
+
return 'malformed-replaced';
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const template = JSON.parse(templateText);
|
|
102
|
+
const tplHooks = isPlainObject(template.hooks) ? template.hooks : {};
|
|
103
|
+
// The ONLY assignment into the host object in this whole function, and it is
|
|
104
|
+
// guarded by the constant. That is what makes MERGE_OWNED_KEYS a declaration
|
|
105
|
+
// rather than a comment: permissions, env, statusLine, model and every key a
|
|
106
|
+
// future Claude Code adds are host-owned because no line here can reach them.
|
|
107
|
+
const merged = { ...host };
|
|
108
|
+
if (MERGE_OWNED_KEYS.includes('hooks') && Object.keys(tplHooks).length > 0) {
|
|
109
|
+
merged.hooks = mergeHookTree(isPlainObject(host.hooks) ? host.hooks : {}, tplHooks, fingerprints);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const text = `${JSON.stringify(merged, null, 2)}\n`;
|
|
113
|
+
// Skipping an identical write is what makes a re-run of an unchanged release
|
|
114
|
+
// byte-identical AND leaves the file's mtime alone.
|
|
115
|
+
if (text === raw) return 'unchanged';
|
|
116
|
+
writeAtomic(target.realPath, text);
|
|
117
|
+
return 'merged';
|
|
118
|
+
}
|