@kinti/a11y-toolkit 5.27.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.
@@ -43,6 +43,7 @@
43
43
  a11ytoolkit annotate page.html --report r.json -o copy.html # per-element marks on a copy
44
44
  a11ytoolkit locate --file page.html --query "Submit" # element by accessible name → route
45
45
  a11ytoolkit patches --file page.html -o patches.json # sealed fix record (verify with --verify)
46
+ a11ytoolkit guard --file page.html # write-time gate: NEW high/medium refuse the save
46
47
  """
47
48
 
48
49
  import sys
@@ -78,6 +79,7 @@ from . import a11yscope
78
79
  from . import a11yannotate
79
80
  from . import a11ylocate
80
81
  from . import a11ypatches
82
+ from . import a11ygate
81
83
  from . import a11yengines
82
84
  from . import a11ytrace
83
85
  from . import a11ypatterns
@@ -124,6 +126,7 @@ SUBCOMMANDS = {
124
126
  'annotate': (a11yannotate, None),
125
127
  'locate': (a11ylocate, None),
126
128
  'patches': (a11ypatches, None),
129
+ 'guard': (a11ygate, None),
127
130
  'engines': (a11yengines, None),
128
131
  'trace': (a11ytrace, None),
129
132
  'patterns': (a11ypatterns, None),
@@ -71,9 +71,18 @@ _ROLE_FIELDS = {'textbox', 'searchbox', 'spinbutton', 'combobox', 'listbox',
71
71
  'checkbox', 'radio', 'switch'}
72
72
 
73
73
  # Subetiquetas BCP-47 principales habituales (validación blanda)
74
- _LANG_CODES = set('''af am ar az be bg bn bs ca cs cy da de el en es et eu fa fi fr ga gl
75
- gu he hi hr hu hy id is it ja ka kk km kn ko ky lo lt lv mk ml mn mr ms my ne nl or pa
76
- pl ps pt ro ru rw si sk sl sq sr sv sw ta te tg th ti tk tr uk ur uz vi zh'''.split())
74
+ # ISO 639-1 COMPLETO: los 190 subtags de idioma de 2 letras del registro IANA
75
+ # language-subtag-registry (File-Date 2026-09-17, la fuente canónica de BCP-47),
76
+ # deprecados incluidos — in/iw/ji/jw/mo/sh siguen vivos en páginas reales. La
77
+ # lista corta de la era v3 (77 códigos) rechazaba válidos como gd/eo/yi — FP de
78
+ # la revisión externa de 2026-11.
79
+ _LANG_CODES = set('''aa ab ae af ak am an ar as av ay az ba be bg bh bi bm bn bo br bs ca ce ch co cr cs cu cv cy
80
+ da de dv dz ee el en eo es et eu fa ff fi fj fo fr fy ga gd gl gn gu gv ha he hi ho hr ht hu
81
+ hy hz ia id ie ig ii ik in io is it iu iw ja ji jv jw ka kg ki kj kk kl km kn ko kr ks ku kv
82
+ kw ky la lb lg li ln lo lt lu lv mg mh mi mk ml mn mo mr ms mt my na nb nd ne ng nl nn no nr
83
+ nv ny oc oj om or os pa pi pl ps pt qu rm rn ro ru rw sa sc sd se sg sh si sk sl sm sn so sq
84
+ sr ss st su sv sw ta te tg th ti tk tl tn to tr ts tt tw ty ug uk ur uz ve vi vo wa wo xh yi
85
+ yo za zh zu'''.split())
77
86
 
78
87
  _REGIONS = set('''af ax al dz as ad ao ai aq ag ar am aw au at az bs bh bd bb by be bz
79
88
  bm bt bo bq ba bw bv io br io bn bg bf bi cv kh cm ca ky cf td cl cn cx cc co km cg cd
@@ -138,6 +147,31 @@ _AUTOFILL_TOKENS = {
138
147
  # nombres de campo que faltaban
139
148
  'cc-additional-name', 'tel-extension', 'webauthn',
140
149
  }
150
+ # 1.3.5 contradicción de propósito: el type y el token de autocomplete que
151
+ # dicen cosas incompatibles (type=email con autocomplete="postal-code").
152
+ # Solo contradicciones DURAS por familia de dato del estándar; lo raro pero
153
+ # legal queda fuera (type=email + username es EL patrón de login por correo y
154
+ # es legítimo: username queda exento en todas las familias).
155
+ _AC_FAMILIA_TEL = {'tel', 'tel-country-code', 'tel-national', 'tel-area-code',
156
+ 'tel-local', 'tel-extension'}
157
+ _AC_FAMILIA_ADDR = {'street-address', 'address-line1', 'address-line2',
158
+ 'address-line3', 'address-level1', 'address-level2',
159
+ 'address-level3', 'address-level4', 'country',
160
+ 'country-name', 'postal-code'}
161
+ _AC_FAMILY_TEXT = {'name', 'given-name', 'additional-name', 'family-name',
162
+ 'nickname', 'honorific-prefix', 'honorific-suffix',
163
+ 'organization', 'cc-name', 'cc-given-name',
164
+ 'cc-additional-name', 'cc-family-name'}
165
+ _AC_MISC = {'bday', 'bday-day', 'bday-month', 'bday-year', 'sex', 'language',
166
+ 'photo', 'impp', 'cc-number', 'cc-exp', 'cc-exp-month',
167
+ 'cc-exp-year', 'cc-csc', 'cc-type', 'transaction-currency',
168
+ 'transaction-amount'}
169
+ _AUTOCOMPLETE_CONTRA = {
170
+ 'email': _AC_FAMILIA_TEL | _AC_FAMILIA_ADDR | _AC_FAMILY_TEXT | _AC_MISC,
171
+ 'tel': {'email', 'url'} | _AC_FAMILIA_ADDR | _AC_FAMILY_TEXT | _AC_MISC,
172
+ 'url': {'email'} | _AC_FAMILIA_TEL | _AC_FAMILIA_ADDR | _AC_FAMILY_TEXT | _AC_MISC,
173
+ }
174
+
141
175
  # sección-*: comodín del estándar (section-main, section-top…)
142
176
  _SECTION = __import__('re').compile(r'^section-[a-z0-9-]+$')
143
177
 
@@ -302,6 +336,13 @@ _OVERLAY_WIDGETS = (
302
336
  ('AudioEye', ('audioeye.com',)),
303
337
  ('EqualWeb', ('equalweb.com',)),
304
338
  ("FACIL'ITI", ('facil-iti.com', 'facil-iti.org')),
339
+ # los históricos del sector público (la investigación 17-nov: Birmingham
340
+ # 2010 recomendaba Browsealoud; el linaje overlay va de Browsealoud a las
341
+ # barras modernas) y el resto del overlayfactsheet común
342
+ ('Texthelp (Browsealoud/ReachDeck)', ('texthelp.com', 'browsealoud.com', 'reachdeck.com')),
343
+ ('Recite Me', ('recite.me',)),
344
+ ('User1st', ('user1st.com',)),
345
+ ('UsableNet', ('usablenet.com',)),
305
346
  )
306
347
 
307
348
  # texto de un skip link (es/en/pt/fr — el vocabulario del patrón 3e12e1)
@@ -468,6 +509,7 @@ class _Auditor(HTMLParser):
468
509
  self.accesskeys = {} # accesskey → tag
469
510
  self.missing_autocomplete = []
470
511
  self.autocomplete_invalid = []
512
+ self.autocomplete_mismatch = []
471
513
  self.links = {} # nombre normalizado → set de hrefs
472
514
  self.generics = 0
473
515
  self.labels_for_dups = {} # id → n labels (los >1, varios)
@@ -510,6 +552,8 @@ class _Auditor(HTMLParser):
510
552
  self.has_search = False
511
553
  self.has_sitemap = False
512
554
  self.gestures = [] # touchmove/drag handlers (2.5.1)
555
+ self.focus_blur = [] # onfocus="blur()": foco robado (2.1.1)
556
+ self.focus_blur_elems = []
513
557
  self.features = {} # tag → n (rasgos de aplicabilidad)
514
558
  self.motions = [] # deviceorientation/devicemotion (2.5.4)
515
559
  self.orientation_locks = [] # screen.orientation.lock / orientation MQ (1.3.4)
@@ -862,6 +906,15 @@ class _Auditor(HTMLParser):
862
906
  _mal = _remainder[1]
863
907
  elif len(_remainder) > 2:
864
908
  _mal = _remainder[1]
909
+ if _mal is None and _remainder:
910
+ # 1.3.5 propósito contradicho: el type y el token de
911
+ # autocomplete de familias de dato distintas (determinista:
912
+ # type=email + postal-code SIEMPRE es error; type=email +
913
+ # username es el login por correo y queda exento)
914
+ _contra = _AUTOCOMPLETE_CONTRA.get(kind or 'text')
915
+ if _contra and _remainder[0].split(':')[-1] in _contra:
916
+ self.autocomplete_mismatch.append(
917
+ f'type={kind} autocomplete="{(a.get("autocomplete") or "")[:20]}"'[:56])
865
918
  if _mal:
866
919
  self.autocomplete_invalid.append(
867
920
  f'{_mal} (input name={a.get("name") or "?"})'[:60])
@@ -1007,6 +1060,13 @@ class _Auditor(HTMLParser):
1007
1060
  if a.get('ontouchmove') or a.get('ondrag'):
1008
1061
  if not (a.get('onclick') or tag in ('input', 'button', 'a')):
1009
1062
  self.gestures.append(f'{tag}[{list(a)[0] if a else ""}]')
1063
+ # 2.1.1: onfocus="blur()" — el control se quita a sí mismo el foco
1064
+ # en cuanto el teclado lo deja ahí: inalcanzable por teclado. El
1065
+ # caso exacto que el scanner de GitHub no caza (issue 288 suyo).
1066
+ _of = (a.get('onfocus') or '')
1067
+ if 'blur' in _of.lower():
1068
+ self.focus_blur.append(f'<{tag} onfocus="{_of[:30]}">')
1069
+ self.focus_blur_elems.append(a)
1010
1070
  # forms: placeholder-only, required sin indicio, financial
1011
1071
  if tag == 'form':
1012
1072
  self._financial_form = False
@@ -2058,6 +2118,9 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2058
2118
  if p.autocomplete_invalid:
2059
2119
  add_ej('medium', '1.3.5', 'autocomplete_invalid', p.autocomplete_invalid,
2060
2120
  n=len(p.autocomplete_invalid), example=', '.join(p.autocomplete_invalid[:4]))
2121
+ if p.autocomplete_mismatch:
2122
+ add_ej('medium', '1.3.5', 'autocomplete_mismatch', p.autocomplete_mismatch,
2123
+ n=len(p.autocomplete_mismatch), example=', '.join(p.autocomplete_mismatch[:4]))
2061
2124
  if p.media_autoplay:
2062
2125
  add('medium', '1.4.2', 'video_autoplay', n=p.media_autoplay,
2063
2126
  paths=[p._elem_paths[id(_a)] for _a in p.media_autoplay_elems
@@ -2118,6 +2181,11 @@ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2118
2181
  if p.gestures:
2119
2182
  add_ej('low', '2.5.1', 'gesture_no_click', p.gestures,
2120
2183
  n=len(p.gestures), example=', '.join(p.gestures[:3]))
2184
+ if p.focus_blur:
2185
+ add_ej('high', '2.1.1', 'onfocus_blur', p.focus_blur,
2186
+ n=len(p.focus_blur),
2187
+ paths=[p._elem_paths[id(_a)] for _a in p.focus_blur_elems
2188
+ if id(_a) in p._elem_paths][:5])
2121
2189
  if p.motions:
2122
2190
  add_ej('low', '2.5.4', 'motion_actuation', p.motions,
2123
2191
  n=len(p.motions), example=', '.join(p.motions[:3]))
@@ -885,6 +885,7 @@ _SIGNAL_CRIT = {
885
885
  'iframe_title': '4.1.2',
886
886
  'images_of_text': '1.4.5',
887
887
  'img_no_alt': '1.1.1',
888
+ 'onfocus_blur': '2.1.1',
888
889
  'alt_quality': '1.1.1',
889
890
  'input_img_alt': '1.1.1',
890
891
  'input_navigates': '3.2.2',
@@ -904,6 +905,9 @@ _SIGNAL_CRIT = {
904
905
  'journey_timeout_confusion': '2.2.1',
905
906
  'journey_unnamed_control': '4.1.2',
906
907
  'kbd_trap': '2.1.2',
908
+ 'skip_target_hidden': '2.4.1',
909
+ 'placeholder_contrast': '1.4.3',
910
+ 'autocomplete_mismatch': '1.3.5',
907
911
  'label_in_name': '2.5.3',
908
912
  'label_orphan': '3.3.2',
909
913
  'label_vague': '2.4.6',
@@ -169,6 +169,7 @@ _JS_NAMEOF = r'''
169
169
  _JS = r'''(maxEj) => {
170
170
  const INTER = 'a[href], button, input, select, textarea, summary, [role="button"], [role="link"], [tabindex]';
171
171
  const out = { contrast: {}, contrastReview: 0, contrastZones: [], targets: [], unnamed: [], fields: [],
172
+ placeholderContrast: [],
172
173
  imgs: [], canvasNoName: [], chartsNoEquiv: [], iframes: [], headings: [], tabindex: [], ariaHidden: [],
173
174
  blank: 0, videos: 0, videoSubs: 0, tables: 0, tableTh: 0,
174
175
  focus: [], focusFail: [], focusContrast: [], focusObscured: [], marks: 0,
@@ -407,6 +408,41 @@ _JS = r'''(maxEj) => {
407
408
  out.colorOnly.push(path(el));
408
409
  }
409
410
 
411
+ // ---- 1.4.3 contraste del placeholder (::placeholder) ----
412
+ // El placeholder ES texto que la gente con visión baja tiene que leer (y el
413
+ // 1.4.3 no distingue pseudo-elementos). El gris típico sobre blanco falla.
414
+ // Excepciones espejo del text_: control disabled (inactivo) y fondos de
415
+ // imagen (ahí ya manda la revisión manual). Sin color propio del autor el
416
+ // navegador pinta su gris por defecto: getComputedStyle lo devuelve igual,
417
+ // y si ese gris falla, el fallo es real y visible — se corrige estilando el
418
+ // placeholder, no dejando de usarlo.
419
+ for (const el of deepQ('input[placeholder], textarea[placeholder]')) {
420
+ if (out.placeholderContrast.length >= 12) break;
421
+ if (el.disabled || el.closest('fieldset[disabled]')) continue;
422
+ if (!vis(el)) continue;
423
+ if ((el.value || '').length) continue; // con valor, el placeholder no se ve
424
+ const ps = getComputedStyle(el, '::placeholder');
425
+ const fg = parseCol(ps.color);
426
+ if (!fg) continue;
427
+ const bg = bgOf(el);
428
+ if (bg.image) continue;
429
+ const px = parseFloat(ps.fontSize || getComputedStyle(el).fontSize);
430
+ const bold = parseInt(ps.fontWeight || getComputedStyle(el).fontWeight || '400', 10) >= 700;
431
+ const isLarge = px >= 24 || (bold && px >= 18.66);
432
+ const a = (fg.a === undefined) ? 1 : fg.a;
433
+ const comp = { r: Math.round(fg.r * a + bg.r * (1 - a)),
434
+ g: Math.round(fg.g * a + bg.g * (1 - a)),
435
+ b: Math.round(fg.b * a + bg.b * (1 - a)), a: 1 };
436
+ const r = ratioOf(comp, bg);
437
+ const threshold = isLarge ? 3.0 : 4.5;
438
+ if (r >= threshold) continue;
439
+ out.placeholderContrast.push({
440
+ example: path(el) + ' ::placeholder',
441
+ fg: 'rgb(' + fg.r + ',' + fg.g + ',' + fg.b + ')',
442
+ bg: 'rgb(' + bg.r + ',' + bg.g + ',' + bg.b + ')',
443
+ ratio: Math.round(r * 100) / 100, large: isLarge });
444
+ }
445
+
410
446
  // ---- 1.3.2 meaningful sequence: DOM order vs visual order, same parent ----
411
447
  {
412
448
  const byParent = new Map();
@@ -689,6 +725,20 @@ def audit_dom(data, url='(rendered)', lang='en', color_scheme='light'):
689
725
  if remaining:
690
726
  _add(findings, lang, 'low', '1.4.3', 'contrast_review', n=remaining)
691
727
 
728
+ # 1b. Contraste del placeholder (::placeholder): el gris típico sobre
729
+ # blanco falla 1.4.3 y el AT lo lee como texto real (Léonie Watson,
730
+ # estado del sector 2026). Severidad de contrast_fail (medium: la misma
731
+ # clase de texto que falla, no grave como un bloqueo de uso).
732
+ ph_failures = data.get('placeholderContrast') or []
733
+ if ph_failures:
734
+ det = '; '.join(
735
+ f"{f['fg']} vs {f['bg']} = {f['ratio']}:1 ({f['example']})"
736
+ for f in ph_failures[:4])
737
+ _add(findings, lang, 'medium', '1.4.3', 'placeholder_contrast',
738
+ examples=[f"{f['example']} → {f['fg']} vs {f['bg']} = {f['ratio']}:1"
739
+ for f in ph_failures],
740
+ n=len(ph_failures), det=det)
741
+
692
742
  # 2. Target size 2.5.8 (enlaces inline → baja: la excepción de espaciado
693
743
  # probablemente aplica y no es medible aquí; bloques → media)
694
744
  targets = data.get('targets') or []
@@ -1324,6 +1374,55 @@ _STOP_META = r"""(i) => {
1324
1374
  return el ? el.getAttribute('data-a11yruta') : ('parada ' + i);
1325
1375
  }"""
1326
1376
 
1377
+ # 2.4.1 rendered: el primer skip link REAL (texto del vocabulario del patrón
1378
+ # 3e12e1 + destino con id existente) se activa con un click de la acción por
1379
+ # defecto (los handlers corren igual que con un usuario) y se comprueba que el
1380
+ # destino quede EXPUESTO tras la activación. El foco NO se exige: los
1381
+ # navegadores modernos mueven el inicio del recorrido secuencial al destino
1382
+ # aunque no tenga tabindex=-1, así que exigir activeElement==destino sería
1383
+ # fabricar falsos positivos (la recomendación del tabindex es de calidad, no
1384
+ # de cumplimiento). Lo que sí es fallo real: el bypass lleva a contenido que
1385
+ # sigue oculto (display:none, hidden, details cerrado, subárbol aria-hidden),
1386
+ # es decir, el mecanismo no lleva a nada perceivable.
1387
+ _SKIP_TEXT_JS = ('skip|jump to|saltar|ir al contenido|ir para o conte|'
1388
+ 'passer au contenu|main content|contenido principal')
1389
+ _JS_SKIP_FIND = ('() => { const re = new RegExp(' + json.dumps(_SKIP_TEXT_JS) + ', "i");\n'
1390
+ ' for (const a of document.querySelectorAll(\'a[href^="#"]\')) {\n'
1391
+ ' const href = a.getAttribute("href"); const id = href.slice(1);\n'
1392
+ ' if (!id) continue;\n'
1393
+ ' if (!document.getElementById(id)) continue;\n'
1394
+ ' const txt = ((a.textContent || "") + " " + (a.getAttribute("aria-label") || "")).trim();\n'
1395
+ ' if (!re.test(txt)) continue;\n'
1396
+ ' return {href: href, id: id, label: txt.slice(0, 40)};\n'
1397
+ ' }\n'
1398
+ ' return null; }')
1399
+ _JS_SKIP_AFTER = r"""(id) => {
1400
+ const t = document.getElementById(id);
1401
+ if (!t) return {exposed: false, focus_path: null};
1402
+ let node = t, closed_details = false;
1403
+ while (node && node !== document.documentElement) {
1404
+ if (node.tagName === 'DETAILS' && !node.open) { closed_details = true; break; }
1405
+ node = node.parentElement;
1406
+ }
1407
+ let render_ok = true;
1408
+ if (typeof t.checkVisibility === 'function') {
1409
+ render_ok = t.checkVisibility({checkVisibilityCSS: true, checkOpacity: false});
1410
+ } else {
1411
+ let n = t;
1412
+ while (n && n !== document.documentElement) {
1413
+ const s = getComputedStyle(n);
1414
+ if (s.display === 'none' || s.visibility === 'hidden') { render_ok = false; break; }
1415
+ n = n.parentElement;
1416
+ }
1417
+ }
1418
+ const exposed = render_ok && !t.hidden && !closed_details
1419
+ && t.closest('[aria-hidden="true"]') === null;
1420
+ const ae = document.activeElement;
1421
+ const focus_path = (ae && ae !== document.body && ae !== document.documentElement)
1422
+ ? (ae.tagName.toLowerCase() + (ae.id ? '#' + ae.id : '')) : null;
1423
+ return {exposed: exposed, focus_path: focus_path};
1424
+ }"""
1425
+
1327
1426
 
1328
1427
  def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, browser='auto'):
1329
1428
  """Detección de TRAMPAS DE TECLADO (2.1.2) con Tab real.
