@kinti/a11y-toolkit 5.25.2 → 5.27.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.
Files changed (44) hide show
  1. package/README.md +1 -1
  2. package/a11y_toolkit/a11y.py +31 -4
  3. package/a11y_toolkit/a11yact.py +9 -1
  4. package/a11y_toolkit/a11yannotate.py +185 -0
  5. package/a11y_toolkit/a11yaudit.py +903 -186
  6. package/a11y_toolkit/a11ybadge.py +24 -17
  7. package/a11y_toolkit/a11ybudget.py +145 -1
  8. package/a11y_toolkit/a11ycorpus.py +58 -24
  9. package/a11y_toolkit/a11ycrit.py +110 -53
  10. package/a11y_toolkit/a11ydiff.py +104 -34
  11. package/a11y_toolkit/a11ydisprove.py +15 -8
  12. package/a11y_toolkit/a11ydocx.py +8 -6
  13. package/a11y_toolkit/a11ydom.py +451 -96
  14. package/a11y_toolkit/a11yen301549.py +147 -0
  15. package/a11y_toolkit/a11yengines.py +157 -0
  16. package/a11y_toolkit/a11yevidence.py +182 -36
  17. package/a11y_toolkit/a11yfix.py +131 -52
  18. package/a11y_toolkit/a11yinit.py +30 -5
  19. package/a11y_toolkit/a11yjourney.py +110 -4
  20. package/a11y_toolkit/a11yledger.py +119 -12
  21. package/a11y_toolkit/a11ylocate.py +247 -0
  22. package/a11y_toolkit/a11yopenacr.py +28 -7
  23. package/a11y_toolkit/a11ypatches.py +154 -0
  24. package/a11y_toolkit/a11ypatterns.py +344 -0
  25. package/a11y_toolkit/a11ypdf.py +109 -53
  26. package/a11y_toolkit/a11yrgaa.py +60 -0
  27. package/a11y_toolkit/a11yroute.py +34 -12
  28. package/a11y_toolkit/a11ysarif.py +70 -21
  29. package/a11y_toolkit/a11yscope.py +296 -0
  30. package/a11y_toolkit/a11yscroll.py +7 -5
  31. package/a11y_toolkit/a11ystatement.py +30 -6
  32. package/a11y_toolkit/a11ytrace.py +293 -0
  33. package/a11y_toolkit/a11yvalidate.py +21 -15
  34. package/a11y_toolkit/a11yvpat.py +54 -11
  35. package/a11y_toolkit/a11yvtt.py +22 -6
  36. package/a11y_toolkit/a11ywiz.py +121 -0
  37. package/a11y_toolkit/contrast.py +62 -24
  38. package/a11y_toolkit/locales/en.json +222 -24
  39. package/a11y_toolkit/locales/es.json +223 -25
  40. package/a11y_toolkit/rgaa.json +2661 -0
  41. package/a11y_toolkit/server.py +247 -59
  42. package/package.json +2 -2
  43. package/a11y_toolkit/a11yplan.py +0 -214
  44. package/a11y_toolkit/a11ywcagem.py +0 -237
@@ -28,7 +28,7 @@ import json
28
28
  import re
29
29
  import sys
30
30
 
31
- from .a11yaudit import audit_html, _PERSONAL_DATA
31
+ from .a11yaudit import audit_html
32
32
 
33
33
  from . import a11yi18n
34
34
  # token autocomplete por type de input (determinista por especificación)
@@ -40,15 +40,13 @@ _TOKEN_BY_HINT = [
40
40
  (re.compile(r'ciudad|city', re.I), 'address-level2'),
41
41
  (re.compile(r'country|pais', re.I), 'country-name'),
42
42
  (re.compile(r'organi[sz]ation|company|empresa', re.I), 'organization'),
43
- (re.compile(r'phone|telefono|tel\b', re.I), 'tel'),
43
+ (re.compile(r'phone|telefono|\btel\b', re.I), 'tel'),
44
44
  (re.compile(r'email|correo', re.I), 'email'),
45
45
  (re.compile(r'(?:^|[\W_])(?:full)?name|nombre', re.I), 'name'),
46
46
  ]
47
47
 
