vibecode-anything 0.3.0 → 0.4.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 (160) hide show
  1. package/README.md +239 -67
  2. package/dist/cli.js +2140 -73
  3. package/dist/core/adapters.d.ts +26 -3
  4. package/dist/core/adapters.js +411 -25
  5. package/dist/core/agent-adapter.d.ts +67 -0
  6. package/dist/core/agent-adapter.js +312 -0
  7. package/dist/core/anti-cheat.d.ts +6 -0
  8. package/dist/core/anti-cheat.js +372 -0
  9. package/dist/core/badge.d.ts +18 -0
  10. package/dist/core/badge.js +360 -0
  11. package/dist/core/cache.d.ts +47 -0
  12. package/dist/core/cache.js +403 -0
  13. package/dist/core/ci-export.d.ts +35 -0
  14. package/dist/core/ci-export.js +796 -0
  15. package/dist/core/ci-formats.d.ts +21 -0
  16. package/dist/core/ci-formats.js +388 -0
  17. package/dist/core/client-codegen.d.ts +36 -0
  18. package/dist/core/client-codegen.js +2538 -0
  19. package/dist/core/compose.d.ts +71 -0
  20. package/dist/core/compose.js +1088 -0
  21. package/dist/core/docs-export.d.ts +37 -0
  22. package/dist/core/docs-export.js +2706 -0
  23. package/dist/core/doctor.d.ts +21 -1
  24. package/dist/core/doctor.js +234 -21
  25. package/dist/core/exec.d.ts +26 -2
  26. package/dist/core/exec.js +235 -8
  27. package/dist/core/fixtures.d.ts +153 -0
  28. package/dist/core/fixtures.js +2245 -0
  29. package/dist/core/format.d.ts +77 -0
  30. package/dist/core/format.js +632 -0
  31. package/dist/core/fs-snapshot.d.ts +37 -0
  32. package/dist/core/fs-snapshot.js +216 -0
  33. package/dist/core/graphql-export.d.ts +34 -0
  34. package/dist/core/graphql-export.js +2482 -0
  35. package/dist/core/har-export.d.ts +29 -0
  36. package/dist/core/har-export.js +988 -0
  37. package/dist/core/html-report.d.ts +27 -0
  38. package/dist/core/html-report.js +1535 -0
  39. package/dist/core/http-export.d.ts +31 -0
  40. package/dist/core/http-export.js +726 -0
  41. package/dist/core/impact.d.ts +80 -0
  42. package/dist/core/impact.js +1412 -0
  43. package/dist/core/lint.d.ts +38 -0
  44. package/dist/core/lint.js +1111 -0
  45. package/dist/core/load-export.d.ts +37 -0
  46. package/dist/core/load-export.js +1813 -0
  47. package/dist/core/mcp-export.d.ts +35 -0
  48. package/dist/core/mcp-export.js +1736 -0
  49. package/dist/core/mock-server.d.ts +47 -0
  50. package/dist/core/mock-server.js +1722 -0
  51. package/dist/core/openapi-export.d.ts +44 -0
  52. package/dist/core/openapi-export.js +1074 -0
  53. package/dist/core/parity.d.ts +6 -1
  54. package/dist/core/parity.js +36 -1
  55. package/dist/core/playwright-exporter.d.ts +23 -0
  56. package/dist/core/playwright-exporter.js +1343 -0
  57. package/dist/core/png.js +45 -9
  58. package/dist/core/regression.d.ts +54 -0
  59. package/dist/core/regression.js +529 -0
  60. package/dist/core/responsive.d.ts +86 -0
  61. package/dist/core/responsive.js +606 -0
  62. package/dist/core/run.d.ts +74 -0
  63. package/dist/core/run.js +696 -0
  64. package/dist/core/scheduler.d.ts +24 -0
  65. package/dist/core/scheduler.js +162 -0
  66. package/dist/core/schema-export.d.ts +29 -0
  67. package/dist/core/schema-export.js +2215 -0
  68. package/dist/core/schema.d.ts +3 -2
  69. package/dist/core/schema.js +460 -17
  70. package/dist/core/security.d.ts +233 -0
  71. package/dist/core/security.js +1839 -0
  72. package/dist/core/server-export.d.ts +38 -0
  73. package/dist/core/server-export.js +3198 -0
  74. package/dist/core/spec-writer.d.ts +9 -0
  75. package/dist/core/spec-writer.js +1202 -0
  76. package/dist/core/store.d.ts +11 -2
  77. package/dist/core/store.js +128 -8
  78. package/dist/core/target-map.d.ts +34 -0
  79. package/dist/core/target-map.js +262 -0
  80. package/dist/core/test-exporter.d.ts +25 -0
  81. package/dist/core/test-exporter.js +1918 -0
  82. package/dist/core/types.d.ts +182 -14
  83. package/dist/core/visual-semantic.d.ts +67 -0
  84. package/dist/core/visual-semantic.js +673 -0
  85. package/dist/core/visual.js +65 -16
  86. package/dist/core/watch.d.ts +28 -3
  87. package/dist/core/watch.js +222 -12
  88. package/dist/core/yaml.d.ts +5 -0
  89. package/dist/core/yaml.js +1009 -0
  90. package/dist/diagnostics/diagnose.d.ts +53 -0
  91. package/dist/diagnostics/diagnose.js +1083 -0
  92. package/dist/diagnostics/flake.d.ts +71 -0
  93. package/dist/diagnostics/flake.js +608 -0
  94. package/dist/diagnostics/mutation-audit.d.ts +69 -0
  95. package/dist/diagnostics/mutation-audit.js +769 -0
  96. package/dist/diagnostics/spatial.d.ts +42 -0
  97. package/dist/diagnostics/spatial.js +346 -0
  98. package/dist/diagnostics/trends.d.ts +122 -0
  99. package/dist/diagnostics/trends.js +1190 -0
  100. package/dist/discovery/discover.d.ts +111 -0
  101. package/dist/discovery/discover.js +2017 -0
  102. package/dist/discovery/lock.d.ts +116 -0
  103. package/dist/discovery/lock.js +1505 -0
  104. package/dist/discovery/routes.d.ts +36 -0
  105. package/dist/discovery/routes.js +1494 -0
  106. package/dist/discovery/test-importer.d.ts +92 -0
  107. package/dist/discovery/test-importer.js +4952 -0
  108. package/dist/index.d.ts +123 -0
  109. package/dist/index.js +99 -0
  110. package/dist/ingestors/api-collections.d.ts +28 -0
  111. package/dist/ingestors/api-collections.js +2335 -0
  112. package/dist/ingestors/api-repo.d.ts +2 -1
  113. package/dist/ingestors/api-repo.js +483 -85
  114. package/dist/ingestors/asyncapi.d.ts +26 -0
  115. package/dist/ingestors/asyncapi.js +2105 -0
  116. package/dist/ingestors/bridges.d.ts +2 -0
  117. package/dist/ingestors/bridges.js +702 -0
  118. package/dist/ingestors/cli.d.ts +2 -1
  119. package/dist/ingestors/cli.js +234 -46
  120. package/dist/ingestors/curl.d.ts +14 -0
  121. package/dist/ingestors/curl.js +1024 -0
  122. package/dist/ingestors/graphql.d.ts +56 -0
  123. package/dist/ingestors/graphql.js +1852 -0
  124. package/dist/ingestors/http-file.d.ts +20 -0
  125. package/dist/ingestors/http-file.js +923 -0
  126. package/dist/ingestors/index.js +486 -6
  127. package/dist/ingestors/openrpc.d.ts +29 -0
  128. package/dist/ingestors/openrpc.js +1807 -0
  129. package/dist/ingestors/proto.d.ts +47 -0
  130. package/dist/ingestors/proto.js +2690 -0
  131. package/dist/ingestors/trace.d.ts +10 -0
  132. package/dist/ingestors/trace.js +599 -0
  133. package/dist/ingestors/video.d.ts +4 -1
  134. package/dist/ingestors/video.js +86 -36
  135. package/dist/ingestors/web.d.ts +16 -1
  136. package/dist/ingestors/web.js +474 -32
  137. package/dist/mcp/server.js +3532 -67
  138. package/dist/oracles/api-repo.js +102 -30
  139. package/dist/oracles/cli.js +65 -17
  140. package/dist/oracles/http-workflow.d.ts +68 -0
  141. package/dist/oracles/http-workflow.js +828 -0
  142. package/dist/oracles/image.js +178 -28
  143. package/dist/oracles/index.d.ts +3 -1
  144. package/dist/oracles/index.js +243 -14
  145. package/dist/oracles/perf-budget.d.ts +90 -0
  146. package/dist/oracles/perf-budget.js +1329 -0
  147. package/dist/oracles/stream.d.ts +94 -0
  148. package/dist/oracles/stream.js +1268 -0
  149. package/dist/oracles/ui-states.d.ts +49 -0
  150. package/dist/oracles/ui-states.js +894 -0
  151. package/dist/oracles/video.d.ts +1 -1
  152. package/dist/oracles/video.js +232 -16
  153. package/dist/oracles/web.js +464 -73
  154. package/dist/plugins/builtins.d.ts +12 -0
  155. package/dist/plugins/builtins.js +1052 -0
  156. package/dist/plugins/registry.d.ts +86 -0
  157. package/dist/plugins/registry.js +554 -0
  158. package/dist/setup/index.js +145 -33
  159. package/package.json +56 -47
  160. package/skills/vibecode-anything/SKILL.md +75 -52
