@yeison.restrepo.r/code-conductor 1.24.1 → 1.31.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.
@@ -0,0 +1,509 @@
1
+ #!/usr/bin/env node
2
+ // PreToolUse front door. Contract: https://code.claude.com/docs/en/hooks (read 2026-09-25).
3
+ // Claude Code writes the payload to stdin as JSON; a decision is returned as
4
+ // hookSpecificOutput.permissionDecision and EVERY path exits 0. Nothing here exits 2:
5
+ // a deliberate denial must never be indistinguishable from a crashed script.
6
+ // Zero dependencies by design; node: builtins only.
7
+ import { readFileSync, statSync } from 'node:fs';
8
+ import { posix, join } from 'node:path';
9
+
10
+ const LINE_LIMIT = 150;
11
+ const BLOCKED_COMPONENTS = new Set(['graphify-out', 'node_modules']);
12
+
13
+ let emitted = false;
14
+
15
+ function debug(msg) {
16
+ if (process.env.CC_HOOK_DEBUG) process.stderr.write(`PRE_TOOL_USE: ${msg}\n`);
17
+ }
18
+
19
+ const deny = (reason) => ({ permissionDecision: 'deny', permissionDecisionReason: reason });
20
+ const ask = (reason) => ({ permissionDecision: 'ask', permissionDecisionReason: reason });
21
+
22
+ function emit(decision) {
23
+ if (emitted) return;
24
+ emitted = true;
25
+ process.stdout.write(JSON.stringify({
26
+ hookSpecificOutput: { hookEventName: 'PreToolUse', ...decision },
27
+ }) + '\n');
28
+ }
29
+
30
+ // `wc -l` counts newline characters and the 150-line threshold was calibrated against
31
+ // it, so count the same way rather than splitting (which would report one line more).
32
+ function countLines(text) {
33
+ let n = 0;
34
+ for (let i = 0; i < text.length; i++) if (text[i] === '\n') n++;
35
+ return n;
36
+ }
37
+
38
+ function isRegularFile(path) {
39
+ try { return statSync(path).isFile(); } catch { return false; }
40
+ }
41
+
42
+ // The platform sends `file_path` for Read/Write/Edit. The bash original read `path`,
43
+ // which no tool sends, which is why Guard 2 never fired even where the wiring worked;
44
+ // both are accepted so an MCP-provided create_file/write_file keeps working.
45
+ function targetPath(input) {
46
+ const raw = input.file_path ?? input.path;
47
+ return typeof raw === 'string' ? raw.trim() : '';
48
+ }
49
+
50
+ function stamp(ms) {
51
+ const d = new Date(ms);
52
+ const p = (n) => String(n).padStart(2, '0');
53
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
54
+ }
55
+
56
+ // Guard 4: reads of graphify-out/ and node_modules/ (BUG-017). Runs before Guard 1 for
57
+ // Read: a forbidden path is forbidden whatever its size, and deciding here spares a stat
58
+ // and a full file read on a path that is about to be denied anyway.
59
+ function guard4BlockedRead(input) {
60
+ const path = targetPath(input);
61
+ if (!path) return null; // Case A: nothing to verify
62
+ const normalized = posix.normalize(path.replace(/\\/g, '/'));
63
+ const parts = normalized.split('/').filter(p => p && p !== '.');
64
+ if (!parts.some(p => BLOCKED_COMPONENTS.has(p.toLowerCase()))) return null;
65
+ return deny(
66
+ 'Guard 4: direct reads of graphify-out/ and node_modules/ are forbidden. ' +
67
+ 'Use Glob for existence checks or the graphify skill: /graphify query "<question>".'
68
+ );
69
+ }
70
+
71
+ // Guard 1: a large-file Read with no limit. A path that cannot be stat'd has no size to
72
+ // exceed the threshold, so it allows.
73
+ function guard1LargeRead(input) {
74
+ if (input.limit !== undefined) return null;
75
+ const path = targetPath(input);
76
+ if (!path || !isRegularFile(path)) return null;
77
+ let lines;
78
+ try { lines = countLines(readFileSync(path, 'utf8')); }
79
+ catch (e) { debug(`guard 1 could not read ${path}: ${e.message}`); return null; }
80
+ if (lines <= LINE_LIMIT) return null;
81
+ return deny(
82
+ `Guard 1: LARGE FILE READ BLOCKED. File: ${path}. Lines: ${lines} ` +
83
+ `(>${LINE_LIMIT}, no limit specified). Follow the orchestrator lookup chain: ` +
84
+ '1. Check .claude/memory/project.md 2. Query graphify for structural questions ' +
85
+ '3. Use Grep/Glob for pattern searches 4. Read with explicit offset + limit.'
86
+ );
87
+ }
88
+
89
+ // Guard 2: writing over a file that already exists. "ask" rather than "deny" because the
90
+ // bash original printed a three-option prompt, and the contract's "ask" is that prompt in
91
+ // the platform's own vocabulary. Not registered for Edit: a targeted edit is the action
92
+ // this guard recommends, so gating it would contradict its own text.
93
+ function guard2DuplicateWrite(input) {
94
+ const path = targetPath(input);
95
+ if (!path || !isRegularFile(path)) return null;
96
+ let lines = '?';
97
+ try { lines = countLines(readFileSync(path, 'utf8')); } catch { /* keep '?' */ }
98
+ let modified = 'unknown';
99
+ try { modified = stamp(statSync(path).mtimeMs); } catch { /* keep 'unknown' */ }
100
+ return ask(
101
+ 'FILE ALREADY EXISTS\n' +
102
+ ` Path: ${path}\n` +
103
+ ` Lines: ${lines}\n` +
104
+ ` Last modified: ${modified}\n\n` +
105
+ ' Choose an action:\n' +
106
+ ' 1. Edit the existing file instead of overwriting\n' +
107
+ ' 2. Confirm you want to overwrite (re-issue the command)\n' +
108
+ ' 3. Cancel'
109
+ );
110
+ }
111
+
112
+ // ── Guard 3 constants ─────────────────────────────────────────────────────────
113
+ // POSIX ERE fragments from tests/fixtures/guard3-reference.sh, translated class by
114
+ // class. [[:space:]] in the C locale is EXACTLY [ \t\n\r\f\v]; JavaScript \s also
115
+ // matches U+00A0, U+2028, U+2029 and U+FEFF, so using it here would widen every
116
+ // check below and make the port disagree with its own authority. No \s \S \w \W \d
117
+ // \D appears anywhere in this block, and a test asserts that.
118
+ const SP = '[ \\t\\n\\r\\f\\v]';
119
+ const NSP = '[^ \\t\\n\\r\\f\\v]';
120
+ const G3_POS = '(^|[|;{([!&]|`|&&|\\|\\||;;|\\$\\(|<\\(|>\\(|(then|else|elif|do)' + SP + '|!' + SP + ')' + SP + '*';
121
+ const G3_MOD = '((env|exec|time|nohup|coproc|command|builtin)(' + SP + '+' + NSP + '+)*' + SP + '+)?';
122
+ const G3_PATH = '([A-Za-z0-9_./@%-]*/)?';
123
+ const G3_READERS = '(cat|less|more|head|tail|sed|awk|grep|egrep|fgrep|mapfile|readarray)';
124
+ const G3_SHELLS = '(sh|bash|dash|zsh|ksh|fish)';
125
+ const G3_MAX_LEN = 8192;
126
+ const G3_ALLOWLIST_REL = ['.claude', 'memory', 'bash-scan-allowlist.txt'];
127
+
128
+ const reFind = new RegExp(G3_POS + G3_MOD + G3_PATH + 'find(' + SP + '|$)');
129
+ const reCat = new RegExp(G3_POS + G3_MOD + G3_PATH + 'cat(' + SP + '|$)');
130
+ const rePager = new RegExp(G3_POS + G3_MOD + G3_PATH + '(less|more|head|tail|sed|awk)(' + SP + '|$)');
131
+ const reReader = new RegExp(G3_POS + G3_MOD + G3_PATH + G3_READERS + '(' + SP + '|$)');
132
+
133
+ // bash's `read -ra` splits on IFS (space, tab, newline), which is NARROWER than
134
+ // [[:space:]]. The token walks in P3 and P6 use this, everything else uses SP.
135
+ const IFS_SPLIT = /[ \t\n]+/;
136
+
137
+ // Join line continuations. A line ending in an ODD number of backslashes continues;
138
+ // an even number does not. bash's here-string appends a trailing newline, so a
139
+ // non-continued line always contributes one, including the last: the preprocessed
140
+ // string normally ends in a separator and every ([[:space:]]|$) anchor depends on it.
141
+ function g3JoinContinuations(input) {
142
+ let result = '';
143
+ for (const raw of input.split('\n')) {
144
+ const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;
145
+ let bs = 0;
146
+ while (bs < line.length && line[line.length - 1 - bs] === '\\') bs += 1;
147
+ if (bs % 2 === 1) result += line.slice(0, -1) + ' ';
148
+ else result += line + '\n';
149
+ }
150
+ return result;
151
+ }
152
+
153
+ // The five-state scanner, in two modes. "strip" removes unquoted comments and
154
+ // reports malformed input (a state other than UNQUOTED at end of input, meaning an
155
+ // unclosed quote). "glob" reports whether an unquoted glob character appears, and
156
+ // treats malformed input as a glob, which is the authority's fail-closed choice.
157
+ function g3Scan(mode, input) {
158
+ let state = 'UNQUOTED';
159
+ let result = '';
160
+ let i = 0;
161
+ const len = input.length;
162
+ while (i < len) {
163
+ const ch = input[i];
164
+ const two = input.slice(i, i + 2);
165
+ if (state === 'UNQUOTED') {
166
+ if (two === "$'") { if (mode === 'strip') result += two; i += 2; state = 'ANSI_C_QUOTED'; }
167
+ else if (two === '$"') { if (mode === 'strip') result += two; i += 2; state = 'LOCALE_QUOTED'; }
168
+ else if (ch === '\\') { if (mode === 'strip') result += input.slice(i, i + 2); i += 2; }
169
+ else if (ch === "'") { if (mode === 'strip') result += ch; i += 1; state = 'SINGLE_QUOTED'; }
170
+ else if (ch === '"') { if (mode === 'strip') result += ch; i += 1; state = 'DOUBLE_QUOTED'; }
171
+ else if (ch === '#' && mode === 'strip') { while (i < len && input[i] !== '\n') i += 1; }
172
+ else {
173
+ if (mode === 'glob' && (ch === '*' || ch === '?' || ch === '{' || ch === '[')) return { glob: true };
174
+ if (mode === 'strip') result += ch;
175
+ i += 1;
176
+ }
177
+ } else if (state === 'SINGLE_QUOTED') {
178
+ // Backslash is literal here and ANY quote exits: there is no escape mechanism.
179
+ if (mode === 'strip') result += ch;
180
+ if (ch === "'") state = 'UNQUOTED';
181
+ i += 1;
182
+ } else if (state === 'DOUBLE_QUOTED' || state === 'LOCALE_QUOTED') {
183
+ if (ch === '\\') { if (mode === 'strip') result += input.slice(i, i + 2); i += 2; }
184
+ else if (ch === '"') { if (mode === 'strip') result += ch; i += 1; state = 'UNQUOTED'; }
185
+ else { if (mode === 'strip') result += ch; i += 1; }
186
+ } else {
187
+ if (ch === '\\') { if (mode === 'strip') result += input.slice(i, i + 2); i += 2; }
188
+ else if (ch === "'") { if (mode === 'strip') result += ch; i += 1; state = 'UNQUOTED'; }
189
+ else { if (mode === 'strip') result += ch; i += 1; }
190
+ }
191
+ }
192
+ if (state !== 'UNQUOTED') return mode === 'strip' ? { result, malformed: true } : { glob: true };
193
+ return mode === 'strip' ? { result, malformed: false } : { glob: false };
194
+ }
195
+
196
+ // Each check returns true when it FIRES (the authority's shell functions returned 1).
197
+ //
198
+ // A quirk worth naming, because it looks like a bug and is not: the authority walks
199
+ // with `after="${rest:mlen}"`, slicing by the match LENGTH from position 0 rather
200
+ // than from the match index. For `ls; cat *.ts` the match is `; cat ` and bash's
201
+ // `after` is `at *.ts`, not `*.ts`. P4 and P7 reproduce that exactly. "Fixing" it
202
+ // would make the port disagree with the corpus.
203
+
204
+ function g3P1FindDepth(s) {
205
+ if (!reFind.test(s)) return false;
206
+ const m = new RegExp('-(-)?maxdepth[= \\t\\n\\r\\f\\v]+(\\+?)([0-9]+)').exec(s);
207
+ if (m) return m[3] !== '1';
208
+ return true;
209
+ }
210
+
211
+ function g3P2FindExec(s) {
212
+ if (!reFind.test(s)) return false;
213
+ if (!new RegExp('-(exec|execdir|ok|okdir)' + SP).test(s)) return false;
214
+ return new RegExp('-(exec|execdir|ok|okdir)' + SP + '+(' + G3_READERS + '|' + G3_SHELLS + ')(' + SP + '|$)').test(s);
215
+ }
216
+
217
+ function g3P3Xargs(s) {
218
+ if (!new RegExp(G3_POS + G3_MOD + 'xargs(' + SP + '|$)').test(s)) return false;
219
+ const at = s.indexOf('xargs');
220
+ const after = at === -1 ? '' : s.slice(at + 'xargs'.length);
221
+ const toks = after.split(IFS_SPLIT).filter(Boolean);
222
+ const optRe = /^(-I|--replace|-n|--max-args|-P|--max-procs|-s|--max-chars|-a|--arg-file|-d|--delimiter|-E|--eof)$/;
223
+ const utilRe = new RegExp('^(' + G3_READERS + '|' + G3_SHELLS + ')$');
224
+ let i = 0;
225
+ while (i < toks.length) {
226
+ const t = toks[i];
227
+ if (optRe.test(t)) {
228
+ if (i + 1 < toks.length && !/^-[A-Za-z]/.test(toks[i + 1])) i += 2;
229
+ else i += 1;
230
+ } else if (t.startsWith('-')) {
231
+ i += 1;
232
+ } else {
233
+ return utilRe.test(t);
234
+ }
235
+ }
236
+ return false;
237
+ }
238
+
239
+ function g3GlobWalk(s, re) {
240
+ let rest = s;
241
+ for (;;) {
242
+ const m = re.exec(rest);
243
+ if (!m) return false;
244
+ const after = rest.slice(m[0].length); // authority quirk: slice by length, not index
245
+ if (g3Scan('glob', after).glob) return true;
246
+ rest = after;
247
+ if (rest === '') return false;
248
+ }
249
+ }
250
+
251
+ function g3P4CatGlob(s) { return g3GlobWalk(s, reCat); }
252
+ function g3P7PagerGlob(s) { return g3GlobWalk(s, rePager); }
253
+
254
+ function g3P5CmdSubst(s) {
255
+ const m = reReader.exec(s);
256
+ if (!m) return false;
257
+ const at = s.indexOf(m[0]);
258
+ const after = at === -1 ? '' : s.slice(at + m[0].length);
259
+ if (/^"?\$\(([^)]+)\)"?(\/[A-Za-z0-9_./@%-]+)"?$/.test(after)) return false;
260
+ if (/\$\(/.test(after)) return true;
261
+ if (after.includes('`')) return true;
262
+ return false;
263
+ }
264
+
265
+ const G3_MATCHALL = '(\\.\\*|\\.|\\.\\+|\\^|"")';
266
+ const stripQuotes = (v) => v.replace(/'/g, '').replace(/"/g, '');
267
+
268
+ function g3GrepHasMatchAll(s) {
269
+ const whole = new RegExp('^' + G3_MATCHALL + '$');
270
+ const eRe = new RegExp(SP + '-e' + SP + '+(' + NSP + '+)');
271
+ let rest = s;
272
+ for (;;) {
273
+ const m = eRe.exec(rest);
274
+ if (!m) break;
275
+ if (whole.test(stripQuotes(m[1]))) return true;
276
+ const at = rest.indexOf(m[0]);
277
+ rest = at === -1 ? '' : rest.slice(at + m[0].length);
278
+ }
279
+ const rm = new RegExp('--regexp[= \\t\\n\\r\\f\\v]+(' + NSP + '+)').exec(s);
280
+ if (rm && whole.test(stripQuotes(rm[1]))) return true;
281
+ let seenCmd = false;
282
+ let pat = '';
283
+ for (const tok of s.split(IFS_SPLIT).filter(Boolean)) {
284
+ if (/^(git|grep|egrep|fgrep|-r|-R|--recursive|-[a-zA-Z]+)$/.test(tok)) { seenCmd = true; continue; }
285
+ if (!seenCmd) continue;
286
+ if (tok.includes('(') || tok.includes(')')) continue;
287
+ if (/^-/.test(tok)) continue;
288
+ if (/^(\/|\.\/|\.\.\/|~\/)/.test(tok)) continue;
289
+ if (tok.includes('/') && !/[*+?[\](){}^$|\\]/.test(tok)) continue;
290
+ pat = stripQuotes(tok);
291
+ break;
292
+ }
293
+ if (pat === '') return true;
294
+ return whole.test(pat);
295
+ }
296
+
297
+ function g3P6GrepMatchAll(s) {
298
+ if (new RegExp(SP + '-F(' + SP + '|$)').test(s)) return false;
299
+ if (new RegExp(SP + '--fixed-strings(' + SP + '|$)').test(s)) return false;
300
+ if (new RegExp(G3_POS + G3_MOD + '(grep|egrep|fgrep)(' + SP + '|$)').test(s)) {
301
+ if (!new RegExp(SP + '(-r|-R|--recursive)(' + SP + '|$)').test(s)) return false;
302
+ if (g3GrepHasMatchAll(s)) return true;
303
+ }
304
+ if (new RegExp(G3_POS + 'git' + SP + '+grep(' + SP + '|$)').test(s)) {
305
+ if (g3GrepHasMatchAll(s)) return true;
306
+ }
307
+ return false;
308
+ }
309
+
310
+ function g3P8LsRecursive(s) {
311
+ if (!new RegExp(G3_POS + G3_MOD + G3_PATH + 'ls(' + SP + '|$)').test(s)) return false;
312
+ if (new RegExp(SP + '--recursive(' + SP + '|$)').test(s)) return true;
313
+ if (new RegExp(SP + '-R(' + SP + '|$)').test(s)) return true;
314
+ if (new RegExp(SP + '-[a-zA-Z]*R[a-zA-Z]*(' + SP + '|$)').test(s)) return true;
315
+ return false;
316
+ }
317
+
318
+ function g3P9ShellLoop(s) {
319
+ return new RegExp(G3_POS + '(for|while|until)' + SP).test(s);
320
+ }
321
+
322
+ function g3P10SlurpBuiltins(s) {
323
+ return new RegExp(G3_POS + '(mapfile|readarray)(' + SP + '|$)').test(s);
324
+ }
325
+
326
+ function g3P11DynamicExec(s) {
327
+ if (new RegExp(G3_POS + '(eval|source)(' + SP + '|$)').test(s)) return true;
328
+ if (new RegExp(G3_POS + '\\.' + SP).test(s)) return true;
329
+ if (new RegExp(G3_POS + '\\.$').test(s)) return true;
330
+ return false;
331
+ }
332
+
333
+ function g3P12Alias(s) {
334
+ if (!new RegExp(G3_POS + 'alias' + SP).test(s)) return false;
335
+ const m = new RegExp('alias' + SP + '+[A-Za-z_][A-Za-z_0-9]*=(.+)').exec(s);
336
+ if (!m) return false;
337
+ let val = m[1];
338
+ val = val.replace(/^'/, '').replace(/'$/, '').replace(/^"/, '').replace(/"$/, '');
339
+ if (new RegExp('^(' + G3_READERS + '|eval|source|\\.)' + SP).test(val)) return true;
340
+ if (new RegExp('^(' + G3_READERS + '|eval|source|\\.)$').test(val)) return true;
341
+ return false;
342
+ }
343
+
344
+ function g3Obfuscation(s) {
345
+ if (/^\$"/.test(s)) return true;
346
+ if (new RegExp(G3_POS + '(\\\\.)+(' + SP + '|$)').test(s)) return true;
347
+ if (new RegExp(G3_POS + "[a-zA-Z]'[a-zA-Z]+'[a-zA-Z]").test(s)) return true;
348
+ return false;
349
+ }
350
+
351
+ // All thirteen in one place, in the authority's order. A reviewer reads this table,
352
+ // not the call sites.
353
+ const G3_CHECKS = [
354
+ { id: 'P1', check: g3P1FindDepth },
355
+ { id: 'P2', check: g3P2FindExec },
356
+ { id: 'P3', check: g3P3Xargs },
357
+ { id: 'P4', check: g3P4CatGlob },
358
+ { id: 'P5', check: g3P5CmdSubst },
359
+ { id: 'P6', check: g3P6GrepMatchAll },
360
+ { id: 'P7', check: g3P7PagerGlob },
361
+ { id: 'P8', check: g3P8LsRecursive },
362
+ { id: 'P9', check: g3P9ShellLoop },
363
+ { id: 'P10', check: g3P10SlurpBuiltins },
364
+ { id: 'P11', check: g3P11DynamicExec },
365
+ { id: 'P12', check: g3P12Alias },
366
+ { id: 'OBF', check: g3Obfuscation },
367
+ ];
368
+
369
+ // Operator policy, read fresh on every invocation so a change applies without a
370
+ // session restart. Absent means an empty list, which is policy, not a fault.
371
+ // Present-but-unreadable means an empty list PLUS a debug line, because that is a
372
+ // fault worth seeing, and neither condition may throw: a permissions problem on a
373
+ // policy file must never escalate into denying every tool call in the session.
374
+ function g3ReadAllowlist() {
375
+ let raw;
376
+ try {
377
+ raw = readFileSync(join(process.cwd(), ...G3_ALLOWLIST_REL), 'utf8');
378
+ } catch (e) {
379
+ if (e.code !== 'ENOENT') debug(`guard 3 allowlist unreadable: ${e.message}`);
380
+ return [];
381
+ }
382
+ return raw.split('\n')
383
+ .map(l => l.trim())
384
+ .filter(l => l !== '' && !l.startsWith('#'));
385
+ }
386
+
387
+ // Entries match LITERALLY. The authority interpolates them raw into an ERE, so its
388
+ // entry file.ts also matches fileXts; that leak is fixed here and the divergence is
389
+ // asserted by the corpus EXCEPTIONS row. Escaping also keeps an entry from adding a
390
+ // capture group, which would shift the suffix index below.
391
+ const g3EscapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
392
+ const G3_BD = '(^|[ \\t\\n\\r\\f\\v|;()])';
393
+ const G3_AD = '([ \\t\\n\\r\\f\\v|;()]|$)';
394
+
395
+ function g3AllowlistCovers(s, entries) {
396
+ if (entries.length === 0) return false;
397
+ for (const entry of entries) {
398
+ if (entry.endsWith('/')) {
399
+ const m = new RegExp(G3_BD + g3EscapeRe(entry) + '([A-Za-z0-9_./@%*?-]*)' + G3_AD).exec(s);
400
+ if (m) {
401
+ // G3_BD contributes group 1, so the suffix is group 2, matching the
402
+ // authority's BASH_REMATCH[2]. A suffix that walks up the tree is not
403
+ // covered: an allowlist entry must not become a path-traversal gift.
404
+ if (/(^|\/)\.\.(\/|$)/.test(m[2])) continue;
405
+ return true;
406
+ }
407
+ } else if (new RegExp(G3_BD + g3EscapeRe(entry) + G3_AD).test(s)) {
408
+ return true;
409
+ }
410
+ }
411
+ return false;
412
+ }
413
+
414
+ // bash's $( ) strips ALL trailing newlines from a command substitution, and the
415
+ // authority captures both preprocessing stages that way. The joiner appends a newline
416
+ // per line INCLUDING the last, so without this chomp the port's preprocessed string
417
+ // ends in a spurious ';' and every ([ \t\n\r\f\v]|$) end anchor silently fails:
418
+ // `ls -laR` stops matching P8, `alias c='cat'` stops matching P12, `git grep '.*'`
419
+ // stops matching P6 and `ls | xargs cat` stops matching P3.
420
+ const g3Chomp = (s) => s.replace(/\n+$/, '');
421
+
422
+ // CC_GUARD3_WARN converts THIS guard's denial into an ask carrying the identical
423
+ // reason, so a developer who hits a false positive mid-task sees the pattern ids and
424
+ // keeps working instead of filing an uninstall. It is documented as triage, not as
425
+ // configuration: the allowlist is the sanctioned permanent exception. It has no
426
+ // relationship to CC_HOOK_ALLOW, whose scope stays the two pre-verdict conditions.
427
+ function g3Blocked(detail) {
428
+ const decide = process.env.CC_GUARD3_WARN ? ask : deny;
429
+ return decide(
430
+ `BASH SCAN BLOCKED. ${detail} ` +
431
+ 'Authorized alternatives: 1. Grep for targeted content search with file and pattern scope. ' +
432
+ '2. Glob for path listing without file content. 3. Read with an explicit offset and limit. ' +
433
+ 'To permit a path permanently, add a commented entry to .claude/memory/bash-scan-allowlist.txt.'
434
+ );
435
+ }
436
+
437
+ // Guard 3: the bash command scanner, ported from tests/fixtures/guard3-reference.sh.
438
+ // That file remains the behavioral authority and both are driven by one shared corpus.
439
+ function guard3BashScan(input) {
440
+ const command = typeof input.command === 'string' ? input.command : '';
441
+ if (command === '') return null;
442
+ if (command.length > G3_MAX_LEN) {
443
+ return g3Blocked(`The command string exceeds the maximum scan length (${G3_MAX_LEN} chars).`);
444
+ }
445
+ const scan = g3Scan('strip', g3Chomp(g3JoinContinuations(command)));
446
+ if (scan.malformed) {
447
+ return g3Blocked('Malformed shell syntax (unclosed quote), blocked as a precaution.');
448
+ }
449
+ // Real newlines become semicolons so a multi-line script reads as a command
450
+ // sequence to every position-anchored pattern above.
451
+ const pre = g3Chomp(scan.result).split('\n').join(';');
452
+ const ids = [];
453
+ for (const { id, check } of G3_CHECKS) if (check(pre)) ids.push(id);
454
+ if (ids.length === 0) return null;
455
+ if (g3AllowlistCovers(pre, g3ReadAllowlist())) return null;
456
+ return g3Blocked(`The command triggered a mass content-dump pattern. Pattern ids: ${ids.join(' ')}.`);
457
+ }
458
+
459
+ const DISPATCH = {
460
+ Read: [guard4BlockedRead, guard1LargeRead],
461
+ Write: [guard2DuplicateWrite],
462
+ create_file: [guard2DuplicateWrite],
463
+ write_file: [guard2DuplicateWrite],
464
+ Edit: [],
465
+ Bash: [guard3BashScan],
466
+ };
467
+
468
+ // Case B. Unparseable input is not "nothing to verify", it is "the verifier could not
469
+ // run", which is the condition that fails closed. CC_HOOK_ALLOW bypasses THIS denial only;
470
+ // it does not suppress, alter or bypass any guard's decision on input that parses.
471
+ function unreadable(why) {
472
+ process.stderr.write(
473
+ `pre-tool-use: ${why}; no guard could inspect this call. ` +
474
+ 'Set CC_HOOK_ALLOW=1 to allow calls whose payload this hook cannot read.\n'
475
+ );
476
+ if (process.env.CC_HOOK_ALLOW) return;
477
+ emit(deny(
478
+ `Pre-tool-use hook: ${why}, so no guard could inspect this call. ` +
479
+ 'Unreadable input fails closed. Set CC_HOOK_ALLOW=1 to override.'
480
+ ));
481
+ }
482
+
483
+ function main() {
484
+ let raw = '';
485
+ try { raw = readFileSync(0, 'utf8'); }
486
+ catch (e) { debug(`stdin read failed: ${e.message}`); }
487
+
488
+ let payload;
489
+ try { payload = JSON.parse(raw); }
490
+ catch { return unreadable('stdin did not parse as JSON'); }
491
+
492
+ // Parsed, so not Case B. Anything the table cannot route on is unfamiliar-but-valid,
493
+ // and fail-closed is scoped to unparseable input, never to an additive payload change.
494
+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {
495
+ debug('payload is not a JSON object; allowing');
496
+ return;
497
+ }
498
+ const name = typeof payload.tool_name === 'string' ? payload.tool_name : '';
499
+ const rawInput = payload.tool_input;
500
+ const input = (rawInput && typeof rawInput === 'object' && !Array.isArray(rawInput)) ? rawInput : {};
501
+ const guards = DISPATCH[name];
502
+ if (!guards) { debug(`no guard registered for tool_name "${name}"; allowing`); return; }
503
+ for (const guard of guards) {
504
+ const decision = guard(input);
505
+ if (decision) { emit(decision); return; }
506
+ }
507
+ }
508
+
509
+ try { main(); } catch (e) { unreadable(`the hook threw (${e && e.message})`); }
@@ -2,11 +2,11 @@
2
2
  "hooks": {
3
3
  "PreToolUse": [
4
4
  {
5
- "matcher": "Write|Edit|create_file|write_file",
5
+ "matcher": "Read|Write|Edit|create_file|write_file|Bash",
6
6
  "hooks": [
7
7
  {
8
8
  "type": "command",
9
- "command": "bash -c 'h=\".claude/hooks/pre-tool-use.sh\"; [ -f \"$h\" ] && bash \"$h\" || { echo \"⚠ Hook missing — run /cc-init to repair\"; exit 0; }'"
9
+ "command": "node .claude/hooks/pre-tool-use.mjs"
10
10
  }
11
11
  ]
12
12
  }
@@ -36,6 +36,8 @@ You are a Senior Full-Stack Architect and Orchestrator specialized in spec-drive
36
36
  ## Session Initialization
37
37
  - At session start: use **Glob** (NEVER use Read) to check that `project.md` and
38
38
  `graphify-out/graph.json` exist; run `/cc-init` if absent.
39
+ - Guard 3 scans every `Bash` command for mass content-dump patterns and denies a match;
40
+ prefer Grep, Glob and a bounded Read. See README.md for the pattern list.
39
41
  - NEVER read raw files under `graphify-out/` or `node_modules/` — Guard 4 blocks such
40
42
  reads at the hook level. For graph queries, invoke the graphify skill:
41
43
  `/graphify query "<question>"`.
@@ -100,7 +102,7 @@ VERBOSITY: MIN (default)
100
102
  ## Hard Constraints
101
103
  - Never hardcode secrets, tokens, passwords, or API keys.
102
104
  - Never run destructive shell commands (rm -rf, git reset --hard, git push --force) without explicit user confirmation.
103
- - Never skip the pre-tool-use.sh hook; if it blocks a tool invocation, investigate — do not bypass.
105
+ - Never skip the pre-tool-use hook; if it blocks a tool invocation, investigate — do not bypass.
104
106
  - Never write code without an approved /cc-spec; never implement without an approved /cc-plan.
105
107
  - Never overwrite plan or tracking files in bulk; all state updates must be surgical single-line edits targeting one checkbox or field at a time (BUG-003 invariant).
106
108
  <!-- cc:managed:end -->
@@ -0,0 +1,42 @@
1
+ // scripts/claude-md-fields.mjs
2
+ // The canonical CLAUDE.md field list and the one resolved/unresolved predicate.
3
+ // detect-stack.mjs, init-wizard.mjs and the test fixtures all key off this module,
4
+ // so a field added here fails the suite on every side that has not followed.
5
+
6
+ export const FIELDS = [
7
+ { key: 'name', label: 'Name' },
8
+ { key: 'description', label: 'Description' },
9
+ { key: 'stack', label: 'Stack' },
10
+ { key: 'build', label: 'Build' },
11
+ { key: 'test', label: 'Test' },
12
+ { key: 'lint', label: 'Lint' },
13
+ { key: 'format', label: 'Format' },
14
+ { key: 'setup', label: 'Setup' },
15
+ ];
16
+
17
+ export const FIELD_KEYS = FIELDS.map(f => f.key);
18
+
19
+ export function fieldByKey(key) {
20
+ return FIELDS.find(f => f.key === key);
21
+ }
22
+
23
+ // The line `report` locates and `apply` replaces, e.g. `- Build:`.
24
+ export function canonicalLine(field) {
25
+ return `- ${field.label}:`;
26
+ }
27
+
28
+ // 'empty' | 'placeholder' for an unresolved value, null when resolved.
29
+ // Trimmed, or `- Build: <command> ` would miss the exact match and slip through as
30
+ // resolved. Case-sensitive: the template ships exactly one spelling, so only the
31
+ // lowercase `<command>` is a placeholder — `<COMMAND>` is a value someone typed.
32
+ // `N/A` is resolved: it means asked, and there is none.
33
+ export function unresolvedReason(value) {
34
+ const v = String(value ?? '').trim();
35
+ if (v === '') return 'empty';
36
+ if (v === '<command>') return 'placeholder';
37
+ return null;
38
+ }
39
+
40
+ export function isResolved(value) {
41
+ return unresolvedReason(value) === null;
42
+ }