48
- _RE_FORM = re.compile(r'<form\b[^>]*>', re.I)
49
48
  _RE_TAG_Q = r'(?:[^>\"\']|\"[^\"]*\"|\'[^\']*\')*'
50
49
  _RE_FIELD = re.compile(r'<input' + _RE_TAG_Q + r'>|<(select|textarea)' + _RE_TAG_Q + r'>.*?</\1\s*>', re.I | re.S)
51
- _RE_SCRIPTS = re.compile(r'<script\b.*?</script>', re.S | re.I)
52
50
  _RE_FORM_BLOCK = re.compile(r'<form\b.*?</form>', re.S | re.I)
53
51
 
54
52
  _PHRASES = a11yi18n.pair('fix') # locales/<lang>.json — community-editable
@@ -88,7 +86,7 @@ _JS_PHRASES = """<script>
88
86
 
89
87
  _RE_INPUT = re.compile(r'<input' + _RE_TAG_Q + r'>', re.I)
90
88
  _RE_VIEWPORT = re.compile(r'(<meta\s[^>]*name=["\']viewport["\'][^>]*content=["\'])([^"\']*)(["\'])', re.I)
91
- _RE_HTML_TAG = re.compile(r'<html\b([^>]*)>', re.I)
89
+ _RE_HTML_TAG = re.compile(r'<html\b(' + _RE_TAG_Q + r')>', re.I)
92
90
  _RE_TITLE = re.compile(r'<title>\s*</title>', re.I)
93
91
 
94
92
 
@@ -117,6 +115,25 @@ def _clean_viewport(content):
117
115
  return ', '.join(clean), removed
118
116
 
119
117
 
118
+ def _drop_selfclose(base):
119
+ """Drop a trailing self-closing slash — only OUTSIDE quotes: a value like
120
+ "x/" is data, not markup (an unquoted rstrip('/') would eat it)."""
121
+ q = None
122
+ last = -1 # índice del último carácter significativo fuera de comillas
123
+ for i, ch in enumerate(base):
124
+ if q:
125
+ if ch == q:
126
+ q = None
127
+ elif ch in ('"', "'"):
128
+ q = ch
129
+ last = i
130
+ elif not ch.isspace():
131
+ last = i
132
+ if last >= 0 and base[last] == '/':
133
+ return base[:last].rstrip()
134
+ return base
135
+
136
+
120
137
  def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
121
138
  """Aplica los arreglos seguros. Devuelve fixed_html + aplicados + no_aplicados."""
122
139
  applied = []
@@ -126,13 +143,20 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
126
143
  # no son marcado — ninguna regex de transformación debe verlo. Sin este
127
144
  # paso, el "no toco scripts" era falso (revisión externa, ronda 2).
128
145
  _masks = []
146
+ # bloques <script> ORIGINALES, capturados ANTES de enmascarar: el guard
147
+ # de 4b decide sobre el código real — en el texto vivo ya no son buscables
148
+ _scripts_raw = []
129
149
 
130
150
  def _mask(text):
151
+ def _cap_script(m):
152
+ _scripts_raw.append(m.group(0))
153
+ return _pon(m)
154
+
131
155
  def _pon(m):
132
156
  tok = '\x00A11YFXMASK%d\x00' % len(_masks)
133
157
  _masks.append((tok, m.group(0)))
134
158
  return tok
135
- text = re.sub(r'<script\b[^>]*>.*?</script\s*>', _pon, text, flags=re.I | re.S)
159
+ text = re.sub(r'<script\b[^>]*>.*?</script\s*>', _cap_script, text, flags=re.I | re.S)
136
160
  text = re.sub(r'<style\b[^>]*>.*?</style\s*>', _pon, text, flags=re.I | re.S)
137
161
  # textarea NO se enmascara: la capa de error se inserta tras su cierre
138
162
  # (5.2.1) y el contenido queda intacto; ocultarlo quitaría el 3.3.1
@@ -140,37 +164,44 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
140
164
  return text
141
165
 
142
166
  def _unmask(text):
143
- for tok, original in _masks:
167
+ # orden INVERSO de creación: un mask puede vivir dentro del ORIGINAL
168
+ # de otro (un <script> dentro de un comentario) — restaurar primero el
169
+ # contenedor devuelve los tokens internos al texto vivo; en orden de
170
+ # creación el interno se restauraba dentro del original almacenado
171
+ # (no en el texto) y el token quedaba filtrado en la salida
172
+ for tok, original in reversed(_masks):
144
173
  text = text.replace(tok, original)
145
174
  return text
146
175
 
147
176
  fixed = _mask(fixed)
148
177
 
149
- # 1. viewport: zoom sin bloqueos (1.4.4)
178
+ # 1. viewport: zoom sin bloqueos (1.4.4) — solo si algo se quita de verdad:
179
+ # un maximum-scale=5 no bloquea el zoom y reescribirlo sin cambios sería
180
+ # un fix fantasma en `applied`
150
181
  m = _RE_VIEWPORT.search(fixed)
151
- if m and (re.search(r'user-scalable\s*=\s*(no|0)', m.group(2), re.I)
152
- or re.search(r'maximum-scale\s*=\s*([\d.]+)', m.group(2), re.I)):
182
+ if m:
153
183
  clean, removed = _clean_viewport(m.group(2))
154
- if clean:
155
- fixed = fixed[:m.start()] + m.group(1) + clean + m.group(3) + fixed[m.end():]
156
- else:
157
- # eliminar el meta COMPLETO: escanear el final de etiqueta
158
- # respetando comillas (un `>` dentro de value= no cierra el tag)
159
- end = m.end()
160
- q = None
161
- while end < len(fixed):
162
- ch = fixed[end]
163
- if q:
164
- if ch == q:
165
- q = None
166
- elif ch in ('"', "'"):
167
- q = ch
168
- elif ch == '>':
169
- break
170
- end += 1
171
- fixed = fixed[:m.start()] + (fixed[end + 1:] if end < len(fixed) else '')
172
- applied.append({'signal': 'zoom_no',
173
- 'fix': f'viewport without {", ".join(removed)} (1.4.4: zoom no longer blocked)'})
184
+ if removed:
185
+ if clean:
186
+ fixed = fixed[:m.start()] + m.group(1) + clean + m.group(3) + fixed[m.end():]
187
+ else:
188
+ # eliminar el meta COMPLETO: escanear el final de etiqueta
189
+ # respetando comillas (un `>` dentro de value= no cierra el tag)
190
+ end = m.end()
191
+ q = None
192
+ while end < len(fixed):
193
+ ch = fixed[end]
194
+ if q:
195
+ if ch == q:
196
+ q = None
197
+ elif ch in ('"', "'"):
198
+ q = ch
199
+ elif ch == '>':
200
+ break
201
+ end += 1
202
+ fixed = fixed[:m.start()] + (fixed[end + 1:] if end < len(fixed) else '')
203
+ applied.append({'signal': 'zoom_no',
204
+ 'fix': f'viewport without {", ".join(removed)} (1.4.4: zoom no longer blocked)'})
174
205
 
175
206
  # 2. autocomplete determinista (1.3.5)
176
207
  n_ac = 0
@@ -194,7 +225,9 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
194
225
  if not token:
195
226
  return tag
196
227
  n_ac += 1
197
- return tag[:-1].rstrip() + f' autocomplete="{token}">'
228
+ # la barra de autocierre no es un atributo: quitarla ANTES de inyectar
229
+ # (`<input .../ autocomplete>` sería markup inválido)
230
+ return _drop_selfclose(tag[:-1].rstrip()) + f' autocomplete="{token}">'
198
231
  fixed = _RE_INPUT.sub(_input_fix, fixed)
199
232
  if n_ac:
200
233
  applied.append({'signal': 'autocomplete',
@@ -204,10 +237,23 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
204
237
  # este toolkit ESCRIBE HTML, no puede ser vector de inyección
205
238
  if lang and re.fullmatch(r'[a-zA-Z]{2,3}(-[a-zA-Z0-9]{2,8})*', lang.strip()):
206
239
  m = _RE_HTML_TAG.search(fixed)
207
- if m and 'lang=' not in m.group(1).lower():
208
- fixed = fixed[:m.start()] + f'<html lang="{_html.escape(lang.strip())}"' + m.group(1) + '>' + fixed[m.end():]
209
- applied.append({'signal': 'lang_missing',
210
- 'fix': f'<html lang="{lang.strip()}"> added (3.1.1)'})
240
+ if m:
241
+ # atributo lang REAL (límite de atributo vía lookbehind: xml:lang=,
242
+ # data-lang= no cuentan) y con valor NO vacío (lang="" no cumple
243
+ # 3.1.1) — antes un simple 'lang=' in attr casaba con cualquiera
244
+ lm = re.search(r'(?<![\w:.\-])lang\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s>]+))',
245
+ m.group(1), re.I)
246
+ lval = next((g for g in (lm.groups() if lm else ()) if g is not None), '')
247
+ if not lval.strip():
248
+ new_lang = _html.escape(lang.strip())
249
+ if lm is None: # no hay lang: se antepone
250
+ fixed = (fixed[:m.start()] + f'<html lang="{new_lang}"' + m.group(1) + '>'
251
+ + fixed[m.end():])
252
+ else: # lang="": se RELLENA el existente, nunca duplicar
253
+ attrs = m.group(1)[:lm.start()] + f'lang="{new_lang}"' + m.group(1)[lm.end():]
254
+ fixed = fixed[:m.start()] + '<html' + attrs + '>' + fixed[m.end():]
255
+ applied.append({'signal': 'lang_missing',
256
+ 'fix': f'<html lang="{lang.strip()}"> added (3.1.1)'})
211
257
 
212
258
  # 4. title (solo si vacío y lo dan); escapado por la misma razón
213
259
  if title and _RE_TITLE.search(fixed):
@@ -216,8 +262,10 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
216
262
 
217
263
  # 4b. form errors: accessible error layer (3.3.1 + 3.3.3 from attributes)
218
264
  if form_errors and 'a11yfx' not in fixed:
219
- scripts = _RE_SCRIPTS.findall(fixed)
220
- if not any(('aria-invalid' in s or 'setCustomValidity' in s) for s in scripts):
265
+ # el guard mira los <script> ORIGINALES (_scripts_raw): en `fixed` ya
266
+ # están enmascarados y findall no vería nada — la capa se inyectaba
267
+ # aunque la página ya hiciera setCustomValidity/aria-invalid
268
+ if not any(('aria-invalid' in s or 'setCustomValidity' in s) for s in _scripts_raw):
221
269
  import json as _json
222
270
  state = {'forms': 0, 'fields': 0}
223
271
 
@@ -238,6 +286,7 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
238
286
  state['fields'] += 1
239
287
  fid = "a11yfx-e-%d-%d" % (state['forms'], state['fields'])
240
288
  opening = re.match(r'<[a-zA-Z]+(?:[^>"\']|"[^"]*"|\'[^\']*\')*>', elem).group(0)
289
+ head_len = len(opening) # límite del tag ANTES de inyectar attrs
241
290
  mdb = re.search(r'aria-describedby=["\']([^"\']*)["\']', opening, re.I)
242
291
  if mdb: # merge, preserving the existing reference
243
292
  new = 'aria-describedby="%s %s"' % (mdb.group(1), fid)
@@ -249,8 +298,13 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
249
298
  if opening.lower().startswith(('<textarea', '<select')):
250
299
  # content-bearing element: the layer goes AFTER the close,
251
300
  # never inside (inside would become its value — a real
252
- # data-corruption regression, caught in external review)
253
- return elem.replace(re.match(r'<[^>]*>', elem).group(0), opening, 1) + layer
301
+ # data-corruption regression, caught in external review).
302
+ # `opening` matchea elem desde el índice 0 (quote-aware) y
303
+ # cubre exactamente head_len bytes: el resto es contenido +
304
+ # cierre, preservado byte a byte (el replace por prefijo
305
+ # ingenuo dejaba el fragmento tras un `>` citado como
306
+ # contenido del elemento)
307
+ return opening + elem[head_len:] + layer
254
308
  return opening + layer
255
309
 
256
310
  def _own_handling(atrs_form):
@@ -263,7 +317,15 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
263
317
 
264
318
  def _process_block(mb):
265
319
  block = mb.group(0)
266
- opening = re.match(r'<form\b[^>]*>', block, re.I).group(0)
320
+ # opening quote-aware: un `>` dentro de un atributo citado
321
+ # (action="/search?q=a>b") NO cierra el tag — el prefijo
322
+ # ingenuo mutilaba la URL. Si el block acaba DENTRO de una
323
+ # cita (action="x</form>"), la apertura no es delimitable:
324
+ # no se toca (hostil: jamás caer)
325
+ mop = re.match(r'<form\b' + _RE_TAG_Q + r'>', block, re.I)
326
+ if mop is None:
327
+ return block
328
+ opening = mop.group(0)
267
329
  if 'data-a11yfx' in opening or _own_handling(opening):
268
330
  return block # custom error handling present: never fight it
269
331
  state['forms'] += 1
@@ -275,22 +337,19 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
275
337
  if state['fields']:
276
338
  fr = _PHRASES.get(lang, _PHRASES['en'])
277
339
  js = _JS_PHRASES % {k: _json.dumps(v) for k, v in fr.items()}
278
- fixed = fixed.replace('</body>', js + '\n</body>', 1)
340
+ # case-insensitive: </BODY> perdía el JS y `applied` seguía
341
+ # declarando la capa (aria-describedby colgantes)
342
+ fixed = re.sub(r'</body\s*>', lambda _mb: js + '\n' + _mb.group(0),
343
+ fixed, count=1, flags=re.I)
279
344
  applied.append({'signal': 'form_error_missing',
280
345
  'fix': f"accessible error layer on {state['forms']} form(s), "
281
346
  f"{state['fields']} field(s) — 3.3.1 identification + "
282
347
  f"3.3.3 attribute-derived suggestions"})
283
348
 
284
- # 5. lo que NO se toca — honestidad operativa
285
- report = audit_html(html_text, url, lang='en')
286
- do_not_touch = {
287
- 'img_no_alt': 'we cannot know if the image is decorative: alt="" vs descriptive is a human call',
288
- 'ctrl_name': 'the accessible name requires knowing what the control does',
289
- 'field_label': 'the label text is dictated by the content',
290
- 'contrast_fail': 'picking the new color is a design decision (use a11y_suggest_color)',
291
- 'target_small': 'needs a layout redesign',
292
- 'list_structure': 'rebuilding the markup requires understanding the structure',
293
- }
349
+ # 5. lo que NO se toca — honestidad operativa (bilingüe: el report y los
350
+ # remediation ya llegan en `lang`; el why_not también debe)
351
+ report = audit_html(html_text, url, lang=lang)
352
+ do_not_touch = _DO_NOT_TOUCH.get(lang, _DO_NOT_TOUCH['en'])
294
353
  already = {a['signal'] for a in applied}
295
354
  not_applied = []
296
355
  seen = set()
@@ -306,6 +365,26 @@ def autofix(html_text, lang=None, title=None, url='(html)', form_errors=True):
306
365
  return {'fixed_html': fixed, 'applied': applied, 'not_applied': not_applied}
307
366
 
308
367
 
368
+ _DO_NOT_TOUCH = {
369
+ 'en': {
370
+ 'img_no_alt': 'we cannot know if the image is decorative: alt="" vs descriptive is a human call',
371
+ 'ctrl_name': 'the accessible name requires knowing what the control does',
372
+ 'field_label': 'the label text is dictated by the content',
373
+ 'contrast_fail': 'picking the new color is a design decision (use a11y_suggest_color)',
374
+ 'target_small': 'needs a layout redesign',
375
+ 'list_structure': 'rebuilding the markup requires understanding the structure',
376
+ },
377
+ 'es': {
378
+ 'img_no_alt': 'no podemos saber si la imagen es decorativa: alt="" vs descriptivo es decisión humana',
379
+ 'ctrl_name': 'el nombre accesible exige saber qué hace el control',
380
+ 'field_label': 'el texto de la etiqueta lo dicta el contenido',
381
+ 'contrast_fail': 'elegir el nuevo color es decisión de diseño (usa a11y_suggest_color)',
382
+ 'target_small': 'exige rediseñar el layout',
383
+ 'list_structure': 'reconstruir el marcado exige entender la estructura',
384
+ },
385
+ }
386
+
387
+
309
388
  def _star_nudge_once():
310
389
  """Thank the operator once per machine after a real fix lands — never in