@@ -1,10 +1,41 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { VibecodeError } from "../core/errors.js";
4
- import { artifactPath, ensureDir } from "../core/store.js";
3
+ import { VibecodeError, errorMessage } from "../core/errors.js";
4
+ import { STRICT_CONTROL_CHARS_RE, isForbiddenObjectKey, isInsideVaultDirectory, isPathWithinDir, parseSafeHttpBaseUrl, redactSensitiveText, resolveSafeTargetUrl } from "../core/security.js";
5
+ import { artifactPath, ensureDir, resolveWorkspace } from "../core/store.js";
5
6
  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";
7
+ import { decodeImage, computeSSIM, computePixelDiff, computeDHash, hammingDistanceHex, extractPalette, comparePalettes, extractLayoutRegions, compareRegionsIoU, estimateTypographyBands, writeDiffPng } from "../core/visual.js";
8
+ import { auditWcagContrast } from "../core/visual-semantic.js";
9
+ import { loadPlaywright, launchBrowser } from "../core/adapters.js";
10
+ function applyWcagAudit(candImg, level, failures, metrics, diff) {
11
+ const wcag = auditWcagContrast(candImg, { level });
12
+ metrics.wcagAudit = {
13
+ passed: wcag.passed,
14
+ level: wcag.level,
15
+ worstContrastRatio: wcag.worstContrastRatio,
16
+ violationsCount: wcag.violations.length,
17
+ checkedRegions: wcag.checkedRegions,
18
+ minRequiredRatio: wcag.minRequiredRatio,
19
+ designTokens: wcag.designTokens
20
+ };
21
+ if (!wcag.passed) {
22
+ for (const v of wcag.violations.slice(0, 10)) {
23
+ failures.push(`WCAG ${v.level} contrast ratio ${v.contrastRatio.toFixed(2)}:1 < ${v.requiredRatio.toFixed(1)}:1 ` +
24
+ `in region ${v.regionId} (${v.foregroundHex} on ${v.backgroundHex})`);
25
+ }
26
+ if (wcag.violations.length > 10) {
27
+ failures.push(`WCAG ${wcag.level} contrast audit found ${wcag.violations.length} total contrast violations`);
28
+ }
29
+ diff.wcagViolations = wcag.violations;
30
+ }
31
+ return wcag;
32
+ }
33
+ function wcagAuditScore(wcag) {
34
+ if (!wcag || wcag.passed)
35
+ return 1;
36
+ const req = wcag.minRequiredRatio > 0 ? wcag.minRequiredRatio : 4.5;
37
+ return Math.max(0, Math.min(0.99, wcag.worstContrastRatio / req));
38
+ }
8
39
  function assertValidPngHeaderIfPng(filePath) {
9
40
  if (path.extname(filePath).toLowerCase() !== ".png")
10
41
  return;
@@ -15,21 +46,45 @@ function assertValidPngHeaderIfPng(filePath) {
15
46
  }
16
47
  function resolveReference(invariant, ctx) {
17
48
  const refKey = invariant.input?.referenceArtifact;
18
- if (!refKey)
49
+ if (!refKey || typeof refKey !== "string" || isForbiddenObjectKey(refKey)) {
19
50
  throw new VibecodeError("CONTRACT_INVALID", `Invariant ${invariant.id} missing input.referenceArtifact`);
51
+ }
20
52
  const files = ctx.contract?.artifacts?.files || {};
21
- const rel = files[refKey];
22
- if (!rel)
53
+ const rel = Object.prototype.hasOwnProperty.call(files, refKey) ? files[refKey] : undefined;
54
+ if (!rel || typeof rel !== "string") {
23
55
  throw new VibecodeError("CONTRACT_INVALID", `Reference artifact ${refKey} not found in contract.artifacts.files`);
56
+ }
57
+ if (STRICT_CONTROL_CHARS_RE.test(rel) ||
58
+ path.isAbsolute(rel) ||
59
+ /^[A-Za-z]:/.test(rel) ||
60
+ isInsideVaultDirectory(rel)) {
61
+ throw new VibecodeError("CONFIG_INVALID", "Reference artifact path must remain inside .vibecode/artifacts and outside vault directories.");
62
+ }
63
+ const { artifactsDir } = resolveWorkspace(ctx.cwd);
24
64
  const abs = artifactPath(rel, ctx.cwd);
65
+ if (!isPathWithinDir(abs, artifactsDir, { allowEqual: false }) || isInsideVaultDirectory(abs)) {
66
+ throw new VibecodeError("CONFIG_INVALID", "Reference artifact path must remain inside .vibecode/artifacts and outside vault directories.");
67
+ }
25
68
  if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
26
- throw new VibecodeError("CONTRACT_NOT_FOUND", `Reference artifact missing on disk: ${rel}`);
69
+ throw new VibecodeError("CONTRACT_NOT_FOUND", `Reference artifact missing on disk: ${redactSensitiveText(rel)}`);
70
+ }
71
+ try {
72
+ const realArtifacts = fs.realpathSync(artifactsDir);
73
+ const realAbs = fs.realpathSync(abs);
74
+ if (!isPathWithinDir(realAbs, realArtifacts, { allowEqual: false }) || isInsideVaultDirectory(realAbs)) {
75
+ throw new VibecodeError("CONFIG_INVALID", "Reference artifact symlink must remain inside .vibecode/artifacts and outside vault directories.");
76
+ }
77
+ }
78
+ catch (err) {
79
+ if (err instanceof VibecodeError)
80
+ throw err;
81
+ throw new VibecodeError("CONFIG_INVALID", "Reference artifact path could not be verified safely.");
27
82
  }
28
83
  return { refKey, rel, abs };
29
84
  }
