@codewizard-dt/bootstrap 2.15.0 → 2.17.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.
@@ -16,24 +16,22 @@ for arg in "$@"; do
16
16
  [ "$arg" = "--skip-mcps" ] && SKIP_MCPS=true
17
17
  done
18
18
 
19
- # 1. Ensure global MCP servers are installed (user scope, non-interactive)
20
- # Pass --skip-mcps when MCPs were already handled interactively by the caller.
21
- if [ "$SKIP_MCPS" = false ]; then
22
- echo "Checking global MCP servers (user scope)..."
23
- "$SCRIPT_DIR/install-mcps.sh"
24
- echo ""
25
- fi
19
+ # Local/offline-safe steps (1-5) run first so hooks, skills, and settings
20
+ # always land; the network-dependent MCP install runs last (step 6), guarded
21
+ # so a failure cannot abort the script under `set -euo pipefail`.
26
22
 
27
- # 2. Install hooks globally
23
+ # 1. Install hooks globally
28
24
  GLOBAL_HOOKS_DIR="$HOME/.claude/hooks"
29
25
  if [ -d "$TEMPLATE_DIR/lib/hooks" ]; then
30
26
  echo "Installing hooks globally (~/.claude/hooks/)..."
31
27
  mkdir -p "$GLOBAL_HOOKS_DIR"
32
28
  rsync -av --exclude='.DS_Store' "$TEMPLATE_DIR/lib/hooks/" "$GLOBAL_HOOKS_DIR/"
33
29
  echo ""
30
+ else
31
+ echo "Warning: $TEMPLATE_DIR/lib/hooks not found — hook scripts NOT installed" >&2
34
32
  fi
35
33
 
36
- # 3. Install skills globally
34
+ # 2. Install skills globally
37
35
  echo "Installing skills globally (~/.claude/skills/)..."
38
36
 
39
37
  # Ensure the global skills directory exists
