@mizchi/vlmkit-core 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +1 -1
  2. package/dist/a11y-semantic.d.mts +34 -0
  3. package/dist/a11y-semantic.mjs +261 -0
  4. package/dist/arg-reader.d.mts +52 -0
  5. package/dist/arg-reader.mjs +129 -0
  6. package/dist/auth-state.d.mts +30 -0
  7. package/dist/auth-state.mjs +82 -0
  8. package/dist/authored-style-capture.d.mts +42 -0
  9. package/dist/authored-style-capture.mjs +117 -0
  10. package/dist/authored-style-diff.d.mts +15 -0
  11. package/dist/authored-style-diff.mjs +16 -0
  12. package/dist/cli-args.d.mts +35 -0
  13. package/dist/cli-args.mjs +63 -0
  14. package/dist/cli-error.d.mts +12 -0
  15. package/dist/cli-error.mjs +71 -0
  16. package/dist/computed-style-capture.d.mts +41 -0
  17. package/dist/computed-style-capture.mjs +589 -0
  18. package/dist/computed-style-diff.d.mts +83 -0
  19. package/dist/computed-style-diff.mjs +123 -0
  20. package/dist/diff-regions.d.mts +8 -0
  21. package/dist/diff-regions.mjs +52 -0
  22. package/dist/dom-equivalence.d.mts +51 -0
  23. package/dist/dom-equivalence.mjs +91 -0
  24. package/dist/dom-position-styles.d.mts +166 -0
  25. package/dist/dom-position-styles.mjs +296 -0
  26. package/dist/element-compare.d.mts +71 -0
  27. package/dist/element-compare.mjs +269 -0
  28. package/dist/gate-config.d.mts +116 -0
  29. package/dist/gate-config.mjs +169 -0
  30. package/dist/gate-exit.d.mts +45 -0
  31. package/dist/gate-exit.mjs +25 -0
  32. package/dist/heatmap-regions.d.mts +57 -0
  33. package/dist/heatmap-regions.mjs +158 -0
  34. package/dist/heatmap.d.mts +86 -0
  35. package/dist/heatmap.mjs +510 -0
  36. package/dist/image-resize.d.mts +34 -0
  37. package/dist/image-resize.mjs +92 -0
  38. package/dist/index.d.mts +15 -0
  39. package/dist/index.mjs +14 -0
  40. package/dist/legacy-names.d.mts +48 -0
  41. package/dist/legacy-names.mjs +134 -0
  42. package/dist/mask.d.mts +18 -0
  43. package/dist/mask.mjs +27 -0
  44. package/dist/navigation-redirect.d.mts +28 -0
  45. package/dist/navigation-redirect.mjs +47 -0
  46. package/dist/page-open.d.mts +102 -0
  47. package/dist/page-open.mjs +133 -0
  48. package/dist/png-utils.d.mts +30 -0
  49. package/dist/png-utils.mjs +80 -0
  50. package/dist/region-shift.d.mts +20 -0
  51. package/dist/region-shift.mjs +128 -0
  52. package/dist/run-ledger.d.mts +14 -0
  53. package/dist/run-ledger.mjs +31 -0
  54. package/dist/terminal-colors.d.mts +12 -0
  55. package/dist/terminal-colors.mjs +14 -0
  56. package/dist/text-rows.d.mts +121 -0
  57. package/dist/text-rows.mjs +246 -0
  58. package/{src/types.ts → dist/types.d.mts} +88 -206
  59. package/dist/types.mjs +1 -0
  60. package/package.json +17 -5
  61. package/src/a11y-semantic.ts +0 -384
  62. package/src/authored-style-capture.ts +0 -185
  63. package/src/authored-style-diff.ts +0 -32
  64. package/src/cli-args.ts +0 -29
  65. package/src/cli-error.ts +0 -85
  66. package/src/computed-style-capture.ts +0 -717
  67. package/src/computed-style-diff.ts +0 -192
  68. package/src/diff-regions.ts +0 -70
  69. package/src/dom-equivalence.ts +0 -158
  70. package/src/dom-position-styles.ts +0 -457
  71. package/src/element-compare.ts +0 -354
  72. package/src/heatmap-regions.ts +0 -245
  73. package/src/heatmap.ts +0 -670
  74. package/src/image-resize.ts +0 -112
  75. package/src/index.ts +0 -105
  76. package/src/mask.ts +0 -41
  77. package/src/png-utils.ts +0 -86
  78. package/src/region-shift.ts +0 -173
  79. package/src/run-ledger.ts +0 -39
  80. package/src/terminal-colors.ts +0 -13
  81. package/src/text-rows.ts +0 -412
