@kinti/a11y-toolkit 5.22.3 → 5.24.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.
@@ -29,6 +29,7 @@
29
29
  a11ytoolkit route --goal "gate my PR" # which tools for the task
30
30
  a11ytoolkit route --file page.html # diagnosis: read the page, order the exams
31
31
  a11ytoolkit mutants --seed 7 --n 12 # the engine's sealed self-exam
32
+ a11ytoolkit fingerprints page1.html page2.html --dir p/ # twin-page detection (one audit per template)
32
33
  """
33
34
 
34
35
  import sys
@@ -47,6 +48,7 @@ from . import a11ycrit
47
48
  from . import a11ydiff
48
49
  from . import a11ysarif
49
50
  from . import a11ywcagem
51
+ from . import a11yplan
50
52
  from . import contrast
51
53
  from . import a11ystatement
52
54
  from . import a11yjourney
@@ -59,6 +61,7 @@ from . import a11yinit
59
61
  from . import a11ywcag3
60
62
  from . import a11yroute
61
63
  from . import a11ymutants
64
+ from . import a11yfingerprints
62
65
 
63
66
  SUBCOMMANDS = {
64
67
  'pair': (contrast, 'pair'),
@@ -70,6 +73,7 @@ SUBCOMMANDS = {
70
73
  'criterion': (a11ycrit, None),
71
74
  'sarif': (a11ysarif, None),
72
75
  'wcagem': (a11ywcagem, None),
76
+ 'plan': (a11yplan, None),
73
77
  'fix': (a11yfix, None),
74
78
  'kbd': (a11ydom, 'kbd_main'),
75
79
  'scroll': (a11yscroll, None),
@@ -93,6 +97,7 @@ SUBCOMMANDS = {
93
97
  'wcag3': (a11ywcag3, None),
94
98
  'route': (a11yroute, None),
95
99
  'mutants': (a11ymutants, None),
100
+ 'fingerprints': (a11yfingerprints, None),
96
101
  }
97
102
 
98
103
 
@@ -0,0 +1,270 @@
1
+ #!/usr/bin/env python3
2
+ """a11y_fingerprints — multi-hash template fingerprints (twin-page detection).
3
+
4
+ Cross-industry translation: multi-hash identification. One hash of a page
5
+ breaks the moment a csrf token or a timestamp changes; several independent
6
+ hashes over DIFFERENT normalizations identify by intersection — a template
7
+ stays recognizable when its volatile parts change, and the view that
8
+ diverges tells what KIND of change it was.
9
+
10
+ Three views of the document, text always excluded (content varies per page;
11
+ that is the point):
12
+ structure tag + depth — the skeleton (defines the template)
13
+ classes + sorted class list — the skin (design-system change)
14
+ attributes + stable attributes — real attribute changes, with the
15
+ id-referencing / volatile attrs excluded by design (id, for,
16
+ name, href, src, …) so per-page ids and csrf tokens can never
17
+ split a template
18
+
19
+ Regions: the landmark containers (header/nav/main/aside/footer) plus
20
+ `document` for everything outside them. Each (view, region) → sha256[:12].
21
+
22
+ Template = the complete structure view (same skeleton = same template — a
23
+ declared rule, not fuzzy similarity). Inside a template every page is
24
+ compared view-by-view against the representative (the lexicographically
25
+ smallest page id); each mismatch is a localized {page, region, view} entry:
26
+ "header diverges in classes, footer identical".
27
+
28
+ sample_suggestion = one representative per template, the structured-sample
29
+ helper for WCAG-EM Step 3. The evaluator still owns the sample; identical
30
+ structure does not guarantee identical findings after rendering.
31
+
32
+ CLI:
33
+ a11yfingerprints.py page1.html page2.html [--dir pages/] [--lang es] [-o out.json]
34
+ """
35
+
36
+ import argparse
37
+ import hashlib
38
+ import json
39
+ import os
40
+ import sys
41
+ from html.parser import HTMLParser
42
+
43
+ VIEWS = ('structure', 'classes', 'attributes')
44
+
45
+ # landmarks que abren región propia; lo que queda fuera vive en 'document'
46
+ _REGIONS = ('header', 'nav', 'main', 'aside', 'footer')
47
+
48
+ # attrs volátiles por construcción: referencian ids únicos por página o
49
+ # cambian con cada petición — si entraran en una vista, partirían plantillas
50
+ # falsamente (el csrf/token/per-page-id NO es un rediseño)
51
+ _VOLATILE = frozenset((
52
+ 'id', 'for', 'name', 'href', 'src', 'srcset', 'action', 'headers',
53
+ 'list', 'style', 'value', 'aria-controls', 'aria-describedby',
54
+ 'aria-labelledby', 'aria-owns', 'aria-details', 'aria-errormessage',
55
+ ))
56
+
57
+ _VOID = frozenset(('area', 'base', 'br', 'col', 'embed', 'hr', 'img',
58
+ 'input', 'link', 'meta', 'param', 'source', 'track',
59
+ 'wbr', 'path', 'circle', 'rect', 'line', 'polyline',
60
+ 'polygon', 'ellipse', 'stop', 'use'))
61
+
62
+ # vistas que se comparan dentro de una plantilla (structure NO puede divergir
63
+ # por definición — es la clave de agrupación)
64
+ _DIVERGENCE_VIEWS = ('classes', 'attributes')
65
+
66
+ _NOTES = {
67
+ 'en': ('Suggests a structured sample: one representative per detected '
68
+ 'template (WCAG-EM Step 3 helper). The evaluator still owns sample '
69
+ 'selection; identical structure does not guarantee identical '
70
+ 'findings after rendering. Volatile attributes (per-page ids, '
71
+ 'urls, tokens) are excluded by design so they cannot split '
72
+ 'templates.'),
73
+ 'es': ('Sugiere una muestra estructurada: un representante por plantilla '
74
+ 'detectada (ayudante del paso 3 de WCAG-EM). El evaluador sigue '
75
+ 'siendo dueño de la selección; estructura idéntica no garantiza '
76
+ 'hallazgos idénticos tras el render. Los atributos volátiles '
77
+ '(ids por página, urls, tokens) se excluyen a propósito para que '
78
+ 'no puedan partir plantillas.'),
79
+ }
80
+
81
+
82
+ def _digest(lines):
83
+ return hashlib.sha256('\n'.join(lines).encode('utf-8')).hexdigest()[:12]
84
+
85
+
86
+ class _Serializer(HTMLParser):
87
+ """Serializa el documento a 3 vistas × regiones. Tolerante al HTML hostil:
88
+ cierres sin apertura, anidación imposible y attrs duplicados no rompen
89
+ nada (el parser de stdlib ya de-duplica attrs; los cierres huérfanos se
90
+ ignoran, los abiertos sin cerrar se limpian al final)."""
91
+
92
+ def __init__(self):
93
+ super().__init__(convert_charrefs=True)
94
+ self.lines = {v: {} for v in VIEWS} # view -> region -> [lines]
95
+ self._stack = [] # [(tag, era_landmark_antes)]
96
+ self._landmarks = [] # landmarks abiertos (externo→interno)
97
+
98
+ # región vigente: el landmark MÁS EXTERNO abierto; si ninguno, 'document'
99
+ def _region(self):
100
+ return self._landmarks[0] if self._landmarks else 'document'
101
+
102
+ def _close_landmark(self, tag):
103
+ """Cierra el landmark MÁS RECIENTE de ese tag (LIFO, como el stack).
104
+ remove() a secas borraría el primero y corrompería el orden
105
+ externo→interno con landmarks anidados del mismo tipo."""
106
+ for i in range(len(self._landmarks) - 1, -1, -1):
107
+ if self._landmarks[i] == tag:
108
+ del self._landmarks[i]
109
+ return
110
+
111
+ def _emit(self, tag, attrs, depth):
112
+ region = self._region()
113
+ cls = sorted((attrs.get('class') or '').split())
114
+ # sin \n/\r en los valores: un attr hostil no puede falsificar
115
+ # líneas del material que se hashea (dos documentos distintos, un
116
+ # mismo digest sería una divergencia perdida)
117
+ stable = sorted('{}={}'.format(k, v.replace('\n', ' ').replace('\r', ' '))
118
+ for k, v in attrs.items()
119
+ if k not in _VOLATILE and k != 'class')
120
+ for view, extra in (('structure', ''),
121
+ ('classes', ' .' + '.'.join(cls) if cls else ''),
122
+ ('attributes', ' ' + ' '.join(stable) if stable else '')):
123
+ self.lines[view].setdefault(region, []).append(
124
+ '{} {}{}'.format(depth, tag, extra))
125
+
126
+ def handle_starttag(self, tag, attrs):
127
+ tag = tag.lower()
128
+ adict = {}
129
+ for k, v in attrs: # parser stdlib ya deduplica,
130
+ adict.setdefault(k, v or '') # pero no perdemos nada siendo explícitos
131
+ depth = len(self._stack)
132
+ if tag in _REGIONS:
133
+ # el propio landmark pertenece a SU región: abre antes de emitir
134
+ # (append: el PRIMERO de la lista es el más externo → _region())
135
+ self._landmarks.append(tag)
136
+ self._emit(tag, adict, depth)
137
+ if tag not in _VOID:
138
+ self._stack.append(tag)
139
+
140
+ def handle_startendtag(self, tag, attrs):
141
+ # <tag/> autocontenido: emite sin apilar (el mismo elemento, una vez)
142
+ self.handle_starttag(tag, attrs)
143
+ if self._stack and self._stack[-1] == tag and tag not in _VOID:
144
+ self._stack.pop()
145
+ if tag in self._landmarks:
146
+ self._close_landmark(tag)
147
+
148
+ def handle_endtag(self, tag):
149
+ tag = tag.lower()
150
+ if tag in self._stack:
151
+ # pop hasta el cierre correcto; lo que quede abierto fuera se ignora
152
+ while self._stack:
153
+ open_tag = self._stack.pop()
154
+ if open_tag in _REGIONS:
155
+ self._close_landmark(open_tag)
156
+ if open_tag == tag:
157
+ break
158
+ elif tag in _REGIONS and tag in self._landmarks:
159
+ self._close_landmark(tag)
160
+
161
+
162
+ def fingerprint_html(html_text):
163
+ """html (str) → {hashes: {view: {region: digest}}, template, regions}.
164
+
165
+ Determinista: mismas vistas, mismo sha, sin red ni azar."""
166
+ s = _Serializer()
167
+ try:
168
+ s.feed(html_text or '')
169
+ s.close()
170
+ except Exception:
171
+ pass # el parser stdlib no lanza con entrada hostil, pero si algo
172
+ # escapa, lo YA serializado sigue siendo un fingerprint válido
173
+ hashes = {v: {r: _digest(ls) for r, ls in s.lines[v].items()}
174
+ for v in VIEWS}
175
+ structure = hashes['structure']
176
+ template = 't-' + hashlib.sha256(
177
+ '|'.join('{}:{}'.format(r, structure[r]) for r in sorted(structure))
178
+ .encode('utf-8')).hexdigest()[:8]
179
+ return {'hashes': hashes, 'template': template,
180
+ 'regions': sorted(structure)}
181
+
182
+
183
+ def fingerprint_pages(pages, lang='en'):
184
+ """pages: [{'page': id, 'html': str}] → informe completo.
185
+
186
+ Agrupa por plantilla (vista structure), localiza la divergencia vista a
187
+ vista contra el representante (id lexicográfico mínimo — regla
188
+ declarada) y sugiere una muestra de un representante por plantilla
189
+ (ayudante del paso 3 de WCAG-EM; el evaluador decide)."""
190
+ if not isinstance(pages, list) or not all(
191
+ isinstance(p, dict) and 'page' in p and 'html' in p for p in pages):
192
+ raise ValueError('pages must be a list of {page, html} dicts')
193
+
194
+ entries = []
195
+ for p in pages:
196
+ fp = fingerprint_html(p['html'])
197
+ entries.append({'page': p['page'], 'hashes': fp['hashes'],
198
+ 'regions': fp['regions'], 'template': fp['template']})
199
+
200
+ groups = {}
201
+ for e in entries:
202
+ groups.setdefault(e['template'], []).append(e)
203
+
204
+ templates = []
205
+ for tid in sorted(groups):
206
+ members = sorted(groups[tid], key=lambda e: e['page'])
207
+ rep = members[0]
208
+ rep_h = rep['hashes']
209
+ divergence = []
210
+ for m in members[1:]:
211
+ for view in _DIVERGENCE_VIEWS:
212
+ regions = set(rep_h[view]) | set(m['hashes'][view])
213
+ for r in sorted(regions):
214
+ if rep_h[view].get(r) != m['hashes'][view].get(r):
215
+ divergence.append({'page': m['page'],
216
+ 'region': r, 'view': view})
217
+ templates.append({
218
+ 'template': tid,
219
+ 'pages': [m['page'] for m in members],
220
+ 'page_count': len(members),
221
+ 'representative': rep['page'],
222
+ 'divergence': divergence,
223
+ })
224
+
225
+ return {
226
+ 'mode': 'template-fingerprints',
227
+ 'pages_total': len(entries),
228
+ 'templates_total': len(templates),
229
+ 'views': list(VIEWS),
230
+ 'volatile_attrs_ignored': sorted(_VOLATILE),
231
+ 'pages': entries,
232
+ 'templates': templates,
233
+ 'sample_suggestion': sorted(t['representative'] for t in templates),
234
+ 'note': _NOTES['es' if lang == 'es' else 'en'],
235
+ }
236
+
237
+
238
+ def main(argv):
239
+ ap = argparse.ArgumentParser(description=__doc__)
240
+ ap.add_argument('pages', nargs='*', help='HTML pages to fingerprint')
241
+ ap.add_argument('--dir', help='also read every *.html/*.htm in this '
242
+ 'directory (sorted)')
243
+ ap.add_argument('--lang', default='en', choices=['en', 'es'])
244
+ ap.add_argument('-o', '--out', help='also write the report to this file')
245
+ a = ap.parse_args(argv)
246
+
247
+ names = list(a.pages)
248
+ if a.dir:
249
+ for f in sorted(os.listdir(a.dir)):
250
+ if f.lower().endswith(('.html', '.htm')):
251
+ names.append(os.path.join(a.dir, f))
252
+ if not names:
253
+ ap.error('no pages: pass pages and/or --dir')
254
+
255
+ pages = []
256
+ for name in names:
257
+ with open(name, encoding='utf-8', errors='replace') as f:
258
+ pages.append({'page': name, 'html': f.read()})
259
+
260
+ report = fingerprint_pages(pages, lang=a.lang)
261
+ text = json.dumps(report, ensure_ascii=False, indent=1)
262
+ if a.out:
263
+ with open(a.out, 'w', encoding='utf-8') as f:
264
+ f.write(text + '\n')
265
+ print(text)
266
+ return 0
267
+
268
+
269
+ if __name__ == '__main__':
270
+ sys.exit(main(sys.argv[1:]))
@@ -0,0 +1,214 @@
1
+ #!/usr/bin/env python3
2
+ """Remediation plan — turn a findings list into an ordered ROUTE.
3
+
4
+ An inventory of 40 findings overwhelms; nobody answers "in what order?".
5
+ Planning matters because fixes change the cost of other fixes: semantic
6
+ infrastructure (headings, landmarks, labels) makes later work cheaper, one
7
+ design-token decision kills many contrast findings at once, and instances
8
+ on a page headed for redesign are wasted minutes. Cross-industry origin:
9
+ planning over evolving state (candidate-generation MDPs, arXiv 2607.02115)
10
+ — translated here into a deterministic, auditable heuristic. No ML, no
11
+ network: batches, declared phases, declared minute assumptions, a root
12
+ seal. The human reorders; the plan is evidence, not an oracle.
13
+
14
+ Phases (in order):
15
+ infrastructure — structural semantics first (they reprice everything else)
16
+ design-system — shared-cause decisions (contrast as a system fix)
17
+ instances — per-instance work, severity high → medium → low
18
+ redesign-zone — one page accumulating many distinct signals: flagged,
19
+ moved last, with an explicit note
20
+
21
+ CLI:
22
+ a11ytoolkit plan --report audit.json [-o plan.json]
23
+ a11ytoolkit plan --report audit.json --from-pack pack.json # pack effort
24
+ """
25
+
26
+ import argparse
27
+ import hashlib
28
+ import json
29
+ import sys
30
+
31
+ # Phase assignment by signal class (declared, not learned).
32
+ INFRA_SIGNALS = {'no_h1', 'heading_order', 'landmark', 'bypass_missing',
33
+ 'region_missing', 'field_label', 'button_name', 'link_name',
34
+ 'img_no_alt', 'iframe_title', 'html_lang_missing',
35
+ 'title_missing', 'viewport_zoom_blocked'}
36
+ DESIGN_SIGNALS = {'contrast_low', 'contrast_image_fail', 'color_alone',
37
+ 'focus_visibility', 'text_spacing'}
38
+ MINUTES_BY_SEVERITY = {'high': [12, 20], 'medium': [5, 10], 'low': [2, 4]}
39
+ REDESIGN_SIGNAL_THRESHOLD = 4 # distinct signals on one URL → zone flag
40
+
41
+ # What each assumption means, printed with the plan (honesty by default).
42
+ ASSUMPTIONS_HEURISTIC = {
43
+ 'source': 'severity heuristic',
44
+ 'minutes': MINUTES_BY_SEVERITY,
45
+ 'note': ('per-finding heuristic ranges, NOT measured effort; the pack '
46
+ 'effort pricing (a11y_evidence) is the better source when '
47
+ 'available'),
48
+ }
49
+
50
+
51
+ def _canon(obj):
52
+ return json.dumps(obj, ensure_ascii=False, sort_keys=True,
53
+ separators=(',', ':'))
54
+
55
+
56
+ def _minutes_for(findings, effort_by_criterion=None):
57
+ """Sum of per-finding minute ranges. With pack effort pricing, the
58
+ criterion's MIN/MED/MAX range replaces the severity heuristic."""
59
+ lo = hi = 0
60
+ for f in findings:
61
+ eff = effort_by_criterion.get((f.get('criterion') or '').split(' ')[0])
62
+ if eff and eff.get('minutes'):
63
+ lo += eff['minutes'][0]
64
+ hi += eff['minutes'][1]
65
+ else:
66
+ r = MINUTES_BY_SEVERITY.get(f.get('severity', 'low'), MINUTES_BY_SEVERITY['low'])
67
+ lo += r[0]
68
+ hi += r[1]
69
+ return [lo, hi]
70
+
71
+
72
+ def build_plan(report, pack=None):
73
+ """Report (dict with findings[]) → sealed fix-plan dict. Deterministic:
74
+ same report, same plan. Malformed findings are skipped, never fatal."""
75
+ findings = [f for f in (report.get('findings') or []) if isinstance(f, dict)
76
+ and f.get('signal')]
77
+ effort_by_criterion = {}
78
+ if pack:
79
+ for c in pack.get('criteria', []):
80
+ if c.get('effort', {}).get('minutes'):
81
+ effort_by_criterion[c['criterion'].split(' ')[0]] = c['effort']
82
+ assumptions = dict(ASSUMPTIONS_HEURISTIC)
83
+ if pack:
84
+ assumptions = {'source': 'pack effort',
85
+ 'note': 'minutes from the evidence pack effort pricing'}
86
+
87
+ # redesign zones: one URL accumulating many distinct signals
88
+ by_url = {}
89
+ for f in findings:
90
+ u = f.get('url') or report.get('url') or ''
91
+ by_url.setdefault(u, set()).add(f['signal'])
92
+ zones = {u for u, sigs in by_url.items() if len(sigs) >= REDESIGN_SIGNAL_THRESHOLD}
93
+
94
+ # batch by signal inside each phase (one signal = one kind of fix)
95
+ by_signal = {}
96
+ for f in findings:
97
+ by_signal.setdefault(f['signal'], []).append(f)
98
+
99
+ def phase_of(signal):
100
+ if signal in INFRA_SIGNALS:
101
+ return 'infrastructure'
102
+ if signal in DESIGN_SIGNALS:
103
+ return 'design-system'
104
+ return 'instances'
105
+
106
+ sev_rank = {'high': 0, 'medium': 1, 'low': 2}
107
+ batches = []
108
+ infra_signals = sorted(s for s in by_signal if phase_of(s) == 'infrastructure')
109
+ for signal in sorted(by_signal):
110
+ if signal in infra_signals and signal != (infra_signals or [signal])[0]:
111
+ continue # infrastructure is ONE combined batch (one work session)
112
+ fs = by_signal[signal]
113
+ if signal == (infra_signals or [None])[0] and infra_signals:
114
+ fs = [f for sg in infra_signals for f in by_signal[sg]]
115
+ signal = 'document_structure'
116
+ phase = 'infrastructure' if signal == 'document_structure' else phase_of(signal)
117
+ zone = bool(zones & {f.get('url') or '' for f in fs})
118
+ if phase == 'instances' and zone and len({f.get('url') for f in fs}) == 1 \
119
+ and len(by_url[list(zones & {f.get('url') for f in fs})[0]]) >= REDESIGN_SIGNAL_THRESHOLD:
120
+ phase = 'redesign-zone'
121
+ sev = min((sev_rank.get(f.get('severity', 'low'), 2) for f in fs))
122
+ batch = {
123
+ 'title': (f"Fix document structure semantics ({len(fs)} findings)"
124
+ if signal == 'document_structure' else
125
+ f"Fix {signal.replace('_', ' ')} ({len(fs)} finding"
126
+ f"{'s' if len(fs) != 1 else ''})"),
127
+ 'phase': phase, 'signal': signal,
128
+ 'finding_count': len(fs), 'severity': ('high', 'medium', 'low')[sev],
129
+ 'signals': infra_signals if signal == 'document_structure' else [signal],
130
+ 'urls': sorted({f.get('url') or '' for f in fs})[:8],
131
+ 'criteria': sorted({(f.get('criterion') or '').split(' ')[0] for f in fs}),
132
+ 'minutes': _minutes_for(fs, effort_by_criterion),
133
+ 'note': ('same kind of fix repeated — fix the pattern once and '
134
+ 're-apply; itemized minutes are the upper bound'
135
+ if len(fs) > 1 else ''),
136
+ }
137
+ if phase == 'redesign-zone':
138
+ batch['note'] = ('this URL accumulates %d distinct signals — '
139
+ 'consider fixing it in a redesign pass, not '
140
+ 'piecemeal' % len(by_url[list(zones & {f.get('url') for f in fs})[0]]))
141
+ batches.append(batch)
142
+
143
+ order = {'infrastructure': 0, 'design-system': 1, 'instances': 2, 'redesign-zone': 3}
144
+ batches.sort(key=lambda b: (order[b['phase']], sev_rank[b['severity']],
145
+ b['signal']))
146
+
147
+ # design-system note when contrast concentrates: one decision, many fixes
148
+ design = [b for b in batches if b['phase'] == 'design-system']
149
+ if design and sum(b['finding_count'] for b in design) >= 3:
150
+ design[0]['note'] = (design[0]['note'] or '') + (
151
+ ' — consider a design-token/theme decision: one change here '
152
+ 'typically resolves every finding in this batch').strip(' —')
153
+
154
+ cumulative = [0, 0]
155
+ for b in batches:
156
+ cumulative[0] += b['minutes'][0]
157
+ cumulative[1] += b['minutes'][1]
158
+ b['cumulative_minutes'] = list(cumulative)
159
+
160
+ itemized = [cumulative[0], cumulative[1]]
161
+ savings = [max(0, itemized[0] // 6), max(0, itemized[1] // 5)] # declared: 15-20% pattern reuse
162
+
163
+ plan = {
164
+ 'format': 'a11y-fix-plan/1',
165
+ 'source_report': {'url': report.get('url'), 'score': report.get('score'),
166
+ 'mode': report.get('mode'),
167
+ 'findings_total': len(findings)},
168
+ 'assumptions': assumptions,
169
+ 'batches': batches,
170
+ 'total_minutes': list(cumulative),
171
+ 'grouping_savings_minutes': savings,
172
+ 'grouping_note': ('declared estimate of pattern-reuse savings from '
173
+ 'fixing by batch instead of item by item — an '
174
+ 'optimistic bound, not a promise'),
175
+ 'redesign_zones': sorted(zones),
176
+ 'note': ('the order is a declared heuristic: infrastructure first '
177
+ '(it reprices everything else), then design decisions, '
178
+ 'then instances; the human reorders — re-run the seal '
179
+ 'after reordering')
180
+ + ('' if findings else ' NO FINDINGS in the source report '
181
+ '— nothing to plan (run the audit first).'),
182
+ }
183
+ plan['sha256'] = hashlib.sha256(
184
+ _canon({k: v for k, v in plan.items() if k != 'sha256'}).encode('utf-8')
185
+ ).hexdigest()
186
+ return plan
187
+
188
+
189
+ def verify_plan(plan):
190
+ expected = hashlib.sha256(
191
+ _canon({k: v for k, v in plan.items() if k != 'sha256'}).encode('utf-8')
192
+ ).hexdigest()
193
+ return expected == plan.get('sha256'), 'root sha256'
194
+
195
+
196
+ def main(argv):
197
+ ap = argparse.ArgumentParser(description='Remediation plan: findings → ordered fix route')
198
+ ap.add_argument('--report', required=True, help='audit report JSON (findings[])')
199
+ ap.add_argument('--from-pack', help='evidence pack JSON: use its effort pricing for minutes')
200
+ ap.add_argument('-o', '--out', default='fix-plan.json')
201
+ a = ap.parse_args(argv)
202
+ report = json.load(open(a.report, encoding='utf-8'))
203
+ pack = json.load(open(a.from_pack, encoding='utf-8')) if a.from_pack else None
204
+ plan = build_plan(report, pack=pack)
205
+ with open(a.out, 'w', encoding='utf-8') as f:
206
+ json.dump(plan, f, ensure_ascii=False, indent=1)
207
+ print(json.dumps({'plan': a.out, 'sha256': plan['sha256'],
208
+ 'batches': len(plan['batches']),
209
+ 'total_minutes': plan['total_minutes']}, ensure_ascii=False))
210
+ return 0
211
+
212
+
213
+ if __name__ == '__main__':
214
+ sys.exit(main(sys.argv[1:]))
@@ -87,7 +87,7 @@ try:
87
87
  except ImportError:
88
88
  ARIALIVE_JS = None # repo checkout: read the file
89
89
 
90
- VERSION = '5.22.3'
90
+ VERSION = '5.24.0'
91
91
 
92
92
  # Params renombrados a inglés en 5.11.0; se aceptan los nombres previos.
93
93
  PARAM_ALIASES = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kinti/a11y-toolkit",
3
- "version": "5.22.3",
3
+ "version": "5.24.0",
4
4
  "description": "Zero-dependency WCAG 2.2 accessibility engine (34 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.",
5
5
  "license": "MIT",
6
6
  "repository": {