@kinti/a11y-toolkit 5.22.1 → 5.22.3

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 (38) hide show
  1. package/LICENSE +21 -0
  2. package/a11y_toolkit/__init__.py +5 -0
  3. package/a11y_toolkit/a11y.py +117 -0
  4. package/a11y_toolkit/a11yact.py +167 -0
  5. package/a11y_toolkit/a11yaudit.py +1951 -0
  6. package/a11y_toolkit/a11ybadge.py +102 -0
  7. package/a11y_toolkit/a11ybudget.py +122 -0
  8. package/a11y_toolkit/a11ycrit.py +1017 -0
  9. package/a11y_toolkit/a11ydiff.py +192 -0
  10. package/a11y_toolkit/a11ydisprove.py +175 -0
  11. package/a11y_toolkit/a11ydocx.py +132 -0
  12. package/a11y_toolkit/a11ydom.py +1831 -0
  13. package/a11y_toolkit/a11yevidence.py +272 -0
  14. package/a11y_toolkit/a11yfix.py +330 -0
  15. package/a11y_toolkit/a11yi18n.py +100 -0
  16. package/a11y_toolkit/a11yinit.py +113 -0
  17. package/a11y_toolkit/a11yjourney.py +284 -0
  18. package/a11y_toolkit/a11yledger.py +210 -0
  19. package/a11y_toolkit/a11ymutants.py +406 -0
  20. package/a11y_toolkit/a11yopenacr.py +207 -0
  21. package/a11y_toolkit/a11ypdf.py +273 -0
  22. package/a11y_toolkit/a11yroute.py +378 -0
  23. package/a11y_toolkit/a11ysarif.py +139 -0
  24. package/a11y_toolkit/a11yscroll.py +212 -0
  25. package/a11y_toolkit/a11ystatement.py +158 -0
  26. package/a11y_toolkit/a11yvalidate.py +127 -0
  27. package/a11y_toolkit/a11yvpat.py +238 -0
  28. package/a11y_toolkit/a11yvtt.py +136 -0
  29. package/a11y_toolkit/a11ywcag3.py +262 -0
  30. package/a11y_toolkit/a11ywcagem.py +177 -0
  31. package/a11y_toolkit/arialive.js +107 -0
  32. package/a11y_toolkit/arialive_js.py +113 -0
  33. package/a11y_toolkit/contrast.py +536 -0
  34. package/a11y_toolkit/locales/_template.json +468 -0
  35. package/a11y_toolkit/locales/en.json +525 -0
  36. package/a11y_toolkit/locales/es.json +525 -0
  37. package/a11y_toolkit/server.py +1529 -0
  38. package/package.json +7 -2