@@ -1416,6 +1515,29 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1416
1515
  esc_releases = False
1417
1516
  except Exception:
1418
1517
  esc_releases = None
1518
+ # 2.4.1 rendered: un skip link real debe llevar a contenido expuesto
1519
+ skip = {'checked': 0, 'label': None, 'target_exposed': None,
1520
+ 'focus_after': None, 'broken': []}
1521
+ if not focus_navigated:
1522
+ try:
1523
+ found = page.evaluate(_JS_SKIP_FIND)
1524
+ if found:
1525
+ skip['checked'] = 1
1526
+ skip['label'] = found.get('label')
1527
+ # click por acción por defecto (clip del texto visible o
1528
+ # no, el hash navigation y los handlers corren igual)
1529
+ page.evaluate(
1530
+ "h => { for (const a of document.querySelectorAll('a[href]')) {"
1531
+ " if (a.getAttribute('href') === h) { a.click(); return true; } }"
1532
+ " return false; }", found['href'])
1533
+ page.wait_for_timeout(350)
1534
+ after = page.evaluate(_JS_SKIP_AFTER, found['id'])
1535
+ skip['target_exposed'] = after.get('exposed')
1536
+ skip['focus_after'] = after.get('focus_path')
1537
+ if not after.get('exposed'):
1538
+ skip['broken'].append(found['id'])
1539
+ except Exception: # noqa: BLE001 — SPA o contexto destruido: sin dato
1540
+ pass
1419
1541
  try:
1420
1542
  nav.close()
1421
1543
  except Exception:
@@ -1443,6 +1565,13 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1443
1565
  'remediation': _t(lang, 'kbd_trap_rem'),
1444
1566
  'examples': elems,
1445
1567
  })
1568
+ if skip['broken']:
1569
+ findings.append({
1570
+ 'severity': 'medium', 'criterion': CRIT.get(lang, CRIT['es']).get('2.4.1', '2.4.1'),
1571
+ 'signal': 'skip_target_hidden',
1572
+ 'issue': _t(lang, 'skip_target_hidden').format(
1573
+ label=skip.get('label') or 'skip link', id=', '.join(skip['broken'])),
1574
+ 'remediation': _t(lang, 'skip_target_hidden_rem')})
1446
1575
  from .a11yaudit import compute_score
1447
1576
  return {
1448
1577
  'url': url,
@@ -1455,14 +1584,25 @@ def audit_keyboard(url, max_steps=60, lang='en', timeout=45, auth_state=None, br
1455
1584
  'cycle': {'detected': bool(cycle),
1456
1585
  'elements': [paths.get(i, f'tab stop {i}') for i in cycle] if cycle else [],
1457
1586
  'escape_releases': esc_releases},
1587
+ 'skip_link': {'checked': skip['checked'], 'label': skip.get('label'),
1588
+ 'target_exposed': skip.get('target_exposed'),
1589
+ 'focus_after': skip.get('focus_after')},
1458
1590
  'findings': findings,
1459
1591
  'limits': (('Real Tab walk in Chromium (max {n} steps). Focus inside cross-origin '
1460
1592
  'iframes is not trackable and is marked as such. A cycle that Escape '
1461
- 'releases (a correct modal) is NOT reported as a finding.'
1593
+ 'releases (a correct modal) is NOT reported as a finding. The first '
1594
+ 'real skip link is activated once: a target still hidden after '
1595
+ 'activation is reported (2.4.1), but focus not landing on it is not '
1596
+ 'measured (modern browsers move the sequential-focus start regardless '
1597
+ 'of tabindex).'
1462
1598
  ).format(n=max_steps) if lang == 'en' else
1463
1599
  ('Recorrido con Tab real en Chromium (tope {n} pasos). El foco dentro de '
1464
1600
  'iframes entre dominios no es rastreable y se marca como tal. Un ciclo '
1465
- 'con Escape operativo (modal correcto) NO se reporta como hallazgo.'
1601
+ 'con Escape operativo (modal correcto) NO se reporta como hallazgo. Se '
1602
+ 'activa una vez el primer skip link real: si el destino sigue oculto '
1603
+ 'tras activarlo se reporta (2.4.1), pero que el foco no caiga en él no '
1604
+ 'se mide (los navegadores modernos mueven el inicio del recorrido '
1605
+ 'secuencial con o sin tabindex).'
1466
1606
  ).format(n=max_steps)),
1467
1607
  }
1468
1608
 
@@ -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
@@ -92,7 +100,33 @@ def merge_block(content):
92
100
  return (content.rstrip('\n') + '\n\n' if content.strip() else '') + BLOCK.strip('\n') + '\n'
93
101
 
94
102
 
95
- 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):
96
130
  """Install the agent hook. Returns dict with what happened."""
