@yeison.restrepo.r/code-conductor 1.24.1 → 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/README.md CHANGED
@@ -172,19 +172,27 @@ Hooks run automatically at specific points in a Claude Code session. They requir
172
172
 
173
173
  ### graphify-ast-refresh *(global)*
174
174
 
175
- Fires on every `UserPromptSubmit`. Checks whether `graphify-out/.graphify_ast_done` is fresh (default: 60 min, override with `GRAPHIFY_STALE_MINUTES`). If stale or missing, spawns a non-blocking background Python process that runs file detection and AST extraction — no LLM calls, no tokens. The main session inherits a ready graph without paying the generation cost.
175
+ Fires on every `UserPromptSubmit`. A small Node wrapper (`graphify-ast-refresh.mjs`) checks whether `graphify-out/.graphify_ast_done` is fresh (default: 60 min, override with `GRAPHIFY_STALE_MINUTES`). If it is stale or missing, the wrapper looks for a `python3` or `python` on `PATH` (override with `GRAPHIFY_PYTHON`) and spawns the Python payload (`graphify-ast-refresh.py`) in the background to run file detection and AST extraction - no LLM calls, no tokens. The main session inherits a ready graph without paying the generation cost.
176
176
 
177
- Works on Windows, Linux, and macOS. Exits in under 5ms when the graph is current.
177
+ Node hosts the check because Python is what is being probed: on a machine with no Python the wrapper exits 0 in silence rather than printing an interpreter error on every prompt. Set `CC_GRAPHIFY_DEBUG=1` to see the one line it would otherwise swallow. Works on Windows, Linux, and macOS, and returns immediately when the graph is current.
178
178
 
179
179
  ### pre-tool-use
180
180
 
181
- Fires before every tool call. Three guards:
181
+ Fires before `Read`, `Write`, `Edit`, `create_file`, `write_file` and `Bash`. A single zero-dependency Node front door (`pre-tool-use.mjs`) reads the `PreToolUse` payload from stdin, dispatches on `tool_name`, and returns its verdict as `hookSpecificOutput.permissionDecision`. Every path exits 0: a denial is data, never an exit code.
182
182
 
183
- **Large-file Read guard** — if Claude tries to read a file with more than 150 lines without specifying an `offset` and `limit`, the call is blocked and Claude is redirected to the orchestrator lookup chain (memory → graph → grep → targeted read). Prevents reading entire codebases when a targeted search would do.
183
+ **Large-file Read guard (Guard 1)** - a `Read` of a file over 150 lines that names no `limit` is denied, and the reason redirects Claude to the orchestrator lookup chain (memory, graph, grep, targeted read). Prevents reading entire codebases when a targeted search would do.
184
184
 
185
- **Duplicate file guard** — if Claude tries to write or create a file that already exists, it prints a warning showing the file path, line count, and last-modified timestamp, then presents three options: overwrite, edit in place, or cancel. Prevents silently replacing files you've already configured.
185
+ **Duplicate file guard (Guard 2)** - a `Write`, `create_file` or `write_file` naming a path that already exists returns `ask`, showing the path, line count and last-modified timestamp with three options: edit in place, confirm the overwrite, or cancel. `Edit` is deliberately not gated, because editing in place is the action this guard recommends.
186
186
 
