@kw-yeh/vibeflow 4.11.66 → 4.11.69

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 (43) hide show
  1. package/README.md +1 -1
  2. package/dist/builtin-skills/address-review/scripts/pr-lib.mjs +29 -1
  3. package/dist/builtin-skills/pr/SKILL.md +112 -16
  4. package/dist/builtin-skills/pr-watch/SKILL.md +64 -31
  5. package/dist/builtin-skills/pr-watch/scripts/pr-lib.mjs +29 -1
  6. package/dist/builtin-skills/pr-watch/scripts/pr-watch.mjs +27 -11
  7. package/dist/builtin-skills/visual-parity/README.md +225 -0
  8. package/dist/builtin-skills/visual-parity/SKILL.md +168 -12
  9. package/dist/builtin-skills/visual-parity/scripts/parity.py +854 -63
  10. package/dist/builtin-skills/visual-parity/scripts/scaffold_verify.py +126 -0
  11. package/dist/builtin-skills/visual-parity/scripts/vendor/README +1 -0
  12. package/dist/builtin-skills/visual-parity/scripts/vendor/axe-core.LICENSE +362 -0
  13. package/dist/builtin-skills/visual-parity/scripts/vendor/axe.min.js +12 -0
  14. package/dist/builtin-skills/visual-parity/templates/verify-app/SKILL.md +46 -0
  15. package/dist/builtin-skills/visual-parity/templates/verify-app/features/README.md +18 -0
  16. package/dist/builtin-skills/visual-parity/templates/verify-app/features/home.md +19 -0
  17. package/dist/builtin-skills/visual-parity/templates/verify-app/flows/home.json +5 -0
  18. package/dist/builtin-skills/visual-parity/templates/verify-app/scripts/check-map.sh +33 -0
  19. package/dist/builtin-skills/visual-parity/templates/verify-app/scripts/cleanup.sh +27 -0
  20. package/dist/builtin-skills/visual-parity/templates/verify-app/scripts/doctor.sh +31 -0
  21. package/dist/builtin-skills/visual-parity/templates/verify-app/scripts/launch.sh +31 -0
  22. package/dist/builtin-skills/visual-parity/templates/verify-app/scripts/lib.sh +54 -0
  23. package/dist/builtin-skills/visual-parity/templates/verify-app/scripts/verify.sh +19 -0
  24. package/dist/builtin-skills/work-mode/SKILL.md +114 -0
  25. package/dist/builtin-skills/work-mode/playbooks/babysit-pr.md +19 -0
  26. package/dist/builtin-skills/work-mode/playbooks/bug-fix.md +19 -0
  27. package/dist/builtin-skills/work-mode/playbooks/feature.md +17 -0
  28. package/dist/builtin-skills/work-mode/playbooks/investigation.md +16 -0
  29. package/dist/builtin-skills/work-mode/playbooks/refactor.md +18 -0
  30. package/dist/vibeflow.mjs +370 -26
  31. package/dist/web/404/index.html +1 -1
  32. package/dist/web/404.html +1 -1
  33. package/dist/web/_next/static/{rGD00oN1g3FGv_hbb0V82 → VYsg0UtYDVl6PsB_NgjIH}/_buildManifest.js +1 -1
  34. package/dist/web/_next/static/chunks/{2362-46f5f7e798186269.js → 9038-bd3ba259c7af7029.js} +2 -2
  35. package/dist/web/_next/static/chunks/pages/{_app-cc5f3a5ded198d58.js → _app-16ca7c5ca7e39461.js} +1 -1
  36. package/dist/web/_next/static/chunks/pages/home-d30108228923847c.js +14 -0
  37. package/dist/web/_next/static/chunks/{webpack-d7cc7d90e557abc8.js → webpack-1f79da4960e22d5d.js} +1 -1
  38. package/dist/web/_next/static/css/77470e9065b0013a.css +2 -0
  39. package/dist/web/home/index.html +1 -1
  40. package/package.json +1 -1
  41. package/dist/web/_next/static/chunks/pages/home-c544d714b749bca6.js +0 -14
  42. package/dist/web/_next/static/css/2653922154b6a451.css +0 -2
  43. /package/dist/web/_next/static/{rGD00oN1g3FGv_hbb0V82 → VYsg0UtYDVl6PsB_NgjIH}/_ssgManifest.js +0 -0
