@devrik-tools/claude-gates 0.4.0 → 0.7.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 (57) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/README.es.md +39 -4
  3. package/README.md +34 -5
  4. package/cli/config.mjs +126 -124
  5. package/cli/init.mjs +303 -276
  6. package/cli/install.mjs +281 -175
  7. package/cli/materialize.mjs +103 -102
  8. package/cli/registry.mjs +139 -136
  9. package/cli/smoke-fixtures.json +65 -0
  10. package/cli/task.mjs +140 -140
  11. package/package.json +1 -1
  12. package/plugins/gates/.claude-plugin/plugin.json +1 -1
  13. package/plugins/gates/hooks/ask-adoption.mjs +147 -147
  14. package/plugins/gates/hooks/doctor.mjs +207 -207
  15. package/plugins/gates/hooks/gates/atomic-commit/index.mjs +229 -0
  16. package/plugins/gates/hooks/gates/audit-before-build/index.mjs +110 -88
  17. package/plugins/gates/hooks/gates/autonomous-mode/index.mjs +50 -50
  18. package/plugins/gates/hooks/gates/bash-commands/index.mjs +215 -215
  19. package/plugins/gates/hooks/gates/brief-approved/index.mjs +216 -0
  20. package/plugins/gates/hooks/gates/brief-before-delegate/index.mjs +269 -265
  21. package/plugins/gates/hooks/gates/capability-map/index.mjs +701 -0
  22. package/plugins/gates/hooks/gates/circuit-breaker/index.mjs +527 -501
  23. package/plugins/gates/hooks/gates/diagnosis-before-patch/index.mjs +48 -43
  24. package/plugins/gates/hooks/gates/feature-catalog/index.mjs +83 -83
  25. package/plugins/gates/hooks/gates/force-parallel/index.mjs +134 -119
  26. package/plugins/gates/hooks/gates/forge-flow/index.mjs +134 -134
  27. package/plugins/gates/hooks/gates/implementation-pipeline/index.mjs +187 -187
  28. package/plugins/gates/hooks/gates/intent-flow/index.mjs +260 -260
  29. package/plugins/gates/hooks/gates/lint-commit/index.mjs +152 -149
  30. package/plugins/gates/hooks/gates/mandatory-flow/index.mjs +180 -180
  31. package/plugins/gates/hooks/gates/never-assume/index.mjs +59 -58
  32. package/plugins/gates/hooks/gates/no-blocking/index.mjs +163 -148
  33. package/plugins/gates/hooks/gates/no-coauthor/index.mjs +127 -0
  34. package/plugins/gates/hooks/gates/no-lint-suppression/index.mjs +183 -0
  35. package/plugins/gates/hooks/gates/protected-paths/index.mjs +149 -144
  36. package/plugins/gates/hooks/gates/recurrence-lock/index.mjs +91 -89
  37. package/plugins/gates/hooks/gates/reuse-before-build/index.mjs +263 -159
  38. package/plugins/gates/hooks/gates/risk-level/index.mjs +265 -263
  39. package/plugins/gates/hooks/gates/root-cause-first/index.mjs +57 -56
  40. package/plugins/gates/hooks/gates/root-whitelist/index.mjs +211 -131
  41. package/plugins/gates/hooks/gates/rule-skill-autodiscovery/index.mjs +181 -184
  42. package/plugins/gates/hooks/gates/sdd-specs/index.mjs +256 -256
  43. package/plugins/gates/hooks/gates/staged-lint/index.mjs +187 -0
  44. package/plugins/gates/hooks/gates/stop-pending/index.mjs +169 -164
  45. package/plugins/gates/hooks/gates/test-matrix/index.mjs +187 -187
  46. package/plugins/gates/hooks/gates/tool-map/index.mjs +168 -143
  47. package/plugins/gates/hooks/hooks.json +61 -0
  48. package/plugins/gates/hooks/lib/config.mjs +179 -172
  49. package/plugins/gates/hooks/lib/hook-io.mjs +367 -357
  50. package/plugins/gates/hooks/lib/signals.mjs +172 -127
  51. package/plugins/gates/hooks/wiring-check.mjs +227 -227
  52. package/plugins/tasks/.claude-plugin/plugin.json +1 -1
  53. package/plugins/tasks/hooks/hooks.json +26 -26
  54. package/plugins/tasks/hooks/lib/task-store.mjs +217 -197
  55. package/plugins/tasks/hooks/register-requests.mjs +145 -145
  56. package/plugins/tasks/hooks/session-tasks.mjs +108 -108
  57. package/registry.json +192 -1