187
- **Bash scan guard (Guard 3)** — intercepts every Bash tool call and pattern-matches the command string against 12 mass content-dump patterns before execution: deep `find` without `maxdepth 1`, `find -exec` with readers/shells, `xargs` with readers, `cat`/pager/grep with unquoted globs, command substitution with readers, shell loops, `mapfile`/`readarray`, `eval`/`source`/dot operator, alias remapping to readers, and obfuscation sequences. Commands over 8192 characters and unclosed quotes are blocked fail-closed. Operators can whitelist specific directory prefixes or exact tokens via `BASH_SCAN_ALLOWLIST` in the hook file.
187
+ **Bash scan guard (Guard 3)** - every `Bash` command is matched against twelve mass content-dump patterns before it runs: deep `find` without `-maxdepth 1`, `find -exec` with readers or shells, `xargs` with readers, `cat` or a pager followed by an unquoted glob, command substitution as a reader's argument, `grep -r` with a match-all pattern, `ls -R`, shell loops, `mapfile` and `readarray`, `eval`, `source` and the dot operator, alias remapping to a reader, and obfuscation sequences. Commands over 8192 characters and unclosed quotes are denied fail-closed.
188
+
189
+ Permanent exceptions live in `.claude/memory/bash-scan-allowlist.txt`, one entry per line, blank lines and `#` comments ignored and whitespace trimmed. An entry ending in `/` covers paths under that prefix, rejecting any suffix that walks up the tree with `..`; any other entry matches a whole command token. **Entries match literally: regex metacharacters carry no special meaning, so `file.ts` matches `file.ts` and nothing else.** The installer never ships or overwrites this file. Every line in it disarms patterns for matching commands, so give each entry a comment saying why it exists; an uncommented entry is a review smell.
190
+
191
+ Hit a block you believe is wrong? Re-run the command with `CC_GUARD3_WARN=1` and the guard asks instead of denying, carrying the same pattern ids. That is a triage aid for reporting a false positive while you keep working, not a configuration mode: the allowlist is the sanctioned permanent exception. The variable affects Guard 3 alone.
192
+
193
+ **graphify-out and node_modules guard (Guard 4)** - a `Read` whose path carries `graphify-out` or `node_modules` as an exact path component is denied, with backslashes and `..` resolved first. Use Glob for existence checks and the graphify skill for graph questions.
194
+
195
+ Input the hook cannot parse fails closed: it is denied with one stderr line naming `CC_HOOK_ALLOW=1`, which overrides that denial alone and leaves every guard fully active on every payload the hook can read. Set `CC_HOOK_DEBUG=1` to see the diagnostic lines it otherwise swallows.
188
196
 
189
197
  ### context-guard *(global + project)* — v1.15.0
190
198
 
@@ -276,6 +284,7 @@ code-conductor/
276
284
  │ │ ├── cc-stack.md /cc-stack
277
285
  │ │ └── cc-lang.md /cc-lang
278
286
  │ ├── hooks/
287
+ │ │ ├── graphify-ast-refresh.mjs Node wrapper: freshness + interpreter check
279
288
  │ │ └── graphify-ast-refresh.py Background AST refresh on UserPromptSubmit
280
289
  │ └── memory/
281
290
  │ └── personal.md Template (never committed)
@@ -297,7 +306,7 @@ code-conductor/
297
306
  │ │ ├── cc-test.md /cc-test
298
307
  │ │ └── cc-docs.md /cc-docs
299
308
  │ ├── hooks/
300
- │ │ ├── pre-tool-use.sh Large-file read guard + duplicate file guard + bash scan guard
309
+ │ │ ├── pre-tool-use.mjs Node front door: large-file, duplicate-write and graphify-out guards
301
310
  │ │ ├── context-guard.sh Turn-counter warning (.sh + .ps1)
302
311
  │ │ └── post-compact.sh Checkpoint reminder + cache sweep after `/compact` (.sh + .ps1)
303
312
  │ └── memory/
@@ -4,8 +4,8 @@ import { join } from 'node:path';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import { resolveAssetRoot, resolveHome, nodeMajorAtLeast } from '../lib/installer/env.mjs';
6
6
  import { assertAssets, assertMergeTargets, deployGlobal, deployProject, chmodHooks } from '../lib/installer/deploy.mjs';
7
- import { verbosityHookCommand, mergeVerbosityHook } from '../lib/installer/settings.mjs';
8
- import { writeVerbosity, seedMemoryFile, writeVersionFile } from '../lib/installer/config.mjs';
7
+ import { verbosityHookCommand, mergeVerbosityHook, graphifyHookCommand, mergeGraphifyHook } from '../lib/installer/settings.mjs';
8
+ import { writeVerbosity, writeVersionFile } from '../lib/installer/config.mjs';
9
9
 
10
10
  const USAGE = `Usage: code-conductor [--project] [--verbosity MIN|INFO|VERBOSE] [--version] [--help]`;
11
11
 
