@kinti/a11y-toolkit 5.26.0 → 5.28.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 (45) hide show
  1. package/README.md +1 -1
  2. package/a11y_toolkit/a11y.py +30 -4
  3. package/a11y_toolkit/a11yact.py +9 -1
  4. package/a11y_toolkit/a11yannotate.py +185 -0
  5. package/a11y_toolkit/a11yaudit.py +924 -196
  6. package/a11y_toolkit/a11ybadge.py +24 -17
  7. package/a11y_toolkit/a11ybudget.py +145 -1
  8. package/a11y_toolkit/a11ycorpus.py +58 -24
  9. package/a11y_toolkit/a11ycrit.py +114 -53
  10. package/a11y_toolkit/a11ydiff.py +104 -34
  11. package/a11y_toolkit/a11ydisprove.py +15 -8
  12. package/a11y_toolkit/a11ydocx.py +8 -6
  13. package/a11y_toolkit/a11ydom.py +567 -97
  14. package/a11y_toolkit/a11yen301549.py +53 -1
  15. package/a11y_toolkit/a11yengines.py +157 -0
  16. package/a11y_toolkit/a11yevidence.py +81 -33
  17. package/a11y_toolkit/a11yfix.py +131 -52
  18. package/a11y_toolkit/a11ygate.py +225 -0
  19. package/a11y_toolkit/a11yinit.py +73 -7
  20. package/a11y_toolkit/a11yjourney.py +110 -4
  21. package/a11y_toolkit/a11yledger.py +119 -12
  22. package/a11y_toolkit/a11ylocate.py +247 -0
  23. package/a11y_toolkit/a11yopenacr.py +10 -3
  24. package/a11y_toolkit/a11ypatches.py +154 -0
  25. package/a11y_toolkit/a11ypatterns.py +344 -0
  26. package/a11y_toolkit/a11ypdf.py +109 -53
  27. package/a11y_toolkit/a11yrgaa.py +60 -0
  28. package/a11y_toolkit/a11yroute.py +34 -12
  29. package/a11y_toolkit/a11ysarif.py +45 -18
  30. package/a11y_toolkit/a11yscope.py +67 -15
  31. package/a11y_toolkit/a11yscroll.py +7 -5
  32. package/a11y_toolkit/a11ystatement.py +30 -6
  33. package/a11y_toolkit/a11ytrace.py +293 -0
  34. package/a11y_toolkit/a11yvalidate.py +21 -15
  35. package/a11y_toolkit/a11yvpat.py +34 -7
  36. package/a11y_toolkit/a11yvtt.py +22 -6
  37. package/a11y_toolkit/a11ywiz.py +121 -0
  38. package/a11y_toolkit/contrast.py +62 -24
  39. package/a11y_toolkit/locales/en.json +185 -20
  40. package/a11y_toolkit/locales/es.json +186 -21
  41. package/a11y_toolkit/rgaa.json +2661 -0
  42. package/a11y_toolkit/server.py +157 -54
  43. package/package.json +2 -2
  44. package/a11y_toolkit/a11yplan.py +0 -214
  45. package/a11y_toolkit/a11ywcagem.py +0 -237
@@ -28,7 +28,7 @@ import json
28
28
  import re
29
29
  import sys
30
30
 
31
- from .a11yaudit import audit_html, _PERSONAL_DATA
31
+ from .a11yaudit import audit_html
32
32
 
33
33
  from . import a11yi18n
34
34
  # token autocomplete por type de input (determinista por especificación)
@@ -40,15 +40,13 @@ _TOKEN_BY_HINT = [
40
40
  (re.compile(r'ciudad|city', re.I), 'address-level2'),
41
41
  (re.compile(r'country|pais', re.I), 'country-name'),
42
42
  (re.compile(r'organi[sz]ation|company|empresa', re.I), 'organization'),
43
- (re.compile(r'phone|telefono|tel\b', re.I), 'tel'),
43
+ (re.compile(r'phone|telefono|\btel\b', re.I), 'tel'),
44
44
  (re.compile(r'email|correo', re.I), 'email'),
45
45
  (re.compile(r'(?:^|[\W_])(?:full)?name|nombre', re.I), 'name'),
46
46
  ]
47
47
 
48
- _RE_FORM = re.compile(r'<form\b[^>]*>', re.I)
49
48
  _RE_TAG_Q = r'(?:[^>\"\']|\"[^\"]*\"|\'[^\']*\')*'
50
49
  _RE_FIELD = re.compile(r'<input' + _RE_TAG_Q + r'>|<(select|textarea)' + _RE_TAG_Q + r'>.*?</\1\s*>', re.I | re.S)
51
- _RE_SCRIPTS = re.compile(r'<script\b.*?</script>', re.S | re.I)
52
50
  _RE_FORM_BLOCK = re.compile(r'<form\b.*?</form>', re.S | re.I)
53
51
 
54
52
  _PHRASES = a11yi18n.pair('fix') # locales/<lang>.json — community-editable