311
390
  CI, never blocking, silence with A11Y_NO_STAR_NUDGE=1. The marker lives in
@@ -335,7 +414,7 @@ def _star_nudge_once():
335
414
  def main(argv):
336
415
  ap = argparse.ArgumentParser(description=__doc__)
337
416
  ap.add_argument('--file', required=True)
338
- ap.add_argument('--lang', choices=['es', 'en', 'pt', 'fr', 'de', 'it', 'gl', 'ca', 'eu'])
417
+ ap.add_argument('--lang', default='en', choices=['en', 'es']) # packs que existen
339
418
  ap.add_argument('--title')
340
419
  ap.add_argument('-o', '--out')
341
420
  a = ap.parse_args(argv)
@@ -65,12 +65,30 @@ MCP_CONFIG = {
65
65
  }
66
66
 
67
67
 
68
+ # BEGIN sin su END (fichero truncado a mano): mensaje claro, nunca un
69
+ # ValueError — el fragmento huérfano se respeta y se añade bloque nuevo
70
+ _MERGE_MSGS = {
71
+ 'es': 'Marcador a11y-toolkit incompleto en AGENTS.md (BEGIN sin END): se '
72
+ 'dejó el fragmento tal cual y se añadió un bloque nuevo y completo.',
73
+ 'en': 'Incomplete a11y-toolkit marker in AGENTS.md (BEGIN without END): '
74
+ 'the fragment was left as-is and a fresh complete block was appended.',
75
+ }
76
+
77
+
68
78
  def merge_block(content):
