capybara-storyboard 0.4.0 → 0.5.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3bf6a851426d1aa00542d1d81071115072cd603519243887686156f178c62d57
4
- data.tar.gz: 145f880b26d5d6ae6b8042f2434b398bb018f7d0b646cc5fc0922cd9ed25d509
3
+ metadata.gz: 1ffabae69ca2a4b827fb35214945f5ca04c2adda2576073e14510e49fe441a96
4
+ data.tar.gz: b0c5d05738ad7eb1e72917e756c86806b1414857ee7e1e08a6a7b3f0a2fc1100
5
5
  SHA512:
6
- metadata.gz: b73fed754aafe430f72452947b62f3ebb50480b3deeeea2c3dff00f6296d17297eaa96004c94d12908838dedbde58ac5ff966db331003e628fc3b639d9312129
7
- data.tar.gz: 6f61ca195317e9c69f7cd476e158d55b48f86fc1d072a60829a93a780527176d94d0a5c1bf44cb5137e8ddbd6739cd7f4081d12f84c850e9991bcd39b6ac4a6f
6
+ metadata.gz: dbd3ac053c0928b612c0b51dbe226fa04549c9e77360abd80673fd8b48dc435f2dff5da423884102922e542bf8a404fcc94219faad14cae9f9c1b8ce24f4f51f
7
+ data.tar.gz: a51ec8ea5efb5aeca79d1038c3df9aabb62a5e6e1bc486bf6b9f2f45f076a29620a9ed5062093f67053d46accf20a309294e1f18e9bae8f4e1e6e4b966ea7bfa
data/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.5.0] - 2026-11-25
4
+
5
+ - Add `screenshot-compare` skill that captures before/after screenshots and renders them side by side in a self-contained HTML page
6
+ - Fix `visual-regression-test` baseline resolution picking a feature branch's own upstream
7
+ (e.g. `origin/feature`) as the base branch on a clean tree, which made the baseline collapse
8
+ to (nearly) HEAD
9
+
3
10
  ## [0.4.0] - 2026-08-12
4
11
 
5
12
  - Replace wholly-numeric path segments in `visit` paths with `N` in screenshot filenames
data/README.md CHANGED
@@ -270,6 +270,9 @@ is still taken. The wait is tunable via:
270
270
  - [skills/capybara-storyboard](skills/capybara-storyboard) — an agent skill for visually
271
271
  verifying captured screenshots (Claude Code, or any agent that can read PNG files from the
272
272
  filesystem).
273
+ - [skills/screenshot-compare](skills/screenshot-compare) — an agent skill that captures
274
+ before/after screenshots of a UI change and shows them side by side in a self-contained HTML
275
+ page.
273
276
  - [skills/visual-regression-test](skills/visual-regression-test) — an agent skill that
274
277
  compares before/after screenshots with `reg-cli` to catch unintended visual regressions,
275
278
  invoked via `/visual-regression-test [ref]` in Claude Code.
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Capybara
4
4
  module Storyboard
5
- VERSION = '0.4.0'
5
+ VERSION = '0.5.0'
6
6
  end
7
7
  end
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: capybara-storyboard
3
- description: Visually verify UI changes by running system specs with capybara-storyboard and reading the captured screenshot sequence. Use whenever app/views or app/components changes need a visual check, or when a system spec is changed and run.
3
+ description: Visually verify UI changes by running system specs with capybara-storyboard and reading the captured screenshot sequence. Use whenever app/views or app/components changes need a visual check, or when a system spec is changed and run. To compare before and after a change and show the user the difference, use screenshot-compare instead.
4
4
  model: sonnet
5
5
  ---
6
6
 