@@ -88,7 +86,7 @@ _JS_PHRASES = """<script>
88
86
 
89
87
  _RE_INPUT = re.compile(r'<input' + _RE_TAG_Q + r'>', re.I)
90
88
  _RE_VIEWPORT = re.compile(r'(<meta\s[^>]*name=["\']viewport["\'][^>]*content=["\'])([^"\']*)(["\'])', re.I)
91
- _RE_HTML_TAG = re.compile(r'<html\b([^>]*)>', re.I)
89
+ _RE_HTML_TAG = re.compile(r'<html\b(' + _RE_TAG_Q + r')>', re.I)
92
90
  _RE_TITLE = re.compile(r'<title>\s*</title>', re.I)
93
91
 
94
92
 
@@ -117,6 +115,25 @@ def _clean_viewport(content):
117
115
  return ', '.join(clean), removed
118
116
 
119
117
 
118
+ def _drop_selfclose(base):
119
+ """Drop a trailing self-closing slash — only OUTSIDE quotes: a value like
120
+ "x/" is data, not markup (an unquoted rstrip('/') would eat it)."""
121
+ q = None
122
+ last = -1 # índice del último carácter significativo fuera de comillas
123
+ for i, ch in enumerate(base):
124
+ if q:
125
+ if ch == q:
126
+ q = None
127
+ elif ch in ('"', "'"):
128
+ q = ch
129
+ last = i
130
+ elif not ch.isspace():
131
+ last = i
132
+ if last >= 0 and base[last] == '/':
133
+ return base[:last].rstrip()
134
+ return base
135
+
136
+
120
137
  def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
121
138
  """Aplica los arreglos seguros. Devuelve fixed_html + aplicados + no_aplicados."""
122
139
  applied = []
@@ -126,13 +143,20 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
126
143
  # no son marcado — ninguna regex de transformación debe verlo. Sin este
127
144
  # paso, el "no toco scripts" era falso (revisión externa, ronda 2).
128
145
  _masks = []
146
+ # bloques <script> ORIGINALES, capturados ANTES de enmascarar: el guard
147
+ # de 4b decide sobre el código real — en el texto vivo ya no son buscables
148
+ _scripts_raw = []
129
149
 
130
150
  def _mask(text):
151
+ def _cap_script(m):
152
+ _scripts_raw.append(m.group(0))
153
+ return _pon(m)
154
+
131
155
  def _pon(m):
132
156
  tok = '\x00A11YFXMASK%d\x00' % len(_masks)
133
157
  _masks.append((tok, m.group(0)))
134
158
  return tok
135
- text = re.sub(r'<script\b[^>]*>.*?</script\s*>', _pon, text, flags=re.I | re.S)
159
+ text = re.sub(r'<script\b[^>]*>.*?</script\s*>', _cap_script, text, flags=re.I | re.S)
136
160
  text = re.sub(r'<style\b[^>]*>.*?</style\s*>', _pon, text, flags=re.I | re.S)
137
161
  # textarea NO se enmascara: la capa de error se inserta tras su cierre
138
162
  # (5.2.1) y el contenido queda intacto; ocultarlo quitaría el 3.3.1
@@ -140,37 +164,44 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
140
164
  return text
141
165
 
142
166
  def _unmask(text):
143
- for tok, original in _masks:
167
+ # orden INVERSO de creación: un mask puede vivir dentro del ORIGINAL
168
+ # de otro (un <script> dentro de un comentario) — restaurar primero el
169
+ # contenedor devuelve los tokens internos al texto vivo; en orden de
170
+ # creación el interno se restauraba dentro del original almacenado
171
+ # (no en el texto) y el token quedaba filtrado en la salida
172
+ for tok, original in reversed(_masks):
144
173
  text = text.replace(tok, original)
145
174
  return text
146
175
 
147
176
  fixed = _mask(fixed)
148
177
 
149
- # 1. viewport: zoom sin bloqueos (1.4.4)
178
+ # 1. viewport: zoom sin bloqueos (1.4.4) — solo si algo se quita de verdad:
179
+ # un maximum-scale=5 no bloquea el zoom y reescribirlo sin cambios sería
180
+ # un fix fantasma en `applied`
150
181
  m = _RE_VIEWPORT.search(fixed)
151
- if m and (re.search(r'user-scalable\s*=\s*(no|0)', m.group(2), re.I)
152
- or re.search(r'maximum-scale\s*=\s*([\d.]+)', m.group(2), re.I)):
182
+ if m:
153
183
  clean, removed = _clean_viewport(m.group(2))
154
- if clean:
155
- fixed = fixed[:m.start()] + m.group(1) + clean + m.group(3) + fixed[m.end():]
156
- else:
157
- # eliminar el meta COMPLETO: escanear el final de etiqueta
158
- # respetando comillas (un `>` dentro de value= no cierra el tag)
159
- end = m.end()
160
- q = None
161
- while end < len(fixed):
162
- ch = fixed[end]
163
- if q:
164
- if ch == q:
165
- q = None
166
- elif ch in ('"', "'"):
167
- q = ch
168
- elif ch == '>':
169
- break
170
- end += 1
171
- fixed = fixed[:m.start()] + (fixed[end + 1:] if end < len(fixed) else '')
172
- applied.append({'signal': 'zoom_no',
173
- 'fix': f'viewport without {", ".join(removed)} (1.4.4: zoom no longer blocked)'})
184
+ if removed:
185
+ if clean:
186
+ fixed = fixed[:m.start()] + m.group(1) + clean + m.group(3) + fixed[m.end():]
187
+ else:
188
+ # eliminar el meta COMPLETO: escanear el final de etiqueta
189
+ # respetando comillas (un `>` dentro de value= no cierra el tag)
190
+ end = m.end()
191
+ q = None
192
+ while end < len(fixed):
193
+ ch = fixed[end]
194
+ if q:
195
+ if ch == q:
196
+ q = None
197
+ elif ch in ('"', "'"):
198
+ q = ch
199
+ elif ch == '>':
200
+ break
201
+ end += 1
202
+ fixed = fixed[:m.start()] + (fixed[end + 1:] if end < len(fixed) else '')
203
+ applied.append({'signal': 'zoom_no',
204
+ 'fix': f'viewport without {", ".join(removed)} (1.4.4: zoom no longer blocked)'})
174
205
 
175
206
  # 2. autocomplete determinista (1.3.5)
176
207
  n_ac = 0
@@ -194,7 +225,9 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
194
225
  if not token:
195
226
  return tag
196
227
  n_ac += 1
197
- return tag[:-1].rstrip() + f' autocomplete="{token}">'
228
+ # la barra de autocierre no es un atributo: quitarla ANTES de inyectar
229
+ # (`<input .../ autocomplete>` sería markup inválido)
230
+ return _drop_selfclose(tag[:-1].rstrip()) + f' autocomplete="{token}">'
198
231
  fixed = _RE_INPUT.sub(_input_fix, fixed)
199
232
  if n_ac:
200
233
  applied.append({'signal': 'autocomplete',
@@ -204,10 +237,23 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
204
237
  # este toolkit ESCRIBE HTML, no puede ser vector de inyección
205
238
  if lang and re.fullmatch(r'[a-zA-Z]{2,3}(-[a-zA-Z0-9]{2,8})*', lang.strip()):
206
239
  m = _RE_HTML_TAG.search(fixed)
207
- if m and 'lang=' not in m.group(1).lower():
208
- fixed = fixed[:m.start()] + f'<html lang="{_html.escape(lang.strip())}"' + m.group(1) + '>' + fixed[m.end():]
209
- applied.append({'signal': 'lang_missing',
210
- 'fix': f'<html lang="{lang.strip()}"> added (3.1.1)'})
240
+ if m:
241
+ # atributo lang REAL (límite de atributo vía lookbehind: xml:lang=,
242
+ # data-lang= no cuentan) y con valor NO vacío (lang="" no cumple
243
+ # 3.1.1) — antes un simple 'lang=' in attr casaba con cualquiera
244
+ lm = re.search(r'(?<![\w:.\-])lang\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s>]+))',
245
+ m.group(1), re.I)
246
+ lval = next((g for g in (lm.groups() if lm else ()) if g is not None), '')
247
+ if not lval.strip():
248
+ new_lang = _html.escape(lang.strip())
249
+ if lm is None: # no hay lang: se antepone
250
+ fixed = (fixed[:m.start()] + f'<html lang="{new_lang}"' + m.group(1) + '>'
251
+ + fixed[m.end():])
252
+ else: # lang="": se RELLENA el existente, nunca duplicar
253
+ attrs = m.group(1)[:lm.start()] + f'lang="{new_lang}"' + m.group(1)[lm.end():]
254
+ fixed = fixed[:m.start()] + '<html' + attrs + '>' + fixed[m.end():]
255
+ applied.append({'signal': 'lang_missing',
256
+ 'fix': f'<html lang="{lang.strip()}"> added (3.1.1)'})
211
257
 
212
258
  # 4. title (solo si vacío y lo dan); escapado por la misma razón
213
259
  if title and _RE_TITLE.search(fixed):
@@ -216,8 +262,10 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
216
262
 
217
263
  # 4b. form errors: accessible error layer (3.3.1 + 3.3.3 from attributes)
218
264
  if form_errors and 'a11yfx' not in fixed:
219
- scripts = _RE_SCRIPTS.findall(fixed)
220
- if not any(('aria-invalid' in s or 'setCustomValidity' in s) for s in scripts):
265
+ # el guard mira los <script> ORIGINALES (_scripts_raw): en `fixed` ya
266
+ # están enmascarados y findall no vería nada — la capa se inyectaba
267
+ # aunque la página ya hiciera setCustomValidity/aria-invalid
268
+ if not any(('aria-invalid' in s or 'setCustomValidity' in s) for s in _scripts_raw):
221
269
  import json as _json
222
270
  state = {'forms': 0, 'fields': 0}
223
271
 
@@ -238,6 +286,7 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
238
286
  state['fields'] += 1
239
287
  fid = "a11yfx-e-%d-%d" % (state['forms'], state['fields'])
240
288
  opening = re.match(r'<[a-zA-Z]+(?:[^>"\']|"[^"]*"|\'[^\']*\')*>', elem).group(0)
289
+ head_len = len(opening) # límite del tag ANTES de inyectar attrs
241
290
  mdb = re.search(r'aria-describedby=["\']([^"\']*)["\']', opening, re.I)
242
291
  if mdb: # merge, preserving the existing reference
243
292
  new = 'aria-describedby="%s %s"' % (mdb.group(1), fid)
@@ -249,8 +298,13 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
249
298
  if opening.lower().startswith(('<textarea', '<select')):
250
299
  # content-bearing element: the layer goes AFTER the close,
251
300
  # never inside (inside would become its value — a real
252
- # data-corruption regression, caught in external review)
253
- return elem.replace(re.match(r'<[^>]*>', elem).group(0), opening, 1) + layer
301
+ # data-corruption regression, caught in external review).
302
+ # `opening` matchea elem desde el índice 0 (quote-aware) y
303
+ # cubre exactamente head_len bytes: el resto es contenido +
304
+ # cierre, preservado byte a byte (el replace por prefijo
305
+ # ingenuo dejaba el fragmento tras un `>` citado como
306
+ # contenido del elemento)
307
+ return opening + elem[head_len:] + layer
254
308
  return opening + layer
255
309
 
256
310
  def _own_handling(atrs_form):
@@ -263,7 +317,15 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
263
317
 
264
318
  def _process_block(mb):
265
319
  block = mb.group(0)
266
- opening = re.match(r'<form\b[^>]*>', block, re.I).group(0)
320
+ # opening quote-aware: un `>` dentro de un atributo citado
321
+ # (action="/search?q=a>b") NO cierra el tag — el prefijo
322
+ # ingenuo mutilaba la URL. Si el block acaba DENTRO de una
323
+ # cita (action="x</form>"), la apertura no es delimitable:
324
+ # no se toca (hostil: jamás caer)
325
+ mop = re.match(r'<form\b' + _RE_TAG_Q + r'>', block, re.I)
326
+ if mop is None:
327
+ return block
328
+ opening = mop.group(0)
267
329
  if 'data-a11yfx' in opening or _own_handling(opening):
268
330
  return block # custom error handling present: never fight it
269
331
  state['forms'] += 1
@@ -275,22 +337,19 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
275
337
  if state['fields']:
276
338
  fr = _PHRASES.get(lang, _PHRASES['en'])
277
339
  js = _JS_PHRASES % {k: _json.dumps(v) for k, v in fr.items()}
278
- fixed = fixed.replace('</body>', js + '\n</body>', 1)
340
+ # case-insensitive: </BODY> perdía el JS y `applied` seguía
341
+ # declarando la capa (aria-describedby colgantes)
342
+ fixed = re.sub(r'</body\s*>', lambda _mb: js + '\n' + _mb.group(0),
343
+ fixed, count=1, flags=re.I)
279
344
  applied.append({'signal': 'form_error_missing',
280
345
  'fix': f"accessible error layer on {state['forms']} form(s), "
281
346
  f"{state['fields']} field(s) — 3.3.1 identification + "
282
347
  f"3.3.3 attribute-derived suggestions"})
283
348
 
284
- # 5. lo que NO se toca — honestidad operativa
285
- report = audit_html(html_text, url, lang='en')
286
- do_not_touch = {
287
- 'img_no_alt': 'we cannot know if the image is decorative: alt="" vs descriptive is a human call',
288
- 'ctrl_name': 'the accessible name requires knowing what the control does',
289
- 'field_label': 'the label text is dictated by the content',
290
- 'contrast_fail': 'picking the new color is a design decision (use a11y_suggest_color)',
291
- 'target_small': 'needs a layout redesign',
292
- 'list_structure': 'rebuilding the markup requires understanding the structure',
293
- }
349
+ # 5. lo que NO se toca — honestidad operativa (bilingüe: el report y los
350
+ # remediation ya llegan en `lang`; el why_not también debe)
351
+ report = audit_html(html_text, url, lang=lang)
352
+ do_not_touch = _DO_NOT_TOUCH.get(lang, _DO_NOT_TOUCH['en'])
294
353
  already = {a['signal'] for a in applied}
295
354
  not_applied = []
296
355
  seen = set()
@@ -306,6 +365,26 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
306
365
  return {'fixed_html': fixed, 'applied': applied, 'not_applied': not_applied}
307
366
 
308
367
 
368
+ _DO_NOT_TOUCH = {
369
+ 'en': {
370
+ 'img_no_alt': 'we cannot know if the image is decorative: alt="" vs descriptive is a human call',
371
+ 'ctrl_name': 'the accessible name requires knowing what the control does',
372
+ 'field_label': 'the label text is dictated by the content',
373
+ 'contrast_fail': 'picking the new color is a design decision (use a11y_suggest_color)',
374
+ 'target_small': 'needs a layout redesign',
375
+ 'list_structure': 'rebuilding the markup requires understanding the structure',
376
+ },
377
+ 'es': {
378
+ 'img_no_alt': 'no podemos saber si la imagen es decorativa: alt="" vs descriptivo es decisión humana',
379
+ 'ctrl_name': 'el nombre accesible exige saber qué hace el control',
380
+ 'field_label': 'el texto de la etiqueta lo dicta el contenido',
381
+ 'contrast_fail': 'elegir el nuevo color es decisión de diseño (usa a11y_suggest_color)',
382
+ 'target_small': 'exige rediseñar el layout',
383
+ 'list_structure': 'reconstruir el marcado exige entender la estructura',
384
+ },
385
+ }
386
+
387
+
309
388
  def _star_nudge_once():
310
389
  """Thank the operator once per machine after a real fix lands — never in
