vibecode-anything 0.0.0-stage → 0.3.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 (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +235 -2
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +452 -0
  5. package/dist/core/adapters.d.ts +8 -0
  6. package/dist/core/adapters.js +92 -0
  7. package/dist/core/diff.d.ts +10 -0
  8. package/dist/core/diff.js +207 -0
  9. package/dist/core/doctor.d.ts +50 -0
  10. package/dist/core/doctor.js +312 -0
  11. package/dist/core/errors.d.ts +32 -0
  12. package/dist/core/errors.js +81 -0
  13. package/dist/core/exec.d.ts +14 -0
  14. package/dist/core/exec.js +109 -0
  15. package/dist/core/parity.d.ts +9 -0
  16. package/dist/core/parity.js +138 -0
  17. package/dist/core/png.d.ts +7 -0
  18. package/dist/core/png.js +303 -0
  19. package/dist/core/schema.d.ts +17 -0
  20. package/dist/core/schema.js +614 -0
  21. package/dist/core/slices.d.ts +24 -0
  22. package/dist/core/slices.js +294 -0
  23. package/dist/core/store.d.ts +17 -0
  24. package/dist/core/store.js +97 -0
  25. package/dist/core/types.d.ts +751 -0
  26. package/dist/core/types.js +4 -0
  27. package/dist/core/visual.d.ts +34 -0
  28. package/dist/core/visual.js +459 -0
  29. package/dist/core/watch.d.ts +53 -0
  30. package/dist/core/watch.js +285 -0
  31. package/dist/ingestors/api-repo.d.ts +5 -0
  32. package/dist/ingestors/api-repo.js +722 -0
  33. package/dist/ingestors/bridges.d.ts +3 -0
  34. package/dist/ingestors/bridges.js +562 -0
  35. package/dist/ingestors/cli.d.ts +9 -0
  36. package/dist/ingestors/cli.js +266 -0
  37. package/dist/ingestors/image.d.ts +2 -0
  38. package/dist/ingestors/image.js +147 -0
  39. package/dist/ingestors/index.d.ts +5 -0
  40. package/dist/ingestors/index.js +97 -0
  41. package/dist/ingestors/video.d.ts +47 -0
  42. package/dist/ingestors/video.js +605 -0
  43. package/dist/ingestors/web.d.ts +25 -0
  44. package/dist/ingestors/web.js +397 -0
  45. package/dist/mcp/server.d.ts +2 -0
  46. package/dist/mcp/server.js +504 -0
  47. package/dist/oracles/api-repo.d.ts +2 -0
  48. package/dist/oracles/api-repo.js +214 -0
  49. package/dist/oracles/cli.d.ts +2 -0
  50. package/dist/oracles/cli.js +157 -0
  51. package/dist/oracles/image.d.ts +2 -0
  52. package/dist/oracles/image.js +279 -0
  53. package/dist/oracles/index.d.ts +4 -0
  54. package/dist/oracles/index.js +91 -0
  55. package/dist/oracles/video.d.ts +21 -0
  56. package/dist/oracles/video.js +411 -0
  57. package/dist/oracles/web.d.ts +2 -0
  58. package/dist/oracles/web.js +480 -0
  59. package/dist/setup/index.d.ts +7 -0
  60. package/dist/setup/index.js +186 -0
  61. package/package.json +47 -6
  62. package/skills/vibecode-anything/SKILL.md +52 -0
@@ -0,0 +1,214 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { VibecodeError, errorMessage } from "../core/errors.js";
4
+ import { validateJsonSchema, queryJsonPath } from "../core/schema.js";
5
+ import { diffJsonSubset } from "../core/diff.js";
6
+ import { scanExportsFromText } from "../ingestors/api-repo.js";
7
+ function isObject(v) {
8
+ return v !== null && typeof v === "object" && !Array.isArray(v);
9
+ }
10
+ async function fetchWithTimeout(url, { method = "GET", headers = {}, body, timeoutMs = 10000 } = {}) {
11
+ const ctrl = new AbortController();
12
+ const t = setTimeout(() => ctrl.abort(), timeoutMs);
13
+ try {
14
+ const res = await fetch(url, {
15
+ method,
16
+ headers,
17
+ body: body === undefined || body === null ? undefined : (typeof body === "string" ? body : JSON.stringify(body)),
18
+ signal: ctrl.signal
19
+ });
20
+ const text = await res.text();
21
+ let json = null;
22
+ try {
23
+ json = text ? JSON.parse(text) : null;
24
+ }
25
+ catch { /* ignore */ }
26
+ const headersObj = {};
27
+ for (const [k, v] of res.headers.entries())
28
+ headersObj[k.toLowerCase()] = v;
29
+ return { status: res.status, headers: headersObj, text, json };
30
+ }
31
+ finally {
32
+ clearTimeout(t);
33
+ }
34
+ }
35
+ function buildUrl(base, p, query) {
36
+ const baseUrl = /^https?:\/\//i.test(base) ? base : `http://${base}`;
37
+ const url = /^https?:\/\//i.test(p) ? new URL(p) : new URL(p, baseUrl);
38
+ if (isObject(query)) {
39
+ for (const [k, v] of Object.entries(query)) {
40
+ if (v !== undefined && v !== null)
41
+ url.searchParams.set(k, String(v));
42
+ }
43
+ }
44
+ return url.toString();
45
+ }
46
+ async function verifyHttp(invariant, ctx, deps) {
47
+ if (!ctx.target)
48
+ throw new VibecodeError("TARGET_MISSING", "Missing --target <base-url> for HTTP verification.");
49
+ const input = invariant.input || {};
50
+ const expected = invariant.expected || {};
51
+ const url = buildUrl(ctx.target, input.path || "/", input.query);
52
+ const method = String(input.method || "GET").toUpperCase();
53
+ const headers = isObject(input.headers) ? input.headers : {};
54
+ const timeoutMs = input.timeoutMs || 10000;
55
+ const body = input.body ?? null;
56
+ let obs;
57
+ const started = Date.now();
58
+ try {
59
+ obs = await (deps.fetchWithTimeout || fetchWithTimeout)(url, { method, headers, body, timeoutMs });
60
+ }
61
+ catch (err) {
62
+ return { status: "fail", score: 0, failures: [`request failed: ${errorMessage(err)}`], metrics: { url, method } };
63
+ }
64
+ const durationMs = Date.now() - started;
65
+ const failures = [];
66
+ const diff = {};
67
+ if (expected.status !== undefined) {
68
+ const accepted = Array.isArray(expected.status) ? expected.status : [expected.status];
69
+ if (!accepted.includes(obs.status)) {
70
+ failures.push(`status expected ${JSON.stringify(accepted)}, got ${obs.status}`);
71
+ }
72
+ }
73
+ if (typeof expected.maxLatencyMs === "number" && durationMs > expected.maxLatencyMs) {
74
+ failures.push(`latency ${durationMs}ms > maxLatencyMs ${expected.maxLatencyMs}ms`);
75
+ }
76
+ if (expected.bodyExact !== undefined && obs.text !== String(expected.bodyExact)) {
77
+ failures.push("bodyExact mismatch");
78
+ }
79
+ if (expected.bodyContains !== undefined) {
80
+ const needles = Array.isArray(expected.bodyContains) ? expected.bodyContains : [expected.bodyContains];
81
+ for (const n of needles) {
82
+ if (!obs.text.includes(String(n)))
83
+ failures.push(`body missing ${JSON.stringify(n)}`);
84
+ }
85
+ }
86
+ if (isObject(expected.headers)) {
87
+ for (const [k, v] of Object.entries(expected.headers)) {
88
+ const actual = obs.headers[String(k).toLowerCase()];
89
+ if (actual === undefined)
90
+ failures.push(`missing header ${k}`);
91
+ else if (String(actual).toLowerCase() !== String(v).toLowerCase() && !String(actual).toLowerCase().includes(String(v).toLowerCase())) {
92
+ failures.push(`header ${k} expected ${JSON.stringify(v)}, got ${JSON.stringify(actual)}`);
93
+ }
94
+ }
95
+ }
96
+ if (expected.jsonSchema) {
97
+ if (obs.json === null) {
98
+ failures.push("response is not valid JSON (required by jsonSchema assertion)");
99
+ }
100
+ else {
101
+ const schemaErrors = validateJsonSchema(obs.json, expected.jsonSchema, "$");
102
+ if (schemaErrors.length) {
103
+ for (const e of schemaErrors.slice(0, 10))
104
+ failures.push(`jsonSchema ${e.path}: ${e.message}`);
105
+ diff.jsonSchema = schemaErrors;
106
+ }
107
+ }
108
+ }
109
+ if (expected.jsonSubset !== undefined) {
110
+ const subsetDiff = diffJsonSubset(expected.jsonSubset, obs.json, "$");
111
+ if (subsetDiff.length) {
112
+ for (const e of subsetDiff.slice(0, 10))
113
+ failures.push(`jsonSubset ${e.path}: expected ${JSON.stringify(e.expected)}, got ${JSON.stringify(e.actual)}`);
114
+ diff.jsonSubset = subsetDiff;
115
+ }
116
+ }
117
+ const jsonPathDiffs = [];
118
+ for (const assertion of expected.jsonPaths || []) {
119
+ if (obs.json === null) {
120
+ failures.push(`jsonPath ${assertion.path}: response is not valid JSON`);
121
+ jsonPathDiffs.push({ path: assertion.path, expected: assertion.equals, actual: undefined });
122
+ continue;
123
+ }
124
+ const q = queryJsonPath(obs.json, assertion.path);
125
+ if (!q.found) {
126
+ failures.push(`jsonPath ${assertion.path}: not found`);
127
+ jsonPathDiffs.push({ path: assertion.path, expected: assertion.equals, actual: undefined });
128
+ continue;
129
+ }
130
+ let ok = true;
131
+ if (Object.prototype.hasOwnProperty.call(assertion, "equals")) {
132
+ ok = JSON.stringify(q.value) === JSON.stringify(assertion.equals);
133
+ }
134
+ else if (Object.prototype.hasOwnProperty.call(assertion, "matches")) {
135
+ try {
136
+ ok = new RegExp(assertion.matches ?? "").test(String(q.value));
137
+ }
138
+ catch (err) {
139
+ const msg = errorMessage(err);
140
+ failures.push(`jsonPath ${assertion.path}: invalid regex ${assertion.matches}: ${msg}`);
141
+ jsonPathDiffs.push({ path: assertion.path, expected: assertion.matches, actual: q.value, error: msg });
142
+ continue;
143
+ }
144
+ }
145
+ if (!ok) {
146
+ const expectedVal = Object.prototype.hasOwnProperty.call(assertion, "equals") ? assertion.equals : assertion.matches;
147
+ failures.push(`jsonPath ${assertion.path}: expected ${JSON.stringify(expectedVal)}, got ${JSON.stringify(q.value)}`);
148
+ jsonPathDiffs.push({ path: assertion.path, expected: expectedVal, actual: q.value });
149
+ }
150
+ }
151
+ if (jsonPathDiffs.length > 0)
152
+ diff.jsonPaths = jsonPathDiffs;
153
+ return {
154
+ status: failures.length ? "fail" : "pass",
155
+ score: failures.length ? 0 : 1,
156
+ failures,
157
+ ...(Object.keys(diff).length ? { diff } : {}),
158
+ metrics: { url, method, status: obs.status, bytes: obs.text.length, durationMs }
159
+ };
160
+ }
161
+ async function verifyRepoExports(invariant, ctx, _deps) {
162
+ if (!ctx.target)
163
+ throw new VibecodeError("TARGET_MISSING", "Missing --target <repo-dir> for repo verification.");
164
+ const repoDir = path.resolve(ctx.cwd || process.cwd(), ctx.target);
165
+ if (!fs.existsSync(repoDir) || !fs.statSync(repoDir).isDirectory()) {
166
+ throw new VibecodeError("TARGET_MISSING", `Repo target not found: ${ctx.target}`);
167
+ }
168
+ const expected = invariant.expected || {};
169
+ const failures = [];
170
+ for (const rel of expected.filesPresent || []) {
171
+ const abs = path.join(repoDir, rel);
172
+ if (!fs.existsSync(abs))
173
+ failures.push(`missing file ${rel}`);
174
+ }
175
+ const modulePath = invariant.input?.modulePath || (expected.filesPresent || [])[0];
176
+ if (Array.isArray(expected.exports) && expected.exports.length) {
177
+ if (!modulePath) {
178
+ failures.push("no modulePath provided for export verification");
179
+ }
180
+ else {
181
+ const abs = path.join(repoDir, modulePath);
182
+ if (!fs.existsSync(abs)) {
183
+ failures.push(`module not found: ${modulePath}`);
184
+ }
185
+ else {
186
+ const text = fs.readFileSync(abs, "utf8");
187
+ const actual = scanExportsFromText(text);
188
+ const actualNames = new Set(actual.map((e) => e.name));
189
+ for (const exp of expected.exports) {
190
+ if (!actualNames.has(exp.name))
191
+ failures.push(`missing export ${exp.name}`);
192
+ else if (exp.kind && exp.kind !== "unknown") {
193
+ const found = actual.find((e) => e.name === exp.name);
194
+ if (found && found.kind !== "unknown" && found.kind !== exp.kind)
195
+ failures.push(`export ${exp.name} kind expected ${exp.kind}, got ${found.kind}`);
196
+ }
197
+ }
198
+ }
199
+ }
200
+ }
201
+ return {
202
+ status: failures.length ? "fail" : "pass",
203
+ score: failures.length ? 0 : 1,
204
+ failures,
205
+ metrics: { repoDir }
206
+ };
207
+ }
208
+ export async function verifyInvariant(invariant, ctx, deps = {}) {
209
+ if (invariant.type === "http")
210
+ return verifyHttp(invariant, ctx, deps);
211
+ if (invariant.type === "repo_exports")
212
+ return verifyRepoExports(invariant, ctx, deps);
213
+ throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported api-repo invariant type: ${invariant.type}`);
214
+ }
@@ -0,0 +1,2 @@
1
+ import type { Invariant, OracleContext, OracleInvariantOutcome, VerifyDeps } from "../core/types.js";
2
+ export declare function verifyInvariant(invariant: Invariant, ctx: OracleContext, _deps?: VerifyDeps): Promise<OracleInvariantOutcome>;
@@ -0,0 +1,157 @@
1
+ import path from "node:path";
2
+ import { splitCommand, runCommand } from "../core/exec.js";
3
+ import { normalizeText, diffLines } from "../core/diff.js";
4
+ import { validateJsonSchema, queryJsonPath } from "../core/schema.js";
5
+ import { VibecodeError, errorMessage } from "../core/errors.js";
6
+ export async function verifyInvariant(invariant, ctx, _deps = {}) {
7
+ if (!ctx.target)
8
+ throw new VibecodeError("TARGET_MISSING", "Missing --target \"<command>\" for CLI verification.");
9
+ const tokens = splitCommand(ctx.target);
10
+ if (tokens.length === 0)
11
+ throw new VibecodeError("TARGET_MISSING", "Invalid --target command");
12
+ const [target, ...baseArgs] = tokens;
13
+ const input = invariant.input || {};
14
+ const expected = invariant.expected || {};
15
+ const modes = Array.isArray(expected.normalize) ? expected.normalize : [];
16
+ const args = [...baseArgs, ...(Array.isArray(input.args) ? input.args : [])];
17
+ const cwd = input.cwd && input.cwd !== "." ? path.resolve(ctx.cwd || process.cwd(), input.cwd) : ctx.cwd;
18
+ const run = runCommand(target, args, {
19
+ stdin: input.stdin,
20
+ env: input.env,
21
+ cwd,
22
+ timeoutMs: input.timeoutMs || 10000,
23
+ shell: input.shell === true
24
+ });
25
+ const failures = [];
26
+ const diff = {};
27
+ const stdout = normalizeText(run.stdout, modes);
28
+ const stderr = normalizeText(run.stderr, modes);
29
+ if (run.timedOut) {
30
+ failures.push(`TIMEOUT: command exceeded ${input.timeoutMs || 10000}ms`);
31
+ }
32
+ if (run.error && run.exitCode === null) {
33
+ failures.push(`EXEC_ERROR: ${run.error.message}`);
34
+ }
35
+ // exitCode
36
+ if (expected.exitCode !== undefined) {
37
+ const accepted = Array.isArray(expected.exitCode) ? expected.exitCode : [expected.exitCode];
38
+ if (!accepted.includes(run.exitCode))
39
+ failures.push(`exitCode expected ${JSON.stringify(accepted)}, got ${run.exitCode}`);
40
+ }
41
+ // stdout assertions
42
+ if (expected.stdoutExact !== undefined && expected.stdoutExact !== null) {
43
+ const want = normalizeText(expected.stdoutExact, modes);
44
+ if (want !== stdout)
45
+ failures.push("stdoutExact mismatch");
46
+ }
47
+ for (const needle of expected.stdoutContains || []) {
48
+ if (!stdout.includes(needle))
49
+ failures.push(`stdout missing ${JSON.stringify(needle)}`);
50
+ }
51
+ for (const needle of expected.stdoutNotContains || []) {
52
+ if (stdout.includes(needle))
53
+ failures.push(`stdout unexpectedly contains ${JSON.stringify(needle)}`);
54
+ }
55
+ for (const pattern of expected.stdoutRegex || []) {
56
+ try {
57
+ if (!new RegExp(pattern).test(stdout))
58
+ failures.push(`stdout did not match /${pattern}/`);
59
+ }
60
+ catch (err) {
61
+ failures.push(`invalid stdoutRegex: ${errorMessage(err)}`);
62
+ }
63
+ }
64
+ // stderr assertions
65
+ if (expected.stderrExact !== undefined && expected.stderrExact !== null) {
66
+ const want = normalizeText(expected.stderrExact, modes);
67
+ if (want !== stderr)
68
+ failures.push("stderrExact mismatch");
69
+ }
70
+ for (const needle of expected.stderrContains || []) {
71
+ if (!stderr.includes(needle))
72
+ failures.push(`stderr missing ${JSON.stringify(needle)}`);
73
+ }
74
+ // golden stdout diff
75
+ if (expected.goldenStdout != null) {
76
+ const golden = normalizeText(expected.goldenStdout, modes);
77
+ const d = diffLines(golden, stdout, { context: 2, maxLines: 60 });
78
+ if (!d.identical) {
79
+ diff.goldenStdout = d;
80
+ failures.push(`stdout differs from golden (${d.added} added, ${d.removed} removed)`);
81
+ }
82
+ }
83
+ // JSON Schema
84
+ let parsed = null;
85
+ let parseOk = false;
86
+ const parseText = normalizeText(run.stdout, [...new Set([...modes, "ansi"])]);
87
+ const trimmed = parseText.trim();
88
+ if (trimmed) {
89
+ try {
90
+ parsed = JSON.parse(trimmed);
91
+ parseOk = true;
92
+ }
93
+ catch { /* ignore */ }
94
+ }
95
+ if (expected.jsonSchema) {
96
+ if (!parseOk) {
97
+ failures.push("stdout is not valid JSON (required by jsonSchema assertion)");
98
+ }
99
+ else {
100
+ const schemaErrors = validateJsonSchema(parsed, expected.jsonSchema, "$");
101
+ if (schemaErrors.length) {
102
+ for (const e of schemaErrors.slice(0, 10))
103
+ failures.push(`jsonSchema ${e.path}: ${e.message}`);
104
+ diff.jsonSchema = schemaErrors;
105
+ }
106
+ }
107
+ }
108
+ const jsonPathDiffs = [];
109
+ for (const assertion of expected.jsonPaths || []) {
110
+ if (!parseOk) {
111
+ failures.push(`jsonPath ${assertion.path}: stdout not JSON`);
112
+ continue;
113
+ }
114
+ const q = queryJsonPath(parsed, assertion.path);
115
+ if (!q.found) {
116
+ failures.push(`jsonPath ${assertion.path}: not found`);
117
+ jsonPathDiffs.push({ path: assertion.path, expected: assertion.equals, actual: undefined });
118
+ continue;
119
+ }
120
+ if (Object.prototype.hasOwnProperty.call(assertion, "equals")) {
121
+ const ok = JSON.stringify(q.value) === JSON.stringify(assertion.equals);
122
+ if (!ok) {
123
+ failures.push(`jsonPath ${assertion.path}: expected ${JSON.stringify(assertion.equals)}, got ${JSON.stringify(q.value)}`);
124
+ jsonPathDiffs.push({ path: assertion.path, expected: assertion.equals, actual: q.value });
125
+ }
126
+ }
127
+ else if (Object.prototype.hasOwnProperty.call(assertion, "matches")) {
128
+ let re;
129
+ try {
130
+ re = new RegExp(assertion.matches ?? "");
131
+ }
132
+ catch (err) {
133
+ failures.push(`jsonPath ${assertion.path}: invalid matches regex: ${errorMessage(err)}`);
134
+ jsonPathDiffs.push({ path: assertion.path, matches: assertion.matches, actual: q.value });
135
+ continue;
136
+ }
137
+ if (!re.test(String(q.value))) {
138
+ failures.push(`jsonPath ${assertion.path}: value ${JSON.stringify(q.value)} did not match /${assertion.matches}/`);
139
+ jsonPathDiffs.push({ path: assertion.path, matches: assertion.matches, actual: q.value });
140
+ }
141
+ }
142
+ }
143
+ if (jsonPathDiffs.length > 0)
144
+ diff.jsonPaths = jsonPathDiffs;
145
+ return {
146
+ status: failures.length === 0 ? "pass" : "fail",
147
+ score: failures.length === 0 ? 1 : 0,
148
+ failures,
149
+ ...(Object.keys(diff).length ? { diff } : {}),
150
+ metrics: {
151
+ exitCode: run.exitCode,
152
+ durationMs: run.durationMs,
153
+ stdoutBytes: (run.stdout || "").length,
154
+ stderrBytes: (run.stderr || "").length
155
+ }
156
+ };
157
+ }
@@ -0,0 +1,2 @@
1
+ import type { Invariant, OracleContext, OracleInvariantOutcome, VerifyDeps } from "../core/types.js";
2
+ export declare function verifyInvariant(invariant: Invariant, ctx: OracleContext, deps?: VerifyDeps): Promise<OracleInvariantOutcome>;
@@ -0,0 +1,279 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { VibecodeError } from "../core/errors.js";
4
+ import { artifactPath, ensureDir } from "../core/store.js";
5
+ import { readImageDimensions } from "../core/png.js";
6
+ import { decodeImage, computeSSIM, computePixelDiff, computeDHash, hammingDistanceHex, extractPalette, comparePalettes, extractLayoutRegions, compareRegionsIoU, writeDiffPng } from "../core/visual.js";
7
+ import { loadPlaywright } from "../core/adapters.js";
8
+ function assertValidPngHeaderIfPng(filePath) {
9
+ if (path.extname(filePath).toLowerCase() !== ".png")
10
+ return;
11
+ const dims = readImageDimensions(fs.readFileSync(filePath));
12
+ if (!dims || dims.format !== "png" || !(dims.width > 0 && dims.height > 0)) {
13
+ throw new VibecodeError("UNSUPPORTED_FORMAT", `Corrupt or invalid PNG image: ${path.basename(filePath)}`);
14
+ }
15
+ }
16
+ function resolveReference(invariant, ctx) {
17
+ const refKey = invariant.input?.referenceArtifact;
18
+ if (!refKey)
19
+ throw new VibecodeError("CONTRACT_INVALID", `Invariant ${invariant.id} missing input.referenceArtifact`);
20
+ const files = ctx.contract?.artifacts?.files || {};
21
+ const rel = files[refKey];
22
+ if (!rel)
23
+ throw new VibecodeError("CONTRACT_INVALID", `Reference artifact ${refKey} not found in contract.artifacts.files`);
24
+ const abs = artifactPath(rel, ctx.cwd);
25
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
26
+ throw new VibecodeError("CONTRACT_NOT_FOUND", `Reference artifact missing on disk: ${rel}`);
27
+ }
28
+ return { refKey, rel, abs };
29
+ }
30
+ async function captureUrlScreenshot(url, ctx, deps) {
31
+ const explicitPw = Object.prototype.hasOwnProperty.call(deps, "playwright") ? deps.playwright : undefined;
32
+ const pw = explicitPw === null ? null : (explicitPw || (await loadPlaywright(deps)));
33
+ if (!pw) {
34
+ throw new VibecodeError("ADAPTER_MISSING", "Cannot capture URL target as image without Playwright", {
35
+ adapter: "playwright",
36
+ installHint: "npm install -D playwright && npx playwright install chromium",
37
+ fallbackHint: "Provide a PNG screenshot path as --target instead of a URL."
38
+ });
39
+ }
40
+ const browser = await pw.chromium.launch({ headless: true });
41
+ try {
42
+ const viewport = ctx.viewport || { width: 1280, height: 720 };
43
+ const page = await browser.newPage({ viewport });
44
+ await page.goto(url, { waitUntil: "networkidle", timeout: 15000 });
45
+ const outDir = path.join(ctx.cacheDir || path.join(ctx.cwd || process.cwd(), ".vibecode", "cache"), "captures");
46
+ ensureDir(outDir);
47
+ const outPath = path.join(outDir, `${invariantSafeName(ctx.currentInvariantId || "capture")}.png`);
48
+ await page.screenshot({ path: outPath, fullPage: false });
49
+ return outPath;
50
+ }
51
+ finally {
52
+ try {
53
+ await browser.close();
54
+ }
55
+ catch { /* ignore */ }
56
+ }
57
+ }
58
+ function invariantSafeName(id) {
59
+ return String(id).replace(/[^A-Za-z0-9_.-]+/g, "-");
60
+ }
61
+ async function resolveCandidatePath(invariant, ctx, deps) {
62
+ const target = ctx.target;
63
+ if (!target)
64
+ throw new VibecodeError("TARGET_MISSING", "Missing --target <image-path-or-url> for image verification.");
65
+ if (/^https?:\/\//i.test(target)) {
66
+ return captureUrlScreenshot(target, { ...ctx, currentInvariantId: invariant.id }, deps);
67
+ }
68
+ const abs = path.resolve(ctx.cwd || process.cwd(), target);
69
+ if (!fs.existsSync(abs))
70
+ throw new VibecodeError("TARGET_MISSING", `Target image not found: ${target}`);
71
+ if (fs.statSync(abs).isDirectory()) {
72
+ throw new VibecodeError("UNSUPPORTED_FORMAT", `Target image path is a directory: ${target}`);
73
+ }
74
+ return abs;
75
+ }
76
+ function writeDiffArtifact(diffMask, invariant, ctx) {
77
+ const cacheDir = ctx.cacheDir || path.join(ctx.cwd || process.cwd(), ".vibecode", "cache");
78
+ const diffDir = path.join(cacheDir, "diffs");
79
+ ensureDir(diffDir);
80
+ const file = path.join(diffDir, `${invariantSafeName(invariant.id)}.png`);
81
+ writeDiffPng(diffMask, file);
82
+ return path.relative(ctx.cwd || process.cwd(), file).replace(/\\/g, "/");
83
+ }
84
+ function checkDimensions(expectedDims, actualDims) {
85
+ if (!expectedDims)
86
+ return [];
87
+ const failures = [];
88
+ if (!actualDims || !(actualDims.width > 0 && actualDims.height > 0)) {
89
+ failures.push(`invalid image dimensions ${actualDims?.width}x${actualDims?.height}`);
90
+ return failures;
91
+ }
92
+ if (typeof expectedDims.width === "number" && expectedDims.width !== actualDims.width) {
93
+ failures.push(`width expected ${expectedDims.width}, got ${actualDims.width}`);
94
+ }
95
+ if (typeof expectedDims.height === "number" && expectedDims.height !== actualDims.height) {
96
+ failures.push(`height expected ${expectedDims.height}, got ${actualDims.height}`);
97
+ }
98
+ if (typeof expectedDims.aspectRatioTolerance === "number") {
99
+ const expectedRatio = typeof expectedDims.aspectRatio === "number" && expectedDims.aspectRatio > 0
100
+ ? expectedDims.aspectRatio
101
+ : typeof expectedDims.width === "number" &&
102
+ expectedDims.width > 0 &&
103
+ typeof expectedDims.height === "number" &&
104
+ expectedDims.height > 0
105
+ ? expectedDims.width / expectedDims.height
106
+ : null;
107
+ if (expectedRatio !== null) {
108
+ const actualRatio = actualDims.width / actualDims.height;
109
+ if (Math.abs(expectedRatio - actualRatio) > expectedDims.aspectRatioTolerance) {
110
+ failures.push(`aspectRatio delta ${Math.abs(expectedRatio - actualRatio).toFixed(4)} > ${expectedDims.aspectRatioTolerance}`);
111
+ }
112
+ }
113
+ }
114
+ return failures;
115
+ }
116
+ async function decodeCached(filePath, ctx, deps) {
117
+ if (!ctx?.runtimeCache || Object.keys(deps || {}).length > 0) {
118
+ return decodeImage(filePath, deps);
119
+ }
120
+ const st = fs.statSync(filePath);
121
+ const key = `img:${filePath}:${st.size}:${st.mtimeMs}`;
122
+ const cached = ctx.runtimeCache[key];
123
+ if (!cached) {
124
+ const decoded = await decodeImage(filePath, deps);
125
+ ctx.runtimeCache[key] = decoded;
126
+ return decoded;
127
+ }
128
+ return cached;
129
+ }
130
+ async function verifyLayout(invariant, ctx, deps) {
131
+ const { abs: refPath } = resolveReference(invariant, ctx);
132
+ const candPath = await resolveCandidatePath(invariant, ctx, deps);
133
+ assertValidPngHeaderIfPng(refPath);
134
+ assertValidPngHeaderIfPng(candPath);
135
+ const expected = invariant.expected || {};
136
+ const tolerance = invariant.tolerance || {};
137
+ const expectedPalette = Array.isArray(expected.palette) ? expected.palette : [];
138
+ const expectedRegions = Array.isArray(expected.regions) ? expected.regions : [];
139
+ const hasPalette = expectedPalette.length > 0;
140
+ const hasRegions = expectedRegions.length > 0;
141
+ const needsPixels = Boolean(expected.nonBlank) || hasPalette || hasRegions;
142
+ if (!needsPixels) {
143
+ const refDims = readImageDimensions(fs.readFileSync(refPath));
144
+ const candDims = readImageDimensions(fs.readFileSync(candPath));
145
+ if (refDims && candDims && candDims.width > 0 && candDims.height > 0) {
146
+ const failures = checkDimensions(expected.dimensions, { width: candDims.width, height: candDims.height });
147
+ const metrics = {
148
+ reference: { width: refDims.width, height: refDims.height },
149
+ candidate: { width: candDims.width, height: candDims.height },
150
+ ...(failures.length ? { dimensionMismatch: true } : {})
151
+ };
152
+ return { status: failures.length ? "fail" : "pass", score: failures.length ? 0 : 1, failures, metrics };
153
+ }
154
+ }
155
+ // Let decode errors (notably ADAPTER_MISSING) propagate so the dispatcher can mark skipped.
156
+ const refImg = await decodeCached(refPath, ctx, deps);
157
+ const candImg = await decodeCached(candPath, ctx, deps);
158
+ const failures = [];
159
+ const metrics = {
160
+ reference: { width: refImg.width, height: refImg.height },
161
+ candidate: { width: candImg.width, height: candImg.height }
162
+ };
163
+ const dimFailures = checkDimensions(expected.dimensions, { width: candImg.width, height: candImg.height });
164
+ if (dimFailures.length) {
165
+ failures.push(...dimFailures);
166
+ metrics.dimensionMismatch = true;
167
+ }
168
+ if (expected.nonBlank === true) {
169
+ const data = candImg.data;
170
+ if (!data || data.length < 4) {
171
+ failures.push("candidate image is blank (empty pixel buffer)");
172
+ }
173
+ else {
174
+ let uniform = true;
175
+ let allTransparent = data[3] === 0;
176
+ const r0 = data[0], g0 = data[1], b0 = data[2], a0 = data[3];
177
+ for (let i = 4; i < data.length; i += 4) {
178
+ if (data[i + 3] !== 0)
179
+ allTransparent = false;
180
+ if (data[i] !== r0 || data[i + 1] !== g0 || data[i + 2] !== b0 || data[i + 3] !== a0) {
181
+ uniform = false;
182
+ }
183
+ if (!uniform && !allTransparent)
184
+ break;
185
+ }
186
+ if (allTransparent)
187
+ failures.push("candidate image is blank (fully transparent)");
188
+ else if (uniform)
189
+ failures.push("candidate image is blank (uniform color)");
190
+ }
191
+ metrics.nonBlank = !failures.some((f) => f.includes("blank"));
192
+ }
193
+ // Soft metrics: palette/regions
194
+ let paletteSimilarity = 1;
195
+ let regionIoU = 1;
196
+ if (hasPalette) {
197
+ const candPalette = extractPalette(candImg, expectedPalette.length);
198
+ paletteSimilarity = comparePalettes(expectedPalette, candPalette);
199
+ metrics.paletteSimilarity = paletteSimilarity;
200
+ const minPalette = typeof tolerance.minPaletteSimilarity === "number" ? tolerance.minPaletteSimilarity : 0.8;
201
+ if (paletteSimilarity < minPalette)
202
+ failures.push(`paletteSimilarity ${paletteSimilarity.toFixed(3)} < ${minPalette}`);
203
+ }
204
+ if (hasRegions) {
205
+ const candRegions = extractLayoutRegions(candImg, { maxDepth: 3 });
206
+ const cmp = compareRegionsIoU(expectedRegions, candRegions);
207
+ regionIoU = cmp.meanIoU;
208
+ metrics.regionIoU = regionIoU;
209
+ metrics.matchedRegions = cmp.matched;
210
+ const minIoU = typeof tolerance.minLayoutIoU === "number" ? tolerance.minLayoutIoU : 0.75;
211
+ if (regionIoU < minIoU)
212
+ failures.push(`regionIoU ${regionIoU.toFixed(3)} < ${minIoU}`);
213
+ }
214
+ if (failures.length > 0) {
215
+ // Hard dimension mismatch should fail; soft palette/region also fail when invoked as soft invariant under strict gate handled by scorer.
216
+ // Status here is pass/fail; scorer applies severity/gate.
217
+ return { status: "fail", score: invariant.severity === "hard" ? 0 : Math.min(paletteSimilarity, regionIoU), failures, metrics };
218
+ }
219
+ const score = invariant.severity === "hard" ? 1 : Math.min(paletteSimilarity, regionIoU);
220
+ return { status: "pass", score, failures: [], metrics };
221
+ }
222
+ async function verifyPerceptual(invariant, ctx, deps) {
223
+ const { abs: refPath } = resolveReference(invariant, ctx);
224
+ const candPath = await resolveCandidatePath(invariant, ctx, deps);
225
+ assertValidPngHeaderIfPng(refPath);
226
+ assertValidPngHeaderIfPng(candPath);
227
+ const tolerance = invariant.tolerance || {};
228
+ const refImg = await decodeCached(refPath, ctx, deps);
229
+ const candImg = await decodeCached(candPath, ctx, deps);
230
+ const minSSIM = typeof tolerance.minSSIM === "number" ? tolerance.minSSIM : 0.85;
231
+ const maxPixelDiffRatio = typeof tolerance.maxPixelDiffRatio === "number" ? tolerance.maxPixelDiffRatio : 0.1;
232
+ const colorDelta = typeof tolerance.colorDelta === "number" ? tolerance.colorDelta : 0.1;
233
+ const ssimRes = computeSSIM(refImg, candImg);
234
+ const diffRes = computePixelDiff(refImg, candImg, { colorDelta });
235
+ const refHash = computeDHash(refImg);
236
+ const candHash = computeDHash(candImg);
237
+ const hamming = hammingDistanceHex(refHash, candHash);
238
+ const failures = [];
239
+ if (ssimRes.ssim < minSSIM)
240
+ failures.push(`ssim ${ssimRes.ssim.toFixed(4)} < ${minSSIM}`);
241
+ if (diffRes.diffRatio > maxPixelDiffRatio)
242
+ failures.push(`diffRatio ${diffRes.diffRatio.toFixed(4)} > ${maxPixelDiffRatio}`);
243
+ const metrics = {
244
+ ssim: ssimRes.ssim,
245
+ diffRatio: diffRes.diffRatio,
246
+ diffPixels: diffRes.diffPixels,
247
+ totalPixels: diffRes.totalPixels,
248
+ hammingDistance: hamming,
249
+ referenceHash: refHash,
250
+ candidateHash: candHash,
251
+ dimensionMismatch: ssimRes.dimensionMismatch || diffRes.dimensionMismatch
252
+ };
253
+ let diffArtifact = null;
254
+ if (failures.length > 0) {
255
+ try {
256
+ diffArtifact = writeDiffArtifact(diffRes.diffMask, invariant, ctx);
257
+ metrics.diffPng = diffArtifact;
258
+ }
259
+ catch {
260
+ // ignore diff write failures
261
+ }
262
+ }
263
+ // Continuous score for soft perceptual: blend ssim and pixel match
264
+ const score = Math.max(0, Math.min(1, (ssimRes.ssim * 0.7) + ((1 - diffRes.diffRatio) * 0.3)));
265
+ return {
266
+ status: failures.length > 0 ? "fail" : "pass",
267
+ score,
268
+ failures,
269
+ metrics,
270
+ ...(diffArtifact ? { diff: { diffPng: diffArtifact } } : {})
271
+ };
272
+ }
273
+ export async function verifyInvariant(invariant, ctx, deps = {}) {
274
+ if (invariant.type === "image_layout")
275
+ return verifyLayout(invariant, ctx, deps);
276
+ if (invariant.type === "image_perceptual")
277
+ return verifyPerceptual(invariant, ctx, deps);
278
+ throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported image invariant type: ${invariant.type}`);
279
+ }
@@ -0,0 +1,4 @@
1
+ import type { ContractV02, Invariant, InvariantResult, OracleContext, OracleFn, ParityReport, VerifyDeps } from "../core/types.js";
2
+ export declare function getOracle(type: string): Promise<OracleFn | null>;
3
+ export declare function verifyInvariant(invariant: Invariant, ctx: OracleContext, deps?: VerifyDeps): Promise<InvariantResult>;
4
+ export declare function verifyContract(contract: ContractV02, ctx: OracleContext, deps?: VerifyDeps): Promise<ParityReport>;