@@ -92,12 +92,12 @@ export function run(argv, env = process.env, { cwd = process.cwd(), log } = {})
92
92
  writing = true; // copy phase begins
93
93
  const claudeDir = deployGlobal(assetRoot, home);
94
94
  chmodHooks(claudeDir);
95
- seedMemoryFile(home, 'personal.md', assetRoot);
96
95
  const v = writeVerbosity(home, assetRoot, opts.verbosity, opts.verbosityGiven);
97
96
  if (v.warn) emit('stderr', v.warn);
98
97
  mergeVerbosityHook(join(claudeDir, 'settings.json'), verbosityHookCommand(home));
98
+ mergeGraphifyHook(join(claudeDir, 'settings.json'), graphifyHookCommand(home));
99
99
  writeVersionFile(home, pkgVersion(assetRoot));
100
- if (opts.project) deployProject(assetRoot, cwd);
100
+ if (opts.project) deployProject(assetRoot, cwd, { warn: (m) => emit('stderr', m) });
101
101
  return 0;
102
102
  } catch (err) {
103
103
  // Pre-flight failures (nothing written yet) → exit 1.
@@ -0,0 +1,91 @@
1
+ #!/usr/bin/env node
2
+ // UserPromptSubmit hook: Node wrapper over the Python AST-refresh payload.
3
+ //
4
+ // Node hosts the decision because Python is the thing being probed: a Python
5
+ // script cannot report that Python is missing. Every path exits 0 and prints
6
+ // nothing unless CC_GRAPHIFY_DEBUG is set (the CC_VERBOSITY_DEBUG and
7
+ // CC_GUARD4_DEBUG precedent), so a machine without the toolchain is silent.
8
+
9
+ import { statSync, accessSync, constants } from 'node:fs';
10
+ import { spawn } from 'node:child_process';
11
+ import { join, dirname, delimiter } from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+
14
+ const HOOK_DIR = dirname(fileURLToPath(import.meta.url));
15
+ const PAYLOAD = join(HOOK_DIR, 'graphify-ast-refresh.py');
16
+
17
+ function debug(msg) {
18
+ if (process.env.CC_GRAPHIFY_DEBUG) process.stderr.write(`GRAPHIFY_HOOK: ${msg}\n`);
19
+ }
20
+
21
+ // Mirrors the payload's int(os.environ.get("GRAPHIFY_STALE_MINUTES", "60")) and
22
+ // its ValueError fallback. Python's int() accepts surrounding whitespace and a
23
+ // sign and rejects everything else, while parseInt would read "120abc" as 120;
24
+ // the regex keeps the two readers of this variable in agreement.
25
+ function staleMinutes() {
26
+ const raw = process.env.GRAPHIFY_STALE_MINUTES;
27
+ if (typeof raw !== 'string' || !/^\s*[+-]?\d+\s*$/.test(raw)) return 60;
28
+ return Number.parseInt(raw, 10);
29
+ }
30
+
31
+ function isFresh(cwd) {
32
+ try {
33
+ const { mtimeMs } = statSync(join(cwd, 'graphify-out', '.graphify_ast_done'));
34
+ return (Date.now() - mtimeMs) / 60000 < staleMinutes();
35
+ } catch {
36
+ return false; // absent or unreadable sentinel counts as stale
37
+ }
38
+ }
39
+
40
+ function isExecutableFile(candidate) {
41
+ try {
42
+ if (!statSync(candidate).isFile()) return false;
43
+ accessSync(candidate, constants.X_OK);
44
+ return true;
45
+ } catch {
46
+ return false;
47
+ }
48
+ }
49
+
50
+ // A PATH scan, never an execution: starting an interpreter to learn whether an
51
+ // interpreter exists is the cost this hook is meant to avoid, and it is the
52
+ // reason no negative cache is needed.
53
+ function resolveInterpreter() {
54
+ const override = process.env.GRAPHIFY_PYTHON;
55
+ if (override && isExecutableFile(override)) return override;
56
+ const exts = process.platform === 'win32' ? ['.exe', '.bat', '.cmd'] : [''];
57
+ const dirs = (process.env.PATH || '').split(delimiter).filter(Boolean);
58
+ for (const name of ['python3', 'python']) {
59
+ for (const dir of dirs) {
60
+ for (const ext of exts) {
61
+ const candidate = join(dir, `${name}${ext}`);
62
+ if (isExecutableFile(candidate)) return candidate;
63
+ }
64
+ }
65
+ }
66
+ return null;
67
+ }
68
+
69
+ function main() {
70
+ const cwd = process.cwd();
71
+ if (isFresh(cwd)) return;
72
+ const python = resolveInterpreter();
73
+ if (!python) {
74
+ debug('no python3 or python on PATH; graph refresh skipped');
75
+ return;
76
+ }
77
+ // Detached with stdio ignored and unref'd: the child's exit status can never
78
+ // surface as a hook error, which is what keeps the `import graphify` guard in
79
+ // the payload where it already lives.
80
+ const child = spawn(python, [PAYLOAD], { cwd, detached: true, stdio: 'ignore', windowsHide: true });
81
+ child.on('error', (e) => debug(`spawn failed: ${e.message}`));
82
+ child.unref();
83
+ }
84
+
85
+ // No explicit process.exit: the unref'd child holds nothing open, so the default
86
+ // exit code 0 stands, and the deferred 'error' event above still gets to fire.
87
+ try {
88
+ main();
89
+ } catch (e) {
90
+ debug(`unexpected: ${e && e.message}`);
91
+ }
@@ -7,18 +7,5 @@
7
7
  "Bash(cat:*)"
8
8
  ],
