@kinti/a11y-toolkit 5.25.1 → 5.26.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.
@@ -31,6 +31,8 @@
31
31
  a11ytoolkit mutants --seed 7 --n 12 # the engine's sealed self-exam
32
32
  a11ytoolkit corpus build && a11ytoolkit corpus verify # versioned audit corpus (dataset + baselines)
33
33
  a11ytoolkit fingerprints page1.html page2.html --dir p/ # twin-page detection (one audit per template)
34
+ a11ytoolkit audit --url https://web --standard en301549 # EN 301 549 clause on every finding
35
+ a11ytoolkit scope audit.json -o scope.json --standard en301549 # applicability: machine proposes, human confirms
34
36
  """
35
37
 
36
38
  import sys
@@ -64,6 +66,7 @@ from . import a11ywcag3
64
66
  from . import a11yroute
65
67
  from . import a11ymutants
66
68
  from . import a11yfingerprints
69
+ from . import a11yscope
67
70
 
68
71
  SUBCOMMANDS = {
69
72
  'pair': (contrast, 'pair'),
@@ -101,6 +104,7 @@ SUBCOMMANDS = {
101
104
  'route': (a11yroute, None),
102
105
  'mutants': (a11ymutants, None),
103
106
  'fingerprints': (a11yfingerprints, None),
107
+ 'scope': (a11yscope, None),
104
108
  }
105
109
 
106
110
 
@@ -291,6 +291,10 @@ def _crit(lang, code):
291
291
 
292
292
 
293
293
  class _Auditor(HTMLParser):
294
+ # rasgos contados para el scope (evidencia positiva de aplicabilidad)
295
+ FEATURE_TAGS = ('video', 'audio', 'track', 'embed', 'object', 'iframe',
296
+ 'form', 'input', 'select', 'textarea', 'table')
297
+
294
298
  def __init__(self):
295
299
  super().__init__(convert_charrefs=True)
296
300
  self.imgs_no_alt = []
@@ -422,6 +426,7 @@ class _Auditor(HTMLParser):
422
426
  self.has_search = False
423
427
  self.has_sitemap = False
424
428
  self.gestures = [] # touchmove/drag handlers (2.5.1)
429
+ self.features = {} # tag → n (rasgos de aplicabilidad)
425
430
  self.motions = [] # deviceorientation/devicemotion (2.5.4)
426
431
  self.orientation_locks = [] # screen.orientation.lock / orientation MQ (1.3.4)
427
432
  self.videos_descriptions = 0 # videos WITH descriptions track
@@ -503,6 +508,15 @@ class _Auditor(HTMLParser):
503
508
  def handle_starttag(self, tag, attrs):
504
509
  a = dict(attrs)
505
510
  self.elements += 1
511
+ # rasgos estructurales para el scope de aplicabilidad (a11yscope):
512
+ # evidencia POSITIVA — cero <video> habilita proponer 1.2.x como no
513
+ # aplicable; la ausencia de señal jamás cuenta como ausencia de
514
+ # contenido. input type=hidden no es un campo visible.
515
+ if tag in self.FEATURE_TAGS:
516
+ if tag == 'input' and (a.get('type') or '').strip().lower() == 'hidden':
517
+ pass
518
+ else:
519
+ self.features[tag] = self.features.get(tag, 0) + 1
506
520
  if a.get('id'):
507
521
  self.ids[a['id']] = self.ids.get(a['id'], 0) + 1
508
522
  if self.root_tag is None:
@@ -1169,7 +1183,7 @@ def _not_measured(lang='en'):
1169
1183
  } for c in sorted(RENDERED_ONLY)]
1170
1184
 
1171
1185
 
1172
- def audit_html(html_text, url='(html)', lang='en'):
1186
+ def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
1173
1187
  """Analiza una cadena HTML y devuelve el informe de hallazgos (es/en)."""
1174
1188
  p = _Auditor()
1175
1189
  try:
@@ -1577,6 +1591,20 @@ def audit_html(html_text, url='(html)', lang='en'):
1577
1591
  'findings': findings,
1578
1592
  'limits': _t(lang, 'limits'),
1579
1593
  }
1594
+ # rasgos de aplicabilidad (evidencia positiva para a11yscope): cuentan
1595
+ # lo que el parser VIO, no lo que dejó de señalar. Va SIEMPRE (vacío es
1596
+ # evidencia: el parser corrió y no vio ninguno) — un informe sin bloque
1597
+ # es un informe viejo y a11yscope no propone nada sobre él.
1598
+ res['features'] = dict(sorted(p.features.items()))
1599
+ # --standard en301549: cláusula EN por hallazgo + bloque del estándar
1600
+ if standard == 'en301549':
1601
+ from . import a11yen301549 as _enstd
1602
+ _tgt = target or _enstd.target_for_mode('static')
1603
+ res['standard'] = _enstd.standard_block(_tgt, lang)
1604
+ for h in findings:
1605
+ _cl = _enstd.clause_for(h['criterion'].split(' ')[0], _tgt)
1606
+ if _cl:
1607
+ h['clause'] = _cl
1580
1608
  # overlays detectados: dato del informe (diligencia de compra), nunca un
1581
1609
  # hallazgo — no hay criterio WCAG que anclar y el score no se toca
1582
1610
  overlays, _seen = [], set()
@@ -1676,7 +1704,7 @@ _T_SCHEME = {
1676
1704
  }
1677
1705
 
1678
1706
 
1679
- def audit_url(url, timeout=30, lang='en'):
1707
+ def audit_url(url, timeout=30, lang='en', standard=None, target=None):
1680
1708
  if url.split(':')[0].lower() not in ('http', 'https'):
1681
1709
  return {'error': _T_SCHEME.get(lang, _T_SCHEME['es'])}
1682
1710
  try:
@@ -1685,7 +1713,7 @@ def audit_url(url, timeout=30, lang='en'):
1685
1713
  return {'error': str(e)}
1686
1714
  except Exception as e: # noqa: BLE001
1687
1715
  return {'error': _t(lang, 'fetch_error').format(e=e)}
1688
- return audit_html(html_text, url, lang=lang)
1716
+ return audit_html(html_text, url, lang=lang, standard=standard, target=target)
1689
1717
 
1690
1718
 
1691
1719
  _LOC = re.compile(r'<loc>\s*([^<\s]+)\s*</loc>', re.I)
@@ -1910,6 +1938,22 @@ def audit_changed(base='HEAD', lang='en', cwd='.'):
1910
1938
  }
1911
1939
 
1912
1940
 
1941
+ def _apply_standard(res, standard, target, lang):
1942
+ """ Enriquecimiento post-hoc EN 301 549 (site crawl, --changed): añade
1943
+ bloque standard y cláusula por hallazgo. standard=None → res intacto."""
1944
+ if standard != 'en301549' or not isinstance(res, dict) or 'error' in res:
1945
+ return res
1946
+ from . import a11yen301549 as _enstd
1947
+ _tgt = target or _enstd.target_for_mode(res.get('mode', 'static'))
1948
+ res['standard'] = _enstd.standard_block(_tgt, lang)
1949
+ for _pg in res.get('reports', [res]):
1950
+ for h in _pg.get('findings', []):
1951
+ _cl = _enstd.clause_for(h.get('criterion'), _tgt)
1952
+ if _cl:
1953
+ h['clause'] = _cl
1954
+ return res
1955
+
1956
+
1913
1957
  def main(argv):
1914
1958
  ap = argparse.ArgumentParser(description=__doc__)
1915
1959
  g = ap.add_mutually_exclusive_group(required=True)
@@ -1924,25 +1968,38 @@ def main(argv):
1924
1968
  help='crawl ligero mismo dominio (1 = solo la página)')
1925
1969
  ap.add_argument('--no-sitemap', action='store_true',
1926
1970
  help='descubre por enlaces, sin leer el sitemap')
1971
+ ap.add_argument('--standard', choices=['en301549'], default=None,
1972
+ help='añade a cada hallazgo su cláusula EN 301 549 V4.1.1 '
1973
+ '(9.x web por defecto)')
1974
+ ap.add_argument('--target', choices=['web', 'documents', 'software'],
1975
+ default=None, help='target EN: web=9.x, documents=10.x, '
1976
+ 'software=11.x (default: según el modo)')
1927
1977
  a = ap.parse_args(argv)
1928
1978
  if a.changed:
1929
1979
  res = audit_changed(base=a.base, lang=a.lang)
1930
1980
  if 'error' in res:
1931
1981
  print(json.dumps(res))
1932
1982
  return 1
1983
+ res = _apply_standard(res, a.standard, a.target, a.lang)
1933
1984
  print(json.dumps(res, ensure_ascii=False, indent=1))
1934
1985
  return 2 if res.get('blocking') else 0
1935
1986
  if a.url:
1936
1987
  try:
1937
1988
  res = (audit_site(a.url, max_pages=a.pages, lang=a.lang,
1938
1989
  from_sitemap=not a.no_sitemap)
1939
- if a.pages > 1 else audit_url(a.url, lang=a.lang))
1990
+ if a.pages > 1 else audit_url(a.url, lang=a.lang,
1991
+ standard=a.standard,
1992
+ target=a.target))
1940
1993
  except Exception as e: # noqa: BLE001
1941
1994
  print(json.dumps({'error': f'no se pudo descargar: {e}'}))
1942
1995
  return 1
1943
1996
  else:
1944
1997
  with open(a.file, encoding='utf-8', errors='replace') as f:
1945
- res = audit_html(f.read(), a.file, lang=a.lang)
1998
+ res = audit_html(f.read(), a.file, lang=a.lang,
1999
+ standard=a.standard, target=a.target)
2000
+ # site/changed no pasan por audit_html: enriquecer post-hoc para que
2001
+ # --standard nunca se descarte en silencio en NINGUNA ruta del CLI
2002
+ res = _apply_standard(res, a.standard, a.target, a.lang)
1946
2003
  print(json.dumps(res, ensure_ascii=False, indent=1))
1947
2004
  return 0
1948
2005
 
@@ -144,6 +144,28 @@ _JS = r'''(maxEj) => {
144
144
  return s.visibility !== 'hidden' && s.display !== 'none' && parseFloat(s.opacity || '1') > 0.05
145
145
  && !el.closest('[aria-hidden="true"]');
146
146
  };
147
+ const visText = el => {
148
+ if (!vis(el)) return false;
149
+ const s = getComputedStyle(el);
150
+ const ti = parseFloat(s.textIndent) || 0;
151
+ if (ti < -100 && (['hidden', 'clip'].includes(s.overflow) || ['hidden', 'clip'].includes(s.overflowX) || ['hidden', 'clip'].includes(s.overflowY))) return false;
152
+ if (s.position === 'absolute' && (s.clip !== 'auto' || s.clipPath !== 'none')) {
153
+ const r = el.getBoundingClientRect();
154
+ if (r.width <= 2 && r.height <= 2) return false;
155
+ }
156
+ return true;
157
+ };
158
+ const hasVisibleText = el => {
159
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
160
+ let n;
161
+ while ((n = walker.nextNode())) {
162
+ const txt = (n.nodeValue || '').trim();
163
+ if (!txt) continue;
164
+ const p = n.parentElement;
165
+ if (p && visText(p)) return true;
166
+ }
167
+ return false;
168
+ };
147
169
  const path = el => {
148
170
  let p = el.tagName.toLowerCase();
149
171
  if (el.id) return '#' + el.id;
@@ -212,6 +234,7 @@ _JS = r'''(maxEj) => {
212
234
  }
213
235
  if (!el || el.closest('script, style, noscript, svg title')) continue;
214
236
  if (!vis(el)) continue;
237
+ if (!visText(el)) continue;
215
238
  // text_ de solo símbolos (±±±@@) o UN carácter ASCII (X de cerrar):
216
239
  // contenido no verbal — sin requisito. CUALQUIER letra/dígito de
217
240
  // cualquier alfabeto (CJK, cirílico, árabe…) ES text_ verbal
@@ -518,8 +541,10 @@ _JS = r'''(maxEj) => {
518
541
  if (fgf && !bgf.image) {
519
542
  const fs = parseFloat(s.fontSize) || 16;
520
543
  const isLarge = fs >= 24 || (fs >= 18.66 && (parseInt(s.fontWeight) || 400) >= 700);
544
+ const hasText = hasVisibleText(el);
545
+ const threshold = !hasText ? 3.0 : (isLarge ? 3.0 : 4.5);
521
546
  const rf2 = ratioOf(over(fgf, bgf), bgf);
522
- if (rf2 < (isLarge ? 3.0 : 4.5) && out.focusContrast.length < 20)
547
+ if (rf2 < threshold && out.focusContrast.length < 20)
523
548
  out.focusContrast.push({ example: path(el), ratio: Math.round(rf2 * 100) / 100 });
524
549
  }
525
550
  // (2.4.11 por parada se cubre abajo con la causa raíz)
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env python3
2
+ """EN 301 549 V4.1.1 (2026) — the clause map and the standard metadata.
3
+
4
+ EN 301 549 is the European harmonized ICT accessibility standard (the EAA's
5
+ technical backbone, and — since 2026 — the basis of Canada's ICT
6
+ accessibility standard). Its clauses 9 (web), 10 (non-web documents) and
7
+ 11 (non-web software) each carry the WCAG success criteria under the SAME
8
+ numbering: SC 1.4.3 is clause 9.1.4.3 for web, 10.1.4.3 for documents and
9
+ 11.1.4.3 for software.
10
+
11
+ That numbering identity was not assumed — it was verified against the
12
+ Government of Canada CIO applicability wizard built on EN 301 549 V4.1.1
13
+ (2026): all 55 WCAG 2.2 A/AA criteria carry their mirrored clause number in
14
+ clauses 9, 10 AND 11 (55/55 each). AAA is NOT claimed: clause 9 carries only
15
+ the AAA criteria the standard itself modifies, and A/AA is the conformance
16
+ level the toolkit evaluates.
17
+
18
+ The families beyond the WCAG mirror (5, 6, 7, 8, 12, 13) are real
19
+ applicability territory — closed functionality, RTT, hardware, relay — that
20
+ no HTML audit can answer. They appear here as honest rows for the scope
21
+ engine (a11yscope), never as something this toolkit evaluates.
22
+
23
+ No network, no third parties: this module is pure data.
24
+ """
25
+
26
+ # Clause prefix per ICT target (EN 301 549 V4.1.1 structure).
27
+ _CLAUSE_PREFIX = {'web': '9', 'documents': '10', 'software': '11'}
28
+
29
+ STANDARD_NAME = 'EN 301 549 V4.1.1 (2026)'
30
+
31
+ # Targets the toolkit can map findings for. 'web' covers the HTML audits
32
+ # (static/rendered), 'documents' the PDF/DOCX screening, 'software' non-web
33
+ # UIs audited as HTML prototypes.
34
+ TARGETS = tuple(sorted(_CLAUSE_PREFIX))
35
+
36
+ # Families outside the WCAG mirror. status: machine proposal only where the
37
+ # product shape itself decides (a web-only product cannot carry RTT/hardware
38
+ # clauses); everything else is a human applicability question. Titles are
39
+ # the standard's own chapter titles (verified against the V4.1.1 wizard).
40
+ FAMILIES = (
41
+ {'family': '5', 'key': 'generic'},
42
+ {'family': '6', 'key': 'rtt'},
43
+ {'family': '7', 'key': 'video_capabilities'},
44
+ {'family': '8', 'key': 'hardware'},
45
+ {'family': '12', 'key': 'products_info'},
46
+ {'family': '13', 'key': 'relay_emergency'},
47
+ )
48
+
49
+
50
+ def clause_for(code, target='web'):
51
+ """'1.4.3' + target → '9.1.4.3'. None si el código no es un SC válido.
52
+
53
+ Acepta la forma con nombre ('1.4.3 Contrast (Minimum)') que viaja en los
54
+ hallazgos y en la matriz del pack: solo el primer token es el código.
55
+ """
56
+ token = str(code).split(' ')[0] if code is not None else ''
57
+ parts = token.split('.')
58
+ if len(parts) != 3 or not all(p.isdigit() for p in parts):
59
+ return None
60
+ prefix = _CLAUSE_PREFIX.get(target)
61
+ return f'{prefix}.{token}' if prefix else None
62
+
63
+
64
+ def target_for_mode(mode):
65
+ """Modo del informe → target EN: la web es 9.x, los documentos 10.x."""
66
+ return 'documents' if mode in ('pdf', 'docx') else 'web'
67
+
68
+
69
+ def family_rows(lang='en'):
70
+ """Filas de familias EN para el scope: número, título y nota del estándar
71
+ en el idioma pedido. El ESTADO lo decide el llamador (a11yscope): aquí
72
+ solo vive el texto, no la aplicabilidad."""
73
+ from .a11yi18n import pack
74
+ tx = pack(lang).get('scope', {}).get('families', {}) or {}
75
+ rows = []
76
+ for fam in FAMILIES:
77
+ entry = tx.get(fam['key'], {}) or {}
78
+ row = {'family': fam['family'],
79
+ 'title': entry.get('title') or fam['key']}
80
+ if entry.get('note'):
81
+ row['note'] = entry['note']
82
+ rows.append(row)
83
+ return rows
84
+
85
+
86
+ def standard_block(target='web', lang='en'):
87
+ """Bloque 'standard' para informes audit --standard en301549."""
88
+ from .a11yi18n import pack
89
+ tx = pack(lang).get('scope', {}) or {}
90
+ return {
91
+ 'name': STANDARD_NAME,
92
+ 'target': target,
93
+ 'clause_prefix': _CLAUSE_PREFIX[target],
94
+ 'mapping_note': tx.get('mapping_note'),
95
+ }
@@ -43,19 +43,53 @@ MANUAL_AA = [
43
43
  ]
44
44
 
45
45
  _STATES = ('automated-fail', 'automated-review', 'not-flagged', 'manual-only',
46
- 'agent-verified', 'not-run')
46
+ 'agent-verified', 'not-run', 'not-applicable')
47
47
 
48
48
 
49
49
  def _canon(obj):
50
50
  return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
51
51
 
52
52
 
53
+ def apply_scope(pack, scope, lang='en'):
54
+ """Aplica un a11y-scope/1 a un pack YA construido (VPAT/OpenACR con
55
+ pack + scope): las exclusiones CONFIRMADAS por humano pasan sus filas a
56
+ not-applicable con su razón. Las propuestas jamás. Devuelve una copia —
57
+ el sha256 del pack original queda intacto (el sello sella el pack; el
58
+ scope viaja aparte con su propio sello)."""
59
+ from . import a11yi18n
60
+ tx = a11yi18n.pack(lang).get('evidence', {})
61
+ note_base = tx.get('not_applicable_note') or a11yi18n.pack('en')['evidence']['not_applicable_note']
62
+ excluded = {}
63
+ rows = scope.get('criteria') if isinstance(scope.get('criteria'), list) else []
64
+ for row in rows:
65
+ if not isinstance(row, dict) or row.get('status') != 'excluded':
66
+ continue
67
+ crit = row.get('criterion')
68
+ if not isinstance(crit, str) or not crit:
69
+ continue
70
+ reason = row.get('reason')
71
+ excluded[crit.split(' ')[0]] = reason if isinstance(reason, str) else ''
72
+ out = dict(pack)
73
+ criteria = []
74
+ for row in pack.get('criteria', []):
75
+ code = (row.get('criterion') or '').split(' ')[0] if isinstance(row, dict) else ''
76
+ if code in excluded:
77
+ note = note_base + (f' {excluded[code]}' if excluded[code] else '')
78
+ row = {**row, 'status': 'not-applicable', 'note': note,
79
+ 'scope_reason': excluded[code] or None}
80
+ row.pop('effort', None) # fuera de alcance: cero trabajo humano
81
+ criteria.append(row)
82
+ out['criteria'] = criteria
83
+ out['summary'] = {e: sum(1 for m in criteria if m.get('status') == e) for e in _STATES}
84
+ return out
85
+
86
+
53
87
  def _sha256(obj):
54
88
  return hashlib.sha256(_canon(obj).encode('utf-8')).hexdigest()
55
89
 
56
90
 
57
91
  def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
58
- sr_transcript=None, lang='en'):
92
+ sr_transcript=None, lang='en', scope=None):
59
93
  """Informes (lista de dicts JSON) → paquete de evidencia verificable.