@@ -0,0 +1,116 @@
1
+ //#region src/gate-config.d.ts
2
+ /**
3
+ * `vlmkit.gates.json` — one reviewed file that says which gates run on which
4
+ * pages, and holds every suppression with a reason attached.
5
+ *
6
+ * Why this exists: the documented convention was npm scripts, one line per
7
+ * page. Three separate reviewers landed on the same complaint — the scripts
8
+ * stop scaling around twenty pages, and once a `--allow-invisible` or an
9
+ * integrity exemption is inlined in a script, the only way to audit what has
10
+ * been silenced repo-wide is `grep`. A suppression nobody can enumerate is a
11
+ * suppression nobody revisits.
12
+ *
13
+ * Two decisions make the file worth reviewing rather than just worth having:
14
+ *
15
+ * 1. **A suppression must carry a reason.** Parsing fails without one. The
16
+ * flag alone records what was silenced but not why, which is exactly the
17
+ * state that makes a reviewer approve it again a year later.
18
+ * 2. **An expired suppression is dropped, not applied.** It is reported
19
+ * loudly and the gate goes back to failing. An expiry date that keeps
20
+ * working after it passes is a comment, not a deadline.
21
+ */
22
+ interface GateSuppression {
23
+ /**
24
+ * Gate this applies to, as a prefix of the gate command: `check copy`
25
+ * matches `check copy --manifest x.txt`.
26
+ */
27
+ gate: string;
28
+ /** Flag(s) appended to that gate's invocation, e.g. `--allow-invisible visually-hidden`. */
29
+ flag: string;
30
+ /** Why this is acceptable. Required — an unexplained suppression is unauditable. */
31
+ reason: string;
32
+ /** Who signed off. Optional but reported, so an unowned entry is visible. */
33
+ owner?: string;
34
+ /** `YYYY-MM-DD`. Omitted means permanent, which the inventory counts separately. */
35
+ expires?: string;
36
+ }
37
+ interface GatePage {
38
+ /** Short stable name for `--only` and reports. Defaults to the source. */
39
+ id?: string;
40
+ /** File path, glob, or URL handed to each gate. */
41
+ source: string;
42
+ /** Gate commands for this page. Falls back to `defaults.gates`. */
43
+ gates?: string[];
44
+ /** Extra gates for this page on top of the defaults. */
45
+ extraGates?: string[];
46
+ suppressions?: GateSuppression[];
47
+ }
48
+ interface GateConfig {
49
+ defaults?: {
50
+ gates?: string[];
51
+ suppressions?: GateSuppression[];
52
+ };
53
+ pages: GatePage[];
54
+ }
55
+ interface ResolvedSuppression extends GateSuppression {
56
+ /** Page id this came from, or `defaults`. */
57
+ scope: string;
58
+ status: "active" | "expired" | "permanent";
59
+ /** Days until expiry; negative when overdue, null when permanent. */
60
+ daysLeft: number | null;
61
+ }
62
+ interface GateJob {
63
+ pageId: string;
64
+ source: string;
65
+ /** Gate command with any active suppression flags already appended. */
66
+ gate: string;
67
+ /** The gate as written in the config, before suppression flags. */
68
+ baseGate: string;
69
+ appliedSuppressions: ResolvedSuppression[];
70
+ }
71
+ interface GatePlan {
72
+ jobs: GateJob[];
73
+ /** Every suppression the config declares, resolved against `now`. */
74
+ suppressions: ResolvedSuppression[];
75
+ /**
76
+ * Suppressions past their expiry. Their flags are NOT applied — the gate
77
+ * fails again — and callers are expected to print these before running.
78
+ */
79
+ expired: ResolvedSuppression[];
80
+ }
81
+ declare const GATE_CONFIG_FILENAMES: string[];
82
+ /** Parse and validate. Every error names the JSON path so the fix is obvious. */
83
+ declare function parseGateConfig(raw: string): GateConfig;
84
+ declare function resolveSuppression(s: GateSuppression, scope: string, now: Date): ResolvedSuppression;
85
+ interface ResolveOptions {
86
+ now?: Date;
87
+ /** Page ids or sources to keep. Substring match, so `admin` selects a subtree. */
88
+ only?: string[];
89
+ }
90
+ /**
91
+ * Turn the config into the exact list of gate invocations to run.
92
+ *
93
+ * Suppression flags are appended to matching gates only when active. An
94
+ * expired one is surfaced in `plan.expired` and deliberately left off the
95
+ * command line: the gate returns to failing, which is what an expiry date is
96
+ * supposed to mean.
97
+ */
98
+ declare function resolveGatePlan(config: GateConfig, options?: ResolveOptions): GatePlan;
99
+ /**
100
+ * Token-wise prefix match: `check copy` matches `check copy --manifest x.txt`
101
+ * but not `check copyright`, and `check` matches every check gate.
102
+ */
103
+ declare function gateMatches(gate: string, pattern: string): boolean;
104
+ interface SuppressionSummary {
105
+ rows: ResolvedSuppression[];
106
+ active: number;
107
+ expired: number;
108
+ permanent: number;
109
+ /** Active entries with no owner — visible rather than tolerated silently. */
110
+ unowned: number;
111
+ /** Active entries expiring within `soonDays`. */
112
+ expiringSoon: number;
113
+ }
114
+ declare function summarizeSuppressions(suppressions: ResolvedSuppression[], soonDays?: number): SuppressionSummary;
115
+ //#endregion
116
+ export { GATE_CONFIG_FILENAMES, GateConfig, GateJob, GatePage, GatePlan, GateSuppression, ResolveOptions, ResolvedSuppression, SuppressionSummary, gateMatches, parseGateConfig, resolveGatePlan, resolveSuppression, summarizeSuppressions };
@@ -0,0 +1,169 @@
1
+ //#region src/gate-config.ts
2
+ const DAY_MS = 864e5;
3
+ const GATE_CONFIG_FILENAMES = ["vlmkit.gates.json", ".vlmkit/gates.json"];
4
+ function fail(path, message) {
5
+ throw new Error(`${path}: ${message}`);
6
+ }
7
+ function parseSuppression(raw, path) {
8
+ if (typeof raw !== "object" || raw === null) fail(path, "must be an object");
9
+ const s = raw;
10
+ for (const key of [
11
+ "gate",
12
+ "flag",
13
+ "reason"
14
+ ]) if (typeof s[key] !== "string" || !s[key].trim()) fail(path, `${key} is required and must be a non-empty string`);
15
+ if (s.owner !== void 0 && typeof s.owner !== "string") fail(path, "owner must be a string");
16
+ if (s.expires !== void 0) {
17
+ if (typeof s.expires !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(s.expires)) fail(path, `expires must be YYYY-MM-DD, got ${JSON.stringify(s.expires)}`);
18
+ if (Number.isNaN(Date.parse(`${s.expires}T00:00:00Z`))) fail(path, `expires is not a real date: ${s.expires}`);
19
+ }
20
+ return {
21
+ gate: s.gate.trim(),
22
+ flag: s.flag.trim(),
23
+ reason: s.reason.trim(),
24
+ ...s.owner ? { owner: s.owner } : {},
25
+ ...s.expires ? { expires: s.expires } : {}
26
+ };
27
+ }
28
+ function parseGateList(raw, path) {
29
+ if (!Array.isArray(raw)) fail(path, "must be an array of gate command strings");
30
+ if (raw.length === 0) fail(path, "is empty — remove the key or list at least one gate");
31
+ return raw.map((g, i) => {
32
+ if (typeof g !== "string" || !g.trim()) fail(`${path}[${i}]`, "must be a non-empty string");
33
+ return g.trim();
34
+ });
35
+ }
36
+ /** Parse and validate. Every error names the JSON path so the fix is obvious. */
37
+ function parseGateConfig(raw) {
38
+ let data;
39
+ try {
40
+ data = JSON.parse(raw);
41
+ } catch (e) {
42
+ throw new Error(`gate config is not valid JSON: ${e instanceof Error ? e.message : e}`);
43
+ }
44
+ if (typeof data !== "object" || data === null) fail("config", "must be a JSON object");
45
+ const root = data;
46
+ const defaults = {};
47
+ if (root.defaults !== void 0) {
48
+ if (typeof root.defaults !== "object" || root.defaults === null) fail("defaults", "must be an object");
49
+ const d = root.defaults;
50
+ if (d.gates !== void 0) defaults.gates = parseGateList(d.gates, "defaults.gates");
51
+ if (d.suppressions !== void 0) {
52
+ if (!Array.isArray(d.suppressions)) fail("defaults.suppressions", "must be an array");
53
+ defaults.suppressions = d.suppressions.map((s, i) => parseSuppression(s, `defaults.suppressions[${i}]`));
54
+ }
55
+ }
56
+ if (!Array.isArray(root.pages)) fail("pages", "must be an array");
57
+ if (root.pages.length === 0) fail("pages", "is empty — nothing would run");
58
+ const seen = /* @__PURE__ */ new Set();
59
+ const pages = root.pages.map((raw, i) => {
60
+ const at = `pages[${i}]`;
61
+ if (typeof raw !== "object" || raw === null) fail(at, "must be an object");
62
+ const p = raw;
63
+ if (typeof p.source !== "string" || !p.source.trim()) fail(at, "source is required (path, glob, or URL)");
64
+ const id = typeof p.id === "string" && p.id.trim() ? p.id.trim() : p.source.trim();
65
+ if (seen.has(id)) fail(at, `duplicate page id "${id}" — ids must be unique so --only is unambiguous`);
66
+ seen.add(id);
67
+ const page = {
68
+ id,
69
+ source: p.source.trim()
70
+ };
71
+ if (p.gates !== void 0) page.gates = parseGateList(p.gates, `${at}.gates`);
72
+ if (p.extraGates !== void 0) page.extraGates = parseGateList(p.extraGates, `${at}.extraGates`);
73
+ if (p.suppressions !== void 0) {
74
+ if (!Array.isArray(p.suppressions)) fail(`${at}.suppressions`, "must be an array");
75
+ page.suppressions = p.suppressions.map((s, j) => parseSuppression(s, `${at}.suppressions[${j}]`));
76
+ }
77
+ if (!page.gates && !page.extraGates && !defaults.gates) fail(at, `no gates: set ${at}.gates or defaults.gates`);
78
+ return page;
79
+ });
80
+ return {
81
+ ...Object.keys(defaults).length > 0 ? { defaults } : {},
82
+ pages
83
+ };
84
+ }
85
+ /** UTC midnight, so "expires today" behaves the same in every timezone. */
86
+ function utcDay(date) {
87
+ return Math.floor(date.getTime() / DAY_MS);
88
+ }
89
+ function resolveSuppression(s, scope, now) {
90
+ if (!s.expires) return {
91
+ ...s,
92
+ scope,
93
+ status: "permanent",
94
+ daysLeft: null
95
+ };
96
+ const daysLeft = utcDay(/* @__PURE__ */ new Date(`${s.expires}T00:00:00Z`)) - utcDay(now);
97
+ return {
98
+ ...s,
99
+ scope,
100
+ status: daysLeft < 0 ? "expired" : "active",
101
+ daysLeft
102
+ };
103
+ }
104
+ /**
105
+ * Turn the config into the exact list of gate invocations to run.
106
+ *
107
+ * Suppression flags are appended to matching gates only when active. An
108
+ * expired one is surfaced in `plan.expired` and deliberately left off the
109
+ * command line: the gate returns to failing, which is what an expiry date is
110
+ * supposed to mean.
111
+ */
112
+ function resolveGatePlan(config, options = {}) {
113
+ const now = options.now ?? /* @__PURE__ */ new Date();
114
+ const only = options.only?.filter((s) => s.trim()) ?? [];
115
+ const defaultGates = config.defaults?.gates ?? [];
116
+ const defaultSuppressions = (config.defaults?.suppressions ?? []).map((s) => resolveSuppression(s, "defaults", now));
117
+ const jobs = [];
118
+ const suppressions = [...defaultSuppressions];
119
+ for (const page of config.pages) {
120
+ const pageId = page.id ?? page.source;
121
+ const pageSuppressions = (page.suppressions ?? []).map((s) => resolveSuppression(s, pageId, now));
122
+ suppressions.push(...pageSuppressions);
123
+ if (only.length > 0 && !only.some((o) => pageId.includes(o) || page.source.includes(o))) continue;
124
+ const gates = [...page.gates ?? defaultGates, ...page.extraGates ?? []];
125
+ if (gates.length === 0) throw new Error(`Page "${pageId}" resolved to zero gates — set its \`gates\` or \`defaults.gates\`. A page that silently runs nothing is worse than a config error.`);
126
+ const candidates = [...defaultSuppressions, ...pageSuppressions];
127
+ for (const baseGate of gates) {
128
+ const applied = candidates.filter((s) => s.status !== "expired" && gateMatches(baseGate, s.gate));
129
+ jobs.push({
130
+ pageId,
131
+ source: page.source,
132
+ baseGate,
133
+ gate: [baseGate, ...applied.map((s) => s.flag)].join(" "),
134
+ appliedSuppressions: applied
135
+ });
136
+ }
137
+ }
138
+ return {
139
+ jobs,
140
+ suppressions,
141
+ expired: suppressions.filter((s) => s.status === "expired")
142
+ };
143
+ }
144
+ /**
145
+ * Token-wise prefix match: `check copy` matches `check copy --manifest x.txt`
146
+ * but not `check copyright`, and `check` matches every check gate.
147
+ */
148
+ function gateMatches(gate, pattern) {
149
+ const g = gate.split(/\s+/).filter(Boolean);
150
+ const p = pattern.split(/\s+/).filter(Boolean);
151
+ if (p.length > g.length) return false;
152
+ return p.every((token, i) => token === g[i]);
153
+ }
154
+ function summarizeSuppressions(suppressions, soonDays = 30) {
155
+ const rows = [...suppressions].sort((a, b) => {
156
+ const rank = (s) => s.status === "expired" ? 0 : s.status === "active" ? 1 : 2;
157
+ return rank(a) - rank(b) || (a.daysLeft ?? Infinity) - (b.daysLeft ?? Infinity);
158
+ });
159
+ return {
160
+ rows,
161
+ active: rows.filter((s) => s.status === "active").length,
162
+ expired: rows.filter((s) => s.status === "expired").length,
163
+ permanent: rows.filter((s) => s.status === "permanent").length,
164
+ unowned: rows.filter((s) => s.status !== "expired" && !s.owner).length,
165
+ expiringSoon: rows.filter((s) => s.status === "active" && (s.daysLeft ?? Infinity) <= soonDays).length
166
+ };
167
+ }
168
+ //#endregion
169
+ export { GATE_CONFIG_FILENAMES, gateMatches, parseGateConfig, resolveGatePlan, resolveSuppression, summarizeSuppressions };
@@ -0,0 +1,45 @@
1
+ //#region src/gate-exit.d.ts
2
+ /**
3
+ * One exit-code contract for every gate.
4
+ *
5
+ * Measured during the 2026-08-01 round-10 audit, the behaviour was
6
+ * incoherent: verdict gates (integrity DEFECTS, layout VIOLATED, flow
7
+ * FAILED, markup NOT DONE) exited non-zero on their own, `check
8
+ * interactions` and `scan handlers` also exited non-zero on a suspect, but
9
+ * `check copy`, `check asset` and `scan scroll` exited ZERO unless you
10
+ * remembered `--fail-on-suspect`. Two commands in the same `scan` group
11
+ * disagreed. Worse, the safe-looking default was the dangerous one: a
12
+ * pre-push or CI command that printed a defect and exited 0.
13
+ *
14
+ * The contract is now: **a suspect fails the command.** A verification tool
15
+ * whose default is "found a defect, exiting 0" is a footgun; the burden
16
+ * belongs on the person who wants to ignore findings, not on the person who
17
+ * wants them enforced.
18
+ *
19
+ * `--advisory` opts back into print-and-succeed for gates being piloted
20
+ * before they gate CI — which is the rollout order the docs recommend.
21
+ * `--fail-on-suspect` is kept as an accepted no-op so existing scripts and
22
+ * the published documentation keep working.
23
+ *
24
+ * Warns never affect the exit code, under any flag.
25
+ */
26
+ interface GateExitFlags {
27
+ /** Print findings and exit 0 even when suspects exist. */
28
+ advisory: boolean;
29
+ }
30
+ /** Parse the shared exit-code flags out of an argv array. */
31
+ declare function parseGateExitFlags(argv: readonly string[]): GateExitFlags;
32
+ /**
33
+ * Decide the process exit code. `hasSuspect` should count only
34
+ * defect-severity findings; warn-level findings must not reach it.
35
+ */
36
+ declare function gateExitCode(hasSuspect: boolean, flags: GateExitFlags): 0 | 1;
37
+ /** Shared help text so every gate documents the contract identically. */
38
+ declare const GATE_EXIT_HELP = " --advisory Print findings but exit 0 (default: a suspect exits 1)";
39
+ /**
40
+ * Apply the contract. Sets `process.exitCode` rather than calling
41
+ * `process.exit` so buffered stdout is not truncated.
42
+ */
43
+ declare function applyGateExit(hasSuspect: boolean, flags: GateExitFlags): void;
44
+ //#endregion
45
+ export { GATE_EXIT_HELP, GateExitFlags, applyGateExit, gateExitCode, parseGateExitFlags };
@@ -0,0 +1,25 @@
1
+ //#region src/gate-exit.ts
2
+ /** Parse the shared exit-code flags out of an argv array. */
3
+ function parseGateExitFlags(argv) {
4
+ return { advisory: argv.includes("--advisory") };
5
+ }
6
+ /**
7
+ * Decide the process exit code. `hasSuspect` should count only
8
+ * defect-severity findings; warn-level findings must not reach it.
9
+ */
10
+ function gateExitCode(hasSuspect, flags) {
11
+ if (!hasSuspect) return 0;
12
+ return flags.advisory ? 0 : 1;
13
+ }
14
+ /** Shared help text so every gate documents the contract identically. */
15
+ const GATE_EXIT_HELP = " --advisory Print findings but exit 0 (default: a suspect exits 1)";
16
+ /**
17
+ * Apply the contract. Sets `process.exitCode` rather than calling
18
+ * `process.exit` so buffered stdout is not truncated.
19
+ */
20
+ function applyGateExit(hasSuspect, flags) {
21
+ const code = gateExitCode(hasSuspect, flags);
22
+ if (code !== 0) process.exitCode = code;
23
+ }
24
+ //#endregion
25
+ export { GATE_EXIT_HELP, applyGateExit, gateExitCode, parseGateExitFlags };
@@ -0,0 +1,57 @@
1
+ //#region src/heatmap-regions.d.ts
2
+ interface HeatmapRegion {
3
+ top: number;
4
+ left: number;
5
+ width: number;
6
+ height: number;
7
+ /** Hot-pixel count inside the bbox. */
8
+ area: number;
9
+ /**
10
+ * Dominant color of the region as sampled from a *source* image
11
+ * (the baseline / target PNG that the heatmap was generated against).
12
+ * Only populated when `findHeatmapRegionsFromFile` was called with a
13
+ * `sourceImagePath`. Lets the agent close the loop between
14
+ * "this region differs" and "fill it with this color".
15
+ */
16
+ dominantColor?: {
17
+ r: number;
18
+ g: number;
19
+ b: number;
20
+ hex: string;
21
+ };
22
+ /**
23
+ * Content classification of the region inside the source image —
24
+ * `text` / `filled-rect` / `icon` / `image` / `unknown`. Helps the
25
+ * agent decide whether to paint a flat background, write a text
26
+ * run, or place an icon. Only populated when callers run an
27
+ * explicit annotation pass (see `annotateHeatmapRegionKinds` in
28
+ * `@mizchi/vlmkit-markup/heatmap-region-kinds.ts`); the bare
29
+ * `findHeatmapRegionsFromFile` no longer fills it in to keep
30
+ * vlmkit-core free of MoonBit policy.
31
+ */
32
+ kind?: "text" | "filled-rect" | "icon" | "image" | "unknown";
33
+ /** Classifier confidence ∈ [0, 1]. */
34
+ kindConfidence?: number;
35
+ }
36
+ interface FindHeatmapRegionsOptions {
37
+ /** Minimum hot-pixel count for a region to be kept. Default 80. */
38
+ minArea?: number;
39
+ /** Cap on returned regions, sorted by area desc. Default 8. */
40
+ topN?: number;
41
+ /** Hot-pixel threshold: red − max(green, blue) >= this. Default 60. */
42
+ redOverGreenBlue?: number;
43
+ /**
44
+ * Skip regions whose bbox covers ≥ this fraction of the image. When
45
+ * baseline and variant are almost entirely different (e.g. blank
46
+ * page vs full target), the CC pass produces one giant region
47
+ * spanning 0,0 → W,H. That region is uninformative ("the whole
48
+ * page differs" is already obvious from diff %) and wastes
49
+ * iteration. Default 0.8 — drop regions covering ≥80% of the image.
50
+ * From subagent dogfood eval.
51
+ */
52
+ maxRegionFraction?: number;
53
+ }
54
+ declare function findHeatmapRegionsFromRgba(data: Uint8Array, width: number, height: number, options?: FindHeatmapRegionsOptions): HeatmapRegion[];
55
+ declare function findHeatmapRegionsFromFile(path: string, options?: FindHeatmapRegionsOptions, sourceImagePath?: string): Promise<HeatmapRegion[]>;
56
+ //#endregion
57
+ export { FindHeatmapRegionsOptions, HeatmapRegion, findHeatmapRegionsFromFile, findHeatmapRegionsFromRgba };
@@ -0,0 +1,158 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { PNG } from "pngjs";
3
+ //#region src/heatmap-regions.ts
4
+ /**
5
+ * Heatmap region clustering.
6
+ *
7
+ * `detectBandShifts` (see `heatmap.ts`) reports per-band Y-shifts —
8
+ * useful for global translations but loses horizontal localization.
9
+ * Subagent F wished for "heatmap region clustering": group connected
10
+ * hot pixels in `*_heatmap.png` into clusters with rectangular
11
+ * bounding boxes, so "a text run at y=420 shifted up 4px" becomes
12
+ * one row instead of being smeared across a tall band.
13
+ *
14
+ * Reuses the connected-component algorithm from `component-bbox.ts`
15
+ * — the input is just a different mask (foreground = "hot pixel").
16
+ *
17
+ * Pixelmatch heatmaps use a fixed palette: bright red for "diff
18
+ * pixel", original (resized) baseline tinted for context. We treat
19
+ * any pixel whose red channel is strongly elevated relative to the
20
+ * other two channels as a hot pixel.
21
+ */
22
+ const DEFAULT_MIN_AREA = 80;
23
+ const DEFAULT_TOP_N = 8;
24
+ const DEFAULT_RED_OVER = 60;
25
+ const DEFAULT_MAX_REGION_FRACTION = .8;
26
+ function buildHotMask(data, width, height, redOver) {
27
+ const mask = new Uint8Array(width * height);
28
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
29
+ const idx = (y * width + x) * 4;
30
+ const r = data[idx], g = data[idx + 1], b = data[idx + 2];
31
+ if (r - Math.max(g, b) >= redOver) mask[y * width + x] = 1;
32
+ }
33
+ return mask;
34
+ }
35
+ function labelComponents(mask, width, height) {
36
+ const labels = new Int32Array(width * height);
37
+ const parent = [0];
38
+ const find = (x) => {
39
+ while (parent[x] !== x) {
40
+ parent[x] = parent[parent[x]];
41
+ x = parent[x];
42
+ }
43
+ return x;
44
+ };
45
+ const union = (a, b) => {
46
+ const ra = find(a), rb = find(b);
47
+ if (ra !== rb) parent[Math.max(ra, rb)] = Math.min(ra, rb);
48
+ };
49
+ let next = 1;
50
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
51
+ const idx = y * width + x;
52
+ if (!mask[idx]) continue;
53
+ const up = y > 0 ? labels[idx - width] : 0;
54
+ const left = x > 0 ? labels[idx - 1] : 0;
55
+ if (up && left) {
56
+ labels[idx] = Math.min(up, left);
57
+ if (up !== left) union(up, left);
58
+ } else if (up) labels[idx] = up;
59
+ else if (left) labels[idx] = left;
60
+ else {
61
+ labels[idx] = next;
62
+ parent[next] = next;
63
+ next++;
64
+ }
65
+ }
66
+ const byRoot = /* @__PURE__ */ new Map();
67
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
68
+ const l = labels[y * width + x];
69
+ if (!l) continue;
70
+ const root = find(l);
71
+ let s = byRoot.get(root);
72
+ if (!s) {
73
+ s = {
74
+ minX: x,
75
+ minY: y,
76
+ maxX: x,
77
+ maxY: y,
78
+ area: 0
79
+ };
80
+ byRoot.set(root, s);
81
+ }
82
+ if (x < s.minX) s.minX = x;
83
+ if (x > s.maxX) s.maxX = x;
84
+ if (y < s.minY) s.minY = y;
85
+ if (y > s.maxY) s.maxY = y;
86
+ s.area++;
87
+ }
88
+ const out = [];
89
+ for (const s of byRoot.values()) out.push({
90
+ top: s.minY,
91
+ left: s.minX,
92
+ width: s.maxX - s.minX + 1,
93
+ height: s.maxY - s.minY + 1,
94
+ area: s.area
95
+ });
96
+ return out;
97
+ }
98
+ function findHeatmapRegionsFromRgba(data, width, height, options = {}) {
99
+ const minArea = options.minArea ?? DEFAULT_MIN_AREA;
100
+ const topN = options.topN ?? DEFAULT_TOP_N;
101
+ const redOver = options.redOverGreenBlue ?? DEFAULT_RED_OVER;
102
+ const maxFraction = options.maxRegionFraction ?? DEFAULT_MAX_REGION_FRACTION;
103
+ if (width <= 0 || height <= 0) return [];
104
+ const mask = buildHotMask(data, width, height, redOver);
105
+ const imageArea = width * height;
106
+ return labelComponents(mask, width, height).filter((r) => r.area >= minArea).filter((r) => r.width * r.height / imageArea < maxFraction).sort((a, b) => b.area - a.area).slice(0, topN);
107
+ }
108
+ function toHex(r, g, b) {
109
+ const c = (n) => n.toString(16).padStart(2, "0");
110
+ return `#${c(r)}${c(g)}${c(b)}`;
111
+ }
112
+ /** Sample the dominant color inside `region` from the source image data. */
113
+ function sampleRegionColor(sourceData, sourceWidth, sourceHeight, region) {
114
+ const inset = 2;
115
+ const x0 = Math.max(0, region.left + inset);
116
+ const x1 = Math.min(sourceWidth, region.left + region.width - inset);
117
+ const y0 = Math.max(0, region.top + inset);
118
+ const y1 = Math.min(sourceHeight, region.top + region.height - inset);
119
+ if (x1 <= x0 || y1 <= y0) return void 0;
120
+ const stepX = Math.max(1, Math.floor((x1 - x0) / 5));
121
+ const stepY = Math.max(1, Math.floor((y1 - y0) / 5));
122
+ const rs = [], gs = [], bs = [];
123
+ for (let y = y0; y < y1; y += stepY) for (let x = x0; x < x1; x += stepX) {
124
+ const i = (y * sourceWidth + x) * 4;
125
+ if (sourceData[i + 3] === 0) continue;
126
+ rs.push(sourceData[i]);
127
+ gs.push(sourceData[i + 1]);
128
+ bs.push(sourceData[i + 2]);
129
+ }
130
+ if (rs.length === 0) return void 0;
131
+ rs.sort((a, b) => a - b);
132
+ gs.sort((a, b) => a - b);
133
+ bs.sort((a, b) => a - b);
134
+ const mid = rs.length >> 1;
135
+ const r = rs[mid], g = gs[mid], b = bs[mid];
136
+ return {
137
+ r,
138
+ g,
139
+ b,
140
+ hex: toHex(r, g, b)
141
+ };
142
+ }
143
+ async function findHeatmapRegionsFromFile(path, options = {}, sourceImagePath) {
144
+ const buf = await readFile(path);
145
+ const png = PNG.sync.read(buf);
146
+ const regions = findHeatmapRegionsFromRgba(png.data, png.width, png.height, options);
147
+ if (sourceImagePath) try {
148
+ const sourceBuf = await readFile(sourceImagePath);
149
+ const sourcePng = PNG.sync.read(sourceBuf);
150
+ for (const region of regions) {
151
+ const color = sampleRegionColor(sourcePng.data, sourcePng.width, sourcePng.height, region);
152
+ if (color) region.dominantColor = color;
153
+ }
154
+ } catch {}
155
+ return regions;
156
+ }
157
+ //#endregion
158
+ export { findHeatmapRegionsFromFile, findHeatmapRegionsFromRgba };
@@ -0,0 +1,86 @@
1
+ import { DiffRegionColorSample, DiffReport, ShiftRegion, VrtDiff, VrtSnapshot } from "./types.mjs";
2
+ import { PngData } from "./png-utils.mjs";
3
+
4
+ //#region src/heatmap.d.ts
5
+ /**
6
+ * Compare two screenshots pixel-by-pixel and generate a diff heatmap.
7
+ */
8
+ declare function compareScreenshots(snapshot: VrtSnapshot, opts?: {
9
+ threshold?: number;
10
+ outputDir?: string;
11
+ skipHeatmap?: boolean;
12
+ }): Promise<VrtDiff | null>;
13
+ /**
14
+ * Sample a region's color pair from the pixels that actually differ.
15
+ *
16
+ * A region-wide median (the old behaviour) reflects the unchanged majority
17
+ * and reads as "no change" on exactly the regions that changed in a minority
18
+ * of their pixels — e.g. a dark background recolor hidden behind dominant
19
+ * white form inputs (A/B v3 draft 10). We accumulate only pixels whose
20
+ * baseline↔current per-channel delta clears CHANGED_PIXEL_DELTA, falling back
21
+ * to every opaque pixel when nothing clears the gate.
22
+ *
23
+ * When the changed pixels are sparse, the mean is still dominated by
24
+ * antialiasing blends, so we additionally surface the single highest-delta
25
+ * pixel pair as `peak` (draft 11).
26
+ */
27
+ declare function sampleRegionColorSample(baseline: PngData, current: PngData, region: {
28
+ x: number;
29
+ y: number;
30
+ width: number;
31
+ height: number;
32
+ }): DiffRegionColorSample | undefined;
33
+ /**
34
+ * Per-band shift detection — split the image into horizontal bands and run
35
+ * the same cross-correlation per band. Lets us report "section A shifted
36
+ * +8px, section B shifted +20px" instead of a single global average that
37
+ * loses localization.
38
+ *
39
+ * Bands with low luminance variance (e.g. a flat white footer) are dropped
40
+ * because cross-correlation can't lock onto them and the result is noise.
41
+ *
42
+ * Exported for unit testing.
43
+ */
44
+ declare function detectBandShifts(baseline: {
45
+ data: Uint8Array;
46
+ width: number;
47
+ height: number;
48
+ }, current: {
49
+ data: Uint8Array;
50
+ width: number;
51
+ height: number;
52
+ }, options?: {
53
+ bandHeight?: number;
54
+ minConfidence?: number;
55
+ maxShift?: number;
56
+ }): ShiftRegion[];
57
+ /**
58
+ * Generate a comprehensive diff report including clustering, shift detection,
59
+ * and region classification. Compatible with mizchi/pixelmatch 0.5.0 DiffReport format.
60
+ */
61
+ declare function generateDiffReport(snapshot: VrtSnapshot, opts?: {
62
+ threshold?: number;
63
+ outputDir?: string;
64
+ skipHeatmap?: boolean;
65
+ detectShift?: boolean;
66
+ }): Promise<DiffReport | null>;
67
+ /**
68
+ * Whiteout detection: checks if most of the image is white (or a single color).
69
+ */
70
+ declare function detectWhiteout(data: PngData, opts?: {
71
+ threshold?: number;
72
+ }): {
73
+ isWhiteout: boolean;
74
+ whiteRatio: number;
75
+ };
76
+ /**
77
+ * Empty content detection: checks if the image has low entropy.
78
+ */
79
+ declare function detectEmptyContent(data: PngData, opts?: {
80
+ threshold?: number;
81
+ }): {
82
+ isEmpty: boolean;
83
+ uniqueColors: number;
84
+ };
85
+ //#endregion
86
+ export { compareScreenshots, detectBandShifts, detectEmptyContent, detectWhiteout, generateDiffReport, sampleRegionColorSample };