9
9
  "deny": []
10
- },
11
- "hooks": {
12
- "UserPromptSubmit": [
13
- {
14
- "matcher": "",
15
- "hooks": [
16
- {
17
- "type": "command",
18
- "command": "python ~/.claude/hooks/graphify-ast-refresh.py"
19
- }
20
- ]
21
- }
22
- ]
23
10
  }
24
11
  }
@@ -32,14 +32,6 @@ export function writeVerbosity(home, assetRoot, requested, flagGiven) {
32
32
  return { level: 'MIN', warn: 'code-conductor: verbosity.md unreadable, reset to MIN' };
33
33
  }
34
34
 
35
- export function seedMemoryFile(home, relName, assetRoot) {
36
- const dst = join(home, '.claude', 'memory', relName);
37
- if (existsSync(dst)) return false;
38
- mkdirSync(dirname(dst), { recursive: true });
39
- copyFileSync(join(assetRoot, 'global', 'memory', relName), dst);
40
- return true;
41
- }
42
-
43
35
  // conductor-version.md is a plain data file, NOT markdown prose: exactly one bare
44
36
  // semver line plus a trailing newline (e.g. "1.22.0\n"). No frontmatter, no heading.
45
37
  // This matches the legacy install.sh contract, which reads it with `cat` and string-
@@ -1,7 +1,9 @@
1
1
  import { cpSync, mkdirSync, chmodSync, existsSync, lstatSync, readdirSync, readFileSync, statSync, rmSync, unlinkSync } from 'node:fs';
2
- import { join, relative, sep } from 'node:path';
2
+ import { join } from 'node:path';
3
3
  import { mergeFileInto, resolveRealTarget } from './file-merge.mjs';
4
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';
5
7
 
6
8
  // Host-authored data, not managed assets: these are merged, never force-copied —
7
9
  // everything else in the template keeps its overwrite. Keyed by the name the file
@@ -37,19 +39,6 @@ export function assertAssets(assetRoot, dirs) {
37
39
  }
38
40
  }
39
41
 
40
- // User data under global/memory (personal.md, verbosity.md) is preserved, so it
41
- // is excluded from the forced overwrite and seeded write-if-absent by config.mjs.
42
- // CLAUDE.md is excluded for a different reason: deployGlobal merges it instead.
43
- // The filter matches on the path RELATIVE to the copy source, so a parent
44
- // directory named e.g. "/memory/checkout/..." can never exclude every file.
45
- function skipHostOwned(sourceRoot) {
46
- return (src) => {
47
- const rel = relative(sourceRoot, src);
48
- if (rel === 'CLAUDE.md') return false;
49
- return rel !== 'memory' && !rel.startsWith(`memory${sep}`);
50
- };
51
- }
52
-
53
42
  // Derived from the shipped tree rather than a constant list: a hardcoded list