60
94
 
61
95
  verificados: lista de códigos de criterio ("1.4.1", "3.3.1"…) que un
@@ -63,7 +97,11 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
63
97
  (protocolo del checklist del skill). El criterio pasa a estado
64
98
  'agent-verified' — salvo que una señal automática diera fail, que
65
99
  permanece como fail (el fallo no se borra verificando). La fuente
66
- (agente/humano, fecha) queda registrada en el bloque verificacion."""
100
+ (agente/humano, fecha) queda registrada en el bloque verificacion.
101
+
102
+ alcance (a11y_scope): las exclusiones CONFIRMADAS por una persona pasan
103
+ a 'not-applicable' con su razón; las propuestas de la máquina jamás
104
+ excluyen (a11y-scope/1 las marca 'proposed-excluded' y aquí no entran)."""
67
105
  now = datetime.now(timezone.utc).isoformat(timespec='seconds')
68
106
  from . import a11yi18n
69
107
  tx = a11yi18n.pack(lang).get('evidence', {})
@@ -94,6 +132,24 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
94
132
  touched[code] = state
95
133
 
96
134
  verified = {v.split(' ')[0] for v in (verified or [])}
135
+
136
+ # exclusiones confirmadas por humano (a11y-scope/1): código → razón.
137
+ # Solo status 'excluded' — una 'proposed-excluded' NO descuenta aquí.
138
+ # Filas malformadas (scope editado a mano, JSON hostil) se saltan, como
139
+ # los hallazgos malformados: la entrada sucia jamás tira el pack.
140
+ excluded = {}
141
+ if scope is not None and not isinstance(scope, dict):
142
+ raise ValueError('scope must be an object (a11y-scope/1 JSON)')
143
+ if isinstance(scope, dict) and scope.get('format') == 'a11y-scope/1':
144
+ rows = scope.get('criteria')
145
+ for row in rows if isinstance(rows, list) else []:
146
+ if not isinstance(row, dict) or row.get('status') != 'excluded':
147
+ continue
148
+ crit = row.get('criterion')
149
+ if not isinstance(crit, str) or not crit:
150
+ continue
151
+ reason = row.get('reason')
152
+ excluded[crit.split(' ')[0]] = reason if isinstance(reason, str) else ''
97
153
  # extraer valores medidos clave de los hallazgos (ratio, ejemplos)
