@kinti/a11y-toolkit 5.34.1 → 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
@@ -1981,6 +1981,13 @@ def page_identity(url):
1981
1981
  return (parts.scheme, parts.hostname, port, parts.path or '/', parts.query)
1982
1982
 
1983
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
+
1984
1991
  def completed_report_pages(report):
1985
1992
  """Return measured pages or the reason they cannot support a comparison."""
1986
1993
  if not isinstance(report, dict) or report.get('error'):
@@ -3241,21 +3248,24 @@ def audit_changed(base='HEAD', lang='en', cwd='.'):
3241
3248
  is no HTML to audit). Deleted files are skipped.
3242
3249
  """
3243
3250
  import subprocess
3244
- spec = ['git', 'diff', '--name-only', '--diff-filter=d',
3251
+ spec = ['git', 'diff', '--name-only', '-z', '--diff-filter=d',
3245
3252
  base if base == 'HEAD' else f'{base}...HEAD']
3246
3253
  try:
3247
- 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)
3248
3255
  except FileNotFoundError:
3249
3256
  return {'error': 'git not available'}
3250
3257
  if out.returncode != 0:
3251
- return {'error': f'git diff failed: {out.stderr.strip()[:200]}'}
3252
- 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}'}
3253
3260
  # los NUEVOS sin trackear no salen en git diff — entran también:
3254
3261
  # una página recién creada no puede escaparse del gate local
3255
- untracked = subprocess.run(['git', 'ls-files', '--others', '--exclude-standard'],
3256
- cwd=cwd, capture_output=True, text=True, timeout=30)
3257
- if untracked.returncode == 0:
3258
- 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]
3259
3269
  auditables, web_touched = [], []
3260
3270
  for f in changed:
3261
3271
  ext = os.path.splitext(f)[1].lower()
@@ -44,7 +44,7 @@ import datetime
44
44
  import json
45
45
  from collections import Counter
46
46
 
47
- from .a11yaudit import completed_report_pages, 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,6 +65,14 @@ _CLI_MSG = {
65
65
  BUDGET_FORMAT = 'a11y-budget/2'
66
66
 
67
67
 
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
74
+
75
+
68
76
  def _page_index(pages):
69
77
  result = {}
70
78
  for page in pages:
@@ -72,7 +80,7 @@ def _page_index(pages):
72
80
  if not isinstance(url, str) or not url or url in result:
73
81
  raise ValueError('every audited page must have a unique URL')
74
82
  findings = {}
75
- for finding in page['findings']:
83
+ for finding in _active_findings(page):
76
84
  signal = normalize_signal(finding['signal'])
77
85
  paths = [path for path in (finding.get('paths') or []) if isinstance(path, str)]
78
86
  count = finding.get('count')
@@ -80,7 +88,8 @@ def _page_index(pages):
80
88
  count = max(len(paths), len(finding.get('examples') or []), 1)
81
89
  findings[signal] = {'severity': finding['severity'], 'count': max(count, len(paths)),
82
90
  'paths': sorted(paths)}
83
- result[url] = {'mode': page.get('mode', 'static'), 'findings': findings}
91
+ result[url] = {'mode': page.get('mode', 'static'), 'conditions': audit_conditions(page),
92
+ 'findings': findings}
84
93
  return result
85
94
 
86
95
 
@@ -136,6 +145,9 @@ def _compare_instances(budget, pages, blocking):
136
145
  prior = base.get(url)
137
146
  if prior and prior['mode'] != page['mode']:
138
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}
139
151
  old = prior['findings'] if prior else {}
140
152
  current = page['findings']
141
153
  for signal in sorted(set(old) | set(current)):
@@ -162,7 +174,7 @@ def _compare_signals(budget, pages, blocking):
162
174
  base = {normalize_signal(s) for s in budget.get('signals', [])}
163
175
  current = {}
164
176
  for pg in pages:
165
- for h in pg.get('findings', []):
177
+ for h in _active_findings(pg):
166
178
  current.setdefault(normalize_signal(h.get('signal', '')), []).append(h['severity'])
167
179
  new = sorted(s for s in current if s not in base)
168
180
  resolved = sorted(base - set(current))
@@ -182,6 +194,7 @@ def compare(budget, audit, today=None):
182
194
  try:
183
195
  blocking = set(budget.get('blocking', ['high', 'medium']))
184
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)}
185
198
  if budget.get('format') == BUDGET_FORMAT:
186
199
  verdict = _compare_instances(budget, _page_index(pages), blocking)
187
200
  else:
@@ -201,7 +214,7 @@ def compare(budget, audit, today=None):
201
214
  **verdict,
202
215
  'summary': {
203
216
  'baseline': len(set(budget.get('signals', []))),
204
- 'current': len({normalize_signal(h['signal']) for pg in pages for h in pg['findings']}),
217
+ 'current': len(signals),
205
218
  'new': len(verdict['new']),
206
219
  'resolved': len(verdict['resolved']),
207
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)
@@ -29,42 +29,68 @@ import sys
29
29
  from .a11yaudit import audit_url, normalize_signal, page_identity
30
30
 
31
31
 
32
- def _recheck(url, expected_url, findings, timeout, lang, color_scheme=None):
33
- """Compare findings only after a successful visit to the same page."""
32
+ def _recheck(url, expected_url, timeout, lang, color_scheme=None):
33
+ """Obtain a successful measurement of the same page."""
34
34
  if color_scheme is None:
35
35
  fresh = audit_url(url, timeout=timeout, lang=lang)
36
36
  else:
37
37
  from .a11ydom import audit_dom_url
38
38
  fresh = audit_dom_url(url, timeout=timeout, lang=lang, color_scheme=color_scheme)
39
39
  if 'error' in fresh:
40
- return findings, fresh['error']
40
+ return None, fresh['error']
41
41
  if page_identity(fresh.get('url')) != page_identity(expected_url):
42
- return findings, ('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.')
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
45
46
 
46
- signals = {h['signal'] for h in fresh['findings']}
47
- rejected = ('La señal {signal!r} ya no aparece en la nueva auditoría de la página.'
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.'
48
68
  if lang == 'es' else
49
- 'Signal {signal!r} no longer fires in the new audit of the page.')
50
- verified = []
51
- for finding in findings:
52
- checked = dict(finding)
53
- checked.pop('disprover_status', None)
54
- checked.pop('reject_reason', None)
55
- if normalize_signal(checked.get('signal', '')) in signals:
56
- checked['status'] = 'confirmed'
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'
57
85
  else:
58
- checked['status'] = 'rejected'
59
- checked['reject_reason'] = rejected.format(signal=checked.get('signal', '?'))
60
- verified.append(checked)
61
- return verified, None
86
+ historical.append(dict(old, disprover_status='not-rechecked'))
87
+ return current, historical
62
88
 
63
89
 
64
90
  def disprove(url, report=None, timeout=30, lang='en'):
65
91
  """Audit a URL and disprove findings, or verify an existing report.
