@kinti/a11y-toolkit 5.34.0 → 5.35.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.
@@ -37,7 +37,7 @@
37
37
  a11ytoolkit wizard --url https://client.web --lang es # guided: standard, audit, scope, annex
38
38
  a11ytoolkit mutants --seed 7 --n 12 # the engine's sealed self-exam
39
39
  a11ytoolkit corpus build && a11ytoolkit corpus verify # versioned audit corpus (dataset + baselines)
40
- a11ytoolkit fingerprints page1.html page2.html --dir p/ # twin-page detection (one audit per template)
40
+ a11ytoolkit fingerprints page1.html page2.html --dir p/ # suggest a structural sample
41
41
  a11ytoolkit audit --url https://web --standard en301549 # EN 301 549 clause on every finding
42
42
  a11ytoolkit scope audit.json -o scope.json --standard en301549 # applicability: machine proposes, human confirms
43
43
  a11ytoolkit annotate page.html --report r.json -o copy.html # per-element marks on a copy
@@ -22,7 +22,7 @@ import os
22
22
  import re
23
23
  import sys
24
24
  import urllib.request
25
- from urllib.parse import unquote
25
+ from urllib.parse import unquote, urlsplit
26
26
  from html.parser import HTMLParser
27
27
  from . import a11yi18n
28
28
 
@@ -461,6 +461,17 @@ _IMPLICIT_PARENT = {'list': ('ul', 'ol'), 'menu': ('menu',)}
461
461
  # contexto (un treeitem carpeta agrupa sus hijos en un group)
462
462
  _OWN_GROUP_ROLE = {'treeitem'}
463
463
  _IMPLICIT_CONTEXT = {tag: role for role, tags in _IMPLICIT_PARENT.items() for tag in tags}
464
+ _HTML_UNSIGNED_INTEGER = re.compile(r'[\t\n\f\r ]*\+?([0-9]+)')
465
+
466
+
467
+ def _implicit_context(tag, attrs):
468
+ if tag == 'select':
469
+ if 'multiple' in attrs:
470
+ return 'listbox'
471
+ size = _HTML_UNSIGNED_INTEGER.match(attrs.get('size') or '')
472
+ if size and size.group(1).lstrip('0') not in ('', '1'):
473
+ return 'listbox'
474
+ return _IMPLICIT_CONTEXT.get(tag)
464
475
 
465
476
 
466
477
  class _RoleContext:
@@ -871,9 +882,9 @@ class _Auditor(HTMLParser):
871
882
  if not _hidden and tag != 'template':
872
883
  if role in _ROLE_PARENTS:
873
884
  self._role_ctx_pending.append((a, role, parent_context))
874
- if role or tag in _IMPLICIT_CONTEXT or a.get('id') or a.get('aria-owns'):
875
- context = _RoleContext(role or _IMPLICIT_CONTEXT.get(tag),
876
- a.get('id'), parent_context)
885
+ effective_role = role or _implicit_context(tag, a)
886
+ if effective_role or a.get('id') or a.get('aria-owns'):
887
+ context = _RoleContext(effective_role, a.get('id'), parent_context)
877
888
  for owned_id in (a.get('aria-owns') or '').split():
878
889
  if owned_id != context.element_id:
879
890
  self._owned_by.setdefault(owned_id, context)
@@ -1954,6 +1965,53 @@ def normalize_report(report):
1954
1965
  return out
1955
1966
 
1956
1967
 
1968
+ def page_identity(url):
1969
+ """Ignore fragments and normalize the origin and empty root path."""
1970
+ if not isinstance(url, str) or not url:
1971
+ return None
1972
+ try:
1973
+ parts = urlsplit(url)
1974
+ if parts.scheme not in ('http', 'https') or not parts.hostname:
1975
+ return url
1976
+ port = parts.port
1977
+ except ValueError:
1978
+ return url
1979
+ if port is None:
1980
+ port = 443 if parts.scheme == 'https' else 80
1981
+ return (parts.scheme, parts.hostname, port, parts.path or '/', parts.query)
1982
+
1983
+
1984
+ def audit_conditions(report):
1985
+ """Identify recorded capture conditions that affect comparability."""
1986
+ if report.get('mode') == 'rendered':
1987
+ return {'color_scheme': report.get('color_scheme') or report.get('scheme')}
1988
+ return {}
1989
+
1990
+
1991
+ def completed_report_pages(report):
1992
+ """Return measured pages or the reason they cannot support a comparison."""
1993
+ if not isinstance(report, dict) or report.get('error'):
1994
+ return [], {'error': 'the audit failed or was not a report'}
1995
+ pages = report.get('reports', [report])
1996
+ if not isinstance(pages, list) or not pages:
1997
+ return [], {'error': 'the audit contains no page reports'}
1998
+ failures = report.get('page_errors', [])
1999
+ if not isinstance(failures, list) or any(not isinstance(page, dict) for page in failures):
2000
+ return [], {'error': 'the audit contains invalid page errors'}
2001
+ failures = failures[:]
2002
+ for page in pages:
2003
+ if not isinstance(page, dict):
2004
+ return [], {'error': 'the audit contains an invalid page report'}
2005
+ status = page.get('http_status')
2006
+ if (page.get('error') or not isinstance(page.get('findings'), list)
2007
+ or status is not None and (type(status) is not int or not 200 <= status < 400)):
2008
+ failures.append(page)
2009
+ if failures or report.get('budget_exhausted'):
2010
+ return [], {'error': 'the audit did not complete; compare after all pages are measured',
2011
+ 'pages_failed': [page.get('url') for page in failures]}
2012
+ return pages, None
2013
+
2014
+
1957
2015
  def compute_score(findings):
1958
2016
  """Puntuación 0-100: penalización ponderada por hallazgo (alta 12, media 6, baja 2)."""
1959
2017
  weights = {'high': 12, 'medium': 6, 'low': 2}
@@ -2014,9 +2072,11 @@ def _not_measured(lang='en'):
2014
2072
 
2015
2073
  def audit_html(html_text, url='(html)', lang='en', standard=None, target=None):
2016
2074
  """Analiza una cadena HTML y devuelve el informe de hallazgos (es/en)."""