@@ -0,0 +1,287 @@
1
+ ---
2
+ name: screenshot-compare
3
+ description: >-
4
+ Show the user a before/after comparison of a UI change (views, components,
5
+ CSS): capture capybara-storyboard screenshots of both states, diff them with
6
+ reg-cli to confirm nothing unintended changed, and present before / after /
7
+ diff side by side in a self-contained HTML page. Use when the user asks to
8
+ compare old and new screens or to see the visual effect of a change (e.g.
9
+ "change this CSS, then compare the old and new screens and show me"), or
10
+ when a change such as CSS can ripple into screens beyond the one being
11
+ edited. To only check that the current screens look right, use
12
+ capybara-storyboard instead. The agent picks how to obtain "before"
13
+ (pre-capture, worktree, stash, or existing directories).
14
+ ---
15
+
16
+ # Screenshot compare (before / after side-by-side HTML)
17
+
18
+ Capture capybara-storyboard screenshots for the "before" and "after" states of a UI change,
19
+ diff them with `reg-cli`, verify the result yourself, and then present everything to the user as
20
+ a single self-contained HTML page: for each screen, before / after / diff side by side, with
21
+ your verdict on each change.
22
+
23
+ How this differs from the neighboring skills:
24
+
25
+ - `visual-regression-test` is explicit-invocation only, always captures "before" in a worktree
26
+ at a baseline ref, and opens reg-cli's own HTML report. This skill may fire automatically,
27
+ chooses the cheapest safe way to get "before", and produces a before/after/diff page with the
28
+ agent's verdicts attached.
29
+ - The plain `capybara-storyboard` review looks at a single snapshot of the current code ("does
30
+ this look right now?"). This skill answers "what changed compared to before, and was it
31
+ intended?" and shows the user the answer.
32
+
33
+ ## Prerequisites (confirm before starting)
34
+
35
+ - capybara-storyboard is already set up (screenshots are captured with `SCREENSHOTS=1` and land
36
+ under `tmp/screenshots/`). Setting it up is out of scope for this skill.
37
+ - `npx reg-cli` is available (no install needed), `ruby` is available (the HTML builder uses the
38
+ standard library only), and the platform's `open` command exists (macOS).
39
+ - Bundled scripts live in `scripts/` next to this SKILL.md, so they work wherever the skill is
40
+ installed. Commands run from the project root; in the commands below, `$SKILL_DIR` stands for
41
+ the absolute path of this skill's base directory (the directory containing this SKILL.md) —
42
+ substitute it, or set `SKILL_DIR` in the same shell call. Output goes under
43
+ `tmp/screenshot-compare/`:
44
+
45
+ ```
46
+ tmp/screenshot-compare/
47
+ before/ screenshots before the change
48
+ after/ screenshots after the change
49
+ diff/ reg-cli diff images
50
+ report.json reg-cli result (failedItems / newItems / deletedItems / passedItems)
51
+ report.html reg-cli's own report (not shown to the user)
52
+ notes.json the agent's verdicts (written in step 7)
53
+ compare.html the final side-by-side page (built in step 8)
54
+ ```
55
+
56
+ ## Procedure
57
+
58
+ ### 1. Identify the target specs
59
+
60
+ Narrow to the system specs that exercise the changed screen(s), the same way as the plain
61
+ `capybara-storyboard` review. Never run the entire suite.
62
+
63
+ - Search for specs that render the changed view/component (by name, controller action, or
64
+ route). If the call sites are countable (roughly 10 or fewer), target those specs directly.
65
+ - For a shared layout or widely used partial/component, propose a small representative sample
66
+ (roughly 3-6 specs across distinct contexts) and **confirm with the user** before running.
67
+ - If a system spec itself changed, that spec is the target.
68
+ - Record the exact `rspec` arguments: "before" and "after" must run the identical command.
69
+
70
+ ### 2. Choose how to obtain "before"
71
+
72
+ Pick the method from the situation. Do not ask the user unless the situation is ambiguous.
73
+
74
+ | Situation | Method |
75
+ | --- | --- |
76
+ | Invoked before any edit (nothing changed yet, e.g. just asked to change some CSS) | **Pre-capture**: screenshot the current state, copy it to `before`, then edit and capture "after". No worktree or stash needed; the safest option. Recommended. |
77
+ | `before` and `after` directories already exist or were handed over (a CI `vr-shots` artifact, an earlier run) | **Existing directories**: skip capturing. Use them as they are (copy to `tmp/screenshot-compare/before` and `after` if needed) and go to step 6. |
78
+ | After editing, and the baseline is something other than HEAD (an explicit ref, or a clean tree compared against the base branch) | **Worktree only** (a stash cannot reproduce this). |
79
+ | After editing, comparing uncommitted changes only | **Worktree** by default. Use **stash** if the worktree does not boot in this project, or the change is small. |
80
+
81
+ For worktree and stash modes, the baseline is decided by `scripts/resolve-baseline.sh`
82
+ (priority: explicit ref argument, then HEAD when there are uncommitted changes, then the base
83
+ branch when the tree is clean; anything other than HEAD resolves to the merge-base with HEAD;
84
+ exit 2 means it can't be resolved, so abort). Pass the first argument only (an empty string if
85
+ none); if more were given, tell the user the rest were ignored. If the given ref can't be
86
+ resolved, tell the user and abort — never silently fall back to a different ref.
87
+
88
+ For pre-capture mode:
89
+
90
+ ```bash
91
+ rm -rf tmp/screenshots
92
+ SCREENSHOTS=1 bundle exec rspec <target specs>
93
+ mkdir -p tmp/screenshot-compare && rm -rf tmp/screenshot-compare/before
94
+ cp -R tmp/screenshots tmp/screenshot-compare/before
95
+ ```
96
+
97
+ Then make the edit, and continue with step 3.
98
+
99
+ ### 3. Capture "after" (skip when using existing directories)
100
+
101
+ Run it against the main repo's working tree (with the change applied). Remove `tmp/screenshots`
102
+ first so stale images from earlier runs don't leak in.
103
+
104
+ ```bash
105
+ rm -rf tmp/screenshots
106
+ SCREENSHOTS=1 bundle exec rspec <target specs>
107
+ mkdir -p tmp/screenshot-compare && rm -rf tmp/screenshot-compare/after
108
+ cp -R tmp/screenshots tmp/screenshot-compare/after
109
+ ```
110
+
111
+ If the target spec **fails**, the capture may be incomplete. Report the failure (it is a
112
+ finding) and confirm with the user whether to use the partial capture.
113
+
114
+ In pre-capture mode, this is the capture that runs after the edit. In worktree and stash modes,
115
+ do this before step 4 so a failing spec is discovered before any worktree or stash is created.
116
+
117
+ ### 4. Capture "before" (worktree or stash modes only)
118
+
119
+ #### 4a. Worktree
120
+
121
+ ```bash
122
+ WT=.claude/worktrees/screenshot-compare-baseline
123
+ # Pass "" if no argument was given. Prints the starting ref/SHA to stdout on one line. Abort on exit 2.
124
+ BEFORE_REF=$("$SKILL_DIR"/scripts/resolve-baseline.sh "${BASELINE_ARG:-}")
125
+ git worktree add "$WT" "$BEFORE_REF"
126
+ ( cd "$WT" && bundle exec rails runner 'exit 0' )
127
+ ```
128
+
129
+ If the boot check fails, remove the worktree and stop:
130
+
131
+ ```bash
132
+ git worktree remove --force "$WT"
133
+ ```
134
+
135
+ Tell the user the worktree lacks the config files and dependencies that git ignores
136
+ (e.g. `config/database.yml`, installed gems/packages), and that they need automatic setup on
137
+ worktree creation — for example a `post-checkout` hook that copies those files and installs
138
+ dependencies, running only when `$1` is the all-zero SHA (i.e. a freshly created worktree). If
139
+ only uncommitted changes are being compared, offer the stash method instead.
140
+
141
+ If it boots, capture "before" and discard the worktree:
142
+
143
+ ```bash
144
+ ( cd "$WT" && SCREENSHOTS=1 bundle exec rspec <target specs> )
145
+ rm -rf tmp/screenshot-compare/before
146
+ cp -R "$WT/tmp/screenshots" tmp/screenshot-compare/before
147
+ git worktree remove --force "$WT"
148
+ ```
149
+
150
+ The worktree shares the main repo's DB, so do not run other tests concurrently. An old baseline
151
+ may not match the current DB schema and fail to boot or run; that is an expected failure, so
152
+ suggest a baseline closer to HEAD.
153
+
154
+ #### 4b. Stash (take every safeguard below)
155
+
156
+ The stash stack is shared with other worktrees and sessions, so never use a bare `git stash` or
157
+ `git stash pop`. First make sure the output directory is ignored; otherwise `-u` would stash the
158
+ "after" capture itself, so do not use stash in that case:
159
+
160
+ ```bash
161
+ git check-ignore -q tmp/screenshot-compare/after || echo "not ignored: do not use stash"
162
+ ```
163
+
164
+ Stash with a unique tag and record the SHA:
165
+
166
+ ```bash
167
+ TAG="screenshot-compare-$(date +%s)"
168
+ git stash push -u -m "$TAG"
169
+ STASH_SHA=$(git stash list --format='%H %gs' | grep -F "$TAG" | head -1 | cut -d' ' -f1)
170
+ ```
171
+
172
+ If `STASH_SHA` is empty, no entry was created (there was nothing to stash), so stop. Otherwise
173
+ capture "before" on the now-clean tree:
174
+
175
+ ```bash
176
+ rm -rf tmp/screenshots
177
+ SCREENSHOTS=1 bundle exec rspec <target specs>
178
+ rm -rf tmp/screenshot-compare/before
179
+ cp -R tmp/screenshots tmp/screenshot-compare/before
180
+ ```
181
+
182
+ **Always** restore afterwards, whether or not the spec passed, and verify:
183
+
184
+ ```bash
185
+ git stash apply "$STASH_SHA"
186
+ git status --short # confirm the original changes are back
187
+ ```
188
+
189
+ Only after verifying, re-find the entry's current position by tag and drop it:
190
+
191
+ ```bash
192
+ git stash list --format='%gd %gs' | grep -F "$TAG" # -> stash@{n}
193
+ git stash drop "stash@{n}"
194
+ ```
195
+
196
+ ### 5. Beware of built assets when changing CSS
197
+
198
+ Built assets (`app/assets/builds`, `public/assets`, etc.) are often gitignored, so a stash or
199
+ worktree does not roll them back to the old state, or they don't exist there at all. If a CSS
200
+ change should produce a diff but the diff is zero, suspect this first: rebuild the assets with
201
+ the project's own command (e.g. `bin/rails assets:precompile`, `yarn build:css`) and capture
202
+ again.
203
+
204
+ ### 6. Diff with reg-cli
205
+
206
+ ```bash
207
+ "$SKILL_DIR"/scripts/reg-diff.sh \
208
+ tmp/screenshot-compare/after tmp/screenshot-compare/before tmp/screenshot-compare
209
+ ```
210
+
211
+ - Argument order matters: **after (actual) first, before (expected) second, output directory
212
+ third.**
213
+ - Exit codes: `0` no visual change, `1` diff detected (expected, **not an error**), `2`
214
+ execution error (bad arguments / missing directory).
215
+ - Images present on only one side are reported as new/deleted. This happens when the change
216
+ altered the spec's own steps, or when an ID in a query string (e.g. `/search?user_id=42`)
217
+ shifted a filename. Record IDs in `visit` path segments are already normalized to `N` by the
218
+ gem, so those are not a cause.
219
+
220
+ ### 7. Verify the diffs and write `notes.json`
221
+
222
+ Read `tmp/screenshot-compare/report.json` (`failedItems`, `newItems`, `deletedItems`). For every
223
+ such image, actually read the diff image (`diff/**`) and the corresponding before/after PNGs
224
+ (`before/{Group}/{example}/{NNN_action}.png`), and judge each one:
225
+
226
+ - **intended**: the visual change matches what the code change was meant to do.
227
+ - **regression**: an unrelated screen shifted, or something broke — layout breakage, overflow,
228
+ a shared partial/layout/CSS edit leaking into pages it shouldn't affect.
229
+ - **noise**: sub-pixel or anti-aliasing differences with no meaningful change. If noise
230
+ dominates, mention reg-cli's `--threshold` / `--enableAntialias` options for a re-run.
231
+
232
+ Write the verdicts to `tmp/screenshot-compare/notes.json`. Keys are the same relative paths as
233
+ the items in `report.json`; passed images need no entry.
234
+
235
+ ```json
236
+ {
237
+ "summary": "Overall conclusion (optional)",
238
+ "items": {
239
+ "Group/example/003_after_click_on_Done.png": {
240
+ "verdict": "intended | regression | noise",
241
+ "comment": "Why"
242
+ }
243
+ }
244
+ }
245
+ ```
246
+
247
+ ### 8. Build the HTML, show it, and report
248
+
249
+ Build the page only after the verification in step 7, so the user never sees diffs you haven't
250
+ judged yet.
251
+
252
+ ```bash
253
+ ruby "$SKILL_DIR"/scripts/build-html.rb --dir tmp/screenshot-compare \
254
+ [--notes PATH] [--title TEXT] [--out PATH]
255
+ open tmp/screenshot-compare/compare.html
256
+ ```
257
+
258
+ `--notes` defaults to `<dir>/notes.json` and `--out` to `<dir>/compare.html`. The page lays out
259
+ every image per spec/example in three columns (before / after / diff), badges changed / new /
260
+ deleted screens, shows each verdict and comment from `notes.json`, and collapses unchanged
261
+ screens (shown as a single image, since before and after are identical). Clicking an image
262
+ opens it at full size in an overlay (close it by clicking the backdrop, the × button, or Esc).
263
+ Images are embedded as base64 in a single HTML file, so it gets large with many images (the
264
+ script warns above 50 MB).
265
+
266
+ Then give a concise written report:
267
+
268
+ - How many screens changed / were added / were deleted (from `report.json`).
269
+ - For each meaningful change: which screen and your verdict.
270
+ - A clear conclusion: either "all changes are consistent with the intended edit," or "the
271
+ following look like regressions: ...".
272
+ - How "before" was obtained (pre-capture / worktree with baseline / stash / existing
273
+ directories).
274
+ - That the HTML is open in the browser for the user to check.
275
+
276
+ ### 9. Output and cleanup
277
+
278
+ Leave `tmp/screenshot-compare/` in place — the user is looking at it. Only mention that it can be
279
+ removed when no longer needed:
280
+
281
+ ```bash
282
+ rm -rf tmp/screenshot-compare tmp/screenshots
283
+ ```
284
+
285
+ Check `git worktree list` for a stray `.claude/worktrees/screenshot-compare-baseline` and remove
286
+ it with `git worktree remove --force <path>`. If the stash method was used, confirm the entry was
287
+ dropped.
@@ -0,0 +1,360 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ # Build a single-file side-by-side (before / after / diff) HTML from reg-cli output.
5
+ #
6
+ # Usage:
7
+ # ruby build-html.rb [--dir tmp/screenshot-compare] [--notes <dir>/notes.json]
8
+ # [--title "Screenshot comparison"] [--out <dir>/compare.html]
9
+ #
10
+ # Reads <dir>/before, <dir>/after, <dir>/diff and <dir>/report.json.
11
+ # Exit codes: 0 success, 2 invalid input.
12
+
13
+ require 'base64'
14
+ require 'cgi'
15
+ require 'json'
16
+ require 'optparse'
17
+ require 'pathname'
18
+
19
+ CSS = <<~CSS
20
+ :root {
21
+ --bg: #f6f7f9; --fg: #1d2330; --muted: #5d6677; --card: #ffffff; --border: #d9dde5;
22
+ --changed: #b45309; --changed-bg: #fef3c7; --new: #1d4ed8; --new-bg: #dbeafe;
23
+ --deleted: #b91c1c; --deleted-bg: #fee2e2; --passed: #4b5563; --passed-bg: #e5e7eb;
24
+ --intended: #166534; --intended-bg: #dcfce7; --regression: #991b1b; --regression-bg: #fecaca;
25
+ --checker: #e9ebef;
26
+ }
27
+ @media (prefers-color-scheme: dark) {
28
+ :root {
29
+ --bg: #12151b; --fg: #e6e9ef; --muted: #9aa3b2; --card: #1b1f27; --border: #2e3440;
30
+ --changed: #fcd34d; --changed-bg: #422d06; --new: #93c5fd; --new-bg: #172554;
31
+ --deleted: #fca5a5; --deleted-bg: #450a0a; --passed: #cbd5e1; --passed-bg: #2b303a;
32
+ --intended: #86efac; --intended-bg: #052e16; --regression: #fecaca; --regression-bg: #7f1d1d;
33
+ --checker: #252a33;
34
+ }
35
+ }
36
+ * { box-sizing: border-box; }
37
+ body { margin: 0; padding: 16px 24px 48px; background: var(--bg); color: var(--fg);
38
+ font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
39
+ h1 { margin: 0 0 8px; font-size: 22px; }
40
+ h2 { margin: 32px 0 8px; font-size: 16px; font-family: ui-monospace, Menlo, monospace; word-break: break-all; }
41
+ .counts { display: flex; flex-wrap: wrap; gap: 8px; margin: 8px 0; }
42
+ .summary { margin: 12px 0; padding: 10px 14px; background: var(--card);
43
+ border: 1px solid var(--border); border-radius: 6px; white-space: pre-wrap; }
44
+ .badge { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 12px; font-weight: 600; }
45
+ .b-changed { color: var(--changed); background: var(--changed-bg); }
46
+ .b-new { color: var(--new); background: var(--new-bg); }
47
+ .b-deleted { color: var(--deleted); background: var(--deleted-bg); }
48
+ .b-passed, .b-noise { color: var(--passed); background: var(--passed-bg); }
49
+ .b-intended { color: var(--intended); background: var(--intended-bg); }
50
+ .b-regression { color: var(--regression); background: var(--regression-bg); }
51
+ .b-unknown { color: var(--muted); background: var(--passed-bg); }
52
+ .row { margin: 8px 0; padding: 10px 12px; background: var(--card);
53
+ border: 1px solid var(--border); border-radius: 6px; }
54
+ .row-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-bottom: 8px; }
55
+ .fname { font-family: ui-monospace, Menlo, monospace; font-size: 13px; word-break: break-all; }
56
+ .comment { margin: 0 0 8px; color: var(--muted); white-space: pre-wrap; }
57
+ .cols { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
58
+ .col h3 { margin: 0 0 4px; font-size: 12px; color: var(--muted); text-transform: uppercase; }
59
+ .col img { display: block; max-width: 100%; height: auto; border: 1px solid var(--border);
60
+ background: var(--checker); cursor: zoom-in; }
61
+ .col { overflow-x: auto; }
62
+ .none { color: var(--muted); font-style: italic; }
63
+ details > summary { cursor: pointer; color: var(--muted); margin: 8px 0; }
64
+ @media (max-width: 800px) { .cols { grid-template-columns: 1fr; } }
65
+ .lb { position: fixed; inset: 0; z-index: 100; display: flex; flex-direction: column;
66
+ background: rgba(8, 10, 14, 0.85); color: #f1f3f7; }
67
+ .lb[hidden] { display: none; }
68
+ .lb-bar { display: flex; align-items: center; gap: 12px; padding: 8px 16px;
69
+ background: rgba(8, 10, 14, 0.7); border-bottom: 1px solid rgba(255, 255, 255, 0.2); }
70
+ .lb-title { flex: 1; min-width: 0; font: 13px ui-monospace, Menlo, monospace; word-break: break-all; }
71
+ .lb-close { flex: none; width: 32px; height: 32px; border: 1px solid rgba(255, 255, 255, 0.4);
72
+ border-radius: 6px; background: transparent; color: inherit; font-size: 20px; line-height: 1; cursor: pointer; }
73
+ .lb-close:hover, .lb-close:focus-visible { background: rgba(255, 255, 255, 0.2); }
74
+ .lb-body { flex: 1; display: flex; overflow: auto; padding: 16px; }
75
+ .lb-body img { display: block; flex: none; max-width: none; margin: auto; cursor: default;
76
+ background: var(--checker); border: 1px solid var(--border); }
77
+ CSS
78
+
79
+ JS = <<~JS
80
+ (function () {
81
+ var lb = document.getElementById('lb');
82
+ var img = document.getElementById('lb-img');
83
+ var title = document.getElementById('lb-title');
84
+ function close() { lb.hidden = true; img.removeAttribute('src'); }
85
+ document.addEventListener('click', function (e) {
86
+ var t = e.target;
87
+ if (t.tagName === 'IMG' && t !== img && t.src) {
88
+ img.src = t.src;
89
+ img.alt = t.alt;
90
+ title.textContent = t.alt;
91
+ lb.hidden = false;
92
+ lb.querySelector('.lb-body').scrollTo(0, 0);
93
+ } else if (t === lb || t.classList.contains('lb-body') || t.classList.contains('lb-close')) {
94
+ close();
95
+ }
96
+ });
97
+ document.addEventListener('keydown', function (e) {
98
+ if (e.key === 'Escape' && !lb.hidden) { close(); }
99
+ });
100
+ })();
101
+ JS
102
+
103
+ # rubocop:disable Metrics/ClassLength
104
+ # Reads reg-cli output and renders the self-contained side-by-side HTML.
105
+ class CompareBuilder
106
+ # Raised for invalid input (missing directories, broken JSON); mapped to exit code 2.
107
+ class InputError < StandardError; end
108
+
109
+ WARN_BYTES = 50 * 1024 * 1024
110
+ STATUS_ORDER = %i[changed new deleted passed].freeze
111
+ VERDICTS = %w[intended regression noise].freeze
112
+
113
+ # reg-cli report.json key => status. When a path appears under several keys the later one wins,
114
+ # so the order here is significant (passed < deleted < new < changed).
115
+ REPORT_KEYS = {
116
+ 'passedItems' => :passed,
117
+ 'deletedItems' => :deleted,
118
+ 'newItems' => :new,
119
+ 'failedItems' => :changed,
120
+ }.freeze
121
+
122
+ Entry =
123
+ Struct.new(:path, :status, :before, :after, :diff, :note) do
124
+ def passed?
125
+ status == :passed
126
+ end
127
+
128
+ def changed?
129
+ status == :changed
130
+ end
131
+
132
+ # Images that get embedded; an unchanged screen has identical before/after, so only one is kept.
133
+ def images
134
+ passed? ? [after] : [before, after, diff]
135
+ end
136
+ end
137
+
138
+ def initialize(dir: 'tmp/screenshot-compare', notes: nil, title: 'Screenshot comparison', out: nil)
139
+ @dir = Pathname(dir)
140
+ @notes_path = Pathname(notes || @dir.join('notes.json'))
141
+ @title = title
142
+ @out = Pathname(out || @dir.join('compare.html'))
143
+ @summary = nil
144
+ @items = {}
145
+ end
146
+
147
+ def run
148
+ validate_inputs
149
+ report = load_json(@dir.join('report.json'))
150
+ load_notes
151
+ entries = build_entries(report)
152
+ warn_size(entries)
153
+ @out.dirname.mkpath
154
+ @out.write(render(entries))
155
+ @out.to_s
156
+ end
157
+
158
+ private
159
+
160
+ def validate_inputs
161
+ raise InputError, "directory not found: #{@dir}" unless @dir.directory?
162
+
163
+ %w[before after].each do |name|
164
+ raise InputError, "directory not found: #{@dir.join(name)}" unless @dir.join(name).directory?
165
+ end
166
+ raise InputError, "report.json not found: #{@dir.join('report.json')}" unless @dir.join('report.json').file?
167
+ end
168
+
169
+ # Parses a JSON file whose top level must be an object.
170
+ def load_json(path)
171
+ data = JSON.parse(path.read)
172
+ raise InputError, "#{path} must be a JSON object" unless data.is_a?(Hash)
173
+
174
+ data
175
+ rescue JSON::ParserError => e
176
+ raise InputError, "failed to parse #{path}: #{e.message}"
177
+ end
178
+
179
+ def load_notes
180
+ return unless @notes_path.file?
181
+
182
+ data = load_json(@notes_path)
183
+ @summary = data['summary']
184
+ items = data['items'].is_a?(Hash) ? data['items'] : {}
185
+ @items = items.each_with_object({}) { |(k, v), h| h[normalize(k)] = v.is_a?(Hash) ? v : {} }
186
+ end
187
+
188
+ def normalize(path)
189
+ path.to_s.sub(%r{\A(?:\./|/)+}, '')
190
+ end
191
+
192
+ def build_entries(report)
193
+ states = {}
194
+ REPORT_KEYS.each { |key, status| Array(report[key]).each { |p| states[normalize(p)] = status } }
195
+
196
+ states.map do |path, status|
197
+ before = status == :new ? nil : image_path('before', path)
198
+ after = status == :deleted ? nil : image_path('after', path)
199
+ diff = status == :changed ? image_path('diff', diff_name(path)) : nil
200
+ Entry.new(path, status, before, after, diff, @items.fetch(path, {}))
201
+ end
202
+ end
203
+
204
+ def diff_name(path)
205
+ path.sub(%r{\.[^./]+\z}, '.png')
206
+ end
207
+
208
+ def image_path(kind, rel)
209
+ candidate = @dir.join(kind, rel)
210
+ candidate.file? ? candidate : nil
211
+ end
212
+
213
+ # Estimates the base64-embedded size up front; only warns, generation continues.
214
+ def warn_size(entries)
215
+ raw = entries.sum { |e| e.images.compact.sum { |p| File.size(p) } }
216
+ estimated = raw * 4 / 3
217
+ return if estimated <= WARN_BYTES
218
+
219
+ mb = (estimated / 1024.0 / 1024).round(1)
220
+ warn "warning: embedded images total #{mb}MB (> 50MB); the HTML may be slow to open"
221
+ end
222
+
223
+ def data_uri(path)
224
+ "data:image/png;base64,#{Base64.strict_encode64(path.binread)}"
225
+ end
226
+
227
+ def esc(value)
228
+ CGI.escapeHTML(value.to_s)
229
+ end
230
+
231
+ def badge(css, text)
232
+ %(<span class="badge b-#{css}">#{esc(text)}</span>)
233
+ end
234
+
235
+ def render(entries)
236
+ <<~HTML
237
+ <!DOCTYPE html>
238
+ <html lang="en">
239
+ <head>
240
+ <meta charset="utf-8">
241
+ <meta name="viewport" content="width=device-width, initial-scale=1">
242
+ <title>#{esc(@title)}</title>
243
+ <style>
244
+ #{CSS}</style>
245
+ </head>
246
+ <body>
247
+ <h1>#{esc(@title)}</h1>
248
+ #{render_counts(entries)}
249
+ #{render_summary}
250
+ #{render_sections(entries)}
251
+ #{render_lightbox}
252
+ <script>
253
+ #{JS}</script>
254
+ </body>
255
+ </html>
256
+ HTML
257
+ end
258
+
259
+ def render_lightbox
260
+ <<~HTML.chomp
261
+ <div id="lb" class="lb" hidden role="dialog" aria-modal="true" aria-label="Image viewer">
262
+ <div class="lb-bar"><span id="lb-title" class="lb-title"></span><button type="button" class="lb-close" aria-label="Close">&times;</button></div>
263
+ <div class="lb-body"><img id="lb-img" alt=""></div>
264
+ </div>
265
+ HTML
266
+ end
267
+
268
+ def render_counts(entries)
269
+ badges = STATUS_ORDER.map { |s| badge(s, "#{s}: #{entries.count { |e| e.status == s }}") }
270
+ %(<div class="counts">#{badges.join}</div>)
271
+ end
272
+
273
+ def render_summary
274
+ return '' if @summary.to_s.strip.empty?
275
+
276
+ %(<div class="summary">#{esc(@summary)}</div>)
277
+ end
278
+
279
+ def render_sections(entries)
280
+ sections = entries.group_by { |e| File.dirname(e.path) }
281
+ ordered = sections.sort_by { |dir, list| [list.all?(&:passed?) ? 1 : 0, dir] }
282
+ ordered.map { |dir, list| render_section(dir, list.sort_by(&:path)) }.join("\n")
283
+ end
284
+
285
+ def render_section(dir, list)
286
+ passed, active = list.partition(&:passed?)
287
+ parts = [%(<section>\n<h2>#{esc(dir)}</h2>)]
288
+ parts.concat(active.map { |e| render_row(e) })
289
+ unless passed.empty?
290
+ parts << %(<details><summary>#{passed.size} unchanged</summary>)
291
+ parts.concat(passed.map { |e| render_row(e) })
292
+ parts << '</details>'
293
+ end
294
+ parts << '</section>'
295
+ parts.join("\n")
296
+ end
297
+
298
+ def render_row(entry)
299
+ <<~HTML.chomp
300
+ <div class="row">
301
+ <div class="row-head">#{badge(entry.status, entry.status)}#{verdict_badge(entry.note)}<span class="fname">#{esc(File.basename(entry.path))}</span></div>
302
+ #{comment_html(entry.note)}
303
+ <div class="cols">
304
+ #{render_columns(entry)}
305
+ </div>
306
+ </div>
307
+ HTML
308
+ end
309
+
310
+ def render_columns(entry)
311
+ return column('before = after', entry.after, entry.path) if entry.passed?
312
+
313
+ before = column('before', entry.before, entry.path)
314
+ after = column('after', entry.after, entry.path)
315
+ "#{before}\n#{after}\n#{column('diff', entry.diff, entry.path, show: entry.changed?)}"
316
+ end
317
+
318
+ def comment_html(note)
319
+ text = note['comment'].to_s
320
+ text.empty? ? '' : %(<p class="comment">#{esc(text)}</p>)
321
+ end
322
+
323
+ def verdict_badge(note)
324
+ return '' unless note['verdict']
325
+
326
+ verdict = note['verdict'].to_s
327
+ badge(VERDICTS.include?(verdict) ? verdict : 'unknown', verdict)
328
+ end
329
+
330
+ def column(label, path, rel, show: true)
331
+ return '' unless show
332
+
333
+ inner =
334
+ if path
335
+ %(<img src="#{data_uri(path)}" alt="#{esc(label)}: #{esc(rel)}" loading="lazy">)
336
+ else
337
+ '<span class="none">(none)</span>'
338
+ end
339
+ %(<div class="col"><h3>#{esc(label)}</h3>#{inner}</div>)
340
+ end
341
+ end
342
+ # rubocop:enable Metrics/ClassLength
343
+
344
+ options = {}
345
+ parser =
346
+ OptionParser.new do |o|
347
+ o.banner = 'usage: build-html.rb [options]'
348
+ o.on('--dir DIR', 'directory holding before/ after/ diff/ report.json') { |v| options[:dir] = v }
349
+ o.on('--notes FILE', 'notes.json (default: <dir>/notes.json, ignored if missing)') { |v| options[:notes] = v }
350
+ o.on('--title TITLE', 'page title') { |v| options[:title] = v }
351
+ o.on('--out FILE', 'output html (default: <dir>/compare.html)') { |v| options[:out] = v }
352
+ end
353
+
354
+ begin
355
+ parser.parse!
356
+ puts CompareBuilder.new(**options).run
357
+ rescue CompareBuilder::InputError, OptionParser::ParseError => e
358
+ warn "error: #{e.message}"
359
+ exit(2)
360
+ end
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env bash
2
+ # Diff a before/after set of screenshots using reg-cli.
3
+ # Fixes reg-cli's argument order (actual -> expected -> diff) and report paths
4
+ # to prevent mix-ups on the caller's side.
5
+ #
6
+ # NOTE: does not open the report. The agent verifies report.json / diff images
7
+ # first, then generates the HTML via build-html.rb after verification.
8
+ #
9
+ # Usage:
10
+ # scripts/reg-diff.sh <after_dir> <before_dir> [out_dir]
11
+ # after_dir : screenshot directory for after (working tree) = reg-cli's actual
12
+ # before_dir : screenshot directory for before (HEAD) = reg-cli's expected
13
+ # out_dir : output destination (default tmp/screenshot-compare). diff/report.html/report.json written here
14
+ #
15
+ # Exit codes:
16
+ # 0 ... no diff (no visual change)
17
+ # 1 ... diff detected (expected in this skill's flow, not an error)
18
+ # 2 ... execution error such as invalid arguments or missing input directory
19
+
20
+ set -u
21
+
22
+ after_dir=${1:-}
23
+ before_dir=${2:-}
24
+ out_dir=${3:-tmp/screenshot-compare}
25
+
26
+ if [[ -z "$after_dir" || -z "$before_dir" ]]; then
27
+ echo "usage: reg-diff.sh <after_dir> <before_dir> [out_dir]" >&2
28
+ exit 2
29
+ fi
30
+ for d in "$after_dir" "$before_dir"; do
31
+ if [[ ! -d "$d" ]]; then
32
+ echo "error: directory not found: $d" >&2
33
+ exit 2
34
+ fi
35
+ done
36
+
37
+ diff_dir="$out_dir/diff"
38
+ report_html="$out_dir/report.html"
39
+ report_json="$out_dir/report.json"
40
+ mkdir -p "$diff_dir"
41
+
42
+ # Pass args in the order actual(after) -> expected(before) -> diff.
43
+ npx reg-cli "$after_dir" "$before_dir" "$diff_dir" \
44
+ --report "$report_html" \
45
+ --json "$report_json"
46
+ reg_status=$?
47
+
48
+ # reg-cli exits non-zero (1) when a diff is detected. That's expected, so don't abort here.
49
+ # Don't open the report (the HTML is generated by build-html.rb after verification).
50
+ echo "---"
51
+ echo "reg-cli exit=$reg_status (0=no diff, 1=diff detected)"
52
+ echo "report.html: $report_html # reg-cli built-in report (the side-by-side HTML comes from build-html.rb)"
53
+ echo "report.json: $report_json"
54
+ echo "diff images: $diff_dir"
55
+
56
+ exit "$reg_status"
@@ -0,0 +1,99 @@
1
+ #!/usr/bin/env bash
2
+ # Resolve the starting ref for the "before" worktree according to a priority order.
3
+ #
4
+ # Priority:
5
+ # 1. <ref> argument given -> use that ref as baseline
6
+ # 2. no argument & uncommitted changes present -> HEAD as baseline (current behavior)
7
+ # 3. no argument & clean tree -> base branch as baseline
8
+ #
9
+ # If baseline is anything other than HEAD, the worktree starting point is
10
+ # merge-base <baseline> HEAD (equivalent to a three-dot diff).
11
+ # If it's HEAD, no merge-base is needed and "HEAD" is returned as-is.
12
+ #
13
+ # stdout : one line with the ref/SHA to pass to worktree add
14
+ # stderr : human-readable explanation of the resolution
15
+ # exit : 0=resolved, 2=execution error
16
+
17
+ set -u
18
+
19
+ arg_ref=${1:-}
20
+
21
+ log() { echo "$@" >&2; }
22
+
23
+ # Check whether a ref actually exists (existence check only, no side effects)
24
+ ref_exists() { git rev-parse --verify --quiet "$1" >/dev/null; }
25
+
26
+ # Resolve the base branch (order follows github.com/aki77/claude-code-review as reference)
27
+ resolve_base_branch() {
28
+ local cur cfg branch cand upstream sym
29
+ cur=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
30
+
31
+ # 1. branch.<cur>.github-pr-base-branch
32
+ # NOTE: the value may be in "owner#repo#branch" form (VSCode GitHub PR extension).
33
+ # Extract the last '#' segment as the branch name and prefer origin/.
34
+ # The raw value can't be passed to rev-parse as-is.
35
+ cfg=$(git config "branch.$cur.github-pr-base-branch" 2>/dev/null)
36
+ if [ -n "$cfg" ]; then
37
+ branch=${cfg##*#}
38
+ for cand in "origin/$branch" "$branch" "$cfg"; do
39
+ if ref_exists "$cand"; then echo "$cand"; return 0; fi
40
+ done
41
+ fi
42
+
43
+ # 2. branch.<cur>.vscode-merge-base (e.g. origin/release-candidate; usable as-is)
44
+ cfg=$(git config "branch.$cur.vscode-merge-base" 2>/dev/null)
45
+ if [ -n "$cfg" ] && ref_exists "$cfg"; then
46
+ echo "$cfg"; return 0
47
+ fi
48
+
49
+ # 3. @{upstream}
50
+ # Skip it when it tracks the current branch's own remote counterpart
51
+ # (e.g. feature -> origin/feature): that is not a base branch, and its
52
+ # merge-base with HEAD would collapse the baseline to (nearly) HEAD.
53
+ upstream=$(git rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null)
54
+ if [ -n "$upstream" ] && [ "$(git config "branch.$cur.merge" 2>/dev/null)" != "refs/heads/$cur" ]; then
55
+ echo "$upstream"; return 0
56
+ fi
57
+
58
+ # 4. origin/HEAD (e.g. refs/remotes/origin/release-candidate)
59
+ sym=$(git symbolic-ref --quiet refs/remotes/origin/HEAD 2>/dev/null)
60
+ if [ -n "$sym" ]; then
61
+ echo "${sym#refs/remotes/}"; return 0
62
+ fi
63
+
64
+ return 1
65
+ }
66
+
67
+ emit_mergebase() {
68
+ local baseline=$1 mb
69
+ if ! ref_exists "$baseline"; then
70
+ log "error: baseline ref not found: $baseline"
71
+ exit 2
72
+ fi
73
+ mb=$(git merge-base "$baseline" HEAD 2>/dev/null)
74
+ if [ -z "$mb" ]; then
75
+ log "error: no merge-base between $baseline and HEAD"
76
+ exit 2
77
+ fi
78
+ log "baseline: '$baseline' -> merge-base $mb"
79
+ echo "$mb"
80
+ }
81
+
82
+ # --- Priority resolution ---
83
+ if [ -n "$arg_ref" ]; then
84
+ log "baseline mode: explicit ref '$arg_ref'"
85
+ emit_mergebase "$arg_ref"
86
+ exit 0
87
+ fi
88
+
89
+ if [ -n "$(git status --short)" ]; then
90
+ log "baseline mode: uncommitted changes present -> HEAD"
91
+ echo "HEAD"
92
+ exit 0
93
+ fi
94
+
95
+ log "baseline mode: clean tree -> base branch"
96
+ base=$(resolve_base_branch) || { log "error: could not resolve base branch"; exit 2; }
97
+ log "resolved base branch: $base"
98
+ emit_mergebase "$base"
99
+ exit 0
@@ -47,8 +47,11 @@ resolve_base_branch() {
47
47
  fi
48
48
 
49
49
  # 3. @{upstream}
50
+ # Skip it when it tracks the current branch's own remote counterpart
51
+ # (e.g. feature -> origin/feature): that is not a base branch, and its
52
+ # merge-base with HEAD would collapse the baseline to (nearly) HEAD.
50
53
  upstream=$(git rev-parse --abbrev-ref --symbolic-full-name '@{upstream}' 2>/dev/null)
51
- if [ -n "$upstream" ]; then
54
+ if [ -n "$upstream" ] && [ "$(git config "branch.$cur.merge" 2>/dev/null)" != "refs/heads/$cur" ]; then
52
55
  echo "$upstream"; return 0
53
56
  fi
54
57
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: capybara-storyboard
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.0
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - aki
@@ -50,6 +50,10 @@ files:
50
50
  - lib/capybara/storyboard/version.rb
51
51
  - sig/capybara/storyboard.rbs
52
52
  - skills/capybara-storyboard/SKILL.md
53
+ - skills/screenshot-compare/SKILL.md
54
+ - skills/screenshot-compare/scripts/build-html.rb
55
+ - skills/screenshot-compare/scripts/reg-diff.sh
56
+ - skills/screenshot-compare/scripts/resolve-baseline.sh
53
57
  - skills/visual-regression-test/README.md
54
58
  - skills/visual-regression-test/SKILL.md
55
59
  - skills/visual-regression-test/scripts/reg-diff.sh
@@ -76,7 +80,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
76
80
  - !ruby/object:Gem::Version
77
81
  version: '0'
78
82
  requirements: []
79
- rubygems_version: 4.0.15
83
+ rubygems_version: 4.0.20
80
84
  specification_version: 4
81
85
  summary: Capture and visualize Capybara system test flows as screenshot storyboards.
82
86
  test_files: []