@@ -58,18 +58,63 @@ COLLECT_JS = """
58
58
  ? el.textContent
59
59
  : Array.from(el.childNodes).filter(n => n.nodeType === 3).map(n => n.textContent).join(' '));
60
60
 
61
+ // Same asset on two hosts or two builds: drop origin, query, and content
62
+ // hashes so /_next/static/media/logo.3f2a9c1d.png matches /img/logo.png.
63
+ const asset = (u) => {
64
+ if (!u) return '';
65
+ try {
66
+ const url = new URL(u, location.href);
67
+ const inner = url.searchParams.get('url');
68
+ if (inner) return asset(inner);
69
+ u = url.pathname;
70
+ } catch (e) {}
71
+ const base = decodeURIComponent(u.split('/').pop() || '');
72
+ return base.replace(/[._-][0-9a-f]{8,}(?=\\.[a-z0-9]+$)/i, '').toLowerCase();
73
+ };
74
+ const bgAsset = (cs) => {
75
+ const m = /url\\(["']?([^"')]+)/.exec(cs.backgroundImage || '');
76
+ return m ? asset(m[1]) : '';
77
+ };
78
+ const visualKey = (el, cs) => {
79
+ const t = el.tagName.toLowerCase();
80
+ const a = (n) => (el.getAttribute(n) || '').trim().toLowerCase();
81
+ if (t === 'img') return 'img:' + (asset(el.currentSrc || el.src) || a('alt'));
82
+ if (t === 'video') return 'video:' + asset(el.currentSrc || el.getAttribute('src') || el.poster);
83
+ if (t === 'iframe') return 'iframe:' + asset(el.src);
84
+ if (t === 'svg') {
85
+ const use = el.querySelector('use');
86
+ const href = use && (use.getAttribute('href') || use.getAttribute('xlink:href'));
87
+ if (href) return 'svg:' + href.split('#').pop();
88
+ if (a('aria-label')) return 'svg:' + a('aria-label');
89
+ const title = el.querySelector('title');
90
+ if (title && title.textContent.trim()) return 'svg:' + title.textContent.trim().toLowerCase();
91
+ const d = el.querySelector('path');
92
+ return d ? 'svg-path:' + (d.getAttribute('d') || '').replace(/\\s+/g, '').slice(0, 80) : '';
93
+ }
94
+ if (t === 'input' || t === 'textarea' || t === 'select')
95
+ return t + ':' + [a('type'), a('name'), a('placeholder'), a('aria-label')].join('|');
96
+ if (a('aria-label')) return t + ':' + a('aria-label');
97
+ if (a('title')) return t + ':' + a('title');
98
+ const bg = bgAsset(cs);
99
+ return bg ? 'bg:' + bg : '';
100
+ };
101
+
61
102
  const out = [];
62
103
  for (const el of document.querySelectorAll('*')) {
63
104
  if (SKIP.has(el.tagName)) continue;
105
+ if (el.closest('svg') && el.tagName.toLowerCase() !== 'svg') continue;
64
106
  const r = el.getBoundingClientRect();
65
107
  if (r.width === 0 && r.height === 0) continue;
66
108
  const cs = getComputedStyle(el);
67
109
  const styles = {};
68
110
  for (const p of props) styles[p] = cs.getPropertyValue(p).trim();
111
+ const text = ownText(el).replace(/\\s+/g, ' ').trim().slice(0, 120);
69
112
  out.push({
70
113
  path: cssPath(el),
71
114
  tag: el.tagName.toLowerCase(),
72
- text: ownText(el).replace(/\\s+/g, ' ').trim().slice(0, 120),
115
+ text,
116
+ key: text ? '' : visualKey(el, cs),
117
+ leaf: el.children.length === 0 || el.tagName === 'svg',
73
118
  x: Math.round(r.left + scrollX), y: Math.round(r.top + scrollY),
74
119
  w: Math.round(r.width), h: Math.round(r.height),
75
120
  styles,
@@ -85,6 +130,41 @@ COLLECT_JS = """
85
130
  """
86
131
 
87
132
 
133
+ def provenance(urls, cwd=None):
134
+ """Which code and which pages a report is evidence for: commit, tree state, URLs, time."""
135
+ import datetime
136
+
137
+ def git(*a):
138
+ r = subprocess.run(["git", *a], cwd=cwd, capture_output=True, text=True)
139
+ return r.stdout.strip() if r.returncode == 0 else None
140
+
141
+ sha = git("rev-parse", "HEAD")
142
+ if sha is None:
143
+ commit = tree = "(not a git repo)"
144
+ else:
145
+ commit = sha
146
+ dirty = [l for l in (git("status", "--porcelain") or "").splitlines() if l.strip()]
147
+ tree = f"dirty ({len(dirty)} files changed)" if dirty else "clean"
148
+ return {
149
+ "commit": commit,
150
+ "tree": tree,
151
+ "urls": [u for u in urls if u],
152
+ "time": datetime.datetime.now().astimezone().isoformat(timespec="seconds"),
153
+ }
154
+
155
+
156
+ def provenance_md(prov):
157
+ return [f"- commit: {prov['commit']}", f"- working tree: {prov['tree']}",
158
+ f"- url: {', '.join(prov['urls']) or '(none)'}", f"- run at: {prov['time']}"]
159
+
160
+
161
+ def print_provenance(prov):
162
+ if prov["tree"] == "(not a git repo)":
163
+ print(f"commit: (not a git repo) · {prov['time']}")
164
+ else:
165
+ print(f"commit: {prov['commit'][:7]} ({prov['tree']}) · {prov['time']}")
166
+
167
+
88
168
  def norm(t):
89
169
  return re.sub(r"\s+", " ", t or "").strip().lower()
90
170
 
@@ -131,6 +211,7 @@ def build_pairs(ref_els, loc_els, manual_map):
131
211
  for keyfn, label in (
132
212
  (lambda e: f"{e['tag']}|{norm(e['text'])}" if norm(e["text"]) else None, "tag+text"),
133
213
  (lambda e: norm(e["text"]) if norm(e["text"]) else None, "text"),
214
+ (lambda e: e.get("key") or None, "visual"),
134
215
  ):
135
216
  ridx, lidx = index(ref_els, keyfn), index(loc_els, keyfn)
136
217
  for k, r in ridx.items():
@@ -146,14 +227,20 @@ def build_pairs(ref_els, loc_els, manual_map):
146
227
  # locally. Text that exists but is ambiguous (repeated nav labels, table
147
228
  # cells) simply cannot be paired 1:1 — reporting it as missing sends the
148
229
  # reader chasing content that is actually on the page.
149
- loc_texts = {norm(e["text"]) for e in loc_els if norm(e["text"])}
150
- missing, ambiguous = [], []
230
+ loc_ids = {norm(e["text"]) or e.get("key") for e in loc_els} - {"", None}
231
+ missing, ambiguous, unkeyed = [], [], []
151
232
  for e in ref_els:
152
- t = norm(e["text"])
153
- if id(e) in matched_ref or not t:
233
+ if id(e) in matched_ref:
234
+ continue
235
+ ident = norm(e["text"]) or e.get("key")
236
+ if not ident:
237
+ # Text-less leaves with nothing to pair on are reported so the
238
+ # coverage gap is visible; text-less containers are just layout.
239
+ if e.get("leaf"):
240
+ unkeyed.append(e)
154
241
  continue
155
- (missing if t not in loc_texts else ambiguous).append(e)
156
- return pairs, missing, ambiguous
242
+ (missing if ident not in loc_ids else ambiguous).append(e)
243
+ return pairs, missing, ambiguous, unkeyed
157
244
 
158
245
 
159
246
  def diff_pair(r, l):
@@ -194,20 +281,22 @@ def run_diff(args):
194
281
  f"(scrollWidth {loc['docScrollWidth']} > clientWidth {loc['clientWidth']})"
195
282
  )
196
283
 
197
- pairs, missing, ambiguous = build_pairs(ref["elements"], loc["elements"], manual_map)
284
+ pairs, missing, ambiguous, unkeyed = build_pairs(ref["elements"], loc["elements"], manual_map)
198
285
  total_pairs += len(pairs)
199
286
 
287
+ label = lambda e: e["text"] or e.get("key") or ""
200
288
  rows = []
201
289
  for r, l, how in pairs:
202
290
  for prop, a, b in diff_pair(r, l):
203
- rows.append((prop, r["path"], l["path"], a, b, r["text"][:40], how))
291
+ rows.append((prop, r["path"], l["path"], a, b, label(r)[:40], how))
204
292
  prop_counter[prop] += 1
205
- total_diffs += len(rows)
293
+ total_diffs += len(rows) + len(missing)
206
294
 
207
295
  sec = [f"\n## viewport {w}px\n",
208
296
  f"matched {len(pairs)} elements, {len(rows)} property diffs, "
209
297
  f"{len(missing)} missing locally, "
210
- f"{len(ambiguous)} not compared (text present but ambiguous)\n"]
298
+ f"{len(ambiguous)} not compared (text or asset present but ambiguous), "
299
+ f"{len(unkeyed)} not compared (text-less leaves with no src/alt/aria-label/title)\n"]
211
300
  if rows:
212
301
  sec.append("\n| property | ref value | local value | ref selector | text |")
213
302
  sec.append("|---|---|---|---|---|")
@@ -216,19 +305,29 @@ def run_diff(args):
216
305
  if missing:
217
306
  sec.append("\n### present in ref, missing locally\n")
218
307
  for e in missing[:60]:
219
- sec.append(f"- `{e['tag']}` {e['text'][:90]}")
308
+ sec.append(f"- `{e['tag']}` {label(e)[:90]}")
220
309
  if len(missing) > 60:
221
310
  sec.append(f"- ...and {len(missing) - 60} more")
222
311
  if ambiguous:
223
312
  sec.append(
224
- f"\n### not compared: {len(ambiguous)} elements whose text is repeated on the page\n"
313
+ f"\n### not compared: {len(ambiguous)} elements whose text or asset is repeated on the page\n"
225
314
  "Add entries to `--map` to compare these explicitly.\n")
315
+ if unkeyed:
316
+ sec.append(
317
+ f"\n### not compared: {len(unkeyed)} text-less leaves with nothing to pair on\n"
318
+ "Decorative boxes, CSS icons, dividers. Use `--map` for any that matter, "
319
+ "or cover them with `snapshot`.\n")
320
+ for e in unkeyed[:20]:
321
+ sec.append(f"- `{e['path']}` ({e['w']}x{e['h']})")
322
+ if len(unkeyed) > 20:
323
+ sec.append(f"- ...and {len(unkeyed) - 20} more")
226
324
  sections.append("\n".join(sec))
227
- stdout_rows.append((w, len(pairs), len(rows), len(missing), len(ambiguous)))
325
+ stdout_rows.append((w, len(pairs), len(rows), len(missing), len(ambiguous), len(unkeyed)))
228
326
 
229
327
  browser.close()
230
328
 
231
- report = [f"# visual-parity diff\n", f"- ref: {args.ref}", f"- local: {args.local}",
329
+ prov = provenance([args.ref, args.local])
330
+ report = [f"# visual-parity diff\n", *provenance_md(prov), f"- ref: {args.ref}", f"- local: {args.local}",
232
331
  f"- widths: {widths}"]
233
332
  if overflow_notes:
234
333
  report.append("\n**layout warnings**")
@@ -238,8 +337,10 @@ def run_diff(args):
238
337
  f.write("\n".join(report))
239
338
 
240
339
  print(f"report: {args.out}")
241
- for w, np_, nd, nm, na in stdout_rows:
242
- print(f" {w}px: {np_} matched, {nd} diffs, {nm} missing-locally, {na} skipped-ambiguous")
340
+ print_provenance(prov)
341
+ for w, np_, nd, nm, na, nu in stdout_rows:
342
+ print(f" {w}px: {np_} matched, {nd} diffs, {nm} missing-locally, "
343
+ f"{na} skipped-ambiguous, {nu} skipped-textless")
243
344
  for n in overflow_notes:
244
345
  print(f" WARN {n}")
245
346
  if prop_counter:
@@ -494,7 +595,7 @@ def run_pixel(args):
494
595
  notes.append(f"page widths differ (ref {ref.shape[1]}px, local {loc.shape[1]}px); compared the first {W}px")
495
596
  ref, loc = ref[:, :W].copy(), loc[:, :W].copy()
496
597
  ref_els, loc_els = ref_data["elements"], loc_data["elements"]
497
- pairs, missing, _ = build_pairs(ref_els, loc_els, manual_map)
598
+ pairs, missing, _, _ = build_pairs(ref_els, loc_els, manual_map)
498
599
 
499
600
  ref_g = cv2.cvtColor(ref, cv2.COLOR_BGR2GRAY).astype(np.float32)
500
601
  loc_g = cv2.cvtColor(loc, cv2.COLOR_BGR2GRAY).astype(np.float32)
@@ -660,9 +761,343 @@ def save_video(video, out_path):
660
761
  return out_path
661
762
 
662
763
 
764
+ CURSOR_JS = """
765
+ (() => {
766
+ if (window.__parityCursorInstalled) return;
767
+ window.__parityCursorInstalled = true;
768
+ const css = (el, s) => { for (const k in s) el.style.setProperty(k, s[k], 'important'); };
769
+ const root = () => document.body || document.documentElement;
770
+ let dot = null;
771
+ function ensure() {
772
+ if (dot && dot.isConnected) return dot;
773
+ const r = root();
774
+ if (!r) return null;
775
+ dot = document.createElement('div');
776
+ css(dot, {
777
+ position: 'fixed', left: '0', top: '0', width: '18px', height: '18px',
778
+ 'margin-left': '-9px', 'margin-top': '-9px', 'border-radius': '50%',
779
+ background: 'rgba(255,255,255,.35)', border: '2px solid rgba(18,18,18,.92)',
780
+ 'box-shadow': '0 0 0 1px rgba(255,255,255,.9), 0 1px 3px rgba(0,0,0,.45)',
781
+ 'pointer-events': 'none', 'z-index': '2147483647', opacity: '0',
782
+ transition: 'opacity .12s linear'
783
+ });
784
+ r.appendChild(dot);
785
+ return dot;
786
+ }
787
+ addEventListener('mousemove', (e) => {
788
+ const d = ensure();
789
+ if (!d) return;
790
+ css(d, { opacity: '1', transform: 'translate3d(' + e.clientX + 'px,' + e.clientY + 'px,0)' });
791
+ }, true);
792
+ addEventListener('mousedown', (e) => {
793
+ const r = root();
794
+ if (!r) return;
795
+ const ring = document.createElement('div');
796
+ css(ring, {
797
+ position: 'fixed', left: e.clientX + 'px', top: e.clientY + 'px',
798
+ width: '14px', height: '14px', 'margin-left': '-7px', 'margin-top': '-7px',
799
+ 'border-radius': '50%', border: '2px solid rgba(0,120,255,.95)',
800
+ background: 'rgba(0,120,255,.22)', 'pointer-events': 'none',
801
+ 'z-index': '2147483646',
802
+ transition: 'transform .45s ease-out, opacity .45s ease-out'
803
+ });
804
+ r.appendChild(ring);
805
+ requestAnimationFrame(() => css(ring, { transform: 'scale(3.2)', opacity: '0' }));
806
+ setTimeout(() => ring.remove(), 600);
807
+ }, true);
808
+ })();
809
+ """
810
+
811
+ GLIDE_STEPS = 24
812
+ GLIDE_MS = 15
813
+ GLIDE_SETTLE_MS = 120
814
+
815
+
816
+ def glide(page, pos, selector):
817
+ """Walk the pointer to the element before acting on it.
818
+
819
+ Playwright dispatches synthetic events with no pointer travel, so a video
820
+ would show the click landing with no indication of what was clicked. Moving
821
+ in timed increments gives CURSOR_JS real mousemove events to render.
822
+ """
823
+ loc = page.locator(selector).first
824
+ try:
825
+ loc.scroll_into_view_if_needed(timeout=15000)
826
+ box = loc.bounding_box()
827
+ except Exception:
828
+ box = None
829
+ if not box:
830
+ return
831
+ tx, ty = box["x"] + box["width"] / 2, box["y"] + box["height"] / 2
832
+ sx, sy = pos
833
+ for i in range(1, GLIDE_STEPS + 1):
834
+ t = i / GLIDE_STEPS
835
+ t = t * t * (3 - 2 * t)
836
+ page.mouse.move(sx + (tx - sx) * t, sy + (ty - sy) * t)
837
+ page.wait_for_timeout(GLIDE_MS)
838
+ pos[0], pos[1] = tx, ty
839
+ page.wait_for_timeout(GLIDE_SETTLE_MS)
840
+
841
+
842
+ STYLE_PROBE_JS = """
843
+ ([sel, pseudo, props]) => {
844
+ const el = document.querySelector(sel);
845
+ if (!el) return null;
846
+ const cs = getComputedStyle(el, pseudo || null);
847
+ const out = {};
848
+ for (const p of props) out[p] = cs.getPropertyValue(p).trim();
849
+ return out;
850
+ }
851
+ """
852
+
853
+ # Expected values are written by people ("#fff", "300ms", "1rem"), computed
854
+ # values come back canonical ("rgb(255, 255, 255)", "0.3s", "16px"). Resolving
855
+ # the expected value through the same element's parent makes both sides
856
+ # canonical without hand-maintaining a unit table.
857
+ CANONICAL_JS = """
858
+ ([sel, prop, value]) => {
859
+ const el = document.querySelector(sel);
860
+ const host = (el && el.parentElement) || document.body;
861
+ const probe = document.createElement(el ? el.tagName : 'div');
862
+ probe.style.setProperty('position', 'absolute');
863
+ probe.style.setProperty('visibility', 'hidden');
864
+ probe.style.setProperty(prop, value);
865
+ if (!probe.style.getPropertyValue(prop)) return null;
866
+ host.appendChild(probe);
867
+ const got = getComputedStyle(probe).getPropertyValue(prop).trim();
868
+ probe.remove();
869
+ return got;
870
+ }
871
+ """
872
+
873
+ BOX_JS = """
874
+ (sel) => {
875
+ const el = document.querySelector(sel);
876
+ if (!el) return null;
877
+ const r = el.getBoundingClientRect();
878
+ return {x: r.x + scrollX, y: r.y + scrollY, width: r.width, height: r.height};
879
+ }
880
+ """
881
+
882
+ WAIT_ANIMATIONS_JS = """
883
+ async (sel) => {
884
+ const root = sel ? document.querySelector(sel) : document;
885
+ if (!root) throw new Error('no element for ' + sel);
886
+ const anims = root.getAnimations({subtree: true}).filter(a => a.effect && a.effect.getTiming().iterations !== Infinity);
887
+ await Promise.all(anims.map(a => a.finished.catch(() => null)));
888
+ return anims.length;
889
+ }
890
+ """
891
+
892
+ _NUM_UNIT = re.compile(r"^(-?\d*\.?\d+)(px|ms|s)?$")
893
+
894
+
895
+ def _as_number(v):
896
+ """'0.3s' -> 300.0, '12px' -> 12.0, anything compound -> None."""
897
+ m = _NUM_UNIT.match(v.strip())
898
+ if not m:
899
+ return None
900
+ n, unit = float(m.group(1)), m.group(2)
901
+ return n * 1000 if unit == "s" else n
902
+
903
+
904
+ def check_styles(page, step):
905
+ sel, pseudo = step["selector"], step.get("pseudo")
906
+ expected = step["styles"]
907
+ tol = step.get("tolerance", 0.5)
908
+ got = page.evaluate(STYLE_PROBE_JS, [sel, pseudo, list(expected)])
909
+ if got is None:
910
+ raise AssertionError(f"no element for {sel}")
911
+ bad = []
912
+ for prop, want in expected.items():
913
+ have = got[prop]
914
+ if have == want:
915
+ continue
916
+ canon = page.evaluate(CANONICAL_JS, [sel, prop, want]) or want
917
+ if have == canon:
918
+ continue
919
+ a, b = _as_number(have), _as_number(canon)
920
+ if a is not None and b is not None and abs(a - b) <= tol:
921
+ continue
922
+ bad.append(f"{prop}: expected {want!r}, got {have!r}")
923
+ assert not bad, "; ".join(bad)
924
+
925
+
926
+ def check_box(page, step, saved):
927
+ box = page.evaluate(BOX_JS, step["selector"])
928
+ if box is None:
929
+ raise AssertionError(f"no element for {step['selector']}")
930
+ if "same_as" in step:
931
+ want = saved.get(step["same_as"])
932
+ if want is None:
933
+ raise AssertionError(f"no box saved as {step['same_as']!r}")
934
+ else:
935
+ want = {k: step[k] for k in ("x", "y", "width", "height") if k in step}
936
+ tol = step.get("tolerance", 2)
937
+ bad = [f"{k}: expected {want[k]:.1f}, got {box[k]:.1f}"
938
+ for k in want if abs(box[k] - want[k]) > tol]
939
+ assert not bad, "; ".join(bad)
940
+
941
+
942
+ AXE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "vendor", "axe.min.js")
943
+ AXE_IMPACT = ["minor", "moderate", "serious", "critical"]
944
+ AXE_DEFAULT_TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"]
945
+
946
+
947
+ def run_axe(page, step):
948
+ """Returns (markdown section, failure message or '')."""
949
+ if not page.evaluate("() => typeof window.axe !== 'undefined'"):
950
+ page.add_script_tag(path=AXE_PATH)
951
+ context = {"include": [[step["selector"]]]} if step.get("selector") else {}
952
+ if step.get("exclude"):
953
+ context["exclude"] = [[s] for s in step["exclude"]]
954
+ options = {"runOnly": {"type": "tag", "values": step.get("tags", AXE_DEFAULT_TAGS)}}
955
+ res = page.evaluate(
956
+ "([ctx, opts]) => axe.run(Object.keys(ctx).length ? ctx : document, opts)"
957
+ ".then(r => r.violations.map(v => ({id: v.id, impact: v.impact, help: v.help,"
958
+ " nodes: v.nodes.map(n => n.target.join(' '))})))",
959
+ [context, options])
960
+ fail_at = AXE_IMPACT.index(step.get("fail_on", "serious"))
961
+ res.sort(key=lambda v: -AXE_IMPACT.index(v["impact"] or "minor"))
962
+ if not res:
963
+ return "no violations\n", ""
964
+ lines = ["| impact | rule | nodes | example targets |", "|---|---|---|---|"]
965
+ for v in res:
966
+ ex = ", ".join(f"`{t}`" for t in v["nodes"][:3])
967
+ lines.append(f"| {v['impact']} | {v['id']}: {v['help']} | {len(v['nodes'])} | {ex} |")
968
+ blocking = [v for v in res if AXE_IMPACT.index(v["impact"] or "minor") >= fail_at]
969
+ msg = ""
970
+ if blocking:
971
+ msg = f"{len(blocking)} axe violations at or above {AXE_IMPACT[fail_at]}: " + \
972
+ ", ".join(f"{v['id']}({v['impact']})" for v in blocking)
973
+ return "\n".join(lines) + "\n", msg
974
+
975
+
976
+ FLOW_ACTIONS = (
977
+ "goto", "click", "fill", "press", "hover", "wait", "wait_animations", "emulate",
978
+ "expect_text", "expect_visible", "expect_focused", "expect_style", "save_box", "expect_box",
979
+ "axe", "screenshot",
980
+ )
981
+
982
+ STRIP_CSS_JS = """() => {
983
+ for (const s of document.styleSheets) { try { s.disabled = true; } catch (e) {} }
984
+ document.adoptedStyleSheets = [];
985
+ for (const el of document.querySelectorAll('[style]')) el.removeAttribute('style');
986
+ }"""
987
+
988
+ # How each assertion is broken on purpose; an assertion that still passes afterwards checks nothing.
989
+ MUTATIONS = {
990
+ "expect_style": ("strip all CSS", lambda page, step: page.evaluate(STRIP_CSS_JS)),
991
+ "expect_box": ("strip all CSS", lambda page, step: page.evaluate(STRIP_CSS_JS)),
992
+ "expect_text": ("empty the element's text", lambda page, step: page.evaluate(
993
+ "s => document.querySelectorAll(s).forEach(e => { e.textContent = ''; })", step["selector"])),
994
+ "expect_visible": ("hide the element", lambda page, step: page.add_style_tag(
995
+ content=step["selector"] + "{display:none!important;visibility:hidden!important}")),
996
+ "expect_focused": ("move focus away", lambda page, step: page.evaluate(
997
+ "() => { document.activeElement && document.activeElement.blur(); document.body.focus(); }")),
998
+ }
999
+
1000
+
1001
+ def exec_step(page, step, i, desc, *, cursor, pos, saved_boxes, axe_sections, timeout=15000):
1002
+ act = step.get("action")
1003
+ if act == "goto":
1004
+ page.goto(step["url"], wait_until="domcontentloaded", timeout=60000)
1005
+ try:
1006
+ page.wait_for_load_state("networkidle", timeout=20000)
1007
+ except Exception:
1008
+ pass
1009
+ elif act == "click":
1010
+ if cursor:
1011
+ glide(page, pos, step["selector"])
1012
+ page.click(step["selector"], timeout=timeout)
1013
+ elif act == "fill":
1014
+ if cursor:
1015
+ glide(page, pos, step["selector"])
1016
+ page.fill(step["selector"], step["value"], timeout=timeout)
1017
+ elif act == "press":
1018
+ page.press(step["selector"], step["key"], timeout=timeout)
1019
+ elif act == "wait":
1020
+ if "ms" in step:
1021
+ page.wait_for_timeout(step["ms"])
1022
+ else:
1023
+ page.wait_for_selector(step["selector"], timeout=step.get("timeout", timeout))
1024
+ elif act == "expect_text":
1025
+ got = page.inner_text(step["selector"], timeout=timeout)
1026
+ assert step["value"] in got, f"expected {step['value']!r} in {got[:120]!r}"
1027
+ elif act == "expect_visible":
1028
+ assert page.is_visible(step["selector"]), "not visible"
1029
+ elif act == "expect_focused":
1030
+ got = page.evaluate(
1031
+ "s => document.activeElement === document.querySelector(s)", step["selector"])
1032
+ assert got, "element is not document.activeElement"
1033
+ elif act == "hover":
1034
+ if cursor:
1035
+ glide(page, pos, step["selector"])
1036
+ page.hover(step["selector"], timeout=timeout)
1037
+ elif act == "emulate":
1038
+ media = {k: step[k] for k in ("reduced_motion", "color_scheme", "media") if k in step}
1039
+ page.emulate_media(**media)
1040
+ elif act == "wait_animations":
1041
+ page.evaluate(WAIT_ANIMATIONS_JS, step.get("selector"))
1042
+ elif act == "expect_style":
1043
+ check_styles(page, step)
1044
+ elif act == "save_box":
1045
+ box = page.evaluate(BOX_JS, step["selector"])
1046
+ if box is None:
1047
+ raise AssertionError(f"no element for {step['selector']}")
1048
+ saved_boxes[step["as"]] = box
1049
+ elif act == "expect_box":
1050
+ check_box(page, step, saved_boxes)
1051
+ elif act == "axe":
1052
+ section, blocking = run_axe(page, step)
1053
+ axe_sections.append(f"\n## axe — step {i}: {desc}\n\n" + section)
1054
+ assert not blocking, blocking
1055
+ elif act == "screenshot":
1056
+ page.screenshot(path=step["path"], full_page=step.get("full_page", True))
1057
+ else:
1058
+ raise ValueError(f"unknown action {act!r}; known: {', '.join(FLOW_ACTIONS)}")
1059
+
1060
+
1061
+ def describe(step):
1062
+ act = step.get("action")
1063
+ return step.get("desc", f"{act} {step.get('selector') or step.get('url') or ''}")
1064
+
1065
+
1066
+ def mutation_check(browser, steps, results):
1067
+ """Replay up to each passing assertion, break the page the way that assertion should notice, rerun it."""
1068
+ rows = []
1069
+ for i, desc, verdict, _ in results:
1070
+ step = steps[i]
1071
+ act = step.get("action")
1072
+ if verdict != "PASS" or act not in MUTATIONS:
1073
+ continue
1074
+ how, mutate = MUTATIONS[act]
1075
+ ctx = browser.new_context(ignore_https_errors=True)
1076
+ page = ctx.new_page()
1077
+ saved, sink = {}, []
1078
+ try:
1079
+ for j in range(i):
1080
+ if steps[j].get("action") in ("screenshot", "axe"):
1081
+ continue
1082
+ exec_step(page, steps[j], j, describe(steps[j]), cursor=False, pos=[0.0, 0.0],
1083
+ saved_boxes=saved, axe_sections=sink)
1084
+ mutate(page, step)
1085
+ exec_step(page, step, i, desc, cursor=False, pos=[0.0, 0.0], saved_boxes=saved,
1086
+ axe_sections=sink, timeout=3000)
1087
+ rows.append((i, desc, how, "INVALID", "still passes on the broken page"))
1088
+ except AssertionError as e:
1089
+ rows.append((i, desc, how, "valid", str(e)[:160]))
1090
+ except Exception as e:
1091
+ rows.append((i, desc, how, "valid", f"errors on the broken page: {str(e)[:140]}"))
1092
+ finally:
1093
+ ctx.close()
1094
+ return rows
1095
+
1096
+
663
1097
  def run_flow(args):
664
1098
  steps = json.load(open(args.steps, encoding="utf-8"))
665
1099
  console_errors, failed_requests, results = [], [], []
1100
+ saved_boxes, axe_sections, mutations = {}, [], []
666
1101
 
667
1102
  video_path, tmpdir = None, None
668
1103
 
@@ -676,45 +1111,19 @@ def run_flow(args):
676
1111
  record_video_size={"width": w, "height": h},
677
1112
  viewport={"width": w, "height": h})
678
1113
  ctx = browser.new_context(**ctx_opts)
1114
+ if args.cursor:
1115
+ ctx.add_init_script(CURSOR_JS)
679
1116
  page = ctx.new_page()
1117
+ pos = [0.0, 0.0]
680
1118
  page.on("console", lambda m: console_errors.append(f"[{m.type}] {m.text}"[:300])
681
1119
  if m.type in ("error", "warning") else None)
682
1120
  page.on("requestfailed", lambda r: failed_requests.append(f"{r.method} {r.url} — {r.failure}"[:300]))
683
1121
 
684
1122
  for i, step in enumerate(steps):
685
- act = step.get("action")
686
- desc = step.get("desc", f"{act} {step.get('selector') or step.get('url') or ''}")
1123
+ desc = describe(step)
687
1124
  try:
688
- if act == "goto":
689
- page.goto(step["url"], wait_until="domcontentloaded", timeout=60000)
690
- try:
691
- page.wait_for_load_state("networkidle", timeout=20000)
692
- except Exception:
693
- pass
694
- elif act == "click":
695
- page.click(step["selector"], timeout=15000)
696
- elif act == "fill":
697
- page.fill(step["selector"], step["value"], timeout=15000)
698
- elif act == "press":
699
- page.press(step["selector"], step["key"], timeout=15000)
700
- elif act == "wait":
701
- if "ms" in step:
702
- page.wait_for_timeout(step["ms"])
703
- else:
704
- page.wait_for_selector(step["selector"], timeout=step.get("timeout", 15000))
705
- elif act == "expect_text":
706
- got = page.inner_text(step["selector"], timeout=15000)
707
- assert step["value"] in got, f"expected {step['value']!r} in {got[:120]!r}"
708
- elif act == "expect_visible":
709
- assert page.is_visible(step["selector"]), "not visible"
710
- elif act == "expect_focused":
711
- got = page.evaluate(
712
- "s => document.activeElement === document.querySelector(s)", step["selector"])
713
- assert got, "element is not document.activeElement"
714
- elif act == "screenshot":
715
- page.screenshot(path=step["path"], full_page=step.get("full_page", True))
716
- else:
717
- raise ValueError(f"unknown action {act!r}")
1125
+ exec_step(page, step, i, desc, cursor=args.cursor, pos=pos,
1126
+ saved_boxes=saved_boxes, axe_sections=axe_sections)
718
1127
  results.append((i, desc, "PASS", ""))
719
1128
  except Exception as e:
720
1129
  results.append((i, desc, "FAIL", str(e)[:300]))
@@ -727,15 +1136,25 @@ def run_flow(args):
727
1136
  ctx.close() # the video file is only finalized on context close
728
1137
  if video:
729
1138
  video_path = save_video(video, args.video)
1139
+ if getattr(args, "mutate", False):
1140
+ mutations = mutation_check(browser, steps, results)
730
1141
  browser.close()
731
1142
  if tmpdir:
732
1143
  shutil.rmtree(tmpdir, ignore_errors=True)
733
1144
 
734
- lines = ["# visual-parity flow\n", f"steps file: {args.steps}\n"]
1145
+ prov = provenance([s.get("url") for s in steps if s.get("action") == "goto"])
1146
+ lines = ["# visual-parity flow\n", *provenance_md(prov), f"- steps file: {args.steps}\n"]
735
1147
  if video_path:
736
1148
  lines.append(f"video: {video_path}\n")
737
1149
  lines += ["| # | step | result | detail |", "|---|---|---|---|"]
738
1150
  lines += [f"| {i} | {d} | {r} | {m} |" for i, d, r, m in results]
1151
+ lines += axe_sections
1152
+ if mutations:
1153
+ lines += ["\n## mutation check\n",
1154
+ "Each passing assertion was rerun on a deliberately broken page. INVALID means it still "
1155
+ "passed, so it cannot tell a working page from a broken one.\n",
1156
+ "| # | assertion | mutation | verdict | detail |", "|---|---|---|---|---|"]
1157
+ lines += [f"| {i} | {d} | {h} | {v} | {m} |" for i, d, h, v, m in mutations]
739
1158
  if console_errors:
740
1159
  lines += ["\n## console errors/warnings\n"] + [f"- {e}" for e in dict.fromkeys(console_errors)]
741
1160
  if failed_requests:
@@ -744,16 +1163,190 @@ def run_flow(args):
744
1163
  f.write("\n".join(lines))
745
1164
 
746
1165
  failed = [r for r in results if r[2] == "FAIL"]
1166
+ invalid = [m for m in mutations if m[3] == "INVALID"]
747
1167
  print(f"report: {args.out}")
1168
+ print_provenance(prov)
748
1169
  if video_path:
749
1170
  print(f"video: {video_path}")
750
1171
  print(f" {len(results) - len(failed)}/{len(results)} steps passed")
751
1172
  for i, d, r, m in failed:
752
1173
  print(f" FAIL step {i}: {d} — {m}")
1174
+ if mutations:
1175
+ print(f" mutation check: {len(mutations) - len(invalid)} valid, {len(invalid)} invalid assertions")
1176
+ for i, d, h, v, m in invalid:
1177
+ print(f" INVALID step {i}: {d} — still passes after '{h}'")
753
1178
  if console_errors:
754
1179
  print(f" {len(set(console_errors))} unique console errors/warnings")
755
1180
  if failed_requests:
756
1181
  print(f" {len(set(failed_requests))} failed requests")
1182
+ return 1 if failed or invalid else 0
1183
+
1184
+
1185
+ FREEZE_CSS = """*,*::before,*::after{animation-duration:0s!important;animation-delay:0s!important;
1186
+ transition:none!important;caret-color:transparent!important}"""
1187
+
1188
+ ELEMENT_AT_JS = """
1189
+ ([x, y]) => {
1190
+ window.scrollTo(0, Math.max(0, y - innerHeight / 2));
1191
+ let el = document.elementFromPoint(x - scrollX, y - scrollY);
1192
+ if (!el) return null;
1193
+ const parts = [];
1194
+ for (let n = el; n && n.nodeType === 1 && parts.length < 4 && n !== document.body; n = n.parentElement) {
1195
+ let p = n.tagName.toLowerCase();
1196
+ if (n.id) { parts.unshift(p + '#' + n.id); break; }
1197
+ const cls = [...n.classList].filter(c => !/^(css|sc|jsx)-|^[a-z]+_[a-zA-Z0-9]{5}$/.test(c)).slice(0, 2);
1198
+ if (cls.length) p += '.' + cls.join('.');
1199
+ parts.unshift(p);
1200
+ }
1201
+ const t = (el.innerText || el.getAttribute('alt') || el.getAttribute('aria-label') || '').trim();
1202
+ return {path: parts.join(' > ') || el.tagName.toLowerCase(), text: t.replace(/\\s+/g, ' ').slice(0, 50)};
1203
+ }
1204
+ """
1205
+
1206
+
1207
+ def _flatten(img):
1208
+ from PIL import Image
1209
+ img = img.convert("RGBA")
1210
+ bg = Image.new("RGBA", img.size, (255, 255, 255, 255))
1211
+ return Image.alpha_composite(bg, img).convert("RGB")
1212
+
1213
+
1214
+ def _regions(mask, cell_px, min_ratio):
1215
+ """Group mismatched pixels into rectangles on a coarse grid (BFS, 8-way)."""
1216
+ from PIL import Image
1217
+ gw, gh = max(1, round(mask.width / cell_px)), max(1, round(mask.height / cell_px))
1218
+ grid = mask.resize((gw, gh), Image.BOX).load()
1219
+ hot = {(x, y) for y in range(gh) for x in range(gw) if grid[x, y] >= min_ratio * 255}
1220
+ sx, sy = mask.width / gw, mask.height / gh
1221
+ out = []
1222
+ while hot:
1223
+ stack = [hot.pop()]
1224
+ cells = []
1225
+ while stack:
1226
+ cx, cy = stack.pop()
1227
+ cells.append((cx, cy))
1228
+ for dx in (-1, 0, 1):
1229
+ for dy in (-1, 0, 1):
1230
+ n = (cx + dx, cy + dy)
1231
+ if n in hot:
1232
+ hot.remove(n)
1233
+ stack.append(n)
1234
+ xs, ys = [c[0] for c in cells], [c[1] for c in cells]
1235
+ weight = sum(grid[c] for c in cells) / 255
1236
+ out.append({"box": (min(xs) * sx, min(ys) * sy, (max(xs) + 1) * sx, (max(ys) + 1) * sy),
1237
+ "weight": weight, "density": weight / len(cells)})
1238
+ return sorted(out, key=lambda r: -r["weight"])
1239
+
1240
+
1241
+ def run_snapshot(args):
1242
+ from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageOps
1243
+
1244
+ ref = _flatten(Image.open(args.ref_image))
1245
+ with sync_playwright() as p:
1246
+ browser = p.chromium.launch(headless=True)
1247
+ ctx = browser.new_context(ignore_https_errors=True, reduced_motion="reduce",
1248
+ viewport={"width": args.width, "height": args.height},
1249
+ device_scale_factor=args.scale)
1250
+ page = ctx.new_page()
1251
+ page.goto(args.url, wait_until="domcontentloaded", timeout=60000)
1252
+ try:
1253
+ page.wait_for_load_state("networkidle", timeout=30000)
1254
+ except Exception:
1255
+ pass
1256
+ if args.wait_selector:
1257
+ page.wait_for_selector(args.wait_selector, timeout=30000)
1258
+ if args.freeze:
1259
+ page.add_style_tag(content=FREEZE_CSS)
1260
+ page.evaluate("() => document.fonts.ready.then(() => true)")
1261
+ if args.extra_wait:
1262
+ page.wait_for_timeout(int(args.extra_wait * 1000))
1263
+
1264
+ shot = os.path.join(tempfile.mkdtemp(prefix="parity-snap-"), "local.png")
1265
+ if args.selector:
1266
+ loc = page.locator(args.selector).first
1267
+ loc.scroll_into_view_if_needed(timeout=15000)
1268
+ origin = page.evaluate(BOX_JS, args.selector)
1269
+ loc.screenshot(path=shot, animations="disabled")
1270
+ else:
1271
+ origin = {"x": 0, "y": 0}
1272
+ page.screenshot(path=shot, full_page=True, animations="disabled")
1273
+ local_raw = _flatten(Image.open(shot))
1274
+
1275
+ css_w = local_raw.width / args.scale
1276
+ k = ref.width / css_w # ref-image pixels per CSS pixel
1277
+ local = local_raw.resize((ref.width, max(1, round(local_raw.height * ref.width / local_raw.width))),
1278
+ Image.LANCZOS)
1279
+ ref_css_h, loc_css_h = ref.height / k, local.height / k
1280
+ h = min(ref.height, local.height)
1281
+ a, b = ref.crop((0, 0, ref.width, h)), local.crop((0, 0, ref.width, h))
1282
+
1283
+ if not args.strict:
1284
+ # Figma and Chrome rasterise text and curves differently; blur away
1285
+ # sub-pixel edge noise and drop isolated pixels so only real shape,
1286
+ # position and colour changes survive.
1287
+ r = max(1.0, k * 0.75)
1288
+ a, b = a.filter(ImageFilter.GaussianBlur(r)), b.filter(ImageFilter.GaussianBlur(r))
1289
+ delta = ImageChops.difference(a, b).convert("L")
1290
+ mask = delta.point(lambda v: 255 if v > args.threshold * 255 else 0)
1291
+ if not args.strict:
1292
+ size = 3 if k < 2 else 5
1293
+ mask = mask.filter(ImageFilter.MinFilter(size)).filter(ImageFilter.MaxFilter(size))
1294
+ bad_px = mask.histogram()[255]
1295
+ mismatch = 100.0 * bad_px / (mask.width * mask.height)
1296
+
1297
+ regions = _regions(mask, args.cell * k, 0.15)[:15]
1298
+ for reg in regions:
1299
+ x0, y0, x1, y1 = reg["box"]
1300
+ reg["css"] = tuple(round(v / k) for v in reg["box"])
1301
+ cx = origin["x"] + (x0 + x1) / 2 / k
1302
+ cy = origin["y"] + (y0 + y1) / 2 / k
1303
+ reg["element"] = page.evaluate(ELEMENT_AT_JS, [cx, cy])
1304
+ browser.close()
1305
+
1306
+ overlay = ImageOps.grayscale(local.crop((0, 0, ref.width, h))).convert("RGB")
1307
+ overlay = Image.blend(overlay, Image.new("RGB", overlay.size, "white"), 0.5)
1308
+ overlay.paste(Image.new("RGB", overlay.size, (230, 0, 0)), mask=mask)
1309
+ draw = ImageDraw.Draw(overlay)
1310
+ for n, reg in enumerate(regions, 1):
1311
+ draw.rectangle(reg["box"], outline=(0, 90, 255), width=max(2, round(k)))
1312
+ draw.text((reg["box"][0] + 4, reg["box"][1] + 2), str(n), fill=(0, 90, 255))
1313
+ panel_h = max(ref.height, local.height)
1314
+ sheet = Image.new("RGB", (ref.width * 3, panel_h), (240, 240, 240))
1315
+ sheet.paste(ref, (0, 0))
1316
+ sheet.paste(local, (ref.width, 0))
1317
+ sheet.paste(overlay, (ref.width * 2, 0))
1318
+ sheet.save(args.diff_image)
1319
+
1320
+ height_gap = loc_css_h - ref_css_h
1321
+ prov = provenance([args.url])
1322
+ lines = ["# visual-parity snapshot\n", *provenance_md(prov),
1323
+ f"- design: {args.ref_image} ({ref.width}x{ref.height}px, {k:.2f}px per CSS px)",
1324
+ f"- local: {args.url}" + (f" `{args.selector}`" if args.selector else " (full page)"),
1325
+ f"- viewport: {args.width}px, mode: {'strict' if args.strict else 'anti-alias tolerant'}",
1326
+ f"- diff image (design | local | mismatch): {args.diff_image}\n",
1327
+ f"**mismatch {mismatch:.2f}%** of the compared area (limit {args.max_mismatch}%)\n",
1328
+ f"height: design {ref_css_h:.0f}px, local {loc_css_h:.0f}px (CSS) — "
1329
+ f"{'compared the top ' + str(round(h / k)) + 'px only' if abs(height_gap) > 1 else 'same'}\n"]
1330
+ if regions:
1331
+ lines += ["| # | CSS box (x,y,w,h) | density | local element at centre |", "|---|---|---|---|"]
1332
+ for n, reg in enumerate(regions, 1):
1333
+ x0, y0, x1, y1 = reg["css"]
1334
+ el = reg["element"] or {}
1335
+ lines.append(f"| {n} | {x0},{y0},{x1 - x0},{y1 - y0} | {reg['density']:.0%} | "
1336
+ f"`{el.get('path', '?')}` {el.get('text', '')} |")
1337
+ with open(args.out, "w", encoding="utf-8") as f:
1338
+ f.write("\n".join(lines) + "\n")
1339
+
1340
+ failed = mismatch > args.max_mismatch or abs(height_gap) > args.max_height_diff
1341
+ print(f"report: {args.out}")
1342
+ print_provenance(prov)
1343
+ print(f"diff image: {args.diff_image}")
1344
+ print(f" mismatch {mismatch:.2f}% (limit {args.max_mismatch}%), "
1345
+ f"height design {ref_css_h:.0f}px vs local {loc_css_h:.0f}px")
1346
+ for n, reg in enumerate(regions[:5], 1):
1347
+ x0, y0, x1, y1 = reg["css"]
1348
+ el = reg["element"] or {}
1349
+ print(f" region {n}: {x0},{y0} {x1 - x0}x{y1 - y0} ({reg['density']:.0%}) -> {el.get('path', '?')}")
757
1350
  return 1 if failed else 0
758
1351
 
759
1352
 
@@ -777,6 +1370,14 @@ def selftest():
777
1370
  assert "color" in body, "should detect the li color change"
778
1371
  assert "Only in ref" in body, "should report the ref-only element as missing locally"
779
1372
  assert "`div`" in body or "margin-bottom" in body, "should match p->div across tag change"
1373
+ assert_provenance(body, "diff")
1374
+
1375
+ selftest_provenance(d)
1376
+ selftest_docs()
1377
+ selftest_visual(d)
1378
+ selftest_flow(d)
1379
+ selftest_mutate(d)
1380
+ selftest_snapshot(d)
780
1381
  selftest_pixel(d)
781
1382
  print("\nselftest OK")
782
1383
 
@@ -829,12 +1430,192 @@ def selftest_pixel(d):
829
1430
  assert os.path.exists(os.path.join(d, "pixel-montage.png"))
830
1431
 
831
1432
 
1433
+ def assert_provenance(body, what):
1434
+ for field in ("- commit: ", "- working tree: ", "- url: ", "- run at: "):
1435
+ assert field in body, f"{what} report should record {field.strip('- :')}"
1436
+
1437
+
1438
+ def selftest_provenance(d):
1439
+ outside = provenance(["https://x"], cwd=d)
1440
+ assert outside["commit"] == "(not a git repo)" == outside["tree"], outside
1441
+ here = os.path.dirname(os.path.abspath(__file__))
1442
+ if subprocess.run(["git", "rev-parse"], cwd=here, capture_output=True).returncode == 0:
1443
+ inside = provenance([], cwd=here)
1444
+ assert re.fullmatch(r"[0-9a-f]{40}", inside["commit"]), inside
1445
+ assert inside["tree"] == "clean" or inside["tree"].startswith("dirty"), inside
1446
+
1447
+
1448
+ def doc_sync_problems(root):
1449
+ """Every subcommand and flow action must be named in both README.md and SKILL.md."""
1450
+ import inspect
1451
+ in_code = set(re.findall(r'act == "(\w+)"', inspect.getsource(exec_step)))
1452
+ problems = [f"FLOW_ACTIONS and exec_step disagree: {sorted(in_code ^ set(FLOW_ACTIONS))}"] \
1453
+ if in_code != set(FLOW_ACTIONS) else []
1454
+ sub = next(a for a in build_parser()._actions if isinstance(a, argparse._SubParsersAction))
1455
+ names = [("subcommand", n) for n in sub.choices] + [("flow action", n) for n in FLOW_ACTIONS]
1456
+ for doc in ("README.md", "SKILL.md"):
1457
+ text = open(os.path.join(root, doc), encoding="utf-8").read()
1458
+ problems += [f"{doc} does not mention {kind} `{n}`" for kind, n in names
1459
+ if not re.search(rf"`{n}`|^#+ {n}\b|parity\.py {n}\b", text, re.M)]
1460
+ return problems
1461
+
1462
+
1463
+ def selftest_docs():
1464
+ root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
1465
+ problems = doc_sync_problems(root)
1466
+ assert not problems, "docs out of sync with the code:\n " + "\n ".join(problems)
1467
+
1468
+
1469
+ def _write(d, name, html):
1470
+ path = os.path.join(d, name)
1471
+ open(path, "w", encoding="utf-8").write(html)
1472
+ return "file://" + path
1473
+
1474
+
1475
+ def selftest_visual(d):
1476
+ a = _write(d, "va.html", """<html><body>
1477
+ <img src="/img/logo.1a2b3c4d5e.png" alt="Logo" width=40 height=40>
1478
+ <img src="/uploads/banner_95de82a84f.webp" width=60 height=30>
1479
+ <img src="hero.png" width=100 height=50>
1480
+ <svg aria-label="close" width="20" height="20"><path d="M0 0L10 10"/></svg>
1481
+ <span style="display:inline-block;width:10px;height:10px;background:red"></span></body></html>""")
1482
+ b = _write(d, "vb.html", """<html><body>
1483
+ <img src="https://cdn.example.com/logo.png?v=2" alt="Logo" width=40 height=40>
1484
+ <img src="/_next/image?url=%2Fuploads%2Fbanner_0a1b2c3d4e.webp&w=128" width=60 height=30>
1485
+ <svg aria-label="close" width="30" height="20"><path d="M0 0L10 10"/></svg>
1486
+ <span style="display:inline-block;width:10px;height:10px;background:red"></span></body></html>""")
1487
+ out = os.path.join(d, "v.md")
1488
+ rc = run_diff(argparse.Namespace(ref=a, local=b, map=None, widths=None, width=800, height=600,
1489
+ wait_selector=None, extra_wait=0, out=out))
1490
+ body = open(out, encoding="utf-8").read()
1491
+ assert rc == 1, "missing content must fail the run"
1492
+ assert "img:hero.png" in body.split("missing locally")[-1], "should report the dropped image as missing"
1493
+ assert "img:logo.png" not in body.split("missing locally")[-1], "hashed and CDN logo URLs should pair"
1494
+ assert "banner" not in body.split("missing locally")[-1], "Strapi-hashed and next/image URLs should pair"
1495
+ assert "box-w" in body and "svg:close" in body, "should pair the svg by aria-label and diff its width"
1496
+ assert "text-less leaves" in body, "should count the unpairable decorative span"
1497
+
1498
+
1499
+ def selftest_flow(d):
1500
+ url = _write(d, "flow.html", """<html><head><style>
1501
+ #btn{color:#000;transition:color 300ms}
1502
+ #btn:hover{color:#f00}
1503
+ @media (prefers-reduced-motion: reduce){#btn{transition:none}}
1504
+ #box{width:100px;height:40px;margin-left:16px}
1505
+ #anim{width:10px;height:10px;animation:grow 200ms forwards}
1506
+ @keyframes grow{to{width:200px}}
1507
+ </style></head><body lang="en"><main><h1>t</h1>
1508
+ <button id=btn>Go</button><div id=box></div><div id=anim></div><img src="x.png"></main></body></html>""")
1509
+ steps = [
1510
+ {"action": "goto", "url": url},
1511
+ {"action": "expect_style", "selector": "#btn", "styles": {"transition-duration": "300ms", "color": "#000"}},
1512
+ {"action": "hover", "selector": "#btn"},
1513
+ {"action": "wait", "ms": 450},
1514
+ {"action": "expect_style", "selector": "#btn", "styles": {"color": "red"}},
1515
+ {"action": "save_box", "selector": "#box", "as": "box"},
1516
+ {"action": "expect_box", "selector": "#box", "same_as": "box"},
1517
+ {"action": "expect_box", "selector": "#box", "width": 100, "height": 40},
1518
+ {"action": "wait_animations", "selector": "#anim"},
1519
+ {"action": "expect_style", "selector": "#anim", "styles": {"width": "200px"}},
1520
+ {"action": "emulate", "reduced_motion": "reduce"},
1521
+ {"action": "expect_style", "selector": "#btn", "styles": {"transition-duration": "0s"}},
1522
+ {"action": "expect_style", "selector": "#btn", "styles": {"color": "blue"}, "desc": "must fail"},
1523
+ {"action": "expect_box", "selector": "#box", "width": 120, "desc": "must fail"},
1524
+ {"action": "axe", "desc": "must fail"},
1525
+ ]
1526
+ sp = os.path.join(d, "steps.json")
1527
+ json.dump(steps, open(sp, "w", encoding="utf-8"))
1528
+ out = os.path.join(d, "flow.md")
1529
+ run_flow(argparse.Namespace(steps=sp, out=out, headless=True, keep_going=True, video=None,
1530
+ video_size="1280x720", video_tail=0, cursor=False))
1531
+ rows = [l.split(" | ") for l in open(out, encoding="utf-8").read().splitlines() if re.match(r"^\| \d+ \|", l)]
1532
+ verdict = {int(r[0].strip("| ")): (r[1], r[2]) for r in rows}
1533
+ for i, (desc, res) in verdict.items():
1534
+ want = "FAIL" if "must fail" in desc else "PASS"
1535
+ assert res == want, f"flow step {i} ({desc}) was {res}, expected {want}"
1536
+ assert "image-alt" in open(out, encoding="utf-8").read(), "axe should flag the img without alt"
1537
+ assert_provenance(open(out, encoding="utf-8").read(), "flow")
1538
+
1539
+
1540
+ def selftest_mutate(d):
1541
+ url = _write(d, "mutate.html", """<html><head><style>#a{color:rgb(255,0,0)}</style></head>
1542
+ <body><p id=a>hi there</p><input id=q autofocus></body></html>""")
1543
+ steps = [
1544
+ {"action": "goto", "url": url},
1545
+ {"action": "expect_style", "selector": "#a", "styles": {"color": "rgb(255, 0, 0)"}, "desc": "valid style"},
1546
+ {"action": "expect_style", "selector": "#a", "pseudo": "::after", "styles": {"content": "none"},
1547
+ "desc": "always passes"},
1548
+ {"action": "expect_text", "selector": "#a", "value": "hi", "desc": "valid text"},
1549
+ {"action": "expect_visible", "selector": "#a", "desc": "valid visible"},
1550
+ {"action": "click", "selector": "#q"},
1551
+ {"action": "expect_focused", "selector": "#q", "desc": "valid focus"},
1552
+ ]
1553
+ sp = os.path.join(d, "mutate.json")
1554
+ json.dump(steps, open(sp, "w", encoding="utf-8"))
1555
+ out = os.path.join(d, "mutate.md")
1556
+ rc = run_flow(argparse.Namespace(steps=sp, out=out, headless=True, keep_going=True, video=None,
1557
+ video_size="1280x720", video_tail=0, cursor=False, mutate=True))
1558
+ body = open(out, encoding="utf-8").read()
1559
+ rows = {r.split(" | ")[1]: r.split(" | ")[3] for r in body.split("## mutation check")[1].splitlines()
1560
+ if re.match(r"^\| \d+ \|", r)}
1561
+ assert rows.get("always passes") == "INVALID", rows
1562
+ for name in ("valid style", "valid text", "valid visible", "valid focus"):
1563
+ assert rows.get(name) == "valid", (name, rows)
1564
+ assert rc == 1, "an invalid assertion must fail the run"
1565
+
1566
+
1567
+ def selftest_snapshot(d):
1568
+ page = """<html><body style="margin:0;background:#fff;font:16px sans-serif">
1569
+ <div id=block style="position:absolute;left:{x}px;top:20px;width:100px;height:60px;background:#1565c0"></div>
1570
+ <p style="position:absolute;left:20px;top:120px;margin:0">Design copy</p></body></html>"""
1571
+ a = _write(d, "sa.html", page.format(x=20))
1572
+ b = _write(d, "sb.html", page.format(x=80))
1573
+ ref = os.path.join(d, "design.png")
1574
+ with sync_playwright() as p:
1575
+ browser = p.chromium.launch(headless=True)
1576
+ pg = browser.new_page(viewport={"width": 400, "height": 200})
1577
+ pg.goto(a)
1578
+ pg.screenshot(path=ref)
1579
+ browser.close()
1580
+
1581
+ def snap(url):
1582
+ out = os.path.join(d, "snap.md")
1583
+ rc = run_snapshot(argparse.Namespace(
1584
+ ref_image=ref, url=url, selector=None, width=400, height=200, scale=2, threshold=0.1,
1585
+ max_mismatch=1.0, max_height_diff=8, cell=16, strict=False, freeze=True,
1586
+ wait_selector=None, extra_wait=0, out=out, diff_image=os.path.join(d, "snap.png")))
1587
+ return rc, open(out, encoding="utf-8").read()
1588
+
1589
+ rc, body = snap(a)
1590
+ assert rc == 0, "a page should match its own design export at a different scale:\n" + body
1591
+ assert_provenance(body, "snapshot")
1592
+ rc, body = snap(b)
1593
+ assert rc == 1 and "div#block" in body, "a moved block should fail and be traced to its element:\n" + body
1594
+
1595
+
832
1596
  def main():
833
1597
  # Windows consoles default to a legacy codepage (e.g. cp950); page text
834
1598
  # echoed to stdout must not crash the run.
835
1599
  for stream in (sys.stdout, sys.stderr):
836
1600
  if hasattr(stream, "reconfigure"):
837
1601
  stream.reconfigure(errors="replace")
1602
+ ap = build_parser()
1603
+ args = ap.parse_args()
1604
+ if args.cmd == "diff":
1605
+ sys.exit(run_diff(args))
1606
+ if args.cmd == "pixel":
1607
+ sys.exit(run_pixel(args))
1608
+ if args.cmd == "responsive":
1609
+ args.widths, args.width = "375,768,1440", 1440
1610
+ sys.exit(run_diff(args))
1611
+ if args.cmd == "flow":
1612
+ sys.exit(run_flow(args))
1613
+ if args.cmd == "snapshot":
1614
+ sys.exit(run_snapshot(args))
1615
+ selftest()
1616
+
1617
+
1618
+ def build_parser():
838
1619
  ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
839
1620
  sub = ap.add_subparsers(dest="cmd", required=True)
840
1621
 
@@ -866,6 +1647,8 @@ def main():
866
1647
  f.add_argument("--video", help="record the run to this path; .mp4 converts via ffmpeg, .webm keeps the native output")
867
1648
  f.add_argument("--video-size", default="1280x720", help="WxH of both the recording and the viewport (default 1280x720)")
868
1649
  f.add_argument("--video-tail", type=float, default=1.0, help="seconds to keep recording after the last step so trailing animations finish (default 1)")
1650
+ f.add_argument("--no-cursor", dest="cursor", action="store_false", default=True, help="disable the synthetic pointer (on by default: it travels to each click/fill target and ripples on press)")
1651
+ f.add_argument("--mutate", action="store_true", help="rerun every passing expect_* on a deliberately broken page; one that still passes is reported INVALID and fails the run")
869
1652
 
870
1653
  x = sub.add_parser("pixel", help="OpenCV screenshot diff, aligned by matched elements and "
871
1654
  "cross-checked against computed styles")
@@ -886,19 +1669,27 @@ def main():
886
1669
  x.add_argument("--out", default="parity-pixel.md",
887
1670
  help="report path; screenshots and montage are written next to it")
888
1671
 
889
- sub.add_parser("selftest", help="verify the matcher/differ still work")
1672
+ s = sub.add_parser("snapshot", help="pixel-compare a rendered page or element against a design PNG (e.g. a Figma export)")
1673
+ s.add_argument("--ref-image", required=True, help="design PNG, e.g. downloaded from Figma get_screenshot")
1674
+ s.add_argument("--url", required=True, help="URL under development")
1675
+ s.add_argument("--selector", help="capture only this element (match the Figma frame); default full page")
1676
+ s.add_argument("--width", type=int, default=1440, help="viewport CSS width; use the Figma frame's original_width")
1677
+ s.add_argument("--height", type=int, default=900)
1678
+ s.add_argument("--scale", type=float, default=2, help="device scale factor for the local capture (default 2)")
1679
+ s.add_argument("--threshold", type=float, default=0.1, help="per-pixel luma difference 0-1 that counts as a mismatch")
1680
+ s.add_argument("--max-mismatch", type=float, default=1.0, help="percent of mismatched pixels allowed before exit 1")
1681
+ s.add_argument("--max-height-diff", type=float, default=8, help="CSS px of height difference allowed before exit 1")
1682
+ s.add_argument("--cell", type=int, default=16, help="grid cell size in CSS px for grouping mismatch regions")
1683
+ s.add_argument("--strict", action="store_true", help="no anti-alias tolerance (exact pixel comparison)")
1684
+ s.add_argument("--no-freeze", dest="freeze", action="store_false", default=True,
1685
+ help="keep animations, transitions and the caret running")
1686
+ s.add_argument("--wait-selector")
1687
+ s.add_argument("--extra-wait", type=float, default=0)
1688
+ s.add_argument("--out", default="parity-snapshot.md")
1689
+ s.add_argument("--diff-image", default="parity-snapshot.png")
890
1690
 
891
- args = ap.parse_args()
892
- if args.cmd == "diff":
893
- sys.exit(run_diff(args))
894
- if args.cmd == "pixel":
895
- sys.exit(run_pixel(args))
896
- if args.cmd == "responsive":
897
- args.widths, args.width = "375,768,1440", 1440
898
- sys.exit(run_diff(args))
899
- if args.cmd == "flow":
900
- sys.exit(run_flow(args))
901
- selftest()
1691
+ sub.add_parser("selftest", help="verify the matcher/differ still work")
1692
+ return ap
902
1693
 
903
1694
 
904
1695
  if __name__ == "__main__":