54
43
  // silently drifts the day a skill is added or renamed.
55
44
  function bundledSkillNames(assetRoot) {
@@ -107,16 +96,22 @@ export function deployGlobal(assetRoot, home) {
107
96
  const target = join(home, '.claude');
108
97
  const globalDir = join(assetRoot, 'global');
109
98
  mkdirSync(target, { recursive: true });
110
- cpSync(globalDir, target, { ...CP_OPTS, filter: skipHostOwned(globalDir) });
99
+ cpSync(globalDir, target, { ...CP_OPTS, filter: hostOwnedFilter(globalDir, GLOBAL_HOST_OWNED) });
111
100
  mergeFileInto(join(globalDir, 'CLAUDE.md'), join(target, 'CLAUDE.md'), mergeClaudeMdText);
112
101
  const skillsDir = join(target, 'skills');
113
102
  unblockSkillPaths(assetRoot, skillsDir);
114
103
  cpSync(join(assetRoot, 'skills'), skillsDir, CP_OPTS);
115
104
  sweepStaleFlatSkills(assetRoot, skillsDir);
116
- // skipHostOwned excludes global/memory from the copy, so cpSync never creates
117
- // <target>/memory. Create it explicitly here so the write-if-absent seeding in
118
- // config.mjs (and the version/verbosity writes) always has its parent dir.
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.
119
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);
120
115
  return target;
121
116
  }
122
117
 
@@ -134,7 +129,28 @@ function sweepStaleRootScripts(assetRoot, cwd) {
134
129
  if (matches) rmSync(staleDir, { recursive: true, force: true });
135
130
  }
136
131
 