2075
+ if isinstance(html_text, str) and len(html_text) > MAX_HTML:
2076
+ return {'url': url, 'error': _t(lang, 'err_too_big').format(mb=MAX_HTML // 1000000)}
2017
2077
  p = _Auditor()
2018
2078
  try:
2019
- p.feed(html_text[:MAX_HTML])
2079
+ p.feed(html_text)
2020
2080
  p.close()
2021
2081
  except Exception as e: # noqa: BLE001
2022
2082
  # un atributo hostil NO puede tirar la auditoría de 3 MB de página
@@ -2857,7 +2917,7 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=(), _meta=None):
2857
2917
  ceiling = truncate_at or MAX_HTML
2858
2918
  # TOTAL-CLOCK reading: the socket timeout is per-operation and a server
2859
2919
  # dribbling one byte per operation reset it forever. Read in chunks
2860
- # with a global deadline: what arrived is enough to audit (partial).
2920
+ # with a global deadline. A full audit requires a complete response.
2861
2921
  import time
2862
2922
  read_deadline = time.monotonic() + max(timeout, 5)
2863
2923
  try:
@@ -2867,19 +2927,30 @@ def _fetch(url, timeout=30, truncate_at=None, accept_ct=(), _meta=None):
2867
2927
  data = b''
2868
2928
  while len(data) < ceiling + 1:
2869
2929
  if time.monotonic() >= read_deadline:
2870
- break # partial: what arrived suffices to audit
2930
+ if truncate_at is None:
2931
+ raise _FetchError('err_incomplete_html')
2932
+ break
2871
2933
  chunk = r.read(min(65536, ceiling + 1 - len(data)))
2872
2934
  if not chunk:
2873
2935
  break
2874
2936
  data += chunk
2875
- if len(data) > ceiling and truncate_at is None:
2876
- raise _FetchError('err_too_big', mb=MAX_HTML // 1000000)
2937
+ if truncate_at is None:
2938
+ if len(data) > ceiling:
2939
+ raise _FetchError('err_too_big', mb=MAX_HTML // 1000000)
2940
+ if getattr(r, 'length', 0):
2941
+ raise _FetchError('err_incomplete_html')
2877
2942
  if (r.headers.get('Content-Encoding') or '').lower() == 'gzip' or data[:2] == b'\x1f\x8b':
2878
- import zlib
2879
- d = zlib.decompressobj(16 + zlib.MAX_WBITS)
2880
- data = d.decompress(data, ceiling) # techo duro también al descomprimir
2881
- if d.unconsumed_tail:
2882
- data = data[:ceiling] # bomba gzip: truncado, no OOM
2943
+ import gzip
2944
+ from io import BytesIO
2945
+ try:
2946
+ with gzip.GzipFile(fileobj=BytesIO(data)) as stream:
2947
+ data = stream.read(ceiling + 1)
2948
+ except EOFError as err:
2949
+ raise _FetchError('err_incomplete_html') from err
2950
+ if truncate_at is None and len(data) > ceiling:
2951
+ raise _FetchError('err_too_big', mb=MAX_HTML // 1000000)
2952
+ if truncate_at is not None:
2953
+ data = data[:ceiling]
2883
2954
  ctype = (r.headers.get('Content-Type') or '').lower()
2884
2955
  base = ctype.split(';')[0].strip()
2885
2956
  extra_ok = any(base == p or base.startswith(p + '/') for p in accept_ct)
@@ -3077,7 +3148,7 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
3077
3148
  def _parse_page(html_txt, page_url):
3078
3149
  pg = _Auditor()
3079
3150
  try:
3080
- pg.feed(html_txt[:MAX_HTML])
3151
+ pg.feed(html_txt)
3081
3152
  pg.close()
3082
3153
  except Exception as e: # noqa: BLE001
3083
3154
  return pg, {'url': page_url, 'error': _t(lang, 'err_unparseable').format(e=str(e)[:120])}
@@ -3085,7 +3156,10 @@ def audit_site(url, max_pages=5, timeout=30, lang='en', from_sitemap=True,
3085
3156
  p0, p0_err = _parse_page(html_text, entry_final)
3086
3157
  if p0_err:
3087
3158
  return p0_err
3088
- reports = [audit_html(html_text, entry_final, lang=lang)]
3159
+ initial = audit_html(html_text, entry_final, lang=lang)
3160
+ if initial.get('error'):
3161
+ return dict(initial, url=entry_final)
3162
+ reports = [initial]
3089
3163
  parsers = [p0]
3090
3164
  page_errors = []
3091
3165
  budget_exhausted = False
@@ -3174,21 +3248,24 @@ def audit_changed(base='HEAD', lang='en', cwd='.'):
3174
3248
  is no HTML to audit). Deleted files are skipped.
3175
3249
  """
3176
3250
  import subprocess
3177
- spec = ['git', 'diff', '--name-only', '--diff-filter=d',
3251
+ spec = ['git', 'diff', '--name-only', '-z', '--diff-filter=d',
3178
3252
  base if base == 'HEAD' else f'{base}...HEAD']
3179
3253
  try:
3180
- out = subprocess.run(spec, cwd=cwd, capture_output=True, text=True, timeout=30)
3254
+ out = subprocess.run(spec, cwd=cwd, capture_output=True, timeout=30)
3181
3255
  except FileNotFoundError:
3182
3256
  return {'error': 'git not available'}
3183
3257
  if out.returncode != 0:
3184
- return {'error': f'git diff failed: {out.stderr.strip()[:200]}'}
3185
- changed = [f for f in out.stdout.splitlines() if f.strip()]
3258
+ detail = os.fsdecode(out.stderr).strip()[:200]
3259
+ return {'error': f'git diff failed: {detail}'}
3186
3260
  # los NUEVOS sin trackear no salen en git diff — entran también:
3187
3261
  # una página recién creada no puede escaparse del gate local
3188
- untracked = subprocess.run(['git', 'ls-files', '--others', '--exclude-standard'],
3189
- cwd=cwd, capture_output=True, text=True, timeout=30)
3190
- if untracked.returncode == 0:
3191
- changed += [f for f in untracked.stdout.splitlines() if f.strip() and f not in changed]
3262
+ untracked = subprocess.run(['git', 'ls-files', '-z', '--others', '--exclude-standard'],
3263
+ cwd=cwd, capture_output=True, timeout=30)
3264
+ if untracked.returncode != 0:
3265
+ detail = os.fsdecode(untracked.stderr).strip()[:200]
3266
+ return {'error': f'git ls-files failed: {detail}'}
3267
+ changed = [os.fsdecode(path) for path in dict.fromkeys((out.stdout + untracked.stdout).split(b'\0'))
3268
+ if path]
3192
3269
  auditables, web_touched = [], []
3193
3270
  for f in changed:
3194
3271
  ext = os.path.splitext(f)[1].lower()
@@ -3203,7 +3280,10 @@ def audit_changed(base='HEAD', lang='en', cwd='.'):
3203
3280
  if not os.path.exists(filepath):
3204
3281
  continue # renombrado/eliminado entre el diff y ahora
3205
3282
  with open(filepath, encoding='utf-8', errors='replace') as fh:
3206
- reports.append(audit_html(fh.read(), f, lang=lang))
3283
+ report = audit_html(fh.read(MAX_HTML + 1), f, lang=lang)
3284
+ if report.get('error'):
3285
+ return report
3286
+ reports.append(report)
3207
3287
 
3208
3288
  findings = [h for r in reports for h in r.get('findings', [])]
3209
3289
  scores = [r['score'] for r in reports if r.get('score') is not None]
@@ -3297,7 +3377,7 @@ def main(argv):
3297
3377
  return 1
3298
3378
  else:
3299
3379
  with open(a.file, encoding='utf-8', errors='replace') as f:
3300
- res = audit_html(f.read(), a.file, lang=a.lang,
3380
+ res = audit_html(f.read(MAX_HTML + 1), a.file, lang=a.lang,
3301
3381
  standard=a.standard, target=a.target)
3302
3382
  # site/changed no pasan por audit_html: enriquecer post-hoc para que
3303
3383
  # --standard nunca se descarte en silencio en NINGUNA ruta del CLI
@@ -44,7 +44,7 @@ import datetime
44
44
  import json
45
45
  from collections import Counter
46
46
 
47
- from .a11yaudit import normalize_signal # noqa: E402 (compat 5.10)
47
+ from .a11yaudit import audit_conditions, completed_report_pages, normalize_signal
48
48
  import sys
49
49
 
50
50
  # mensajes CLI bilingües (patrón _labels): el stdin de --init espera el JSON
@@ -65,26 +65,12 @@ _CLI_MSG = {
65
65
  BUDGET_FORMAT = 'a11y-budget/2'
66
66
 
67
67
 
68
- def _report_pages(audit):
69
- """Return usable pages, or an error if the measurement was incomplete."""
70
- if not isinstance(audit, dict) or audit.get('error'):
71
- return [], {'error': 'the audit failed or was not a report'}
72
- pages = audit.get('reports', [audit])
73
- if not isinstance(pages, list) or not pages:
74
- return [], {'error': 'the audit contains no page reports'}
75
- failures = audit.get('page_errors', [])
76
- if not isinstance(failures, list) or any(not isinstance(page, dict) for page in failures):
77
- return [], {'error': 'the audit contains invalid page errors'}
78
- failures = failures[:]
79
- for page in pages:
80
- if not isinstance(page, dict):
81
- return [], {'error': 'the audit contains an invalid page report'}
82
- if page.get('error') or not isinstance(page.get('findings'), list):
83
- failures.append(page)
84
- if failures or audit.get('budget_exhausted'):
85
- return [], {'error': 'the audit did not complete; compare after all pages are measured',
86
- 'pages_failed': [page.get('url') for page in failures]}
87
- return pages, None
68
+ def _active_findings(page):
69
+ for finding in page['findings']:
70
+ if not isinstance(finding, dict):
71
+ raise ValueError('invalid finding')
72
+ if finding.get('status') != 'rejected' and finding.get('disprover_status') != 'rejected':
73
+ yield finding
88
74
 
89
75
 
90
76
  def _page_index(pages):
@@ -94,7 +80,7 @@ def _page_index(pages):
94
80
  if not isinstance(url, str) or not url or url in result:
95
81
  raise ValueError('every audited page must have a unique URL')
96
82
  findings = {}
97
- for finding in page['findings']:
83
+ for finding in _active_findings(page):
98
84
  signal = normalize_signal(finding['signal'])
99
85
  paths = [path for path in (finding.get('paths') or []) if isinstance(path, str)]
100
86
  count = finding.get('count')
@@ -102,13 +88,14 @@ def _page_index(pages):
102
88
  count = max(len(paths), len(finding.get('examples') or []), 1)
103
89
  findings[signal] = {'severity': finding['severity'], 'count': max(count, len(paths)),
104
90
  'paths': sorted(paths)}
105
- result[url] = {'mode': page.get('mode', 'static'), 'findings': findings}
91
+ result[url] = {'mode': page.get('mode', 'static'), 'conditions': audit_conditions(page),
92
+ 'findings': findings}
106
93
  return result
107
94
 
108
95
 
109
96
  def init(audit):
110
97
  """Build a page- and instance-scoped baseline from a complete audit."""
111
- pages, error = _report_pages(audit)
98
+ pages, error = completed_report_pages(audit)
112
99
  if error:
113
100
  return error
114
101
  try:
@@ -131,10 +118,21 @@ def _instance_delta(before, after):
131
118
  after_count = after['count'] if after else 0
132
119
  before_paths = (before or {}).get('paths', [])
133
120
  after_paths = (after or {}).get('paths', [])
134
- if len(before_paths) == before_count and len(after_paths) == after_count:
135
- old, new = Counter(before_paths), Counter(after_paths)
136
- return sum((new - old).values()), sum((old - new).values()), 'paths'
137
- return max(0, after_count - before_count), max(0, before_count - after_count), 'count'
121
+ old, new = Counter(before_paths), Counter(after_paths)
122
+ before_missing = max(0, before_count - len(before_paths))
123
+ after_missing = max(0, after_count - len(after_paths))
124
+ added_paths = sum((new - old).values())
125
+ removed_paths = sum((old - new).values())
126
+ if not before_missing and not after_missing:
127
+ return added_paths, removed_paths, 'paths'
128
+ # A path observed on one side could be among the hidden paths on the other.
129
+ # Any excess over those hidden slots is still a demonstrated change.
130
+ added_by_count = max(0, after_count - before_count)
131
+ removed_by_count = max(0, before_count - after_count)
132
+ added = max(added_by_count, added_paths - before_missing)
133
+ removed = max(removed_by_count, removed_paths - after_missing)
134
+ basis = 'partial-paths' if (added, removed) != (added_by_count, removed_by_count) else 'count'
135
+ return added, removed, basis
138
136
 
139
137
 
140
138
  def _compare_instances(budget, pages, blocking):
@@ -147,6 +145,9 @@ def _compare_instances(budget, pages, blocking):
147
145
  prior = base.get(url)
148
146
  if prior and prior['mode'] != page['mode']:
149
147
  return {'error': 'the audit mode changed for a baseline page', 'url': url}
148
+ if prior and prior.get('conditions', {}) != page['conditions']:
149
+ return {'error': 'the capture conditions changed or were not recorded in the baseline',
150
+ 'url': url}
150
151
  old = prior['findings'] if prior else {}
151
152
  current = page['findings']
152
153
  for signal in sorted(set(old) | set(current)):
@@ -173,7 +174,7 @@ def _compare_signals(budget, pages, blocking):
173
174
  base = {normalize_signal(s) for s in budget.get('signals', [])}
174
175
  current = {}
175
176
  for pg in pages:
176
- for h in pg.get('findings', []):
177
+ for h in _active_findings(pg):
177
178
  current.setdefault(normalize_signal(h.get('signal', '')), []).append(h['severity'])
178
179
  new = sorted(s for s in current if s not in base)
179
180
  resolved = sorted(base - set(current))
@@ -185,7 +186,7 @@ def _compare_signals(budget, pages, blocking):
185
186
 
186
187
  def compare(budget, audit, today=None):
187
188
  """Compare a complete run against the active baseline."""
188
- pages, error = _report_pages(audit)
189
+ pages, error = completed_report_pages(audit)
189
190
  if error:
190
191
  return error
191
192
  if not isinstance(budget, dict) or budget.get('format') not in (None, BUDGET_FORMAT):
@@ -193,6 +194,7 @@ def compare(budget, audit, today=None):
193
194
  try:
194
195
  blocking = set(budget.get('blocking', ['high', 'medium']))
195
196
  max_new = int(budget.get('max_new', 0))
197
+ signals = {normalize_signal(h['signal']) for pg in pages for h in _active_findings(pg)}
196
198
  if budget.get('format') == BUDGET_FORMAT:
197
199
  verdict = _compare_instances(budget, _page_index(pages), blocking)
198
200
  else:
@@ -212,7 +214,7 @@ def compare(budget, audit, today=None):
212
214
  **verdict,
213
215
  'summary': {
214
216
  'baseline': len(set(budget.get('signals', []))),
215
- 'current': len({normalize_signal(h['signal']) for pg in pages for h in pg['findings']}),
217
+ 'current': len(signals),
216
218
  'new': len(verdict['new']),
217
219
  'resolved': len(verdict['resolved']),
218
220
  },
@@ -748,11 +748,7 @@ _C = {
748
748
  _LEVEL = {'A': 'A', 'AA': 'AA', 'AAA': 'AAA'}
749
749
 
750
750
  # Human-effort class for every A/AA criterion — what the HUMAN still does after
751
- # the machine's best signal. Used for review-marketplace pricing interlocks
752
- # and emitted in the evidence pack matrix.
753
- # MIN (1-3 min): the agent verified with a measured signal; the human reads and confirms.
754
- # MED (5-10 min): the agent prepares context; the human verifies in the browser.
755
- # MAX (15-30 min): real interaction, real judgment, real tooling.
751
+ # The public evidence pack classifies the remaining review by effort.
756
752
  # A not-flagged on a partially-covered criterion never earns a lower class:
757
753
  # "the machine looked and found nothing" is weaker than a confirmation.
758
754
  _EFFORT = {
@@ -813,8 +809,6 @@ _EFFORT = {
813
809
  '4.1.3': ('MAX', 'fire each status message and listen for the announcement.'),
814
810
  }
815
811
 
816
- _EFFORT_MINUTES = {'MIN': (1, 3), 'MED': (5, 10), 'MAX': (15, 30)}
817
-
818
812
  # Criterios A/AA que SOLO el modo renderizado puede medir (a11y_audit_dom):
819
813
  # contraste computado, espaciado, tamaño de objetivo, foco, formularios vivos…
820
814
  # El informe estático los declara en `not_measured` — un 100 estático jamás
@@ -1110,11 +1104,11 @@ def criterion(code=None, lang='en', signal=None):
1110
1104
 
1111
1105
 
1112
1106
  def effort(code):
1113
- """Human-effort class for an A/AA criterion: {clase, porque, minutos} or None."""
1107
+ """Human review class and rationale for an A/AA criterion."""
1114
1108
  if code not in _EFFORT:
1115
1109
  return None
1116
1110
  grade, why = _EFFORT[code]
1117
- return {'class': grade, 'why': why, 'minutes': list(_EFFORT_MINUTES[grade])}
1111
+ return {'class': grade, 'why': why}
1118
1112
 
1119
1113
 
1120
1114
  def main(argv):
@@ -8,8 +8,8 @@ accessibility findings:
8
8
 
9
9
  1. Take an audit report
10
10
  2. For each finding, re-check the signal against the live page
11
- 3. Findings that reproduce → estado: confirmed
12
- 4. Findings that don't → estado: rejected + reject_reason
11
+ 3. Findings that reproduce → status: confirmed
12
+ 4. Findings that don't → status: rejected + reject_reason
13
13
 
14
14
  This catches:
15
15
  - False positives (the element changed, was fixed, or never existed)
@@ -24,100 +24,99 @@ CLI:
24
24
  import argparse
25
25
  import json
26
26
 
27
- from .a11yaudit import normalize_signal # noqa: E402 (compat 5.10)
28
27
  import sys
29
28
 
30
- from .a11yaudit import audit_url, audit_html
29
+ from .a11yaudit import audit_url, normalize_signal, page_identity
31
30
 
32
31
 
33
- def _recheck_static(url, findings, timeout=30, lang='en'):
34
- """Re-run the static audit and check which findings still fire."""
35
- fresh_report = audit_url(url, timeout=timeout, lang=lang)
36
- if 'error' in fresh_report:
37
- return findings, fresh_report['error']
38
- fresh_signals = {h['signal'] for h in fresh_report.get('findings', [])}
39
- verified = []
40
- for h in findings:
41
- if normalize_signal(h.get('signal', '')) in fresh_signals:
42
- h['status'] = 'confirmed'
43
- else:
44
- h['status'] = 'rejected'
45
- _rj = ('la señal {s!r} ya no dispara al re-auditar — la página '
46
- 'puede haber cambiado, o el hallazgo era un falso positivo'
47
- if lang == 'es' else
48
- "signal {s!r} no longer fires on re-audit — the page may "
49
- 'have changed, or the finding was a false positive')
50
- h['reject_reason'] = _rj.format(s=h.get('signal', '?'))
51
- verified.append(h)
52
- return verified, None
53
-
54
-
55
- def _recheck_rendered(url, findings, timeout=45, lang='en', color_scheme=None):
56
- """Re-run the rendered audit and check which findings still fire.
57
-
58
- Repite las CONDICIONES del informe original (revisión externa
59
- 2026-11-22): un informe auditado en dark mode reverificado en claro
60
- «rechazaba» contrast_fail reales — 88→100 con la página intacta. Sin la
61
- condición registrada, nada se rechaza: not-rechecked."""
62
- try:
32
+ def _recheck(url, expected_url, timeout, lang, color_scheme=None):
33
+ """Obtain a successful measurement of the same page."""
34
+ if color_scheme is None:
35
+ fresh = audit_url(url, timeout=timeout, lang=lang)
36
+ else:
63
37
  from .a11ydom import audit_dom_url
64
- except ImportError:
65
- return findings, "Playwright not installed"
66
- fresh_report = audit_dom_url(url, timeout=timeout, lang=lang,
67
- color_scheme=color_scheme or 'light')
68
- if 'error' in fresh_report:
69
- return findings, fresh_report['error']
70
- fresh_signals = {h['signal'] for h in fresh_report.get('findings', [])}
71
- verified = []
72
- for h in findings:
73
- if normalize_signal(h.get('signal', '')) in fresh_signals:
74
- h['status'] = 'confirmed'
38
+ fresh = audit_dom_url(url, timeout=timeout, lang=lang, color_scheme=color_scheme)
39
+ if 'error' in fresh:
40
+ return None, fresh['error']
41
+ if page_identity(fresh.get('url')) != page_identity(expected_url):
42
+ return None, ('La reauditoría terminó en una URL distinta de la del informe original.'
43
+ if lang == 'es' else
44
+ 'The re-audit ended at a different URL from the original report.')
45
+ return fresh, None
46
+
47
+
48
+ def _finding_key(finding):
49
+ return (normalize_signal(finding.get('signal', '')),
50
+ (finding.get('criterion') or '').split(' ', 1)[0])
51
+
52
+
53
+ def _location_evidence(finding):
54
+ paths = tuple(sorted(set(finding.get('paths') or [])))
55
+ if paths:
56
+ count = finding.get('count')
57
+ return paths, count == len(paths) if count is not None else len(paths) < 5
58
+ return (), False
59
+
60
+
61
+ def _classify_findings(previous, current, lang):
62
+ current = [dict(finding) for finding in current]
63
+ by_key = {}
64
+ for finding in current:
65
+ by_key.setdefault(_finding_key(finding), []).append(finding)
66
+ historical = []
67
+ rejected = ('El hallazgo anterior ya no aparece en la nueva auditoría de la página.'
68
+ if lang == 'es' else
69
+ 'The earlier finding no longer appears in the new audit of the page.')
70
+ for old in previous:
71
+ if old.get('status') == 'rejected' or old.get('disprover_status') == 'rejected':
72
+ continue
73
+ key = _finding_key(old)
74
+ candidates = by_key.get(key, [])
75
+ paths, complete = _location_evidence(old)
76
+ locations = [_location_evidence(row) for row in candidates]
77
+ if not candidates or (complete and all(known and not set(paths).intersection(new_paths)
78
+ for new_paths, known in locations)):
79
+ historical.append(dict(old, status='rejected', reject_reason=rejected))
80
+ elif len(candidates) == 1 and ((complete and locations[0] == (paths, True))
81
+ or (not paths and not locations[0][0]
82
+ and old.get('examples') == candidates[0].get('examples')
83
+ and old.get('count') == candidates[0].get('count'))):
84
+ candidates[0]['status'] = 'confirmed'
75
85
  else:
76
- h['status'] = 'rejected'
77
- _rj = ('la señal {s!r} ya no dispara en la re-auditoría renderizada '
78
- '— el elemento puede haber cambiado o arreglarse, o el primer '
79
- 'hallazgo era un falso positivo'
80
- if lang == 'es' else
81
- "signal {s!r} no longer fires in the rendered re-audit — the "
82
- 'element may have changed, been fixed, or the first finding '
83
- 'was a false positive')
84
- h['reject_reason'] = _rj.format(s=h.get('signal', '?'))
85
- verified.append(h)
86
- return verified, None
86
+ historical.append(dict(old, disprover_status='not-rechecked'))
87
+ return current, historical
87
88
 
88
89
 
89
90
  def disprove(url, report=None, timeout=30, lang='en'):
90
91
  """Audit a URL and disprove findings, or verify an existing report.
91
92
 
92
- Returns a report with each finding marked confirmed/rejected."""
93
+ Return the fresh measurement and the outcomes of prior findings."""
93
94
  if report is None:
94
95
  report = audit_url(url, timeout=timeout, lang=lang)
95
- if 'error' in report:
96
- return report
97
-
96
+ if report.get('error'):
97
+ return report
98
98
  mode_name = report.get('mode', 'static')
99
+ expected_url = report.get('url') or url
99
100
  findings = report.get('findings', [])
100
101
 
101
- if mode_name == 'site' and not findings:
102
+ if mode_name == 'site':
102
103
  # site reports nest findings INSIDE each page: re-checking them against
103
104
  # ONE url marked everything 'rejected' and scored 100 on unreviewed
104
105
  # evidence. Honest path: not-rechecked per page, with the pointer to
105
106
  # re-verify each page properly.
106
- every_finding = []
107
- for page in (report.get('reports') or []): # 'pages' es un CONTEO, no una lista
108
- for h in page.get('findings', []):
109
- every_finding.append(dict(h, disprover_status='not-rechecked',
110
- page=page.get('url', '')))
107
+ if not findings:
108
+ findings = [dict(h, page=page.get('url', '')) for page in report.get('reports', [])
109
+ for h in page.get('findings', [])]
111
110
  res = dict(report)
112
- res['findings'] = every_finding
111
+ res['findings'] = [dict(h, disprover_status='not-rechecked') for h in findings]
113
112
  res['disprover'] = {'executed': False,
114
113
  'reason': ('site mode: each finding belongs to a page; '
115
114
  're-verify with a11ydisprove --url <page> '
116
115
  '--file <that page report>')}
117
116
  return res
118
117
 
119
- if mode_name in ('static', 'site'):
120
- verified, err = _recheck_static(url, findings, timeout=timeout, lang=lang)
118
+ if mode_name == 'static':
119
+ fresh, err = _recheck(url, expected_url, timeout, lang)
121
120
  elif mode_name == 'rendered':
122
121
  # condición necesaria: el esquema de color bajo el que se auditó. Sin
123
122
  # él no se reverifica (rechazar un contrast_fail de dark mode tras
@@ -135,8 +134,7 @@ def disprove(url, report=None, timeout=30, lang='en'):
135
134
  'under light); re-audit with a11y_audit_dom and disprove '
136
135
  'THAT report')}
137
136
  return res
138
- verified, err = _recheck_rendered(url, findings, timeout=timeout, lang=lang,
139
- color_scheme=scheme)
137
+ fresh, err = _recheck(url, expected_url, timeout, lang, color_scheme=scheme)
140
138
  else:
141
139
  # no re-verifier for this mode: report not-rechecked, never a proxy
142
140
  # audit (a keyboard finding must not vanish just because the wrong
@@ -149,28 +147,21 @@ def disprove(url, report=None, timeout=30, lang='en'):
149
147
  return res
150
148
 
151
149
  if err:
152
- return {'error': f'disprove re-audit failed: {err}'}
150
+ return dict(report, error=err, disprover={'executed': False, 'reason': err})
153
151
 
154
- result = dict(report)
155
- result['findings'] = verified
152
+ current, historical = _classify_findings(findings, fresh['findings'], lang)
153
+ rejected = [h for h in historical if h.get('status') == 'rejected']
154
+ result = dict(fresh, findings=current + rejected, score_original=report.get('score'))
156
155
  result['disprover'] = {
157
156
  'executed': True,
158
- 'confirmed': sum(1 for h in verified if h.get('status') == 'confirmed'),
159
- 'rejected': sum(1 for h in verified if h.get('status') == 'rejected'),
160
- 'note': ('Each finding was re-checked against the live page. '
161
- 'Rejected findings include the reason they did not reproduce. '
162
- 'Confirmed findings survived a fresh verification pass.'),
163
- }
164
-
165
- # recalcular score sobre los confirmed
166
- from .a11yaudit import compute_score
167
- solo_confirmed = [h for h in verified if h.get('status') == 'confirmed']
168
- result['score_original'] = report.get('score')
169
- result['score'] = compute_score(solo_confirmed)
170
- result['summary'] = {
171
- 'high': sum(1 for h in solo_confirmed if h['severity'] == 'high'),
172
- 'medium': sum(1 for h in solo_confirmed if h['severity'] == 'medium'),
173
- 'low': sum(1 for h in solo_confirmed if h['severity'] == 'low'),
157
+ 'confirmed': sum(h.get('status') == 'confirmed' for h in current),
158
+ 'rejected': len(rejected),
159
+ 'previous_findings': historical,
160
+ 'note': ('La puntuación y la cobertura corresponden a la nueva auditoría. '
161
+ 'Se conservan los descartes y las coincidencias dudosas para su revisión.'
162
+ if lang == 'es' else
163
+ 'Score and coverage describe the fresh audit. Rejected findings '
164
+ 'and ambiguous historical matches are retained for review.'),
174
165
  }
175
166
  return result
176
167
 
@@ -29,7 +29,6 @@ import hashlib
29
29
  import json
30
30
 
31
31
  from .a11yaudit import normalize_report # noqa: E402 (compat 5.10)
32
- from .a11ycrit import _EFFORT_MINUTES # single source: a11ycrit prices the classes
33
32
  import sys
34
33
  from datetime import datetime, timezone
35
34
 
@@ -104,13 +103,10 @@ def apply_scope(pack, scope, lang='en'):
104
103
  criteria.append(row)
105
104
  out['criteria'] = criteria
106
105
  out['summary'] = {e: sum(1 for m in criteria if m.get('status') == e) for e in _STATES}
107
- # the scope changes what REMAINS to do: effort_pending and manual_pending
108
- # must describe the resulting matrix (excluded = zero pending human
109
- # effort), not the pre-scope pack — otherwise the human is overcharged
110
- # and criteria already not-applicable keep being named as pending
111
106
  out['effort_pending'] = _pending_effort(
112
107
  criteria, tx.get('manual_remaining')
113
- or a11yi18n.pack('en')['evidence']['manual_remaining'])
108
+ or a11yi18n.pack('en')['evidence']['manual_remaining'],
109
+ legacy=pack.get('format') == 'a11y-evidence-pack/2')
114
110
  out['manual_pending'] = [m['criterion'] for m in criteria
115
111
  if m.get('status') == 'manual-only']
116
112
  return out
@@ -120,31 +116,26 @@ def _sha256(obj):
120
116
  return hashlib.sha256(_canon(obj).encode('utf-8')).hexdigest()
121
117
 
122
118
 
123
- def _pending_effort(matrix, note):
124
- """Remaining human review, in minutes: MIN/MED/MAX per class summed over
125
- every row a human still has to touch (agent-verified excluded; rows out
126
- of applicability scope carry no effort). Shared by build_pack AND
127
- apply_scope — the priced scope must always describe the CURRENT matrix,
128
- never the pre-scope one."""
129
- pend = {}
130
- for m in matrix:
131
- if m.get('status') == 'agent-verified':
119
+ def _pending_effort(matrix, note, legacy=False):
120
+ """Count pending review by class. Preserve supplied durations for v2."""
121
+ groups = {}
122
+ for row in matrix:
123
+ if row.get('status') in ('agent-verified', 'not-applicable') or not row.get('effort'):
132
124
  continue
133
- ef = m.get('effort')
134
- if ef:
135
- lo, hi = _EFFORT_MINUTES[ef['class']]
136
- pend.setdefault(ef['class'], [0, 0])
137
- pend[ef['class']][0] += lo
138
- pend[ef['class']][1] += hi
139
- return {
140
- 'by_class': {k: {'criteria': sum(1 for m in matrix
141
- if m.get('status') != 'agent-verified'
142
- and m.get('effort', {}).get('class') == k),
143
- 'minutes': v}
144
- for k, v in sorted(pend.items())},
145
- 'total_minutes': [sum(v[0] for v in pend.values()), sum(v[1] for v in pend.values())],
146
- 'note': note,
147
- }
125
+ effort = row['effort']
126
+ bucket = groups.setdefault(effort['class'], {'criteria': 0})
127
+ bucket['criteria'] += 1
128
+ minutes = effort.get('minutes')
129
+ if legacy and isinstance(minutes, (list, tuple)) and len(minutes) == 2:
130
+ if all(type(value) in (int, float) for value in minutes):
131
+ totals = bucket.setdefault('minutes', [0, 0])
132
+ for index, value in enumerate(minutes):
133
+ totals[index] += value
134
+ result = {'by_class': dict(sorted(groups.items())), 'note': note}
135
+ if legacy:
136
+ result['total_minutes'] = [sum(group.get('minutes', [0, 0])[i] for group in groups.values())
137
+ for i in range(2)]
138
+ return result
148
139
 
149
140
 
150
141
  def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
@@ -205,10 +196,7 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
205
196
  touched = {}
206
197
  for inf in pages:
207
198
  for h in inf.get('findings', []):
208
- if (h.get('status') == 'rejected'
209
- or h.get('disprover_status') in ('rejected', 'not-rechecked')):
210
- # un hallazgo desmentido (o no reverificado) no puede volver a
211
- # convertirse en fallo dentro del pack
199
+ if h.get('status') == 'rejected' or h.get('disprover_status') == 'rejected':
212
200
  continue
213
201
  crit = h.get('criterion')
214
202
  if not crit or not isinstance(crit, str): # informe malformado: saltar
@@ -219,6 +207,7 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
219
207
  # afirmar un FALLO — el hallazgo queda como review (evidencia, no
220
208
  # veredicto). Solo un fail del motor es un automated-fail.
221
209
  state = ('automated-fail' if severity in ('high', 'medium')
210
+ and h.get('disprover_status') != 'not-rechecked'
222
211
  else 'automated-review')
223
212
  # el peor estado gana: fail > review
224
213
  if touched.get(code) != 'automated-fail':
@@ -313,10 +302,7 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
313
302
  'status': state, 'note': note}