@@ -75,12 +73,30 @@ if [ ${#ORPHAN_FOUND[@]} -gt 0 ]; then
75
73
  fi
76
74
  fi
77
75
 
78
- # 4. Merge the canonical permission deny list into ~/.claude/settings.json
76
+ # 3. Merge the canonical permission deny list into ~/.claude/settings.json
79
77
  echo ""
80
78
  echo "Merging permissions deny list (~/.claude/settings.json)..."
81
79
  node "$SCRIPT_DIR/merge-settings-deny.js"
82
80
  echo ""
83
81
 
82
+ # 4. Merge the canonical hook wiring into ~/.claude/settings.json so the
83
+ # scripts installed in step 1 are actually registered (no more manual
84
+ # paste from lib/hooks/README.md).
85
+ echo "Merging hooks wiring (~/.claude/settings.json)..."
86
+ # The merge exits 0 on every outcome, so its message is the only way to tell
87
+ # a fresh/changed wiring from a no-op. Capture stdout+stderr together and
88
+ # echo it back; only nudge a restart when something actually changed.
89
+ HOOKS_WIRING_OUT="$(node "$SCRIPT_DIR/merge-settings-hooks.js" 2>&1)"
90
+ if [ -n "$HOOKS_WIRING_OUT" ]; then
91
+ echo "$HOOKS_WIRING_OUT"
92
+ fi
93
+ case "$HOOKS_WIRING_OUT" in
94
+ *'hooks wiring: created'*|*' applied'*)
95
+ echo "Restart Claude Code sessions to activate hook changes."
96
+ ;;
97
+ esac
98
+ echo ""
99
+
84
100
  # 5. Install the @-autocomplete file suggestion picker and register it
85
101
  echo "Installing file suggestion picker (~/.claude/file-suggestion.sh)..."
86
102
  mkdir -p "$HOME/.claude"
@@ -104,4 +120,16 @@ case "$FILE_SUGGESTION_OUT" in
104
120
  esac
105
121
  echo ""
106
122
 
107
- echo "Global setup complete (MCPs + hooks + skills + deny list + file suggestion)."
123
+ # 6. Ensure global MCP servers are installed (user scope, non-interactive) —
124
+ # LAST because it is the only network-dependent step, and guarded so a
125
+ # failure warns instead of aborting the local installs above.
126
+ # Pass --skip-mcps when MCPs were already handled interactively by the caller.
127
+ if [ "$SKIP_MCPS" = false ]; then
128
+ echo "Checking global MCP servers (user scope)..."
129
+ if ! "$SCRIPT_DIR/install-mcps.sh"; then
130
+ echo "Warning: MCP install failed — hooks, skills, and settings were installed; re-run 'bootstrap install' to retry MCPs." >&2
131
+ fi
132
+ echo ""
133
+ fi
134
+
135
+ echo "Global setup complete (hooks + skills + deny list + hooks wiring + file suggestion + MCPs)."
@@ -124,25 +124,30 @@ detect_installed_mcps() {
124
124
  # run_project_sync <project_dir> <script_dir>
125
125
  #
126
126
  # The shared setup/update sequence run identically by setup-project.sh and
127
- # update-project.sh: install MCPs interactively, install skills+hooks globally,
128
- # sync the wiki scaffold (tiered guide delivery — --interactive enables the
129
- # optional-guide prompts), merge the .gitignore, build the MCP-tools guide for
130
- # the detected MCPs, then bootstrap Serena's project.yml. Prints the same
131
- # section headers and blank-line separators the two scripts printed inline.
127
+ # update-project.sh: install skills+hooks globally first (offline-safe, via
128
+ # install-global.sh --skip-mcps), then attempt the interactive MCP install
129
+ # (guarded — a failure only warns and continues, it does not abort the rest
130
+ # of the sync), sync the wiki scaffold (tiered guide delivery — --interactive
131
+ # enables the optional-guide prompts), merge the .gitignore, build the
132
+ # MCP-tools guide for the detected MCPs, then bootstrap Serena's project.yml.
133
+ # Prints the same section headers and blank-line separators the two scripts
134
+ # printed inline.
132
135
  # ---------------------------------------------------------------------------
133
136
  run_project_sync() {
134
137
  local project_dir script_dir installed_mcps
135
138
  project_dir="$1"
136
139
  script_dir="$2"
137
140
 
138
- echo "Checking MCP servers..."
139
- "$script_dir/install-mcps.sh" --interactive --project-dir "$project_dir"
140
- echo ""
141
-
142
141
  echo "Installing skills and hooks globally..."
143
142
  "$script_dir/install-global.sh" --skip-mcps
144
143
  echo ""
145
144
 
145
+ echo "Checking MCP servers..."
146
+ if ! "$script_dir/install-mcps.sh" --interactive --project-dir "$project_dir"; then
147
+ echo "Warning: MCP install failed — continuing with wiki sync; re-run update to retry MCPs." >&2
148
+ fi
149
+ echo ""
150
+
146
151
  echo "Syncing wiki scaffold..."
147
152
  "$script_dir/sync-wiki-scaffold.sh" --interactive "$project_dir"
148
153
  "$script_dir/merge-gitignore.sh" --interactive "$project_dir"
@@ -86,6 +86,20 @@ section_missing_count() {
86
86
 
87
87
  added=0
88
88
 
89
+ # section_missing_lines <section-file>: print the entries that would be added,
90
+ # one per line, indented. Same selection logic as section_missing_count — a
91
+ # count alone ("3 new line(s)?") asks the user to consent to something they
92
+ # cannot see, so the prompt shows exactly what it will write.
93
+ section_missing_lines() {
94
+ local line trimmed
95
+ while IFS= read -r line || [ -n "$line" ]; do
96
+ trimmed="${line#"${line%%[![:space:]]*}"}"
97
+ [ -z "$trimmed" ] && continue
98
+ case "$trimmed" in \#*) continue ;; esac
99
+ grep -qFx -- "$line" "$EXISTING" || printf ' %s\n' "$line"
100
+ done < "$1"
101
+ }
102
+
89
103
  # merge_section <section-file>: append the section's missing lines, keeping
90
104
  # comment/blank lines buffered so headers only land when new entries follow.
91
105
  merge_section() {
@@ -114,26 +128,64 @@ merge_section() {
114
128
  done < "$1"
115
129
  }
116
130
 
131
+ # Tally before asking anything: the opening question should state the real
132
+ # scope, and a project with nothing to offer must not be asked at all.
133
+ total_missing=0
134
+ sections_offered=0
117
135
  i=1
118
136
  while [ "$i" -le "$SECTION_COUNT" ]; do
119
- SEC="$WORK_DIR/sec.$i"
120
- TITLE="section $i"
121
- [ -f "$WORK_DIR/title.$i" ] && TITLE="$(cat "$WORK_DIR/title.$i")"
122
- missing="$(section_missing_count "$SEC")"
123
- if [ "$missing" -eq 0 ]; then
124
- : # nothing new to offer for this section
125
- elif prompt_yn " Add/update .gitignore section '$TITLE' ($missing new line(s))? [y/N]: "; then
126
- merge_section "$SEC"
127
- else
128
- echo " .gitignore section '$TITLE': skipped."
137
+ n="$(section_missing_count "$WORK_DIR/sec.$i")"
138
+ if [ "$n" -gt 0 ]; then
139
+ total_missing=$((total_missing + n))
140
+ sections_offered=$((sections_offered + 1))
129
141
  fi
130
142
  i=$((i + 1))
131
143
  done
132
144
 
133
- if [ "$added" -eq 0 ]; then
134
- echo ".gitignore: no changes made in $PROJECT_DIR"
145
+ # One gate for the whole .gitignore pass, so a user who does not want their
146
+ # .gitignore touched answers once instead of once per section. This covers the
147
+ # section loop ONLY — the .git/info/exclude block below is a different mechanism
148
+ # (machine-local, never committed) and keeps its own prompt, so declining here
149
+ # still lets the sentinel repair run.
150
+ review_sections=0
151
+ if [ "$total_missing" -eq 0 ]; then
152
+ echo ".gitignore: already has everything the template offers in $PROJECT_DIR"
153
+ elif prompt_yn " Review .gitignore updates? ($total_missing line(s) across $sections_offered section(s)) [y/N]: "; then
154
+ review_sections=1
135
155
  else
156
+ echo ".gitignore: skipped entirely — no sections offered."
157
+ fi
158
+
159
+ if [ "$review_sections" -eq 1 ]; then
160
+ i=1
161
+ while [ "$i" -le "$SECTION_COUNT" ]; do
162
+ SEC="$WORK_DIR/sec.$i"
163
+ TITLE="section $i"
164
+ [ -f "$WORK_DIR/title.$i" ] && TITLE="$(cat "$WORK_DIR/title.$i")"
165
+ missing="$(section_missing_count "$SEC")"
166
+ if [ "$missing" -gt 0 ]; then
167
+ # Show the actual lines before asking. Comment/blank lines are omitted:
168
+ # they are only written as headers when a real entry follows, so listing
169
+ # them would misrepresent what the "y" adds.
170
+ echo " .gitignore section '$TITLE' would add $missing line(s):"
171
+ section_missing_lines "$SEC"
172
+ if prompt_yn " Add these to .gitignore? [y/N]: "; then
173
+ merge_section "$SEC"
174
+ else
175
+ echo " .gitignore section '$TITLE': skipped."
176
+ fi
177
+ fi
178
+ i=$((i + 1))
179
+ done
180
+ fi
181
+
182
+ # Only summarise when the section pass actually ran; the gate's own message
183
+ # already said what happened otherwise, and a second "no changes made" line
184
+ # reads as if something was attempted.
185
+ if [ "$added" -gt 0 ]; then
136
186
  echo ".gitignore: $added line(s) merged into $PROJECT_DIR"
187
+ elif [ "$review_sections" -eq 1 ]; then
188
+ echo ".gitignore: no changes made in $PROJECT_DIR"
137
189
  fi
138
190
 
139
191
  # Machine-local git exclusion for bootstrap agent state. These dirs must NEVER
@@ -0,0 +1,374 @@
1
+ #!/usr/bin/env node
2
+ // Merge the canonical hook wiring (templates/settings-hooks.json) into the
3
+ // user's ~/.claude/settings.json "hooks" key.
4
+ //
5
+ // This is a sibling of merge-settings-deny.js, not a new mode of it: the deny
6
+ // script does simple additive set-union over a flat array and has a frozen
7
+ // test suite that must not be disturbed. This script implements a structured,
8
+ // block-and-entry-aware "template owns its blocks" merge with materially
9
+ // different semantics (ownership, drift adoption, mixed-block handling).
10
+ //
11
+ // Ownership model:
12
+ // - An "owned" hook entry is one whose `command` references
13
+ // ~/.claude/hooks/<name>.js (or an equivalent absolute-path expansion of
14
+ // the same) where <name> (basename, extension stripped) also appears
15
+ // somewhere in the template. Anything else is "foreign" (user-added) and
16
+ // is never modified, reordered, or removed by this algorithm.
17
+ // - Foreign blocks, and any hooks event not present in the template (e.g.
18
+ // UserPromptSubmit), are completely untouched.
19
+ // - A block containing at least one foreign entry is "mixed": its matcher
20
+ // is never rewritten, and a repo hook found relocated inside it is left
21
+ // in place (with a warning) rather than duplicated into the template's
22
+ // expected block.
23
+ // - A block whose every entry is owned is "pure-owned" and is eligible for
24
+ // drift adoption: if its matcher doesn't match any template matcher for
25
+ // the event, but it shares an owned basename with a template block, its
26
+ // matcher is rewritten to the template's — this propagates a matcher
27
+ // rename shipped in the template without creating a duplicate block.
28
+ //
29
+ // Always exits 0 — the caller (install-global.sh) runs under `set -euo
30
+ // pipefail` and a settings merge must never abort an install. Any state we
31
+ // don't understand (unparseable JSON, unexpected shapes) warns and skips,
32
+ // leaving the target file untouched.
33
+ //
34
+ // Usage: merge-settings-hooks.js [--target <path>] [--source <path>]
35
+ // --target/--source exist as test seams; the install flow passes no args.
36
+ // No --set-key/--set-value mode here — that belongs to merge-settings-deny.js.
37
+
38
+ 'use strict';
39
+
40
+ const fs = require('fs');
41
+ const os = require('os');
42
+ const path = require('path');
43
+
44
+ // ---------------------------------------------------------------------------
45
+ // Helpers below are copied from merge-settings-deny.js (~lines 31-111) rather
46
+ // than shared, because that script's additive set-union semantics and frozen
47
+ // test suite must not be coupled to this script's block-ownership algorithm.
48
+ // ---------------------------------------------------------------------------
49
+
50
+ function parseArgs(argv) {
51
+ const opts = {
52
+ target: path.join(os.homedir(), '.claude', 'settings.json'),
53
+ source: path.join(__dirname, 'templates', 'settings-hooks.json'),
54
+ };
55
+ for (let i = 0; i < argv.length; i++) {
56
+ if (argv[i] === '--target' && argv[i + 1]) opts.target = argv[++i];
57
+ else if (argv[i] === '--source' && argv[i + 1]) opts.source = argv[++i];
58
+ }
59
+ return opts;
60
+ }
61
+
62
+ function warnSkip(message) {
63
+ console.error(`Warning: ${message} — skipping ${operation}`);
64
+ process.exit(0);
65
+ }
66
+
67
+ function isPlainObject(value) {
68
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
69
+ }
70
+
71
+ // Structural comparison, not JSON.stringify equality: differing key order in an
72
+ // equivalent object must still count as a no-op, not a clobber warning.
73
+ function deepEqual(a, b) {
74
+ if (a === b) return true;
75
+ if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;
76
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
77
+ if (Array.isArray(a)) {
78
+ return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));
79
+ }
80
+ const keys = Object.keys(a);
81
+ if (keys.length !== Object.keys(b).length) return false;
82
+ return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k]));
83
+ }
84
+
85
+ function readTarget(file) {
86
+ if (!fs.existsSync(file)) return null;
87
+ try {
88
+ return fs.readFileSync(file, 'utf8');
89
+ } catch (err) {
90
+ warnSkip(`could not read ${file}`);
91
+ }
92
+ }
93
+
94
+ function parseSettings(text, file) {
95
+ if (text === null) return {};
96
+ let parsed;
97
+ try {
98
+ parsed = JSON.parse(text);
99
+ } catch (err) {
100
+ warnSkip(`could not parse ${file} (file untouched)`);
101
+ }
102
+ if (!isPlainObject(parsed)) {
103
+ warnSkip(`${file} is not a JSON object (file untouched)`);
104
+ }
105
+ return parsed;
106
+ }
107
+
108
+ // Reuse the file's existing indentation (tabs or N spaces); default 2 spaces.
109
+ function detectIndent(text) {
110
+ if (text === null) return ' ';
111
+ if (text.match(/\n(\t+)"/)) return '\t';
112
+ const spaceMatch = text.match(/\n( +)"/);
113
+ return spaceMatch ? spaceMatch[1] : ' ';
114
+ }
115
+
116
+ function writeSettings(file, value, indent) {
117
+ const tmp = `${file}.tmp-${process.pid}`;
118
+ try {
119
+ fs.mkdirSync(path.dirname(file), { recursive: true });
120
+ fs.writeFileSync(tmp, JSON.stringify(value, null, indent) + '\n');
121
+ fs.renameSync(tmp, file);
122
+ } catch (err) {
123
+ try { fs.unlinkSync(tmp); } catch (_) {}
124
+ warnSkip(`could not write ${file} (${err.message})`);
125
+ }
126
+ }
127
+
128
+ // ---------------------------------------------------------------------------
129
+ // Block-ownership merge algorithm.
130
+ // ---------------------------------------------------------------------------
131
+
132
+ function clone(value) {
133
+ return JSON.parse(JSON.stringify(value));
134
+ }
135
+
136
+ // Extract the "<name>" out of a command referencing .claude/hooks/<name>.js,
137
+ // regardless of whether the path is the literal "~/.claude/hooks/..." form
138
+ // or an absolute-path expansion of it (e.g. "/Users/xxx/.claude/hooks/...").
139
+ // Matching keys off the trailing ".claude/hooks/<name>.js" segment — not a
140
+ // bare "hooks/<name>.js" — so a foreign command that happens to reference
141
+ // some unrelated .../hooks/ directory (e.g. a project-local lib/hooks/foo.js)
142
+ // is never misclassified as an owned ~/.claude hook, even if its basename
143
+ // collides with a shipped hook name.
144
+ function extractBasename(command) {
145
+ if (typeof command !== 'string') return null;
146
+ const re = /(?:^|[\\/])\.claude[\\/]hooks[\\/]([^\\/\s"']+)\.js\b/g;
147
+ let match;
148
+ let last = null;
149
+ while ((match = re.exec(command)) !== null) last = match[1];
150
+ return last;
151
+ }
152
+
153
+ // Collect every basename referenced anywhere in the template. This is the
154
+ // membership test for "owned": a target entry is owned only if its basename
155
+ // is one the template ships (and it's shaped like a hooks/<name>.js command).
156
+ function collectTemplateBasenames(template) {
157
+ const names = new Set();
158
+ for (const eventName of Object.keys(template)) {
159
+ const blocks = template[eventName];
160
+ if (!Array.isArray(blocks)) continue;
161
+ for (const block of blocks) {
162
+ if (!isPlainObject(block) || !Array.isArray(block.hooks)) continue;
163
+ for (const entry of block.hooks) {
164
+ if (!isPlainObject(entry)) continue;
165
+ const name = extractBasename(entry.command);
166
+ if (name) names.add(name);
167
+ }
168
+ }
169
+ }
170
+ return names;
171
+ }
172
+
173
+ function isOwnedEntry(entry, basenames) {
174
+ if (!isPlainObject(entry)) return false;
175
+ const name = extractBasename(entry.command);
176
+ return name !== null && basenames.has(name);
177
+ }
178
+
179
+ function hasOwnedEntry(block, basenames) {
180
+ return isPlainObject(block) && Array.isArray(block.hooks) && block.hooks.some((h) => isOwnedEntry(h, basenames));
181
+ }
182
+
183
+ function hasForeignEntry(block, basenames) {
184
+ return isPlainObject(block) && Array.isArray(block.hooks) && block.hooks.some((h) => !isOwnedEntry(h, basenames));
185
+ }
186
+
187
+ // Pure-owned: every entry in the block is owned, and there's at least one.
188
+ function isPureOwned(block, basenames) {
189
+ return (
190
+ isPlainObject(block) &&
191
+ Array.isArray(block.hooks) &&
192
+ block.hooks.length > 0 &&
193
+ block.hooks.every((h) => isOwnedEntry(h, basenames))
194
+ );
195
+ }
196
+
197
+ function sharesBasename(block, templateBlock) {
198
+ if (!isPlainObject(block) || !Array.isArray(block.hooks)) return false;
199
+ const names = new Set(block.hooks.map((h) => (isPlainObject(h) ? extractBasename(h.command) : null)).filter(Boolean));
200
+ return (templateBlock.hooks || []).some((e) => {
201
+ const name = isPlainObject(e) ? extractBasename(e.command) : null;
202
+ return name && names.has(name);
203
+ });
204
+ }
205
+
206
+ // Validate the template's shape strictly — a malformed template must never
207
+ // be partially trusted. Returns void; throws on any structural violation.
208
+ function validateTemplate(template) {
209
+ if (!isPlainObject(template)) throw new Error('not a JSON object');
210
+ for (const eventName of Object.keys(template)) {
211
+ const blocks = template[eventName];
212
+ if (!Array.isArray(blocks)) throw new Error(`"${eventName}" is not an array`);
213
+ for (const block of blocks) {
214
+ if (!isPlainObject(block) || !Array.isArray(block.hooks)) {
215
+ throw new Error(`"${eventName}" contains a block without a "hooks" array`);
216
+ }
217
+ for (const entry of block.hooks) {
218
+ if (!isPlainObject(entry) || typeof entry.command !== 'string') {
219
+ throw new Error(`"${eventName}" contains a hook entry without a "command" string`);
220
+ }
221
+ }
222
+ }
223
+ }
224
+ }
225
+
226
+ function findMatchingBlock(targetEvent, matcher, basenames) {
227
+ const candidates = targetEvent.filter((b) => isPlainObject(b) && b.matcher === matcher);
228
+ if (!candidates.length) return null;
229
+ return candidates.find((b) => hasOwnedEntry(b, basenames)) || candidates[0];
230
+ }
231
+
232
+ function findDriftCandidate(targetEvent, templateMatchers, templateBlock, basenames) {
233
+ return (
234
+ targetEvent.find(
235
+ (b) =>
236
+ isPureOwned(b, basenames) &&
237
+ !templateMatchers.has(b.matcher) &&
238
+ sharesBasename(b, templateBlock)
239
+ ) || null
240
+ );
241
+ }
242
+
243
+ const { target, source } = parseArgs(process.argv.slice(2));
244
+ const operation = 'hooks wiring merge';
245
+
246
+ let template;
247
+ try {
248
+ template = JSON.parse(fs.readFileSync(source, 'utf8'));
249
+ validateTemplate(template);
250
+ } catch (err) {
251
+ warnSkip(`hooks template missing or invalid (${source}: ${err.message})`);
252
+ }
253
+
254
+ const templateBasenames = collectTemplateBasenames(template);
255
+
256
+ const raw = readTarget(target);
257
+ const settings = parseSettings(raw, target);
258
+
259
+ if ('hooks' in settings && !isPlainObject(settings.hooks)) {
260
+ warnSkip(`${target}: "hooks" is not an object (file untouched)`);
261
+ }
262
+
263
+ // Top-level case: no file, or file with no "hooks" key at all — the template
264
+ // wins outright; no per-event/per-block logic runs.
265
+ if (raw === null || !('hooks' in settings)) {
266
+ settings.hooks = clone(template);
267
+ writeSettings(target, settings, detectIndent(raw));
268
+ console.log('hooks wiring: created');
269
+ process.exit(0);
270
+ }
271
+
272
+ const targetHooks = settings.hooks;
273
+ const changes = [];
274
+
275
+ // Only the events the template ships are ever visited — anything else already
276
+ // present in the target's hooks object (e.g. UserPromptSubmit) is untouched.
277
+ for (const eventName of Object.keys(template)) {
278
+ const templateEvent = template[eventName];
279
+
280
+ let targetEvent;
281
+ if (eventName in targetHooks) {
282
+ targetEvent = targetHooks[eventName];
283
+ if (!Array.isArray(targetEvent)) {
284
+ warnSkip(`${target}: "hooks.${eventName}" is not an array (file untouched)`);
285
+ }
286
+ } else {
287
+ targetEvent = [];
288
+ targetHooks[eventName] = targetEvent;
289
+ }
290
+
291
+ const templateMatchers = new Set(templateEvent.map((b) => b.matcher));
292
+
293
+ for (const templateBlock of templateEvent) {
294
+ let block = findMatchingBlock(targetEvent, templateBlock.matcher, templateBasenames);
295
+
296
+ if (!block) {
297
+ const drifted = findDriftCandidate(targetEvent, templateMatchers, templateBlock, templateBasenames);
298
+ if (drifted) {
299
+ const oldMatcher = drifted.matcher;
300
+ if ('matcher' in templateBlock) drifted.matcher = templateBlock.matcher;
301
+ else delete drifted.matcher;
302
+ changes.push(` ~ ${eventName} matcher adopted: ${oldMatcher} -> ${templateBlock.matcher}`);
303
+ block = drifted;
304
+ }
305
+ }
306
+
307
+ // A fresh placeholder block is NOT pushed into the target event yet: if
308
+ // every template entry turns out to be relocated into a mixed block
309
+ // elsewhere (warn, don't insert), pushing eagerly would persist an empty
310
+ // {matcher, hooks: []} block whenever another block causes a write in the
311
+ // same run. The push is deferred until at least one entry actually lands.
312
+ // Pre-existing blocks (matched or drift-adopted) are never touched by this
313
+ // guard — only a block this run itself created can be withheld.
314
+ let isNewBlock = false;
315
+ if (!block) {
316
+ block = {};
317
+ if ('matcher' in templateBlock) block.matcher = templateBlock.matcher;
318
+ block.hooks = [];
319
+ isNewBlock = true;
320
+ }
321
+ if (!Array.isArray(block.hooks)) block.hooks = [];
322
+
323
+ for (const templateEntry of templateBlock.hooks) {
324
+ const basename = extractBasename(templateEntry.command);
325
+ const ownedIdx = block.hooks.findIndex(
326
+ (h) => isOwnedEntry(h, templateBasenames) && extractBasename(h.command) === basename
327
+ );
328
+
329
+ if (ownedIdx !== -1) {
330
+ if (!deepEqual(block.hooks[ownedIdx], templateEntry)) {
331
+ block.hooks[ownedIdx] = clone(templateEntry);
332
+ changes.push(` ~ ${eventName}/${basename} replaced`);
333
+ }
334
+ continue;
335
+ }
336
+
337
+ // Not found in this block — check whether it's been relocated into a
338
+ // different, mixed (user-touched) block elsewhere in the same event.
339
+ // Never-remove/duplicate wins: leave it there, warn, don't duplicate.
340
+ let relocated = false;
341
+ for (const other of targetEvent) {
342
+ if (other === block || !isPlainObject(other) || !Array.isArray(other.hooks)) continue;
343
+ const foundHere = other.hooks.some(
344
+ (h) => isPlainObject(h) && extractBasename(h.command) === basename
345
+ );
346
+ if (foundHere && hasForeignEntry(other, templateBasenames)) {
347
+ console.error(
348
+ `Warning: ${eventName}/${basename} appears relocated into a user-modified block — leaving it in place, not duplicating`
349
+ );
350
+ relocated = true;
351
+ break;
352
+ }
353
+ }
354
+
355
+ if (!relocated) {
356
+ block.hooks.push(clone(templateEntry));
357
+ changes.push(` + ${eventName}/${basename} appended`);
358
+ }
359
+ }
360
+
361
+ // Deferred push (see above): only a freshly-created block that actually
362
+ // received entries joins the target event array.
363
+ if (isNewBlock && block.hooks.length > 0) targetEvent.push(block);
364
+ }
365
+ }
366
+
367
+ if (changes.length === 0) {
368
+ console.log('hooks wiring already up to date');
369
+ process.exit(0);
370
+ }
371
+
372
+ writeSettings(target, settings, detectIndent(raw));
373
+ for (const line of changes) console.log(line);
374
+ console.log(`hooks wiring: ${changes.length} change${changes.length === 1 ? '' : 's'} applied`);