@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.
package/src/types.ts ADDED
@@ -0,0 +1,468 @@
1
+ // ---- Playwright Report Types (subset of JSON reporter output) ----
2
+
3
+ export interface PlaywrightReport {
4
+ config: { rootDir: string; projects: ProjectConfig[] };
5
+ suites: TestSuite[];
6
+ }
7
+
8
+ export interface ProjectConfig {
9
+ name: string;
10
+ use: Record<string, unknown>;
11
+ }
12
+
13
+ export interface TestSuite {
14
+ title: string;
15
+ file: string;
16
+ suites?: TestSuite[];
17
+ specs: TestSpec[];
18
+ }
19
+
20
+ export interface TestSpec {
21
+ title: string;
22
+ ok: boolean;
23
+ tests: TestResult[];
24
+ }
25
+
26
+ export interface TestResult {
27
+ projectName: string;
28
+ status: "expected" | "unexpected" | "flaky" | "skipped";
29
+ duration: number;
30
+ results: TestAttempt[];
31
+ }
32
+
33
+ export interface TestAttempt {
34
+ status: "passed" | "failed" | "timedOut" | "skipped";
35
+ duration: number;
36
+ attachments: Attachment[];
37
+ errors: TestError[];
38
+ }
39
+
40
+ export interface Attachment {
41
+ name: string;
42
+ contentType: string;
43
+ path?: string;
44
+ body?: string;
45
+ }
46
+
47
+ export interface TestError {
48
+ message: string;
49
+ stack?: string;
50
+ }
51
+
52
+ // ---- Structured VRT Data ----
53
+
54
+ export interface VrtSnapshot {
55
+ testId: string;
56
+ testTitle: string;
57
+ projectName: string;
58
+ screenshotPath: string;
59
+ baselinePath?: string;
60
+ status: "new" | "unchanged" | "changed" | "missing";
61
+ }
62
+
63
+ export interface VrtDiff {
64
+ snapshot: VrtSnapshot;
65
+ diffPixels: number;
66
+ totalPixels: number;
67
+ diffRatio: number;
68
+ heatmapPath?: string;
69
+ regions: DiffRegion[];
70
+ }
71
+
72
+ export type DiffRegionType = "shift" | "content" | "edge";
73
+
74
+ export interface DiffRegion {
75
+ x: number;
76
+ y: number;
77
+ width: number;
78
+ height: number;
79
+ diffPixelCount: number;
80
+ regionType?: DiffRegionType;
81
+ }
82
+
83
+ export interface ShiftRegion {
84
+ yStart: number;
85
+ yEnd: number;
86
+ shift: number;
87
+ /** Correlation strength of the chosen offset (0..1). Higher = more confident. */
88
+ confidence?: number;
89
+ }
90
+
91
+ export interface DiffReport {
92
+ diffPixels: number;
93
+ totalPixels: number;
94
+ diffRatio: number;
95
+ regions: DiffRegion[];
96
+ shiftOnly: boolean;
97
+ contentChangeCount: number;
98
+ globalShift: number;
99
+ shiftRegions: ShiftRegion[];
100
+ compensatedDiffCount: number;
101
+ compact: string;
102
+ }
103
+
104
+ // ---- Dependency Graph ----
105
+
106
+ export type Language = "typescript" | "moonbit" | "rust";
107
+
108
+ export interface DepNode {
109
+ id: string;
110
+ filePath: string;
111
+ language: Language;
112
+ exports: string[];
113
+ isComponent: boolean;
114
+ }
115
+
116
+ export interface DepEdge {
117
+ from: string; // importer
118
+ to: string; // imported
119
+ specifiers: string[];
120
+ }
121
+
122
+ export interface DepGraph {
123
+ nodes: Map<string, DepNode>;
124
+ edges: DepEdge[];
125
+ }
126
+
127
+ export interface AffectedComponent {
128
+ node: DepNode;
129
+ depth: number; // distance from changed file
130
+ changedDependencies: string[];
131
+ }
132
+
133
+ // ---- Intent / Semantics ----
134
+
135
+ export interface ChangeIntent {
136
+ summary: string;
137
+ expectedVisualChanges: VisualExpectation[];
138
+ expectedA11yChanges: A11yExpectation[];
139
+ affectedComponents: string[];
140
+ changeType: "feature" | "bugfix" | "refactor" | "style" | "deps" | "a11y" | "unknown";
141
+ }
142
+
143
+ export interface VisualExpectation {
144
+ component: string;
145
+ description: string;
146
+ confidence: number; // 0-1
147
+ }
148
+
149
+ export interface A11yExpectation {
150
+ testId: string;
151
+ expectedChanges: ExpectedA11yChange[];
152
+ }
153
+
154
+ export interface ExpectedA11yChange {
155
+ /** NL description (primary). Works standalone */
156
+ description: string;
157
+ /** Structured hint (optional). Used for heuristic matching */
158
+ type?: A11yChangeType;
159
+ path?: string;
160
+ role?: string;
161
+ name?: string;
162
+ }
163
+
164
+ // ---- Expectation Manifest (test-first) ----
165
+ //
166
+ // Design: description is primary, structured fields are hints
167
+ // - Minimal form: { description, pages: [{ testId, expect }] }
168
+ // - Structured fields are optional for improved accuracy
169
+
170
+ export interface VrtExpectation {
171
+ /** NL description of the change intent (primary) */
172
+ description: string;
173
+ /** Structured intent (optional). Inferred from description if omitted */
174
+ intent?: Partial<ChangeIntent>;
175
+ pages: PageExpectation[];
176
+ }
177
+
178
+ export interface PageExpectation {
179
+ testId: string;
180
+ /** Expected state in NL (alternative to structured fields) */
181
+ expect?: string;
182
+ /** Structured hint (optional) */
183
+ visual?: "no-change" | "changed" | "any";
184
+ a11y?: "no-change" | "changed" | "regression-expected" | "any";
185
+ expectedA11yChanges?: ExpectedA11yChange[];
186
+ expectedVisualChanges?: VisualExpectation[];
187
+ }
188
+
189
+ // ---- Long-cycle Spec (invariants) ----
190
+ //
191
+ // short-cycle: expectation.json -- per-commit, what changes in this commit
192
+ // long-cycle: spec.json -- invariants across multiple commits
193
+ //
194
+ // spec declares "what must always hold".
195
+ // expectation can temporarily override it (regression-expected).
196
+
197
+ export interface UiSpec {
198
+ /** Description of this spec */
199
+ description: string;
200
+ /** Per-page invariants */
201
+ pages: PageSpec[];
202
+ /** Global invariants (applied to all pages) */
203
+ global?: SpecInvariant[];
204
+ }
205
+
206
+ export interface PageSpec {
207
+ testId: string;
208
+ /** Purpose of this page */
209
+ purpose?: string;
210
+ /** Invariant list */
211
+ invariants: SpecInvariant[];
212
+ }
213
+
214
+ export interface SpecInvariant {
215
+ /** NL description of the invariant (primary) */
216
+ description: string;
217
+ /** Structured hint (optional) */
218
+ check?: SpecCheckType;
219
+ /** NL assertion (future). Can be skipped via dep graph */
220
+ assert?: string;
221
+ /** Dependencies needed to verify this invariant (for dep graph skip decisions) */
222
+ dependsOn?: string[];
223
+ /** Verification cost. "low" = heuristics, "high" = LLM/Vision */
224
+ cost?: "low" | "high";
225
+ }
226
+
227
+ export type SpecCheckType =
228
+ | "landmark-exists"
229
+ | "label-present"
230
+ | "no-whiteout"
231
+ | "no-error-state"
232
+ | "text-visible"
233
+ | "element-count"
234
+ | "nl-assertion";
235
+
236
+ // ---- Introspect Output ----
237
+
238
+ export interface IntrospectResult {
239
+ generatedAt: string;
240
+ pages: PageIntrospection[];
241
+ }
242
+
243
+ export interface PageIntrospection {
244
+ testId: string;
245
+ /** Auto-generated page description */
246
+ description: string;
247
+ /** Detected landmarks */
248
+ landmarks: { role: string; name: string }[];
249
+ /** Interactive elements */
250
+ interactiveElements: { role: string; name: string; hasLabel: boolean }[];
251
+ /** Page statistics */
252
+ stats: {
253
+ totalNodes: number;
254
+ landmarkCount: number;
255
+ interactiveCount: number;
256
+ unlabeledCount: number;
257
+ headingLevels: number[];
258
+ };
259
+ /** Auto-inferred invariants */
260
+ suggestedInvariants: SpecInvariant[];
261
+ }
262
+
263
+ // ---- NL Assertion (future) ----
264
+ //
265
+ // Assert UI state via natural language.
266
+ // Cost: high (Vision LLM call). Pages unaffected by dep graph are skipped.
267
+
268
+ export interface NlAssertion {
269
+ /** Assertion text */
270
+ assert: string;
271
+ /** Target page */
272
+ testId: string;
273
+ /** Source files this assertion depends on (for dep graph skip decisions) */
274
+ dependsOn?: string[];
275
+ /** Cached result of last verification */
276
+ lastResult?: { passed: boolean; reasoning: string; checkedAt: string };
277
+ }
278
+
279
+ // ---- Scoring ----
280
+
281
+ export interface LoopScore {
282
+ usability: number; // 0-100
283
+ practicality: number; // 0-100
284
+ fixSteps: number; // fewer is better
285
+ finalQuality: number; // 0-100
286
+ tokenUsage: number;
287
+ summary: string;
288
+ details: ScoreDetail[];
289
+ }
290
+
291
+ export interface ScoreDetail {
292
+ category: string;
293
+ score: number;
294
+ maxScore: number;
295
+ reasoning: string;
296
+ }
297
+
298
+ export interface DiffSemantics {
299
+ filesChanged: FileChange[];
300
+ commitMessage: string;
301
+ intent: ChangeIntent;
302
+ }
303
+
304
+ export interface FileChange {
305
+ path: string;
306
+ additions: number;
307
+ deletions: number;
308
+ hunks: DiffHunk[];
309
+ }
310
+
311
+ export interface DiffHunk {
312
+ header: string;
313
+ content: string;
314
+ startLine: number;
315
+ endLine: number;
316
+ }
317
+
318
+ // ---- Agent Reasoning ----
319
+
320
+ export interface VrtVerdict {
321
+ snapshotId: string;
322
+ decision: "approve" | "reject" | "escalate";
323
+ reasoning: string;
324
+ matchedIntent?: VisualExpectation;
325
+ confidence: number;
326
+ }
327
+
328
+ export interface AgentContext {
329
+ intent: ChangeIntent;
330
+ diffs: VrtDiff[];
331
+ verdicts: VrtVerdict[];
332
+ qualityChecks: QualityCheckResult[];
333
+ }
334
+
335
+ // ---- Accessibility Semantic Types ----
336
+
337
+ export interface A11yNode {
338
+ role: string;
339
+ name: string;
340
+ level?: number;
341
+ value?: string;
342
+ description?: string;
343
+ checked?: boolean | "mixed";
344
+ disabled?: boolean;
345
+ expanded?: boolean;
346
+ pressed?: boolean | "mixed";
347
+ selected?: boolean;
348
+ children?: A11yNode[];
349
+ }
350
+
351
+ export interface A11ySnapshot {
352
+ testId: string;
353
+ testTitle: string;
354
+ tree: A11yNode;
355
+ }
356
+
357
+ export type A11yChangeType =
358
+ | "node-added"
359
+ | "node-removed"
360
+ | "role-changed"
361
+ | "name-changed"
362
+ | "state-changed"
363
+ | "structure-changed"
364
+ | "landmark-changed";
365
+
366
+ export interface A11yChange {
367
+ type: A11yChangeType;
368
+ path: string; // e.g. "main > navigation > list > listitem[2]"
369
+ before?: Partial<A11yNode>;
370
+ after?: Partial<A11yNode>;
371
+ severity: "error" | "warning" | "info";
372
+ description: string;
373
+ }
374
+
375
+ export interface A11yDiff {
376
+ testId: string;
377
+ changes: A11yChange[];
378
+ hasRegression: boolean;
379
+ landmarkChanges: A11yChange[];
380
+ stats: {
381
+ added: number;
382
+ removed: number;
383
+ modified: number;
384
+ };
385
+ }
386
+
387
+ // ---- Visual Semantic Types ----
388
+
389
+ export type VisualChangeType =
390
+ | "text-change"
391
+ | "color-change"
392
+ | "layout-shift"
393
+ | "element-added"
394
+ | "element-removed"
395
+ | "icon-change";
396
+
397
+ export interface VisualSemanticChange {
398
+ type: VisualChangeType;
399
+ region: DiffRegion;
400
+ confidence: number;
401
+ description: string;
402
+ }
403
+
404
+ export interface VisualSemanticDiff {
405
+ testId: string;
406
+ changes: VisualSemanticChange[];
407
+ summary: string;
408
+ }
409
+
410
+ // ---- Cross-Validation ----
411
+
412
+ export interface CrossValidationResult {
413
+ testId: string;
414
+ visualDiff?: VisualSemanticDiff;
415
+ a11yDiff?: A11yDiff;
416
+ intentMatch: boolean;
417
+ consistency: "consistent" | "visual-only" | "a11y-only" | "mismatch";
418
+ recommendation: "approve" | "reject" | "escalate";
419
+ reasoning: string;
420
+ }
421
+
422
+ // ---- Unified Agent Context ----
423
+
424
+ export interface UnifiedAgentContext {
425
+ intent: ChangeIntent;
426
+ vrtDiffs: VrtDiff[];
427
+ a11yDiffs: A11yDiff[];
428
+ visualSemanticDiffs: VisualSemanticDiff[];
429
+ crossValidations: CrossValidationResult[];
430
+ verdicts: VrtVerdict[];
431
+ qualityChecks: QualityCheckResult[];
432
+ }
433
+
434
+ // ---- Quality Checks ----
435
+
436
+ export interface QualityCheckResult {
437
+ check: QualityCheckType;
438
+ passed: boolean;
439
+ details: string;
440
+ severity: "error" | "warning" | "info";
441
+ }
442
+
443
+ export type QualityCheckType =
444
+ | "whiteout"
445
+ | "error-state"
446
+ | "coverage"
447
+ | "layout-shift"
448
+ | "empty-content"
449
+ | "a11y-regression"
450
+ | "a11y-coverage"
451
+ | "landmark-missing"
452
+ | "label-missing";
453
+
454
+ // ---- Capture inputs ----
455
+
456
+ /**
457
+ * A targetable HTML source: either an inline HTML string or a URL the
458
+ * server fetches on the client's behalf. Shared by both the HTTP API
459
+ * (`api-types`) and the smoke runner (`vrt-markup/inspect`).
460
+ */
461
+ export interface HtmlSource {
462
+ /** Inline HTML */
463
+ html?: string;
464
+ /** URL (fetched server-side) */
465
+ url?: string;
466
+ /** Label (for reports) */
467
+ label?: string;
468
+ }
@@ -0,0 +1,185 @@
1
+ import type {
2
+ VrtDiff,
3
+ DiffRegion,
4
+ VisualSemanticChange,
5
+ VisualSemanticDiff,
6
+ VisualChangeType,
7
+ } from "./types.ts";
8
+
9
+ /**
10
+ * Convert VRT pixel diff into visual semantics.
11
+ *
12
+ * Analyzes each diff region to infer what changed:
13
+ * - text-change: text area change (wide, small region)
14
+ * - color-change: color-only change (same shape)
15
+ * - layout-shift: element repositioning (large region, correlated diffs)
16
+ * - element-added/removed: new/removed element
17
+ * - icon-change: small square region
18
+ */
19
+ export function classifyVisualDiff(diff: VrtDiff): VisualSemanticDiff {
20
+ const changes: VisualSemanticChange[] = [];
21
+
22
+ for (const region of diff.regions) {
23
+ const classified = classifyRegion(region, diff);
24
+ changes.push(classified);
25
+ }
26
+
27
+ // Group correlated layout-shifts
28
+ const grouped = groupLayoutShifts(changes);
29
+
30
+ return {
31
+ testId: diff.snapshot.testId,
32
+ changes: grouped,
33
+ summary: summarizeChanges(grouped),
34
+ };
35
+ }
36
+
37
+ function classifyRegion(
38
+ region: DiffRegion,
39
+ diff: VrtDiff
40
+ ): VisualSemanticChange {
41
+ const area = region.width * region.height;
42
+ const aspectRatio = region.width / Math.max(region.height, 1);
43
+ const density = region.diffPixelCount / area;
44
+ const globalRatio = region.diffPixelCount / diff.totalPixels;
45
+
46
+ // Small square -> icon change
47
+ if (
48
+ area < 4096 && // <= 64x64
49
+ aspectRatio > 0.5 &&
50
+ aspectRatio < 2.0
51
+ ) {
52
+ return {
53
+ type: "icon-change",
54
+ region,
55
+ confidence: 0.7,
56
+ description: `Small square region changed at (${region.x}, ${region.y})`,
57
+ };
58
+ }
59
+
60
+ // Wide and sparse -> text change
61
+ if (aspectRatio > 3.0 && density < 0.5) {
62
+ return {
63
+ type: "text-change",
64
+ region,
65
+ confidence: 0.6,
66
+ description: `Text-like region changed at (${region.x}, ${region.y}), ${region.width}x${region.height}`,
67
+ };
68
+ }
69
+
70
+ // High density, small-medium area -> color change
71
+ if (density > 0.7 && area < diff.totalPixels * 0.3) {
72
+ return {
73
+ type: "color-change",
74
+ region,
75
+ confidence: 0.65,
76
+ description: `Color change in region (${region.x}, ${region.y}), ${region.width}x${region.height}, ${(density * 100).toFixed(0)}% density`,
77
+ };
78
+ }
79
+
80
+ // Large area -> layout shift
81
+ if (globalRatio > 0.05) {
82
+ return {
83
+ type: "layout-shift",
84
+ region,
85
+ confidence: 0.5,
86
+ description: `Layout shift at (${region.x}, ${region.y}), ${region.width}x${region.height}, ${(globalRatio * 100).toFixed(1)}% of total`,
87
+ };
88
+ }
89
+
90
+ // New element (high density + medium size)
91
+ if (density > 0.5 && area > 1024) {
92
+ return {
93
+ type: "element-added",
94
+ region,
95
+ confidence: 0.4,
96
+ description: `New element appeared at (${region.x}, ${region.y}), ${region.width}x${region.height}`,
97
+ };
98
+ }
99
+
100
+ // Default: element-added
101
+ return {
102
+ type: "element-added",
103
+ region,
104
+ confidence: 0.3,
105
+ description: `Change at (${region.x}, ${region.y}), ${region.width}x${region.height}`,
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Group layout-shifts with close Y coordinates.
111
+ * Multiple regions shifting on the same row = one layout shift.
112
+ */
113
+ function groupLayoutShifts(
114
+ changes: VisualSemanticChange[]
115
+ ): VisualSemanticChange[] {
116
+ const layoutShifts = changes.filter((c) => c.type === "layout-shift");
117
+ const others = changes.filter((c) => c.type !== "layout-shift");
118
+
119
+ if (layoutShifts.length <= 1) return changes;
120
+
121
+ // Sort by Y coordinate and group nearby ones
122
+ layoutShifts.sort((a, b) => a.region.y - b.region.y);
123
+
124
+ const groups: VisualSemanticChange[][] = [];
125
+ let currentGroup: VisualSemanticChange[] = [layoutShifts[0]];
126
+
127
+ for (let i = 1; i < layoutShifts.length; i++) {
128
+ const prev = currentGroup[currentGroup.length - 1];
129
+ const curr = layoutShifts[i];
130
+ // Within 64px Y distance -> same group
131
+ if (Math.abs(curr.region.y - prev.region.y) < 64) {
132
+ currentGroup.push(curr);
133
+ } else {
134
+ groups.push(currentGroup);
135
+ currentGroup = [curr];
136
+ }
137
+ }
138
+ groups.push(currentGroup);
139
+
140
+ // Merge each group into a single change
141
+ const merged = groups.map((group): VisualSemanticChange => {
142
+ if (group.length === 1) return group[0];
143
+
144
+ const minX = Math.min(...group.map((c) => c.region.x));
145
+ const minY = Math.min(...group.map((c) => c.region.y));
146
+ const maxX = Math.max(
147
+ ...group.map((c) => c.region.x + c.region.width)
148
+ );
149
+ const maxY = Math.max(
150
+ ...group.map((c) => c.region.y + c.region.height)
151
+ );
152
+ const totalDiff = group.reduce(
153
+ (sum, c) => sum + c.region.diffPixelCount,
154
+ 0
155
+ );
156
+
157
+ return {
158
+ type: "layout-shift",
159
+ region: {
160
+ x: minX,
161
+ y: minY,
162
+ width: maxX - minX,
163
+ height: maxY - minY,
164
+ diffPixelCount: totalDiff,
165
+ },
166
+ confidence: Math.max(...group.map((c) => c.confidence)),
167
+ description: `Layout shift spanning ${group.length} regions at y=${minY}-${maxY}`,
168
+ };
169
+ });
170
+
171
+ return [...others, ...merged];
172
+ }
173
+
174
+ function summarizeChanges(changes: VisualSemanticChange[]): string {
175
+ const byType = new Map<VisualChangeType, number>();
176
+ for (const c of changes) {
177
+ byType.set(c.type, (byType.get(c.type) ?? 0) + 1);
178
+ }
179
+
180
+ const parts: string[] = [];
181
+ for (const [type, count] of byType) {
182
+ parts.push(`${count} ${type}`);
183
+ }
184
+ return parts.join(", ") || "no changes";
185
+ }