30
85
  async function captureUrlScreenshot(url, ctx, deps) {
31
86
  const explicitPw = Object.prototype.hasOwnProperty.call(deps, "playwright") ? deps.playwright : undefined;
32
- const pw = explicitPw === null ? null : (explicitPw || (await loadPlaywright(deps)));
87
+ const pw = explicitPw === null ? null : (explicitPw || (await loadPlaywright({ ...deps, cwd: ctx.cwd })));
33
88
  if (!pw) {
34
89
  throw new VibecodeError("ADAPTER_MISSING", "Cannot capture URL target as image without Playwright", {
35
90
  adapter: "playwright",
@@ -37,16 +92,24 @@ async function captureUrlScreenshot(url, ctx, deps) {
37
92
  fallbackHint: "Provide a PNG screenshot path as --target instead of a URL."
38
93
  });
39
94
  }
40
- const browser = await pw.chromium.launch({ headless: true });
95
+ const browser = await launchBrowser(pw, { featureName: "Image URL capture" });
41
96
  try {
42
97
  const viewport = ctx.viewport || { width: 1280, height: 720 };
43
98
  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;
99
+ try {
100
+ await page.goto(url, { waitUntil: "networkidle", timeout: 15000 });
101
+ const outDir = path.join(ctx.cacheDir || path.join(ctx.cwd || process.cwd(), ".vibecode", "cache"), "captures");
102
+ ensureDir(outDir);
103
+ const outPath = path.join(outDir, `${invariantSafeName(ctx.currentInvariantId || "capture")}.png`);
104
+ await page.screenshot({ path: outPath, fullPage: false });
105
+ return outPath;
106
+ }
107
+ finally {
108
+ try {
109
+ await page.close?.();
110
+ }
111
+ catch { /* ignore */ }
112
+ }
50
113
  }
51
114
  finally {
52
115
  try {
@@ -62,14 +125,32 @@ async function resolveCandidatePath(invariant, ctx, deps) {
62
125
  const target = ctx.target;
63
126
  if (!target)
64
127
  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);
128
+ const trimmed = target.trim();
129
+ const looksLikeUriScheme = /^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !/^[a-z]:[\\/]/i.test(trimmed);
130
+ if (/^https?:\/\//i.test(trimmed) || looksLikeUriScheme || trimmed.startsWith("//")) {
131
+ let targetUrl;
132
+ try {
133
+ const baseUrl = parseSafeHttpBaseUrl(trimmed);
134
+ if (typeof invariant.input?.urlPath === "string" && invariant.input.urlPath) {
135
+ targetUrl = resolveSafeTargetUrl(invariant.input.urlPath, baseUrl.toString()).toString();
136
+ }
137
+ else {
138
+ targetUrl = /^https?:\/\//i.test(trimmed) ? trimmed : baseUrl.toString();
139
+ }
140
+ }
141
+ catch (err) {
142
+ throw new VibecodeError("CONFIG_INVALID", redactSensitiveText(`Invalid image target URL: ${errorMessage(err)}`));
143
+ }
144
+ return captureUrlScreenshot(targetUrl, { ...ctx, currentInvariantId: invariant.id }, deps);
67
145
  }
68
146
  const abs = path.resolve(ctx.cwd || process.cwd(), target);
147
+ if (isInsideVaultDirectory(abs)) {
148
+ throw new VibecodeError("CONFIG_INVALID", "Target image path must not point inside a holdout vault directory.");
149
+ }
69
150
  if (!fs.existsSync(abs))
70
- throw new VibecodeError("TARGET_MISSING", `Target image not found: ${target}`);
151
+ throw new VibecodeError("TARGET_MISSING", `Target image not found: ${redactSensitiveText(target)}`);
71
152
  if (fs.statSync(abs).isDirectory()) {
72
- throw new VibecodeError("UNSUPPORTED_FORMAT", `Target image path is a directory: ${target}`);
153
+ throw new VibecodeError("UNSUPPORTED_FORMAT", `Target image path is a directory: ${redactSensitiveText(target)}`);
73
154
  }
74
155
  return abs;
75
156
  }
@@ -134,17 +215,24 @@ async function verifyLayout(invariant, ctx, deps) {
134
215
  assertValidPngHeaderIfPng(candPath);
135
216
  const expected = invariant.expected || {};
136
217
  const tolerance = invariant.tolerance || {};
218
+ const mode = ctx.mode ?? "exact";
219
+ const skipPalette = mode === "reskin" || mode === "structural";
220
+ const runWcag = mode === "reskin" || expected.wcagLevel !== undefined;
137
221
  const expectedPalette = Array.isArray(expected.palette) ? expected.palette : [];
138
222
  const expectedRegions = Array.isArray(expected.regions) ? expected.regions : [];
223
+ const expectedTypography = Array.isArray(expected.typographyHierarchy) ? expected.typographyHierarchy : [];
139
224
  const hasPalette = expectedPalette.length > 0;
140
225
  const hasRegions = expectedRegions.length > 0;
141
- const needsPixels = Boolean(expected.nonBlank) || hasPalette || hasRegions;
226
+ const hasTypography = expectedTypography.length > 0;
227
+ const needsPixels = Boolean(expected.nonBlank) || (hasPalette && !skipPalette) || hasRegions || runWcag;
142
228
  if (!needsPixels) {
143
229
  const refDims = readImageDimensions(fs.readFileSync(refPath));
144
230
  const candDims = readImageDimensions(fs.readFileSync(candPath));
145
231
  if (refDims && candDims && candDims.width > 0 && candDims.height > 0) {
146
232
  const failures = checkDimensions(expected.dimensions, { width: candDims.width, height: candDims.height });
147
233
  const metrics = {
234
+ referencePath: refPath,
235
+ candidatePath: candPath,
148
236
  reference: { width: refDims.width, height: refDims.height },
149
237
  candidate: { width: candDims.width, height: candDims.height },
150
238
  ...(failures.length ? { dimensionMismatch: true } : {})
@@ -156,7 +244,10 @@ async function verifyLayout(invariant, ctx, deps) {
156
244
  const refImg = await decodeCached(refPath, ctx, deps);
157
245
  const candImg = await decodeCached(candPath, ctx, deps);
158
246
  const failures = [];
247
+ const diff = {};
159
248
  const metrics = {
249
+ referencePath: refPath,
250
+ candidatePath: candPath,
160
251
  reference: { width: refImg.width, height: refImg.height },
161
252
  candidate: { width: candImg.width, height: candImg.height }
162
253
  };
@@ -190,10 +281,10 @@ async function verifyLayout(invariant, ctx, deps) {
190
281
  }
191
282
  metrics.nonBlank = !failures.some((f) => f.includes("blank"));
192
283
  }
193
- // Soft metrics: palette/regions
284
+ // Soft metrics: palette/regions/typography/WCAG
194
285
  let paletteSimilarity = 1;
195
286
  let regionIoU = 1;
196
- if (hasPalette) {
287
+ if (hasPalette && !skipPalette) {
197
288
  const candPalette = extractPalette(candImg, expectedPalette.length);
198
289
  paletteSimilarity = comparePalettes(expectedPalette, candPalette);
199
290
  metrics.paletteSimilarity = paletteSimilarity;
@@ -211,12 +302,30 @@ async function verifyLayout(invariant, ctx, deps) {
211
302
  if (regionIoU < minIoU)
212
303
  failures.push(`regionIoU ${regionIoU.toFixed(3)} < ${minIoU}`);
213
304
  }
305
+ if (mode === "reskin" && hasTypography) {
306
+ const candTypography = estimateTypographyBands(candImg);
307
+ metrics.typographyHierarchy = candTypography;
308
+ if (candTypography.length === 0) {
309
+ failures.push("typography structure missing (expected typography bands, found 0)");
310
+ }
311
+ }
312
+ const wcag = runWcag
313
+ ? applyWcagAudit(candImg, expected.wcagLevel ?? "AA", failures, metrics, diff)
314
+ : null;
315
+ const wcagScore = wcagAuditScore(wcag);
316
+ const hasDiff = Object.keys(diff).length > 0;
214
317
  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.
318
+ // Hard dimension mismatch should fail; soft palette/region/WCAG also fail when invoked as soft invariant under strict gate handled by scorer.
216
319
  // Status here is pass/fail; scorer applies severity/gate.
217
- return { status: "fail", score: invariant.severity === "hard" ? 0 : Math.min(paletteSimilarity, regionIoU), failures, metrics };
320
+ return {
321
+ status: "fail",
322
+ score: invariant.severity === "hard" ? 0 : Math.min(paletteSimilarity, regionIoU, wcagScore),
323
+ failures,
324
+ metrics,
325
+ ...(hasDiff ? { diff } : {})
326
+ };
218
327
  }
219
- const score = invariant.severity === "hard" ? 1 : Math.min(paletteSimilarity, regionIoU);
328
+ const score = invariant.severity === "hard" ? 1 : Math.min(paletteSimilarity, regionIoU, wcagScore);
220
329
  return { status: "pass", score, failures: [], metrics };
221
330
  }
222
331
  async function verifyPerceptual(invariant, ctx, deps) {
@@ -224,7 +333,39 @@ async function verifyPerceptual(invariant, ctx, deps) {
224
333
  const candPath = await resolveCandidatePath(invariant, ctx, deps);
225
334
  assertValidPngHeaderIfPng(refPath);
226
335
  assertValidPngHeaderIfPng(candPath);
336
+ const expected = invariant.expected || {};
227
337
  const tolerance = invariant.tolerance || {};
338
+ const mode = ctx.mode ?? "exact";
339
+ if (mode === "reskin") {
340
+ const candImg = await decodeCached(candPath, ctx, deps);
341
+ const failures = [];
342
+ const diff = {};
343
+ const metrics = {
344
+ referencePath: refPath,
345
+ candidatePath: candPath,
346
+ candidate: { width: candImg.width, height: candImg.height },
347
+ mode: "reskin"
348
+ };
349
+ const dimFailures = checkDimensions(expected.dimensions, { width: candImg.width, height: candImg.height });
350
+ if (dimFailures.length > 0) {
351
+ failures.push(...dimFailures);
352
+ metrics.dimensionMismatch = true;
353
+ }
354
+ const wcag = applyWcagAudit(candImg, expected.wcagLevel ?? "AA", failures, metrics, diff);
355
+ const hasDiff = Object.keys(diff).length > 0;
356
+ const score = failures.length === 0
357
+ ? 1
358
+ : dimFailures.length > 0 || invariant.severity === "hard"
359
+ ? 0
360
+ : wcagAuditScore(wcag);
361
+ return {
362
+ status: failures.length > 0 ? "fail" : "pass",
363
+ score,
364
+ failures,
365
+ metrics,
366
+ ...(hasDiff ? { diff } : {})
367
+ };
368
+ }
228
369
  const refImg = await decodeCached(refPath, ctx, deps);
229
370
  const candImg = await decodeCached(candPath, ctx, deps);
230
371
  const minSSIM = typeof tolerance.minSSIM === "number" ? tolerance.minSSIM : 0.85;
@@ -241,6 +382,8 @@ async function verifyPerceptual(invariant, ctx, deps) {
241
382
  if (diffRes.diffRatio > maxPixelDiffRatio)
242
383
  failures.push(`diffRatio ${diffRes.diffRatio.toFixed(4)} > ${maxPixelDiffRatio}`);
243
384
  const metrics = {
385
+ referencePath: refPath,
386
+ candidatePath: candPath,
244
387
  ssim: ssimRes.ssim,
245
388
  diffRatio: diffRes.diffRatio,
246
389
  diffPixels: diffRes.diffPixels,
@@ -250,24 +393,31 @@ async function verifyPerceptual(invariant, ctx, deps) {
250
393
  candidateHash: candHash,
251
394
  dimensionMismatch: ssimRes.dimensionMismatch || diffRes.dimensionMismatch
252
395
  };
396
+ const diff = {};
397
+ const wcag = expected.wcagLevel !== undefined
398
+ ? applyWcagAudit(candImg, expected.wcagLevel, failures, metrics, diff)
399
+ : null;
253
400
  let diffArtifact = null;
254
401
  if (failures.length > 0) {
255
402
  try {
256
403
  diffArtifact = writeDiffArtifact(diffRes.diffMask, invariant, ctx);
257
404
  metrics.diffPng = diffArtifact;
405
+ diff.diffPng = diffArtifact;
258
406
  }
259
407
  catch {
260
408
  // ignore diff write failures
261
409
  }
262
410
  }
263
411
  // 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)));
412
+ const baseScore = Math.max(0, Math.min(1, (ssimRes.ssim * 0.7) + ((1 - diffRes.diffRatio) * 0.3)));
413
+ const score = wcag && !wcag.passed ? Math.min(baseScore, wcagAuditScore(wcag)) : baseScore;
414
+ const hasDiff = Object.keys(diff).length > 0;
265
415
  return {
266
416
  status: failures.length > 0 ? "fail" : "pass",
267
417
  score,
268
418
  failures,
269
419
  metrics,
270
- ...(diffArtifact ? { diff: { diffPng: diffArtifact } } : {})
420
+ ...(hasDiff ? { diff } : {})
271
421
  };
272
422
  }
273
423
  export async function verifyInvariant(invariant, ctx, deps = {}) {
@@ -1,4 +1,6 @@
1
1
  import type { ContractV02, Invariant, InvariantResult, OracleContext, OracleFn, ParityReport, VerifyDeps } from "../core/types.js";
2
2
  export declare function getOracle(type: string): Promise<OracleFn | null>;
3
+ /** Deep, cycle-safe, depth-bounded runtime-var scrub of every string (values and keys) in any JSON-like value. */
4
+ export declare function redactRuntimeVarsDeep<T>(value: T, vars?: Record<string, string>): T;
3
5
  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>;
6
+ export declare function verifyContract(contract: ContractV02, rawCtx: OracleContext, deps?: VerifyDeps): Promise<ParityReport>;
@@ -1,5 +1,14 @@
1
- import { scoreReport } from "../core/parity.js";
2
- import { errorMessage, toDiagnostic } from "../core/errors.js";
1
+ import { scoreReport, redactHoldoutResult } from "../core/parity.js";
2
+ import { evaluateAntiCheat } from "../core/anti-cheat.js";
3
+ import { loadReplayCache, lookupCachedResult, saveReplayCache, storeCachedResult } from "../core/cache.js";
4
+ import { runWithFixtures } from "../core/fixtures.js";
5
+ import { readHoldouts } from "../core/store.js";
6
+ import { VibecodeError, errorMessage, toDiagnostic } from "../core/errors.js";
7
+ import { redactDeepValue, redactSensitiveText } from "../core/security.js";
8
+ import { normalizeConcurrency, runBoundedParallel } from "../core/scheduler.js";
9
+ import { VALID_VERIFY_MODES, applyVerifyModeToInvariant } from "../core/visual-semantic.js";
10
+ import { redactRuntimeVars, resolveTargetForInvariant, validateRuntimeVarsObject, validateTargetMapObject } from "../core/target-map.js";
11
+ import { createDefaultPluginRegistry } from "../plugins/builtins.js";
3
12
  import { verifyInvariant as verifyCli } from "./cli.js";
4
13
  const DIRECT = {
5
14
  command: verifyCli
@@ -10,10 +19,22 @@ const LAZY = {
10
19
  web_route: async () => (await import("./web.js")).verifyInvariant,
11
20
  web_flow: async () => (await import("./web.js")).verifyInvariant,
12
21
  web_network: async () => (await import("./web.js")).verifyInvariant,
22
+ web_ui_states: async () => (await import("./ui-states.js")).verifyInvariant,
13
23
  http: async () => (await import("./api-repo.js")).verifyInvariant,
24
+ http_workflow: async () => (await import("./http-workflow.js")).verifyHttpWorkflow,
25
+ http_stream: async () => (await import("./stream.js")).verifyHttpStream,
26
+ ws_protocol: async () => (await import("./stream.js")).verifyWsProtocol,
27
+ perf_budget: async () => (await import("./perf-budget.js")).verifyInvariant,
14
28
  repo_exports: async () => (await import("./api-repo.js")).verifyInvariant,
15
29
  video_timeline: async () => (await import("./video.js")).verifyInvariant
16
30
  };
31
+ let defaultPluginRegistry = null;
32
+ function getDefaultPluginRegistry() {
33
+ if (!defaultPluginRegistry) {
34
+ defaultPluginRegistry = createDefaultPluginRegistry();
35
+ }
36
+ return defaultPluginRegistry;
37
+ }
17
38
  export async function getOracle(type) {
18
39
  if (DIRECT[type])
19
40
  return DIRECT[type];
@@ -22,10 +43,115 @@ export async function getOracle(type) {
22
43
  }
23
44
  return null;
24
45
  }
25
- export async function verifyInvariant(invariant, ctx, deps = {}) {
46
+ const MAX_SCRUB_DEPTH = 32;
47
+ const PRESERVE_HASH_KEYS = new Set(["candidateOutputHash"]);
48
+ function hasRuntimeVars(ctx) {
49
+ return Boolean(ctx.vars && typeof ctx.vars === "object" && Object.keys(ctx.vars).length > 0);
50
+ }
51
+ function hasConfiguredContractFixtures(fixtures) {
52
+ if (!fixtures || typeof fixtures !== "object")
53
+ return false;
54
+ return Boolean((Array.isArray(fixtures.seedFiles) && fixtures.seedFiles.length > 0) ||
55
+ (Array.isArray(fixtures.snapshotPaths) && fixtures.snapshotPaths.length > 0) ||
56
+ (Array.isArray(fixtures.httpSetup) && fixtures.httpSetup.length > 0) ||
57
+ (Array.isArray(fixtures.httpTeardown) && fixtures.httpTeardown.length > 0) ||
58
+ (Array.isArray(fixtures.commandSetup) && fixtures.commandSetup.length > 0) ||
59
+ (Array.isArray(fixtures.commandTeardown) && fixtures.commandTeardown.length > 0));
60
+ }
61
+ /** Validate optional ctx.targets / ctx.vars once, returning a context holding validated copies. */
62
+ function normalizeRuntimeContext(ctx) {
63
+ if (ctx.targets === undefined && ctx.vars === undefined)
64
+ return ctx;
65
+ return {
66
+ ...ctx,
67
+ ...(ctx.targets !== undefined ? { targets: validateTargetMapObject(ctx.targets) } : {}),
68
+ ...(ctx.vars !== undefined ? { vars: validateRuntimeVarsObject(ctx.vars) } : {})
69
+ };
70
+ }
71
+ /** Context whose `target` is the per-invariant resolved target (domain override or fallback). */
72
+ function contextForInvariant(invariant, ctx) {
73
+ if (!ctx.targets)
74
+ return ctx;
75
+ return { ...ctx, target: resolveTargetForInvariant(invariant, ctx) ?? "" };
76
+ }
77
+ /** Deep, cycle-safe, depth-bounded runtime-var scrub of every string (values and keys) in any JSON-like value. */
78
+ export function redactRuntimeVarsDeep(value, vars) {
79
+ if (!vars || typeof vars !== "object" || Object.keys(vars).length === 0)
80
+ return value;
81
+ return scrubRuntimeValue(value, vars);
82
+ }
83
+ /** Cycle-safe, depth-bounded deep scrub of every string (values and keys) with runtime var redaction. */
84
+ function scrubRuntimeValue(value, vars) {
85
+ return redactDeepValue(value, {
86
+ maxDepth: MAX_SCRUB_DEPTH,
87
+ redactText: (s) => redactRuntimeVars(s, vars),
88
+ preserveKeys: PRESERVE_HASH_KEYS
89
+ });
90
+ }
91
+ /** Scrub runtime var values from every free-text field of a result (failures/reason/diagnostic/diff/metrics). */
92
+ function scrubRuntimeResult(result, ctx) {
93
+ if (!hasRuntimeVars(ctx))
94
+ return result;
95
+ const vars = ctx.vars;
96
+ const out = { ...result };
97
+ for (const key of ["id", "repro", "failures", "reason", "diagnostic", "diff", "metrics"]) {
98
+ if (result[key] !== undefined)
99
+ out[key] = scrubRuntimeValue(result[key], vars);
100
+ }
101
+ return out;
102
+ }
103
+ async function executeInvariantRaw(invariant, ctx, deps = {}) {
104
+ return scrubRuntimeResult(await executeInvariantUnscrubbed(invariant, ctx, deps), ctx);
105
+ }
106
+ async function executeInvariantUnscrubbed(invariant, baseCtx, deps = {}) {
26
107
  const started = Date.now();
27
- const fn = await getOracle(invariant.type);
108
+ const mode = baseCtx.mode ?? "exact";
109
+ const decision = applyVerifyModeToInvariant(invariant, mode);
110
+ if (!decision.shouldRun) {
111
+ return {
112
+ id: invariant.id,
113
+ type: invariant.type,
114
+ severity: invariant.severity,
115
+ status: "skipped",
116
+ score: 0,
117
+ failures: [],
118
+ reason: decision.skipReason ?? `Skipped in ${mode} verification mode`,
119
+ durationMs: Date.now() - started
120
+ };
121
+ }
122
+ const effectiveInvariant = decision.adjustedInvariant;
123
+ const ctx = contextForInvariant(effectiveInvariant, baseCtx);
124
+ const fn = await getOracle(effectiveInvariant.type);
28
125
  if (!fn) {
126
+ if (typeof effectiveInvariant.type === "string" && effectiveInvariant.type.startsWith("plugin_")) {
127
+ const registry = ctx.pluginRegistry ?? getDefaultPluginRegistry();
128
+ const outcome = await registry.runOracle(effectiveInvariant, ctx, deps);
129
+ if (!outcome) {
130
+ return {
131
+ id: invariant.id,
132
+ type: invariant.type,
133
+ severity: invariant.severity,
134
+ status: "skipped",
135
+ score: 0,
136
+ failures: [],
137
+ reason: `No plugin registered for invariant type: ${invariant.type}`,
138
+ durationMs: Date.now() - started
139
+ };
140
+ }
141
+ return {
142
+ id: invariant.id,
143
+ type: invariant.type,
144
+ severity: invariant.severity,
145
+ status: outcome.status || "fail",
146
+ score: typeof outcome.score === "number" ? outcome.score : (outcome.status === "pass" ? 1 : 0),
147
+ ...(outcome.failures ? { failures: outcome.failures } : {}),
148
+ ...(outcome.reason ? { reason: outcome.reason } : {}),
149
+ ...(outcome.diff ? { diff: outcome.diff } : {}),
150
+ ...(outcome.metrics ? { metrics: outcome.metrics } : {}),
151
+ ...(outcome.diagnostic ? { diagnostic: outcome.diagnostic } : {}),
152
+ durationMs: Date.now() - started
153
+ };
154
+ }
29
155
  return {
30
156
  id: invariant.id,
31
157
  type: invariant.type,
@@ -38,7 +164,7 @@ export async function verifyInvariant(invariant, ctx, deps = {}) {
38
164
  };
39
165
  }
40
166
  try {
41
- const result = await fn(invariant, ctx, deps);
167
+ const result = await fn(effectiveInvariant, ctx, deps);
42
168
  return {
43
169
  id: invariant.id,
44
170
  type: invariant.type,
@@ -46,6 +172,7 @@ export async function verifyInvariant(invariant, ctx, deps = {}) {
46
172
  status: result.status || "fail",
47
173
  score: typeof result.score === "number" ? result.score : (result.status === "pass" ? 1 : 0),
48
174
  ...(result.failures ? { failures: result.failures } : {}),
175
+ ...(result.reason ? { reason: result.reason } : {}),
49
176
  ...(result.diff ? { diff: result.diff } : {}),
50
177
  ...(result.metrics ? { metrics: result.metrics } : {}),
51
178
  ...(result.diagnostic ? { diagnostic: result.diagnostic } : {}),
@@ -53,7 +180,13 @@ export async function verifyInvariant(invariant, ctx, deps = {}) {
53
180
  };
54
181
  }
55
182
  catch (err) {
56
- const diag = toDiagnostic(err);
183
+ const rawDiag = toDiagnostic(err);
184
+ const diag = {
185
+ ...rawDiag,
186
+ message: redactSensitiveText(rawDiag.message),
187
+ ...(rawDiag.installHint !== undefined ? { installHint: redactSensitiveText(rawDiag.installHint) } : {}),
188
+ ...(rawDiag.fallbackHint !== undefined ? { fallbackHint: redactSensitiveText(rawDiag.fallbackHint) } : {})
189
+ };
57
190
  if (diag.code === "ADAPTER_MISSING") {
58
191
  return {
59
192
  id: invariant.id,
@@ -73,19 +206,115 @@ export async function verifyInvariant(invariant, ctx, deps = {}) {
73
206
  severity: invariant.severity,
74
207
  status: "fail",
75
208
  score: 0,
76
- failures: [errorMessage(err)],
209
+ failures: [redactSensitiveText(errorMessage(err))],
77
210
  diagnostic: diag,
78
211
  durationMs: Date.now() - started
79
212
  };
80
213
  }
81
214
  }
82
- export async function verifyContract(contract, ctx, deps = {}) {
83
- const results = [];
215
+ export async function verifyInvariant(invariant, ctx, deps = {}) {
216
+ const normCtx = normalizeRuntimeContext(ctx);
217
+ const rawOutcome = await executeInvariantRaw(invariant, normCtx, deps);
218
+ return scrubRuntimeResult(redactHoldoutResult(invariant, rawOutcome, Boolean(normCtx.revealHoldouts)), normCtx);
219
+ }
220
+ export async function verifyContract(contract, rawCtx, deps = {}) {
221
+ const ctx = normalizeRuntimeContext(rawCtx);
222
+ const mode = ctx.mode ?? "exact";
223
+ if (!VALID_VERIFY_MODES.has(mode)) {
224
+ throw new VibecodeError("CONFIG_INVALID", `Invalid verify mode: ${String(mode)} (expected one of ${[...VALID_VERIFY_MODES].join(", ")})`);
225
+ }
226
+ const concurrency = normalizeConcurrency(ctx.concurrency);
227
+ const mergedInvariants = [...(contract.invariants || [])];
228
+ if (ctx.cwd) {
229
+ const seen = new Set(mergedInvariants.map((inv) => inv.id));
230
+ for (const inv of readHoldouts(ctx.cwd)) {
231
+ if (!seen.has(inv.id)) {
232
+ seen.add(inv.id);
233
+ mergedInvariants.push(inv);
234
+ }
235
+ }
236
+ }
84
237
  const ids = Array.isArray(ctx.invariantIds) && ctx.invariantIds.length ? new Set(ctx.invariantIds) : null;
85
- for (const inv of contract.invariants || []) {
86
- if (ids && !ids.has(inv.id))
87
- continue;
88
- results.push(await verifyInvariant(inv, ctx, deps));
238
+ const evaluatedInvariants = mergedInvariants.filter((inv) => !ids || ids.has(inv.id));
239
+ const shouldRunFixtures = contract.fixtures !== undefined && !ctx.skipFixtures;
240
+ const fixturesActive = shouldRunFixtures && hasConfiguredContractFixtures(contract.fixtures);
241
+ // Runtime vars (secrets) and stateful contract fixtures bypass the replay cache so secrets
242
+ // never taint .vibecode/cache.json and mutated fixture states never replay stale passes.
243
+ const useReplayCache = Boolean(ctx.useCache && ctx.cwd && mode === "exact" && !hasRuntimeVars(ctx) && !fixturesActive);
244
+ const executeEvaluation = async () => {
245
+ const replayCache = useReplayCache && ctx.cwd ? loadReplayCache(ctx.cwd) : null;
246
+ // Perform replay-cache lookups sequentially before launching bounded parallel workers
247
+ // so replayCache is never mutated concurrently.
248
+ const cachedByIndex = new Map();
249
+ for (let i = 0; i < evaluatedInvariants.length; i++) {
250
+ const inv = evaluatedInvariants[i];
251
+ if (inv.type === "perf_budget")
252
+ continue;
253
+ if (typeof inv.type === "string" && inv.type.startsWith("plugin_")) {
254
+ const registry = ctx.pluginRegistry ?? getDefaultPluginRegistry();
255
+ if (!registry.getOracle(inv.type))
256
+ continue;
257
+ }
258
+ const hit = replayCache ? lookupCachedResult(replayCache, inv, contextForInvariant(inv, ctx)) : null;
259
+ if (hit)
260
+ cachedByIndex.set(i, hit);
261
+ }
262
+ const executionRecords = await runBoundedParallel(evaluatedInvariants, async (inv, idx) => {
263
+ const cached = cachedByIndex.get(idx);
264
+ if (cached)
265
+ return { rawOutcome: cached, fromCache: true };
266
+ const rawOutcome = await executeInvariantRaw(inv, ctx, deps);
267
+ return { rawOutcome, fromCache: false };
268
+ }, { concurrency });
269
+ const results = [];
270
+ const candidateHashes = new Map();
271
+ let cacheDirty = false;
272
+ for (let i = 0; i < evaluatedInvariants.length; i++) {
273
+ const inv = evaluatedInvariants[i];
274
+ const { rawOutcome, fromCache } = executionRecords[i];
275
+ if (!fromCache &&
276
+ inv.type !== "perf_budget" &&
277
+ replayCache &&
278
+ storeCachedResult(replayCache, inv, contextForInvariant(inv, ctx), rawOutcome)) {
279
+ cacheDirty = true;
280
+ }
281
+ const rawHash = rawOutcome.metrics?.candidateOutputHash;
282
+ if (typeof rawHash === "string" && rawHash.length > 0) {
283
+ candidateHashes.set(inv.id, rawHash);
284
+ }
285
+ results.push(scrubRuntimeResult(redactHoldoutResult(inv, rawOutcome, Boolean(ctx.revealHoldouts)), ctx));
286
+ }
287
+ if (replayCache && cacheDirty && ctx.cwd) {
288
+ saveReplayCache(ctx.cwd, replayCache);
289
+ }
290
+ const antiCheat = evaluateAntiCheat(evaluatedInvariants, results, candidateHashes);
291
+ return scoreReport({ ...contract, invariants: mergedInvariants }, results, {
292
+ strict: Boolean(ctx.strict),
293
+ antiCheat
294
+ });
295
+ };
296
+ if (!shouldRunFixtures) {
297
+ return executeEvaluation();
298
+ }
299
+ const fixtureOpts = {
300
+ cwd: ctx.cwd ?? process.cwd(),
301
+ target: ctx.target,
302
+ ...(ctx.targets ? { targets: ctx.targets } : {}),
303
+ ...(ctx.vars ? { vars: ctx.vars } : {}),
304
+ ...(ctx.headers ? { headers: ctx.headers } : {}),
305
+ allowCommandHooks: Boolean(ctx.allowFixtureCommands),
306
+ skipFixtures: Boolean(ctx.skipFixtures),
307
+ ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {})
308
+ };
309
+ const { result: report, fixtureSummary } = await runWithFixtures(contract.fixtures, fixtureOpts, executeEvaluation);
310
+ if (!fixtureSummary.applied) {
311
+ return report;
89
312
  }
90
- return scoreReport(contract, results, { strict: Boolean(ctx.strict) });
313
+ const safeSummary = hasRuntimeVars(ctx)
314
+ ? scrubRuntimeValue(fixtureSummary, ctx.vars)
315
+ : fixtureSummary;
316
+ return {
317
+ ...report,
318
+ fixtureSummary: safeSummary
319
+ };
91
320
  }