98
154
  values = {}
99
155
  for inf in reports:
@@ -122,6 +178,16 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
122
178
  matrix = []
123
179
  _manual_codes = {m.split(' ')[0] for m in MANUAL_AA}
124
180
  for code in codes_aa:
181
+ if code in excluded:
182
+ # aplicabilidad confirmada fuera de alcance por una persona: no
183
+ # queda trabajo humano ni estado de máquina — solo la razón
184
+ note = tx['not_applicable_note']
185
+ if excluded[code]:
186
+ note = f"{note} {excluded[code]}"
187
+ matrix.append({'criterion': f"{code} {(_CAT[code][1].get(language) or _CAT[code][1]['en'])[0]}",
188
+ 'status': 'not-applicable', 'note': note,
189
+ 'scope_reason': excluded[code] or None})
190
+ continue
125
191
  if code in _manual_codes:
126
192
  continue # covered by the manual-only rows appended below
127
193
  state = touched.get(code, 'not-flagged')
@@ -155,7 +221,9 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
155
221
  if code in values:
156
222
  entry['value'] = values[code]
157
223
  matrix.append(entry)
158
- manual_remaining = [m for m in MANUAL_AA if m.split(' ')[0] not in verified]
224
+ manual_remaining = [m for m in MANUAL_AA
225
+ if m.split(' ')[0] not in verified
226
+ and m.split(' ')[0] not in excluded]
159
227
  # los not-run son adicionalmente "pendientes" (la máquina no miró)
