@bbcsoftwarefactory/skills 0.0.0-stage → 0.1.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 (100) hide show
  1. package/dist/index.json +42 -0
  2. package/dist/skills/code-quality-gate/SKILL.md +59 -0
  3. package/dist/skills/code-quality-gate/references/gate-bigo.md +31 -0
  4. package/dist/skills/code-quality-gate/references/gate-earlyreturn.md +73 -0
  5. package/dist/skills/code-quality-gate/references/gate-typesafe.md +32 -0
  6. package/dist/skills/code-quality-gate/references/output-schema.yml +40 -0
  7. package/dist/skills/code-quality-gate/scripts/extract-diff-scope.py +225 -0
  8. package/dist/skills/code-quality-gate/tests/extract-diff-scope.test.sh +200 -0
  9. package/dist/skills/delivery-coordinator/SKILL.md +81 -0
  10. package/dist/skills/delivery-coordinator/references/hud-output.md +55 -0
  11. package/dist/skills/delivery-coordinator/references/intake.md +86 -0
  12. package/dist/skills/delivery-coordinator/references/issue-claim.md +143 -0
  13. package/dist/skills/delivery-coordinator/references/issue-dedup.md +38 -0
  14. package/dist/skills/delivery-coordinator/references/sleuth-regression-exercise.md +60 -0
  15. package/dist/skills/delivery-coordinator/references/visual-reference.md +45 -0
  16. package/dist/skills/delivery-coordinator/references/worktree-isolation.md +19 -0
  17. package/dist/skills/delivery-coordinator/scripts/check-issue-claim.py +363 -0
  18. package/dist/skills/delivery-coordinator/scripts/check-worktree-guard.py +220 -0
  19. package/dist/skills/delivery-coordinator/scripts/classify-change-lane.py +263 -0
  20. package/dist/skills/delivery-coordinator/tests/check-issue-claim.test.sh +221 -0
  21. package/dist/skills/delivery-coordinator/tests/check-worktree-guard.test.sh +123 -0
  22. package/dist/skills/delivery-coordinator/tests/classify-change-lane.test.sh +124 -0
  23. package/dist/skills/documentation-steward/SKILL.md +43 -0
  24. package/dist/skills/documentation-steward/references/discovery.md +17 -0
  25. package/dist/skills/documentation-steward/references/handoff.md +15 -0
  26. package/dist/skills/greptile-review-loop/SKILL.md +57 -0
  27. package/dist/skills/greptile-review-loop/references/review-protocol.md +37 -0
  28. package/dist/skills/greptile-review-loop/scripts/review-loop.py +435 -0
  29. package/dist/skills/greptile-review-loop/tests/review-loop.test.sh +331 -0
  30. package/dist/skills/issue-reviewer/SKILL.md +87 -0
  31. package/dist/skills/issue-reviewer/references/review-format.md +100 -0
  32. package/dist/skills/issue-reviewer/references/triage.md +105 -0
  33. package/dist/skills/issue-reviewer/scripts/fetch-issue-attachments.py +239 -0
  34. package/dist/skills/issue-reviewer/scripts/plan-issue-triage.py +311 -0
  35. package/dist/skills/issue-reviewer/tests/fetch-issue-attachments.test.sh +90 -0
  36. package/dist/skills/issue-reviewer/tests/plan-issue-triage.test.sh +168 -0
  37. package/dist/skills/question-gate/SKILL.md +66 -0
  38. package/dist/skills/question-gate/references/client-hooks.md +111 -0
  39. package/dist/skills/question-gate/references/diagram-routing.md +58 -0
  40. package/dist/skills/question-gate/scripts/triage-question.py +713 -0
  41. package/dist/skills/question-gate/tests/fixtures/question-corpus.json +481 -0
  42. package/dist/skills/question-gate/tests/question-corpus.test.sh +32 -0
  43. package/dist/skills/question-gate/tests/triage-question.test.sh +441 -0
  44. package/dist/skills/regression-testing/SKILL.md +49 -0
  45. package/dist/skills/regression-testing/references/evidence-record.md +35 -0
  46. package/dist/skills/requirements-spec/SKILL.md +59 -0
  47. package/dist/skills/risk-scout/SKILL.md +53 -0
  48. package/dist/skills/risk-scout/references/risk-matrix.md +49 -0
  49. package/dist/skills/skill-clean-architecture/SKILL.md +54 -0
  50. package/dist/skills/skill-clean-architecture/references/layer-rules.md +22 -0
  51. package/dist/skills/skill-clean-architecture/references/source-headers.md +31 -0
  52. package/dist/skills/skill-clean-architecture/scripts/measure-bigo.py +427 -0
  53. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/bad-utf8.js +1 -0
  54. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/edge-crlf.ts +6 -0
  55. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/edge-mixed.ts +15 -0
  56. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/empty.js +0 -0
  57. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/no-newline.js +1 -0
  58. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo.expected.yml +95 -0
  59. package/dist/skills/skill-clean-architecture/tests/measure-bigo.test.sh +222 -0
  60. package/dist/skills/tool-depot/SKILL.md +47 -0
  61. package/dist/skills/tool-depot/references/checkout.md +29 -0
  62. package/dist/skills/tool-depot/references/loki-read.md +41 -0
  63. package/dist/skills/tool-depot/references/readonly-access.md +84 -0
  64. package/dist/skills/tool-depot/references/tool-catalog.json +47 -0
  65. package/dist/skills/tool-depot/scripts/loki-runtime-logs.py +305 -0
  66. package/dist/skills/tool-depot/tests/loki-runtime-logs.test.sh +101 -0
  67. package/dist/skills/watcher-observability/SKILL.md +73 -0
  68. package/dist/skills/watcher-observability/references/batch-protocol.md +44 -0
  69. package/dist/skills/watcher-observability/references/configuration.md +31 -0
  70. package/dist/skills/watcher-observability/references/error-scan.md +102 -0
  71. package/dist/skills/watcher-observability/references/live-protocol.md +49 -0
  72. package/dist/skills/watcher-observability/references/server-account.md +72 -0
  73. package/dist/skills/watcher-observability/scripts/error-scan.py +318 -0
  74. package/dist/skills/watcher-observability/scripts/resolve-containers.py +155 -0
  75. package/dist/skills/watcher-observability/scripts/save-counts.py +381 -0
  76. package/dist/skills/watcher-observability/scripts/summarize-logs.py +113 -0
  77. package/dist/skills/watcher-observability/scripts/watch-live.py +606 -0
  78. package/dist/skills/watcher-observability/server/watcher-gate.sh +51 -0
  79. package/dist/skills/watcher-observability/tests/error-scan.test.sh +257 -0
  80. package/dist/skills/watcher-observability/tests/live-windows.test.sh +177 -0
  81. package/dist/skills/watcher-observability/tests/resolve-containers.test.sh +87 -0
  82. package/dist/skills/watcher-observability/tests/save-counts.test.sh +338 -0
  83. package/dist/skills/watcher-observability/tests/sleuth.test.sh +176 -0
  84. package/dist/skills/watcher-observability/tests/summarize-logs.test.sh +105 -0
  85. package/dist/skills/watcher-observability/tests/watcher-config.test.sh +70 -0
  86. package/dist/skills/watcher-observability/tests/watcher-gate.test.sh +110 -0
  87. package/dist/skills/watcher-observability/watcher.json +1 -0
  88. package/dist/skills/workflow-auditor/SKILL.md +55 -0
  89. package/dist/skills/workflow-auditor/references/audit-protocol.md +49 -0
  90. package/dist/skills/workflow-auditor/references/ledger.md +122 -0
  91. package/dist/skills/workflow-auditor/scripts/audit-ledger.py +624 -0
  92. package/dist/skills/workflow-auditor/scripts/list-zed-commands.py +183 -0
  93. package/dist/skills/workflow-auditor/scripts/render-workflow.py +201 -0
  94. package/dist/skills/workflow-auditor/scripts/validate-skills.py +444 -0
  95. package/dist/skills/workflow-auditor/tests/audit-ledger.test.sh +660 -0
  96. package/dist/skills/workflow-auditor/tests/list-zed-commands.test.sh +93 -0
  97. package/dist/skills/workflow-auditor/tests/render-workflow.test.sh +135 -0
  98. package/dist/skills/workflow-auditor/tests/validate-skills.test.sh +190 -0
  99. package/package.json +27 -6
  100. package/README.md +0 -3