97
131
  filepath = os.path.join(path, 'AGENTS.md')
98
132
  previous = open(filepath, encoding='utf-8').read() if os.path.exists(filepath) else ''
@@ -105,6 +139,8 @@ def init(path='.'):
105
139
  if malformed:
106
140
  out['malformed_marker'] = True
107
141
  out['warning'] = _MERGE_MSGS['en']
142
+ if gate:
143
+ out.update(install_gate(path))
108
144
  return out
109
145
 
110
146
 
@@ -112,15 +148,20 @@ def main(argv):
112
148
  ap = argparse.ArgumentParser(description=__doc__)
113
149
  ap.add_argument('path', nargs='?', default='.', help='project directory (default: current)')
114
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)')
115
153
  a = ap.parse_args(argv)
116
154
  if a.check:
117
155
  target = os.path.join(a.path, 'AGENTS.md')
118
156
  present = os.path.exists(target) and MARKER_BEGIN in open(target, encoding='utf-8').read()
119
157
  print(json.dumps({'hook_present': present, 'file': target}))
120
158
  return 0 if present else 1
121
- res = init(a.path)
159
+ res = init(a.path, gate=not a.no_gate)
122
160
  if res.get('malformed_marker'):
123
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)")
124
165
  verb = 'updated' if res['already_present'] else ('created' if res['created'] else 'installed into')