311
390
  CI, never blocking, silence with A11Y_NO_STAR_NUDGE=1. The marker lives in
@@ -335,7 +414,7 @@ def _star_nudge_once():
335
414
  def main(argv):
336
415
  ap = argparse.ArgumentParser(description=__doc__)
337
416
  ap.add_argument('--file', required=True)
338
- ap.add_argument('--lang', choices=['es', 'en', 'pt', 'fr', 'de', 'it', 'gl', 'ca', 'eu'])
417
+ ap.add_argument('--lang', default='en', choices=['en', 'es']) # packs que existen
339
418
  ap.add_argument('--title')
340
419
  ap.add_argument('-o', '--out')
341
420
  a = ap.parse_args(argv)
@@ -0,0 +1,225 @@
1
+ #!/usr/bin/env python3
2
+ """a11y gate — the write-time guard: stop accessibility failures at birth.
3
+
4
+ The audit-after-the-fact model has a fixed flaw: it arrives after the code
5
+ was saved. This gate lives where failures are BORN — in the AI client's
6
+ write path. `a11ytoolkit init` installs a client hook (Claude Code
7
+ PreToolUse) so every save of a user-facing file runs the audit against the
8
+ git HEAD version: only NEW high/medium findings refuse the write; low
9
+ severity and known issues are warnings. The AI holding the pen has the
10
+ remediation and the element right there — the fix happens in the same
11
+ second the failure would have been born.
12
+
13
+ Honesty, as everywhere: the gate audits what the engine sees (part of
14
+ WCAG) — a filter, not a conformance verdict, and it says so in every
15
+ refusal. A11Y_GATE=off disables it; --hook fails open (a gate that crashes
16
+ a developer's flow gets uninstalled — refusing on OUR error helps nobody).
17
+
18
+ Output:
19
+ verdict(old, new, path) -> {decision, blocked[], warnings[], counts...}
20
+ guard_hook(payload) -> (exit_code, stderr) # Claude Code protocol
21
+
22
+ CLI:
23
+ a11ytoolkit guard --file index.html # human verdict, exit 2 = block
24
+ a11ytoolkit guard --hook # stdin JSON -> exit protocol
25
+ """
26
+
27
+ import argparse
28
+ import json
29
+ import re
30
+ import subprocess
31
+ import sys
32
+
33
+ from .a11yaudit import audit_html, normalize_signal
34
+
35
+ USER_SUFFIXES = ('.html', '.htm', '.css', '.jsx', '.tsx', '.vue', '.svelte',
36
+ '.astro', '.ejs', '.hbs', '.mustache', '.erb', '.twig',
37
+ '.liquid', '.jinja', '.jinja2', '.php')
38
+ BLOCKING = {'high', 'medium'}
39
+ _SEV_ORDER = {'high': 0, 'medium': 1, 'low': 2}
40
+ _LIST_CAP = 6
41
+ _FOOT = ('the gate audits what the engine sees — a filter, not a '
42
+ 'conformance verdict · disable: A11Y_GATE=off')
43
+
44
+
45
+ def is_user_facing(path):
46
+ return bool(path) and path.lower().endswith(USER_SUFFIXES)
47
+
48
+
49
+ def _counts(findings):
50
+ """(normalized signal, criterion code) → occurrences."""
51
+ out = {}
52
+ for h in findings:
53
+ key = (normalize_signal(h.get('signal', '')),
54
+ (h.get('criterion') or '').split(' ')[0])
55
+ out[key] = out.get(key, 0) + 1
56
+ return out
57
+
58
+
59
+ def old_version(path, project='.'):
60
+ """The file's content at git HEAD ('' when untracked, new, or no git —
61
+ a gate must never crash a developer's flow on missing plumbing)."""
62
+ try:
63
+ rel = subprocess.run(['git', 'ls-files', '--', path], cwd=project,
64
+ capture_output=True, text=True, timeout=10)
65
+ if rel.returncode != 0 or not rel.stdout.strip():
66
+ return ''
67
+ shown = subprocess.run(['git', 'show', f'HEAD:{path}'], cwd=project,
68
+ capture_output=True, text=True, timeout=10)
69
+ return shown.stdout if shown.returncode == 0 else ''
70
+ except Exception: # noqa: BLE001 — fail open, always
71
+ return ''
72
+
73
+
74
+ def verdict(old_content, new_content, path='(file)'):
75
+ """Compare findings in OLD (git HEAD) vs NEW (the save in flight).
76
+
77
+ The engine aggregates findings by KIND (one 'img without alt' finding
78
+ covers N images), so the gate works on KINDS, like the budget module:
79
+ a NEW kind with high/medium severity refuses the save; new LOW kinds
80
+ and kinds already in HEAD are warnings. Returns {decision, blocked[],
81
+ warnings[], known, before, after, score}."""
82
+ old = audit_html((old_content or '')[:3_000_000], url=f'(old) {path}')
83
+ new = audit_html((new_content or '')[:3_000_000], url=f'(new) {path}')
84
+ if 'error' in old or 'error' in new:
85
+ return {'decision': 'allow', 'path': path,
86
+ 'note': 'unparseable content — the gate does not judge '
87
+ 'what the engine cannot parse'}
88
+
89
+ before = _counts(old.get('findings', []))
90
+ after = _counts(new.get('findings', []))
91
+ blocked, warnings = [], []
92
+ for h in new.get('findings', []):
93
+ key = (normalize_signal(h.get('signal', '')),
94
+ (h.get('criterion') or '').split(' ')[0])
95
+ if key in before:
96
+ continue
97
+ sev = h.get('severity', 'low')
98
+ if sev in BLOCKING:
99
+ blocked.append(h)
100
+ else:
101
+ warnings.append(f"new low-severity finding: "
102
+ f"{h.get('criterion', '?').split(' ')[0]} "
103
+ f"{h.get('signal', '?')}")
104
+ known = len(before)
105
+ if known:
106
+ warnings.append(f'{known} known finding kind(s) in this file — '
107
+ f'not blocking (fix and re-run audit to lower)')
108
+ blocked.sort(key=lambda h: (_SEV_ORDER.get(h.get('severity'), 3),
109
+ h.get('signal', '')))
110
+ decision = 'block' if blocked else 'allow'
111
+ return {'decision': decision, 'path': path, 'blocked': blocked,
112
+ 'warnings': warnings, 'known': known,
113
+ 'before': sum(before.values()), 'after': sum(after.values()),
114
+ 'score': new.get('score')}
115
+
116
+
117
+ def _fmt_blocked(blocked):
118
+ out = []
119
+ for h in blocked[:_LIST_CAP]:
120
+ out.append(f" - [{h.get('severity')}] {h.get('criterion', '?')} "
121
+ f"{h.get('signal', '?')}: "
122
+ f"{(h.get('issue') or '')[:110]}")
123
+ rem = (h.get('remediation') or '')[:150]
124
+ if rem:
125
+ out.append(f" how to fix: {rem}")
126
+ more = len(blocked) - _LIST_CAP
127
+ if more > 0:
128
+ out.append(f' … and {more} more')
129
+ return '\n'.join(out)
130
+
131
+
132
+ def _fmt_verdict(v):
133
+ lines = [f"[a11y gate] {len(v['blocked'])} NEW accessibility finding(s) "
134
+ f"in {v['path']} — save refused"]
135
+ lines.append(_fmt_blocked(v['blocked']))
136
+ for w in v.get('warnings', []):
137
+ lines.append(f' note: {w}')
138
+ lines.append(_FOOT)
139
+ return '\n'.join(lines)
140
+
141
+
142
+ def payload_to_write(payload):
143
+ """Claude Code PreToolUse payload → (path, new_content or None).
144
+
145
+ Write carries the full content; Edit/MultiEdit carry fragments — apply
146
+ them to the on-disk version (which PreToolUse sees before the write)."""
147
+ if not isinstance(payload, dict):
148
+ return None, None
149
+ tool = payload.get('tool_name', '')
150
+ tin = payload.get('tool_input') or {}
151
+ path = tin.get('file_path') or ''
152
+ if tool == 'Write':
153
+ return path, tin.get('content')
154
+ if tool in ('Edit', 'MultiEdit'):
155
+ try:
156
+ content = open(path, encoding='utf-8', errors='replace').read()
157
+ except Exception: # noqa: BLE001
158
+ return path, None
159
+ edits = tin.get('edits') if tool == 'MultiEdit' else [tin]
160
+ for e in edits or []:
161
+ if not isinstance(e, dict):
162
+ continue
163
+ old, new = e.get('old_string'), e.get('new_string')
164
+ if old is None:
165
+ continue
166
+ content = content.replace(old, new) if new is not None \
167
+ else content.replace(old, '')
168
+ return path, content
169
+ return path, None
170
+
171
+
172
+ def guard_hook(payload_text):
173
+ """stdin JSON → (exit_code, stderr) under the Claude Code protocol:
174
+ exit 2 blocks the write and feeds stderr back to the model; exit 0
175
+ allows (stderr is a transcript note). Fails OPEN on unreadable input —
176
+ a gate that errors the developer's flow gets uninstalled."""
177
+ try:
178
+ payload = json.loads(payload_text or '')
179
+ except Exception: # noqa: BLE001
180
+ return 0, '[a11y gate] unreadable hook payload — allowing (fail-open)'
181
+ path, content = payload_to_write(payload)
182
+ if not path or content is None:
183
+ return 0, ''
184
+ if not is_user_facing(path):
185
+ return 0, ''
186
+ v = verdict(old_version(path), content, path)
187
+ if v['decision'] == 'block':
188
+ return 2, _fmt_verdict(v)
189
+ if v.get('warnings'):
190
+ return 0, '\n'.join(f'[a11y gate] {w}' for w in v['warnings'])
191
+ return 0, ''
192
+
193
+
194
+ def main(argv):
195
+ ap = argparse.ArgumentParser(
196
+ description='Write-time gate: refuse saves that introduce NEW '
197
+ 'high/medium accessibility findings')
198
+ ap.add_argument('--hook', action='store_true',
199
+ help='read the client hook JSON payload from stdin')
200
+ ap.add_argument('--file', help='audit this file directly')
201
+ a = ap.parse_args(argv)
202
+ if a.hook:
203
+ text = sys.stdin.read()
204
+ code, err = guard_hook(text)
205
+ if err:
206
+ print(err, file=sys.stderr)
207
+ return code
208
+ if a.file:
209
+ content = open(a.file, encoding='utf-8', errors='replace').read()
210
+ v = verdict(old_version(a.file), content, a.file)
211
+ print(json.dumps({k: v[k] for k in ('decision', 'path', 'known',
212
+ 'before', 'after', 'score')},
213
+ ensure_ascii=False, indent=1))
214
+ for w in v.get('warnings', []):
215
+ print('note:', w)
216
+ if v['decision'] == 'block':
217
+ print(_fmt_verdict(v), file=sys.stderr)
218
+ return 2
219
+ return 0
220
+ ap.print_usage()
221
+ return 2
222
+
223
+
224
+ if __name__ == '__main__':
225
+ sys.exit(main(sys.argv[1:]))
@@ -17,6 +17,9 @@ import sys
17
17
  MARKER_BEGIN = '<!-- BEGIN a11y-toolkit agent hook -->'
