@codewizard-dt/bootstrap 2.14.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.
Files changed (40) hide show
  1. package/lib/hooks/README.md +639 -142
  2. package/lib/hooks/absolute-path-guard.js +142 -0
  3. package/lib/hooks/claude-settings-guard.js +200 -0
  4. package/lib/hooks/env-content-read-guard.js +367 -0
  5. package/lib/hooks/git-protected-ops-block.js +12 -7
  6. package/lib/hooks/interpreter-indirection-guard.js +576 -0
  7. package/lib/hooks/lib/command-parse.js +63 -0
  8. package/lib/hooks/package-install-consent.js +151 -0
  9. package/lib/hooks/protected-write-guard.js +237 -0
  10. package/lib/scripts/README.md +73 -8
  11. package/lib/scripts/build-mcp-guide.sh +9 -1
  12. package/lib/scripts/install-global.sh +62 -11
  13. package/lib/scripts/install-mcps.sh +140 -36
  14. package/lib/scripts/lib.sh +24 -15
  15. package/lib/scripts/merge-gitignore.sh +221 -33
  16. package/lib/scripts/merge-settings-deny.js +112 -39
  17. package/lib/scripts/merge-settings-hooks.js +374 -0
  18. package/lib/scripts/templates/file-suggestion.sh +142 -0
  19. package/lib/scripts/templates/gitignore +8 -0
  20. package/lib/scripts/templates/guides/stubs/playwright.md +2 -0
  21. package/lib/scripts/templates/settings-deny.json +81 -1
  22. package/lib/scripts/templates/settings-hooks.json +151 -0
  23. package/lib/skills/debug-logs/SKILL.md +1 -1
  24. package/lib/skills/git-commit/SKILL.md +8 -0
  25. package/package.json +5 -2
  26. package/raw/research/brave-mcp-single-docker-container/index.md +0 -94
  27. package/raw/research/brave-mcp-single-docker-container/sources.md +0 -70
  28. package/raw/research/dark-mode-theme/index.md +0 -85
  29. package/raw/research/dark-mode-theme/sources.md +0 -49
  30. package/raw/research/mcp-add-scope-writes/index.md +0 -46
  31. package/raw/research/mcp-add-scope-writes/sources.md +0 -38
  32. package/raw/research/mcp-one-process-per-user/index.md +0 -75
  33. package/raw/research/mcp-one-process-per-user/sources.md +0 -66
  34. package/raw/research/mcp-scope-conflict-handling/index.md +0 -61
  35. package/raw/research/mcp-scope-conflict-handling/sources.md +0 -32
  36. package/raw/research/serena-mcp-disconnect/index.md +0 -81
  37. package/raw/research/serena-mcp-disconnect/sources.md +0 -87
  38. package/raw/research/wiki-tooling-improvements/index.md +0 -126
  39. package/raw/research/wiki-tooling-improvements/sources.md +0 -73
  40. package/raw/software-factory-case-study.pdf +0 -0
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
- // Merge the canonical Bash deny list (templates/settings-deny.json) into the
3
- // user's ~/.claude/settings.json permissions.deny array.
2
+ // Merge the canonical permission deny list (templates/settings-deny.json) into
3
+ // the user's ~/.claude/settings.json permissions.deny array. Entries cover both
4
+ // Bash command patterns and file-tool path patterns (Edit(...) / Read(...)).
4
5
  //
5
6
  // Additive union only: canonical entries missing from the user's list are
6
7
  // appended; user entries are never removed, reordered, or deduplicated, and
@@ -12,7 +13,14 @@
12
13
  // leaving the target file untouched.
13
14
  //
14
15
  // Usage: merge-settings-deny.js [--target <path>] [--source <path>]
16
+ // merge-settings-deny.js --set-key <name> --set-value <json> [--target <path>]
15
17
  // --target/--source exist as test seams; the install flow passes no args.
18
+ //
19
+ // --set-key/--set-value is a separate operation: it sets one top-level settings
20
+ // key when that key is absent, no-ops when it is already deep-equal, and warns
21
+ // and leaves the file alone when it holds a different value. The deny merge does
22
+ // not run in this mode. A malformed --set-value is a usage error and exits
23
+ // non-zero; a malformed target still fails safe with exit 0.
16
24
 
