@kinti/a11y-toolkit 5.34.1 → 5.35.1

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.
@@ -33,6 +33,7 @@ import sys
33
33
  from datetime import datetime, timezone
34
34
 
35
35
  from . import a11ydiff
36
+ from .a11ydom import _NavigationHTTPError, _load_page
36
37
 
37
38
  # Silent live-region collector: accumulates announcements and exposes a
38
39
  # drain() so each trace step reads EXACTLY the announcements it triggered.
@@ -97,19 +98,6 @@ _DIALOG_STATE_JS = '''() => {
97
98
  }'''
98
99
 
99
100
 
100
- class _TraceHttpError(Exception):
101
- def __init__(self, status, url):
102
- super().__init__(f'HTTP {status}: could not capture the requested page')
103
- self.status = status
104
- self.url = url
105
-
106
-
107
- def _goto(page, url, timeout):
108
- response = page.goto(url, wait_until='load', timeout=timeout)
109
- if response is not None and response.status >= 400:
110
- raise _TraceHttpError(response.status, page.url)
111
-
112
-
113
101
  def _run_script_action(page, act):
114
102
  """One scripted action → (label, ok). Selector-valued actions target CSS."""
115
103
  kind = act.get('kind', '')
@@ -131,7 +119,7 @@ def _run_script_action(page, act):
131
119
  page.wait_for_timeout(int(act.get('ms', 300)))
132
120
  return f'wait:{act.get("ms", 300)}', True
133
121
  if kind == 'goto':
134
- _goto(page, act.get('url', ''), timeout=30000)
122
+ _load_page(page, act.get('url', ''), timeout=30000)
135
123
  # la navegación destruye el recolector (contexto nuevo): re-inyectarlo
136
124
  # o el drain de ESTE paso y de los siguientes tronaría/volvería vacío
137
125
  page.evaluate(_COLLECTOR)
@@ -139,29 +127,33 @@ def _run_script_action(page, act):
139
127
  return f'unknown:{kind or sel}', False
140
128
 
141
129
 
142
- def _run_script(page, script, dialog_state=False):
130
+ def _run_script(page, script, dialog_state=False, check_navigation=None):
143
131
  """Scripted actions → (walk, navigations). Factored out of trace() so the
144
132
  loop is testable against a fake page (no Playwright needed)."""
145
133
  walk = []
146
134
  navigations = 0
147
135
  url_now = page.url
148
136
  for i, act in enumerate(script):
149
- if not isinstance(act, dict):
150
- continue
151
137
  try:
152
- label, _ok = _run_script_action(page, act)
153
- except _TraceHttpError:
138
+ if isinstance(act, dict):
139
+ label, succeeded = _run_script_action(page, act)
140
+ else:
141
+ label, succeeded = 'invalid action', False
142
+ except _NavigationHTTPError:
154
143
  raise
155
144
  except Exception as e: # noqa: BLE001 — a failed action is a recorded step too
156
145
  label = f'{act.get("kind", "?")}:{act.get("selector") or act.get("key") or ""}'
157
146
  label += f' (failed: {str(e)[:60]})'
147
+ succeeded = False
158
148
  page.wait_for_timeout(200)
149
+ if check_navigation is not None:
150
+ check_navigation()
159
151
  info = page.evaluate(a11ydiff.FOCUS_KEY_JS)
160
152
  anns = page.evaluate(_DRAIN)
161
153
  if page.url != url_now:
162
154
  navigations += 1
163
155
  url_now = page.url