125
166
  print(f"✓ agent hook {verb}: {res['file']}")
126
167
  print('\nMCP config (any MCP client that accepts stdio servers):')
@@ -25,6 +25,8 @@
25
25
  },
26
26
  "autocomplete_invalid": "{n} invalid autocomplete token values: {example}. Tokens must come from the HTML autofill standard (§7.5) or assistive tech cannot identify the purpose (1.3.5).",
27
27
  "autocomplete_invalid_rem": "Use standard tokens: email, tel, name, postal-code, one-time-code… (full list in the tool).",
28
+ "autocomplete_mismatch": "{n} fields with purpose contradicted between type and autocomplete: {example}. The browser cannot decide the purpose (1.3.5).",
29
+ "autocomplete_mismatch_rem": "For humans, don't make me think; for machines, don't make me guess: type and token must say the same thing. type=email takes an email-family token (email, username); type=tel, the tel family; type=url, url.",
28
30
  "autocomplete_rem": "Add autocomplete with the right token (email, tel, name, postal-code…, 1.3.5): free accessibility and autofill at zero cost.",
29
31
  "blank_no_warning": "{n} links with target=\"_blank\" that do not warn they open a new window.",
30
32
  "blank_no_warning_rem": "Add a text hint (or title/aria-label): \"(opens in a new window)\", or let the user decide.",