17
25
  'use strict';
18
26
 
@@ -24,16 +32,20 @@ function parseArgs(argv) {
24
32
  const opts = {
25
33
  target: path.join(os.homedir(), '.claude', 'settings.json'),
26
34
  source: path.join(__dirname, 'templates', 'settings-deny.json'),
35
+ setKey: null,
36
+ setValue: null,
27
37
  };
28
38
  for (let i = 0; i < argv.length; i++) {
29
39
  if (argv[i] === '--target' && argv[i + 1]) opts.target = argv[++i];
30
40
  else if (argv[i] === '--source' && argv[i + 1]) opts.source = argv[++i];
41
+ else if (argv[i] === '--set-key' && argv[i + 1]) opts.setKey = argv[++i];
42
+ else if (argv[i] === '--set-value' && argv[i + 1]) opts.setValue = argv[++i];
31
43
  }
32
44
  return opts;
33
45
  }
34
46
 
35
47
  function warnSkip(message) {
36
- console.error(`Warning: ${message} — skipping deny-list merge`);
48
+ console.error(`Warning: ${message} — skipping ${operation}`);
37
49
  process.exit(0);
38
50
  }
39
51
 
@@ -41,39 +53,117 @@ function isPlainObject(value) {
41
53
  return typeof value === 'object' && value !== null && !Array.isArray(value);
42
54
  }
43
55
 
44
- const { target, source } = parseArgs(process.argv.slice(2));
56
+ // Structural comparison, not JSON.stringify equality: differing key order in an
57
+ // equivalent object must still count as a no-op, not a clobber warning.
58
+ function deepEqual(a, b) {
59
+ if (a === b) return true;
60
+ if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;
61
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
62
+ if (Array.isArray(a)) {
63
+ return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));
64
+ }
65
+ const keys = Object.keys(a);
66
+ if (keys.length !== Object.keys(b).length) return false;
67
+ return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k]));
68
+ }
45
69
 