314
303
  ef = effort(code)
315
304
  if ef:
316
- # human-effort class: what the HUMAN still does after the machine's
317
- # best signal (pricing input for human-review scoping)
318
- entry['effort'] = {'class': ef['class'], 'minutes': ef['minutes'],
319
- 'why': ef['why']}
305
+ entry['effort'] = ef
320
306
  if code in values:
321
307
  entry['value'] = values[code]
322
308
  matrix.append(entry)
@@ -333,8 +319,7 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
333
319
  'note': tx['no_signal']}
334
320
  ef = effort(code)
335
321
  if ef:
336
- row['effort'] = {'class': ef['class'], 'minutes': ef['minutes'],
337
- 'why': ef['why']}
322
+ row['effort'] = ef
338
323
  matrix.append(row)
339
324
  for code in sorted(verified):
340
325
  # una exclusión confirmada gana a una verificación previa: el
@@ -348,16 +333,11 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
348
333
  'note': 'verified against this sample per the manual checklist protocol'}
349
334
  ef = effort(code)
350
335
  if ef:
351
- row['effort'] = {'class': ef['class'], 'minutes': ef['minutes'],
352
- 'why': ef['why']}
336
+ row['effort'] = ef
353
337
  matrix.append(row)
354
338
 
355
339
  summary = {e: sum(1 for m in matrix if m['status'] == e) for e in _STATES}