66
92
 
67
- Returns a report with each finding marked confirmed/rejected."""
93
+ Return the fresh measurement and the outcomes of prior findings."""
68
94
  if report is None:
69
95
  report = audit_url(url, timeout=timeout, lang=lang)
70
96
  if report.get('error'):
@@ -90,7 +116,7 @@ def disprove(url, report=None, timeout=30, lang='en'):
90
116
  return res
91
117
 
92
118
  if mode_name == 'static':
93
- verified, err = _recheck(url, expected_url, findings, timeout, lang)
119
+ fresh, err = _recheck(url, expected_url, timeout, lang)
94
120
  elif mode_name == 'rendered':
95
121
  # condición necesaria: el esquema de color bajo el que se auditó. Sin
96
122
  # él no se reverifica (rechazar un contrast_fail de dark mode tras
@@ -108,7 +134,7 @@ def disprove(url, report=None, timeout=30, lang='en'):
108
134
  'under light); re-audit with a11y_audit_dom and disprove '
109
135
  'THAT report')}
110
136
  return res
111
- verified, err = _recheck(url, expected_url, findings, timeout, lang, color_scheme=scheme)
137
+ fresh, err = _recheck(url, expected_url, timeout, lang, color_scheme=scheme)
112
138
  else:
113
139
  # no re-verifier for this mode: report not-rechecked, never a proxy
114
140
  # audit (a keyboard finding must not vanish just because the wrong
@@ -123,26 +149,19 @@ def disprove(url, report=None, timeout=30, lang='en'):
123
149
  if err:
124
150
  return dict(report, error=err, disprover={'executed': False, 'reason': err})
125
151
 
126
- result = dict(report)
127
- 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'))
128
155
  result['disprover'] = {
129
156
  'executed': True,
130
- 'confirmed': sum(1 for h in verified if h.get('status') == 'confirmed'),
131
- 'rejected': sum(1 for h in verified if h.get('status') == 'rejected'),
132
- 'note': ('Each finding was re-checked against the live page. '
133
- 'Rejected findings include the reason they did not reproduce. '
134
- 'Confirmed findings survived a fresh verification pass.'),
135
- }
136
-
137
- # recalcular score sobre los confirmed
138
- from .a11yaudit import compute_score
139
- solo_confirmed = [h for h in verified if h.get('status') == 'confirmed']
140
- result['score_original'] = report.get('score')
141
- result['score'] = compute_score(solo_confirmed)
142
- result['summary'] = {
143
- 'high': sum(1 for h in solo_confirmed if h['severity'] == 'high'),
144
- 'medium': sum(1 for h in solo_confirmed if h['severity'] == 'medium'),
145
- '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.'),
146
165
  }
147
166
  return result
148
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,
@@ -311,10 +302,7 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
311
302
  'status': state, 'note': note}
312
303
  ef = effort(code)
313
304
  if ef:
314
- # human-effort class: what the HUMAN still does after the machine's
315
- # best signal (pricing input for human-review scoping)
316
- entry['effort'] = {'class': ef['class'], 'minutes': ef['minutes'],
317
- 'why': ef['why']}
305
+ entry['effort'] = ef
318
306
  if code in values:
319
307
  entry['value'] = values[code]
320
308
  matrix.append(entry)
@@ -331,8 +319,7 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
331
319
  'note': tx['no_signal']}
332
320
  ef = effort(code)
333
321
  if ef:
334
- row['effort'] = {'class': ef['class'], 'minutes': ef['minutes'],
335
- 'why': ef['why']}
322
+ row['effort'] = ef
336
323
  matrix.append(row)
337
324
  for code in sorted(verified):
338
325
  # una exclusión confirmada gana a una verificación previa: el
@@ -346,16 +333,11 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
346
333
  'note': 'verified against this sample per the manual checklist protocol'}
347
334
  ef = effort(code)
348
335
  if ef:
349
- row['effort'] = {'class': ef['class'], 'minutes': ef['minutes'],
350
- 'why': ef['why']}
336
+ row['effort'] = ef
351
337
  matrix.append(row)
352
338
 
353
339
  summary = {e: sum(1 for m in matrix if m['status'] == e) for e in _STATES}
354
340
 
355
- # remaining human review, in minutes: MIN/MED/MAX per class summed over
356
- # every row a human still has to touch (everything except agent-verified).
357
- # This is the scope input for human review: agent output in,
358
- # priced human scope out. The class prices live in a11ycrit (single source).
359
341
  pending_effort = _pending_effort(matrix, tx['manual_remaining'])
360
342
 
361
343
  artifacts = report_artifacts
@@ -389,7 +371,7 @@ def build_pack(reports, snapshot=None, reviewer=None, notes=None, verified=None,
389
371
  }
390
372
 
391
373
  pack = {
392
- 'format': 'a11y-evidence-pack/2',
374
+ 'format': 'a11y-evidence-pack/3',
393
375
  'lang': language,
394
376
  'generated': now,
395
377
  'tool': 'a11y-toolkit (github.com/kinti/a11y-toolkit)',
@@ -30,7 +30,7 @@ from datetime import datetime, timezone
30
30
 
31
31
  import tempfile
32
32
 
33
- from .a11yaudit import completed_report_pages, normalize_signal, page_identity
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
@@ -120,7 +120,7 @@ def _record(url, report, ledger=None, path='a11y-ledger.json', lang='en'):
120
120
  page_identity(pages[0].get('url'))}:
121
121
  return {'error': ('La URL no coincide con el informe.' if lang == 'es' else
122
122
  'The URL does not match the audit report.')}
123
- page_modes, measured = {}, {}
123
+ page_modes, page_conditions, measured = {}, {}, {}
124
124
  mode = report.get('mode', 'static')
125
125
  for page in pages:
126
126
  page_url = page.get('url') or (url if 'reports' not in report else None)
@@ -131,6 +131,9 @@ def _record(url, report, ledger=None, path='a11y-ledger.json', lang='en'):
131
131
  if lang == 'es' else
132
132
  'Every page must have a unique URL and an audit mode.')}
133
133
  page_modes[page_url] = page_mode
134
+ conditions = audit_conditions(page)
135
+ if conditions:
136
+ page_conditions[page_url] = conditions
134
137
  measured[identity] = page_mode
135
138
  if ledger is None:
136
139
  ledger = _load(path)
@@ -149,6 +152,13 @@ def _record(url, report, ledger=None, path='a11y-ledger.json', lang='en'):
149
152
  'Usa un historial distinto para otro alcance.' if lang == 'es' else
150
153
  'The audit mode changed or prior pages are missing. '
151
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.')}
152
162
 
153
163
  signals = set()
154
164
  for page in pages:
@@ -195,6 +205,7 @@ def _record(url, report, ledger=None, path='a11y-ledger.json', lang='en'):
195
205
  'resolutions': resolutions,
196
206
  'mode': mode,
197
207
  'page_modes': page_modes,
208
+ 'page_conditions': page_conditions,
198
209
  'disprover': report.get('disprover'),
199
210
  }
200
211
 
@@ -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
 
@@ -371,7 +371,7 @@
371
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."
372
372
  },
373
373
  "evidence": {
374
- "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",
375
375
  "no_signal": "no automated signal exists for this criterion in this toolkit",
376
376
  "not_flagged": "not-flagged ≠ pass: no automated signal fired on this sample",
377
377
  "not_run": "no check for this criterion ran on this sample — missing: {modes}",
@@ -371,7 +371,7 @@
371
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."
372
372
  },
373
373
  "evidence": {
374
- "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",
375
375
  "no_signal": "no hay señal automática para este criterio en este motor",
376
376
  "not_flagged": "sin señal ≠ pasa: ninguna señal automática saltó en esta muestra",
377
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.1'
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.',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kinti/a11y-toolkit",
3
- "version": "5.34.1",
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",