69
- """Merge the hook block into existing AGENTS.md content (idempotent)."""
70
- if MARKER_BEGIN in content:
71
- start = content.index(MARKER_BEGIN)
79
+ """Merge the hook block into existing AGENTS.md content (idempotent).
80
+
81
+ A BEGIN marker without its END (hand-truncated file) is left untouched
82
+ and a fresh complete block is appended — never a crash."""
83
+ if MARKER_BEGIN in content and MARKER_END in content:
84
+ # anchor the COMPLETE pair: the BEGIN closest before the first END —
85
+ # an orphan BEGIN above it must not clobber the live block
72
86
  end = content.index(MARKER_END) + len(MARKER_END)
87
+ start = content.rindex(MARKER_BEGIN, 0, end - len(MARKER_END))
73
88
  return content[:start] + BLOCK.strip('\n') + content[end:]
89
+ if MARKER_BEGIN in content or MARKER_END in content:
90
+ # malformed marker pair: keep hands off the fragment, append fresh
91
+ return (content.rstrip('\n') + '\n\n') + BLOCK.strip('\n') + '\n'
74
92
  return (content.rstrip('\n') + '\n\n' if content.strip() else '') + BLOCK.strip('\n') + '\n'
75
93
 
76
94
 
@@ -78,11 +96,16 @@ def init(path='.'):
78
96
  """Install the agent hook. Returns dict with what happened."""