356
340
 
357
- # remaining human review, in minutes: MIN/MED/MAX per class summed over
358
- # every row a human still has to touch (everything except agent-verified).
359
- # This is the scope input for human review: agent output in,
360
- # priced human scope out. The class prices live in a11ycrit (single source).
361
341
  pending_effort = _pending_effort(matrix, tx['manual_remaining'])
362
342
 
363
343
  artifacts = report_artifacts
@@ -391,7 +371,7 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
391
371
  }
392
372
 
393
373
  pack = {
394
- 'format': 'a11y-evidence-pack/2',
374
+ 'format': 'a11y-evidence-pack/3',
395
375
  'lang': language,
396
376
  'generated': now,
397
377
  'tool': 'a11y-toolkit (github.com/kinti/a11y-toolkit)',
@@ -79,8 +79,8 @@ def verdict(old_content, new_content, path='(file)'):
79
79
  a NEW kind with high/medium severity refuses the save; new LOW kinds
80
80
  and kinds already in HEAD are warnings. Returns {decision, blocked[],
81
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}')
82
+ old = audit_html(old_content or '', url=f'(old) {path}')
83
+ new = audit_html(new_content or '', url=f'(new) {path}')
84
84
  if 'error' in old or 'error' in new:
85
85
  return {'decision': 'allow', 'path': path,
86
86
  'note': 'unparseable content — the gate does not judge '
@@ -30,7 +30,7 @@ from datetime import datetime, timezone
30
30
 
31
31
  import tempfile
32
32
 
33
- from .a11yaudit import normalize_signal # noqa: E402 (compat 5.10)
33
+ from .a11yaudit import audit_conditions, completed_report_pages, normalize_signal, page_identity
34
34
 
35
35
  # per-path lock: always multi-thread; multi-process on POSIX (fcntl).
36
36
  # Without it, two concurrent writes left a truncated JSON (external review
@@ -99,33 +99,76 @@ def _save(ledger, path='a11y-ledger.json'):
99
99
  raise
100
100
 
101
101
 
102
- def record(url, report, ledger=None, path='a11y-ledger.json'):
102
+ def record(url, report, ledger=None, path='a11y-ledger.json', lang='en'):
103
103
  """Record an audit result in the ledger (thread/process safe)."""
104
104
  with _lock(path):
105
- return _record(url, report, ledger=ledger, path=path)
105
+ return _record(url, report, ledger=ledger, path=path, lang=lang)
106
106
 
107
107
 
108
108
  def _hash_url(url):
109
109
  return hashlib.sha256(url.encode()).hexdigest()[:16]
110
110
 
111
111
 
112
- def _record(url, report, ledger=None, path='a11y-ledger.json'):
113
- # un informe FALLIDO jamás escribe (revisión externa 2026-11-22: con
114
- # {'error': …} findings quedaba vacío y TODAS las señales activas
115
- # pasaban a «resolved» — el libro mentía). Se conserva el último estado
116
- # válido y se devuelve el error.
117
- if not isinstance(report, dict) or report.get('error'):
118
- return {'error': 'the audit report failed (error field) — the last '
119
- 'valid ledger state is preserved'}
112
+ def _record(url, report, ledger=None, path='a11y-ledger.json', lang='en'):
113
+ pages, error = completed_report_pages(report)
114
+ if error:
115
+ return {**error, 'error': ('La auditoría falló o es incompleta. Se conserva el historial.'
116
+ if lang == 'es' else
117
+ 'The audit failed or is incomplete. The ledger is unchanged.')}
118
+ if page_identity(url) not in {page_identity(report.get('url') or url),
119
+ page_identity(report.get('requested_url')),
120
+ page_identity(pages[0].get('url'))}:
121
+ return {'error': ('La URL no coincide con el informe.' if lang == 'es' else
122
+ 'The URL does not match the audit report.')}
123
+ page_modes, page_conditions, measured = {}, {}, {}
124
+ mode = report.get('mode', 'static')
125
+ for page in pages:
126
+ page_url = page.get('url') or (url if 'reports' not in report else None)
127
+ page_mode = page.get('mode', 'static')
128
+ identity = page_identity(page_url)
129
+ if identity is None or identity in measured or not isinstance(page_mode, str):
130
+ return {'error': ('Cada página debe tener una URL única y un modo de auditoría.'
131
+ if lang == 'es' else
132
+ 'Every page must have a unique URL and an audit mode.')}
133
+ page_modes[page_url] = page_mode
134
+ conditions = audit_conditions(page)
135
+ if conditions:
136
+ page_conditions[page_url] = conditions
137
+ measured[identity] = page_mode
120
138
  if ledger is None:
121
139
  ledger = _load(path)
122
140
  now = datetime.now(timezone.utc).isoformat(timespec='seconds')
123
141
  entry_key = _hash_url(url)
124
142
 
125
- # señales activas y score
126
- signals = sorted({normalize_signal(h.get('signal', '')) for h in report.get('findings', [])})
127
- score = report.get('score')
128
143
  prev = ledger['entries'].get(entry_key, {})
144
+ previous_mode = prev.get('mode', 'static')
145
+ # Older crawl entries have no list of measured pages. The first complete
146
+ # crawl records that scope without resolving findings from an unknown one.
147
+ previous_pages = prev.get('page_modes', {} if previous_mode == 'site' else {url: previous_mode})
148
+ if prev and (mode != previous_mode or any(
149
+ measured.get(page_identity(page)) != page_mode
150
+ for page, page_mode in previous_pages.items())):
151
+ return {'error': ('Cambió el modo o faltan páginas de la auditoría anterior. '
152
+ 'Usa un historial distinto para otro alcance.' if lang == 'es' else
153
+ 'The audit mode changed or prior pages are missing. '
154
+ 'Use a different ledger for a different scope.')}
155
+ current_conditions = {page_identity(page): value for page, value in page_conditions.items()}
156
+ previous_conditions = prev.get('page_conditions', {})
157
+ if prev and any(previous_conditions.get(page, {}) != current_conditions.get(page_identity(page), {})
158
+ for page in previous_pages):
159
+ return {'error': ('Cambiaron las condiciones de captura o el historial antiguo no las registra.'
160
+ if lang == 'es' else
161
+ 'Capture conditions changed or were not recorded in the old ledger.')}
162
+
163
+ signals = set()
164
+ for page in pages:
165
+ for finding in page['findings']:
166
+ if not isinstance(finding, dict) or not isinstance(finding.get('signal'), str) or not finding['signal']:
167
+ return {'error': ('El informe contiene un hallazgo inválido.' if lang == 'es' else
168
+ 'The audit contains an invalid finding.')}
169
+ if finding.get('status') != 'rejected' and finding.get('disprover_status') != 'rejected':
170
+ signals.add(normalize_signal(finding['signal']))
171
+ score = report.get('score', report.get('mean_score'))
129
172
 
130
173
  # resoluciones PERSISTENTES (señal→{resolved_on, seen_count}): antes se
131
174
  # recalculaban solo contra el audit anterior y la resolución se olvidaba
@@ -143,8 +186,10 @@ def _record(url, report, ledger=None, path='a11y-ledger.json'):
143
186
  for s in prev['resolved_signals']}
144
187
  for s in signals: # volvió a estar activa → la resolución caduca
145
188
  resolutions.pop(s, None)
146
- ever_seen = set(resolutions) | set(prev.get('active_signals', []))
147
- for s in ever_seen - set(signals):
189
+ ever_seen = set(resolutions)
190
+ if previous_pages:
191
+ ever_seen.update(prev.get('active_signals', []))
192
+ for s in ever_seen - signals:
148
193
  if s in resolutions: # sigue ausente: la resolución original aguanta
149
194
  resolutions[s]['seen_count'] = int(resolutions[s].get('seen_count', 1)) + 1
150
195
  else:
@@ -155,10 +200,12 @@ def _record(url, report, ledger=None, path='a11y-ledger.json'):
155
200
  'last_audit': now,
156
201
  'score': score,
157
202
  'previous_score': prev.get('score'),
158
- 'active_signals': signals,
203
+ 'active_signals': sorted(signals),
159
204
  'resolved_signals': sorted(resolutions),
160
205
  'resolutions': resolutions,
161
- 'mode': report.get('mode', 'static'),
206
+ 'mode': mode,
207
+ 'page_modes': page_modes,
208
+ 'page_conditions': page_conditions,
162
209
  'disprover': report.get('disprover'),
163
210
  }
