@mizchi/vlmkit-core 0.6.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.
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Region content-type classifier.
3
+ *
4
+ * Given a rectangular region of an image (e.g. a heatmap cluster or
5
+ * a component bbox), classify what it most likely represents:
6
+ * - `text` — horizontal text rows (high horizontal entropy,
7
+ * consistent row stripe pattern)
8
+ * - `filled-rect` — solid color block (button, badge, banner)
9
+ * - `icon` — small compact graphic (2-4 colors, square-ish)
10
+ * - `image` — high color variance, no stripe pattern
11
+ * - `unknown` — region too small or empty
12
+ *
13
+ * Pure pixel heuristic — no DOM access. Closes the "is this region
14
+ * text or a filled rectangle?" question called out by subagent G v2
15
+ * dogfood: "the heatmap gives (x, y, W×H) but no clue what the
16
+ * region is."
17
+ */
18
+ export type RegionKind = "text" | "filled-rect" | "icon" | "image" | "unknown";
19
+
20
+ export interface RegionClassification {
21
+ kind: RegionKind;
22
+ /** Confidence ∈ [0, 1]. */
23
+ confidence: number;
24
+ /** Diagnostics used to make the decision. */
25
+ features: {
26
+ colorCount: number;
27
+ /** Standard deviation of luminance across the region. Low = uniform fill. */
28
+ lumaStd: number;
29
+ /** Number of distinct horizontal "stripes" — dark-row clusters. */
30
+ stripeRows: number;
31
+ /** Aspect ratio width/height. */
32
+ aspect: number;
33
+ /** Width × height. */
34
+ area: number;
35
+ };
36
+ }
37
+
38
+ export interface ClassifyOptions {
39
+ /** Quantization bits per channel for color counting. Default 4. */
40
+ bitsPerChannel?: number;
41
+ /** Stride for stripe-row scanning. Default 1. */
42
+ stripeStride?: number;
43
+ }
44
+
45
+ /**
46
+ * Classify a region of an RGBA image. The region is given by
47
+ * `top, left, width, height` (clamped to image bounds).
48
+ */
49
+ export function classifyRegion(
50
+ data: Uint8Array,
51
+ imageWidth: number,
52
+ imageHeight: number,
53
+ region: { top: number; left: number; width: number; height: number },
54
+ options: ClassifyOptions = {},
55
+ ): RegionClassification {
56
+ const bits = options.bitsPerChannel ?? 4;
57
+ const stripeStride = options.stripeStride ?? 1;
58
+ const shift = 8 - bits;
59
+ const bucketCount = 1 << bits;
60
+
61
+ const x0 = Math.max(0, region.left);
62
+ const y0 = Math.max(0, region.top);
63
+ const x1 = Math.min(imageWidth, region.left + region.width);
64
+ const y1 = Math.min(imageHeight, region.top + region.height);
65
+ const W = x1 - x0;
66
+ const H = y1 - y0;
67
+ if (W <= 1 || H <= 1) {
68
+ return {
69
+ kind: "unknown",
70
+ confidence: 1,
71
+ features: { colorCount: 0, lumaStd: 0, stripeRows: 0, aspect: 0, area: 0 },
72
+ };
73
+ }
74
+
75
+ // Single-pass aggregation:
76
+ // - color histogram (quantized) for colorCount
77
+ // - per-pixel luma → row-mean & total mean/std
78
+ // - per-row luma → stripe detection
79
+ const histogram = new Set<number>();
80
+ const rowMeanLuma = new Float32Array(H);
81
+ let totalSum = 0, totalSumSq = 0;
82
+ let n = 0;
83
+ for (let yy = 0; yy < H; yy++) {
84
+ const y = y0 + yy;
85
+ let rowSum = 0;
86
+ for (let xx = 0; xx < W; xx++) {
87
+ const x = x0 + xx;
88
+ const i = (y * imageWidth + x) * 4;
89
+ if (data[i + 3]! === 0) continue;
90
+ const r = data[i]!, g = data[i + 1]!, b = data[i + 2]!;
91
+ const key = ((r >> shift) << (2 * bits)) | ((g >> shift) << bits) | (b >> shift);
92
+ histogram.add(key);
93
+ const L = 0.299 * r + 0.587 * g + 0.114 * b;
94
+ rowSum += L;
95
+ totalSum += L;
96
+ totalSumSq += L * L;
97
+ n++;
98
+ }
99
+ rowMeanLuma[yy] = W > 0 ? rowSum / W : 0;
100
+ }
101
+
102
+ if (n === 0) {
103
+ return {
104
+ kind: "unknown",
105
+ confidence: 1,
106
+ features: { colorCount: 0, lumaStd: 0, stripeRows: 0, aspect: W / H, area: W * H },
107
+ };
108
+ }
109
+
110
+ const colorCount = histogram.size;
111
+ const mean = totalSum / n;
112
+ const variance = totalSumSq / n - mean * mean;
113
+ const lumaStd = Math.sqrt(Math.max(0, variance));
114
+
115
+ // Stripe detection: count alternating dark/light row transitions.
116
+ // A row is "dark" if rowMeanLuma is meaningfully below the region's
117
+ // mean luma. Multiple distinct dark stripes → likely text.
118
+ const stripeDip = 12;
119
+ let stripeRows = 0;
120
+ let inDarkRun = false;
121
+ for (let yy = 0; yy < H; yy += stripeStride) {
122
+ const isDark = mean - rowMeanLuma[yy]! >= stripeDip;
123
+ if (isDark && !inDarkRun) {
124
+ stripeRows++;
125
+ inDarkRun = true;
126
+ } else if (!isDark && inDarkRun) {
127
+ inDarkRun = false;
128
+ }
129
+ }
130
+
131
+ const aspect = W / H;
132
+ const area = W * H;
133
+
134
+ // Heuristic classification:
135
+ // text — multiple stripes (≥ 2 alternating dark-row runs)
136
+ // AND aspect ratio not tiny (text bands tend to be
137
+ // wider than tall, but a single short word can be
138
+ // ~square)
139
+ // filled-rect — colorCount ≤ 4 AND lumaStd < 20 (essentially
140
+ // uniform fill)
141
+ // icon — small region (area < 4000), colorCount ≤ 16,
142
+ // aspect 0.5-2 (square-ish)
143
+ // image — colorCount > 16 AND not striped → textured
144
+ // unknown — none of the above hold confidently
145
+ let kind: RegionKind = "unknown";
146
+ let confidence = 0.5;
147
+ // Thresholds tuned against real anti-aliased rendering — a "uniform"
148
+ // button has ~30-80 quantized colors from AA on text + corners, not
149
+ // the ~4 a naive view would suggest. Buckets calibrated against
150
+ // system-ui at 14-40 px on light bg.
151
+
152
+ // Tiny region — likely icon or single character.
153
+ if (area < 2000 && aspect > 0.4 && aspect < 2.5) {
154
+ kind = "icon";
155
+ confidence = 0.65;
156
+ }
157
+ // Multiple distinct dark stripes → text.
158
+ else if (stripeRows >= 2) {
159
+ kind = "text";
160
+ confidence = Math.min(1, 0.55 + stripeRows * 0.08);
161
+ }
162
+ // Truly uniform fill (single color block, no text overlay).
163
+ else if (colorCount <= 8 && lumaStd < 12) {
164
+ kind = "filled-rect";
165
+ confidence = 0.9;
166
+ }
167
+ // Button-/badge-like: bounded color count, narrow luma std (AA on
168
+ // text inside a solid fill is the main source of variation).
169
+ else if (colorCount <= 120 && lumaStd < 45) {
170
+ kind = "filled-rect";
171
+ confidence = 0.65;
172
+ }
173
+ // Single-stripe text band — common short labels / single-line text.
174
+ else if (stripeRows === 1) {
175
+ kind = "text";
176
+ confidence = 0.55;
177
+ }
178
+ // Many colors + no stripe structure → textured / image content.
179
+ else if (colorCount > 200) {
180
+ kind = "image";
181
+ confidence = 0.6;
182
+ }
183
+
184
+ return {
185
+ kind,
186
+ confidence,
187
+ features: { colorCount, lumaStd: Number(lumaStd.toFixed(1)), stripeRows, aspect: Number(aspect.toFixed(2)), area },
188
+ };
189
+ }
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Vertical-shift origin diagnostic.
3
+ *
4
+ * Closes the residual gap from `docs/reports/2026-05-12-subagent-eval.md`:
5
+ * after per-viewport DOM-position diff lands, layout-shift bands can
6
+ * still appear with no DOM-position delta attributing them. Subagent D
7
+ * plateaued at 4 viewports × ~3% diff because of one such band
8
+ * (`[0..1047]: +152px`) at viewports ≥ 1024.
9
+ *
10
+ * This module captures per-element bounding boxes on each page and,
11
+ * given the existing per-band shift report, names the *first* element
12
+ * whose y-coordinate diverges between baseline and variant. The agent
13
+ * gets a "shift origin" pointer instead of just "everything below row
14
+ * N moved +152px."
15
+ *
16
+ * Pure module. Browser-side capture script is a string for
17
+ * `page.evaluate()`; matching algorithm runs in Node.
18
+ */
19
+
20
+ import type { ShiftRegion } from "./types.ts";
21
+
22
+ export interface BboxElement {
23
+ /** DOM path: `tag[childIndex]>...` rooted at body (same scheme as dom-position-styles). */
24
+ path: string;
25
+ tag: string;
26
+ classes: string;
27
+ top: number;
28
+ left: number;
29
+ width: number;
30
+ height: number;
31
+ }
32
+
33
+ export interface ShiftOrigin {
34
+ /** Band y-range this origin explains. */
35
+ bandStart: number;
36
+ bandEnd: number;
37
+ bandShift: number;
38
+ originPath: string;
39
+ originTag: string;
40
+ originBaselineTop: number;
41
+ originVariantTop: number;
42
+ originDeltaY: number;
43
+ originBaselineClasses: string;
44
+ originVariantClasses: string;
45
+ /** Heuristic guess at the responsible CSS axis based on bbox deltas. */
46
+ suspectedAxis?: "height" | "margin/padding-above" | "y-position" | "unknown";
47
+ }
48
+
49
+ export interface FindShiftOriginsOptions {
50
+ /**
51
+ * Δy magnitude (px) above which an element is considered "shifted." Defaults
52
+ * to 5 — below this is usually subpixel rounding from font metrics.
53
+ */
54
+ minDeltaPx?: number;
55
+ /**
56
+ * Number of candidate origin elements to emit per band (most useful is the
57
+ * first; subsequent ones can be downstream propagation, but giving the
58
+ * agent 2–3 helps when the first guess is wrong).
59
+ */
60
+ perBandLimit?: number;
61
+ }
62
+
63
+ const DEFAULT_MIN_DELTA = 5;
64
+ const DEFAULT_PER_BAND_LIMIT = 3;
65
+
66
+ function classifySuspect(
67
+ baseline: BboxElement,
68
+ variant: BboxElement,
69
+ ): ShiftOrigin["suspectedAxis"] {
70
+ // Element itself has different height → its `height`/`padding`/`line-height` is the cause.
71
+ const heightDelta = Math.abs(baseline.height - variant.height);
72
+ // Element's top moved but its left didn't → vertical-axis cause.
73
+ const topDelta = Math.abs(baseline.top - variant.top);
74
+ if (heightDelta >= 5) return "height";
75
+ if (topDelta >= 5) return "margin/padding-above";
76
+ return "y-position";
77
+ }
78
+
79
+ /**
80
+ * For each shift band, walk baseline elements in document order (sorted by
81
+ * baseline.top) and find the first one whose matching-by-path variant
82
+ * counterpart has a Δy comparable to the band's shift magnitude.
83
+ *
84
+ * The "first such element" is the most actionable origin — everything below
85
+ * it just inherits the shift. We emit up to `perBandLimit` candidates so
86
+ * the agent gets fallback options.
87
+ */
88
+ export function findShiftOrigins(
89
+ baseline: BboxElement[],
90
+ variant: BboxElement[],
91
+ shiftRegions: ShiftRegion[],
92
+ options: FindShiftOriginsOptions = {},
93
+ ): ShiftOrigin[] {
94
+ const minDelta = options.minDeltaPx ?? DEFAULT_MIN_DELTA;
95
+ const perBandLimit = options.perBandLimit ?? DEFAULT_PER_BAND_LIMIT;
96
+ if (baseline.length === 0 || variant.length === 0 || shiftRegions.length === 0) return [];
97
+
98
+ const variantByPath = new Map<string, BboxElement>();
99
+ for (const v of variant) variantByPath.set(v.path, v);
100
+
101
+ const sorted = [...baseline].sort((a, b) => a.top - b.top || a.left - b.left);
102
+ const origins: ShiftOrigin[] = [];
103
+
104
+ for (const band of shiftRegions) {
105
+ const bandShift = band.shift;
106
+ if (Math.abs(bandShift) < minDelta) continue;
107
+
108
+ // Look at elements whose baseline.top is at or just above the band's
109
+ // start — typical origin is the element just before the visible shift
110
+ // boundary (extra height/padding pushes everything below).
111
+ const candidates: ShiftOrigin[] = [];
112
+ for (const b of sorted) {
113
+ // Skip elements far above the band (they wouldn't be the local cause).
114
+ if (b.top < band.yStart - 200) continue;
115
+ // Stop scanning well past the band end — origin is always at or above.
116
+ if (b.top > band.yEnd) break;
117
+
118
+ const v = variantByPath.get(b.path);
119
+ if (!v) continue;
120
+ const deltaY = v.top - b.top;
121
+ if (Math.abs(deltaY) < minDelta) continue;
122
+ // Note: do NOT require Math.sign(deltaY) === Math.sign(bandShift).
123
+ // The pixelmatch-derived band shift uses cross-correlation which can
124
+ // report a sign opposite to the bbox Δy when the variant has *less*
125
+ // content than the baseline (or vice versa). We still want to flag
126
+ // the element so the agent can interpret the direction itself.
127
+
128
+ candidates.push({
129
+ bandStart: band.yStart,
130
+ bandEnd: band.yEnd,
131
+ bandShift,
132
+ originPath: b.path,
133
+ originTag: b.tag,
134
+ originBaselineTop: b.top,
135
+ originVariantTop: v.top,
136
+ originDeltaY: deltaY,
137
+ originBaselineClasses: b.classes,
138
+ originVariantClasses: v.classes,
139
+ suspectedAxis: classifySuspect(b, v),
140
+ });
141
+ }
142
+
143
+ // Rank: closer to |bandShift| first (best explanatory match), then
144
+ // smallest baseline.top (earliest divergence wins ties).
145
+ candidates.sort((a, b) =>
146
+ Math.abs(Math.abs(a.originDeltaY) - Math.abs(bandShift)) -
147
+ Math.abs(Math.abs(b.originDeltaY) - Math.abs(bandShift))
148
+ || a.originBaselineTop - b.originBaselineTop,
149
+ );
150
+ origins.push(...candidates.slice(0, perBandLimit));
151
+ }
152
+
153
+ return origins;
154
+ }
155
+
156
+ /**
157
+ * Browser-side capture: same path scheme as
158
+ * `dom-position-styles.DOM_POSITION_STYLES_BROWSER_SCRIPT`, returns bbox
159
+ * (top/left/width/height in document-coords) instead of computed styles.
160
+ */
161
+ export const DOM_BBOX_BROWSER_SCRIPT = `JSON.stringify((function(){
162
+ var SEMANTIC = new Set([
163
+ "main","header","nav","footer","aside","article","section",
164
+ "h1","h2","h3","h4","h5","h6","p","a","button","input","select","textarea",
165
+ "label","blockquote","pre","code","table","thead","tbody","tr","th","td",
166
+ "ul","ol","li","img","span"
167
+ ]);
168
+ var out = [];
169
+ function walk(el, parentPath, indexAmongChildren) {
170
+ var tag = el.tagName.toLowerCase();
171
+ var path = parentPath === "" ? tag + "[0]" : parentPath + ">" + tag + "[" + indexAmongChildren + "]";
172
+ var hasClass = el.hasAttribute && el.hasAttribute("class");
173
+ var interesting = hasClass || SEMANTIC.has(tag);
174
+ if (interesting) {
175
+ var r = el.getBoundingClientRect();
176
+ out.push({
177
+ path: path,
178
+ tag: tag,
179
+ classes: (el.getAttribute("class") || "").trim(),
180
+ top: r.top + window.scrollY,
181
+ left: r.left + window.scrollX,
182
+ width: r.width,
183
+ height: r.height
184
+ });
185
+ }
186
+ var children = el.children;
187
+ for (var j = 0; j < children.length; j++) {
188
+ walk(children[j], path, j);
189
+ }
190
+ }
191
+ if (document.body) walk(document.body, "", 0);
192
+ return out;
193
+ })())`;
194
+
195
+ export function parseBboxes(value: unknown): BboxElement[] {
196
+ if (Array.isArray(value)) return value as BboxElement[];
197
+ if (typeof value !== "string") return [];
198
+ try {
199
+ const parsed = JSON.parse(value);
200
+ return Array.isArray(parsed) ? parsed as BboxElement[] : [];
201
+ } catch {
202
+ return [];
203
+ }
204
+ }
@@ -0,0 +1,13 @@
1
+ /** Shared ANSI terminal color codes and helpers */
2
+
3
+ export const DIM = "\x1b[2m";
4
+ export const RESET = "\x1b[0m";
5
+ export const GREEN = "\x1b[32m";
6
+ export const RED = "\x1b[31m";
7
+ export const YELLOW = "\x1b[33m";
8
+ export const CYAN = "\x1b[36m";
9
+ export const BOLD = "\x1b[1m";
10
+
11
+ export function hr(width = 72) {
12
+ console.log(`${DIM}${"─".repeat(width)}${RESET}`);
13
+ }