79
97
  filepath = os.path.join(path, 'AGENTS.md')
80
98
  previous = open(filepath, encoding='utf-8').read() if os.path.exists(filepath) else ''
99
+ malformed = (MARKER_BEGIN in previous) != (MARKER_END in previous)
81
100
  merged = merge_block(previous)
82
101
  with open(filepath, 'w', encoding='utf-8') as f:
83
102
  f.write(merged)
84
- return {'file': filepath, 'already_present': MARKER_BEGIN in previous,
85
- 'created': not previous.strip()}
103
+ out = {'file': filepath, 'already_present': MARKER_BEGIN in previous,
104
+ 'created': not previous.strip()}
105
+ if malformed:
106
+ out['malformed_marker'] = True
107
+ out['warning'] = _MERGE_MSGS['en']
108
+ return out
86
109
 
87
110
 
88
111
  def main(argv):
@@ -96,6 +119,8 @@ def main(argv):
96
119
  print(json.dumps({'hook_present': present, 'file': target}))
97
120
  return 0 if present else 1
98
121
  res = init(a.path)
122
+ if res.get('malformed_marker'):
123
+ print('! ' + res['warning'])
99
124
  verb = 'updated' if res['already_present'] else ('created' if res['created'] else 'installed into')
100
125
  print(f"✓ agent hook {verb}: {res['file']}")