@@ -221,7 +223,9 @@
221
223
  "role_no_tabindex_rem": "Add tabindex=\"0\" to every element that receives role=\"button\"/\"link\", plus Enter/Space key handling — or use the native <button>/<a href> element.",
222
224
  "err_redirect_blocked": "redirect to a disallowed destination (private network): {url}",
223
225
  "alt_quality": "{n} images with low-quality alt text (filenames, generic words or placeholders).",
224
- "alt_quality_rem": "Alt like \"image\", \"foto\", \"img_123.jpg\" or a dash says nothing to a screen-reader user. Replace it with what the image conveys in its context; if the image is decorative, use alt=\"\" so assistive tech skips it."
226
+ "alt_quality_rem": "Alt like \"image\", \"foto\", \"img_123.jpg\" or a dash says nothing to a screen-reader user. Replace it with what the image conveys in its context; if the image is decorative, use alt=\"\" so assistive tech skips it.",
227
+ "onfocus_blur": "{n} element(s) whose onfocus handler removes focus (onfocus=\"blur()\"): keyboard users cannot reach them at all.",
228
+ "onfocus_blur_rem": "Remove the onfocus=\"blur()\" handler: stealing focus makes the element unreachable by keyboard (2.1.1). If the element must not be focusable, use tabindex=\"-1\" instead of taking focus away."
225
229
  },
226
230
  "badge": {
227
231
  "name": "a11y-toolkit",
@@ -309,6 +313,10 @@
309
313
  "input_navigates_rem": "Changing a setting must never navigate without user request (3.2.2): add an \"Apply\" button or confirm before submitting.",
310
314
  "kbd_trap": "KEYBOARD TRAP: {n} controls caught in a cycle ({cycle}) and Escape does not release. Focus cannot leave (2.1.2).",
311
315
  "kbd_trap_rem": "Every focus-containing component (modal, menu) must release with Escape (ideally click-outside too): close it and return focus to the trigger. Test it with the keyboard alone.",
316
+ "skip_target_hidden": "Skip link \"{label}\" leads to hidden content: after activating it, the target ({id}) is still not exposed (display:none, hidden, closed details or aria-hidden). The bypass mechanism lands on nothing perceivable (2.4.1).",
317
+ "skip_target_hidden_rem": "A bypass mechanism must land on perceivable content (2.4.1): point the link at visible content, or have the page reveal or expand the target on activation (hashchange or click), and give the target tabindex=\"-1\" so focus follows.",
318
+ "placeholder_contrast": "{n} placeholders with insufficient contrast: {det}. The placeholder is text low-vision users must read, and 1.4.3 does not distinguish pseudo-elements (4.5:1, or 3:1 large text).",
319
+ "placeholder_contrast_rem": "Give the placeholder its own color at ≥4.5:1 against the field background (the browser default gray sits at the minimum and fails on non-white backgrounds). Safe recipe: same color as the field text with opacity 0.7.",
312
320
  "limits": "Rendered audit: honest heuristics, no substitute for a screen reader or manual review. Contrast computed over computed backgrounds; cases with background images are reported as \"review\". 2.5.8 allows exceptions (equivalent inline, spacing) approximated here.",
313
321
  "reduced_motion_ignored": "{n} looping animations still run with prefers-reduced-motion set (before {n}, after {nr}): the user's preference is ignored (2.2.2).",
314
322
  "reduced_motion_ignored_rem": "Wrap animations in @media (prefers-reduced-motion: reduce) { animation: none } — or pause via the Animation API. The user asked for less motion; honor it.",
@@ -25,6 +25,8 @@
25
25
  },