164
211
 
@@ -298,9 +345,11 @@ def main(argv):
298
345
  s1.add_argument('--url', required=True)
299
346
  s1.add_argument('--audit', required=True, help='audit report JSON file')
300
347
  s1.add_argument('--ledger', default='a11y-ledger.json')
348
+ s1.add_argument('--lang', default='en', choices=['en', 'es'])
301
349
  s2 = sub.add_parser('gaps')
302
350
  s2.add_argument('--url', required=True)
303
351
  s2.add_argument('--ledger', default='a11y-ledger.json')
352
+ s2.add_argument('--lang', default='en', choices=['en', 'es'])
304
353
  s3 = sub.add_parser('summary')
305
354
  s3.add_argument('--ledger', default='a11y-ledger.json')
306
355
  s4 = sub.add_parser('recurrence')
@@ -309,7 +358,7 @@ def main(argv):
309
358
  if a.cmd == 'record':
310
359
  with open(a.audit, encoding='utf-8') as f:
311
360
  report = json.load(f)
312
- r = record(a.url, report, path=a.ledger)
361
+ r = record(a.url, report, path=a.ledger, lang=a.lang)
313
362
  print(json.dumps(r, ensure_ascii=False, indent=1))
314
363
  if isinstance(r, dict) and r.get('error'):
