Skip to content

Find code by asking what it does. A CLI for coding agents that uses Jev to discover relevant files and source context.

Sync skills from dzhng/skills@f2fbf92

David Zhang620468877c3a
diff --git a/.agents/skills/claude/SKILL.md b/.agents/skills/claude/SKILL.md
index d89941c..f5ce44b 100644
--- a/.agents/skills/claude/SKILL.md
+++ b/.agents/skills/claude/SKILL.md
@@ -63,7 +63,17 @@ the user explicitly asks it to edit.
output, or labelled inferences.
2. Prefer a read-only tool surface for reviews:
`--tools "Read,Grep,Glob,Bash" --permission-mode dontAsk`.
-3. Triage every finding against the code before acting. Report what Claude
+3. **Never grant fewer tools than your output contract requires.** Read your
+ own prompt and ask which tool produces each claim you demanded. A judge that
+ cannot run a command will still answer a question posed in numbers — with
+ numbers, self-consistent and measured from nothing, and with the artifacts
+ it says it wrote. Trimming the tool surface does not make the answer
+ cautious; it makes the fabrication harder to spot. Either grant the tool or
+ stop asking for the claim.
+4. Require the receipt with the number: any quantity in the response must
+ arrive with the command that produced it and that command's output. Findings
+ that fail this are struck, not discounted.
+5. Triage every finding against the code before acting. Report what Claude
flagged, what you accepted, and what you dismissed.
## Implementation — explicit ask only
@@ -112,3 +122,5 @@ classify the failure before retrying.
- Keep Claude's writes out of the working tree unless delegation was explicit.
- Do not touch the same working tree while Claude is making edits.
- Treat Claude output as evidence to verify, not authority to relay.
+- Match the tool surface to the output contract; a claim shape you granted no
+ tool for comes back invented.
diff --git a/.agents/skills/compare-screenshots/SKILL.md b/.agents/skills/compare-screenshots/SKILL.md
index 4019709..5880731 100644
--- a/.agents/skills/compare-screenshots/SKILL.md
+++ b/.agents/skills/compare-screenshots/SKILL.md
@@ -154,9 +154,11 @@ Keep comparison scripts inside the skill or a temporary workspace, not in
product code, unless the product genuinely needs screenshot comparison at
runtime.
-- `scripts/visual-parity-diff.mjs` is a reusable local helper. Run it with
- `REFERENCE_DIR=<png-folder>`, `CANDIDATE_DIR=<png-folder>`, and optional
- `OUT_DIR=<artifact-folder>`. `REPORT_ORDER=a,b,c` pins ordering;
+- `scripts/visual-parity-diff.mjs` is a reusable local helper. Its PNG and
+ pixel-diff runtime is bundled with the skill, so target repositories do not
+ need `pngjs` or `pixelmatch`. Run it with `REFERENCE_DIR=<png-folder>`,
+ `CANDIDATE_DIR=<png-folder>`, and optional `OUT_DIR=<artifact-folder>`.
+ `REPORT_ORDER=a,b,c` pins ordering;
`CROPS_JSON=<file>` adds labeled crops (keyed by image id, each crop in pixels
or `{ "unit": "ratio" }` normalized bounds). Pair reports carry a
`sceneMetrics` block per side.
diff --git a/.agents/skills/compare-screenshots/references/subagent-visual-review.md b/.agents/skills/compare-screenshots/references/subagent-visual-review.md
index 8053ce6..c4cd6b0 100644
--- a/.agents/skills/compare-screenshots/references/subagent-visual-review.md
+++ b/.agents/skills/compare-screenshots/references/subagent-visual-review.md
@@ -14,6 +14,9 @@ judgment.
- Supply full frames and matched detail crops including surrounding space.
Withhold previous verdicts, implementation details and the author's preferred
answer; do not withhold the target needed to judge fidelity.
+- Give it a shell only if you want numbers back. Images alone buy a description;
+ a judge asked for measurements it has no way to take answers in the register
+ the question was posed in and invents them.
## Prompt
@@ -32,7 +35,8 @@ Compare Image A and Image B. Report:
feature it crosses. Report local discrepancies even if everything is legible.
4. Give a per-feature reference observation → candidate observation →
pass/fix/uncertain record. Distinguish solid/core edges from faint fringe;
- measure endpoints and gaps relative to visible anchors. Verify crops include
+ locate endpoints and gaps relative to visible anchors, in words unless you
+ quote the command and output that measured them. Verify crops include
the entire feature. Request paired effect-on/off captures when background
texture makes extent ambiguous. A small discrepancy still needs resolution;
do not label it acceptable merely because the whole looks similar.
@@ -42,6 +46,12 @@ Compare Image A and Image B. Report:
When an approved reference is identified, judge fidelity to it. Otherwise do not
assume either image is the target. Overall attractiveness does not excuse a
local mismatch. Judge only from visible pixels and supplied design requirements.
+
+Describe what you see in words. State no pixel value, luminance, percentage,
+ratio, count, or offset unless you ran a command that produced it and you quote
+that command and its output beside the number. "Image B reads clearly darker
+along the lower edge" is a finding; a luminance mean you did not measure is a
+fabrication.
```
## How To Use The Result
@@ -49,6 +59,10 @@ local mismatch. Judge only from visible pixels and supplied design requirements.
- Treat the subagent result as independent evidence about which image is less
wrong, not a replacement for metrics or your own inspection — and not a vote
for whichever image is the baseline.
+- Run the returned review through the receipts checker that ships with
+ `screenshot-critique` before you read it, and strike whatever it flags. An
+ unsupported number reads as the strongest evidence in the review precisely
+ because it is numeric, so it has to be removed before it can persuade you.
- If the subagent flags wrong camera, mismatched state, missing content, or
visible artifacts, fix capture/rendering quality before judging the rest.
- Preserve the findings, not just the headline verdict. A “pass” accompanied
diff --git a/.agents/skills/compare-screenshots/scripts/visual-parity-diff.eval.mjs b/.agents/skills/compare-screenshots/scripts/visual-parity-diff.eval.mjs
index 0888d1d..0ef3dfb 100644
--- a/.agents/skills/compare-screenshots/scripts/visual-parity-diff.eval.mjs
+++ b/.agents/skills/compare-screenshots/scripts/visual-parity-diff.eval.mjs
@@ -2,10 +2,9 @@
//
// Every fixture is generated here, so the correct answer is known by
// construction rather than read back from a previous run — a snapshot of
-// current output would happily bless a bug. Run it from a repo where the
-// script's own dependencies resolve:
+// current output would happily bless a bug. Dependencies are bundled in vendor/:
//
-// REPO_ROOT=<repo> node visual-parity-diff.eval.mjs
+// node visual-parity-diff.eval.mjs
//
// Exits nonzero on the first failing expectation set, printing every check.
@@ -19,8 +18,8 @@ import { fileURLToPath } from 'node:url';
const here = dirname(fileURLToPath(import.meta.url));
const script = resolve(here, 'visual-parity-diff.mjs');
const repoRoot = resolve(process.env.REPO_ROOT ?? process.cwd());
-const require = createRequire(resolve(repoRoot, 'web/package.json'));
-const { PNG } = require('pngjs');
+const require = createRequire(import.meta.url);
+const { PNG } = require('../vendor/pngjs');
const checks = [];
const check = (name, pass, detail = '') => checks.push({ name, pass, detail });
diff --git a/.agents/skills/compare-screenshots/scripts/visual-parity-diff.mjs b/.agents/skills/compare-screenshots/scripts/visual-parity-diff.mjs
index 8767e66..61b43bb 100644
--- a/.agents/skills/compare-screenshots/scripts/visual-parity-diff.mjs
+++ b/.agents/skills/compare-screenshots/scripts/visual-parity-diff.mjs
@@ -5,9 +5,9 @@ import { pathToFileURL } from 'node:url';
const cwd = resolve(process.cwd());
const repoRoot = process.env.REPO_ROOT ? resolve(process.env.REPO_ROOT) : basename(cwd) === 'web' ? resolve(cwd, '..') : cwd;
-const require = createRequire(resolve(repoRoot, 'web/package.json'));
-const { PNG } = require('pngjs');
-const pixelmatch = (await import(require.resolve('pixelmatch'))).default;
+const require = createRequire(import.meta.url);
+const { PNG } = require('../vendor/pngjs');
+const pixelmatch = (await import('../vendor/pixelmatch/index.js')).default;
const currentDir = process.env.REFERENCE_DIR ? requiredDir('REFERENCE_DIR') : null;
const candidateDir = requiredDir('CANDIDATE_DIR');
diff --git a/.agents/skills/compare-screenshots/test/fixtures/target-without-helper-packages/README.md b/.agents/skills/compare-screenshots/test/fixtures/target-without-helper-packages/README.md
new file mode 100644
index 0000000..07ac7d7
--- /dev/null
+++ b/.agents/skills/compare-screenshots/test/fixtures/target-without-helper-packages/README.md
@@ -0,0 +1 @@
+Fixture repository intentionally has no package.json or node_modules.
diff --git a/.agents/skills/compare-screenshots/test/fixtures/target-without-helper-packages/candidate/fixture.png b/.agents/skills/compare-screenshots/test/fixtures/target-without-helper-packages/candidate/fixture.png
new file mode 100644
index 0000000..2f1fdcd
Binary files /dev/null and b/.agents/skills/compare-screenshots/test/fixtures/target-without-helper-packages/candidate/fixture.png differ
diff --git a/.agents/skills/compare-screenshots/test/fixtures/target-without-helper-packages/reference/fixture.png b/.agents/skills/compare-screenshots/test/fixtures/target-without-helper-packages/reference/fixture.png
new file mode 100644
index 0000000..9fe96e1
Binary files /dev/null and b/.agents/skills/compare-screenshots/test/fixtures/target-without-helper-packages/reference/fixture.png differ
diff --git a/.agents/skills/compare-screenshots/test/visual-parity-diff.test.mjs b/.agents/skills/compare-screenshots/test/visual-parity-diff.test.mjs
new file mode 100644
index 0000000..c4c3078
--- /dev/null
+++ b/.agents/skills/compare-screenshots/test/visual-parity-diff.test.mjs
@@ -0,0 +1,68 @@
+import assert from 'node:assert/strict';
+import { access, readFile, rm } from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { spawnSync } from 'node:child_process';
+import test from 'node:test';
+
+const testDir = dirname(fileURLToPath(import.meta.url));
+const skillDir = resolve(testDir, '..');
+const helper = resolve(skillDir, 'scripts/visual-parity-diff.mjs');
+const targetRepo = resolve(testDir, 'fixtures/target-without-helper-packages');
+const outDir = resolve(targetRepo, 'visual-diff-test-output');
+const controlOutDir = resolve(targetRepo, 'visual-diff-control-output');
+
+test('runs from a target repository without pngjs or pixelmatch', async () => {
+ const targetRequire = createRequire(resolve(targetRepo, 'web/package.json'));
+ for (const dependency of ['pngjs', 'pixelmatch']) {
+ assert.throws(
+ () => targetRequire.resolve(dependency),
+ (error) => error?.code === 'MODULE_NOT_FOUND',
+ `${dependency} must remain unavailable to the target repository`,
+ );
+ }
+
+ try {
+ const result = spawnSync(process.execPath, [helper], {
+ cwd: targetRepo,
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ REFERENCE_DIR: 'reference',
+ CANDIDATE_DIR: 'candidate',
+ OUT_DIR: 'visual-diff-test-output',
+ },
+ });
+ assert.equal(result.status, 0, result.stderr || result.stdout);
+
+ const report = JSON.parse(await readFile(resolve(outDir, 'visual-parity-diff.json'), 'utf8'));
+ assert.equal(report.pairCount, 1);
+ assert.equal(report.results[0].id, 'fixture');
+ assert.equal(report.results[0].grayscale.pixelmatchRatio, 1);
+ await access(resolve(outDir, 'fixture-pixelmatch.png'));
+ } finally {
+ await rm(outDir, { recursive: true, force: true });
+ }
+});
+
+test('preserves the identical-image control case', async () => {
+ try {
+ const result = spawnSync(process.execPath, [helper], {
+ cwd: targetRepo,
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ REFERENCE_DIR: 'reference',
+ CANDIDATE_DIR: 'reference',
+ OUT_DIR: 'visual-diff-control-output',
+ },
+ });
+ assert.equal(result.status, 0, result.stderr || result.stdout);
+
+ const report = JSON.parse(await readFile(resolve(controlOutDir, 'visual-parity-diff.json'), 'utf8'));
+ assert.equal(report.results[0].grayscale.pixelmatchRatio, 0);
+ } finally {
+ await rm(controlOutDir, { recursive: true, force: true });
+ }
+});
diff --git a/.agents/skills/compare-screenshots/vendor/pixelmatch/LICENSE b/.agents/skills/compare-screenshots/vendor/pixelmatch/LICENSE
new file mode 100644
index 0000000..3194b3c
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pixelmatch/LICENSE
@@ -0,0 +1,15 @@
+ISC License
+
+Copyright (c) 2025, Mapbox
+
+Permission to use, copy, modify, and/or distribute this software for any purpose
+with or without fee is hereby granted, provided that the above copyright notice
+and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
+OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
+TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
+THIS SOFTWARE.
diff --git a/.agents/skills/compare-screenshots/vendor/pixelmatch/index.js b/.agents/skills/compare-screenshots/vendor/pixelmatch/index.js
new file mode 100644
index 0000000..be64dc9
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pixelmatch/index.js
@@ -0,0 +1,314 @@
+/**
+ * Compare two equally sized images, pixel by pixel.
+ *
+ * @param {Uint8Array | Uint8ClampedArray} img1 First image data.
+ * @param {Uint8Array | Uint8ClampedArray} img2 Second image data.
+ * @param {Uint8Array | Uint8ClampedArray | void} output Image data to write the diff to, if provided.
+ * @param {number} width Input images width.
+ * @param {number} height Input images height.
+ *
+ * @param {Object} [options]
+ * @param {number} [options.threshold=0.1] Matching threshold (0 to 1); smaller is more sensitive.
+ * @param {boolean} [options.includeAA=false] Whether to skip anti-aliasing detection.
+ * @param {number} [options.alpha=0.1] Opacity of original image in diff output.
+ * @param {[number, number, number]} [options.aaColor=[255, 255, 0]] Color of anti-aliased pixels in diff output.
+ * @param {[number, number, number]} [options.diffColor=[255, 0, 0]] Color of different pixels in diff output.
+ * @param {[number, number, number]} [options.diffColorAlt=options.diffColor] Whether to detect dark on light differences between img1 and img2 and set an alternative color to differentiate between the two.
+ * @param {boolean} [options.diffMask=false] Draw the diff over a transparent background (a mask).
+ * @param {boolean} [options.checkerboard=true] Whether to blend semi-transparent pixels against a checkerboard pattern (true) or plain white (false) when comparing.
+ *
+ * @return {number} The number of mismatched pixels.
+ */
+export default function pixelmatch(img1, img2, output, width, height, options = {}) {
+ const {
+ threshold = 0.1,
+ alpha = 0.1,
+ aaColor = [255, 255, 0],
+ diffColor = [255, 0, 0],
+ checkerboard = true,
+ includeAA, diffColorAlt, diffMask
+ } = options;
+
+ if (!isPixelData(img1) || !isPixelData(img2) || (output && !isPixelData(output)))
+ throw new Error('Image data: Uint8Array, Uint8ClampedArray or Buffer expected.');
+
+ if (img1.length !== img2.length || (output && output.length !== img1.length))
+ throw new Error(`Image sizes do not match. Image 1 size: ${img1.length}, image 2 size: ${img2.length}`);
+
+ if (img1.length !== width * height * 4) throw new Error(`Image data size does not match width/height. Expecting ${width * height * 4}. Got ${img1.length}`);
+
+ // check if images are identical
+ const len = width * height;
+ const a32 = new Uint32Array(img1.buffer, img1.byteOffset, len);
+ const b32 = new Uint32Array(img2.buffer, img2.byteOffset, len);
+ let identical = true;
+
+ for (let i = 0; i < len; i++) {
+ if (a32[i] !== b32[i]) { identical = false; break; }
+ }
+ if (identical) { // fast path if identical
+ if (output && !diffMask) {
+ for (let i = 0, pos = 0; i < len; i++, pos += 4) drawGrayPixel(img1, pos, alpha, output);
+ }
+ return 0;
+ }
+
+ // maximum acceptable square distance between two colors;
+ // 35215 is the maximum possible value for the YIQ difference metric
+ const maxDelta = 35215 * threshold * threshold;
+ const [aaR, aaG, aaB] = aaColor;
+ const [diffR, diffG, diffB] = diffColor;
+ const [altR, altG, altB] = diffColorAlt || diffColor;
+ let diff = 0;
+
+ // compare each pixel of one image against the other one
+ for (let i = 0, pos = 0; i < len; i++, pos += 4) {
+ // squared YUV distance between colors at this pixel position, negative if the img2 pixel is darker
+ const delta = a32[i] === b32[i] ? 0 : colorDelta(img1, img2, pos, pos, checkerboard);
+
+ // the color difference is above the threshold
+ if (Math.abs(delta) > maxDelta) {
+ const x = i % width;
+ const y = (i / width) | 0;
+ // check it's a real rendering difference or just anti-aliasing
+ const isExcludedAA = !includeAA && (antialiased(img1, x, y, width, height, a32, b32, checkerboard) || antialiased(img2, x, y, width, height, b32, a32, checkerboard));
+ if (isExcludedAA) {
+ // one of the pixels is anti-aliasing; draw as yellow and do not count as difference
+ // note that we do not include such pixels in a mask
+ if (output && !diffMask) drawPixel(output, pos, aaR, aaG, aaB);
+
+ } else {
+ // found substantial difference not caused by anti-aliasing; draw it as such
+ if (output) {
+ if (delta < 0) {
+ drawPixel(output, pos, altR, altG, altB);
+ } else {
+ drawPixel(output, pos, diffR, diffG, diffB);
+ }
+ }
+ diff++;
+ }
+
+ } else if (output && !diffMask) {
+ // pixels are similar; draw background as grayscale image blended with white
+ drawGrayPixel(img1, pos, alpha, output);
+ }
+ }
+
+ // return the number of different pixels
+ return diff;
+}
+
+/** @param {Uint8Array | Uint8ClampedArray} arr */
+function isPixelData(arr) {
+ // work around instanceof Uint8Array not working properly in some Jest environments
+ return ArrayBuffer.isView(arr) && arr.BYTES_PER_ELEMENT === 1;
+}
+
+/**
+ * Check if a pixel is likely a part of anti-aliasing;
+ * based on "Anti-aliased Pixel and Intensity Slope Detector" paper by V. Vysniauskas, 2009
+ * @param {Uint8Array | Uint8ClampedArray} img
+ * @param {number} x1
+ * @param {number} y1
+ * @param {number} width
+ * @param {number} height
+ * @param {Uint32Array} a32
+ * @param {Uint32Array} b32
+ * @param {boolean} checkerboard
+ */
+function antialiased(img, x1, y1, width, height, a32, b32, checkerboard) {
+ const x0 = Math.max(x1 - 1, 0);
+ const y0 = Math.max(y1 - 1, 0);
+ const x2 = Math.min(x1 + 1, width - 1);
+ const y2 = Math.min(y1 + 1, height - 1);
+ const pos4 = (y1 * width + x1) * 4;
+ // cache the center pixel's RGBA once instead of re-reading it on every neighbor comparison
+ const cr = img[pos4];
+ const cg = img[pos4 + 1];
+ const cb = img[pos4 + 2];
+ const ca = img[pos4 + 3];
+ let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0;
+ let min = 0;
+ let max = 0;
+ let minX = 0;
+ let minY = 0;
+ let maxX = 0;
+ let maxY = 0;
+
+ // go through 8 adjacent pixels
+ for (let x = x0; x <= x2; x++) {
+ for (let y = y0; y <= y2; y++) {
+ if (x === x1 && y === y1) continue;
+
+ // brightness delta between the center pixel and adjacent one
+ const delta = brightnessDelta(img, pos4, (y * width + x) * 4, cr, cg, cb, ca, checkerboard);
+
+ // count the number of equal, darker and brighter adjacent pixels
+ if (delta === 0) {
+ zeroes++;
+ // if found more than 2 equal siblings, it's definitely not anti-aliasing
+ if (zeroes > 2) return false;
+
+ // remember the darkest pixel
+ } else if (delta < min) {
+ min = delta;
+ minX = x;
+ minY = y;
+
+ // remember the brightest pixel
+ } else if (delta > max) {
+ max = delta;
+ maxX = x;
+ maxY = y;
+ }
+ }
+ }
+
+ // if there are no both darker and brighter pixels among siblings, it's not anti-aliasing
+ if (min === 0 || max === 0) return false;
+
+ // if either the darkest or the brightest pixel has 3+ equal siblings in both images
+ // (definitely not anti-aliased), this pixel is anti-aliased
+ return (hasManySiblings(a32, minX, minY, width, height) && hasManySiblings(b32, minX, minY, width, height)) ||
+ (hasManySiblings(a32, maxX, maxY, width, height) && hasManySiblings(b32, maxX, maxY, width, height));
+}
+
+/**
+ * Check if a pixel has 3+ adjacent pixels of the same color.
+ * @param {Uint32Array} img
+ * @param {number} x1
+ * @param {number} y1
+ * @param {number} width
+ * @param {number} height
+ */
+function hasManySiblings(img, x1, y1, width, height) {
+ const x0 = Math.max(x1 - 1, 0);
+ const y0 = Math.max(y1 - 1, 0);
+ const x2 = Math.min(x1 + 1, width - 1);
+ const y2 = Math.min(y1 + 1, height - 1);
+ const val = img[y1 * width + x1];
+ let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0;
+
+ // go through 8 adjacent pixels
+ for (let x = x0; x <= x2; x++) {
+ for (let y = y0; y <= y2; y++) {
+ if (x === x1 && y === y1) continue;
+ zeroes += +(val === img[y * width + x]);
+ if (zeroes > 2) return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Calculate color difference according to the paper "Measuring perceived color difference
+ * using YIQ NTSC transmission color space in mobile applications" by Y. Kotsarenko and F. Ramos.
+ * Caller guarantees the two pixels differ, so the early-zero check is omitted.
+ * @param {Uint8Array | Uint8ClampedArray} img1
+ * @param {Uint8Array | Uint8ClampedArray} img2
+ * @param {number} k
+ * @param {number} m
+ * @param {boolean} checkerboard
+ */
+function colorDelta(img1, img2, k, m, checkerboard) {
+ const r1 = img1[k];
+ const g1 = img1[k + 1];
+ const b1 = img1[k + 2];
+ const a1 = img1[k + 3];
+ const r2 = img2[m];
+ const g2 = img2[m + 1];
+ const b2 = img2[m + 2];
+ const a2 = img2[m + 3];
+
+ let dr = r1 - r2;
+ let dg = g1 - g2;
+ let db = b1 - b2;
+ const da = a1 - a2;
+
+ if (a1 < 255 || a2 < 255) { // blend pixels with background
+ let rb = 255, gb = 255, bb = 255;
+ if (checkerboard) {
+ rb = 48 + 159 * (k % 2);
+ gb = 48 + 159 * ((k / 1.618033988749895 | 0) % 2);
+ bb = 48 + 159 * ((k / 2.618033988749895 | 0) % 2);
+ }
+ dr = (r1 * a1 - r2 * a2 - rb * da) / 255;
+ dg = (g1 * a1 - g2 * a2 - gb * da) / 255;
+ db = (b1 * a1 - b2 * a2 - bb * da) / 255;
+ }
+
+ const y = dr * 0.29889531 + dg * 0.58662247 + db * 0.11448223;
+ const i = dr * 0.59597799 - dg * 0.27417610 - db * 0.32180189;
+ const q = dr * 0.21147017 - dg * 0.52261711 + db * 0.31114694;
+
+ const delta = 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q;
+
+ // encode whether the pixel lightens or darkens in the sign
+ return y > 0 ? -delta : delta;
+}
+
+/**
+ * Specialized brightness-only color delta for the anti-aliasing detector,
+ * with the center pixel's RGBA hoisted out of the neighbor loop.
+ * @param {Uint8Array | Uint8ClampedArray} img
+ * @param {number} k center pixel offset
+ * @param {number} m neighbor pixel offset
+ * @param {number} r1
+ * @param {number} g1
+ * @param {number} b1
+ * @param {number} a1
+ * @param {boolean} checkerboard
+ */
+function brightnessDelta(img, k, m, r1, g1, b1, a1, checkerboard) {
+ const r2 = img[m];
+ const g2 = img[m + 1];
+ const b2 = img[m + 2];
+ const a2 = img[m + 3];
+
+ let dr = r1 - r2;
+ let dg = g1 - g2;
+ let db = b1 - b2;
+ const da = a1 - a2;
+
+ if (!dr && !dg && !db && !da) return 0;
+
+ if (a1 < 255 || a2 < 255) {
+ let rb = 255, gb = 255, bb = 255;
+ if (checkerboard) {
+ rb = 48 + 159 * (k % 2);
+ gb = 48 + 159 * ((k / 1.618033988749895 | 0) % 2);
+ bb = 48 + 159 * ((k / 2.618033988749895 | 0) % 2);
+ }
+ dr = (r1 * a1 - r2 * a2 - rb * da) / 255;
+ dg = (g1 * a1 - g2 * a2 - gb * da) / 255;
+ db = (b1 * a1 - b2 * a2 - bb * da) / 255;
+ }
+
+ return dr * 0.29889531 + dg * 0.58662247 + db * 0.11448223;
+}
+
+/**
+ * @param {Uint8Array | Uint8ClampedArray} output
+ * @param {number} pos
+ * @param {number} r
+ * @param {number} g
+ * @param {number} b
+ */
+function drawPixel(output, pos, r, g, b) {
+ output[pos] = r;
+ output[pos + 1] = g;
+ output[pos + 2] = b;
+ output[pos + 3] = 255;
+}
+
+/**
+ * @param {Uint8Array | Uint8ClampedArray} img
+ * @param {number} i
+ * @param {number} alpha
+ * @param {Uint8Array | Uint8ClampedArray} output
+ */
+function drawGrayPixel(img, i, alpha, output) {
+ const val = 255 + (img[i] * 0.29889531 + img[i + 1] * 0.58662247 + img[i + 2] * 0.11448223 - 255) * alpha * img[i + 3] / 255;
+ drawPixel(output, i, val, val, val);
+}
diff --git a/.agents/skills/compare-screenshots/vendor/pixelmatch/package.json b/.agents/skills/compare-screenshots/vendor/pixelmatch/package.json
new file mode 100644
index 0000000..211ab79
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pixelmatch/package.json
@@ -0,0 +1,42 @@
+{
+ "name": "pixelmatch",
+ "version": "7.2.0",
+ "type": "module",
+ "description": "The smallest and fastest pixel-level image comparison library.",
+ "main": "index.js",
+ "types": "index.d.ts",
+ "bin": {
+ "pixelmatch": "bin/pixelmatch"
+ },
+ "files": [
+ "bin/pixelmatch",
+ "index.d.ts"
+ ],
+ "dependencies": {
+ "pngjs": "^7.0.0"
+ },
+ "devDependencies": {
+ "eslint": "^10.2.1",
+ "eslint-config-mourner": "^4.1.0",
+ "typescript": "^6.0.3"
+ },
+ "scripts": {
+ "pretest": "eslint",
+ "test": "tsc && node --test"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/mapbox/pixelmatch.git"
+ },
+ "keywords": [
+ "image",
+ "comparison",
+ "diff"
+ ],
+ "author": "Volodymyr Agafonkin",
+ "license": "ISC",
+ "bugs": {
+ "url": "https://github.com/mapbox/pixelmatch/issues"
+ },
+ "homepage": "https://github.com/mapbox/pixelmatch#readme"
+}
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/LICENSE b/.agents/skills/compare-screenshots/vendor/pngjs/LICENSE
new file mode 100644
index 0000000..8c42032
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/LICENSE
@@ -0,0 +1,20 @@
+pngjs original work Copyright (c) 2015 Luke Page & Original Contributors
+pngjs derived work Copyright (c) 2012 Kuba Niegowski
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/bitmapper.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/bitmapper.js
new file mode 100644
index 0000000..18378a0
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/bitmapper.js
@@ -0,0 +1,267 @@
+"use strict";
+
+let interlaceUtils = require("./interlace");
+
+let pixelBppMapper = [
+ // 0 - dummy entry
+ function () {},
+
+ // 1 - L
+ // 0: 0, 1: 0, 2: 0, 3: 0xff
+ function (pxData, data, pxPos, rawPos) {
+ if (rawPos === data.length) {
+ throw new Error("Ran out of data");
+ }
+
+ let pixel = data[rawPos];
+ pxData[pxPos] = pixel;
+ pxData[pxPos + 1] = pixel;
+ pxData[pxPos + 2] = pixel;
+ pxData[pxPos + 3] = 0xff;
+ },
+
+ // 2 - LA
+ // 0: 0, 1: 0, 2: 0, 3: 1
+ function (pxData, data, pxPos, rawPos) {
+ if (rawPos + 1 >= data.length) {
+ throw new Error("Ran out of data");
+ }
+
+ let pixel = data[rawPos];
+ pxData[pxPos] = pixel;
+ pxData[pxPos + 1] = pixel;
+ pxData[pxPos + 2] = pixel;
+ pxData[pxPos + 3] = data[rawPos + 1];
+ },
+
+ // 3 - RGB
+ // 0: 0, 1: 1, 2: 2, 3: 0xff
+ function (pxData, data, pxPos, rawPos) {
+ if (rawPos + 2 >= data.length) {
+ throw new Error("Ran out of data");
+ }
+
+ pxData[pxPos] = data[rawPos];
+ pxData[pxPos + 1] = data[rawPos + 1];
+ pxData[pxPos + 2] = data[rawPos + 2];
+ pxData[pxPos + 3] = 0xff;
+ },
+
+ // 4 - RGBA
+ // 0: 0, 1: 1, 2: 2, 3: 3
+ function (pxData, data, pxPos, rawPos) {
+ if (rawPos + 3 >= data.length) {
+ throw new Error("Ran out of data");
+ }
+
+ pxData[pxPos] = data[rawPos];
+ pxData[pxPos + 1] = data[rawPos + 1];
+ pxData[pxPos + 2] = data[rawPos + 2];
+ pxData[pxPos + 3] = data[rawPos + 3];
+ },
+];
+
+let pixelBppCustomMapper = [
+ // 0 - dummy entry
+ function () {},
+
+ // 1 - L
+ // 0: 0, 1: 0, 2: 0, 3: 0xff
+ function (pxData, pixelData, pxPos, maxBit) {
+ let pixel = pixelData[0];
+ pxData[pxPos] = pixel;
+ pxData[pxPos + 1] = pixel;
+ pxData[pxPos + 2] = pixel;
+ pxData[pxPos + 3] = maxBit;
+ },
+
+ // 2 - LA
+ // 0: 0, 1: 0, 2: 0, 3: 1
+ function (pxData, pixelData, pxPos) {
+ let pixel = pixelData[0];
+ pxData[pxPos] = pixel;
+ pxData[pxPos + 1] = pixel;
+ pxData[pxPos + 2] = pixel;
+ pxData[pxPos + 3] = pixelData[1];
+ },
+
+ // 3 - RGB
+ // 0: 0, 1: 1, 2: 2, 3: 0xff
+ function (pxData, pixelData, pxPos, maxBit) {
+ pxData[pxPos] = pixelData[0];
+ pxData[pxPos + 1] = pixelData[1];
+ pxData[pxPos + 2] = pixelData[2];
+ pxData[pxPos + 3] = maxBit;
+ },
+
+ // 4 - RGBA
+ // 0: 0, 1: 1, 2: 2, 3: 3
+ function (pxData, pixelData, pxPos) {
+ pxData[pxPos] = pixelData[0];
+ pxData[pxPos + 1] = pixelData[1];
+ pxData[pxPos + 2] = pixelData[2];
+ pxData[pxPos + 3] = pixelData[3];
+ },
+];
+
+function bitRetriever(data, depth) {
+ let leftOver = [];
+ let i = 0;
+
+ function split() {
+ if (i === data.length) {
+ throw new Error("Ran out of data");
+ }
+ let byte = data[i];
+ i++;
+ let byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1;
+ switch (depth) {
+ default:
+ throw new Error("unrecognised depth");
+ case 16:
+ byte2 = data[i];
+ i++;
+ leftOver.push((byte << 8) + byte2);
+ break;
+ case 4:
+ byte2 = byte & 0x0f;
+ byte1 = byte >> 4;
+ leftOver.push(byte1, byte2);
+ break;
+ case 2:
+ byte4 = byte & 3;
+ byte3 = (byte >> 2) & 3;
+ byte2 = (byte >> 4) & 3;
+ byte1 = (byte >> 6) & 3;
+ leftOver.push(byte1, byte2, byte3, byte4);
+ break;
+ case 1:
+ byte8 = byte & 1;
+ byte7 = (byte >> 1) & 1;
+ byte6 = (byte >> 2) & 1;
+ byte5 = (byte >> 3) & 1;
+ byte4 = (byte >> 4) & 1;
+ byte3 = (byte >> 5) & 1;
+ byte2 = (byte >> 6) & 1;
+ byte1 = (byte >> 7) & 1;
+ leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8);
+ break;
+ }
+ }
+
+ return {
+ get: function (count) {
+ while (leftOver.length < count) {
+ split();
+ }
+ let returner = leftOver.slice(0, count);
+ leftOver = leftOver.slice(count);
+ return returner;
+ },
+ resetAfterLine: function () {
+ leftOver.length = 0;
+ },
+ end: function () {
+ if (i !== data.length) {
+ throw new Error("extra data found");
+ }
+ },
+ };
+}
+
+function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) {
+ // eslint-disable-line max-params
+ let imageWidth = image.width;
+ let imageHeight = image.height;
+ let imagePass = image.index;
+ for (let y = 0; y < imageHeight; y++) {
+ for (let x = 0; x < imageWidth; x++) {
+ let pxPos = getPxPos(x, y, imagePass);
+ pixelBppMapper[bpp](pxData, data, pxPos, rawPos);
+ rawPos += bpp; //eslint-disable-line no-param-reassign
+ }
+ }
+ return rawPos;
+}
+
+function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) {
+ // eslint-disable-line max-params
+ let imageWidth = image.width;
+ let imageHeight = image.height;
+ let imagePass = image.index;
+ for (let y = 0; y < imageHeight; y++) {
+ for (let x = 0; x < imageWidth; x++) {
+ let pixelData = bits.get(bpp);
+ let pxPos = getPxPos(x, y, imagePass);
+ pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit);
+ }
+ bits.resetAfterLine();
+ }
+}
+
+exports.dataToBitMap = function (data, bitmapInfo) {
+ let width = bitmapInfo.width;
+ let height = bitmapInfo.height;
+ let depth = bitmapInfo.depth;
+ let bpp = bitmapInfo.bpp;
+ let interlace = bitmapInfo.interlace;
+ let bits;
+
+ if (depth !== 8) {
+ bits = bitRetriever(data, depth);
+ }
+ let pxData;
+ if (depth <= 8) {
+ pxData = Buffer.alloc(width * height * 4);
+ } else {
+ pxData = new Uint16Array(width * height * 4);
+ }
+ let maxBit = Math.pow(2, depth) - 1;
+ let rawPos = 0;
+ let images;
+ let getPxPos;
+
+ if (interlace) {
+ images = interlaceUtils.getImagePasses(width, height);
+ getPxPos = interlaceUtils.getInterlaceIterator(width, height);
+ } else {
+ let nonInterlacedPxPos = 0;
+ getPxPos = function () {
+ let returner = nonInterlacedPxPos;
+ nonInterlacedPxPos += 4;
+ return returner;
+ };
+ images = [{ width: width, height: height }];
+ }
+
+ for (let imageIndex = 0; imageIndex < images.length; imageIndex++) {
+ if (depth === 8) {
+ rawPos = mapImage8Bit(
+ images[imageIndex],
+ pxData,
+ getPxPos,
+ bpp,
+ data,
+ rawPos
+ );
+ } else {
+ mapImageCustomBit(
+ images[imageIndex],
+ pxData,
+ getPxPos,
+ bpp,
+ bits,
+ maxBit
+ );
+ }
+ }
+ if (depth === 8) {
+ if (rawPos !== data.length) {
+ throw new Error("extra data found");
+ }
+ } else {
+ bits.end();
+ }
+
+ return pxData;
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/bitpacker.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/bitpacker.js
new file mode 100644
index 0000000..d7a4e65
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/bitpacker.js
@@ -0,0 +1,158 @@
+"use strict";
+
+let constants = require("./constants");
+
+module.exports = function (dataIn, width, height, options) {
+ let outHasAlpha =
+ [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(
+ options.colorType
+ ) !== -1;
+ if (options.colorType === options.inputColorType) {
+ let bigEndian = (function () {
+ let buffer = new ArrayBuffer(2);
+ new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
+ // Int16Array uses the platform's endianness.
+ return new Int16Array(buffer)[0] !== 256;
+ })();
+ // If no need to convert to grayscale and alpha is present/absent in both, take a fast route
+ if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)) {
+ return dataIn;
+ }
+ }
+
+ // map to a UInt16 array if data is 16bit, fix endianness below
+ let data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);
+
+ let maxValue = 255;
+ let inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];
+ if (inBpp === 4 && !options.inputHasAlpha) {
+ inBpp = 3;
+ }
+ let outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType];
+ if (options.bitDepth === 16) {
+ maxValue = 65535;
+ outBpp *= 2;
+ }
+ let outData = Buffer.alloc(width * height * outBpp);
+
+ let inIndex = 0;
+ let outIndex = 0;
+
+ let bgColor = options.bgColor || {};
+ if (bgColor.red === undefined) {
+ bgColor.red = maxValue;
+ }
+ if (bgColor.green === undefined) {
+ bgColor.green = maxValue;
+ }
+ if (bgColor.blue === undefined) {
+ bgColor.blue = maxValue;
+ }
+
+ function getRGBA() {
+ let red;
+ let green;
+ let blue;
+ let alpha = maxValue;
+ switch (options.inputColorType) {
+ case constants.COLORTYPE_COLOR_ALPHA:
+ alpha = data[inIndex + 3];
+ red = data[inIndex];
+ green = data[inIndex + 1];
+ blue = data[inIndex + 2];
+ break;
+ case constants.COLORTYPE_COLOR:
+ red = data[inIndex];
+ green = data[inIndex + 1];
+ blue = data[inIndex + 2];
+ break;
+ case constants.COLORTYPE_ALPHA:
+ alpha = data[inIndex + 1];
+ red = data[inIndex];
+ green = red;
+ blue = red;
+ break;
+ case constants.COLORTYPE_GRAYSCALE:
+ red = data[inIndex];
+ green = red;
+ blue = red;
+ break;
+ default:
+ throw new Error(
+ "input color type:" +
+ options.inputColorType +
+ " is not supported at present"
+ );
+ }
+
+ if (options.inputHasAlpha) {
+ if (!outHasAlpha) {
+ alpha /= maxValue;
+ red = Math.min(
+ Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0),
+ maxValue
+ );
+ green = Math.min(
+ Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0),
+ maxValue
+ );
+ blue = Math.min(
+ Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0),
+ maxValue
+ );
+ }
+ }
+ return { red: red, green: green, blue: blue, alpha: alpha };
+ }
+
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ let rgba = getRGBA(data, inIndex);
+
+ switch (options.colorType) {
+ case constants.COLORTYPE_COLOR_ALPHA:
+ case constants.COLORTYPE_COLOR:
+ if (options.bitDepth === 8) {
+ outData[outIndex] = rgba.red;
+ outData[outIndex + 1] = rgba.green;
+ outData[outIndex + 2] = rgba.blue;
+ if (outHasAlpha) {
+ outData[outIndex + 3] = rgba.alpha;
+ }
+ } else {
+ outData.writeUInt16BE(rgba.red, outIndex);
+ outData.writeUInt16BE(rgba.green, outIndex + 2);
+ outData.writeUInt16BE(rgba.blue, outIndex + 4);
+ if (outHasAlpha) {
+ outData.writeUInt16BE(rgba.alpha, outIndex + 6);
+ }
+ }
+ break;
+ case constants.COLORTYPE_ALPHA:
+ case constants.COLORTYPE_GRAYSCALE: {
+ // Convert to grayscale and alpha
+ let grayscale = (rgba.red + rgba.green + rgba.blue) / 3;
+ if (options.bitDepth === 8) {
+ outData[outIndex] = grayscale;
+ if (outHasAlpha) {
+ outData[outIndex + 1] = rgba.alpha;
+ }
+ } else {
+ outData.writeUInt16BE(grayscale, outIndex);
+ if (outHasAlpha) {
+ outData.writeUInt16BE(rgba.alpha, outIndex + 2);
+ }
+ }
+ break;
+ }
+ default:
+ throw new Error("unrecognised color Type " + options.colorType);
+ }
+
+ inIndex += inBpp;
+ outIndex += outBpp;
+ }
+ }
+
+ return outData;
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/chunkstream.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/chunkstream.js
new file mode 100644
index 0000000..95b46d4
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/chunkstream.js
@@ -0,0 +1,189 @@
+"use strict";
+
+let util = require("util");
+let Stream = require("stream");
+
+let ChunkStream = (module.exports = function () {
+ Stream.call(this);
+
+ this._buffers = [];
+ this._buffered = 0;
+
+ this._reads = [];
+ this._paused = false;
+
+ this._encoding = "utf8";
+ this.writable = true;
+});
+util.inherits(ChunkStream, Stream);
+
+ChunkStream.prototype.read = function (length, callback) {
+ this._reads.push({
+ length: Math.abs(length), // if length < 0 then at most this length
+ allowLess: length < 0,
+ func: callback,
+ });
+
+ process.nextTick(
+ function () {
+ this._process();
+
+ // its paused and there is not enought data then ask for more
+ if (this._paused && this._reads && this._reads.length > 0) {
+ this._paused = false;
+
+ this.emit("drain");
+ }
+ }.bind(this)
+ );
+};
+
+ChunkStream.prototype.write = function (data, encoding) {
+ if (!this.writable) {
+ this.emit("error", new Error("Stream not writable"));
+ return false;
+ }
+
+ let dataBuffer;
+ if (Buffer.isBuffer(data)) {
+ dataBuffer = data;
+ } else {
+ dataBuffer = Buffer.from(data, encoding || this._encoding);
+ }
+
+ this._buffers.push(dataBuffer);
+ this._buffered += dataBuffer.length;
+
+ this._process();
+
+ // ok if there are no more read requests
+ if (this._reads && this._reads.length === 0) {
+ this._paused = true;
+ }
+
+ return this.writable && !this._paused;
+};
+
+ChunkStream.prototype.end = function (data, encoding) {
+ if (data) {
+ this.write(data, encoding);
+ }
+
+ this.writable = false;
+
+ // already destroyed
+ if (!this._buffers) {
+ return;
+ }
+
+ // enqueue or handle end
+ if (this._buffers.length === 0) {
+ this._end();
+ } else {
+ this._buffers.push(null);
+ this._process();
+ }
+};
+
+ChunkStream.prototype.destroySoon = ChunkStream.prototype.end;
+
+ChunkStream.prototype._end = function () {
+ if (this._reads.length > 0) {
+ this.emit("error", new Error("Unexpected end of input"));
+ }
+
+ this.destroy();
+};
+
+ChunkStream.prototype.destroy = function () {
+ if (!this._buffers) {
+ return;
+ }
+
+ this.writable = false;
+ this._reads = null;
+ this._buffers = null;
+
+ this.emit("close");
+};
+
+ChunkStream.prototype._processReadAllowingLess = function (read) {
+ // ok there is any data so that we can satisfy this request
+ this._reads.shift(); // == read
+
+ // first we need to peek into first buffer
+ let smallerBuf = this._buffers[0];
+
+ // ok there is more data than we need
+ if (smallerBuf.length > read.length) {
+ this._buffered -= read.length;
+ this._buffers[0] = smallerBuf.slice(read.length);
+
+ read.func.call(this, smallerBuf.slice(0, read.length));
+ } else {
+ // ok this is less than maximum length so use it all
+ this._buffered -= smallerBuf.length;
+ this._buffers.shift(); // == smallerBuf
+
+ read.func.call(this, smallerBuf);
+ }
+};
+
+ChunkStream.prototype._processRead = function (read) {
+ this._reads.shift(); // == read
+
+ let pos = 0;
+ let count = 0;
+ let data = Buffer.alloc(read.length);
+
+ // create buffer for all data
+ while (pos < read.length) {
+ let buf = this._buffers[count++];
+ let len = Math.min(buf.length, read.length - pos);
+
+ buf.copy(data, pos, 0, len);
+ pos += len;
+
+ // last buffer wasn't used all so just slice it and leave
+ if (len !== buf.length) {
+ this._buffers[--count] = buf.slice(len);
+ }
+ }
+
+ // remove all used buffers
+ if (count > 0) {
+ this._buffers.splice(0, count);
+ }
+
+ this._buffered -= read.length;
+
+ read.func.call(this, data);
+};
+
+ChunkStream.prototype._process = function () {
+ try {
+ // as long as there is any data and read requests
+ while (this._buffered > 0 && this._reads && this._reads.length > 0) {
+ let read = this._reads[0];
+
+ // read any data (but no more than length)
+ if (read.allowLess) {
+ this._processReadAllowingLess(read);
+ } else if (this._buffered >= read.length) {
+ // ok we can meet some expectations
+
+ this._processRead(read);
+ } else {
+ // not enought data to satisfy first request in queue
+ // so we need to wait for more
+ break;
+ }
+ }
+
+ if (this._buffers && !this.writable) {
+ this._end();
+ }
+ } catch (ex) {
+ this.emit("error", ex);
+ }
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/constants.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/constants.js
new file mode 100644
index 0000000..21fdad6
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/constants.js
@@ -0,0 +1,32 @@
+"use strict";
+
+module.exports = {
+ PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
+
+ TYPE_IHDR: 0x49484452,
+ TYPE_IEND: 0x49454e44,
+ TYPE_IDAT: 0x49444154,
+ TYPE_PLTE: 0x504c5445,
+ TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase
+ TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase
+
+ // color-type bits
+ COLORTYPE_GRAYSCALE: 0,
+ COLORTYPE_PALETTE: 1,
+ COLORTYPE_COLOR: 2,
+ COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha
+
+ // color-type combinations
+ COLORTYPE_PALETTE_COLOR: 3,
+ COLORTYPE_COLOR_ALPHA: 6,
+
+ COLORTYPE_TO_BPP_MAP: {
+ 0: 1,
+ 2: 3,
+ 3: 1,
+ 4: 2,
+ 6: 4,
+ },
+
+ GAMMA_DIVISION: 100000,
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/crc.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/crc.js
new file mode 100644
index 0000000..950ec8a
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/crc.js
@@ -0,0 +1,40 @@
+"use strict";
+
+let crcTable = [];
+
+(function () {
+ for (let i = 0; i < 256; i++) {
+ let currentCrc = i;
+ for (let j = 0; j < 8; j++) {
+ if (currentCrc & 1) {
+ currentCrc = 0xedb88320 ^ (currentCrc >>> 1);
+ } else {
+ currentCrc = currentCrc >>> 1;
+ }
+ }
+ crcTable[i] = currentCrc;
+ }
+})();
+
+let CrcCalculator = (module.exports = function () {
+ this._crc = -1;
+});
+
+CrcCalculator.prototype.write = function (data) {
+ for (let i = 0; i < data.length; i++) {
+ this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8);
+ }
+ return true;
+};
+
+CrcCalculator.prototype.crc32 = function () {
+ return this._crc ^ -1;
+};
+
+CrcCalculator.crc32 = function (buf) {
+ let crc = -1;
+ for (let i = 0; i < buf.length; i++) {
+ crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
+ }
+ return crc ^ -1;
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/filter-pack.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/filter-pack.js
new file mode 100644
index 0000000..32c85c4
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/filter-pack.js
@@ -0,0 +1,171 @@
+"use strict";
+
+let paethPredictor = require("./paeth-predictor");
+
+function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {
+ for (let x = 0; x < byteWidth; x++) {
+ rawData[rawPos + x] = pxData[pxPos + x];
+ }
+}
+
+function filterSumNone(pxData, pxPos, byteWidth) {
+ let sum = 0;
+ let length = pxPos + byteWidth;
+
+ for (let i = pxPos; i < length; i++) {
+ sum += Math.abs(pxData[i]);
+ }
+ return sum;
+}
+
+function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
+ for (let x = 0; x < byteWidth; x++) {
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
+ let val = pxData[pxPos + x] - left;
+
+ rawData[rawPos + x] = val;
+ }
+}
+
+function filterSumSub(pxData, pxPos, byteWidth, bpp) {
+ let sum = 0;
+ for (let x = 0; x < byteWidth; x++) {
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
+ let val = pxData[pxPos + x] - left;
+
+ sum += Math.abs(val);
+ }
+
+ return sum;
+}
+
+function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {
+ for (let x = 0; x < byteWidth; x++) {
+ let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
+ let val = pxData[pxPos + x] - up;
+
+ rawData[rawPos + x] = val;
+ }
+}
+
+function filterSumUp(pxData, pxPos, byteWidth) {
+ let sum = 0;
+ let length = pxPos + byteWidth;
+ for (let x = pxPos; x < length; x++) {
+ let up = pxPos > 0 ? pxData[x - byteWidth] : 0;
+ let val = pxData[x] - up;
+
+ sum += Math.abs(val);
+ }
+
+ return sum;
+}
+
+function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
+ for (let x = 0; x < byteWidth; x++) {
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
+ let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
+ let val = pxData[pxPos + x] - ((left + up) >> 1);
+
+ rawData[rawPos + x] = val;
+ }
+}
+
+function filterSumAvg(pxData, pxPos, byteWidth, bpp) {
+ let sum = 0;
+ for (let x = 0; x < byteWidth; x++) {
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
+ let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
+ let val = pxData[pxPos + x] - ((left + up) >> 1);
+
+ sum += Math.abs(val);
+ }
+
+ return sum;
+}
+
+function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
+ for (let x = 0; x < byteWidth; x++) {
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
+ let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
+ let upleft =
+ pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
+ let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
+
+ rawData[rawPos + x] = val;
+ }
+}
+
+function filterSumPaeth(pxData, pxPos, byteWidth, bpp) {
+ let sum = 0;
+ for (let x = 0; x < byteWidth; x++) {
+ let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
+ let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
+ let upleft =
+ pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
+ let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
+
+ sum += Math.abs(val);
+ }
+
+ return sum;
+}
+
+let filters = {
+ 0: filterNone,
+ 1: filterSub,
+ 2: filterUp,
+ 3: filterAvg,
+ 4: filterPaeth,
+};
+
+let filterSums = {
+ 0: filterSumNone,
+ 1: filterSumSub,
+ 2: filterSumUp,
+ 3: filterSumAvg,
+ 4: filterSumPaeth,
+};
+
+module.exports = function (pxData, width, height, options, bpp) {
+ let filterTypes;
+ if (!("filterType" in options) || options.filterType === -1) {
+ filterTypes = [0, 1, 2, 3, 4];
+ } else if (typeof options.filterType === "number") {
+ filterTypes = [options.filterType];
+ } else {
+ throw new Error("unrecognised filter types");
+ }
+
+ if (options.bitDepth === 16) {
+ bpp *= 2;
+ }
+ let byteWidth = width * bpp;
+ let rawPos = 0;
+ let pxPos = 0;
+ let rawData = Buffer.alloc((byteWidth + 1) * height);
+
+ let sel = filterTypes[0];
+
+ for (let y = 0; y < height; y++) {
+ if (filterTypes.length > 1) {
+ // find best filter for this line (with lowest sum of values)
+ let min = Infinity;
+
+ for (let i = 0; i < filterTypes.length; i++) {
+ let sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);
+ if (sum < min) {
+ sel = filterTypes[i];
+ min = sum;
+ }
+ }
+ }
+
+ rawData[rawPos] = sel;
+ rawPos++;
+ filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);
+ rawPos += byteWidth;
+ pxPos += byteWidth;
+ }
+ return rawData;
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/filter-parse-async.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/filter-parse-async.js
new file mode 100644
index 0000000..832b86c
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/filter-parse-async.js
@@ -0,0 +1,24 @@
+"use strict";
+
+let util = require("util");
+let ChunkStream = require("./chunkstream");
+let Filter = require("./filter-parse");
+
+let FilterAsync = (module.exports = function (bitmapInfo) {
+ ChunkStream.call(this);
+
+ let buffers = [];
+ let that = this;
+ this._filter = new Filter(bitmapInfo, {
+ read: this.read.bind(this),
+ write: function (buffer) {
+ buffers.push(buffer);
+ },
+ complete: function () {
+ that.emit("complete", Buffer.concat(buffers));
+ },
+ });
+
+ this._filter.start();
+});
+util.inherits(FilterAsync, ChunkStream);
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/filter-parse-sync.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/filter-parse-sync.js
new file mode 100644
index 0000000..6924d16
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/filter-parse-sync.js
@@ -0,0 +1,21 @@
+"use strict";
+
+let SyncReader = require("./sync-reader");
+let Filter = require("./filter-parse");
+
+exports.process = function (inBuffer, bitmapInfo) {
+ let outBuffers = [];
+ let reader = new SyncReader(inBuffer);
+ let filter = new Filter(bitmapInfo, {
+ read: reader.read.bind(reader),
+ write: function (bufferPart) {
+ outBuffers.push(bufferPart);
+ },
+ complete: function () {},
+ });
+
+ filter.start();
+ reader.process();
+
+ return Buffer.concat(outBuffers);
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/filter-parse.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/filter-parse.js
new file mode 100644
index 0000000..3a32e5e
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/filter-parse.js
@@ -0,0 +1,177 @@
+"use strict";
+
+let interlaceUtils = require("./interlace");
+let paethPredictor = require("./paeth-predictor");
+
+function getByteWidth(width, bpp, depth) {
+ let byteWidth = width * bpp;
+ if (depth !== 8) {
+ byteWidth = Math.ceil(byteWidth / (8 / depth));
+ }
+ return byteWidth;
+}
+
+let Filter = (module.exports = function (bitmapInfo, dependencies) {
+ let width = bitmapInfo.width;
+ let height = bitmapInfo.height;
+ let interlace = bitmapInfo.interlace;
+ let bpp = bitmapInfo.bpp;
+ let depth = bitmapInfo.depth;
+
+ this.read = dependencies.read;
+ this.write = dependencies.write;
+ this.complete = dependencies.complete;
+
+ this._imageIndex = 0;
+ this._images = [];
+ if (interlace) {
+ let passes = interlaceUtils.getImagePasses(width, height);
+ for (let i = 0; i < passes.length; i++) {
+ this._images.push({
+ byteWidth: getByteWidth(passes[i].width, bpp, depth),
+ height: passes[i].height,
+ lineIndex: 0,
+ });
+ }
+ } else {
+ this._images.push({
+ byteWidth: getByteWidth(width, bpp, depth),
+ height: height,
+ lineIndex: 0,
+ });
+ }
+
+ // when filtering the line we look at the pixel to the left
+ // the spec also says it is done on a byte level regardless of the number of pixels
+ // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back
+ // a pixel rather than just a different byte part. However if we are sub byte, we ignore.
+ if (depth === 8) {
+ this._xComparison = bpp;
+ } else if (depth === 16) {
+ this._xComparison = bpp * 2;
+ } else {
+ this._xComparison = 1;
+ }
+});
+
+Filter.prototype.start = function () {
+ this.read(
+ this._images[this._imageIndex].byteWidth + 1,
+ this._reverseFilterLine.bind(this)
+ );
+};
+
+Filter.prototype._unFilterType1 = function (
+ rawData,
+ unfilteredLine,
+ byteWidth
+) {
+ let xComparison = this._xComparison;
+ let xBiggerThan = xComparison - 1;
+
+ for (let x = 0; x < byteWidth; x++) {
+ let rawByte = rawData[1 + x];
+ let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
+ unfilteredLine[x] = rawByte + f1Left;
+ }
+};
+
+Filter.prototype._unFilterType2 = function (
+ rawData,
+ unfilteredLine,
+ byteWidth
+) {
+ let lastLine = this._lastLine;
+
+ for (let x = 0; x < byteWidth; x++) {
+ let rawByte = rawData[1 + x];
+ let f2Up = lastLine ? lastLine[x] : 0;
+ unfilteredLine[x] = rawByte + f2Up;
+ }
+};
+
+Filter.prototype._unFilterType3 = function (
+ rawData,
+ unfilteredLine,
+ byteWidth
+) {
+ let xComparison = this._xComparison;
+ let xBiggerThan = xComparison - 1;
+ let lastLine = this._lastLine;
+
+ for (let x = 0; x < byteWidth; x++) {
+ let rawByte = rawData[1 + x];
+ let f3Up = lastLine ? lastLine[x] : 0;
+ let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
+ let f3Add = Math.floor((f3Left + f3Up) / 2);
+ unfilteredLine[x] = rawByte + f3Add;
+ }
+};
+
+Filter.prototype._unFilterType4 = function (
+ rawData,
+ unfilteredLine,
+ byteWidth
+) {
+ let xComparison = this._xComparison;
+ let xBiggerThan = xComparison - 1;
+ let lastLine = this._lastLine;
+
+ for (let x = 0; x < byteWidth; x++) {
+ let rawByte = rawData[1 + x];
+ let f4Up = lastLine ? lastLine[x] : 0;
+ let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
+ let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;
+ let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);
+ unfilteredLine[x] = rawByte + f4Add;
+ }
+};
+
+Filter.prototype._reverseFilterLine = function (rawData) {
+ let filter = rawData[0];
+ let unfilteredLine;
+ let currentImage = this._images[this._imageIndex];
+ let byteWidth = currentImage.byteWidth;
+
+ if (filter === 0) {
+ unfilteredLine = rawData.slice(1, byteWidth + 1);
+ } else {
+ unfilteredLine = Buffer.alloc(byteWidth);
+
+ switch (filter) {
+ case 1:
+ this._unFilterType1(rawData, unfilteredLine, byteWidth);
+ break;
+ case 2:
+ this._unFilterType2(rawData, unfilteredLine, byteWidth);
+ break;
+ case 3:
+ this._unFilterType3(rawData, unfilteredLine, byteWidth);
+ break;
+ case 4:
+ this._unFilterType4(rawData, unfilteredLine, byteWidth);
+ break;
+ default:
+ throw new Error("Unrecognised filter type - " + filter);
+ }
+ }
+
+ this.write(unfilteredLine);
+
+ currentImage.lineIndex++;
+ if (currentImage.lineIndex >= currentImage.height) {
+ this._lastLine = null;
+ this._imageIndex++;
+ currentImage = this._images[this._imageIndex];
+ } else {
+ this._lastLine = unfilteredLine;
+ }
+
+ if (currentImage) {
+ // read, using the byte width that may be from the new current image
+ this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));
+ } else {
+ this._lastLine = null;
+ this.complete();
+ }
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/format-normaliser.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/format-normaliser.js
new file mode 100644
index 0000000..209b66b
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/format-normaliser.js
@@ -0,0 +1,93 @@
+"use strict";
+
+function dePalette(indata, outdata, width, height, palette) {
+ let pxPos = 0;
+ // use values from palette
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ let color = palette[indata[pxPos]];
+
+ if (!color) {
+ throw new Error("index " + indata[pxPos] + " not in palette");
+ }
+
+ for (let i = 0; i < 4; i++) {
+ outdata[pxPos + i] = color[i];
+ }
+ pxPos += 4;
+ }
+ }
+}
+
+function replaceTransparentColor(indata, outdata, width, height, transColor) {
+ let pxPos = 0;
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ let makeTrans = false;
+
+ if (transColor.length === 1) {
+ if (transColor[0] === indata[pxPos]) {
+ makeTrans = true;
+ }
+ } else if (
+ transColor[0] === indata[pxPos] &&
+ transColor[1] === indata[pxPos + 1] &&
+ transColor[2] === indata[pxPos + 2]
+ ) {
+ makeTrans = true;
+ }
+ if (makeTrans) {
+ for (let i = 0; i < 4; i++) {
+ outdata[pxPos + i] = 0;
+ }
+ }
+ pxPos += 4;
+ }
+ }
+}
+
+function scaleDepth(indata, outdata, width, height, depth) {
+ let maxOutSample = 255;
+ let maxInSample = Math.pow(2, depth) - 1;
+ let pxPos = 0;
+
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ for (let i = 0; i < 4; i++) {
+ outdata[pxPos + i] = Math.floor(
+ (indata[pxPos + i] * maxOutSample) / maxInSample + 0.5
+ );
+ }
+ pxPos += 4;
+ }
+ }
+}
+
+module.exports = function (indata, imageData, skipRescale = false) {
+ let depth = imageData.depth;
+ let width = imageData.width;
+ let height = imageData.height;
+ let colorType = imageData.colorType;
+ let transColor = imageData.transColor;
+ let palette = imageData.palette;
+
+ let outdata = indata; // only different for 16 bits
+
+ if (colorType === 3) {
+ // paletted
+ dePalette(indata, outdata, width, height, palette);
+ } else {
+ if (transColor) {
+ replaceTransparentColor(indata, outdata, width, height, transColor);
+ }
+ // if it needs scaling
+ if (depth !== 8 && !skipRescale) {
+ // if we need to change the buffer size
+ if (depth === 16) {
+ outdata = Buffer.alloc(width * height * 4);
+ }
+ scaleDepth(indata, outdata, width, height, depth);
+ }
+ }
+ return outdata;
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/interlace.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/interlace.js
new file mode 100644
index 0000000..a035cb1
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/interlace.js
@@ -0,0 +1,95 @@
+"use strict";
+
+// Adam 7
+// 0 1 2 3 4 5 6 7
+// 0 x 6 4 6 x 6 4 6
+// 1 7 7 7 7 7 7 7 7
+// 2 5 6 5 6 5 6 5 6
+// 3 7 7 7 7 7 7 7 7
+// 4 3 6 4 6 3 6 4 6
+// 5 7 7 7 7 7 7 7 7
+// 6 5 6 5 6 5 6 5 6
+// 7 7 7 7 7 7 7 7 7
+
+let imagePasses = [
+ {
+ // pass 1 - 1px
+ x: [0],
+ y: [0],
+ },
+ {
+ // pass 2 - 1px
+ x: [4],
+ y: [0],
+ },
+ {
+ // pass 3 - 2px
+ x: [0, 4],
+ y: [4],
+ },
+ {
+ // pass 4 - 4px
+ x: [2, 6],
+ y: [0, 4],
+ },
+ {
+ // pass 5 - 8px
+ x: [0, 2, 4, 6],
+ y: [2, 6],
+ },
+ {
+ // pass 6 - 16px
+ x: [1, 3, 5, 7],
+ y: [0, 2, 4, 6],
+ },
+ {
+ // pass 7 - 32px
+ x: [0, 1, 2, 3, 4, 5, 6, 7],
+ y: [1, 3, 5, 7],
+ },
+];
+
+exports.getImagePasses = function (width, height) {
+ let images = [];
+ let xLeftOver = width % 8;
+ let yLeftOver = height % 8;
+ let xRepeats = (width - xLeftOver) / 8;
+ let yRepeats = (height - yLeftOver) / 8;
+ for (let i = 0; i < imagePasses.length; i++) {
+ let pass = imagePasses[i];
+ let passWidth = xRepeats * pass.x.length;
+ let passHeight = yRepeats * pass.y.length;
+ for (let j = 0; j < pass.x.length; j++) {
+ if (pass.x[j] < xLeftOver) {
+ passWidth++;
+ } else {
+ break;
+ }
+ }
+ for (let j = 0; j < pass.y.length; j++) {
+ if (pass.y[j] < yLeftOver) {
+ passHeight++;
+ } else {
+ break;
+ }
+ }
+ if (passWidth > 0 && passHeight > 0) {
+ images.push({ width: passWidth, height: passHeight, index: i });
+ }
+ }
+ return images;
+};
+
+exports.getInterlaceIterator = function (width) {
+ return function (x, y, pass) {
+ let outerXLeftOver = x % imagePasses[pass].x.length;
+ let outerX =
+ ((x - outerXLeftOver) / imagePasses[pass].x.length) * 8 +
+ imagePasses[pass].x[outerXLeftOver];
+ let outerYLeftOver = y % imagePasses[pass].y.length;
+ let outerY =
+ ((y - outerYLeftOver) / imagePasses[pass].y.length) * 8 +
+ imagePasses[pass].y[outerYLeftOver];
+ return outerX * 4 + outerY * width * 4;
+ };
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/packer-async.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/packer-async.js
new file mode 100644
index 0000000..f3df73a
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/packer-async.js
@@ -0,0 +1,50 @@
+"use strict";
+
+let util = require("util");
+let Stream = require("stream");
+let constants = require("./constants");
+let Packer = require("./packer");
+
+let PackerAsync = (module.exports = function (opt) {
+ Stream.call(this);
+
+ let options = opt || {};
+
+ this._packer = new Packer(options);
+ this._deflate = this._packer.createDeflate();
+
+ this.readable = true;
+});
+util.inherits(PackerAsync, Stream);
+
+PackerAsync.prototype.pack = function (data, width, height, gamma) {
+ // Signature
+ this.emit("data", Buffer.from(constants.PNG_SIGNATURE));
+ this.emit("data", this._packer.packIHDR(width, height));
+
+ if (gamma) {
+ this.emit("data", this._packer.packGAMA(gamma));
+ }
+
+ let filteredData = this._packer.filterData(data, width, height);
+
+ // compress it
+ this._deflate.on("error", this.emit.bind(this, "error"));
+
+ this._deflate.on(
+ "data",
+ function (compressedData) {
+ this.emit("data", this._packer.packIDAT(compressedData));
+ }.bind(this)
+ );
+
+ this._deflate.on(
+ "end",
+ function () {
+ this.emit("data", this._packer.packIEND());
+ this.emit("end");
+ }.bind(this)
+ );
+
+ this._deflate.end(filteredData);
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/packer-sync.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/packer-sync.js
new file mode 100644
index 0000000..f5ab0b3
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/packer-sync.js
@@ -0,0 +1,56 @@
+"use strict";
+
+let hasSyncZlib = true;
+let zlib = require("zlib");
+if (!zlib.deflateSync) {
+ hasSyncZlib = false;
+}
+let constants = require("./constants");
+let Packer = require("./packer");
+
+module.exports = function (metaData, opt) {
+ if (!hasSyncZlib) {
+ throw new Error(
+ "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0"
+ );
+ }
+
+ let options = opt || {};
+
+ let packer = new Packer(options);
+
+ let chunks = [];
+
+ // Signature
+ chunks.push(Buffer.from(constants.PNG_SIGNATURE));
+
+ // Header
+ chunks.push(packer.packIHDR(metaData.width, metaData.height));
+
+ if (metaData.gamma) {
+ chunks.push(packer.packGAMA(metaData.gamma));
+ }
+
+ let filteredData = packer.filterData(
+ metaData.data,
+ metaData.width,
+ metaData.height
+ );
+
+ // compress it
+ let compressedData = zlib.deflateSync(
+ filteredData,
+ packer.getDeflateOptions()
+ );
+ filteredData = null;
+
+ if (!compressedData || !compressedData.length) {
+ throw new Error("bad png - invalid compressed data response");
+ }
+ chunks.push(packer.packIDAT(compressedData));
+
+ // End
+ chunks.push(packer.packIEND());
+
+ return Buffer.concat(chunks);
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/packer.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/packer.js
new file mode 100644
index 0000000..4aba12c
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/packer.js
@@ -0,0 +1,129 @@
+"use strict";
+
+let constants = require("./constants");
+let CrcStream = require("./crc");
+let bitPacker = require("./bitpacker");
+let filter = require("./filter-pack");
+let zlib = require("zlib");
+
+let Packer = (module.exports = function (options) {
+ this._options = options;
+
+ options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;
+ options.deflateLevel =
+ options.deflateLevel != null ? options.deflateLevel : 9;
+ options.deflateStrategy =
+ options.deflateStrategy != null ? options.deflateStrategy : 3;
+ options.inputHasAlpha =
+ options.inputHasAlpha != null ? options.inputHasAlpha : true;
+ options.deflateFactory = options.deflateFactory || zlib.createDeflate;
+ options.bitDepth = options.bitDepth || 8;
+ // This is outputColorType
+ options.colorType =
+ typeof options.colorType === "number"
+ ? options.colorType
+ : constants.COLORTYPE_COLOR_ALPHA;
+ options.inputColorType =
+ typeof options.inputColorType === "number"
+ ? options.inputColorType
+ : constants.COLORTYPE_COLOR_ALPHA;
+
+ if (
+ [
+ constants.COLORTYPE_GRAYSCALE,
+ constants.COLORTYPE_COLOR,
+ constants.COLORTYPE_COLOR_ALPHA,
+ constants.COLORTYPE_ALPHA,
+ ].indexOf(options.colorType) === -1
+ ) {
+ throw new Error(
+ "option color type:" + options.colorType + " is not supported at present"
+ );
+ }
+ if (
+ [
+ constants.COLORTYPE_GRAYSCALE,
+ constants.COLORTYPE_COLOR,
+ constants.COLORTYPE_COLOR_ALPHA,
+ constants.COLORTYPE_ALPHA,
+ ].indexOf(options.inputColorType) === -1
+ ) {
+ throw new Error(
+ "option input color type:" +
+ options.inputColorType +
+ " is not supported at present"
+ );
+ }
+ if (options.bitDepth !== 8 && options.bitDepth !== 16) {
+ throw new Error(
+ "option bit depth:" + options.bitDepth + " is not supported at present"
+ );
+ }
+});
+
+Packer.prototype.getDeflateOptions = function () {
+ return {
+ chunkSize: this._options.deflateChunkSize,
+ level: this._options.deflateLevel,
+ strategy: this._options.deflateStrategy,
+ };
+};
+
+Packer.prototype.createDeflate = function () {
+ return this._options.deflateFactory(this.getDeflateOptions());
+};
+
+Packer.prototype.filterData = function (data, width, height) {
+ // convert to correct format for filtering (e.g. right bpp and bit depth)
+ let packedData = bitPacker(data, width, height, this._options);
+
+ // filter pixel data
+ let bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];
+ let filteredData = filter(packedData, width, height, this._options, bpp);
+ return filteredData;
+};
+
+Packer.prototype._packChunk = function (type, data) {
+ let len = data ? data.length : 0;
+ let buf = Buffer.alloc(len + 12);
+
+ buf.writeUInt32BE(len, 0);
+ buf.writeUInt32BE(type, 4);
+
+ if (data) {
+ data.copy(buf, 8);
+ }
+
+ buf.writeInt32BE(
+ CrcStream.crc32(buf.slice(4, buf.length - 4)),
+ buf.length - 4
+ );
+ return buf;
+};
+
+Packer.prototype.packGAMA = function (gamma) {
+ let buf = Buffer.alloc(4);
+ buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);
+ return this._packChunk(constants.TYPE_gAMA, buf);
+};
+
+Packer.prototype.packIHDR = function (width, height) {
+ let buf = Buffer.alloc(13);
+ buf.writeUInt32BE(width, 0);
+ buf.writeUInt32BE(height, 4);
+ buf[8] = this._options.bitDepth; // Bit depth
+ buf[9] = this._options.colorType; // colorType
+ buf[10] = 0; // compression
+ buf[11] = 0; // filter
+ buf[12] = 0; // interlace
+
+ return this._packChunk(constants.TYPE_IHDR, buf);
+};
+
+Packer.prototype.packIDAT = function (data) {
+ return this._packChunk(constants.TYPE_IDAT, data);
+};
+
+Packer.prototype.packIEND = function () {
+ return this._packChunk(constants.TYPE_IEND, null);
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/paeth-predictor.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/paeth-predictor.js
new file mode 100644
index 0000000..9634497
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/paeth-predictor.js
@@ -0,0 +1,16 @@
+"use strict";
+
+module.exports = function paethPredictor(left, above, upLeft) {
+ let paeth = left + above - upLeft;
+ let pLeft = Math.abs(paeth - left);
+ let pAbove = Math.abs(paeth - above);
+ let pUpLeft = Math.abs(paeth - upLeft);
+
+ if (pLeft <= pAbove && pLeft <= pUpLeft) {
+ return left;
+ }
+ if (pAbove <= pUpLeft) {
+ return above;
+ }
+ return upLeft;
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/parser-async.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/parser-async.js
new file mode 100644
index 0000000..1aacde3
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/parser-async.js
@@ -0,0 +1,169 @@
+"use strict";
+
+let util = require("util");
+let zlib = require("zlib");
+let ChunkStream = require("./chunkstream");
+let FilterAsync = require("./filter-parse-async");
+let Parser = require("./parser");
+let bitmapper = require("./bitmapper");
+let formatNormaliser = require("./format-normaliser");
+
+let ParserAsync = (module.exports = function (options) {
+ ChunkStream.call(this);
+
+ this._parser = new Parser(options, {
+ read: this.read.bind(this),
+ error: this._handleError.bind(this),
+ metadata: this._handleMetaData.bind(this),
+ gamma: this.emit.bind(this, "gamma"),
+ palette: this._handlePalette.bind(this),
+ transColor: this._handleTransColor.bind(this),
+ finished: this._finished.bind(this),
+ inflateData: this._inflateData.bind(this),
+ simpleTransparency: this._simpleTransparency.bind(this),
+ headersFinished: this._headersFinished.bind(this),
+ });
+ this._options = options;
+ this.writable = true;
+
+ this._parser.start();
+});
+util.inherits(ParserAsync, ChunkStream);
+
+ParserAsync.prototype._handleError = function (err) {
+ this.emit("error", err);
+
+ this.writable = false;
+
+ this.destroy();
+
+ if (this._inflate && this._inflate.destroy) {
+ this._inflate.destroy();
+ }
+
+ if (this._filter) {
+ this._filter.destroy();
+ // For backward compatibility with Node 7 and below.
+ // Suppress errors due to _inflate calling write() even after
+ // it's destroy()'ed.
+ this._filter.on("error", function () {});
+ }
+
+ this.errord = true;
+};
+
+ParserAsync.prototype._inflateData = function (data) {
+ if (!this._inflate) {
+ if (this._bitmapInfo.interlace) {
+ this._inflate = zlib.createInflate();
+
+ this._inflate.on("error", this.emit.bind(this, "error"));
+ this._filter.on("complete", this._complete.bind(this));
+
+ this._inflate.pipe(this._filter);
+ } else {
+ let rowSize =
+ ((this._bitmapInfo.width *
+ this._bitmapInfo.bpp *
+ this._bitmapInfo.depth +
+ 7) >>
+ 3) +
+ 1;
+ let imageSize = rowSize * this._bitmapInfo.height;
+ let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK);
+
+ this._inflate = zlib.createInflate({ chunkSize: chunkSize });
+ let leftToInflate = imageSize;
+
+ let emitError = this.emit.bind(this, "error");
+ this._inflate.on("error", function (err) {
+ if (!leftToInflate) {
+ return;
+ }
+
+ emitError(err);
+ });
+ this._filter.on("complete", this._complete.bind(this));
+
+ let filterWrite = this._filter.write.bind(this._filter);
+ this._inflate.on("data", function (chunk) {
+ if (!leftToInflate) {
+ return;
+ }
+
+ if (chunk.length > leftToInflate) {
+ chunk = chunk.slice(0, leftToInflate);
+ }
+
+ leftToInflate -= chunk.length;
+
+ filterWrite(chunk);
+ });
+
+ this._inflate.on("end", this._filter.end.bind(this._filter));
+ }
+ }
+ this._inflate.write(data);
+};
+
+ParserAsync.prototype._handleMetaData = function (metaData) {
+ this._metaData = metaData;
+ this._bitmapInfo = Object.create(metaData);
+
+ this._filter = new FilterAsync(this._bitmapInfo);
+};
+
+ParserAsync.prototype._handleTransColor = function (transColor) {
+ this._bitmapInfo.transColor = transColor;
+};
+
+ParserAsync.prototype._handlePalette = function (palette) {
+ this._bitmapInfo.palette = palette;
+};
+
+ParserAsync.prototype._simpleTransparency = function () {
+ this._metaData.alpha = true;
+};
+
+ParserAsync.prototype._headersFinished = function () {
+ // Up until this point, we don't know if we have a tRNS chunk (alpha)
+ // so we can't emit metadata any earlier
+ this.emit("metadata", this._metaData);
+};
+
+ParserAsync.prototype._finished = function () {
+ if (this.errord) {
+ return;
+ }
+
+ if (!this._inflate) {
+ this.emit("error", "No Inflate block");
+ } else {
+ // no more data to inflate
+ this._inflate.end();
+ }
+};
+
+ParserAsync.prototype._complete = function (filteredData) {
+ if (this.errord) {
+ return;
+ }
+
+ let normalisedBitmapData;
+
+ try {
+ let bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);
+
+ normalisedBitmapData = formatNormaliser(
+ bitmapData,
+ this._bitmapInfo,
+ this._options.skipRescale
+ );
+ bitmapData = null;
+ } catch (ex) {
+ this._handleError(ex);
+ return;
+ }
+
+ this.emit("parsed", normalisedBitmapData);
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/parser-sync.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/parser-sync.js
new file mode 100644
index 0000000..76cb134
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/parser-sync.js
@@ -0,0 +1,112 @@
+"use strict";
+
+let hasSyncZlib = true;
+let zlib = require("zlib");
+let inflateSync = require("./sync-inflate");
+if (!zlib.deflateSync) {
+ hasSyncZlib = false;
+}
+let SyncReader = require("./sync-reader");
+let FilterSync = require("./filter-parse-sync");
+let Parser = require("./parser");
+let bitmapper = require("./bitmapper");
+let formatNormaliser = require("./format-normaliser");
+
+module.exports = function (buffer, options) {
+ if (!hasSyncZlib) {
+ throw new Error(
+ "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0"
+ );
+ }
+
+ let err;
+ function handleError(_err_) {
+ err = _err_;
+ }
+
+ let metaData;
+ function handleMetaData(_metaData_) {
+ metaData = _metaData_;
+ }
+
+ function handleTransColor(transColor) {
+ metaData.transColor = transColor;
+ }
+
+ function handlePalette(palette) {
+ metaData.palette = palette;
+ }
+
+ function handleSimpleTransparency() {
+ metaData.alpha = true;
+ }
+
+ let gamma;
+ function handleGamma(_gamma_) {
+ gamma = _gamma_;
+ }
+
+ let inflateDataList = [];
+ function handleInflateData(inflatedData) {
+ inflateDataList.push(inflatedData);
+ }
+
+ let reader = new SyncReader(buffer);
+
+ let parser = new Parser(options, {
+ read: reader.read.bind(reader),
+ error: handleError,
+ metadata: handleMetaData,
+ gamma: handleGamma,
+ palette: handlePalette,
+ transColor: handleTransColor,
+ inflateData: handleInflateData,
+ simpleTransparency: handleSimpleTransparency,
+ });
+
+ parser.start();
+ reader.process();
+
+ if (err) {
+ throw err;
+ }
+
+ //join together the inflate datas
+ let inflateData = Buffer.concat(inflateDataList);
+ inflateDataList.length = 0;
+
+ let inflatedData;
+ if (metaData.interlace) {
+ inflatedData = zlib.inflateSync(inflateData);
+ } else {
+ let rowSize =
+ ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1;
+ let imageSize = rowSize * metaData.height;
+ inflatedData = inflateSync(inflateData, {
+ chunkSize: imageSize,
+ maxLength: imageSize,
+ });
+ }
+ inflateData = null;
+
+ if (!inflatedData || !inflatedData.length) {
+ throw new Error("bad png - invalid inflate data response");
+ }
+
+ let unfilteredData = FilterSync.process(inflatedData, metaData);
+ inflateData = null;
+
+ let bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);
+ unfilteredData = null;
+
+ let normalisedBitmapData = formatNormaliser(
+ bitmapData,
+ metaData,
+ options.skipRescale
+ );
+
+ metaData.data = normalisedBitmapData;
+ metaData.gamma = gamma || 0;
+
+ return metaData;
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/parser.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/parser.js
new file mode 100644
index 0000000..51a8f2a
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/parser.js
@@ -0,0 +1,290 @@
+"use strict";
+
+let constants = require("./constants");
+let CrcCalculator = require("./crc");
+
+let Parser = (module.exports = function (options, dependencies) {
+ this._options = options;
+ options.checkCRC = options.checkCRC !== false;
+
+ this._hasIHDR = false;
+ this._hasIEND = false;
+ this._emittedHeadersFinished = false;
+
+ // input flags/metadata
+ this._palette = [];
+ this._colorType = 0;
+
+ this._chunks = {};
+ this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
+ this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
+ this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
+ this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
+ this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
+ this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);
+
+ this.read = dependencies.read;
+ this.error = dependencies.error;
+ this.metadata = dependencies.metadata;
+ this.gamma = dependencies.gamma;
+ this.transColor = dependencies.transColor;
+ this.palette = dependencies.palette;
+ this.parsed = dependencies.parsed;
+ this.inflateData = dependencies.inflateData;
+ this.finished = dependencies.finished;
+ this.simpleTransparency = dependencies.simpleTransparency;
+ this.headersFinished = dependencies.headersFinished || function () {};
+});
+
+Parser.prototype.start = function () {
+ this.read(constants.PNG_SIGNATURE.length, this._parseSignature.bind(this));
+};
+
+Parser.prototype._parseSignature = function (data) {
+ let signature = constants.PNG_SIGNATURE;
+
+ for (let i = 0; i < signature.length; i++) {
+ if (data[i] !== signature[i]) {
+ this.error(new Error("Invalid file signature"));
+ return;
+ }
+ }
+ this.read(8, this._parseChunkBegin.bind(this));
+};
+
+Parser.prototype._parseChunkBegin = function (data) {
+ // chunk content length
+ let length = data.readUInt32BE(0);
+
+ // chunk type
+ let type = data.readUInt32BE(4);
+ let name = "";
+ for (let i = 4; i < 8; i++) {
+ name += String.fromCharCode(data[i]);
+ }
+
+ //console.log('chunk ', name, length);
+
+ // chunk flags
+ let ancillary = Boolean(data[4] & 0x20); // or critical
+ // priv = Boolean(data[5] & 0x20), // or public
+ // safeToCopy = Boolean(data[7] & 0x20); // or unsafe
+
+ if (!this._hasIHDR && type !== constants.TYPE_IHDR) {
+ this.error(new Error("Expected IHDR on beggining"));
+ return;
+ }
+
+ this._crc = new CrcCalculator();
+ this._crc.write(Buffer.from(name));
+
+ if (this._chunks[type]) {
+ return this._chunks[type](length);
+ }
+
+ if (!ancillary) {
+ this.error(new Error("Unsupported critical chunk type " + name));
+ return;
+ }
+
+ this.read(length + 4, this._skipChunk.bind(this));
+};
+
+Parser.prototype._skipChunk = function (/*data*/) {
+ this.read(8, this._parseChunkBegin.bind(this));
+};
+
+Parser.prototype._handleChunkEnd = function () {
+ this.read(4, this._parseChunkEnd.bind(this));
+};
+
+Parser.prototype._parseChunkEnd = function (data) {
+ let fileCrc = data.readInt32BE(0);
+ let calcCrc = this._crc.crc32();
+
+ // check CRC
+ if (this._options.checkCRC && calcCrc !== fileCrc) {
+ this.error(new Error("Crc error - " + fileCrc + " - " + calcCrc));
+ return;
+ }
+
+ if (!this._hasIEND) {
+ this.read(8, this._parseChunkBegin.bind(this));
+ }
+};
+
+Parser.prototype._handleIHDR = function (length) {
+ this.read(length, this._parseIHDR.bind(this));
+};
+Parser.prototype._parseIHDR = function (data) {
+ this._crc.write(data);
+
+ let width = data.readUInt32BE(0);
+ let height = data.readUInt32BE(4);
+ let depth = data[8];
+ let colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha
+ let compr = data[10];
+ let filter = data[11];
+ let interlace = data[12];
+
+ // console.log(' width', width, 'height', height,
+ // 'depth', depth, 'colorType', colorType,
+ // 'compr', compr, 'filter', filter, 'interlace', interlace
+ // );
+
+ if (
+ depth !== 8 &&
+ depth !== 4 &&
+ depth !== 2 &&
+ depth !== 1 &&
+ depth !== 16
+ ) {
+ this.error(new Error("Unsupported bit depth " + depth));
+ return;
+ }
+ if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
+ this.error(new Error("Unsupported color type"));
+ return;
+ }
+ if (compr !== 0) {
+ this.error(new Error("Unsupported compression method"));
+ return;
+ }
+ if (filter !== 0) {
+ this.error(new Error("Unsupported filter method"));
+ return;
+ }
+ if (interlace !== 0 && interlace !== 1) {
+ this.error(new Error("Unsupported interlace method"));
+ return;
+ }
+
+ this._colorType = colorType;
+
+ let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
+
+ this._hasIHDR = true;
+
+ this.metadata({
+ width: width,
+ height: height,
+ depth: depth,
+ interlace: Boolean(interlace),
+ palette: Boolean(colorType & constants.COLORTYPE_PALETTE),
+ color: Boolean(colorType & constants.COLORTYPE_COLOR),
+ alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),
+ bpp: bpp,
+ colorType: colorType,
+ });
+
+ this._handleChunkEnd();
+};
+
+Parser.prototype._handlePLTE = function (length) {
+ this.read(length, this._parsePLTE.bind(this));
+};
+Parser.prototype._parsePLTE = function (data) {
+ this._crc.write(data);
+
+ let entries = Math.floor(data.length / 3);
+ // console.log('Palette:', entries);
+
+ for (let i = 0; i < entries; i++) {
+ this._palette.push([data[i * 3], data[i * 3 + 1], data[i * 3 + 2], 0xff]);
+ }
+
+ this.palette(this._palette);
+
+ this._handleChunkEnd();
+};
+
+Parser.prototype._handleTRNS = function (length) {
+ this.simpleTransparency();
+ this.read(length, this._parseTRNS.bind(this));
+};
+Parser.prototype._parseTRNS = function (data) {
+ this._crc.write(data);
+
+ // palette
+ if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {
+ if (this._palette.length === 0) {
+ this.error(new Error("Transparency chunk must be after palette"));
+ return;
+ }
+ if (data.length > this._palette.length) {
+ this.error(new Error("More transparent colors than palette size"));
+ return;
+ }
+ for (let i = 0; i < data.length; i++) {
+ this._palette[i][3] = data[i];
+ }
+ this.palette(this._palette);
+ }
+
+ // for colorType 0 (grayscale) and 2 (rgb)
+ // there might be one gray/color defined as transparent
+ if (this._colorType === constants.COLORTYPE_GRAYSCALE) {
+ // grey, 2 bytes
+ this.transColor([data.readUInt16BE(0)]);
+ }
+ if (this._colorType === constants.COLORTYPE_COLOR) {
+ this.transColor([
+ data.readUInt16BE(0),
+ data.readUInt16BE(2),
+ data.readUInt16BE(4),
+ ]);
+ }
+
+ this._handleChunkEnd();
+};
+
+Parser.prototype._handleGAMA = function (length) {
+ this.read(length, this._parseGAMA.bind(this));
+};
+Parser.prototype._parseGAMA = function (data) {
+ this._crc.write(data);
+ this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);
+
+ this._handleChunkEnd();
+};
+
+Parser.prototype._handleIDAT = function (length) {
+ if (!this._emittedHeadersFinished) {
+ this._emittedHeadersFinished = true;
+ this.headersFinished();
+ }
+ this.read(-length, this._parseIDAT.bind(this, length));
+};
+Parser.prototype._parseIDAT = function (length, data) {
+ this._crc.write(data);
+
+ if (
+ this._colorType === constants.COLORTYPE_PALETTE_COLOR &&
+ this._palette.length === 0
+ ) {
+ throw new Error("Expected palette not found");
+ }
+
+ this.inflateData(data);
+ let leftOverLength = length - data.length;
+
+ if (leftOverLength > 0) {
+ this._handleIDAT(leftOverLength);
+ } else {
+ this._handleChunkEnd();
+ }
+};
+
+Parser.prototype._handleIEND = function (length) {
+ this.read(length, this._parseIEND.bind(this));
+};
+Parser.prototype._parseIEND = function (data) {
+ this._crc.write(data);
+
+ this._hasIEND = true;
+ this._handleChunkEnd();
+
+ if (this.finished) {
+ this.finished();
+ }
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/png-sync.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/png-sync.js
new file mode 100644
index 0000000..68cac9b
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/png-sync.js
@@ -0,0 +1,12 @@
+"use strict";
+
+let parse = require("./parser-sync");
+let pack = require("./packer-sync");
+
+exports.read = function (buffer, options) {
+ return parse(buffer, options || {});
+};
+
+exports.write = function (png, options) {
+ return pack(png, options);
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/png.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/png.js
new file mode 100644
index 0000000..0b8af3f
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/png.js
@@ -0,0 +1,194 @@
+"use strict";
+
+let util = require("util");
+let Stream = require("stream");
+let Parser = require("./parser-async");
+let Packer = require("./packer-async");
+let PNGSync = require("./png-sync");
+
+let PNG = (exports.PNG = function (options) {
+ Stream.call(this);
+
+ options = options || {}; // eslint-disable-line no-param-reassign
+
+ // coerce pixel dimensions to integers (also coerces undefined -> 0):
+ this.width = options.width | 0;
+ this.height = options.height | 0;
+
+ this.data =
+ this.width > 0 && this.height > 0
+ ? Buffer.alloc(4 * this.width * this.height)
+ : null;
+
+ if (options.fill && this.data) {
+ this.data.fill(0);
+ }
+
+ this.gamma = 0;
+ this.readable = this.writable = true;
+
+ this._parser = new Parser(options);
+
+ this._parser.on("error", this.emit.bind(this, "error"));
+ this._parser.on("close", this._handleClose.bind(this));
+ this._parser.on("metadata", this._metadata.bind(this));
+ this._parser.on("gamma", this._gamma.bind(this));
+ this._parser.on(
+ "parsed",
+ function (data) {
+ this.data = data;
+ this.emit("parsed", data);
+ }.bind(this)
+ );
+
+ this._packer = new Packer(options);
+ this._packer.on("data", this.emit.bind(this, "data"));
+ this._packer.on("end", this.emit.bind(this, "end"));
+ this._parser.on("close", this._handleClose.bind(this));
+ this._packer.on("error", this.emit.bind(this, "error"));
+});
+util.inherits(PNG, Stream);
+
+PNG.sync = PNGSync;
+
+PNG.prototype.pack = function () {
+ if (!this.data || !this.data.length) {
+ this.emit("error", "No data provided");
+ return this;
+ }
+
+ process.nextTick(
+ function () {
+ this._packer.pack(this.data, this.width, this.height, this.gamma);
+ }.bind(this)
+ );
+
+ return this;
+};
+
+PNG.prototype.parse = function (data, callback) {
+ if (callback) {
+ let onParsed, onError;
+
+ onParsed = function (parsedData) {
+ this.removeListener("error", onError);
+
+ this.data = parsedData;
+ callback(null, this);
+ }.bind(this);
+
+ onError = function (err) {
+ this.removeListener("parsed", onParsed);
+
+ callback(err, null);
+ }.bind(this);
+
+ this.once("parsed", onParsed);
+ this.once("error", onError);
+ }
+
+ this.end(data);
+ return this;
+};
+
+PNG.prototype.write = function (data) {
+ this._parser.write(data);
+ return true;
+};
+
+PNG.prototype.end = function (data) {
+ this._parser.end(data);
+};
+
+PNG.prototype._metadata = function (metadata) {
+ this.width = metadata.width;
+ this.height = metadata.height;
+
+ this.emit("metadata", metadata);
+};
+
+PNG.prototype._gamma = function (gamma) {
+ this.gamma = gamma;
+};
+
+PNG.prototype._handleClose = function () {
+ if (!this._parser.writable && !this._packer.readable) {
+ this.emit("close");
+ }
+};
+
+PNG.bitblt = function (src, dst, srcX, srcY, width, height, deltaX, deltaY) {
+ // eslint-disable-line max-params
+ // coerce pixel dimensions to integers (also coerces undefined -> 0):
+ /* eslint-disable no-param-reassign */
+ srcX |= 0;
+ srcY |= 0;
+ width |= 0;
+ height |= 0;
+ deltaX |= 0;
+ deltaY |= 0;
+ /* eslint-enable no-param-reassign */
+
+ if (
+ srcX > src.width ||
+ srcY > src.height ||
+ srcX + width > src.width ||
+ srcY + height > src.height
+ ) {
+ throw new Error("bitblt reading outside image");
+ }
+
+ if (
+ deltaX > dst.width ||
+ deltaY > dst.height ||
+ deltaX + width > dst.width ||
+ deltaY + height > dst.height
+ ) {
+ throw new Error("bitblt writing outside image");
+ }
+
+ for (let y = 0; y < height; y++) {
+ src.data.copy(
+ dst.data,
+ ((deltaY + y) * dst.width + deltaX) << 2,
+ ((srcY + y) * src.width + srcX) << 2,
+ ((srcY + y) * src.width + srcX + width) << 2
+ );
+ }
+};
+
+PNG.prototype.bitblt = function (
+ dst,
+ srcX,
+ srcY,
+ width,
+ height,
+ deltaX,
+ deltaY
+) {
+ // eslint-disable-line max-params
+
+ PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);
+ return this;
+};
+
+PNG.adjustGamma = function (src) {
+ if (src.gamma) {
+ for (let y = 0; y < src.height; y++) {
+ for (let x = 0; x < src.width; x++) {
+ let idx = (src.width * y + x) << 2;
+
+ for (let i = 0; i < 3; i++) {
+ let sample = src.data[idx + i] / 255;
+ sample = Math.pow(sample, 1 / 2.2 / src.gamma);
+ src.data[idx + i] = Math.round(sample * 255);
+ }
+ }
+ }
+ src.gamma = 0;
+ }
+};
+
+PNG.prototype.adjustGamma = function () {
+ PNG.adjustGamma(this);
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/sync-inflate.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/sync-inflate.js
new file mode 100644
index 0000000..4da0d5f
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/sync-inflate.js
@@ -0,0 +1,168 @@
+"use strict";
+
+let assert = require("assert").ok;
+let zlib = require("zlib");
+let util = require("util");
+
+let kMaxLength = require("buffer").kMaxLength;
+
+function Inflate(opts) {
+ if (!(this instanceof Inflate)) {
+ return new Inflate(opts);
+ }
+
+ if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {
+ opts.chunkSize = zlib.Z_MIN_CHUNK;
+ }
+
+ zlib.Inflate.call(this, opts);
+
+ // Node 8 --> 9 compatibility check
+ this._offset = this._offset === undefined ? this._outOffset : this._offset;
+ this._buffer = this._buffer || this._outBuffer;
+
+ if (opts && opts.maxLength != null) {
+ this._maxLength = opts.maxLength;
+ }
+}
+
+function createInflate(opts) {
+ return new Inflate(opts);
+}
+
+function _close(engine, callback) {
+ if (callback) {
+ process.nextTick(callback);
+ }
+
+ // Caller may invoke .close after a zlib error (which will null _handle).
+ if (!engine._handle) {
+ return;
+ }
+
+ engine._handle.close();
+ engine._handle = null;
+}
+
+Inflate.prototype._processChunk = function (chunk, flushFlag, asyncCb) {
+ if (typeof asyncCb === "function") {
+ return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);
+ }
+
+ let self = this;
+
+ let availInBefore = chunk && chunk.length;
+ let availOutBefore = this._chunkSize - this._offset;
+ let leftToInflate = this._maxLength;
+ let inOff = 0;
+
+ let buffers = [];
+ let nread = 0;
+
+ let error;
+ this.on("error", function (err) {
+ error = err;
+ });
+
+ function handleChunk(availInAfter, availOutAfter) {
+ if (self._hadError) {
+ return;
+ }
+
+ let have = availOutBefore - availOutAfter;
+ assert(have >= 0, "have should not go down");
+
+ if (have > 0) {
+ let out = self._buffer.slice(self._offset, self._offset + have);
+ self._offset += have;
+
+ if (out.length > leftToInflate) {
+ out = out.slice(0, leftToInflate);
+ }
+
+ buffers.push(out);
+ nread += out.length;
+ leftToInflate -= out.length;
+
+ if (leftToInflate === 0) {
+ return false;
+ }
+ }
+
+ if (availOutAfter === 0 || self._offset >= self._chunkSize) {
+ availOutBefore = self._chunkSize;
+ self._offset = 0;
+ self._buffer = Buffer.allocUnsafe(self._chunkSize);
+ }
+
+ if (availOutAfter === 0) {
+ inOff += availInBefore - availInAfter;
+ availInBefore = availInAfter;
+
+ return true;
+ }
+
+ return false;
+ }
+
+ assert(this._handle, "zlib binding closed");
+ let res;
+ do {
+ res = this._handle.writeSync(
+ flushFlag,
+ chunk, // in
+ inOff, // in_off
+ availInBefore, // in_len
+ this._buffer, // out
+ this._offset, //out_off
+ availOutBefore
+ ); // out_len
+ // Node 8 --> 9 compatibility check
+ res = res || this._writeState;
+ } while (!this._hadError && handleChunk(res[0], res[1]));
+
+ if (this._hadError) {
+ throw error;
+ }
+
+ if (nread >= kMaxLength) {
+ _close(this);
+ throw new RangeError(
+ "Cannot create final Buffer. It would be larger than 0x" +
+ kMaxLength.toString(16) +
+ " bytes"
+ );
+ }
+
+ let buf = Buffer.concat(buffers, nread);
+ _close(this);
+
+ return buf;
+};
+
+util.inherits(Inflate, zlib.Inflate);
+
+function zlibBufferSync(engine, buffer) {
+ if (typeof buffer === "string") {
+ buffer = Buffer.from(buffer);
+ }
+ if (!(buffer instanceof Buffer)) {
+ throw new TypeError("Not a string or buffer");
+ }
+
+ let flushFlag = engine._finishFlushFlag;
+ if (flushFlag == null) {
+ flushFlag = zlib.Z_FINISH;
+ }
+
+ return engine._processChunk(buffer, flushFlag);
+}
+
+function inflateSync(buffer, opts) {
+ return zlibBufferSync(new Inflate(opts), buffer);
+}
+
+module.exports = exports = inflateSync;
+exports.Inflate = Inflate;
+exports.createInflate = createInflate;
+exports.inflateSync = inflateSync;
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/lib/sync-reader.js b/.agents/skills/compare-screenshots/vendor/pngjs/lib/sync-reader.js
new file mode 100644
index 0000000..213d1a7
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/lib/sync-reader.js
@@ -0,0 +1,45 @@
+"use strict";
+
+let SyncReader = (module.exports = function (buffer) {
+ this._buffer = buffer;
+ this._reads = [];
+});
+
+SyncReader.prototype.read = function (length, callback) {
+ this._reads.push({
+ length: Math.abs(length), // if length < 0 then at most this length
+ allowLess: length < 0,
+ func: callback,
+ });
+};
+
+SyncReader.prototype.process = function () {
+ // as long as there is any data and read requests
+ while (this._reads.length > 0 && this._buffer.length) {
+ let read = this._reads[0];
+
+ if (
+ this._buffer.length &&
+ (this._buffer.length >= read.length || read.allowLess)
+ ) {
+ // ok there is any data so that we can satisfy this request
+ this._reads.shift(); // == read
+
+ let buf = this._buffer;
+
+ this._buffer = buf.slice(read.length);
+
+ read.func.call(this, buf.slice(0, read.length));
+ } else {
+ break;
+ }
+ }
+
+ if (this._reads.length > 0) {
+ throw new Error("There are some read requests waitng on finished stream");
+ }
+
+ if (this._buffer.length > 0) {
+ throw new Error("unrecognised content at end of stream");
+ }
+};
diff --git a/.agents/skills/compare-screenshots/vendor/pngjs/package.json b/.agents/skills/compare-screenshots/vendor/pngjs/package.json
new file mode 100644
index 0000000..25688f5
--- /dev/null
+++ b/.agents/skills/compare-screenshots/vendor/pngjs/package.json
@@ -0,0 +1,76 @@
+{
+ "name": "pngjs",
+ "version": "7.0.0",
+ "description": "PNG encoder/decoder in pure JS, supporting any bit size & interlace, async & sync with full test suite.",
+ "contributors": [
+ "Alexandre Paré",
+ "Gaurav Mali",
+ "Gusts Kaksis",
+ "Kuba Niegowski",
+ "Luke Page",
+ "Pietajan De Potter",
+ "Steven Sojka",
+ "liangzeng",
+ "Michael Vogt",
+ "Xin-Xin Wang",
+ "toriningen",
+ "Eugene Kulabuhov"
+ ],
+ "homepage": "https://github.com/lukeapage/pngjs",
+ "keywords": [
+ "PNG",
+ "decoder",
+ "encoder",
+ "js-png",
+ "node-png",
+ "parser",
+ "png",
+ "png-js",
+ "png-parse",
+ "pngjs"
+ ],
+ "engines": {
+ "node": ">=14.19.0"
+ },
+ "main": "./lib/png.js",
+ "directories": {
+ "lib": "lib",
+ "example": "examples",
+ "test": "test"
+ },
+ "files": [
+ "browser.js",
+ "lib/"
+ ],
+ "scripts": {
+ "build": "yarn prepublish",
+ "prepublish": "yarn browserify",
+ "browserify": "browserify lib/png.js --standalone png > browser.js",
+ "coverage": "nyc --reporter=lcov --reporter=text-summary tape test/*-spec.js",
+ "test": "yarn lint && yarn prettier:check && tape test/*-spec.js | tap-dot && node test/run-compare",
+ "lint": "eslint .",
+ "prettier:write": "prettier --write .",
+ "prettier:check": "prettier --check ."
+ },
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/pngjs/pngjs.git"
+ },
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/pngjs/pngjs/issues"
+ },
+ "devDependencies": {
+ "browserify": "17.0.0",
+ "buffer-equal": "1.0.1",
+ "connect": "3.7.0",
+ "eslint": "8.34.0",
+ "eslint-config-prettier": "8.6.0",
+ "nyc": "15.1.0",
+ "prettier": "2.8.4",
+ "puppeteer": "19.7.1",
+ "serve-static": "1.15.0",
+ "tap-dot": "2.0.0",
+ "tape": "5.6.3"
+ }
+}
diff --git a/.agents/skills/screenshot-critique/SKILL.md b/.agents/skills/screenshot-critique/SKILL.md
index 2126b23..bc6aa40 100644
--- a/.agents/skills/screenshot-critique/SKILL.md
+++ b/.agents/skills/screenshot-critique/SKILL.md
@@ -30,10 +30,14 @@ any content in it at all.
contrast, ground-plane perspective, flag/pole attachment, label style and
icon readability, blur, scale, lighting, artifacts, missing models, terrain
feature readability, roads, water, and overall scan readability.
-5. Compare the sub-agent's critique against your own inspection. Treat overlap
+5. Run the returned critique through `scripts/receipts.mjs`. Every number it
+ flags is a claim the critique cannot show a command for, and every file it
+ flags is one the critique named but never wrote; strike those claims or
+ re-measure them yourself before any of them reach a decision.
+6. Compare the sub-agent's critique against your own inspection. Treat overlap
as high-priority evidence. Treat novel high-confidence findings as bugs to
inspect, not as taste notes to dismiss.
-6. Record actionable findings in the spec, visual report, or next task plan
+7. Record actionable findings in the spec, visual report, or next task plan
before claiming the screenshot is accepted.
## Sub-Agent Prompt
@@ -51,6 +55,14 @@ missing models, terrain feature readability, roads, water, and scan
readability. Do not assume these are correct. Return a concise list of issues
you can see, with confidence and whether the issue is visible in the full image,
the crop, or both.
+
+Describe what you see in words. You are looking at these images, not measuring
+them, so state no pixel value, luminance, percentage, ratio, count, or offset
+unless you ran a command that produced it and you quote that command and its
+output beside the number. "The hem reads clearly darker than the floor beside
+it" is a finding; "44.0 versus 33.6" without a receipt is a fabrication. The
+same goes for files: name no artifact you did not create with a tool you
+actually have.
```
Spawn config:
@@ -59,6 +71,52 @@ Spawn config:
- `fork_context`: `false`
- attach screenshots as `local_image` items
- omit model overrides unless the user explicitly requests one
+- grant a measurement tool whenever you want numbers back — see Receipts
+
+## Receipts
+
+A number in a critique is a **receipt or a guess**, and the two are
+indistinguishable once they are written down. An agent handed images and asked
+for defects will answer in whatever register the question was posed in: ask it
+how much darker the hem is and it returns a luminance mean, because that is
+what the answer is shaped like — not because it measured anything. Sometimes
+the estimate lands close and sometimes it inverts the finding; nothing in the
+report tells you which, and it reads as the strongest evidence there precisely
+because it is numeric. The same reflex names the crops and dumps it says it
+wrote.
+
+- **Match the tool surface to the output contract.** Before spawning, read your
+ own prompt and ask which tool produces each claim you demanded. A judge with
+ images and no shell can report what it sees and nothing else. If you want
+ measurements, grant the tool that measures and name it in the prompt;
+ otherwise stop asking for them.
+- **A number without its command is not a finding.** Every quantity must arrive
+ with the command that produced it and that command's output, close enough to
+ read together. Findings that fail this are struck, not discounted.
+- **Verify, don't trust the eye of the verifier.** Run `scripts/receipts.mjs`
+ over the returned report — `node scripts/receipts.mjs <report.md>` — before
+ you read the findings, so an unsupported number never gets to be persuasive
+ first. It exits nonzero and prints each unbacked quantity and each file the
+ report named but never wrote. `scripts/receipts.eval.mjs` is its own eval,
+ over reports written in the eval whose right answer is known by construction,
+ both directions pinned: run it after changing the checker, and never widen
+ what counts as a receipt to make a failing case pass.
+- **Know which half of it is proof.** The file check is proof: the path is
+ resolved on disk and a stated sha256 is recomputed, so an invented crop dies
+ there. The number check is attribution, not execution — it asks whether a
+ command is shown running with this number in its output, and a report that
+ invents the whole transcript passes. Nothing readable from static text can
+ separate an invented transcript from a real one. So a clean run means the
+ claims are attributable and the files are real, not that anything ran; ask
+ for the artifact and the hash when a number has to hold weight.
+- **Ordinal words are still findings; numbers are not.** "Clearly darker",
+ "roughly a third of the panel", "the left edge is cut off" are what an eye can
+ honestly report. Push the critique toward that register rather than trying to
+ make its arithmetic more careful.
+- **The measured pass is a separate run.** When the words justify numbers, take
+ the measurement yourself with `compare-screenshots`, or re-run the critic with
+ a shell and this same receipt rule. Never repair a report by asking its author
+ to double-check its own figures.
## Rules
diff --git a/.agents/skills/screenshot-critique/scripts/receipts.eval.mjs b/.agents/skills/screenshot-critique/scripts/receipts.eval.mjs
new file mode 100755
index 0000000..121645f
--- /dev/null
+++ b/.agents/skills/screenshot-critique/scripts/receipts.eval.mjs
@@ -0,0 +1,517 @@
+#!/usr/bin/env node
+// Eval harness for receipts.mjs.
+//
+// Every report here is written in this file, so the right answer is known by
+// construction rather than read back from a previous run — a snapshot of
+// current output would happily bless a checker that flags nothing. Each case
+// pins both directions: the fabricated report must be rejected, and the
+// honest one must pass untouched. A checker that always fails is as useless as
+// one that always passes, and only the paired cases catch either.
+//
+// node receipts.eval.mjs
+//
+// Exits nonzero on the first failing expectation, printing every check.
+
+import { spawn } from 'node:child_process';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { createHash } from 'node:crypto';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const here = dirname(fileURLToPath(import.meta.url));
+const script = resolve(here, 'receipts.mjs');
+
+const checks = [];
+const check = (name, pass, detail = '') => checks.push({ name, pass, detail });
+
+const workspace = await mkdtemp(resolve(tmpdir(), 'receipts-eval-'));
+
+// A real 1x1 PNG. The reports below name it the way a critique names the shot
+// it measured, and the checker resolves that name on disk — so the file has to
+// be there for the honest fixtures to pass, and its hash has to be the hash
+// they state.
+const SHOT = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmM'
+ + 'IQAAAABJRU5ErkJggg==',
+ 'base64',
+);
+await writeFile(resolve(workspace, 'shot.png'), SHOT);
+const SHOT_SHA = createHash('sha256').update(SHOT).digest('hex');
+// A second real file, so a fixture can pair two paths with two hashes and show
+// that each path is read against the hash written beside it.
+const CROP = Buffer.concat([SHOT, Buffer.from('\n')]);
+await writeFile(resolve(workspace, 'crop.png'), CROP);
+const CROP_SHA = createHash('sha256').update(CROP).digest('hex');
+const WRONG_SHA = 'f'.repeat(64);
+
+function run(args, stdin = null) {
+ return new Promise((done) => {
+ const child = spawn(process.execPath, [script, ...args], {
+ stdio: [stdin === null ? 'ignore' : 'pipe', 'pipe', 'pipe'],
+ });
+ let stdout = '';
+ let stderr = '';
+ child.stdout.on('data', (c) => { stdout += c; });
+ child.stderr.on('data', (c) => { stderr += c; });
+ if (stdin !== null) {
+ child.stdin.end(stdin);
+ }
+ child.on('close', (code) => done({ code, stdout, stderr }));
+ });
+}
+
+async function report(name, body) {
+ const path = resolve(workspace, `${name}.md`);
+ await writeFile(path, body);
+ return path;
+}
+
+async function judge(name, body) {
+ const path = await report(name, body);
+ const result = await run(['--json', path]);
+ return { ...result, json: JSON.parse(result.stdout) };
+}
+
+// --- the fabrication this exists to catch --------------------------------
+// A critic with images and no shell, asked how much darker the hem is. The
+// numbers are self-consistent, plausibly scaled, and measured nothing.
+const FABRICATED = `# Visual critique
+
+## Findings
+
+1. The under-hem region is not darker than the far field. Mean luminance under
+ the hem is 44.0 against 44.0 in the far field, so the contact shadow is
+ absent.
+2. Left/right symmetry is 96% — the silhouette is effectively mirrored.
+3. The hem sits 12px above the floor plane.
+
+I wrote crops to /tmp/receipts-eval-no-such-crop-hem.png and
+/tmp/receipts-eval-no-such-crop-far.png for reference.
+`;
+
+// The same critique from an agent that had a shell, quoting what it ran.
+const MEASURED = `# Visual critique
+
+## Findings
+
+1. The under-hem region is not darker than the far field.
+
+ \`\`\`
+ $ python3 measure.py shot.png --regions hem far
+ hem mean_luminance 33.6
+ far mean_luminance 44.3
+ \`\`\`
+
+ The hem reads 33.6 against 44.3, a real darkening rather than the flat
+ contact the eye first suggested.
+
+2. Left/right symmetry looks close but I did not measure it.
+`;
+
+// What an image-only critic should sound like: ordinal, not numeric.
+const QUALITATIVE = `# Visual critique
+
+## Findings
+
+1. The under-hem region reads clearly darker than the floor beside it, so the
+ contact shadow is present.
+2. The silhouette looks close to mirrored, though the left sleeve hangs lower.
+3. The hem sits a little above the floor plane — a visible gap, not a contact.
+4. Reviewed at 2x on 3 crops.
+`;
+
+const fabricated = await judge('fabricated', FABRICATED);
+check('fabricated report is rejected', fabricated.code === 1, `code=${fabricated.code}`);
+check('every fabricated quantity is named',
+ [44.0, 96, 12].every((n) => fabricated.json.findings.some((f) => f.claim.includes(String(n)))),
+ JSON.stringify(fabricated.json.findings.map((f) => f.claim)));
+check('fabricated findings carry line numbers',
+ fabricated.json.findings.every((f) => Number.isInteger(f.line) && f.line > 0),
+ JSON.stringify(fabricated.json.findings));
+
+const measured = await judge('measured', MEASURED);
+check('measured report passes', measured.code === 0, JSON.stringify(measured.json.findings));
+check('measured report counts its receipt', measured.json.receipts === 1,
+ `receipts=${measured.json.receipts}`);
+
+const qualitative = await judge('qualitative', QUALITATIVE);
+check('qualitative report passes untouched', qualitative.code === 0,
+ JSON.stringify(qualitative.json.findings));
+
+// --- the laundering move --------------------------------------------------
+// Invented numbers pasted into a code fence with no command. A checker that
+// treats any fenced block as evidence blesses exactly this.
+const LAUNDERED = `# Visual critique
+
+\`\`\`
+hem mean_luminance 44.0
+far mean_luminance 44.0
+\`\`\`
+
+Mean luminance under the hem is 44.0 against 44.0 in the far field.
+`;
+const laundered = await judge('laundered', LAUNDERED);
+check('numbers in a fence with no command are still rejected', laundered.code === 1,
+ `code=${laundered.code} findings=${JSON.stringify(laundered.json.findings)}`);
+
+// --- hex ------------------------------------------------------------------
+// An eyeballed hex value is the same fabrication wearing a different notation,
+// and it hides from a plain number scan.
+const HEXED = `# Visual critique
+
+The band reads roughly 0x60 against a 0xB0 field, judged by eye.
+`;
+const hexed = await judge('hexed', HEXED);
+check('eyeballed hex values are rejected',
+ hexed.code === 1 && hexed.json.findings.length === 2,
+ JSON.stringify(hexed.json.findings));
+
+const HEX_MEASURED = `# Visual critique
+
+\`\`\`
+$ python3 sample.py shot.png --at 320,262 --at 40,262
+0x60
+0xb0
+\`\`\`
+
+The band reads 0x60 against a 0xb0 field.
+`;
+const hexMeasured = await judge('hex-measured', HEX_MEASURED);
+check('measured hex values pass', hexMeasured.code === 0,
+ JSON.stringify(hexMeasured.json.findings));
+
+// --- proximity ------------------------------------------------------------
+// A receipt backs the prose beside it, not a claim pages away that happens to
+// share a digit.
+const DISTANT = `# Visual critique
+
+\`\`\`
+$ python3 measure.py shot.png
+hem mean_luminance 33.6
+\`\`\`
+
+The hem measures 33.6.
+
+Filler line 1.
+Filler line 2.
+Filler line 3.
+Filler line 4.
+Filler line 5.
+Filler line 6.
+Filler line 7.
+Filler line 8.
+
+The sleeve also measures 33.6.
+`;
+const distant = await judge('distant', DISTANT);
+check('a receipt backs only nearby prose', distant.code === 1 && distant.json.findings.length === 1,
+ `findings=${JSON.stringify(distant.json.findings)}`);
+check('the backed claim is not the flagged one',
+ distant.json.findings[0]?.text.includes('sleeve'),
+ JSON.stringify(distant.json.findings));
+
+// --- what must not be flagged --------------------------------------------
+// Bare ordinals, versions, dates, and prose numbers are not measurement
+// claims. Flagging them trains the reader to ignore the tool.
+const ORDINARY = `# Visual critique
+
+Reviewed 4 screenshots captured on 2026-08-26 with the 2 crops from finding 1.
+Issue 3 is the most serious of the 5. See the v1.2 baseline for comparison.
+Confidence: high on findings 1 and 2, medium on 3.
+`;
+const ordinary = await judge('ordinary', ORDINARY);
+check('ordinary prose numbers are not flagged', ordinary.code === 0,
+ JSON.stringify(ordinary.json.findings));
+
+// --- laundering, second form ---------------------------------------------
+// The first laundering fixture pastes numbers into a fence with no command at
+// all. This one is the move that beats a checker looking for a command *word*:
+// the fence holds a sentence with `python3` in it. A sentence has no arguments
+// in it, which is the difference the checker reads.
+const LAUNDERED_COMMAND = `# Visual critique
+
+\`\`\`text
+python3 measured the image and reported the region means below
+hem mean_luminance 44.0
+far mean_luminance 44.0
+\`\`\`
+
+Mean luminance under the hem is 44.0 against 44.0 in the far field.
+`;
+const launderedCommand = await judge('laundered-command', LAUNDERED_COMMAND);
+check('a command word in prose is not a receipt',
+ launderedCommand.code === 1
+ && launderedCommand.json.findings.some((f) => f.kind === 'quantity'),
+ `code=${launderedCommand.code} findings=${JSON.stringify(launderedCommand.json.findings)}`);
+check('the laundering fence counts as no receipt at all',
+ launderedCommand.json.receipts === 0,
+ `receipts=${launderedCommand.json.receipts}`);
+
+// The same block with a real invocation in it passes, so the rule above
+// discriminates rather than rejecting fences wholesale.
+const COMMAND_WITH_ARGS = `# Visual critique
+
+\`\`\`text
+$ python3 measure.py shot.png --regions hem far
+hem mean_luminance 44.0
+far mean_luminance 44.0
+\`\`\`
+
+Mean luminance under the hem is 44.0 against 44.0 in the far field.
+`;
+const commandWithArgs = await judge('command-with-args', COMMAND_WITH_ARGS);
+check('an invocation with arguments still counts as a receipt',
+ commandWithArgs.code === 0, JSON.stringify(commandWithArgs.json.findings));
+
+// --- artifacts ------------------------------------------------------------
+// The crops a fabricating critic says it wrote are the one claim that can be
+// settled against the world rather than against the page.
+const fabricatedArtifacts = fabricated.json.findings.filter((f) => f.kind === 'artifact');
+check('crops the report never wrote are flagged',
+ fabricatedArtifacts.length === 2
+ && fabricatedArtifacts.every((f) => f.detail === 'no such file'),
+ JSON.stringify(fabricatedArtifacts));
+
+const HASH_OK = `# Visual critique
+
+\`\`\`
+$ shasum -a 256 shot.png
+${SHOT_SHA} shot.png
+\`\`\`
+
+The frame under review is shot.png, sha256 ${SHOT_SHA}.
+`;
+const hashOk = await judge('hash-ok', HASH_OK);
+check('a file that is there, with the hash it claims, passes',
+ hashOk.code === 0, JSON.stringify(hashOk.json.findings));
+
+const HASH_WRONG = `# Visual critique
+
+The frame under review is shot.png, sha256 ${WRONG_SHA}.
+`;
+const hashWrong = await judge('hash-wrong', HASH_WRONG);
+check('a stated hash that does not match the file is flagged',
+ hashWrong.code === 1
+ && hashWrong.json.findings.some((f) => f.kind === 'artifact' && /sha256/.test(f.detail)),
+ JSON.stringify(hashWrong.json.findings));
+
+// Reports write the pair both ways round, and `shasum` itself prints the hash
+// first. A checker that only looks to the right of the path lets the whole
+// claim through on the line shasum produced.
+const HASH_WRONG_BEFORE = `# Visual critique
+
+\`\`\`
+$ shasum -a 256 -- *.png
+${WRONG_SHA} shot.png
+\`\`\`
+`;
+const hashWrongBefore = await judge('hash-wrong-before', HASH_WRONG_BEFORE);
+check('a wrong hash stated before the path is flagged',
+ hashWrongBefore.code === 1
+ && hashWrongBefore.json.findings.some((f) => f.kind === 'artifact' && /sha256/.test(f.detail)),
+ JSON.stringify(hashWrongBefore.json.findings));
+
+const HASH_OK_BEFORE = `# Visual critique
+
+\`\`\`
+$ shasum -a 256 -- *.png
+${SHOT_SHA} shot.png
+\`\`\`
+`;
+const hashOkBefore = await judge('hash-ok-before', HASH_OK_BEFORE);
+check('the right hash stated before the path passes',
+ hashOkBefore.code === 0, JSON.stringify(hashOkBefore.json.findings));
+
+// Reading both sides is only safe if the nearer hash wins: a line that pairs
+// two files with two hashes must give each path its own, or the fix trades one
+// bypass for a false accusation.
+const HASH_TWO_ON_A_LINE = `# Visual critique
+
+\`\`\`
+$ shasum -a 256 shot.png crop.png
+${SHOT_SHA} shot.png ${CROP_SHA} crop.png
+\`\`\`
+`;
+const hashTwoOnALine = await judge('hash-two-on-a-line', HASH_TWO_ON_A_LINE);
+check('two files and two hashes on one line each keep their own',
+ hashTwoOnALine.code === 0, JSON.stringify(hashTwoOnALine.json.findings));
+
+// A matching repeat does not make a false SHA claim disappear. Both orders
+// matter: judging a path by whether *any* of its hashes is true launders one
+// of these reports.
+const HASH_FALSE_THEN_TRUE = `# Visual critique
+
+The frame is shot.png, sha256 ${WRONG_SHA}.
+The same frame is shot.png, sha256 ${SHOT_SHA}.
+`;
+const hashFalseThenTrue = await judge('hash-false-then-true', HASH_FALSE_THEN_TRUE);
+check('a false hash followed by a true repeat is flagged',
+ hashFalseThenTrue.code === 1
+ && hashFalseThenTrue.json.findings.filter((f) => f.kind === 'artifact').length === 1,
+ JSON.stringify(hashFalseThenTrue.json.findings));
+
+const HASH_TRUE_THEN_FALSE = `# Visual critique
+
+The frame is shot.png, sha256 ${SHOT_SHA}.
+The same frame is shot.png, sha256 ${WRONG_SHA}.
+`;
+const hashTrueThenFalse = await judge('hash-true-then-false', HASH_TRUE_THEN_FALSE);
+check('a true hash followed by a false repeat is flagged',
+ hashTrueThenFalse.code === 1
+ && hashTrueThenFalse.json.findings.filter((f) => f.kind === 'artifact').length === 1,
+ JSON.stringify(hashTrueThenFalse.json.findings));
+
+const HASH_REPEATED_CORRECT = `# Visual critique
+
+The frame is shot.png, sha256 ${SHOT_SHA}.
+The same frame is shot.png, sha256 ${SHOT_SHA}.
+`;
+const hashRepeatedCorrect = await judge('hash-repeated-correct', HASH_REPEATED_CORRECT);
+check('repeated correct hashes pass',
+ hashRepeatedCorrect.code === 0, JSON.stringify(hashRepeatedCorrect.json.findings));
+
+// The command names both inputs, while its output repeats each with the hash
+// that belongs to it. Command paths must not inherit hashes from output paths.
+const HASH_MULTI_FILE_COMMAND_OUTPUT = `# Visual critique
+
+\`\`\`
+$ shasum -a 256 shot.png crop.png
+${SHOT_SHA} shot.png
+${CROP_SHA} crop.png
+\`\`\`
+`;
+const hashMultiFileCommandOutput = await judge('hash-multi-file-command-output', HASH_MULTI_FILE_COMMAND_OUTPUT);
+check('multi-file command and output keep each hash with its output path',
+ hashMultiFileCommandOutput.code === 0,
+ JSON.stringify(hashMultiFileCommandOutput.json.findings));
+
+// Ordered pairs must work in both directions. Path-first prose does not have
+// the hash-first ordering `shasum` emits, even when table pipes or tabs make
+// every neighboring distance identical.
+const HASH_PATH_FIRST_TWO_FILES = `# Visual critique
+
+shot.png sha256 ${SHOT_SHA} crop.png sha256 ${CROP_SHA}
+`;
+const hashPathFirstTwoFiles = await judge('hash-path-first-two-files', HASH_PATH_FIRST_TWO_FILES);
+check('path-first same-line pairs keep each hash with its path',
+ hashPathFirstTwoFiles.code === 0, JSON.stringify(hashPathFirstTwoFiles.json.findings));
+
+const HASH_PATH_FIRST_TAB = `# Visual critique
+
+shot.png\t${CROP_SHA}\tcrop.png\t${CROP_SHA}
+`;
+const hashPathFirstTab = await judge('hash-path-first-tab', HASH_PATH_FIRST_TAB);
+check('a tab-separated path-first false hash is flagged on its own path',
+ hashPathFirstTab.code === 1
+ && hashPathFirstTab.json.findings.length === 1
+ && hashPathFirstTab.json.findings[0].claim === 'shot.png',
+ JSON.stringify(hashPathFirstTab.json.findings));
+
+const HASH_PATH_FIRST_TABLE = `# Visual critique
+
+| shot.png | ${CROP_SHA} | crop.png | ${CROP_SHA} |
+`;
+const hashPathFirstTable = await judge('hash-path-first-table', HASH_PATH_FIRST_TABLE);
+check('a table path-first false hash is flagged on its own path',
+ hashPathFirstTable.code === 1
+ && hashPathFirstTable.json.findings.length === 1
+ && hashPathFirstTable.json.findings[0].claim === 'shot.png',
+ JSON.stringify(hashPathFirstTable.json.findings));
+
+// One following hash after multiple paths has no defensible owner. It must
+// fail instead of being silently attached to an arbitrary file or discarded.
+const HASH_MULTI_PATH_CONTINUATION = `# Visual critique
+
+Wrote crops to shot.png and crop.png.
+${WRONG_SHA}
+`;
+const hashMultiPathContinuation = await judge('hash-multi-path-continuation', HASH_MULTI_PATH_CONTINUATION);
+check('a hash after multiple paths is rejected as unattributable',
+ hashMultiPathContinuation.code === 1
+ && hashMultiPathContinuation.json.findings.length === 1
+ && /cannot attribute sha256/.test(hashMultiPathContinuation.json.findings[0].detail),
+ JSON.stringify(hashMultiPathContinuation.json.findings));
+
+// Same-line claims pair in occurrence order, not in one direction picked for
+// the entire line. The first line has two hashes beside the first path; the
+// second belongs to crop.png and must not disappear.
+const HASH_TWO_HASHES_BETWEEN_PATHS = `# Visual critique
+
+shot.png ${SHOT_SHA} ${SHOT_SHA} crop.png
+`;
+const hashTwoHashesBetweenPaths = await judge('hash-two-hashes-between-paths', HASH_TWO_HASHES_BETWEEN_PATHS);
+check('two hashes between paths flag the false second artifact claim',
+ hashTwoHashesBetweenPaths.code === 1
+ && hashTwoHashesBetweenPaths.json.findings.length === 1
+ && hashTwoHashesBetweenPaths.json.findings[0].claim === 'crop.png',
+ JSON.stringify(hashTwoHashesBetweenPaths.json.findings));
+
+// One pair starts hash-first and the next path-first. Equal occurrence counts
+// make their mapping unambiguous even though no single line direction fits.
+const HASH_MIXED_ORIENTATION = `# Visual critique
+
+${SHOT_SHA} shot.png crop.png ${CROP_SHA}
+`;
+const hashMixedOrientation = await judge('hash-mixed-orientation', HASH_MIXED_ORIENTATION);
+check('mixed hash-first and path-first pairs pass in occurrence order',
+ hashMixedOrientation.code === 0, JSON.stringify(hashMixedOrientation.json.findings));
+
+// A multi-path line that already has an ambiguous hash still cannot make its
+// following bare hash disappear. The continuation must be named explicitly.
+const HASH_MULTI_PATH_HASHED_CONTINUATION = `# Visual critique
+
+shot.png ${SHOT_SHA} crop.png
+${WRONG_SHA}
+`;
+const hashMultiPathHashedContinuation = await judge('hash-multi-path-hashed-continuation', HASH_MULTI_PATH_HASHED_CONTINUATION);
+check('a hash continuation after a hashed multi-path line is unattributable',
+ hashMultiPathHashedContinuation.code === 1
+ && hashMultiPathHashedContinuation.json.findings.some((f) =>
+ f.line === 4 && /cannot attribute sha256/.test(f.detail)),
+ JSON.stringify(hashMultiPathHashedContinuation.json.findings));
+
+// Negative control for the artifact half: naming a file that is really there,
+// with no hash claimed, must stay silent. A checker that flags every path is
+// as useless as one that flags none.
+const ARTIFACT_OK = `# Visual critique
+
+The shot under review is shot.png; the crop discussion refers to its lower
+third. No measurements were taken.
+`;
+const artifactOk = await judge('artifact-ok', ARTIFACT_OK);
+check('naming a file that exists is not a finding',
+ artifactOk.code === 0, JSON.stringify(artifactOk.json.findings));
+
+// --- interfaces -----------------------------------------------------------
+const piped = await run(['--json', '-'], FABRICATED);
+check('stdin is accepted', piped.code === 1 && JSON.parse(piped.stdout).unsupported > 0,
+ piped.stderr.slice(0, 200));
+
+const labelled = await run(['--label', await report('label', FABRICATED)]);
+check('--label annotates in place and keeps every line',
+ labelled.stdout.includes('UNSUPPORTED:')
+ && labelled.stdout.split('\n').length >= FABRICATED.split('\n').length,
+ labelled.stdout.slice(0, 200));
+
+const human = await run([await report('human', FABRICATED)]);
+check('human output names the file and line',
+ /fabrication|unsupported/i.test(human.stdout) && /human\.md:\d+/.test(human.stdout),
+ human.stdout.slice(0, 300));
+
+const missing = await run([resolve(workspace, 'nope.md')]);
+check('a missing report fails loudly', missing.code === 2 && /cannot read/.test(missing.stderr),
+ missing.stderr.slice(0, 200));
+
+const badFlag = await run(['--nonsense', await report('flag', QUALITATIVE)]);
+check('an unknown option fails loudly', badFlag.code === 2 && /unknown option/.test(badFlag.stderr),
+ badFlag.stderr.slice(0, 200));
+
+await rm(workspace, { recursive: true, force: true });
+
+const failed = checks.filter((c) => !c.pass);
+for (const c of checks) {
+ console.log(`${c.pass ? 'PASS' : 'FAIL'} ${c.name}${c.pass || !c.detail ? '' : `\n ${c.detail}`}`);
+}
+console.log(`\n${checks.length - failed.length}/${checks.length} passed`);
+process.exitCode = failed.length === 0 ? 0 : 1;
diff --git a/.agents/skills/screenshot-critique/scripts/receipts.mjs b/.agents/skills/screenshot-critique/scripts/receipts.mjs
new file mode 100755
index 0000000..209fe92
--- /dev/null
+++ b/.agents/skills/screenshot-critique/scripts/receipts.mjs
@@ -0,0 +1,478 @@
+#!/usr/bin/env node
+// Strike unsupported quantities and invented artifacts out of a critique.
+//
+// A judge given images and no shell answers a numeric question numerically:
+// the luminance means, the symmetry percentages, and the crop files it says it
+// wrote all arrive together, self-consistent and invented. This reads the
+// report back and asks two questions of it.
+//
+// Of every number presented as a measurement: does the report show a command
+// that ran, and does that command's output contain this number? That is an
+// attribution check, and attribution is necessary rather than sufficient — a
+// report that invents a whole transcript, command and output together, passes
+// it. Nothing readable from static text can tell an invented transcript from a
+// real one, so this does not claim to.
+//
+// Of every file the report names: is it there, and is it the file the report
+// says it is? That one is not a matter of reading — the path is resolved on
+// disk, and a stated sha256 is recomputed. Fabricated crops and dumps die
+// here, which is the half of the check that touches the world.
+//
+// node receipts.mjs <report.md> [...] # human summary, nonzero if unbacked
+// node receipts.mjs --json <report.md> # machine-readable findings
+// node receipts.mjs --label <report.md> # annotated copy on stdout
+// node receipts.mjs --base DIR <report.md> # resolve relative paths from DIR
+// cat report.md | node receipts.mjs - # read stdin
+
+import { readFile } from 'node:fs/promises';
+import { createHash } from 'node:crypto';
+import { statSync, readFileSync } from 'node:fs';
+import { dirname, isAbsolute, resolve } from 'node:path';
+
+const HELP = `receipts.mjs — reject claims a critique cannot support
+
+ node receipts.mjs [--json|--label] [--window N] [--base DIR] <report.md> [...]
+ node receipts.mjs - read the report from stdin
+
+Numbers are checked for attribution: a command shown running, with this number
+in its output. Files are checked against the filesystem, and against the sha256
+the report states for them if it states one.
+
+Exit code 0 when every claim holds, 1 when any does not, 2 on a usage or read
+error.`;
+
+// A "measurement claim" is a number the report presents as read off the
+// image. Bare ordinals, dates, and dimensions people legitimately eyeball are
+// not claims; a luminance, a ratio, a percentage, a pixel offset, or a count of
+// something measured is.
+const MEASUREMENT_UNITS = [
+ 'px', 'pixel', 'pixels', 'pt', 'dp', 'em', 'rem',
+ 'luminance', 'luma', 'brightness', 'lightness', 'value', 'intensity',
+ 'contrast', 'ratio', 'delta', 'diff', 'difference', 'variance', 'stddev',
+ 'mean', 'median', 'average', 'avg', 'rmse', 'mae', 'psnr', 'ssim',
+ 'entropy', 'density', 'coverage', 'share', 'opacity', 'alpha',
+ 'rgb', 'rgba', 'hsl', 'hex', 'channel', 'saturation', 'hue',
+ 'degrees', 'deg', 'offset', 'width', 'height', 'area', 'count',
+];
+
+// Words that make a nearby number a measurement even without a unit:
+// "the hem measures 44", "symmetry scored 0.82".
+const MEASUREMENT_VERBS = [
+ 'measure', 'measured', 'measures', 'measurement', 'computed', 'calculated',
+ 'sampled', 'scored', 'reads', 'read', 'registers', 'quantif',
+];
+
+const NUMBER = /(?<![\w.$#-])(\d+(?:\.\d+)?)\s*(%|px|pt|dp|em|rem)?(?![\w-])/g;
+
+// A hex literal in a critique is always a pixel value read off the image —
+// there is no other reason to write one — so it needs a receipt whatever
+// words surround it. It also hides from NUMBER, whose word boundaries reject
+// the `0` in `0x60`.
+const HEX = /(?<![\w])(0x[0-9a-f]{2,8}|#[0-9a-f]{3,8})(?![\w])/gi;
+
+// Files a critique claims to have produced or read: crops, dumps, frames,
+// tables. The extension list is deliberately narrow — a report mentioning a
+// script or a module name is not claiming an artifact.
+const ARTIFACT = /(?<![\w@/-])((?:\.{1,2}\/|~\/|\/)?[\w.-]+(?:\/[\w.-]+)*\.(?:png|jpe?g|gif|webp|bmp|tiff?|pdf|csv|tsv|json|ndjson|txt|npy))(?![\w])/gi;
+
+const SHA256 = /\b(?:sha-?256[\s:=]*)?([0-9a-f]{64})\b/i;
+const SHA256_ALL = new RegExp(SHA256.source, 'gi');
+
+const argv = process.argv.slice(2);
+if (argv.length === 0 || argv.includes('--help') || argv.includes('-h')) {
+ console.log(HELP);
+ process.exit(argv.length === 0 ? 2 : 0);
+}
+
+let asJson = false;
+let asLabel = false;
+let window = 4;
+let base = null;
+const targets = [];
+for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i];
+ if (arg === '--json') asJson = true;
+ else if (arg === '--label') asLabel = true;
+ else if (arg === '--window') window = Number.parseInt(argv[++i], 10);
+ else if (arg === '--base') base = argv[++i];
+ else if (arg.startsWith('--')) {
+ console.error(`receipts.mjs: unknown option ${arg}\n\n${HELP}`);
+ process.exit(2);
+ } else targets.push(arg);
+}
+if (!Number.isFinite(window) || window < 0) {
+ console.error('receipts.mjs: --window needs a non-negative integer');
+ process.exit(2);
+}
+if (base !== null && base === undefined) {
+ console.error('receipts.mjs: --base needs a directory');
+ process.exit(2);
+}
+if (targets.length === 0) {
+ console.error(`receipts.mjs: no report given\n\n${HELP}`);
+ process.exit(2);
+}
+
+// --- receipts -------------------------------------------------------------
+
+// Lines that belong to a fenced block, an indented block, or a `$ cmd` shell
+// transcript.
+function receiptLines(lines) {
+ const inReceipt = new Array(lines.length).fill(false);
+ let fence = null;
+ let transcript = false;
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ const fenceMatch = /^\s*(`{3,}|~{3,})/.exec(line);
+ if (fenceMatch) {
+ if (fence === null) {
+ fence = fenceMatch[1][0].repeat(3);
+ inReceipt[i] = true;
+ continue;
+ }
+ if (fenceMatch[1].startsWith(fence)) {
+ fence = null;
+ inReceipt[i] = true;
+ continue;
+ }
+ }
+ if (fence !== null) {
+ inReceipt[i] = true;
+ continue;
+ }
+ if (/^\s{4,}\S/.test(line) && !/^\s*[-*+]\s/.test(line)) {
+ inReceipt[i] = true;
+ continue;
+ }
+ // `$ cmd` opens a transcript; its output runs until a blank line.
+ if (/^\s*\$\s+\S/.test(line)) {
+ inReceipt[i] = true;
+ transcript = true;
+ continue;
+ }
+ if (transcript) {
+ if (line.trim() === '') transcript = false;
+ else inReceipt[i] = true;
+ }
+ }
+ return inReceipt;
+}
+
+const TOOLS = new Set([
+ 'node', 'python', 'python3', 'magick', 'convert', 'ffmpeg', 'ffprobe',
+ 'identify', 'compare', 'sips', 'exiftool', 'jq', 'awk', 'sed', 'grep', 'rg',
+ 'cat', 'head', 'tail', 'ls', 'wc', 'printf', 'echo', 'uv', 'uvx', 'npx',
+ 'pnpm', 'deno', 'bun', 'bash', 'sh', 'zsh', 'sha256sum', 'shasum', 'stat',
+ 'file', 'du', 'find', 'sort', 'uniq', 'cut', 'tr', 'xxd', 'od',
+]);
+
+// A token that reads as an argument rather than as English: a flag, a path, a
+// filename, a key=value, a format string, an ImageMagick sink like `info:`.
+function looksLikeArgument(token) {
+ if (token.startsWith('-')) return true;
+ if (token.includes('/') || token.includes('\\')) return true;
+ if (/\.\w{1,6}$/.test(token)) return true;
+ if (token.includes('=')) return true;
+ if (/^['"]/.test(token) || token.includes('%[') || token.includes('{')) return true;
+ if (/^\w+:$/.test(token)) return true;
+ if (/^[$@]/.test(token)) return true;
+ return false;
+}
+
+// A receipt has to actually run something, and running something has a shape:
+// an executable followed by at least one argument. This is the line that
+// separates a transcript from prose wearing a code fence — the laundering
+// move is to paste invented numbers under a sentence that merely contains the
+// word `python3`, and a sentence has no arguments in it.
+function isInvocation(line) {
+ const stripped = line.replace(/^\s*[$>]\s+/, '').trim();
+ if (stripped === '') return false;
+ const tokens = stripped.split(/\s+/);
+ const head = tokens[0].replace(/^.*\//, '');
+ const runnable = TOOLS.has(head)
+ || /^\.{0,2}\//.test(tokens[0])
+ || /^\w[\w.-]*\.(?:mjs|js|py|sh)$/.test(head);
+ if (!runnable) return false;
+ return tokens.slice(1).some(looksLikeArgument);
+}
+
+// --- claims ---------------------------------------------------------------
+
+// `previous` is the line above, joined on for context only. Prose wraps
+// mid-sentence, so the unit that makes a number a measurement — "Mean
+// luminance under / the hem is 44.0" — routinely lands on the line before the
+// number it qualifies. Reading one line at a time misses exactly the claims
+// worth catching, and column and line numbers still report against `line`.
+function claimsIn(line, previous = '') {
+ const lower = line.toLowerCase();
+ const carried = previous.toLowerCase().slice(-60);
+ const hits = [];
+ for (const match of line.matchAll(NUMBER)) {
+ const [, value, suffix] = match;
+ const start = match.index;
+ const before = `${start < 40 ? `${carried} ` : ''}${lower.slice(Math.max(0, start - 40), start)}`;
+ const after = lower.slice(start + match[0].length, start + match[0].length + 24);
+ const context = `${before} ${after}`;
+ const unitAttached = suffix === '%' || Boolean(suffix);
+ const unitNearby = MEASUREMENT_UNITS.some((unit) =>
+ new RegExp(`\\b${unit}\\b`).test(context));
+ const verbNearby = MEASUREMENT_VERBS.some((verb) => before.includes(verb));
+ if (!unitAttached && !unitNearby && !verbNearby) continue;
+ hits.push({ value, text: match[0].trim(), column: start + 1 });
+ }
+ for (const match of line.matchAll(HEX)) {
+ hits.push({
+ value: match[1].toLowerCase(),
+ text: match[1],
+ column: match.index + 1,
+ });
+ }
+ return hits;
+}
+
+// --- artifacts ------------------------------------------------------------
+
+function resolveArtifact(path, baseDir) {
+ if (path.startsWith('~/')) {
+ const home = process.env.HOME ?? process.env.USERPROFILE;
+ return home ? resolve(home, path.slice(2)) : path;
+ }
+ return isAbsolute(path) ? path : resolve(baseDir, path);
+}
+
+// Pair same-line paths and SHA-256 claims by occurrence order when their
+// counts agree. That preserves both `shasum` (`hash path`) and prose (`path
+// hash`), including a line that mixes the two orientations. Unequal runs are
+// ambiguous and fail closed rather than lending a hash to the wrong artifact.
+function statedHashes(lines, sitesByLine) {
+ const claimsBySite = new Map();
+ const findings = [];
+ for (const sites of sitesByLine.values()) {
+ for (const site of sites) claimsBySite.set(site, []);
+ }
+
+ for (let i = 0; i < lines.length; i++) {
+ const sites = sitesByLine.get(i) ?? [];
+ const hashes = [...lines[i].matchAll(SHA256_ALL)];
+ if (sites.length > 0 && hashes.length > 0) {
+ if (sites.length === hashes.length) {
+ for (let j = 0; j < sites.length; j++) {
+ claimsBySite.get(sites[j]).push(hashes[j][1].toLowerCase());
+ }
+ } else {
+ for (const hash of hashes) {
+ findings.push({
+ kind: 'artifact',
+ line: i + 1,
+ column: hash.index + 1,
+ claim: `sha256 ${hash[1]}`,
+ detail: `cannot attribute sha256 one-to-one across artifact paths: ${sites.map((site) => site.claimed).join(', ')}`,
+ text: lines[i].trim(),
+ });
+ }
+ }
+ }
+
+ const nextSites = sitesByLine.get(i + 1) ?? [];
+ const nextHashes = [...(lines[i + 1] ?? '').matchAll(SHA256_ALL)];
+ // Do not borrow a `shasum` output hash for a path named in its command:
+ // the output line has its own artifact path. A hash-only continuation is
+ // unambiguous only when the preceding line named one artifact. It remains
+ // that artifact's claim even when another hash was stated on that line.
+ if (sites.length === 1 && nextSites.length === 0) {
+ for (const hash of nextHashes) {
+ claimsBySite.get(sites[0]).push(hash[1].toLowerCase());
+ }
+ } else if (sites.length > 1 && nextSites.length === 0) {
+ for (const hash of nextHashes) {
+ findings.push({
+ kind: 'artifact',
+ line: i + 2,
+ column: hash.index + 1,
+ claim: `sha256 ${hash[1]}`,
+ detail: `cannot attribute sha256 to one artifact: ${sites.map((site) => site.claimed).join(', ')}`,
+ text: lines[i + 1].trim(),
+ });
+ }
+ }
+ }
+ return { claimsBySite, findings };
+}
+
+function checkArtifacts(lines, baseDir) {
+ // Paths are grouped for the filesystem lookup, but every hash statement is
+ // retained at the occurrence where it was made. A true repeat never erases
+ // an earlier false claim about the same file.
+ const findings = [];
+ const occurrences = new Map();
+ const sitesByLine = new Map();
+ for (let i = 0; i < lines.length; i++) {
+ for (const match of lines[i].matchAll(ARTIFACT)) {
+ const claimed = match[1];
+ if (!occurrences.has(claimed)) occurrences.set(claimed, []);
+ const site = { line: i, column: match.index, end: match.index + claimed.length, claimed };
+ occurrences.get(claimed).push(site);
+ if (!sitesByLine.has(i)) sitesByLine.set(i, []);
+ sitesByLine.get(i).push(site);
+ }
+ }
+ const { claimsBySite, findings: hashFindings } = statedHashes(lines, sitesByLine);
+ findings.push(...hashFindings);
+
+ for (const [claimed, sites] of occurrences) {
+ const full = resolveArtifact(claimed, baseDir);
+ let exists = false;
+ try {
+ exists = statSync(full).isFile();
+ } catch {
+ exists = false;
+ }
+ const first = sites[0];
+ if (!exists) {
+ findings.push({
+ kind: 'artifact',
+ line: first.line + 1,
+ column: first.column + 1,
+ claim: claimed,
+ detail: 'no such file',
+ text: lines[first.line].trim(),
+ });
+ continue;
+ }
+
+ const actual = createHash('sha256').update(readFileSync(full)).digest('hex');
+ for (const site of sites) {
+ for (const stated of claimsBySite.get(site)) {
+ if (stated === actual) continue;
+ findings.push({
+ kind: 'artifact',
+ line: site.line + 1,
+ column: site.column + 1,
+ claim: claimed,
+ detail: `sha256 is ${actual.slice(0, 16)}…, report says ${stated.slice(0, 16)}…`,
+ text: lines[site.line].trim(),
+ });
+ }
+ }
+ }
+ return findings;
+}
+
+// --- analysis -------------------------------------------------------------
+
+function analyse(source, text, baseDir) {
+ const lines = text.split('\n');
+ const inReceipt = receiptLines(lines);
+ const receiptRuns = [];
+ for (let i = 0; i < lines.length; i++) {
+ if (!inReceipt[i]) continue;
+ const start = i;
+ while (i < lines.length && inReceipt[i]) i++;
+ const body = lines.slice(start, i);
+ const commands = body.filter(isInvocation);
+ // Output is what the block holds that is not the command and not a fence.
+ const output = body.filter((line) =>
+ !isInvocation(line) && line.trim() !== '' && !/^\s*(`{3,}|~{3,})/.test(line));
+ receiptRuns.push({
+ start,
+ end: i - 1,
+ // Both halves are required. A command with nothing under it shows an
+ // intention, not a result; output with no command is the laundering
+ // move. Numbers come from the output alone, so a value typed into the
+ // command line cannot vouch for itself.
+ ran: commands.length > 0 && output.length > 0,
+ numbers: new Set(output.flatMap((line) => [
+ ...[...line.matchAll(NUMBER)].map((m) => m[1]),
+ ...[...line.matchAll(HEX)].map((m) => m[1].toLowerCase()),
+ ])),
+ });
+ }
+
+ const findings = [];
+ for (let i = 0; i < lines.length; i++) {
+ if (inReceipt[i]) continue;
+ for (const claim of claimsIn(lines[i], i > 0 && !inReceipt[i - 1] ? lines[i - 1] : '')) {
+ const backing = receiptRuns.find((run) =>
+ run.ran
+ && run.numbers.has(claim.value)
+ && i >= run.start - window - 1
+ && i <= run.end + window + 1);
+ if (backing) continue;
+ findings.push({
+ kind: 'quantity',
+ source,
+ line: i + 1,
+ column: claim.column,
+ claim: claim.text,
+ text: lines[i].trim(),
+ });
+ }
+ }
+ for (const finding of checkArtifacts(lines, baseDir)) {
+ findings.push({ source, ...finding });
+ }
+ findings.sort((a, b) => a.line - b.line || a.column - b.column);
+ return { lines, findings, receipts: receiptRuns.filter((r) => r.ran).length };
+}
+
+// --- run ------------------------------------------------------------------
+
+async function load(target) {
+ if (target === '-') {
+ const chunks = [];
+ for await (const chunk of process.stdin) chunks.push(chunk);
+ return Buffer.concat(chunks).toString('utf8');
+ }
+ return readFile(target, 'utf8');
+}
+
+const reports = [];
+for (const target of targets) {
+ let text;
+ try {
+ text = await load(target);
+ } catch (error) {
+ console.error(`receipts.mjs: cannot read ${target}: ${error.message}`);
+ process.exit(2);
+ }
+ const baseDir = base ?? (target === '-' ? process.cwd() : dirname(resolve(target)));
+ reports.push(analyse(target === '-' ? '<stdin>' : target, text, baseDir));
+}
+
+const findings = reports.flatMap((r) => r.findings);
+
+if (asLabel) {
+ for (const report of reports) {
+ const flagged = new Map();
+ for (const f of report.findings) {
+ flagged.set(f.line, [...(flagged.get(f.line) ?? []), f.claim]);
+ }
+ report.lines.forEach((line, index) => {
+ const claims = flagged.get(index + 1);
+ console.log(claims ? `${line} <!-- UNSUPPORTED: ${claims.join(', ')} -->` : line);
+ });
+ }
+} else if (asJson) {
+ console.log(JSON.stringify({
+ ok: findings.length === 0,
+ receipts: reports.reduce((sum, r) => sum + r.receipts, 0),
+ unsupported: findings.length,
+ findings,
+ }, null, 2));
+} else if (findings.length === 0) {
+ const receipts = reports.reduce((sum, r) => sum + r.receipts, 0);
+ console.log(`receipts: ok — every quantity is attributed and every file is there (${receipts} receipt${receipts === 1 ? '' : 's'} found)`);
+} else {
+ const quantities = findings.filter((f) => f.kind === 'quantity').length;
+ const artifacts = findings.length - quantities;
+ const parts = [];
+ if (quantities) parts.push(`${quantities} unsupported quantit${quantities === 1 ? 'y' : 'ies'}`);
+ if (artifacts) parts.push(`${artifacts} file claim${artifacts === 1 ? '' : 's'} that do not hold`);
+ console.log(`receipts: ${parts.join(', ')} — strike or re-measure before these reach a decision\n`);
+ for (const f of findings) {
+ console.log(` ${f.source}:${f.line}:${f.column} ${f.claim}${f.detail ? ` — ${f.detail}` : ''}`);
+ console.log(` ${f.text}`);
+ }
+}
+
+process.exitCode = findings.length === 0 ? 0 : 1;