46
- let canonical;
47
- try {
48
- canonical = JSON.parse(fs.readFileSync(source, 'utf8'));
49
- } catch (err) {
50
- warnSkip(`settings-deny template missing or invalid (${source})`);
70
+ function readTarget(file) {
71
+ if (!fs.existsSync(file)) return null;
72
+ try {
73
+ return fs.readFileSync(file, 'utf8');
74
+ } catch (err) {
75
+ warnSkip(`could not read ${file}`);
76
+ }
51
77
  }
52
- if (!Array.isArray(canonical) || !canonical.every((e) => typeof e === 'string')) {
53
- warnSkip(`settings-deny template is not an array of strings (${source})`);
78
+
79
+ function parseSettings(text, file) {
80
+ if (text === null) return {};
81
+ let parsed;
82
+ try {
83
+ parsed = JSON.parse(text);
84
+ } catch (err) {
85
+ warnSkip(`could not parse ${file} (file untouched)`);
86
+ }
87
+ if (!isPlainObject(parsed)) {
88
+ warnSkip(`${file} is not a JSON object (file untouched)`);
89
+ }
90
+ return parsed;
54
91
  }
55
92
 
56
- let raw = null;
57
- if (fs.existsSync(target)) {
93
+ // Reuse the file's existing indentation (tabs or N spaces); default 2 spaces.
94
+ function detectIndent(text) {
95
+ if (text === null) return ' ';
96
+ if (text.match(/\n(\t+)"/)) return '\t';
97
+ const spaceMatch = text.match(/\n( +)"/);
98
+ return spaceMatch ? spaceMatch[1] : ' ';
99
+ }
100
+
101
+ function writeSettings(file, value, indent) {
102
+ const tmp = `${file}.tmp-${process.pid}`;
58
103
  try {
59
- raw = fs.readFileSync(target, 'utf8');
104
+ fs.mkdirSync(path.dirname(file), { recursive: true });
105
+ fs.writeFileSync(tmp, JSON.stringify(value, null, indent) + '\n');
106
+ fs.renameSync(tmp, file);
60
107
  } catch (err) {
61
- warnSkip(`could not read ${target}`);
108
+ try { fs.unlinkSync(tmp); } catch (_) {}
109
+ warnSkip(`could not write ${file} (${err.message})`);
62
110
  }
63
111
  }
64
112
 
65
- let settings = {};
66
- if (raw !== null) {
113
+ const { target, source, setKey, setValue } = parseArgs(process.argv.slice(2));
114
+ const operation = setKey === null ? 'deny-list merge' : `"${setKey}" update`;
115
+
116
+ if (setKey !== null || setValue !== null) {
117
+ if (setKey === null) {
118
+ console.error('Error: --set-value requires --set-key <name>');
119
+ process.exit(1);
120
+ }
121
+ if (setValue === null) {
122
+ console.error(`Error: --set-key ${setKey} requires --set-value <json>`);
123
+ process.exit(1);
124
+ }
125
+
126
+ let value;
67
127
  try {
68
- settings = JSON.parse(raw);
128
+ value = JSON.parse(setValue);
69
129
  } catch (err) {
70
- warnSkip(`could not parse ${target} (file untouched)`);
130
+ console.error(`Error: --set-value is not valid JSON (${err.message})`);
131
+ process.exit(1);
71
132
  }
72
- if (!isPlainObject(settings)) {
73
- warnSkip(`${target} is not a JSON object (file untouched)`);
133
+
134
+ const rawTarget = readTarget(target);
135
+ const current = parseSettings(rawTarget, target);
136
+
137
+ if (Object.prototype.hasOwnProperty.call(current, setKey)) {
138
+ if (deepEqual(current[setKey], value)) {
139
+ console.log(`settings.json: "${setKey}" already set`);
140
+ } else {
141
+ console.error(
142
+ `Warning: settings.json already defines "${setKey}" — keeping it and skipping ${JSON.stringify(value)}`
143
+ );
144
+ }
145
+ process.exit(0);
74
146
  }
147
+
148
+ current[setKey] = value;
149
+ writeSettings(target, current, detectIndent(rawTarget));
150
+ console.log(`settings.json: "${setKey}" set`);
151
+ process.exit(0);
75
152
  }
76
153
 
154
+ let canonical;
155
+ try {
156
+ canonical = JSON.parse(fs.readFileSync(source, 'utf8'));
157
+ } catch (err) {
158
+ warnSkip(`settings-deny template missing or invalid (${source})`);
159
+ }
160
+ if (!Array.isArray(canonical) || !canonical.every((e) => typeof e === 'string')) {
161
+ warnSkip(`settings-deny template is not an array of strings (${source})`);
162
+ }
163
+
164
+ const raw = readTarget(target);
165
+ const settings = parseSettings(raw, target);
166
+
77
167
  if ('permissions' in settings && !isPlainObject(settings.permissions)) {
78
168
  warnSkip(`${target}: "permissions" is not an object (file untouched)`);
79
169
  }
@@ -98,24 +188,7 @@ if (added === 0 && raw !== null) {
98
188
  process.exit(0);
99
189
  }
100
190
 
101
- // Reuse the file's existing indentation (tabs or N spaces); default 2 spaces.
102
- let indent = ' ';
103
- if (raw !== null) {
104
- const tabMatch = raw.match(/\n(\t+)"/);
105
- const spaceMatch = raw.match(/\n( +)"/);
106
- if (tabMatch) indent = '\t';
107
- else if (spaceMatch) indent = spaceMatch[1];
108
- }
109
-
110
- const tmp = `${target}.tmp-${process.pid}`;
111
- try {
112
- fs.mkdirSync(path.dirname(target), { recursive: true });
113
- fs.writeFileSync(tmp, JSON.stringify(settings, null, indent) + '\n');
114
- fs.renameSync(tmp, target);
115
- } catch (err) {
116
- try { fs.unlinkSync(tmp); } catch (_) {}
117
- warnSkip(`could not write ${target} (${err.message})`);
118
- }
191
+ writeSettings(target, settings, detectIndent(raw));
119
192
 
120
193
  if (raw === null) {
121
194
  console.log(`settings.json: created with ${added} deny entries`);
@@ -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`);