160
228
  for name in manual_remaining:
161
229
  code = name.split(' ')[0]
@@ -170,6 +238,11 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
170
238
  'why': ef['why']}
171
239
  matrix.append(row)
172
240
  for code in sorted(verified):
241
+ # una exclusión confirmada gana a una verificación previa: el
242
+ # criterio fuera de alcance no puede reaparecer como verificado
243
+ # (fila doble, niveles contradictorios en VPAT/OpenACR)
244
+ if code in excluded:
245
+ continue
173
246
  if any(code in m for m in MANUAL_AA) and not any(m.startswith(code) for m in manual_remaining):
174
247
  row = {'criterion': f"{code} {(_CAT[code][1].get(language) or _CAT[code][1]['en'])[0]}",
175
248
  'status': 'agent-verified',
@@ -220,6 +293,27 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
220
293
  artifacts.append({'type': 'sr_transcript', 'url': sr_transcript.get('url'),
221
294
  'sha256': _sha256(sr_transcript), 'announcements': sr_transcript.get('total', 0),
222
295
  'linearized': sr_transcript.get('announcements', [])[:50]})
296
+ scope_block = None
297
+ if isinstance(scope, dict) and scope.get('format') == 'a11y-scope/1':
298
+ artifacts.append({'type': 'scope:a11y', 'sha256': _sha256(scope),
299
+ 'standard': scope.get('standard'), 'target': scope.get('target'),
300
+ 'body': scope}) # embedded: pack self-verifying
301
+ cnt = scope.get('counters', {})
302
+ scope_block = {
303
+ 'format': 'a11y-scope/1',
304
+ 'standard': scope.get('standard'),
305
+ 'target': scope.get('target'),
306
+ 'in_scope': cnt.get('in_scope'),
307
+ 'proposed_excluded': cnt.get('proposed_excluded'),
308
+ 'excluded': cnt.get('excluded'),
309
+ # lo que aguas abajo (VPAT/OpenACR) puede tratar como N/A:
310
+ # SOLO exclusiones humanas, con su razón
311
+ 'not_applicable': {r['criterion'].split(' ')[0]: r.get('reason')
312
+ for r in (scope.get('criteria') if isinstance(scope.get('criteria'), list) else [])
313
+ if isinstance(r, dict) and r.get('status') == 'excluded'
314
+ and isinstance(r.get('criterion'), str) and r.get('criterion')},
315
+ 'sha256': scope.get('sha256'),
316
+ }
223
317
 
224
318
  pack = {
225
319
  'format': 'a11y-evidence-pack/2',
@@ -228,6 +322,7 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
228
322
  'tool': 'a11y-toolkit (github.com/kinti/a11y-toolkit)',
229
323
  'summary': summary,
230
324
  'effort_pending': pending_effort,
325
+ 'scope': scope_block,
231
326
  'criteria': matrix,
232
327
  'manual_pending': [m['criterion'] for m in matrix if m['status'] == 'manual-only'],
233
328
  'verification': ({'source': 'agent', 'protocol': 'skill manual checklist'}
@@ -254,13 +349,16 @@ def main(argv):
254
349
  ap = argparse.ArgumentParser(description='Evidence pack (verifiable handoff)')
255
350
  ap.add_argument('reports', nargs='+', help='audit report JSON files (any mode)')
256
351
  ap.add_argument('--snapshot', help='a11y snapshot JSON (optional)')
352
+ ap.add_argument('--scope', help='a11y_scope output JSON: confirmed exclusions '
353
+ 'become not-applicable rows (proposals never exclude)')
257
354
  ap.add_argument('--reviewer', help='JSON: {"name":…, "credential":…, "review_date":…}')
258
355
  ap.add_argument('-o', '--out', default='evidence-pack.json')
259
356
  a = ap.parse_args(argv)
260
357
  reports = [json.load(open(f, encoding='utf-8')) for f in a.reports]
261
358
  snapshot = json.load(open(a.snapshot, encoding='utf-8')) if a.snapshot else None
359
+ scope = json.load(open(a.scope, encoding='utf-8')) if a.scope else None
262
360
  reviewer = json.loads(a.reviewer) if a.reviewer else None
263
- pack = build_pack(reports, snapshot=snapshot, reviewer=reviewer)
361
+ pack = build_pack(reports, snapshot=snapshot, reviewer=reviewer, scope=scope)
264
362
  with open(a.out, 'w', encoding='utf-8') as f:
265
363
  json.dump(pack, f, ensure_ascii=False, indent=1)
266
364
  print(json.dumps({'pack': a.out, 'sha256': pack['sha256'],
@@ -306,6 +306,32 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
306
306
  return {'fixed_html': fixed, 'applied': applied, 'not_applied': not_applied}
307
307
 
308
308
 
309
+ def _star_nudge_once():
310
+ """Thank the operator once per machine after a real fix lands — never in
311
+ CI, never blocking, silence with A11Y_NO_STAR_NUDGE=1. The marker lives in
312
+ the system temp dir (never the user's home: the filesystem-boundary pin in
313
+ test_solido applies), so a cleaned tmp dir may show it again — that is the
314
+ honest maximum without telemetry."""
315
+ import os
316
+ if os.environ.get('A11Y_NO_STAR_NUDGE'):
317
+ return
318
+ if any(os.environ.get(k) for k in ('CI', 'GITHUB_ACTIONS', 'GITLAB_CI',
319
+ 'CONTINUOUS_INTEGRATION', 'TF_BUILD')):
320
+ return
321
+ import tempfile
322
+ marker = os.path.join(tempfile.gettempdir(), 'a11y-toolkit-star-nudge')
323
+ try:
324
+ if os.path.exists(marker):
325
+ return
326
+ with open(marker, 'w', encoding='utf-8') as fh:
327
+ fh.write('thanked\n')
328
+ except OSError:
329
+ return
330
+ print('If a11y-toolkit saved you time, a star helps other auditors find '
331
+ 'it: github.com/kinti/a11y-toolkit (shown once; '
332
+ 'A11Y_NO_STAR_NUDGE=1 silences)', file=sys.stderr)
333
+
334
+
309
335
  def main(argv):
310
336
  ap = argparse.ArgumentParser(description=__doc__)
311
337
  ap.add_argument('--file', required=True)
@@ -321,6 +347,9 @@ def main(argv):
321
347
  f.write(res['fixed_html'])
322
348
  print(json.dumps({'file': a.out, 'applied': res['applied'],
323
349
  'not_applied': res['not_applied']}, ensure_ascii=False, indent=1))
350
+ # human-facing thank-you goes to stderr AFTER the JSON: piped stdout
351
+ # stays machine-parseable, and only a real fix (a file written) asks
352
+ _star_nudge_once()
324
353
  else:
325
354
  print(res['fixed_html'])
326
355
  return 0
@@ -77,18 +77,29 @@ def _remarks(row, finding, pack_sha):
77
77
  def generate_openacr(pack=None, reports=None, product='', product_version=None,
78
78
  report_date=None, description=None, author=None, contact=None,
79
79
  methods=None, notes=None, overrides=None, lang='en',
80
- output_path=None):
80
+ scope=None, output_path=None):
81
81
  """Pack (o informes) → OpenACR YAML (GSA) + resumen.
82
82
 
83
83
  overrides: {'1.1.1': 'supports', …} — niveles fijados por una persona
84
84
  cualificada; se aceptan además las formas con guion del propio formato
85
- ('partially-supports'). Ganan sobre la derivación automática."""
85
+ ('partially-supports'). Ganan sobre la derivación automática (scope
86
+ incluido: una exclusión confirmada puede revertirse a mano).
87
+
88
+ scope: salida de a11y_scope — las exclusiones CONFIRMADAS por humano
89
+ salen como not-applicable con su razón; las propuestas nunca."""
86
90
  t = _t(lang)
87
91
  if pack is None:
88
92
  if not reports:
89
93
  return {'error': t['error_no_pack']}
90
94
  from .a11yevidence import build_pack
91
- pack = build_pack(reports)
95
+ pack = build_pack(reports, scope=scope)
96
+ elif scope is not None:
97
+ # pack ya construido + scope: aplicar las exclusiones confirmadas
98
+ # (jamás silencio — el CLI lo promete)
99
+ if not isinstance(scope, dict):
100
+ return {'error': t['error_scope']}
101
+ from .a11yevidence import apply_scope
102
+ pack = apply_scope(pack, scope, lang=lang)
92
103
  if not isinstance(pack, dict) or 'criteria' not in pack:
93
104
  return {'error': t['error_no_pack']}
94
105
  overrides = {k: str(v).replace('-', '_') for k, v in (overrides or {}).items()}
@@ -182,18 +193,21 @@ def main(argv):
182
193
  ap.add_argument('--methods', help='evaluation methods used')
183
194
  ap.add_argument('--notes', help='additional notes')
184
195
  ap.add_argument('--overrides', help='JSON: {"1.1.1": "supports", …}')
196
+ ap.add_argument('--scope', help='a11y_scope output JSON: confirmed exclusions '
197
+ 'become not-applicable (proposals never)')
185
198
  ap.add_argument('--lang', default='en', choices=['en', 'es'])
186
199
  ap.add_argument('-o', '--out')
187
200
  a = ap.parse_args(argv)
188
201
  pack = json.load(open(a.pack, encoding='utf-8')) if a.pack else None
189
202
  reports = [json.load(open(f, encoding='utf-8')) for f in a.reports] if a.reports else None
203
+ scope = json.load(open(a.scope, encoding='utf-8')) if a.scope else None
190
204
  res = generate_openacr(pack=pack, reports=reports, product=a.product,
191
205
  product_version=a.product_version, report_date=a.report_date,
192
206
  description=a.description,
193
207
  author=json.loads(a.author) if a.author else None,
194
208
  contact=a.contact, methods=a.methods, notes=a.notes,
195
209
  overrides=json.loads(a.overrides) if a.overrides else None,
196
- lang=a.lang, output_path=a.out)
210
+ scope=scope, lang=a.lang, output_path=a.out)
197
211
  if 'error' in res:
198
212
  print(res['error'])
199
213
  return 1