26
26
  "autocomplete_invalid": "{n} valores de autocomplete no válidos: {example}. El token debe ser uno del estándar HTML (§7.5 autofill), o el lector no identificará el propósito (1.3.5).",
27
27
  "autocomplete_invalid_rem": "Usa tokens del estándar: email, tel, name, postal-code, one-time-code… (lista completa en la herramienta).",
28
+ "autocomplete_mismatch": "{n} campos con propósito contradicho entre type y autocomplete: {example}. El navegador no puede decidir el propósito (1.3.5).",
29
+ "autocomplete_mismatch_rem": "Para humanos, don't make me think; para máquinas, don't make me guess: el type y el token han de decir lo mismo. type=email lleva autocomplete de familia email (email, username); type=tel, familia tel; type=url, url.",
28
30
  "autocomplete_rem": "Añade autocomplete con el token correcto (email, tel, name, postal-code…, 1.3.5): relleno automático y voz de accesibilidad con sobrecoste cero.",
29
31
  "blank_no_warning": "{n} enlaces con target=\"_blank\" sin avisar de que abren ventana nueva.",
30
32
  "blank_no_warning_rem": "Añade aviso en texto (o title/aria-label): «(abre en ventana nueva)», o deja que la persona usuaria decida.",
@@ -221,7 +223,9 @@
221
223
  "role_no_tabindex_rem": "Añade tabindex=\"0\" a todo elemento con role=\"button\"/\"link\", más manejo de Enter/Espacio — o usa el elemento nativo <button>/<a href>.",
222
224
  "err_redirect_blocked": "redirección a un destino no permitido (red privada): {url}",
223
225
  "alt_quality": "{n} imágenes con texto alt de baja calidad (nombres de fichero, palabras genéricas o marcadores).",
224
- "alt_quality_rem": "Un alt como «imagen», «foto», «img_123.jpg» o una raya no dice nada a quien usa lector de pantalla. Sustitúyelo por lo que la imagen transmite en su contexto; si es decorativa, usa alt=\"\" para que la tecnología asistiva la salte."
226
+ "alt_quality_rem": "Un alt como «imagen», «foto», «img_123.jpg» o una raya no dice nada a quien usa lector de pantalla. Sustitúyelo por lo que la imagen transmite en su contexto; si es decorativa, usa alt=\"\" para que la tecnología asistiva la salte.",
227
+ "onfocus_blur": "{n} elemento(s) cuyo manejador onfocus quita el foco (onfocus=\"blur()\"): con teclado no se puede llegar a ellos.",
228
+ "onfocus_blur_rem": "Quita el manejador onfocus=\"blur()\": robar el foco deja el elemento inalcanzable por teclado (2.1.1). Si el elemento no debe ser enfocable, usa tabindex=\"-1\" en vez de robar el foco."
225
229
  },