315
364
  return 1 # informe fallido: error de ejecución, no un verde
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env python3
2
2
  """OpenACR (GSA) generator — the machine-readable ACR for public procurement.
3
3
 
4
- Input: an a11y-evidence-pack/2 (from a11y_evidence / the a11y_evidence MCP
4
+ Input: an a11y evidence pack (v2 or v3) (from a11y_evidence / the a11y_evidence MCP
5
5
  tool) or raw audit reports (the pack is built here). Output: OpenACR YAML
6
6
  (the GSA open standard born from VPAT 2.4Rev 508; gsa.github.io/openacr)
7
7
  with the full 55-criterion WCAG 2.2 A/AA matrix — chapters
@@ -75,8 +75,8 @@ def _remarks(row, finding, pack_sha):
75
75
  parts.append('remediation: ' + str(finding['remediation'])[:220])
76
76
  ef = row.get('effort')
77
77
  if ef:
78
- parts.append('remaining human effort: ' + str(ef.get('class'))
79
- + ' (' + str(ef.get('minutes')) + ' min)')
78
+ minutes = f" ({ef['minutes']} min)" if ef.get('minutes') else ''
79
+ parts.append(f"remaining human effort: {ef.get('class')}{minutes}")
80
80
  parts.append('evidence pack sha256 ' + pack_sha)
81
81
  return ' | '.join(p for p in parts if p)
82
82
 
@@ -139,7 +139,7 @@ def _run_script_action(page, act):
139
139
  return f'unknown:{kind or sel}', False
140
140
 
141
141
 
142
- def _run_script(page, script, dialog_state=False):
142
+ def _run_script(page, script, dialog_state=False, check_navigation=None):
143
143
  """Scripted actions → (walk, navigations). Factored out of trace() so the