@@ -1,265 +1,269 @@
1
- // brief-before-delegate — denies an implementation delegation whose prompt does not
2
- // declare, in recognizable form, a GOAL, concrete STEPS and a DONE-WHEN criterion.
3
- //
4
- // ── Why this is decidable, and what it deliberately does not judge ─────────────────
5
- // A hook sees a tool call, not how hard the underlying task is. "Complex" is not a
6
- // fact in the payload, and any heuristic that approximates it (file count, prompt
7
- // length, "architecture" keywords) ends up blocking trivial work sooner or later.
8
- // The decidable question is narrower: did THIS delegation's prompt state a goal, its
9
- // steps and a success criterion before the subagent starts? That is a fact about the
10
- // text itself, not a judgment about the task.
11
- //
12
- // Whether the declared goal is the RIGHT goal, or the steps are the RIGHT steps, or
13
- // the criterion truly resolves the ambiguity — that needs domain understanding a
14
- // script cannot supply. This gate only enforces that the brief EXISTS, never that it
15
- // is good. It DOES require each section to carry actual content past its marker —
16
- // pasting the words "Objetivo:"/"Criterio:" next to filler is not a brief either.
17
- //
18
- // ── What is exempt ───────────────────────────────────────────────────────────────
19
- // - Read-only exploration/subagents (readOnlySubagents param, or a prompt whose
20
- // dominant verb is investigate/search/read/explain/audit with no implementation
21
- // verb): that is a QUESTION, not an implementation order — forcing a brief onto it
22
- // would make it simulate project structure it does not have.
23
- // The readOnlySubagents exemption is a name the delegator declares, not a verified
24
- // capability this hook can check — so it is void whenever the prompt itself carries
25
- // a mutation-risk signal (money/auth/data/write/deploy): the signal in the text
26
- // outranks the label on the call.
27
- // - A prompt that already carries structure (a list, numbered steps, or prose that
28
- // otherwise states the three signals): the form is free, only the content is
29
- // required.
30
-
31
- import {
32
- runGate,
33
- deny,
34
- warn,
35
- toolInGroups,
36
- delegationPromptOf,
37
- } from '../../lib/hook-io.mjs';
38
- import { MUTATION_RISK_SIGNAL } from '../../lib/signals.mjs';
39
-
40
- const GATE_ID = 'brief-before-delegate';
41
- const CONFIG_KEY = 'requireBriefBeforeDelegating';
42
-
43
- const DEFAULT_MIN_BRIEF_LENGTH = 180;
44
- const DEFAULT_READ_ONLY_SUBAGENTS = ['explore', 'claude-code-guide', 'plan'];
45
-
46
- // How much of an over-length prompt to quote back in a denial message.
47
- const PROMPT_EXCERPT_LENGTH = 80;
48
- // Total signals this gate checks for (goal, steps, criterion): when all are missing at
49
- // once it is indistinguishable from "never thought through", so that combination denies
50
- // instead of only warning.
51
- const TOTAL_REQUIRED_SIGNALS = 3;
52
- // Minimum substantial (non-stopword) characters a section needs past its own marker to
53
- // count as "stated" instead of merely name-dropped. Chosen so a single short filler
54
- // word ("cosa.", "listo.") does not clear it, but any real sentence does.
55
- const MIN_SECTION_SUBSTANCE_LENGTH = 12;
56
-
57
- /** Unicode-aware word boundary: JS's `\b` does not treat accented letters as word
58
- * chars, so a plain `\bcorregi\b`-style pattern silently misses an accented
59
- * imperative. Lookarounds over `\p{L}|\p{N}|_` cover the full alphabet instead. */
60
- function withUnicodeWordBoundary(alternatives) {
61
- return new RegExp(
62
- `(?<![\\p{L}\\p{N}_])(${alternatives})(?![\\p{L}\\p{N}_])`,
63
- 'iu',
64
- );
65
- }
66
-
67
- const IMPLEMENTATION_VERBS = withUnicodeWordBoundary(
68
- 'implementa|implementar|escrib(e|í)|escribir|cre(a|á)|crear|corrige|correg(í|ir)|' +
69
- 'arregl(a|á)|arreglar|constru(ye|í)|construir|refactoriz(a|á)|refactorizar|' +
70
- 'migr(a|á)|migrar|agreg(a|á)|agregar|añad(e|í)|añadir|elimin(a|á)|eliminar|' +
71
- 'modific(a|á)|modificar|reescrib(e|í)|reescribir|desplieg(a|á)|desplegar|' +
72
- 'hac(e|er|é)|resuelve|resolv(é|er)|soluciona|solucion(á|ar)|encárgate|encargate|' +
73
- 'ocúpate|ocupate|cambi(a|á)|cambiar|actualiz(a|á)|actualizar|' +
74
- 'implement|write|fix|build|refactor|migrate|add|remove|modify|update',
75
- );
76
-
77
- const READ_ONLY_VERBS = withUnicodeWordBoundary(
78
- 'investiga|investigar|busca|buscar|explora|explorar|lee|leer|explica|explicar|' +
79
- 'audita|auditar|analiza|analizar|compara|comparar|diagnostica|diagnosticar|' +
80
- 'revisa|revisar|averigua|averiguar|' +
81
- 'investigate|search|explore|read|explain|audit|analyze|compare|diagnose|review',
82
- );
83
-
84
- // A prompt-level signal that a whitelisted read-only subagent name should NOT be
85
- // trusted to exempt this call: real mutation risk in the text outranks a self-declared
86
- // label. Deliberately broad (over-includes) — a false positive here only means the
87
- // brief check still runs, which is cheap; a false negative would let a mutator hide.
88
- // Centralized in lib/signals.mjs (ES+EN) — see its header for the class this covers.
89
- const MUTATION_RISK_SIGNAL_PATTERN = MUTATION_RISK_SIGNAL;
90
-
91
- /** Evidence of a stated GOAL, captured so its trailing content can be measured. */
92
- const GOAL_PATTERN = withUnicodeWordBoundary(
93
- 'objetivo|meta|el fin es|se busca|para lograr|para que|goal|objective',
94
- );
95
-
96
- /** Evidence of structured STEPS: a list/bullet/numbered form. Anchored per-line (`m`
97
- * flag) with a single bounded `\s*` after the line start, so there is no nested
98
- * quantifier for a backtracking engine to explode on. Global so every item's substance
99
- * can be checked, not just the first. */
100
- const STRUCTURED_STEPS_PATTERN = /^[ \t]*(?:[-*•]|\d+[.)])[ \t]+(\S.*)$/gm;
101
-
102
- /** Evidence of a DONE-WHEN / acceptance criterion. */
103
- const CRITERION_PATTERN = withUnicodeWordBoundary(
104
- 'criterio|acceptance|asserts?|se considera (hecho|terminado|listo)|' +
105
- 'debe (verificarse|cumplir|pasar)|hasta que|done.when|' +
106
- 'cuando (esto|el) (pase|funcione)|dado.{0,20}cuando.{0,20}entonces|' +
107
- 'given.{0,20}when.{0,20}then',
108
- );
109
-
110
- // Filler words that do not count toward a section's substance even though they are
111
- // real words — otherwise "listo cuando funcione bien y quede resuelto satisfactoriamente
112
- // para todos" reads as substantial despite saying nothing concrete.
113
- const FILLER_WORDS = new Set(
114
- (
115
- 'cosa cosas cualquier corresponda correspondiente relevante sistema bien listo ' +
116
- 'cuando funcione quede resuelto satisfactoriamente para todos segun paso arreglo ' +
117
- 'anything something whatever appropriate accordingly relevant properly done ' +
118
- 'the a an and or of to in on for with is are'
119
- ).split(' '),
120
- );
121
-
122
- function stripDiacritics(text) {
123
- return text.normalize('NFD').replace(/[̀-ͯ]/g, '');
124
- }
125
-
126
- /** Non-filler word count in a chunk of text: what is left after dropping stopwords and
127
- * pure-filler vocabulary, so a marker followed only by empty phrasing does not count as
128
- * substance. */
129
- function substantiveWordCount(text) {
130
- const words = stripDiacritics(String(text).toLowerCase())
131
- .split(/[^\p{L}\p{N}]+/u)
132
- .filter(Boolean);
133
- return words.filter((word) => word.length > 2 && !FILLER_WORDS.has(word))
134
- .length;
135
- }
136
-
137
- /** Text following a marker match, cut at end-of-line, so a following unrelated section
138
- * on the next line is not counted as this section's content. */
139
- function contentAfterMarker(prompt, markerMatch) {
140
- const from = markerMatch.index + markerMatch[0].length;
141
- const restOfLine = prompt.slice(from).split(/\r?\n/, 1)[0] ?? '';
142
- return restOfLine.replace(/^[\s:.\-–—]+/, '');
143
- }
144
-
145
- /** Whether the GOAL or CRITERION marker is followed by real substance: enough
146
- * substantive words, not just the marker itself or generic filler around it. */
147
- function markerHasSubstance(prompt, pattern) {
148
- const withGlobal = new RegExp(
149
- pattern.source,
150
- pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`,
151
- );
152
- const match = withGlobal.exec(prompt);
153
- if (!match) return false;
154
- const content = contentAfterMarker(prompt, match);
155
- return (
156
- content.trim().length >= MIN_SECTION_SUBSTANCE_LENGTH &&
157
- substantiveWordCount(content) >= 2
158
- );
159
- }
160
-
161
- /** Whether at least one structured list item carries real substance (not just a single
162
- * filler word like "paso"). */
163
- function stepsHaveSubstance(prompt) {
164
- const matches = [...prompt.matchAll(STRUCTURED_STEPS_PATTERN)];
165
- return matches.some((match) => substantiveWordCount(match[1]) >= 2);
166
- }
167
-
168
- function isReadOnlySubagentName(toolInput, readOnlySubagents) {
169
- const type = String(
170
- toolInput.subagent_type ?? toolInput.subagentType ?? '',
171
- ).toLowerCase();
172
- return new Set(readOnlySubagents.map((name) => name.toLowerCase())).has(type);
173
- }
174
-
175
- /** A whitelisted subagent name exempts a call ONLY when the prompt carries no
176
- * mutation-risk signal. The name is a declared label, never a verified capability this
177
- * hook can check — documented here so a future reader does not mistake it for one — and
178
- * a real risk signal in the text must win over it. */
179
- function isReadOnlySubagent(toolInput, prompt, readOnlySubagents) {
180
- if (!isReadOnlySubagentName(toolInput, readOnlySubagents)) return false;
181
- return !MUTATION_RISK_SIGNAL_PATTERN.test(prompt);
182
- }
183
-
184
- function isReadOnlyRequest(prompt) {
185
- if (IMPLEMENTATION_VERBS.test(prompt)) return false;
186
- return READ_ONLY_VERBS.test(prompt);
187
- }
188
-
189
- function missingSignals(prompt) {
190
- const missing = [];
191
- if (!markerHasSubstance(prompt, GOAL_PATTERN))
192
- missing.push('a stated GOAL with real content (what this aims to achieve, not just the word "goal")');
193
- if (!stepsHaveSubstance(prompt)) {
194
- missing.push('STEPS as a list or numbered form with concrete files/actions, not a placeholder item');
195
- }
196
- if (!markerHasSubstance(prompt, CRITERION_PATTERN)) {
197
- missing.push(
198
- 'a DONE-WHEN / acceptance criterion with real content (how completion is verified, not just the word "criterion")',
199
- );
200
- }
201
- return missing;
202
- }
203
-
204
- function denyTooShort(prompt) {
205
- const excerpt = prompt.slice(0, PROMPT_EXCERPT_LENGTH);
206
- const ellipsis = prompt.length > PROMPT_EXCERPT_LENGTH ? '…' : '';
207
- deny(
208
- GATE_ID,
209
- `This delegation asks for implementation ("${excerpt}${ellipsis}") in a ${prompt.length}-character ` +
210
- 'prompt too short to carry a goal, steps and a done-when criterion. State what this aims to ' +
211
- 'achieve, what concretely needs doing (as a list or steps), and how completion is verified, then ' +
212
- 'relaunch.',
213
- );
214
- }
215
-
216
- function reportMissingSignals(missing) {
217
- if (missing.length === 0) return;
218
-
219
- if (missing.length < TOTAL_REQUIRED_SIGNALS) {
220
- warn(
221
- GATE_ID,
222
- `This implementation delegation does not recognizably state: ${missing.join('; ')}. ` +
223
- 'If it is already there under different wording, proceed — this is only a warning. ' +
224
- 'Otherwise add it before the subagent starts blind.',
225
- );
226
- return;
227
- }
228
-
229
- deny(
230
- GATE_ID,
231
- 'This delegation asks for implementation but states neither as a list nor recognizable prose: ' +
232
- `${missing.join('; ')}. Add to the prompt: (1) the GOAL — what this aims to achieve; ` +
233
- '(2) the STEPS — concrete files/actions, as a list; (3) the CRITERION — how completion is ' +
234
- 'verified. The form is free; the content is not optional.',
235
- );
236
- }
237
-
238
- runGate(
239
- {
240
- id: GATE_ID,
241
- configKey: CONFIG_KEY,
242
- enabledByDefault: false,
243
- defaultParams: {
244
- minBriefLength: DEFAULT_MIN_BRIEF_LENGTH,
245
- readOnlySubagents: DEFAULT_READ_ONLY_SUBAGENTS,
246
- },
247
- },
248
- ({ toolName, toolInput, parameters }) => {
249
- if (!toolInGroups(toolName, ['delegation'])) return;
250
-
251
- const prompt = delegationPromptOf(toolInput);
252
- if (!prompt.trim()) return;
253
- if (isReadOnlySubagent(toolInput, prompt, parameters.readOnlySubagents))
254
- return;
255
- if (isReadOnlyRequest(prompt)) return;
256
- if (!IMPLEMENTATION_VERBS.test(prompt)) return; // neither implementation nor read-only: do not guess
257
-
258
- const trimmed = prompt.trim();
259
- if (trimmed.length < parameters.minBriefLength) {
260
- denyTooShort(trimmed);
261
- }
262
-
263
- reportMissingSignals(missingSignals(prompt));
264
- },
265
- );
1
+ // brief-before-delegate — denies an implementation delegation whose prompt does not
2
+ // declare, in recognizable form, a GOAL, concrete STEPS and a DONE-WHEN criterion.
3
+ //
4
+ // ── Why this is decidable, and what it deliberately does not judge ─────────────────
5
+ // A hook sees a tool call, not how hard the underlying task is. "Complex" is not a
6
+ // fact in the payload, and any heuristic that approximates it (file count, prompt
7
+ // length, "architecture" keywords) ends up blocking trivial work sooner or later.
8
+ // The decidable question is narrower: did THIS delegation's prompt state a goal, its
9
+ // steps and a success criterion before the subagent starts? That is a fact about the
10
+ // text itself, not a judgment about the task.
11
+ //
12
+ // Whether the declared goal is the RIGHT goal, or the steps are the RIGHT steps, or
13
+ // the criterion truly resolves the ambiguity — that needs domain understanding a
14
+ // script cannot supply. This gate only enforces that the brief EXISTS, never that it
15
+ // is good. It DOES require each section to carry actual content past its marker —
16
+ // pasting the words "Objetivo:"/"Criterio:" next to filler is not a brief either.
17
+ //
18
+ // ── What is exempt ───────────────────────────────────────────────────────────────
19
+ // - Read-only exploration/subagents (readOnlySubagents param, or a prompt whose
20
+ // dominant verb is investigate/search/read/explain/audit with no implementation
21
+ // verb): that is a QUESTION, not an implementation order — forcing a brief onto it
22
+ // would make it simulate project structure it does not have.
23
+ // The readOnlySubagents exemption is a name the delegator declares, not a verified
24
+ // capability this hook can check — so it is void whenever the prompt itself carries
25
+ // a mutation-risk signal (money/auth/data/write/deploy): the signal in the text
26
+ // outranks the label on the call.
27
+ // - A prompt that already carries structure (a list, numbered steps, or prose that
28
+ // otherwise states the three signals): the form is free, only the content is
29
+ // required.
30
+
31
+ import {
32
+ runGate,
33
+ deny,
34
+ warn,
35
+ toolInGroups,
36
+ delegationPromptOf,
37
+ } from '../../lib/hook-io.mjs';
38
+ import { MUTATION_RISK_SIGNAL } from '../../lib/signals.mjs';
39
+
40
+ const GATE_ID = 'brief-before-delegate';
41
+ const CONFIG_KEY = 'requireBriefBeforeDelegating';
42
+
43
+ const DEFAULT_MIN_BRIEF_LENGTH = 180;
44
+ const DEFAULT_READ_ONLY_SUBAGENTS = ['explore', 'claude-code-guide', 'plan'];
45
+
46
+ // How much of an over-length prompt to quote back in a denial message.
47
+ const PROMPT_EXCERPT_LENGTH = 80;
48
+ // Total signals this gate checks for (goal, steps, criterion): when all are missing at
49
+ // once it is indistinguishable from "never thought through", so that combination denies
50
+ // instead of only warning.
51
+ const TOTAL_REQUIRED_SIGNALS = 3;
52
+ // Minimum substantial (non-stopword) characters a section needs past its own marker to
53
+ // count as "stated" instead of merely name-dropped. Chosen so a single short filler
54
+ // word ("cosa.", "listo.") does not clear it, but any real sentence does.
55
+ const MIN_SECTION_SUBSTANCE_LENGTH = 12;
56
+
57
+ /** Unicode-aware word boundary: JS's `\b` does not treat accented letters as word
58
+ * chars, so a plain `\bcorregi\b`-style pattern silently misses an accented
59
+ * imperative. Lookarounds over `\p{L}|\p{N}|_` cover the full alphabet instead. */
60
+ function withUnicodeWordBoundary(alternatives) {
61
+ return new RegExp(
62
+ `(?<![\\p{L}\\p{N}_])(${alternatives})(?![\\p{L}\\p{N}_])`,
63
+ 'iu',
64
+ );
65
+ }
66
+
67
+ const IMPLEMENTATION_VERBS = withUnicodeWordBoundary(
68
+ 'implementa|implementar|escrib(e|í)|escribir|cre(a|á)|crear|corrige|correg(í|ir)|' +
69
+ 'arregl(a|á)|arreglar|constru(ye|í)|construir|refactoriz(a|á)|refactorizar|' +
70
+ 'migr(a|á)|migrar|agreg(a|á)|agregar|añad(e|í)|añadir|elimin(a|á)|eliminar|' +
71
+ 'modific(a|á)|modificar|reescrib(e|í)|reescribir|desplieg(a|á)|desplegar|' +
72
+ 'hac(e|er|é)|resuelve|resolv(é|er)|soluciona|solucion(á|ar)|encárgate|encargate|' +
73
+ 'ocúpate|ocupate|cambi(a|á)|cambiar|actualiz(a|á)|actualizar|' +
74
+ 'implement|write|fix|build|refactor|migrate|add|remove|modify|update',
75
+ );
76
+
77
+ const READ_ONLY_VERBS = withUnicodeWordBoundary(
78
+ 'investiga|investigar|busca|buscar|explora|explorar|lee|leer|explica|explicar|' +
79
+ 'audita|auditar|analiza|analizar|compara|comparar|diagnostica|diagnosticar|' +
80
+ 'revisa|revisar|averigua|averiguar|' +
81
+ 'investigate|search|explore|read|explain|audit|analyze|compare|diagnose|review',
82
+ );
83
+
84
+ // A prompt-level signal that a whitelisted read-only subagent name should NOT be
85
+ // trusted to exempt this call: real mutation risk in the text outranks a self-declared
86
+ // label. Deliberately broad (over-includes) — a false positive here only means the
87
+ // brief check still runs, which is cheap; a false negative would let a mutator hide.
88
+ // Centralized in lib/signals.mjs (ES+EN) — see its header for the class this covers.
89
+ const MUTATION_RISK_SIGNAL_PATTERN = MUTATION_RISK_SIGNAL;
90
+
91
+ /** Evidence of a stated GOAL, captured so its trailing content can be measured. */
92
+ const GOAL_PATTERN = withUnicodeWordBoundary(
93
+ 'objetivo|meta|el fin es|se busca|para lograr|para que|goal|objective',
94
+ );
95
+
96
+ /** Evidence of structured STEPS: a list/bullet/numbered form. Anchored per-line (`m`
97
+ * flag) with a single bounded `\s*` after the line start, so there is no nested
98
+ * quantifier for a backtracking engine to explode on. Global so every item's substance
99
+ * can be checked, not just the first. */
100
+ const STRUCTURED_STEPS_PATTERN = /^[ \t]*(?:[-*•]|\d+[.)])[ \t]+(\S.*)$/gm;
101
+
102
+ /** Evidence of a DONE-WHEN / acceptance criterion. */
103
+ const CRITERION_PATTERN = withUnicodeWordBoundary(
104
+ 'criterio|acceptance|asserts?|se considera (hecho|terminado|listo)|' +
105
+ 'debe (verificarse|cumplir|pasar)|hasta que|done.when|' +
106
+ 'cuando (esto|el) (pase|funcione)|dado.{0,20}cuando.{0,20}entonces|' +
107
+ 'given.{0,20}when.{0,20}then',
108
+ );
109
+
110
+ // Filler words that do not count toward a section's substance even though they are
111
+ // real words — otherwise "listo cuando funcione bien y quede resuelto satisfactoriamente
112
+ // para todos" reads as substantial despite saying nothing concrete.
113
+ const FILLER_WORDS = new Set(
114
+ (
115
+ 'cosa cosas cualquier corresponda correspondiente relevante sistema bien listo ' +
116
+ 'cuando funcione quede resuelto satisfactoriamente para todos segun paso arreglo ' +
117
+ 'anything something whatever appropriate accordingly relevant properly done ' +
118
+ 'the a an and or of to in on for with is are'
119
+ ).split(' '),
120
+ );
121
+
122
+ function stripDiacritics(text) {
123
+ return text.normalize('NFD').replace(/[̀-ͯ]/g, '');
124
+ }
125
+
126
+ /** Non-filler word count in a chunk of text: what is left after dropping stopwords and
127
+ * pure-filler vocabulary, so a marker followed only by empty phrasing does not count as
128
+ * substance. */
129
+ function substantiveWordCount(text) {
130
+ const words = stripDiacritics(String(text).toLowerCase())
131
+ .split(/[^\p{L}\p{N}]+/u)
132
+ .filter(Boolean);
133
+ return words.filter((word) => word.length > 2 && !FILLER_WORDS.has(word))
134
+ .length;
135
+ }
136
+
137
+ /** Text following a marker match, cut at end-of-line, so a following unrelated section
138
+ * on the next line is not counted as this section's content. */
139
+ function contentAfterMarker(prompt, markerMatch) {
140
+ const from = markerMatch.index + markerMatch[0].length;
141
+ const restOfLine = prompt.slice(from).split(/\r?\n/, 1)[0] ?? '';
142
+ return restOfLine.replace(/^[\s:.\-–—]+/, '');
143
+ }
144
+
145
+ /** Whether the GOAL or CRITERION marker is followed by real substance: enough
146
+ * substantive words, not just the marker itself or generic filler around it. */
147
+ function markerHasSubstance(prompt, pattern) {
148
+ const withGlobal = new RegExp(
149
+ pattern.source,
150
+ pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`,
151
+ );
152
+ const match = withGlobal.exec(prompt);
153
+ if (!match) return false;
154
+ const content = contentAfterMarker(prompt, match);
155
+ return (
156
+ content.trim().length >= MIN_SECTION_SUBSTANCE_LENGTH &&
157
+ substantiveWordCount(content) >= 2
158
+ );
159
+ }
160
+
161
+ /** Whether at least one structured list item carries real substance (not just a single
162
+ * filler word like "paso"). */
163
+ function stepsHaveSubstance(prompt) {
164
+ const matches = [...prompt.matchAll(STRUCTURED_STEPS_PATTERN)];
165
+ return matches.some((match) => substantiveWordCount(match[1]) >= 2);
166
+ }
167
+
168
+ function isReadOnlySubagentName(toolInput, readOnlySubagents) {
169
+ const type = String(
170
+ toolInput.subagent_type ?? toolInput.subagentType ?? '',
171
+ ).toLowerCase();
172
+ return new Set(readOnlySubagents.map((name) => name.toLowerCase())).has(type);
173
+ }
174
+
175
+ /** A whitelisted subagent name exempts a call ONLY when the prompt carries no
176
+ * mutation-risk signal. The name is a declared label, never a verified capability this
177
+ * hook can check — documented here so a future reader does not mistake it for one — and
178
+ * a real risk signal in the text must win over it. */
179
+ function isReadOnlySubagent(toolInput, prompt, readOnlySubagents) {
180
+ if (!isReadOnlySubagentName(toolInput, readOnlySubagents)) return false;
181
+ return !MUTATION_RISK_SIGNAL_PATTERN.test(prompt);
182
+ }
183
+
184
+ function isReadOnlyRequest(prompt) {
185
+ if (IMPLEMENTATION_VERBS.test(prompt)) return false;
186
+ return READ_ONLY_VERBS.test(prompt);
187
+ }
188
+
189
+ function missingSignals(prompt) {
190
+ const missing = [];
191
+ if (!markerHasSubstance(prompt, GOAL_PATTERN))
192
+ missing.push(
193
+ 'a stated GOAL with real content (what this aims to achieve, not just the word "goal")',
194
+ );
195
+ if (!stepsHaveSubstance(prompt)) {
196
+ missing.push(
197
+ 'STEPS as a list or numbered form with concrete files/actions, not a placeholder item',
198
+ );
199
+ }
200
+ if (!markerHasSubstance(prompt, CRITERION_PATTERN)) {
201
+ missing.push(
202
+ 'a DONE-WHEN / acceptance criterion with real content (how completion is verified, not just the word "criterion")',
203
+ );
204
+ }
205
+ return missing;
206
+ }
207
+
208
+ function denyTooShort(prompt) {
209
+ const excerpt = prompt.slice(0, PROMPT_EXCERPT_LENGTH);
210
+ const ellipsis = prompt.length > PROMPT_EXCERPT_LENGTH ? '…' : '';
211
+ deny(
212
+ GATE_ID,
213
+ `This delegation asks for implementation ("${excerpt}${ellipsis}") in a ${prompt.length}-character ` +
214
+ 'prompt — too short to carry a goal, steps and a done-when criterion. State what this aims to ' +
215
+ 'achieve, what concretely needs doing (as a list or steps), and how completion is verified, then ' +
216
+ 'relaunch.',
217
+ );
218
+ }
219
+
220
+ function reportMissingSignals(missing) {
221
+ if (missing.length === 0) return;
222
+
223
+ if (missing.length < TOTAL_REQUIRED_SIGNALS) {
224
+ warn(
225
+ GATE_ID,
226
+ `This implementation delegation does not recognizably state: ${missing.join('; ')}. ` +
227
+ 'If it is already there under different wording, proceed — this is only a warning. ' +
228
+ 'Otherwise add it before the subagent starts blind.',
229
+ );
230
+ return;
231
+ }
232
+
233
+ deny(
234
+ GATE_ID,
235
+ 'This delegation asks for implementation but states neither as a list nor recognizable prose: ' +
236
+ `${missing.join('; ')}. Add to the prompt: (1) the GOAL — what this aims to achieve; ` +
237
+ '(2) the STEPS — concrete files/actions, as a list; (3) the CRITERION — how completion is ' +
238
+ 'verified. The form is free; the content is not optional.',
239
+ );
240
+ }
241
+
242
+ runGate(
243
+ {
244
+ id: GATE_ID,
245
+ configKey: CONFIG_KEY,
246
+ enabledByDefault: false,
247
+ defaultParams: {
248
+ minBriefLength: DEFAULT_MIN_BRIEF_LENGTH,
249
+ readOnlySubagents: DEFAULT_READ_ONLY_SUBAGENTS,
250
+ },
251
+ },
252
+ ({ toolName, toolInput, parameters }) => {
253
+ if (!toolInGroups(toolName, ['delegation'])) return;
254
+
255
+ const prompt = delegationPromptOf(toolInput);
256
+ if (!prompt.trim()) return;
257
+ if (isReadOnlySubagent(toolInput, prompt, parameters.readOnlySubagents))
258
+ return;
259
+ if (isReadOnlyRequest(prompt)) return;
260
+ if (!IMPLEMENTATION_VERBS.test(prompt)) return; // neither implementation nor read-only: do not guess
261
+
262
+ const trimmed = prompt.trim();
263
+ if (trimmed.length < parameters.minBriefLength) {
264
+ denyTooShort(trimmed);
265
+ }
266
+
267
+ reportMissingSignals(missingSignals(prompt));
268
+ },
269
+ );