137
- export function deployProject(assetRoot, cwd) {
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`));
138
154
  const target = join(cwd, '.claude');
139
155
  const templateRoot = join(assetRoot, 'project-template');
140
156
  // If something already occupies ./.claude and it is NOT a directory, this is a
@@ -149,7 +165,8 @@ export function deployProject(assetRoot, cwd) {
149
165
  // project-template mirrors the project root layout (a .claude/ subdir plus
150
166
  // root files like CLAUDE.md/.gitignore) — copy each half to its matching
151
167
  // destination instead of nesting the whole tree under target.
152
- cpSync(join(templateRoot, '.claude'), target, CP_OPTS);
168
+ const templateClaude = join(templateRoot, '.claude');
169
+ cpSync(templateClaude, target, { ...CP_OPTS, filter: hostOwnedFilter(templateClaude, PROJECT_HOST_OWNED) });
153
170
  for (const name of readdirSync(templateRoot)) {
154
171
  if (name === '.claude' || MERGED_ROOT_FILES.has(name)) continue;
155
172
  cpSync(join(templateRoot, name), join(cwd, name), CP_OPTS);
@@ -157,6 +174,14 @@ export function deployProject(assetRoot, cwd) {
157
174
  for (const [source, { target: dest, merge }] of MERGED_ROOT_FILES) {
158
175
  mergeFileInto(join(templateRoot, source), join(cwd, dest), merge);
159
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);
160
185
  // scripts/ is a sibling of project-template/ under assetRoot (source layout),
161
186
  // but is deployed as a CHILD of .claude/ (target) - it must stay inside the
162
187
  // project's self-contained .claude footprint, not spill into the host's own
@@ -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,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
+ }
@@ -2,6 +2,7 @@ import { readFileSync, writeFileSync, copyFileSync, existsSync, readdirSync, unl
2
2
  import { join, dirname, basename } from 'node:path';
3
3
 
4
4
  const FINGERPRINT = 'verbosity-remind.sh';
5
+ const GRAPHIFY_FINGERPRINT = 'graphify-ast-refresh';
5
6
  const MAX_MALFORMED_BACKUPS = 5;
6
7
  const MALFORMED_SUFFIX = '.malformed-backup.';
7
8
 
@@ -23,11 +24,21 @@ export function verbosityHookCommand(home) {
23
24
  return `bash ${hookPath}`;
24
25
  }
25
26
 
27
+ export function graphifyHookCommand(home) {
28
+ // Same absolute-path rule as verbosityHookCommand, for a second reason: a hook
29
+ // `command` with no `args` runs under PowerShell on a Windows host without Git
30
+ // Bash, and PowerShell does not expand a bare `~/...` passed to an external
31
+ // program. The installer is the only party that knows the host's home, so the
32
+ // shipped settings.json carries no graphify entry at all.
33
+ const hookPath = join(home, '.claude', 'hooks', 'graphify-ast-refresh.mjs').replace(/\\/g, '/');
34
+ return `node ${hookPath}`;
35
+ }
36
+
26
37
  function entryHasCommand(entry, predicate) {
27
38
  return entry && Array.isArray(entry.hooks) && entry.hooks.some(h => h && predicate(h));
28
39
  }
29
40
 
30
- function backupMalformed(settingsPath, now) {
41
+ export function backupMalformed(settingsPath, now) {
31
42
  const dst = `${settingsPath}${MALFORMED_SUFFIX}${utcStamp(now)}`;
32
43
  copyFileSync(settingsPath, dst);
33
44
  pruneMalformedBackups(settingsPath);
@@ -50,7 +61,12 @@ export function pruneMalformedBackups(settingsPath, keep = MAX_MALFORMED_BACKUPS
50
61
  pruneBackups(settingsPath, MALFORMED_SUFFIX, keep);
51
62
  }
52
63
 
53
- export function mergeVerbosityHook(settingsPath, hookCmd, now = new Date()) {
64
+ // One merge serves both hooks: same malformed-file handling, same idempotency
65
+ // rule, same canonical two-space write. `fingerprint` is the substring naming
66
+ // the entry this repo OWNS. Every entry matching it is replaced by hookCmd, so
67
+ // manual edits to an owned entry are discarded by design; every entry that does
68
+ // not match is left exactly as it was.
69
+ function mergeHook(settingsPath, hookCmd, fingerprint, now) {
54
70
  // A missing settings.json (ENOENT) is not an error: initialize a fresh, empty
55
71
  // config object and let the merge create the file. The existsSync check plus
56
72
  // the ENOENT catch guard against both the plain-missing case and a TOCTOU
@@ -75,7 +91,7 @@ export function mergeVerbosityHook(settingsPath, hookCmd, now = new Date()) {
75
91
 
76
92
  if (arr.some(e => entryHasCommand(e, h => h.command === hookCmd))) return { status: 'idempotent-skip' };
77
93
 
78
- arr = arr.filter(e => !entryHasCommand(e, h => typeof h.command === 'string' && h.command.includes(FINGERPRINT)));
94
+ arr = arr.filter(e => !entryHasCommand(e, h => typeof h.command === 'string' && h.command.includes(fingerprint)));
79
95
  arr.push({ matcher: '', hooks: [{ type: 'command', command: hookCmd }] });
80
96
  obj.hooks.UserPromptSubmit = arr;
81
97
  // Enforce 2-space indentation (matches install.sh's JSON.stringify(d,null,2) and the
@@ -86,3 +102,11 @@ export function mergeVerbosityHook(settingsPath, hookCmd, now = new Date()) {
86
102
  writeFileSync(settingsPath, JSON.stringify(obj, null, 2) + '\n', 'utf8');
87
103
  return { status: 'merged' };
88
104
  }
105
+
106
+ export function mergeVerbosityHook(settingsPath, hookCmd, now = new Date()) {
107
+ return mergeHook(settingsPath, hookCmd, FINGERPRINT, now);
108
+ }
109
+
110
+ export function mergeGraphifyHook(settingsPath, hookCmd, now = new Date()) {
111
+ return mergeHook(settingsPath, hookCmd, GRAPHIFY_FINGERPRINT, now);
112
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yeison.restrepo.r/code-conductor",
3
- "version": "1.24.1",
3
+ "version": "1.30.0",
4
4
  "description": "A spec-first, token-efficient Claude Code configuration and installer CLI.",
5
5
  "repository": {
6
6
  "type": "git",