101
126
  print('\nMCP config (any MCP client that accepts stdio servers):')
@@ -19,6 +19,11 @@ user is not an AI agent (different strategies, habits, patience).
19
19
 
20
20
  CLI:
21
21
  a11yjourney.py friction.json [-o verdict.json] [--lang en]
22
+
23
+ Recommended task kinds (free-form by design; these make baselines comparable):
24
+ sign-up, checkout, password-reset, search, onboarding, settings, data-export.
25
+ The friction catalogue lives in locales/<lang>.json (journey_* keys) —
26
+ community-editable, parity-tested.
22
27
  """
23
28
 
24
29
  import argparse
@@ -47,19 +52,28 @@ def _validate_friction(item, crits, lang='en'):
47
52
  if 'pattern' in item:
48
53
  pat = item['pattern']
49
54
  if pat not in cat:
50
- return None, f"patrón desconocido: {pat} — disponibles: {sorted(cat)}"
55
+ _msg = ('patrón desconocido: {p} — disponibles: {d}'
56
+ if lang == 'es' else
57
+ 'unknown pattern: {p} — available: {d}')
58
+ return None, _msg.format(p=pat, d=sorted(cat))
51
59
  crit, sev, issue, rem = cat[pat]
52
60
  return {'signal': pat, 'criterion': crit, 'severity': sev,
53
61
  'issue': issue, 'remediation': rem}, None
54
62
  crit = str(item.get('criterion', '')).strip()
55
63
  if crit not in crits:
56
- return None, f"criterio fuera del conjunto A/AA 2.2: {crit!r}"
64
+ _msg = ('criterio fuera del conjunto A/AA 2.2: {c!r}'
65
+ if lang == 'es' else 'criterion outside the A/AA 2.2 set: {c!r}')
66
+ return None, _msg.format(c=crit)
57
67
  sev = item.get('severity', 'medium')
58
68
  if sev not in ('high', 'medium', 'low'):
59
- return None, f"severidad inválida: {sev!r} (high|medium|low)"
69
+ _msg = ('severidad inválida: {s!r} (high|medium|low)'
70
+ if lang == 'es' else 'invalid severity: {s!r} (high|medium|low)')
71
+ return None, _msg.format(s=sev)
60
72
  issue = str(item.get('issue', '')).strip()
61
73
  if not issue:
62
- return None, 'fricción sin issue (describe la estructura, nunca cites contenido)'
74
+ return None, ('fricción sin issue (describe la estructura, nunca cites contenido)'
75
+ if lang == 'es' else
76
+ 'friction without issue (describe the structure, never quote content)')
63
77
  return {'signal': item.get('signal', 'journey_custom'), 'criterion': crit,
64
78
  'severity': sev, 'issue': issue,
65
79
  'remediation': str(item.get('remediation', '')).strip()}, None
@@ -158,6 +172,98 @@ def verdict(task, steps, outcome, url='', lang='en'):
158
172
  }
159
173
 
160
174
 
175
+ JOURNEY_FORMAT = 'a11y-journey/1'
176
+
177
+
178
+ def seal_record(task, steps, outcome, url='', lang='en', trace=None):
179
+ """Verdict → the sealed journey record (format `a11y-journey/1`).
180
+
181
+ The open artifact the market keeps describing ("replayable traces" in
182
+ every journey-monitoring pitch) and nobody owns: the walk AND the
183
+ judgment in one envelope — the agent's steps as walked, the outcome,
184
+ the deterministic verdict, and an optional a11ytrace capture — sealed
185
+ with a SHA-256 over the canonical payload. Honesty twice over: the sha
186
+ makes the record tamper-evident, and the scoring is deterministic, so
187
+ `record_verify` can RE-DERIVE the verdict from the stored steps and
188
+ demand it matches. A record is evidence, never conformance."""
189
+ import hashlib
190
+ lang = 'es' if lang == 'es' else 'en'
191
+ v = verdict(task, steps, outcome, url=url, lang=lang)
192
+ if 'error' in v:
193
+ return v
194
+ from .server import VERSION # lazy: server imports this module
195
+ record = {
196
+ 'format': JOURNEY_FORMAT,
197
+ 'engine_version': VERSION,
198
+ 'created_at': datetime.now(timezone.utc).isoformat(timespec='seconds'),
199
+ 'lang': lang,
200
+ 'task': v['task'],
201
+ 'url': v['url'],
202
+ 'steps': steps,
203
+ 'outcome': v['outcome'],
204
+ 'verdict': {'verdict': v['verdict'], 'score': v['score'],
205
+ 'summary': v['summary'], 'findings': v['findings']},
206
+ 'trace': trace,
207
+ 'rules': v['rules'],
208
+ 'score_note': v['score_note'],
209
+ }
210
+ payload = json.dumps(record, sort_keys=True, ensure_ascii=False,
211
+ default=str).encode('utf-8')
212
+ record['sha256'] = hashlib.sha256(payload).hexdigest()
213
+ return record
214
+
215
+
216
+ def _canonical_findings(findings):
217
+ """Language-independent projection of a findings list: the sealed verdict
218
+ must re-derive identically regardless of the VERIFIER's lang — issue and
219
+ remediation are localized catalog text, signal/criterion/severity/step
220
+ are the stable contract."""
221
+ return [(f.get('signal'), f.get('criterion'), f.get('severity'),
222
+ f.get('step')) for f in (findings or [])]
223
+
224
+
225
+ def record_verify(record, lang='en'):
226
+ """Re-derive the verdict from the stored steps and demand it matches.
227
+
228
+ Returns {'status': 'verified'|'tampered'|'invalid', ...}: `tampered`
229
+ means the sha no longer covers the payload OR the deterministic scoring
230
+ of the stored steps no longer produces the stored verdict — either way
231
+ the record cannot be trusted. `invalid` means it is not a record.
232
+
233
+ The record's sealed `lang` wins over the param (a record sealed in es
234
+ verifies from an en session without false 'tampered'); legacy records
235
+ without lang fall back to the param."""
236
+ import hashlib
237
+ lang = 'es' if lang == 'es' else 'en'
238
+ if not isinstance(record, dict) or record.get('format') != JOURNEY_FORMAT \
239
+ or not record.get('sha256'):
240
+ _JR = a11yi18n.pair('journeyrec')
241
+ return {'status': 'invalid',
242
+ 'note': _JR.get(lang, _JR['en']).get('bad_format')}
243
+ eff_lang = record.get('lang') if record.get('lang') in ('es', 'en') else lang
244
+ body = {k: v for k, v in record.items() if k != 'sha256'}
245
+ payload = json.dumps(body, sort_keys=True, ensure_ascii=False,
246
+ default=str).encode('utf-8')
247
+ sha_ok = hashlib.sha256(payload).hexdigest() == record['sha256']
248
+ re_v = verdict(record.get('task', {}), record.get('steps', []),
249
+ record.get('outcome', {}), url=record.get('url', ''),
250
+ lang=eff_lang)
251
+ derived_ok = ('error' not in re_v and isinstance(record.get('verdict'), dict)
252
+ and re_v['verdict'] == record['verdict'].get('verdict')
253
+ and re_v['score'] == record['verdict'].get('score')
254
+ and _canonical_findings(re_v.get('findings'))
255
+ == _canonical_findings(record['verdict'].get('findings')))
256
+ if sha_ok and derived_ok:
257
+ return {'status': 'verified', 'sha256': record['sha256'],
258
+ 'verdict': record['verdict'].get('verdict'),
259
+ 'score': record['verdict'].get('score')}
260
+ return {'status': 'tampered',
261
+ 'sha_intact': sha_ok, 'verdict_reproducible': derived_ok,
262
+ 'recomputed': None if 'error' in re_v
263
+ else {'verdict': re_v['verdict'], 'score': re_v['score'],
264
+ 'findings': re_v['findings']}}
265
+
266
+
161
267
  def budget_init(verdict, url=''):
162
268
  """Verdict → baseline del journey (para comparar tras cada deploy).
163
269