144
144
  loop is testable against a fake page (no Playwright needed)."""
145
145
  walk = []
@@ -156,6 +156,8 @@ def _run_script(page, script, dialog_state=False):
156
156
  label = f'{act.get("kind", "?")}:{act.get("selector") or act.get("key") or ""}'
157
157
  label += f' (failed: {str(e)[:60]})'
158
158
  page.wait_for_timeout(200)
159
+ if check_navigation is not None:
160
+ check_navigation()
159
161
  info = page.evaluate(a11ydiff.FOCUS_KEY_JS)
160
162
  anns = page.evaluate(_DRAIN)
161
163
  if page.url != url_now:
@@ -190,7 +192,21 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
190
192
  from .a11ydom import _get_browser, _pooled_page
191
193
  nav = _get_browser(preferred=browser)
192
194
  page, close_page = _pooled_page(nav, auth_state)
195
+ navigation_error = None
196
+
197
+ def observe_response(response):
198
+ nonlocal navigation_error
199
+ request = response.request
200
+ if (navigation_error is None and response.status >= 400
201
+ and request.is_navigation_request() and request.frame == page.main_frame):
202
+ navigation_error = _TraceHttpError(response.status, response.url)
203
+
204
+ def check_navigation():
205
+ if navigation_error is not None:
206
+ raise navigation_error
207
+
193
208
  try:
209
+ page.on('response', observe_response)
194
210
  try:
195
211
  _goto(page, url, timeout=timeout * 1000)
196
212
  except _TraceHttpError:
@@ -198,6 +214,7 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
198
214
  except Exception as e: # noqa: BLE001
199
215
  return {'error': f'could not load: {e}'}
200
216
  page.wait_for_timeout(400)
217
+ check_navigation()
201
218
  page.evaluate(_COLLECTOR)
202
219
 
203
220
  walk = []
@@ -205,16 +222,19 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
205
222
  url_now = page.url
206
223
  if script:
207
224
  ended_by = 'script_done'
208
- walk, navigations = _run_script(page, script, dialog_state=capture_dialog_state)
225
+ walk, navigations = _run_script(page, script, dialog_state=capture_dialog_state,
226
+ check_navigation=check_navigation)
209
227
  else:
210
228
  ended_by = 'step_cap'
211
229
  for i in range(steps):
212
230
  page.keyboard.press('Tab')
231
+ check_navigation()
213
232
  info = page.evaluate(a11ydiff.FOCUS_KEY_JS)
214
233
  if info is None:
215
234
  ended_by = 'no_more_focusables'
216
235
  break
217
236
  page.wait_for_timeout(150) # let the observers flush
237
+ check_navigation()
218
238
  anns = page.evaluate(_DRAIN)
219
239
  if page.url != url_now:
220
240
  navigations += 1
@@ -235,6 +255,7 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
235
255
  tree = tree[:60_000] + '\n… (truncated)'
236
256
  except Exception: # noqa: BLE001
237
257
  tree = None
258
+ check_navigation()
238
259
  except _TraceHttpError as e:
239
260
  return {'error': str(e), 'url': e.url, 'http_status': e.status}
240
261
  finally:
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env python3
2
2
  """VPAT 2.5 (WCAG edition) generator — the US counterpart of the EAA declaration.
3
3
 
4
- Input: an a11y-evidence-pack/2 (from a11y_evidence / a11y_evidence MCP tool)
4
+ Input: an a11y evidence pack (v2 or v3) (from a11y_evidence / a11y_evidence MCP tool)
5
5
  or raw audit reports (the pack is built here). Output: an accessible HTML
6
6
  VPAT with the full 55-criterion WCAG 2.2 A/AA table.
7
7
 
@@ -114,7 +114,8 @@ def _remarks(t, row, finding, level, pack_sha):
114
114
  parts.append(f"remediation: {finding['remediation'][:220]}")
115
115
  ef = row.get('effort')
116
116
  if ef:
117
- parts.append(f"remaining human effort: {ef['class']} ({ef['minutes']} min)")
117
+ minutes = f" ({ef['minutes']} min)" if ef.get('minutes') else ''
118
+ parts.append(f"remaining human effort: {ef['class']}{minutes}")
118
119
  parts.append(f"evidence pack sha256 {pack_sha}")
119
120
  return ' | '.join(p for p in parts if p)
120
121
 
@@ -22,7 +22,7 @@ import sys
22
22
  ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23
23
  sys.path.insert(0, ROOT)
24
24
 
25
- from a11y_toolkit.a11yaudit import audit_html, audit_url # noqa: E402
25
+ from a11y_toolkit.a11yaudit import MAX_HTML, audit_html, audit_url # noqa: E402
26
26
  from a11y_toolkit.a11yscope import build_scope # noqa: E402
27
27
 
28
28
 
@@ -98,8 +98,9 @@ def main(argv):
98
98
  if url:
99
99
  report = audit_url(url, timeout=30, lang=a.lang, standard=std_arg, target=targets[0])
100
100
  else:
101
- report = audit_html(open(a.file, encoding='utf-8', errors='replace').read()[:2_000_000],
102
- url=a.file, lang=a.lang, standard=std_arg, target=targets[0])
101
+ with open(a.file, encoding='utf-8', errors='replace') as source:
102
+ report = audit_html(source.read(MAX_HTML + 1), url=a.file, lang=a.lang,
103
+ standard=std_arg, target=targets[0])
103
104
  if 'error' in report:
104
105
  print(json.dumps(report, ensure_ascii=False))
105
106
  return 1
@@ -232,6 +232,7 @@
232
232
  "rendered_reason": "requires the rendered audit (a11y_audit_dom / a11ytoolkit dom): computed styles, cascade, var(), real layout",
233
233
  "err_unparseable": "unparseable HTML: {e}",
234
234
  "err_too_big": "HTML larger than {mb} MB",
235
+ "err_incomplete_html": "Incomplete HTTP response body; audit cancelled",
235
236
  "err_not_html": "the URL does not return HTML (Content-Type: {ct})",
236
237
  "role_no_tabindex": {
237
238
  "one": "1 element with an interactive role (button/link) and no tabindex: not reachable by keyboard (JS could add it at runtime — the rendered pass confirms).",
@@ -370,7 +371,7 @@
370
371
  "target_small_rem": "Give controls at least 24×24 CSS px (44×44 is better) via padding or min-width/min-height. Exceptions: equivalent inline links and sufficient surrounding spacing."
371
372
  },
372
373
  "evidence": {
373
- "manual_remaining": "human review remaining after the machine, per class (MIN 1-3, MED 5-10, MAX 15-30 min per criterion)",
374
+ "manual_remaining": "human review remaining, grouped by effort class",
374
375
  "no_signal": "no automated signal exists for this criterion in this toolkit",
375
376
  "not_flagged": "not-flagged ≠ pass: no automated signal fired on this sample",
376
377
  "not_run": "no check for this criterion ran on this sample — missing: {modes}",
@@ -232,6 +232,7 @@
232
232
  "rendered_reason": "requiere la auditoría renderizada (a11y_audit_dom / a11ytoolkit dom): estilos computados, cascada, var(), layout real",
233
233
  "err_unparseable": "HTML no analizable: {e}",
234
234
  "err_too_big": "HTML de más de {mb} MB",
235
+ "err_incomplete_html": "Cuerpo HTTP incompleto; auditoría cancelada",
235
236
  "err_not_html": "la URL no devuelve HTML (Content-Type: {ct})",
236
237
  "role_no_tabindex": {
237
238
  "one": "1 elemento con rol interactivo (button/link) sin tabindex: inalcanzable por teclado (el JS puede añadirlo en runtime — el pase rendered confirma).",
@@ -370,7 +371,7 @@
370
371
  "target_small_rem": "Da a los controles al menos 24×24 px CSS (mejor 44×44) con padding o min-width/min-height. Excepciones: enlaces inline equivalentes y espaciado suficiente alrededor."
371
372
  },
372
373
  "evidence": {
373
- "manual_remaining": "revisión humana pendiente después de la máquina, por clase (MIN 1-3, MED 5-10, MAX 15-30 min por criterio)",
374
+ "manual_remaining": "revisión humana pendiente, agrupada por clase de esfuerzo",
374
375
  "no_signal": "no hay señal automática para este criterio en este motor",
375
376
  "not_flagged": "sin señal ≠ pasa: ninguna señal automática saltó en esta muestra",
376
377
  "not_run": "ninguna prueba de este criterio se ejecutó en la muestra — falta: {modes}",
@@ -97,7 +97,7 @@ try:
97
97
  except ImportError:
98
98
  ARIALIVE_JS = None # repo checkout: read the file
99
99
 
100
- VERSION = '5.34.0'
100
+ VERSION = '5.35.0'
101
101
 
102
102
  # Params renombrados a inglés en 5.11.0; se aceptan los nombres previos.
103
103
  PARAM_ALIASES = {
@@ -437,8 +437,7 @@ TOOLS = [
437
437
  'never a pass; not-flagged means an ACCEPTED report of a mode that can '
438
438
  'signal that criterion ran and found nothing, not-run names the missing '
439
439
  'tool, and reports carrying an error never count as coverage), '
440
- 'each row priced with its human-effort class (MIN 1-3 / MED 5-10 / '
441
- 'MAX 15-30 min of human review remaining) and total remaining minutes '
440
+ 'remaining human review by effort class, with counts per class; '
442
441
  'every artifact SHA-256-'
443
442
  'hashed with timestamps, an empty signature block (name, credential, '
444
443
  'date) whose statement must reference the pack\'s own sha256, and the '
@@ -557,16 +556,11 @@ TOOLS = [
557
556
  },
558
557
  {
559
558
  'name': 'a11y_disprove',
560
- 'description': ('Disprover pattern (from Cloudflare\'s security-audit-skill): '
561
- 're-runs the audit against the live page and marks each finding '
562
- 'confirmed or rejected — rendered reports are re-verified under '
563
- 'their ORIGINAL color scheme (a dark-only contrast fail must not '
564
- 'look fixed under light; reports that don\'t record their scheme '
565
- 'come back not-rechecked), and findings that don\'t reproduce are '
566
- 'rejected with the reason. Catches false positives, race '
567
- 'conditions, and page changes between audit and report. Returns '
568
- 'a fresh score over confirmed findings only. — Run this before '
569
- 'acting on any audit report.'),
559
+ 'description': ('Re-audits the original live page and returns its current findings, '
560
+ 'score and coverage. Rendered reports are rechecked under their '
561
+ 'recorded color scheme. Matching findings are confirmed, disappeared '
562
+ 'findings are rejected, and ambiguous historical matches are kept '
563
+ 'for review. — Use a11y_evidence to seal the fresh measurement.'),
570
564
  'inputSchema': {'type': 'object', 'properties': {
571
565
  'url': {'type': 'string', 'description': 'URL to re-verify against'},
572
566
  'report': {'type': 'object', 'description': 'existing audit report (optional; if absent, audits first)'},
@@ -1229,10 +1223,10 @@ _RETURNS = {
1229
1223
  'a11y_html_validate': 'Returns JSON: Nu validator messages mapped to WCAG criteria where they overlap.',
1230
1224
  'a11y_hover': 'Returns JSON: {candidates, dismissed_on_escape, findings}.',
1231
1225
  'a11y_sr_transcript': 'Returns JSON: {url, total, announcements [{time, politeness, role, text}] — the linearized reading order}.',
1232
- 'a11y_disprove': 'Returns JSON: {confirmed, rejected, score} — a fresh score over confirmed findings only.',
1226
+ 'a11y_disprove': 'Returns the fresh audit JSON with score_original and disprover {executed, confirmed, rejected, previous_findings} when re-audited.',
1233
1227
  'a11y_ledger': 'record returns the stored entry; gaps returns criteria never checked; summary returns {entries, active_signals, resolved, mean_score}.',
1234
1228
  'a11y_criterion': 'Returns JSON: {criterion, level, understanding, toolkit_signals, requires, typical_failures, how_to_check} — signal mode adds {signal, act_rules [{id, name, status, url}]}; {error, …} for unknown codes.',
1235
- 'a11y_evidence': 'Returns the pack JSON (a11y-evidence-pack/2) as text content (the agent writes the file).',
1229
+ 'a11y_evidence': 'Returns the pack JSON (a11y-evidence-pack/3) as text content (the agent writes the file).',
1236
1230
  'a11y_journey_verdict': 'Returns JSON: {verdict pass|partial|fail|blocked, score 0-100, findings [{criterion, severity, signal, issue, remediation, step}], summary, rules} — writes a file only when output_path is given.',
1237
1231
  'a11y_generate_declaration': 'Returns {html, summary} — the accessible legal statement; writes a file only when output_path is given.',
1238
1232
  'a11y_generate_vpat': 'Returns {html, summary {level: count}, levels {code: level}, pack_sha256, draft} — the VPAT draft; writes a file only when output_path is given.',
@@ -1518,7 +1512,7 @@ def invoke(name, args):
1518
1512
  if not args.get('url') or not args.get('report'):
1519
1513
  return _content({'error': 'record requires url + report'})
1520
1514
  from .a11yledger import record as _rec
1521
- return _content(_rec(args['url'], args['report'], path=path))
1515
+ return _content(_rec(args['url'], args['report'], path=path, lang=args.get('lang', 'en')))
1522
1516
  if action == 'gaps':
1523
1517
  if not args.get('url'):
1524
1518
  return _content({'error': 'gaps requires url'})
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kinti/a11y-toolkit",
3
- "version": "5.34.0",
3
+ "version": "5.35.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",