226
230
  "badge": {
227
231
  "name": "a11y-toolkit",
@@ -309,6 +313,10 @@
309
313
  "input_navigates_rem": "Cambiar un ajuste nunca debe navegar sin petición del usuario (3.2.2): añade un botón «Aplicar» o confirma antes de enviar.",
310
314
  "kbd_trap": "TRAMPA DE TECLADO: {n} controles atrapados en un ciclo ({cycle}) y Escape no libera. El foco no puede salir (2.1.2).",
311
315
  "kbd_trap_rem": "Todo componente con foco contenido (modal, menú) debe liberarse con Escape (y idealmente clic fuera): ciérralo y devuelve el foco al disparador. Pruébalo solo con teclado.",
316
+ "skip_target_hidden": "El skip link «{label}» lleva a contenido oculto: tras activarlo, el destino ({id}) sigue sin exponerse (display:none, hidden, details cerrado o aria-hidden). El mecanismo de bypass no lleva a nada perceivable (2.4.1).",
317
+ "skip_target_hidden_rem": "Un mecanismo de bypass debe aterrizar en contenido perceivable (2.4.1): apunta el enlace a contenido visible, o haz que la página revele o expanda el destino al activarlo (hashchange o click), y dale tabindex=\"-1\" al destino para que el foco lo acompañe.",
318
+ "placeholder_contrast": "{n} placeholders con contraste insuficiente: {det}. El placeholder es texto que la gente con visión baja tiene que leer, y 1.4.3 no distingue pseudo-elementos (4.5:1, o 3:1 en texto grande).",
319
+ "placeholder_contrast_rem": "Dale color propio al placeholder con contraste ≥4.5:1 sobre el fondo del campo (el gris por defecto del navegador roza el mínimo y falla sobre fondos no blancos). Ejemplo seguro: color igual al texto del campo pero con opacity 0.7.",
312
320
  "limits": "Auditoría renderizada: heurística honesta, no sustituye lector de pantalla ni revisión manual. Contraste calculado sobre fondos computados; los casos con imagen de fondo se reportan como «revisar». 2.5.8 admite excepciones (inline equivalente, espaciado) que aquí se aproximan.",
313
321
  "reduced_motion_ignored": "{n} animaciones en bucle siguen moviéndose con prefers-reduced-motion activo (antes {n}, ahora {nr}): la preferencia del usuario se ignora (2.2.2).",
314
322
  "reduced_motion_ignored_rem": "Envuelve las animaciones en @media (prefers-reduced-motion: reduce) { animation: none } — o paúsala con la API Animation. El usuario pidió menos movimiento; respóndelo.",
@@ -97,7 +97,7 @@ try:
97
97
  except ImportError:
98
98
  ARIALIVE_JS = None # repo checkout: read the file
99
99
 
100
- VERSION = '5.27.0'
100
+ VERSION = '5.28.0'
101
101
 
102
102
  # Params renombrados a inglés en 5.11.0; se aceptan los nombres previos.
103
103
  PARAM_ALIASES = {
@@ -376,8 +376,12 @@ TOOLS = [
376
376
  'up to 60 real tab stops, cycle detection (the modal pattern), then '
377
377
  'the decisive test — does ESCAPE release the cycle? A modal that '
378
378
  'cycles and releases on Escape is correct and NOT reported; a cycle '
379
- 'Escape cannot leave is a trap (high severity). Returns the full tab '
380
- 'stop list too. Requires local Playwright.'),
379
+ 'Escape cannot leave is a trap (high severity). It also activates '
380
+ 'the first real skip link once and reports skip_target_hidden '
381
+ '(medium, 2.4.1) when the target is still not exposed after '
382
+ 'activation — focus landing on it is not required (browsers move '
383
+ 'the sequential-focus start regardless of tabindex). Returns the '
384
+ 'full tab stop list too. Requires local Playwright.'),
381
385
  'inputSchema': {'type': 'object', 'properties': {
382
386
  'url': {'type': 'string'},
383
387
  'lang': {'type': 'string', 'enum': ['es', 'en']},
@@ -1099,7 +1103,7 @@ _ROUTING = {
1099
1103
  'a11y_audit_url': 'Prefer a11y_audit_dom when JS renders the content or contrast/2.5.8/focus matter; use pages for light multi-page sampling. Static CANNOT measure class/var() CSS contrast (1.4.3): the report\'s not_measured says so — a 100 is never \'contrast is fine\'.',
1100
1104
  'a11y_audit_dom': 'Use instead of a11y_audit_url on JS-heavy pages; needs local Playwright.',
1101
1105
  'a11y_reflow': 'Scope: 320px reflow only (1.4.10); for the full rendered pass use a11y_audit_dom.',
1102
- 'a11y_keyboard': 'Scope: keyboard traps (2.1.2); focus visibility is part of a11y_audit_dom.',
1106
+ 'a11y_keyboard': 'Scope: keyboard traps (2.1.2) + rendered bypass landing; focus visibility is part of a11y_audit_dom.',
1103
1107
  'a11y_scroll': 'For paginated feeds only; general page audit is a11y_audit_url/dom.',
1104
1108
  'a11y_contrast_pair': 'For flat pairs; text over images needs a11y_contrast_image.',
1105
1109
  'a11y_contrast_image': 'Use instead of a11y_contrast_pair whenever the background is a photo/gradient.',
@@ -1133,7 +1137,7 @@ _ANN = {
1133
1137
  'a11y_audit_url': ('Express WCAG audit', True, True),
1134
1138
  'a11y_audit_dom': ('Rendered WCAG audit', True, True),
1135
1139
  'a11y_reflow': ('320px reflow check', True, True),
1136
- 'a11y_keyboard': ('Keyboard-trap detector', True, True),
1140
+ 'a11y_keyboard': ('Keyboard-trap + skip-link landing detector', True, True),
1137
1141
  'a11y_html_validate': ('W3C Nu validation', True, True),
1138
1142
  'a11y_forms': ('Form error testing', True, True),
1139
1143
  'a11y_scroll': ('Infinite-scroll audit', True, True),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kinti/a11y-toolkit",
3
- "version": "5.27.0",
3
+ "version": "5.28.0",
4
4
  "mcpName": "io.github.kinti/a11y-toolkit",
5
5
  "description": "Zero-dependency WCAG 2.2 accessibility engine (37 MCP tools + CLI): audits, contrast fixing, SHA-256-sealed evidence packs, SARIF, EARL/ACT, CI ratchet. Self-contained: the pure-stdlib Python engine ships inside and runs via python3 \u2014 no downloads, no installs.",
6
6
  "license": "MIT",