@@ -0,0 +1,713 @@
1
+ """Pre-exit and pre-question triage against the BuilderBot skill workflow diagram.
2
+
3
+ Read-only: inspects a proposed question (or hook payload) and optional delivery ledger,
4
+ then classifies each clause as delegable to a diagram skill, already authorized in the
5
+ ledger, or a genuine human approval gate.
6
+ """
7
+
8
+ import argparse
9
+ import json
10
+ from pathlib import Path
11
+ import re
12
+ import subprocess
13
+ import sys
14
+ import unicodedata
15
+
16
+ LEDGER_NAME = 'bbc-delivery-ledger.json'
17
+
18
+ CODE_FENCE_RE = re.compile(r'```[\s\S]*?```')
19
+ SPLIT_CLAUSE_RE = re.compile(
20
+ r'\s+(?:o\s+(?:prefieres|quieres|mejor|lo|bien)|'
21
+ r'or\s+(?:would\s+you\s+(?:rather|like|prefer)|do\s+you\s+want|should\s+(?:i|we)|prefer))\b',
22
+ re.IGNORECASE,
23
+ )
24
+ CHOICE_CUE_RE = re.compile(
25
+ r'(?:^|\n)\s*(?:'
26
+ r'si\s+quieres|'
27
+ r'puedes\s+elegir|'
28
+ r'elige\s+(?:una\s+)?opci[oó]n|'
29
+ r'if\s+you(?:\'d|\s+would)?\s+like|'
30
+ r'choose\s+(?:an?\s+)?option|'
31
+ r'pick\s+(?:an?\s+)?option|'
32
+ r'what\s+would\s+you\s+like|'
33
+ r'next\s+steps?'
34
+ r')\s*:',
35
+ re.IGNORECASE,
36
+ )
37
+ CHOICE_FIRST_ITEM_RE = re.compile(r'(?m)^\s*1\.\s+\S')
38
+ CHOICE_SECOND_ITEM_RE = re.compile(r'(?m)^\s*2\.\s+\S')
39
+ BOSS_GATE_MARKER_RE = re.compile(r'BOSS\s+GATE', re.IGNORECASE)
40
+ # Roles a BOSS GATE header may declare (delivery-coordinator/references/hud-output.md).
41
+ BOSS_GATE_ROLES = ('PM', 'Tech Lead', 'Commit & PR', 'Code Owner', 'Release Owner')
42
+ BOSS_GATE_ROLE_NAMES = {'PM': 'Product Manager', 'Commit & PR': 'Tech Lead / Commit & PR authorization'}
43
+ BOSS_GATE_ROLE_RE = re.compile(
44
+ r'BOSS\s+GATE\s*[─—–-]+\s*(Product Manager|' + '|'.join(re.escape(r) for r in BOSS_GATE_ROLES) + r')(?![\w&])')
45
+ BOSS_GATE_RECOMMENDED_RE = re.compile(r'(?:Recomendado|Recommended)\s*:', re.IGNORECASE)
46
+ BOSS_GATE_OPTIONS_RE = re.compile(r'\[A\][\s\S]*\[B\]')
47
+
48
+ DELEGABLE_RULES = (
49
+ {
50
+ 'skill': 'regression-testing',
51
+ 'role': 'QA Engineer',
52
+ 'stage': 'verify',
53
+ 'reason': 'Local verification, test execution, and bug reproduction belong to QA (regression-testing), never to the user.',
54
+ 'patterns': (
55
+ r'\bprobar(?:lo)?(?:\s+primero)?\s+en\s+local\b',
56
+ r'\bproban?do\s+en\s+local\b',
57
+ r'\b(?:lo\s+)?prueb[ae]s?(?:\s+tu)?\s+primero\b',
58
+ r'\btest(?:ing)?(?:\s+it)?\s+(?:locally|first)(?:\s+first)?\b',
59
+ r'\bverify\s+locally\b',
60
+ # Spanish first-person forms ("corro", "ejecuto", "lanzo") are the usual way an
61
+ # agent drafts these questions; infinitive-only patterns missed them (#42).
62
+ r'\b(?:run|ejecut(?:o|e|a|ar|amos|emos)|corr(?:o|e|a|er|emos|amos)|pas(?:o|e|a|ar)|lanz(?:o|a|ar|amos)|lance|lancemos)\s+(?:los\s+|las\s+|el\s+|la\s+|the\s+)?(?:tests?|pruebas?|specs?|vitest|jest|pytest|build|suites?)\b',
63
+ # reproducir is irregular: reprodu-zco / reprodu-zca (no c), which the old
64
+ # pattern `reproduc(?:...|zca)` could never match.
65
+ r'\b(?:reproduc(?:e|en|ir|imos)|reproduzc(?:o|a|amos))\b',
66
+ r'\bverifi(?:car|que|quemos|co|camos)\s+(?:si\s+funciona|el\s+build)\b',
67
+ r'\bcheck\s+if\s+it\s+works\b',
68
+ r'\bsmoke\s*test\b',
69
+ ),
70
+ },
71
+ {
72
+ 'skill': 'code-quality-gate',
73
+ 'role': 'Software Engineer self-check',
74
+ 'stage': 'quality',
75
+ 'reason': 'Typecheck, lint, BigO, EarlyReturn, and TypeSafe checks belong to code-quality-gate.',
76
+ 'patterns': (
77
+ r'\b(?:typecheck|lint(?:er)?|prettier|eslint|tsc)\b',
78
+ r'\bquality\s+gate\b',
79
+ r'\b(?:revis(?:o|a|e|ar|amos|emos)|check)\s+(?:la\s+)?calidad\b',
80
+ r'\b(?:early\s*return|type\s*safe|big\s*o)\b',
81
+ ),
82
+ },
83
+ {
84
+ 'skill': 'skill-clean-architecture',
85
+ 'role': 'Software Engineer',
86
+ 'stage': 'implement',
87
+ 'reason': 'Layer boundaries, DDD placement, and source headers belong to skill-clean-architecture.',
88
+ 'patterns': (
89
+ r'\bclean\s+architecture\b',
90
+ r'\b(?:layer|capas)\s+(?:rules|headers|boundaries)\b',
91
+ r'\bsource\s+headers?\b',
92
+ ),
93
+ },
94
+ {
95
+ 'skill': 'documentation-steward',
96
+ 'role': 'Documentation Steward',
97
+ 'stage': 'docs',
98
+ 'reason': 'Auditing affected docs or finding the canonical page belongs to documentation-steward.',
99
+ 'patterns': (
100
+ r'\b(?:actuali(?:zar|ce|cemos|zo|za)|update|revis(?:o|a|e|ar|amos|emos)|check|audit(?:ar|e|emos|o|a)?)\s+(?:si\s+)?(?:la\s+|el\s+|the\s+)?(?:docs?|documentacion|documentation|readme|wiki)\b',
101
+ r'\b(?:docs?|documentacion|documentation)\s+(?:(?:fue|esta|este|ha\s+sido)\s+)?afectad',
102
+ ),
103
+ },
104
+ {
105
+ 'skill': 'risk-scout',
106
+ 'role': 'SRE / Staff Engineer',
107
+ 'stage': 'residual_risk',
108
+ 'reason': 'Failure modes, rollout risk, and edge-case premortems belong to risk-scout.',
109
+ 'patterns': (
110
+ r'\b(?:que|what)\s+(?:puede|podria|could)\s+(?:fallar|break|fail)\b',
111
+ r'\b(?:riesgos?|risk\s+matrix|residual\s+risk|premortem)\b',
112
+ ),
113
+ },
114
+ {
115
+ 'skill': 'greptile-review-loop',
116
+ 'role': 'AI Code Reviewer',
117
+ 'stage': 'review',
118
+ 'reason': 'Triggering or reconciling Greptile review comments and 5/5 status belongs to greptile-review-loop.',
119
+ 'patterns': (
120
+ r'\bgreptile\b',
121
+ r'\b5/5\b',
122
+ r'\b(?:comentarios|comments|threads)\s+(?:del\s+|of\s+the\s+|en\s+el\s+)?pr\b',
123
+ r'\b(?:comentarios\s+de\s+(?:la\s+)?revision|review\s+comments)\b',
124
+ ),
125
+ },
126
+ {
127
+ 'skill': 'workflow-auditor',
128
+ 'role': 'Process Auditor',
129
+ 'stage': 'audit',
130
+ 'reason': 'Checking diagram order, delivery ledger, and Tool Depot compliance belongs to workflow-auditor.',
131
+ 'patterns': (
132
+ r'\b(?:audit(?:ar|e|emos)?|audit)\s+(?:el\s+|the\s+|si\s+el\s+ledger\s+)?(?:workflow|flujo|ledger)\b',
133
+ r'\bcumple\s+(?:con\s+)?(?:el\s+)?(?:diagrama|workflow|flujo)\b',
134
+ ),
135
+ },
136
+ {
137
+ 'skill': 'watcher-observability',
138
+ 'role': 'SRE on call',
139
+ 'stage': 'observe',
140
+ 'reason': 'Reading sanitized logs or container telemetry belongs to watcher-observability (via tool-depot).',
141
+ 'patterns': (
142
+ r'\b(?:ver|veo|revis(?:o|a|e|ar|amos|emos)|check|read)\s+(?:los\s+|the\s+)?(?:docker\s+)?logs\b',
143
+ r'\bsleuth\b',
144
+ r'\b(?:docker\s+ps|contenedores|containers)\b',
145
+ ),
146
+ },
147
+ {
148
+ 'skill': 'tool-depot',
149
+ 'role': 'Tool Depot',
150
+ 'stage': 'external_tool',
151
+ 'reason': 'Checking duplicate issues, reading existing GitHub artifacts, or verifying public docs routes through tool-depot.',
152
+ 'patterns': (
153
+ r'\b(?:issues?\s+duplicad\w*|duplicate\s+issues?)\b',
154
+ r'\b(?:bus(?:car|que)|check|read|le[ae]r?)\s+(?:la\s+|el\s+|the\s+)?(?:issue|pr|wiki)\b',
155
+ ),
156
+ },
157
+ {
158
+ 'skill': 'delivery-coordinator',
159
+ 'role': 'Tech Lead',
160
+ 'stage': 'coordinate',
161
+ 'reason': 'Choosing the next workflow stage from handoff contracts belongs to delivery-coordinator.',
162
+ 'patterns': (
163
+ r'\b(?:que|cual)\s+(?:sigue|hacemos\s+ahora|paso\s+sigue|skill\s+uso)\b',
164
+ r'\bcomo\s+(?:procedo|continuo|seguimos)\b',
165
+ r'\bwhat\s+(?:should\s+(?:i|we)\s+do\s+next|is\s+next|comes\s+next)\b',
166
+ ),
167
+ },
168
+ )
169
+
170
+ COMMIT_PR_PATTERNS = (
171
+ r'\b(?:hacer|haga|hago|hagamos|make|create|crear|cre[ae]|creo)\s+(?:el\s+|the\s+|un\s+)?commit\b',
172
+ r'\b(?:abrir|abra|abro|abramos|open|create|crear|cre[ae]|creo|subir|suba|subo|push)\s+(?:el\s+|the\s+|la\s+|un\s+|una\s+|an?\s+)?(?:pr|pull\s+request)\b',
173
+ r'\b(?:crear|cree|creo|creemos|create|abrir|abra|abro|open|publicar|publique|publico|publish)\s+(?:la\s+|el\s+|the\s+|an?\s+)?issue\b',
174
+ r'\bcommit(?:\s+and|\s+y|\s*,\s*)?\s*(?:push|pr|pull\s+request)\b',
175
+ )
176
+
177
+ ALWAYS_HUMAN_RULES = (
178
+ {
179
+ 'owner': 'Code Owner',
180
+ 'stage': 'code_owner',
181
+ 'reason': 'Merging or approving a PR as Code Owner always requires a person.',
182
+ 'patterns': (
183
+ r'\b(?:hacer|hago|haga|hagamos|hacemos|make)\s+(?:el\s+)?merge\b',
184
+ r'\b(?:merge|mergeo|mergea|mergear|mergeamos|fusiono|fusiona|fusionar)\s+(?:el\s+|the\s+)?(?:pr|pull\s+request)\b',
185
+ r'\bapprove\s+and\s+merge\b',
186
+ ),
187
+ },
188
+ {
189
+ 'owner': 'Release Owner',
190
+ 'stage': 'release_owner',
191
+ 'reason': 'Production deployment decisions always belong to the human Release Owner.',
192
+ 'patterns': (
193
+ r'\b(?:deploy|desplegar|despliego|despliegue|despliega|desplegamos|despleguemos|hacer\s+deploy|release\s+to\s+prod|subir\s+a\s+produccion)\b',
194
+ ),
195
+ },
196
+ {
197
+ 'owner': 'Product Manager',
198
+ 'stage': 'specify',
199
+ 'reason': 'Open product or UX decisions belong to the human Product Manager (via requirements-spec Open Decision Question Format).',
200
+ 'patterns': (
201
+ r'\b(?:decision\s+de\s+producto|product\s+decision|comportamiento\s+esperado)\b',
202
+ r'\b(?:nueva\s+pestana|new\s+tab|misma\s+pestana|same\s+tab)\b',
203
+ ),
204
+ },
205
+ )
206
+
207
+
208
+ class Unusable(Exception):
209
+ """Input or ledger cannot be evaluated."""
210
+
211
+
212
+ def strip_accents(text):
213
+ normalized = unicodedata.normalize('NFKD', text)
214
+ return ''.join(ch for ch in normalized if not unicodedata.combining(ch))
215
+
216
+
217
+ def normalize_text(text):
218
+ return strip_accents(text).lower().strip()
219
+
220
+
221
+ def extract_questions(raw_text):
222
+ cleaned = CODE_FENCE_RE.sub(' ', raw_text or '')
223
+ cleaned = cleaned.strip()
224
+ if not cleaned:
225
+ return []
226
+ if '?' not in cleaned and '¿' not in cleaned:
227
+ return []
228
+ parts = re.split(r'(?<=[?\n])\s+', cleaned)
229
+ questions = [part.strip() for part in parts if '?' in part or '¿' in part]
230
+ return questions if questions else [cleaned]
231
+
232
+
233
+ def split_clauses(question):
234
+ trimmed = question.strip().lstrip('¿').rstrip('?').strip()
235
+ if not trimmed:
236
+ return []
237
+ raw_clauses = SPLIT_CLAUSE_RE.split(trimmed)
238
+ clauses = []
239
+ for chunk in raw_clauses:
240
+ piece = chunk.strip(' ,;:.¿?')
241
+ if piece:
242
+ clauses.append(piece)
243
+ return clauses
244
+
245
+
246
+ def find_default_ledger():
247
+ try:
248
+ result = subprocess.run(
249
+ ['git', 'rev-parse', '--git-path', LEDGER_NAME],
250
+ capture_output=True,
251
+ text=True,
252
+ check=True,
253
+ timeout=5,
254
+ )
255
+ except (OSError, subprocess.SubprocessError):
256
+ return None
257
+ candidate = result.stdout.strip()
258
+ if not candidate:
259
+ return None
260
+ path = Path(candidate)
261
+ return path if path.is_file() else None
262
+
263
+
264
+ def load_ledger(path):
265
+ try:
266
+ with open(path, encoding='utf-8') as handle:
267
+ data = json.load(handle)
268
+ except (OSError, ValueError) as error:
269
+ raise Unusable('Delivery ledger is unreadable or invalid JSON: ' + str(error))
270
+ if not isinstance(data, dict) or data.get('version') != 1:
271
+ raise Unusable('Delivery ledger must be a JSON object with version 1.')
272
+ return data
273
+
274
+
275
+ def ledger_state(ledger):
276
+ if ledger is None:
277
+ return {'present': False, 'commit_authorized': False, 'missing_prereqs': []}
278
+
279
+ authorizations = ledger.get('authorizations', [])
280
+ commit_authorized = False
281
+ if isinstance(authorizations, list):
282
+ for auth in authorizations:
283
+ if not isinstance(auth, dict):
284
+ continue
285
+ if auth.get('by') == 'person' and isinstance(auth.get('covers'), list) and 'commit_pr' in auth['covers']:
286
+ commit_authorized = True
287
+ break
288
+
289
+ stages = ledger.get('stages', [])
290
+ names = [s.get('stage') for s in stages if isinstance(s, dict)]
291
+ last_implement = -1
292
+ for idx, name in enumerate(names):
293
+ if name == 'implement':
294
+ last_implement = idx
295
+
296
+ after_impl = names[last_implement + 1:] if last_implement >= 0 else []
297
+ missing_prereqs = []
298
+ if 'verify' not in after_impl:
299
+ missing_prereqs.append('regression-testing')
300
+ if 'quality' not in after_impl:
301
+ missing_prereqs.append('code-quality-gate')
302
+
303
+ return {
304
+ 'present': True,
305
+ 'commit_authorized': commit_authorized,
306
+ 'missing_prereqs': missing_prereqs,
307
+ }
308
+
309
+
310
+ def matches_any(text, patterns):
311
+ return any(re.search(pattern, text) for pattern in patterns)
312
+
313
+
314
+ def classify_clause(clause, state):
315
+ norm = normalize_text(clause)
316
+
317
+ for rule in DELEGABLE_RULES:
318
+ if matches_any(norm, rule['patterns']):
319
+ return {
320
+ 'clause': clause,
321
+ 'disposition': 'delegate_to_skill',
322
+ 'resolved_by': rule['skill'],
323
+ 'role': rule['role'],
324
+ 'stage': rule['stage'],
325
+ 'reason': rule['reason'],
326
+ }
327
+
328
+ if matches_any(norm, COMMIT_PR_PATTERNS):
329
+ if state['present'] and state['missing_prereqs']:
330
+ first_skill = state['missing_prereqs'][0]
331
+ return {
332
+ 'clause': clause,
333
+ 'disposition': 'delegate_to_skill',
334
+ 'resolved_by': first_skill,
335
+ 'role': 'QA Engineer / Software Engineer',
336
+ 'stage': 'verify' if first_skill == 'regression-testing' else 'quality',
337
+ 'reason': 'Do not ask to commit or open a PR before prerequisites pass: run ' + ', '.join(state['missing_prereqs']) + ' first.',
338
+ }
339
+ if state['commit_authorized']:
340
+ return {
341
+ 'clause': clause,
342
+ 'disposition': 'already_authorized',
343
+ 'resolved_by': 'delivery-coordinator',
344
+ 'role': 'Tech Lead',
345
+ 'stage': 'commit_pr',
346
+ 'reason': 'The delivery ledger already records a person authorization covering commit_pr; execute Commit & PR without asking again.',
347
+ }
348
+ return {
349
+ 'clause': clause,
350
+ 'disposition': 'human_approval_required',
351
+ 'resolved_by': 'person',
352
+ 'role': 'Tech Lead / Commit & PR authorization',
353
+ 'stage': 'commit_pr',
354
+ 'reason': 'Commit, issue publication, and PR creation require explicit person authorization when not yet granted in the session or ledger.',
355
+ }
356
+
357
+ for rule in ALWAYS_HUMAN_RULES:
358
+ if matches_any(norm, rule['patterns']):
359
+ return {
360
+ 'clause': clause,
361
+ 'disposition': 'human_approval_required',
362
+ 'resolved_by': 'person',
363
+ 'role': rule['owner'],
364
+ 'stage': rule['stage'],
365
+ 'reason': rule['reason'],
366
+ }
367
+
368
+ # #54: unrecognised is not the same as human. Allowing it by default let any
369
+ # unmatched question through, the exact leak this gate exists to close.
370
+ return {
371
+ 'clause': clause,
372
+ 'disposition': 'needs_classification',
373
+ 'resolved_by': 'person',
374
+ 'role': 'Unclassified',
375
+ 'stage': 'unknown',
376
+ 'reason': ('No diagram skill or human rule matched. Route it to its owning skill, or declare '
377
+ 'the human owner with a 🟡 BOSS GATE ─ <Role> header (' + ', '.join(BOSS_GATE_ROLES) + ').'),
378
+ }
379
+
380
+
381
+ AND_SPLIT_RE = re.compile(r'\s+(?:y|e|and)\s+', re.IGNORECASE)
382
+
383
+
384
+ def owner_of(item):
385
+ return item['resolved_by'] if item['resolved_by'] != 'person' else item['role']
386
+
387
+
388
+ def classify_compound(clause, state):
389
+ """#54: split "X y Y" / "X and Y" when every part is recognised and the parts
390
+ have different owners, so neither a second human owner nor a human gate next
391
+ to a delegable part is lost. Same-owner lists ("haga el commit, cree la issue
392
+ y abra el PR") and anything unrecognised stay one clause."""
393
+ whole = classify_clause(clause, state)
394
+ parts = [part.strip(' ,;:.') for part in AND_SPLIT_RE.split(clause)]
395
+ parts = [part for part in parts if part]
396
+ if len(parts) < 2:
397
+ return [whole]
398
+ items = [classify_clause(part, state) for part in parts]
399
+ if any(item['stage'] == 'unknown' for item in items):
400
+ return [whole]
401
+ if len({owner_of(item) for item in items}) < 2:
402
+ return [whole]
403
+ return items
404
+
405
+
406
+ def has_choice_offer(raw_text):
407
+ cleaned = CODE_FENCE_RE.sub(' ', raw_text or '')
408
+ if not CHOICE_CUE_RE.search(cleaned):
409
+ return False
410
+ has_numbered = bool(CHOICE_FIRST_ITEM_RE.search(cleaned) and CHOICE_SECOND_ITEM_RE.search(cleaned))
411
+ has_lettered = '[A]' in cleaned and '[B]' in cleaned
412
+ return has_numbered or has_lettered
413
+
414
+
415
+ def has_boss_gate_format(raw_text):
416
+ text = raw_text or ''
417
+ return bool(
418
+ BOSS_GATE_MARKER_RE.search(text)
419
+ and BOSS_GATE_RECOMMENDED_RE.search(text)
420
+ and BOSS_GATE_OPTIONS_RE.search(text)
421
+ )
422
+
423
+
424
+ def evaluate_text(raw_text, ledger=None, require_hud=False):
425
+ questions = extract_questions(raw_text)
426
+ if not questions:
427
+ if require_hud and has_choice_offer(raw_text) and not has_boss_gate_format(raw_text):
428
+ return {
429
+ 'verdict': 'block_format',
430
+ 'ledger_checked': ledger is not None,
431
+ 'clauses': [],
432
+ 'resolved_by': [],
433
+ 'human_gates': [],
434
+ 'hud_format_ok': False,
435
+ 'rewrite_suggestion': (
436
+ 'Format this decision or choice prompt with the Quest-Tree HUD and a compact '
437
+ '🟡 BOSS GATE (🟡 BOSS GATE ─ <Role>, ❓ question, 👉 Recomendado: [A], '
438
+ '⚡ Opciones with [A]/[B]) before stopping.'
439
+ ),
440
+ }
441
+ return {
442
+ 'verdict': 'no_question',
443
+ 'ledger_checked': ledger is not None,
444
+ 'clauses': [],
445
+ 'resolved_by': [],
446
+ 'human_gates': [],
447
+ 'hud_format_ok': True,
448
+ 'rewrite_suggestion': None,
449
+ }
450
+
451
+ state = ledger_state(ledger)
452
+ classified = []
453
+ for question in questions:
454
+ for clause in split_clauses(question):
455
+ classified.extend(classify_compound(clause, state))
456
+
457
+ declared = BOSS_GATE_ROLE_RE.search(raw_text or '')
458
+ if declared:
459
+ role = BOSS_GATE_ROLE_NAMES.get(declared.group(1), declared.group(1))
460
+ for item in classified:
461
+ if item['disposition'] == 'needs_classification':
462
+ item.update(disposition='human_approval_required', role=role, stage='declared',
463
+ reason='Owner declared by the 🟡 BOSS GATE header.')
464
+ unclassified = [c for c in classified if c['disposition'] == 'needs_classification']
465
+ blocked = [c for c in classified if c['disposition'] in ('delegate_to_skill', 'already_authorized')]
466
+ human_gates = [c for c in classified if c['disposition'] == 'human_approval_required']
467
+
468
+ resolved_by = []
469
+ for item in blocked:
470
+ skill = item['resolved_by']
471
+ if skill not in resolved_by:
472
+ resolved_by.append(skill)
473
+
474
+ hud_ok = has_boss_gate_format(raw_text)
475
+ if unclassified and not blocked:
476
+ verdict = 'block_question'
477
+ rewrite_suggestion = (
478
+ 'Unclassified question: ' + '; '.join(c['clause'] for c in unclassified) + '. '
479
+ 'Route it to the skill that owns it, or, if a person must decide, declare the owner with a '
480
+ '🟡 BOSS GATE ─ <Role> header (' + ', '.join(BOSS_GATE_ROLES) + ').'
481
+ )
482
+ elif blocked:
483
+ verdict = 'block_question'
484
+ if human_gates:
485
+ rewrite_suggestion = (
486
+ 'Do not ask the blocked clause(s) (' + ', '.join(resolved_by) + '). '
487
+ 'Run/resolve those diagram stages first; only ask the remaining human approval: '
488
+ + '; '.join(g['clause'] for g in human_gates)
489
+ )
490
+ else:
491
+ rewrite_suggestion = (
492
+ 'Do not ask the user. Resolve directly with: ' + ', '.join(resolved_by) + '.'
493
+ )
494
+ elif require_hud and not hud_ok:
495
+ verdict = 'block_format'
496
+ rewrite_suggestion = (
497
+ 'Format the human decision with the Quest-Tree HUD (`🎮 QUEST ACTUAL` when in a quest) '
498
+ 'and a compact `🟡 BOSS GATE` (`🟡 BOSS GATE ─ <Role>`, `❓`, `👉 Recomendado: [A]`, '
499
+ '`⚡ Opciones` with `[A]`/`[B]`) before stopping.'
500
+ )
501
+ else:
502
+ verdict = 'allow_question'
503
+ rewrite_suggestion = None
504
+
505
+ return {
506
+ 'verdict': verdict,
507
+ 'ledger_checked': ledger is not None,
508
+ 'clauses': classified,
509
+ 'resolved_by': resolved_by,
510
+ 'human_gates': [
511
+ {'clause': g['clause'], 'role': g['role'], 'stage': g['stage']}
512
+ for g in human_gates
513
+ ],
514
+ 'hud_format_ok': hud_ok,
515
+ 'rewrite_suggestion': rewrite_suggestion,
516
+ }
517
+
518
+
519
+ def read_last_assistant_from_transcript(transcript_path):
520
+ if not isinstance(transcript_path, str) or not transcript_path.strip():
521
+ return ''
522
+ path = Path(transcript_path)
523
+ if not path.is_file():
524
+ return ''
525
+ last_text = ''
526
+ try:
527
+ with open(path, encoding='utf-8') as handle:
528
+ for line in handle:
529
+ line = line.strip()
530
+ if not line:
531
+ continue
532
+ try:
533
+ entry = json.loads(line)
534
+ except ValueError:
535
+ continue
536
+ if not isinstance(entry, dict) or entry.get('role') != 'assistant':
537
+ continue
538
+ message = entry.get('message')
539
+ if isinstance(message, str) and message.strip():
540
+ last_text = message
541
+ continue
542
+ if not isinstance(message, dict):
543
+ continue
544
+ content = message.get('content')
545
+ if isinstance(content, str) and content.strip():
546
+ last_text = content
547
+ elif isinstance(content, list):
548
+ texts = [
549
+ part.get('text', '')
550
+ for part in content
551
+ if isinstance(part, dict) and part.get('type') == 'text' and isinstance(part.get('text'), str)
552
+ ]
553
+ joined = '\n'.join(t for t in texts if t.strip()).strip()
554
+ if joined:
555
+ last_text = joined
556
+ except OSError:
557
+ return ''
558
+ return last_text
559
+
560
+
561
+ def extract_input_from_stdin(raw_stdin):
562
+ trimmed = raw_stdin.strip()
563
+ if not trimmed:
564
+ return '', False
565
+ if trimmed.startswith('{'):
566
+ try:
567
+ payload = json.loads(trimmed)
568
+ except ValueError as err:
569
+ raise Unusable('Malformed JSON payload on stdin: ' + str(err))
570
+ if isinstance(payload, dict):
571
+ if payload.get('stop_hook_active') is True:
572
+ return '', True
573
+ status = payload.get('status')
574
+ if isinstance(status, str) and status != 'completed':
575
+ return '', True
576
+ loop_count = payload.get('loop_count')
577
+ if isinstance(loop_count, int) and not isinstance(loop_count, bool) and loop_count >= 2:
578
+ return '', True
579
+ for key in ('last_assistant_message', 'prompt_response', 'assistant_message', 'message', 'question', 'text'):
580
+ value = payload.get(key)
581
+ if isinstance(value, str) and value.strip():
582
+ return value, False
583
+ transcript_text = read_last_assistant_from_transcript(payload.get('transcript_path'))
584
+ return transcript_text, False
585
+ return '', False
586
+ return raw_stdin, False
587
+
588
+
589
+ def block_reason(report):
590
+ if not report['resolved_by']:
591
+ return ('Question Gate: ' + (report['rewrite_suggestion'] or '')).strip()
592
+ return ('Question Gate: resolve via diagram skill(s) [' + ', '.join(report['resolved_by'])
593
+ + '] before asking the user. ' + (report['rewrite_suggestion'] or '')).strip()
594
+
595
+
596
+ def format_output(report, fmt):
597
+ if fmt == 'cursor-hook':
598
+ if report['verdict'] == 'block_question':
599
+ return json.dumps({
600
+ 'followup_message': (
601
+ 'Question Gate blocked stopping to ask the user. '
602
+ + (report['rewrite_suggestion'] or '')
603
+ ).strip(),
604
+ })
605
+ if report['verdict'] == 'block_format':
606
+ return json.dumps({
607
+ 'followup_message': (
608
+ 'Question Gate blocked stopping: missing Quest-Tree HUD / 🟡 BOSS GATE format. '
609
+ + (report['rewrite_suggestion'] or '')
610
+ ).strip(),
611
+ })
612
+ return json.dumps({})
613
+
614
+ if fmt in ('claude-hook', 'codex-hook'):
615
+ if report['verdict'] == 'block_question':
616
+ return json.dumps({
617
+ 'decision': 'block',
618
+ 'reason': block_reason(report),
619
+ })
620
+ if report['verdict'] == 'block_format':
621
+ return json.dumps({
622
+ 'decision': 'block',
623
+ 'reason': ('Question Gate: ' + (report['rewrite_suggestion'] or '')).strip(),
624
+ })
625
+ return json.dumps({})
626
+
627
+ if fmt == 'gemini-hook':
628
+ if report['verdict'] == 'block_question':
629
+ return json.dumps({
630
+ 'decision': 'deny',
631
+ 'reason': block_reason(report),
632
+ })
633
+ if report['verdict'] == 'block_format':
634
+ return json.dumps({
635
+ 'decision': 'deny',
636
+ 'reason': ('Question Gate: ' + (report['rewrite_suggestion'] or '')).strip(),
637
+ })
638
+ return json.dumps({})
639
+
640
+ return json.dumps(report, indent=2, ensure_ascii=False)
641
+
642
+
643
+ def parse_args(argv):
644
+ parser = argparse.ArgumentParser(
645
+ description='Check whether a proposed question can be resolved by a diagram skill before asking the user.',
646
+ )
647
+ parser.add_argument('--question', help='Proposed question or draft assistant message.')
648
+ parser.add_argument('--stdin', action='store_true', help='Read question or hook JSON payload from stdin.')
649
+ parser.add_argument('--ledger', help='Path to bbc-delivery-ledger.json.')
650
+ parser.add_argument('--no-ledger', action='store_true', help='Skip auto-discovering bbc-delivery-ledger.json.')
651
+ parser.add_argument(
652
+ '--require-hud',
653
+ action='store_true',
654
+ help='Require Quest-Tree 🟡 BOSS GATE formatting for human decisions and choice offers.',
655
+ )
656
+ parser.add_argument(
657
+ '--no-hud',
658
+ action='store_true',
659
+ help='Disable 🟡 BOSS GATE format enforcement in client hook modes.',
660
+ )
661
+ parser.add_argument(
662
+ '--format',
663
+ choices=('json', 'cursor-hook', 'claude-hook', 'codex-hook', 'gemini-hook'),
664
+ default='json',
665
+ help='Output format (default: json).',
666
+ )
667
+ return parser.parse_args(argv)
668
+
669
+
670
+ def main(argv):
671
+ try:
672
+ args = parse_args(argv)
673
+ except SystemExit as exc:
674
+ return 2 if exc.code != 0 else 0
675
+
676
+ if args.question is not None:
677
+ raw_text = args.question
678
+ elif args.stdin:
679
+ try:
680
+ raw_text, should_skip = extract_input_from_stdin(sys.stdin.read())
681
+ except Unusable as error:
682
+ print(json.dumps({'verdict': 'unusable', 'detail': str(error)}))
683
+ return 2
684
+ if should_skip:
685
+ print(format_output({'verdict': 'no_question', 'ledger_checked': False, 'clauses': [], 'resolved_by': [], 'human_gates': [], 'hud_format_ok': True, 'rewrite_suggestion': None}, args.format))
686
+ return 0
687
+ else:
688
+ print(json.dumps({'verdict': 'unusable', 'detail': 'Pass --question "..." or --stdin.'}))
689
+ return 2
690
+
691
+ ledger = None
692
+ try:
693
+ if not args.no_ledger:
694
+ ledger_path = Path(args.ledger) if args.ledger else find_default_ledger()
695
+ if ledger_path is not None:
696
+ ledger = load_ledger(ledger_path)
697
+ except Unusable as error:
698
+ print(json.dumps({'verdict': 'unusable', 'detail': str(error)}))
699
+ return 2
700
+
701
+ require_hud = args.require_hud or (args.format != 'json' and not args.no_hud)
702
+ report = evaluate_text(raw_text, ledger=ledger, require_hud=require_hud)
703
+ print(format_output(report, args.format))
704
+
705
+ if args.format == 'json' and report['verdict'] in ('block_question', 'block_format'):
706
+ return 1
707
+ return 0
708
+
709
+
710
+ if __name__ == '__main__':
711
+ # Console code pages such as Windows cp1252 cannot encode the 🟡 BOSS GATE marker.
712
+ sys.stdout.reconfigure(encoding='utf-8')
713
+ sys.exit(main(sys.argv[1:]))