164
- step = {'step': i + 1, 'action': label, 'focus': info,
156
+ step = {'step': i + 1, 'action': label, 'action_succeeded': succeeded, 'focus': info,
165
157
  'announcements': anns, 'url': page.url}
166
158
  if dialog_state:
167
159
  try:
@@ -188,16 +180,33 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
188
180
  el foco al opener pero DEJA el modal abierto es una divergencia de
189
181
  estado que el foco solo no ve."""
190
182
  from .a11ydom import _get_browser, _pooled_page
183
+ if script is not None and (not isinstance(script, list) or not script):
184
+ return {'error': 'the trace script must be a non-empty list of actions'}
191
185
  nav = _get_browser(preferred=browser)
192
186
  page, close_page = _pooled_page(nav, auth_state)
187
+ navigation_error = None
188
+
189
+ def observe_response(response):
190
+ nonlocal navigation_error
191
+ request = response.request
192
+ if (navigation_error is None and response.status >= 400
193
+ and request.is_navigation_request() and request.frame == page.main_frame):
194
+ navigation_error = _NavigationHTTPError(response.status, response.url)
195
+
196
+ def check_navigation():
197
+ if navigation_error is not None:
198
+ raise navigation_error
199
+
193
200
  try:
201
+ page.on('response', observe_response)
194
202
  try:
195
- _goto(page, url, timeout=timeout * 1000)
196
- except _TraceHttpError:
203
+ _load_page(page, url, timeout=timeout * 1000)
204
+ except _NavigationHTTPError:
197
205
  raise
198
206
  except Exception as e: # noqa: BLE001
199
207
  return {'error': f'could not load: {e}'}
200
208
  page.wait_for_timeout(400)
209
+ check_navigation()
201
210
  page.evaluate(_COLLECTOR)
202
211
 
203
212
  walk = []
@@ -205,16 +214,19 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
205
214
  url_now = page.url
206
215
  if script:
207
216
  ended_by = 'script_done'
208
- walk, navigations = _run_script(page, script, dialog_state=capture_dialog_state)
217
+ walk, navigations = _run_script(page, script, dialog_state=capture_dialog_state,
218
+ check_navigation=check_navigation)
209
219
  else:
210
220
  ended_by = 'step_cap'
211
221
  for i in range(steps):
212
222
  page.keyboard.press('Tab')
223
+ check_navigation()
213
224
  info = page.evaluate(a11ydiff.FOCUS_KEY_JS)
214
225
  if info is None:
215
226
  ended_by = 'no_more_focusables'
216
227
  break
217
228
  page.wait_for_timeout(150) # let the observers flush
229
+ check_navigation()
218
230
  anns = page.evaluate(_DRAIN)
219
231
  if page.url != url_now:
220
232
  navigations += 1
@@ -235,8 +247,9 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
235
247
  tree = tree[:60_000] + '\n… (truncated)'
236
248
  except Exception: # noqa: BLE001
237
249
  tree = None
238
- except _TraceHttpError as e:
239
- return {'error': str(e), 'url': e.url, 'http_status': e.status}
250
+ check_navigation()
251
+ except _NavigationHTTPError as e:
252
+ return e.report()
240
253
  finally:
241
254
  close_page()
242
255
 
@@ -245,6 +258,7 @@ def trace(url, steps=25, output=None, auth_state=None, timeout=45, script=None,
245
258
  **({'dialog_state_captured': True} if capture_dialog_state else {}),
246
259
  'steps': walk,
247
260
  'summary': {'steps_taken': len(walk),
261
+ 'failed_actions': sum(s.get('action_succeeded') is False for s in walk),
248
262
  'announcements': sum(len(s.get('announcements') or [])
249
263
  for s in walk),
250
264
  'navigations': navigations,
@@ -318,17 +332,25 @@ def _trace_error(trace):
318
332
  or (step.get('announcements') is not None
319
333
  and not isinstance(step['announcements'], list))):
320
334
  return f'invalid step {index}'
335
+ succeeded = step.get('action_succeeded')
336
+ if 'action_succeeded' in step and type(succeeded) is not bool:
337
+ return f'invalid action status at step {index}'
338
+ action = step.get('action')
339
+ legacy_failure = (succeeded is None and isinstance(action, str)
340
+ and (action.startswith('unknown:') or ' (failed:' in action))
341
+ if succeeded is False or legacy_failure:
342
+ return f'script action failed at step {index}'
321
343
  return None
322
344
 
323
345
 
324
346
  def trace_diff(a, b, gate_dialog_state=False):
325
- """Two traces → verdict. Focus behavior gates; announcements inform.
347
+ """Two traces → verdict. Failed actions invalidate a capture.
326
348
 
327
349
  gate_dialog_state (issue #16): OPT-IN — compara también el estado de
328
350
  diálogo capturado (trace --capture-dialog-state). Sin foco perdido ni
329
351
  reordenado pero con el modal ABIERTO donde antes cerraba: regresión.
330
352
  Evidencia faltante o acciones distintas → INCONCLUSIVE, nunca un falso
331
- PASS. El foco sigue siendo el único gate por defecto."""
353
+ PASS. El foco se compara después de validar la ejecución."""
332
354
  for label, capture in (('reference', a), ('candidate', b)):
333
355
  error = _trace_error(capture)
334
356
  if error:
@@ -361,7 +383,8 @@ def trace_diff(a, b, gate_dialog_state=False):
361
383
  'focus': {'before': fa, 'after': fb, 'lost': lost, 'gained': gained,
362
384
  'first_divergence': first_divergence},
363
385
  **({'dialog_gate': gate} if gate_dialog_state else {}),
364
- 'note': ('focus behavior is the gate: a lost or forked tab sequence '
386
+ 'note': ('failed scripted actions invalidate the capture (exit 1); '
387
+ 'a lost or forked tab sequence '
365
388
  'blocks (exit 2). Announcement counts are reported, not '
366
389
  'gated — content changes legitimately between builds; a '
367
390
  'collapsed layer (had announcements, now zero) is flagged '
@@ -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.1'
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,19 +556,15 @@ 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 browser, color scheme and session type. 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)'},
567
+ 'auth_state': {'type': 'string', 'description': 'Local Playwright session for the original authenticated capture'},
573
568
  'lang': {'type': 'string', 'enum': ['es', 'en'], 'description': 'Output language (en default)'},
574
569
  'timeout': {'type': 'number', 'description': 'Timeout seconds (30 default)'},
575
570
  }, 'required': ['url']},
@@ -1022,6 +1017,7 @@ _PARAM_DOCS = {
1022
1017
  ('a11y_forced_colors', 'timeout'): 'Page load timeout seconds (45 default)',
1023
1018
  ('a11y_disprove', 'url'): 'URL to re-verify findings against',
1024
1019
  ('a11y_disprove', 'report'): 'Existing audit report to verify (optional; audits first if absent)',
1020
+ ('a11y_disprove', 'auth_state'): 'Local Playwright session file for the original authenticated capture',
1025
1021
  ('a11y_disprove', 'timeout'): 'Fetch timeout seconds (default 30)',
1026
1022
  ('a11y_ledger', 'action'): 'record (add audit), gaps (what is missing), or summary (overview)',
1027
1023
  ('a11y_ledger', 'url'): 'URL being audited (for record/gaps)',
@@ -1229,10 +1225,10 @@ _RETURNS = {
1229
1225
  'a11y_html_validate': 'Returns JSON: Nu validator messages mapped to WCAG criteria where they overlap.',
1230
1226
  'a11y_hover': 'Returns JSON: {candidates, dismissed_on_escape, findings}.',
1231
1227
  '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.',
1228
+ 'a11y_disprove': 'Returns the fresh audit JSON with score_original and disprover {executed, confirmed, rejected, previous_findings} when re-audited.',
1233
1229
  'a11y_ledger': 'record returns the stored entry; gaps returns criteria never checked; summary returns {entries, active_signals, resolved, mean_score}.',
1234
1230
  '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).',
1231
+ 'a11y_evidence': 'Returns the pack JSON (a11y-evidence-pack/3) as text content (the agent writes the file).',
1236
1232
  '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
1233
  'a11y_generate_declaration': 'Returns {html, summary} — the accessible legal statement; writes a file only when output_path is given.',
1238
1234
  '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.',
@@ -1507,7 +1503,7 @@ def invoke(name, args):
1507
1503
  try:
1508
1504
  return _content(disprove_fn(args['url'], report=args.get('report'),
1509
1505
  timeout=args.get('timeout', 30),
1510
- lang=args.get('lang', 'en')))
1506
+ lang=args.get('lang', 'en'), auth_state=args.get('auth_state')))
1511
1507
  except Exception as e:
1512
1508
  return {'content': [{'type': 'text', 'text': f'error: {e}'}], 'isError': True}
1513
1509
  if name == 'a11y_ledger':
package/lib/_bootstrap.py CHANGED
@@ -16,8 +16,8 @@ _ENGINE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16
16
  sys.path.insert(0, _ENGINE)
17
17
 
18
18
  _ENTRY = {
19
- 'a11y_toolkit.a11y': 'main',
20
- 'a11y_toolkit.server': 'main',
19
+ 'a11y_toolkit.a11y',
20
+ 'a11y_toolkit.server',
21
21
  }
22
22
 
23
23
 
@@ -25,8 +25,10 @@ def _run(entry, args):
25
25
  if entry not in _ENTRY:
26
26
  print(f'unknown entry: {entry}', file=sys.stderr)
27
27
  return 2
28
- module = __import__(entry, fromlist=[_ENTRY[entry]])
29
- return getattr(module, _ENTRY[entry])(args)
28
+ module = __import__(entry, fromlist=['main'])
29
+ if entry == 'a11y_toolkit.server':
30
+ return module.main()
31
+ return module.main(args)
30
32
 
31
33
 
32
34
  if __name__ == '__main__':
package/lib/runner.cjs CHANGED
@@ -35,7 +35,7 @@ function run(entry) {
35
35
  return;
36
36
  }
37
37
  const SCRIPTS = { 'a11y_toolkit.a11y': 'a11ytoolkit', 'a11y_toolkit.server': 'a11y-toolkit-mcp' };
38
- const child = spawn(UVX, ['--from', `a11y-toolkit==${VERSION}`, SCRIPTS[entry] || entry], { stdio: 'inherit' });
38
+ const child = spawn(UVX, ['--from', `a11y-toolkit==${VERSION}`, SCRIPTS[entry] || entry, ...args], { stdio: 'inherit' });
39
39
  child.on('error', (e) => {
40
40
  if (e.code === 'ENOENT') {
41
41
  console.error('a11y-toolkit: needs python3 (>=3.9) or uv.');
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.1",
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",