18
18
  MARKER_END = '<!-- END a11y-toolkit agent hook -->'
19
19
 
20
+ GATE_MATCHER = 'Write|Edit|MultiEdit'
21
+ GATE_CMD = 'a11ytoolkit guard-hook'
22
+
20
23
  BLOCK = f'''{MARKER_BEGIN}
21
24
 
22
25
  ## Accessibility guardrails — a11y-toolkit
@@ -25,6 +28,11 @@ After any UI change (HTML, CSS, templates, components, copy that becomes
25
28
  visible text), run an accessibility audit BEFORE considering the work done.
26
29
  The audit is part of the change, not an afterthought.
27
30
 
31
+ The write-time gate (installed by this command when the a11y-toolkit CLI is
32
+ on PATH): saves of user-facing files are audited against git HEAD — NEW
33
+ high/medium findings refuse the save with the fix right there. Disable with
34
+ the A11Y_GATE=off environment variable; the gate says so in every refusal.
35
+
28
36
  Quick loop (no install needed — uvx runs it from PyPI):
29
37
 
30
38
  ```bash
@@ -65,37 +73,95 @@ MCP_CONFIG = {
65
73
  }
66
74
 
67
75
 
76
+ # BEGIN sin su END (fichero truncado a mano): mensaje claro, nunca un
77
+ # ValueError — el fragmento huérfano se respeta y se añade bloque nuevo
78
+ _MERGE_MSGS = {
79
+ 'es': 'Marcador a11y-toolkit incompleto en AGENTS.md (BEGIN sin END): se '
80
+ 'dejó el fragmento tal cual y se añadió un bloque nuevo y completo.',
81
+ 'en': 'Incomplete a11y-toolkit marker in AGENTS.md (BEGIN without END): '
82
+ 'the fragment was left as-is and a fresh complete block was appended.',
83
+ }
84
+
85
+
68
86
  def merge_block(content):
69
- """Merge the hook block into existing AGENTS.md content (idempotent)."""
70
- if MARKER_BEGIN in content:
71
- start = content.index(MARKER_BEGIN)
87
+ """Merge the hook block into existing AGENTS.md content (idempotent).
88
+
89
+ A BEGIN marker without its END (hand-truncated file) is left untouched
90
+ and a fresh complete block is appended — never a crash."""
91
+ if MARKER_BEGIN in content and MARKER_END in content:
92
+ # anchor the COMPLETE pair: the BEGIN closest before the first END —
93
+ # an orphan BEGIN above it must not clobber the live block
72
94
  end = content.index(MARKER_END) + len(MARKER_END)
95
+ start = content.rindex(MARKER_BEGIN, 0, end - len(MARKER_END))
73
96
  return content[:start] + BLOCK.strip('\n') + content[end:]
97
+ if MARKER_BEGIN in content or MARKER_END in content:
98
+ # malformed marker pair: keep hands off the fragment, append fresh
99
+ return (content.rstrip('\n') + '\n\n') + BLOCK.strip('\n') + '\n'
74
100
  return (content.rstrip('\n') + '\n\n' if content.strip() else '') + BLOCK.strip('\n') + '\n'
75
101
 
76
102
 
77
- def init(path='.'):
103
+ def install_gate(path='.'):
104
+ """Install the write-time gate hook in .claude/settings.json (idempotent:
105
+ an existing a11ytoolkit guard-hook entry is left alone, as is every hook
106
+ the user added). Returns {'gate': 'installed'|'already', 'file': path}."""
107
+ sdir = os.path.join(path, '.claude')
108
+ os.makedirs(sdir, exist_ok=True)
109
+ spath = os.path.join(sdir, 'settings.json')
110
+ data = {}
111
+ if os.path.exists(spath):
112
+ try:
113
+ data = json.load(open(spath, encoding='utf-8'))
114
+ except Exception: # noqa: BLE001 — never clobber an unparseable file
115
+ data = {}
116
+ hooks = data.setdefault('hooks', {}).setdefault('PreToolUse', [])
117
+ for entry in hooks:
118
+ cmds = [h.get('command', '') for h in entry.get('hooks', [])]
119
+ if any(GATE_CMD in c for c in cmds):
120
+ return {'gate': 'already', 'file': spath}
121
+ hooks.append({'matcher': GATE_MATCHER,
122
+ 'hooks': [{'type': 'command', 'command': GATE_CMD}]})
123
+ with open(spath, 'w', encoding='utf-8') as f:
124
+ json.dump(data, f, ensure_ascii=False, indent=2)
125
+ f.write('\n')
126
+ return {'gate': 'installed', 'file': spath}
127
+
128
+
129
+ def init(path='.', gate=True):
78
130
  """Install the agent hook. Returns dict with what happened."""
79
131
  filepath = os.path.join(path, 'AGENTS.md')
80
132
  previous = open(filepath, encoding='utf-8').read() if os.path.exists(filepath) else ''
133
+ malformed = (MARKER_BEGIN in previous) != (MARKER_END in previous)
81
134
  merged = merge_block(previous)
82
135
  with open(filepath, 'w', encoding='utf-8') as f:
83
136
  f.write(merged)
84
- return {'file': filepath, 'already_present': MARKER_BEGIN in previous,
85
- 'created': not previous.strip()}
137
+ out = {'file': filepath, 'already_present': MARKER_BEGIN in previous,
138
+ 'created': not previous.strip()}
139
+ if malformed:
140
+ out['malformed_marker'] = True
141
+ out['warning'] = _MERGE_MSGS['en']
142
+ if gate:
143
+ out.update(install_gate(path))
144
+ return out
86
145
 
87
146
 
88
147
  def main(argv):
89
148
  ap = argparse.ArgumentParser(description=__doc__)
90
149
  ap.add_argument('path', nargs='?', default='.', help='project directory (default: current)')
91
150
  ap.add_argument('--check', action='store_true', help='only report whether the hook is present')
151
+ ap.add_argument('--no-gate', action='store_true',
152
+ help='do not install the write-time gate (prose hook only)')
92
153
  a = ap.parse_args(argv)
93
154
  if a.check:
94
155
  target = os.path.join(a.path, 'AGENTS.md')
95
156
  present = os.path.exists(target) and MARKER_BEGIN in open(target, encoding='utf-8').read()
96
157
  print(json.dumps({'hook_present': present, 'file': target}))
97
158
  return 0 if present else 1
98
- res = init(a.path)
159
+ res = init(a.path, gate=not a.no_gate)
160
+ if res.get('malformed_marker'):
161
+ print('! ' + res['warning'])
162
+ if res.get('gate'):
163
+ print(f"✓ write-time gate {res['gate']}: {res['file']}"
164
+ f" (block: NEW high/medium · disable: A11Y_GATE=off)")
99
165
  verb = 'updated' if res['already_present'] else ('created' if res['created'] else 'installed into')
100
166
  print(f"✓ agent hook {verb}: {res['file']}")
101
167
  print('\nMCP config (any MCP client that accepts stdio servers):')