@@ -0,0 +1,100 @@
1
+ #!/usr/bin/env python3
2
+ """Locale packs — community-editable message catalogs, zero dependencies.
3
+
4
+ The engine's user-facing messages live in `locales/<lang>.json` (one file per
5
+ language, namespaced by module), NOT in Python code. Anyone can add a language:
6
+ copy `locales/_template.json` → `<lang>.json`, translate the values, and the
7
+ validation test (`tests/test_locales.py`) mechanically checks the result —
8
+ same keys as English, same `{placeholders}`, a working CLDR plural rule.
9
+
10
+ Design (documented in docs/i18n.md):
11
+ - **Fallback chain**: a missing key in a pack falls back to English, so a
12
+ half-translated locale degrades gracefully instead of crashing.
13
+ - **Plural rules**: `_meta.plural` is a CLDR-style expression over `n`
14
+ (True → "one", False → "other"). Entries MAY be `{"one": ..., "other": ...}`
15
+ dicts; `plural_entry()` resolves them.
16
+ - **Overlays**: downstream products (e.g. a hosted service) layer their own
17
+ pack ON TOP of the base via `use_overlay(path)` — deep-merged, overlay wins.
18
+ Brand voice without forking the engine.
19
+ """
20
+
21
+ import json
22
+ import os
23
+ import re
24
+
25
+ _LOCALES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'locales')
26
+ _PACKS = {} # lang → pack dict (with overlays applied)
27
+ _OVERLAYS = [] # paths to overlay packs (applied on load)
28
+ _ARGS = re.compile(r'\{([a-zA-Z_][a-zA-Z0-9_]*)\}')
29
+
30
+
31
+ def available():
32
+ """Locale codes present as locale packs (en always present)."""
33
+ codes = {f[:-5] for f in os.listdir(_LOCALES_DIR)
34
+ if f.endswith('.json') and not f.startswith('_')}
35
+ return sorted(codes | {'en'})
36
+
37
+
38
+ def _deep_merge(base, overlay):
39
+ out = dict(base)
40
+ for k, v in overlay.items():
41
+ if isinstance(v, dict) and isinstance(out.get(k), dict):
42
+ out[k] = _deep_merge(out[k], v)
43
+ else:
44
+ out[k] = v
45
+ return out
46
+
47
+
48
+ def _load(lang):
49
+ path = os.path.join(_LOCALES_DIR, f'{lang}.json')
50
+ if not os.path.exists(path):
51
+ return None
52
+ with open(path, encoding='utf-8') as f:
53
+ return json.load(f)
54
+
55
+
56
+ def pack(lang):
57
+ """The full pack for `lang` (cached, overlays applied, en-fallback filled)."""
58
+ if lang not in _PACKS:
59
+ base = _load(lang) or {}
60
+ en = _load('en') or {}
61
+ merged = _deep_merge(en, base) if lang != 'en' else en
62
+ for ov in _OVERLAYS:
63
+ # overlay: {"<lang>": {"<namespace>": {...}}} — la capa gana siempre
64
+ layer = json.load(open(ov, encoding='utf-8'))
65
+ merged = _deep_merge(merged, layer.get(lang, {}))
66
+ _PACKS[lang] = merged
67
+ return _PACKS[lang]
68
+
69
+
70
+ def use_overlay(path):
71
+ """Register an overlay pack (applies to every subsequently loaded pack)."""
72
+ global _PACKS
73
+ _OVERLAYS.append(path)
74
+ _PACKS = {} # invalidate cache
75
+
76
+
77
+ def pair(namespace):
78
+ """Namespace catalog in the `{'es': ..., 'en': ...}` shape the engine uses."""
79
+ return {lang: pack(lang).get(namespace, {}) for lang in ('es', 'en')}
80
+
81
+
82
+ def plural_category(lang, n):
83
+ """'one' or 'other' per the locale's `_meta.plural` CLDR expression."""
84
+ rule = pack(lang).get('_meta', {}).get('plural', 'n != 1')
85
+ try:
86
+ return 'one' if eval(rule, {'__builtins__': {}}, {'n': n}) else 'other' # noqa: S307
87
+ except Exception:
88
+ return 'other'
89
+
90
+
91
+ def plural_entry(value, lang, n):
92
+ """Resolve a `{"one": ..., "other": ...}` entry; plain strings pass through."""
93
+ if isinstance(value, dict) and {'one', 'other'} & set(value):
94
+ return value.get(plural_category(lang, n), value.get('other', ''))
95
+ return value
96
+
97
+
98
+ def placeholders(text):
99
+ """Named `{args}` a message expects — used by the validation test."""
100
+ return set(_ARGS.findall(text or ''))
@@ -0,0 +1,113 @@
1
+ #!/usr/bin/env python3
2
+ """`a11ytoolkit init` — installs the agent hook in the current project.
3
+
4
+ Writes (or updates, idempotently) an AGENTS.md block that tells coding agents
5
+ the one rule that matters: after any UI change, re-audit accessibility before
6
+ calling the work done — with the exact commands to do it. Also prints the MCP
7
+ config block and the optional skill install step.
8
+
9
+ Offline by design: no network, no filesystem assumptions beyond AGENTS.md.
10
+ """
11
+
12
+ import argparse
13
+ import json
14
+ import os
15
+ import sys
16
+
17
+ MARKER_BEGIN = '<!-- BEGIN a11y-toolkit agent hook -->'
18
+ MARKER_END = '<!-- END a11y-toolkit agent hook -->'
19
+
20
+ BLOCK = f'''{MARKER_BEGIN}
21
+
22
+ ## Accessibility guardrails — a11y-toolkit
23
+
24
+ After any UI change (HTML, CSS, templates, components, copy that becomes
25
+ visible text), run an accessibility audit BEFORE considering the work done.
26
+ The audit is part of the change, not an afterthought.
27
+
28
+ Quick loop (no install needed — uvx runs it from PyPI):
29
+
30
+ ```bash
31
+ uvx --from a11y-toolkit a11ytoolkit audit --file path/to/page.html # static, 0-100 score
32
+ uvx --from a11y-toolkit a11ytoolkit audit --url https://localhost:3000
33
+ ```
34
+
35
+ Acting on findings:
36
+
37
+ 1. `high` and `medium` findings block the change: apply the remediation each
38
+ finding carries, then re-audit until clear (or document why it stays).
39
+ 2. Judgment findings (alt text wording, which color to pick) are HUMAN calls:
40
+ propose an option, never invent final copy. The tool marks them as
41
+ `not_applied` with the reason — that is by design.
42
+ 3. Ask `uvx --from a11y-toolkit a11ytoolkit criterion --signal <id>` when a
43
+ finding's signal needs explaining (it returns the criterion, the official
44
+ W3C Understanding link and the published ACT rule, if any).
45
+
46
+ If the a11y-toolkit MCP server is connected, prefer the `a11y_*` tools — same
47
+ engine, richer output. Before deploys, snapshot + diff catches regressions:
48
+
49
+ ```bash
50
+ uvx --from a11y-toolkit a11ytoolkit snapshot https://staging --out before.json
51
+ # ...deploy...
52
+ uvx --from a11y-toolkit a11ytoolkit diff before.json <(uvx --from a11y-toolkit a11ytoolkit snapshot https://staging)
53
+ ```
54
+
55
+ {MARKER_END}
56
+ '''
57
+
58
+ MCP_CONFIG = {
59
+ 'mcpServers': {
60
+ 'a11y-toolkit': {
61
+ 'command': 'uvx',
62
+ 'args': ['--from', 'a11y-toolkit', 'a11y-toolkit-mcp'],
63
+ }
64
+ }
65
+ }
66
+
67
+
68
+ 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)
72
+ end = content.index(MARKER_END) + len(MARKER_END)
73
+ return content[:start] + BLOCK.strip('\n') + content[end:]
74
+ return (content.rstrip('\n') + '\n\n' if content.strip() else '') + BLOCK.strip('\n') + '\n'
75
+
76
+
77
+ def init(path='.'):
78
+ """Install the agent hook. Returns dict with what happened."""
79
+ filepath = os.path.join(path, 'AGENTS.md')
80
+ previous = open(filepath, encoding='utf-8').read() if os.path.exists(filepath) else ''
81
+ merged = merge_block(previous)
82
+ with open(filepath, 'w', encoding='utf-8') as f:
83
+ f.write(merged)
84
+ return {'file': filepath, 'already_present': MARKER_BEGIN in previous,
85
+ 'created': not previous.strip()}
86
+
87
+
88
+ def main(argv):
89
+ ap = argparse.ArgumentParser(description=__doc__)
90
+ ap.add_argument('path', nargs='?', default='.', help='project directory (default: current)')
91
+ ap.add_argument('--check', action='store_true', help='only report whether the hook is present')
92
+ a = ap.parse_args(argv)
93
+ if a.check:
94
+ target = os.path.join(a.path, 'AGENTS.md')
95
+ present = os.path.exists(target) and MARKER_BEGIN in open(target, encoding='utf-8').read()
96
+ print(json.dumps({'hook_present': present, 'file': target}))
97
+ return 0 if present else 1
98
+ res = init(a.path)
99
+ verb = 'updated' if res['already_present'] else ('created' if res['created'] else 'installed into')
100
+ print(f"✓ agent hook {verb}: {res['file']}")
101
+ print('\nMCP config (any MCP client that accepts stdio servers):')
102
+ print(json.dumps(MCP_CONFIG, indent=2))
103
+ print('\nOptional — the agent skill (audit→fix→document→watch loop):')
104
+ print(' curl -fsSL https://raw.githubusercontent.com/kinti/a11y-toolkit/main/skills/install-skill.sh | bash')
105
+ return 0
106
+
107
+
108
+ if __name__ == '__main__':
109
+ sys.exit(main(sys.argv[1:]))
110
+
111
+ # alias para el dispatcher del hub CLI (convención *_main)
112
+ def init_main(argv):
113
+ return main(argv)
@@ -0,0 +1,284 @@
1
+ #!/usr/bin/env python3
2
+ """Blindfold journey testing — the agent IS the non-visual user.
3
+
4
+ The idea no other accessibility tool has: instead of checking rules, the AI
5
+ coding agent attempts a REAL task ("sign up", "find the price and add to
6
+ cart") perceiving only what a screen reader exposes — the linearized
7
+ accessibility tree — and acting only by accessible name and keyboard. Every
8
+ point of friction it meets is logged against a WCAG criterion. This module
9
+ turns that friction log into a deterministic, scored, evidence-ready verdict.
10
+
11
+ Division of labor:
12
+ - the PROMPT (blindfold-task) drives the perceive→act→log loop in the agent;
13
+ - this module judges it: fixed scoring rules, bilingual remediations,
14
+ criterion validation against the 55 A/AA set, pack-ready output.
15
+
16
+ Honesty: a pass means ONE task was completable non-visually by an AI agent on
17
+ one URL. It is usability evidence, never conformance — a human screen-reader
18
+ user is not an AI agent (different strategies, habits, patience).
19
+
20
+ CLI:
21
+ a11yjourney.py friction.json [-o verdict.json] [--lang en]
22
+ """
23
+
24
+ import argparse
25
+ import json
26
+ import sys
27
+ from datetime import datetime, timezone
28
+ from . import a11yi18n
29
+
30
+ # Friction catalogue: the recurring ways a task breaks non-visually, each with
31
+ # its criterion and bilingual remediation. The agent logs `pattern` keys from
32
+ # here (or raw criterion+issue for anything rarer). Parity-tested like every
33
+ # other catalog in this toolkit.
34
+ _J = a11yi18n.pair('journey') # locales/<lang>.json — community-editable
35
+
36
+ _RULES = {'start': 100, 'high': 25, 'medium': 12, 'low': 5, 'pass_threshold': 85}
37
+
38
+
39
+ def _crit_set():
40
+ from a11y_toolkit.a11ycrit import _C
41
+ return {k for k, v in _C.items() if v[0] in ('A', 'AA')}
42
+
43
+
44
+ def _validate_friction(item, crits, lang='en'):
45
+ """Expand a friction item (pattern key or raw criterion) → dict, or None+error."""
46
+ cat = _J['es' if lang == 'es' else 'en']
47
+ if 'pattern' in item:
48
+ pat = item['pattern']
49
+ if pat not in cat:
50
+ return None, f"patrón desconocido: {pat} — disponibles: {sorted(cat)}"
51
+ crit, sev, issue, rem = cat[pat]
52
+ return {'signal': pat, 'criterion': crit, 'severity': sev,
53
+ 'issue': issue, 'remediation': rem}, None
54
+ crit = str(item.get('criterion', '')).strip()
55
+ if crit not in crits:
56
+ return None, f"criterio fuera del conjunto A/AA 2.2: {crit!r}"
57
+ sev = item.get('severity', 'medium')
58
+ if sev not in ('high', 'medium', 'low'):
59
+ return None, f"severidad inválida: {sev!r} (high|medium|low)"
60
+ issue = str(item.get('issue', '')).strip()
61
+ if not issue:
62
+ return None, 'fricción sin issue (describe la estructura, nunca cites contenido)'
63
+ return {'signal': item.get('signal', 'journey_custom'), 'criterion': crit,
64
+ 'severity': sev, 'issue': issue,
65
+ 'remediation': str(item.get('remediation', '')).strip()}, None
66
+
67
+
68
+ def verdict(task, steps, outcome, url='', lang='en'):
69
+ """Friction log → deterministic journey verdict (pack-ready report shape)."""
70
+ lang = 'es' if lang == 'es' else 'en'
71
+ if not isinstance(task, dict) or not str(task.get('goal', '')).strip():
72
+ return {'error': 'task.goal is required (what task the agent attempted)'}
73
+ if not isinstance(steps, list):
74
+ return {'error': 'steps must be a list of steps'}
75
+ if not isinstance(outcome, dict):
76
+ return {'error': 'outcome must be an object'}
77
+
78
+ crits = _crit_set()
79
+ findings, errors = [], []
80
+ for i, step in enumerate(steps):
81
+ if not isinstance(step, dict):
82
+ errors.append(f'step[{i}] no es un objeto')
83
+ continue
84
+ f = step.get('friction')
85
+ if not f:
86
+ continue
87
+ items = f if isinstance(f, list) else [f]
88
+ for item in items:
89
+ if not isinstance(item, dict):
90
+ errors.append(f'step[{i}].friction no es un objeto')
91
+ continue
92
+ conv, err = _validate_friction(item, crits, lang=lang)
93
+ if err:
94
+ errors.append(f'step[{i}]: {err}')
95
+ continue
96
+ conv['step'] = i
97
+ conv.setdefault('perceived', str(step.get('perceived', ''))[:120] or None)
98
+ findings.append(conv)
99
+
100
+ if errors:
101
+ return {'error': 'log de fricción inválido', 'details': errors}
102
+
103
+ high = sum(1 for x in findings if x['severity'] == 'high')
104
+ medium = sum(1 for x in findings if x['severity'] == 'medium')
105
+ low = sum(1 for x in findings if x['severity'] == 'low')
106
+
107
+ score = _RULES['start'] - high * _RULES['high'] - medium * _RULES['medium'] - low * _RULES['low']
108
+ score = max(0, score)
109
+ def _bool(v):
110
+ if isinstance(v, bool):
111
+ return v
112
+ if isinstance(v, str):
113
+ return v.strip().lower() == 'true'
114
+ return bool(v)
115
+
116
+ completed = _bool(outcome.get('completed'))
117
+ gave_up = _bool(outcome.get('gave_up'))
118
+ workaround = _bool(outcome.get('workaround_used'))
119
+ if workaround:
120
+ score = max(0, score - 15)
121
+
122
+ if gave_up:
123
+ verdict = 'blocked'
124
+ elif not completed:
125
+ verdict = 'fail'
126
+ elif (not workaround and high == 0 and score >= _RULES['pass_threshold']):
127
+ verdict = 'pass'
128
+ else:
129
+ verdict = 'partial'
130
+
131
+ note = ('Task-based usability evidence: ONE task attempted by an AI agent '
132
+ 'perceiving only the accessibility tree, on this URL. A pass means '
133
+ 'the task was completable non-visually by the agent — it is not a '
134
+ 'conformance claim and not a substitute for a human screen-reader '
135
+ 'user. The friction list is the handoff to the human half.'
136
+ if lang == 'en' else
137
+ 'Evidencia de usabilidad por tareas: UNA tarea intentada por un '
138
+ 'agente de IA percibiendo solo el árbol de accesibilidad, en esta '
139
+ 'URL. Un pase significa que el agente completó la tarea sin vista; '
140
+ 'no es una declaración de conformidad ni sustituye a una persona '
141
+ 'usuaria de lector de pantalla. La lista de fricción es el puente '
142
+ 'hacia la mitad humana.')
143
+
144
+ return {
145
+ 'mode': 'journey',
146
+ 'url': url,
147
+ 'task': {'goal': str(task['goal'])[:200], 'kind': str(task.get('kind', 'custom'))},
148
+ 'steps_count': len(steps),
149
+ 'outcome': {'completed': completed, 'gave_up': gave_up, 'workaround_used': workaround,
150
+ 'notes': str(outcome.get('notes', ''))[:300] or None},
151
+ 'verdict': verdict,
152
+ 'score': score,
153
+ 'findings': findings,
154
+ 'summary': {'high': high, 'medium': medium, 'low': low},
155
+ 'rules': dict(_RULES, workaround_penalty=15,
156
+ note='deterministic: start 100, minus friction, minus 15 if only reachable via workaround'),
157
+ 'score_note': note,
158
+ }
159
+
160
+
161
+ def budget_init(verdict, url=''):
162
+ """Verdict → baseline del journey (para comparar tras cada deploy).
163
+
164
+ La clave de fricción es `criterio:señal` — los IDs de señal son estables
165
+ por diseño (D3), así que el baseline sigue siendo válido entre versiones
166
+ del motor."""
167
+ if not isinstance(verdict, dict) or verdict.get('verdict') is None:
168
+ return {'error': 'not a journey verdict (use a11y_journey_verdict)'}
169
+ return {
170
+ 'format': 'a11y-journey-budget/1',
171
+ 'task': verdict.get('task', {}),
172
+ 'url': verdict.get('url', url),
173
+ 'verdict': verdict['verdict'],
174
+ 'score': verdict.get('score'),
175
+ 'friction': sorted({f"{f['criterion']}:{f['signal']}" for f in verdict.get('findings', [])}),
176
+ 'generated': datetime.now(timezone.utc).isoformat(),
177
+ }
178
+
179
+
180
+ def budget_compare(baseline, verdict):
181
+ """Solo la fricción NUEVA bloquea — la regresión de USABILIDAD, no ya de reglas.
182
+
183
+ NO-GO si: aparece fricción alta nueva, o la tarea degradó su veredicto
184
+ (pass→partial/fail/blocked). La fricción nueva media/baja avisa, no bloquea."""
185
+ if not isinstance(baseline, dict) or baseline.get('format') != 'a11y-journey-budget/1':
186
+ return {'error': 'baseline inválida (usa budget_init)'}
187
+ if not isinstance(verdict, dict) or verdict.get('verdict') is None:
188
+ return {'error': 'not a journey verdict'}
189
+ if baseline.get('task', {}).get('goal') != verdict.get('task', {}).get('goal'):
190
+ return {'error': "el baseline es de OTRA tarea: %r vs %r" % (
191
+ baseline.get('task', {}).get('goal'), verdict.get('task', {}).get('goal'))}
192
+
193
+ base = set(baseline.get('friction', []))
194
+ _rank = {'high': 2, 'medium': 1, 'low': 0}
195
+ current = {}
196
+ for f in verdict.get('findings', []):
197
+ k = f"{f['criterion']}:{f['signal']}"
198
+ prev = current.get(k)
199
+ # colisión clave→severidad MÁS grave (dos custom sobre el mismo
200
+ # criterio no pueden esconder una high tras una medium)
201
+ if prev is None or _rank[f['severity']] > _rank[prev['severity']]:
202
+ current[k] = f
203
+ new_f = sorted(set(current) - base)
204
+ resolved = sorted(base - set(current))
205
+ new_high = [k for k in new_f if current[k]['severity'] == 'high']
206
+ degrades = (baseline.get('verdict') == 'pass'
207
+ and verdict['verdict'] in ('partial', 'fail', 'blocked'))
208
+
209
+ go = not new_high and not degrades
210
+ return {
211
+ 'verdict': 'GO' if go else 'NO-GO',
212
+ 'new_blocking': new_high,
213
+ 'new_friction': new_f,
214
+ 'resolved': resolved,
215
+ 'verdict_before': baseline.get('verdict'),
216
+ 'verdict_after': verdict['verdict'],
217
+ 'degraded': degrades,
218
+ 'score_before': baseline.get('score'),
219
+ 'score_after': verdict.get('score'),
220
+ 'note': ('task-based regression gate: only NEW high friction (or a '
221
+ 'pass degrading) blocks the deploy' if go else
222
+ 'the task got harder to complete without sight — fix before deploy'),
223
+ }
224
+
225
+
226
+ def _budget_main(argv):
227
+ ap = argparse.ArgumentParser(description='journey budget: only NEW friction blocks')
228
+ ap.add_argument('verdict', help='verdict JSON from a11y_journey_verdict')
229
+ ap.add_argument('--init', action='store_true', help='create the baseline')
230
+ ap.add_argument('--budget', default='journey-budget.json')
231
+ ap.add_argument('-o', '--out', help='write the result here (default: stdout)')
232
+ a = ap.parse_args(argv)
233
+ with open(a.verdict, encoding='utf-8') as f:
234
+ v = json.load(f)
235
+ if a.init:
236
+ b = budget_init(v)
237
+ if 'error' in b:
238
+ print(json.dumps(b, ensure_ascii=False))
239
+ return 1
240
+ out = json.dumps(b, ensure_ascii=False, indent=1)
241
+ target = a.out or a.budget
242
+ with open(target, 'w', encoding='utf-8') as f:
243
+ f.write(out + '\n')
244
+ print(json.dumps({'budget': target, 'friction': len(b.get('friction', [])),
245
+ 'verdict': b.get('verdict')}))
246
+ return 0
247
+ with open(a.budget, encoding='utf-8') as f:
248
+ b = json.load(f)
249
+ res = budget_compare(b, v)
250
+ out = json.dumps(res, ensure_ascii=False, indent=1)
251
+ if a.out:
252
+ with open(a.out, 'w', encoding='utf-8') as f:
253
+ f.write(out + '\n')
254
+ print(out)
255
+ if 'error' in res:
256
+ return 1 # error de uso ≠ NO-GO de regresión
257
+ return 0 if res.get('verdict') == 'GO' else 2
258
+
259
+
260
+ def main(argv):
261
+ if argv and ('--init' in argv or '--budget' in argv):
262
+ return _budget_main(argv)
263
+ ap = argparse.ArgumentParser(description=__doc__)
264
+ ap.add_argument('log', help='JSON friction log: {task, steps, outcome, url?, lang?}')
265
+ ap.add_argument('-o', '--out', help='escribe el veredicto en fichero')
266
+ ap.add_argument('--lang', default='en', choices=['en', 'es'])
267
+ a = ap.parse_args(argv)
268
+ with open(a.log, encoding='utf-8') as f:
269
+ d = json.load(f)
270
+ res = verdict(d.get('task', {}), d.get('steps', []), d.get('outcome', {}),
271
+ url=d.get('url', ''), lang=a.lang or d.get('lang', 'en'))
272
+ out = json.dumps(res, ensure_ascii=False, indent=1)
273
+ if a.out:
274
+ with open(a.out, 'w', encoding='utf-8') as f:
275
+ f.write(out + '\n')
276
+ print(json.dumps({'verdict': res.get('verdict'), 'score': res.get('score'),
277
+ 'out': a.out}))
278
+ else:
279
+ print(out)
280
+ return 0
281
+
282
+
283
+ if __name__ == '__main__':
284
+ sys.exit(main(sys.argv[1:]))