vibecode-anything 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +407 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +2519 -0
- package/dist/core/adapters.d.ts +31 -0
- package/dist/core/adapters.js +478 -0
- package/dist/core/agent-adapter.d.ts +67 -0
- package/dist/core/agent-adapter.js +312 -0
- package/dist/core/anti-cheat.d.ts +6 -0
- package/dist/core/anti-cheat.js +372 -0
- package/dist/core/badge.d.ts +18 -0
- package/dist/core/badge.js +360 -0
- package/dist/core/cache.d.ts +47 -0
- package/dist/core/cache.js +403 -0
- package/dist/core/ci-export.d.ts +35 -0
- package/dist/core/ci-export.js +796 -0
- package/dist/core/ci-formats.d.ts +21 -0
- package/dist/core/ci-formats.js +388 -0
- package/dist/core/client-codegen.d.ts +36 -0
- package/dist/core/client-codegen.js +2538 -0
- package/dist/core/compose.d.ts +71 -0
- package/dist/core/compose.js +1088 -0
- package/dist/core/diff.d.ts +10 -0
- package/dist/core/diff.js +207 -0
- package/dist/core/docs-export.d.ts +37 -0
- package/dist/core/docs-export.js +2706 -0
- package/dist/core/doctor.d.ts +70 -0
- package/dist/core/doctor.js +525 -0
- package/dist/core/errors.d.ts +32 -0
- package/dist/core/errors.js +81 -0
- package/dist/core/exec.d.ts +38 -0
- package/dist/core/exec.js +336 -0
- package/dist/core/fixtures.d.ts +153 -0
- package/dist/core/fixtures.js +2245 -0
- package/dist/core/format.d.ts +77 -0
- package/dist/core/format.js +632 -0
- package/dist/core/fs-snapshot.d.ts +37 -0
- package/dist/core/fs-snapshot.js +216 -0
- package/dist/core/graphql-export.d.ts +34 -0
- package/dist/core/graphql-export.js +2482 -0
- package/dist/core/har-export.d.ts +29 -0
- package/dist/core/har-export.js +988 -0
- package/dist/core/html-report.d.ts +27 -0
- package/dist/core/html-report.js +1535 -0
- package/dist/core/http-export.d.ts +31 -0
- package/dist/core/http-export.js +726 -0
- package/dist/core/impact.d.ts +80 -0
- package/dist/core/impact.js +1412 -0
- package/dist/core/lint.d.ts +38 -0
- package/dist/core/lint.js +1111 -0
- package/dist/core/load-export.d.ts +37 -0
- package/dist/core/load-export.js +1813 -0
- package/dist/core/mcp-export.d.ts +35 -0
- package/dist/core/mcp-export.js +1736 -0
- package/dist/core/mock-server.d.ts +47 -0
- package/dist/core/mock-server.js +1722 -0
- package/dist/core/openapi-export.d.ts +44 -0
- package/dist/core/openapi-export.js +1074 -0
- package/dist/core/parity.d.ts +14 -0
- package/dist/core/parity.js +173 -0
- package/dist/core/playwright-exporter.d.ts +23 -0
- package/dist/core/playwright-exporter.js +1343 -0
- package/dist/core/png.d.ts +7 -0
- package/dist/core/png.js +339 -0
- package/dist/core/regression.d.ts +54 -0
- package/dist/core/regression.js +529 -0
- package/dist/core/responsive.d.ts +86 -0
- package/dist/core/responsive.js +606 -0
- package/dist/core/run.d.ts +74 -0
- package/dist/core/run.js +696 -0
- package/dist/core/scheduler.d.ts +24 -0
- package/dist/core/scheduler.js +162 -0
- package/dist/core/schema-export.d.ts +29 -0
- package/dist/core/schema-export.js +2215 -0
- package/dist/core/schema.d.ts +18 -0
- package/dist/core/schema.js +1057 -0
- package/dist/core/security.d.ts +233 -0
- package/dist/core/security.js +1839 -0
- package/dist/core/server-export.d.ts +38 -0
- package/dist/core/server-export.js +3198 -0
- package/dist/core/slices.d.ts +24 -0
- package/dist/core/slices.js +294 -0
- package/dist/core/spec-writer.d.ts +9 -0
- package/dist/core/spec-writer.js +1202 -0
- package/dist/core/store.d.ts +26 -0
- package/dist/core/store.js +217 -0
- package/dist/core/target-map.d.ts +34 -0
- package/dist/core/target-map.js +262 -0
- package/dist/core/test-exporter.d.ts +25 -0
- package/dist/core/test-exporter.js +1918 -0
- package/dist/core/types.d.ts +919 -0
- package/dist/core/types.js +4 -0
- package/dist/core/visual-semantic.d.ts +67 -0
- package/dist/core/visual-semantic.js +673 -0
- package/dist/core/visual.d.ts +34 -0
- package/dist/core/visual.js +508 -0
- package/dist/core/watch.d.ts +78 -0
- package/dist/core/watch.js +495 -0
- package/dist/core/yaml.d.ts +5 -0
- package/dist/core/yaml.js +1009 -0
- package/dist/diagnostics/diagnose.d.ts +53 -0
- package/dist/diagnostics/diagnose.js +1083 -0
- package/dist/diagnostics/flake.d.ts +71 -0
- package/dist/diagnostics/flake.js +608 -0
- package/dist/diagnostics/mutation-audit.d.ts +69 -0
- package/dist/diagnostics/mutation-audit.js +769 -0
- package/dist/diagnostics/spatial.d.ts +42 -0
- package/dist/diagnostics/spatial.js +346 -0
- package/dist/diagnostics/trends.d.ts +122 -0
- package/dist/diagnostics/trends.js +1190 -0
- package/dist/discovery/discover.d.ts +111 -0
- package/dist/discovery/discover.js +2017 -0
- package/dist/discovery/lock.d.ts +116 -0
- package/dist/discovery/lock.js +1505 -0
- package/dist/discovery/routes.d.ts +36 -0
- package/dist/discovery/routes.js +1494 -0
- package/dist/discovery/test-importer.d.ts +92 -0
- package/dist/discovery/test-importer.js +4952 -0
- package/dist/index.d.ts +123 -0
- package/dist/index.js +99 -0
- package/dist/ingestors/api-collections.d.ts +28 -0
- package/dist/ingestors/api-collections.js +2335 -0
- package/dist/ingestors/api-repo.d.ts +6 -0
- package/dist/ingestors/api-repo.js +1120 -0
- package/dist/ingestors/asyncapi.d.ts +26 -0
- package/dist/ingestors/asyncapi.js +2105 -0
- package/dist/ingestors/bridges.d.ts +5 -0
- package/dist/ingestors/bridges.js +1264 -0
- package/dist/ingestors/cli.d.ts +10 -0
- package/dist/ingestors/cli.js +454 -0
- package/dist/ingestors/curl.d.ts +14 -0
- package/dist/ingestors/curl.js +1024 -0
- package/dist/ingestors/graphql.d.ts +56 -0
- package/dist/ingestors/graphql.js +1852 -0
- package/dist/ingestors/http-file.d.ts +20 -0
- package/dist/ingestors/http-file.js +923 -0
- package/dist/ingestors/image.d.ts +2 -0
- package/dist/ingestors/image.js +147 -0
- package/dist/ingestors/index.d.ts +5 -0
- package/dist/ingestors/index.js +577 -0
- package/dist/ingestors/openrpc.d.ts +29 -0
- package/dist/ingestors/openrpc.js +1807 -0
- package/dist/ingestors/proto.d.ts +47 -0
- package/dist/ingestors/proto.js +2690 -0
- package/dist/ingestors/trace.d.ts +10 -0
- package/dist/ingestors/trace.js +599 -0
- package/dist/ingestors/video.d.ts +50 -0
- package/dist/ingestors/video.js +655 -0
- package/dist/ingestors/web.d.ts +40 -0
- package/dist/ingestors/web.js +839 -0
- package/dist/mcp/server.d.ts +2 -0
- package/dist/mcp/server.js +3969 -0
- package/dist/oracles/api-repo.d.ts +2 -0
- package/dist/oracles/api-repo.js +286 -0
- package/dist/oracles/cli.d.ts +2 -0
- package/dist/oracles/cli.js +205 -0
- package/dist/oracles/http-workflow.d.ts +68 -0
- package/dist/oracles/http-workflow.js +828 -0
- package/dist/oracles/image.d.ts +2 -0
- package/dist/oracles/image.js +429 -0
- package/dist/oracles/index.d.ts +6 -0
- package/dist/oracles/index.js +320 -0
- package/dist/oracles/perf-budget.d.ts +90 -0
- package/dist/oracles/perf-budget.js +1329 -0
- package/dist/oracles/stream.d.ts +94 -0
- package/dist/oracles/stream.js +1268 -0
- package/dist/oracles/ui-states.d.ts +49 -0
- package/dist/oracles/ui-states.js +894 -0
- package/dist/oracles/video.d.ts +21 -0
- package/dist/oracles/video.js +627 -0
- package/dist/oracles/web.d.ts +2 -0
- package/dist/oracles/web.js +871 -0
- package/dist/plugins/builtins.d.ts +12 -0
- package/dist/plugins/builtins.js +1052 -0
- package/dist/plugins/registry.d.ts +86 -0
- package/dist/plugins/registry.js +554 -0
- package/dist/setup/index.d.ts +7 -0
- package/dist/setup/index.js +298 -0
- package/package.json +54 -4
- package/skills/vibecode-anything/SKILL.md +75 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { FfmpegFrame, Invariant, OracleContext, OracleInvariantOutcome, VerifyDeps } from "../core/types.js";
|
|
2
|
+
interface AlignmentEntry {
|
|
3
|
+
stateIndex: number;
|
|
4
|
+
candidateIndex: number;
|
|
5
|
+
similarity: number;
|
|
6
|
+
}
|
|
7
|
+
/** Load ordered candidate frames from a frame directory, video file, or HTTP/HTTPS URL. */
|
|
8
|
+
export declare function loadCandidateFrames(target: string, ctx: OracleContext, deps?: VerifyDeps): Promise<FfmpegFrame[]>;
|
|
9
|
+
/**
|
|
10
|
+
* Strictly monotone (j_0 < j_1 < ... < j_{K-1}) maximum-score alignment.
|
|
11
|
+
* O(K * M) via running prefix maximum, exactly as specified for the video oracle.
|
|
12
|
+
*
|
|
13
|
+
* @returns {{ score: number, alignment: Array<{ stateIndex: number, candidateIndex: number, similarity: number }>, complete: boolean }}
|
|
14
|
+
*/
|
|
15
|
+
export declare function alignMonotone(similarity: readonly (readonly number[])[], floor?: number): {
|
|
16
|
+
score: number;
|
|
17
|
+
alignment: AlignmentEntry[];
|
|
18
|
+
complete: boolean;
|
|
19
|
+
};
|
|
20
|
+
export declare function verifyInvariant(invariant: Invariant, ctx: OracleContext, deps?: VerifyDeps): Promise<OracleInvariantOutcome>;
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,627 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { VibecodeError, errorMessage } from "../core/errors.js";
|
|
5
|
+
import { STRICT_CONTROL_CHARS_RE, isForbiddenObjectKey, isInsideVaultDirectory, isPathWithinDir, parseSafeHttpBaseUrl, redactSensitiveText } from "../core/security.js";
|
|
6
|
+
import { loadPlaywright, launchBrowser } from "../core/adapters.js";
|
|
7
|
+
import { artifactPath, ensureDir, resolveWorkspace } from "../core/store.js";
|
|
8
|
+
import { readImageDimensions } from "../core/png.js";
|
|
9
|
+
import { decodeImage, computeSSIM, computeDHash, hammingDistanceHex, comparePalettes, bboxIoU } from "../core/visual.js";
|
|
10
|
+
import { VIDEO_EXTS, IMAGE_EXTS, listFrameFiles, resolveFfmpegAdapter, extractVideoFrames, ffmpegMissingError, extractStates, changedRegionBetween } from "../ingestors/video.js";
|
|
11
|
+
const depObjectIds = new WeakMap();
|
|
12
|
+
let nextDepObjectId = 1;
|
|
13
|
+
function shortHash(input) {
|
|
14
|
+
return crypto.createHash("sha256").update(input).digest("hex").slice(0, 12);
|
|
15
|
+
}
|
|
16
|
+
function depValueToken(value) {
|
|
17
|
+
if (value === undefined)
|
|
18
|
+
return "u";
|
|
19
|
+
if (value === null)
|
|
20
|
+
return "n";
|
|
21
|
+
if (typeof value === "object" || typeof value === "function") {
|
|
22
|
+
let id = depObjectIds.get(value);
|
|
23
|
+
if (id === undefined) {
|
|
24
|
+
id = nextDepObjectId++;
|
|
25
|
+
depObjectIds.set(value, id);
|
|
26
|
+
}
|
|
27
|
+
return `o${id}`;
|
|
28
|
+
}
|
|
29
|
+
return `v:${String(value)}`;
|
|
30
|
+
}
|
|
31
|
+
function depsCacheToken(deps) {
|
|
32
|
+
if (!deps)
|
|
33
|
+
return "none";
|
|
34
|
+
const keys = Object.keys(deps).sort();
|
|
35
|
+
if (keys.length === 0)
|
|
36
|
+
return "empty";
|
|
37
|
+
const rec = deps;
|
|
38
|
+
return keys.map((k) => `${k}=${depValueToken(rec[k])}`).join(",");
|
|
39
|
+
}
|
|
40
|
+
function targetCacheToken(absTarget) {
|
|
41
|
+
try {
|
|
42
|
+
const st = fs.statSync(absTarget);
|
|
43
|
+
if (st.isDirectory()) {
|
|
44
|
+
const files = listFrameFiles(absTarget);
|
|
45
|
+
const sig = files
|
|
46
|
+
.map((f) => {
|
|
47
|
+
const fst = fs.statSync(f);
|
|
48
|
+
return `${path.basename(f)}:${fst.size}:${fst.mtimeMs}`;
|
|
49
|
+
})
|
|
50
|
+
.join("|");
|
|
51
|
+
return `dir:${absTarget}:${shortHash(sig)}`;
|
|
52
|
+
}
|
|
53
|
+
return `file:${absTarget}:${st.size}:${st.mtimeMs}`;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return `missing:${absTarget}`;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function assertValidDecodedImage(img, filePath) {
|
|
60
|
+
if (!img || !(img.width > 0 && img.height > 0) || !(img.data instanceof Uint8Array) || img.data.length < img.width * img.height * 4) {
|
|
61
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Invalid decoded frame image: ${path.basename(filePath)}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function listCandidateFrames(dir) {
|
|
65
|
+
return listFrameFiles(dir).map((p, i) => ({ path: p, timestampMs: i * 1000 }));
|
|
66
|
+
}
|
|
67
|
+
const PLAYWRIGHT_INSTALL_HINT = "npm install -D playwright && npx playwright install chromium";
|
|
68
|
+
const VIDEO_URL_FALLBACK_HINT = "Pass a video file or directory of PNG keyframes with --target ./frames/";
|
|
69
|
+
function resolvePlaywright(candidate) {
|
|
70
|
+
if (!candidate || typeof candidate !== "object")
|
|
71
|
+
return null;
|
|
72
|
+
const mod = candidate;
|
|
73
|
+
if (mod.chromium && typeof mod.chromium.launch === "function") {
|
|
74
|
+
return mod;
|
|
75
|
+
}
|
|
76
|
+
if (mod.default?.chromium && typeof mod.default.chromium.launch === "function") {
|
|
77
|
+
return mod.default;
|
|
78
|
+
}
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
async function launchVideoBrowser(pw) {
|
|
82
|
+
try {
|
|
83
|
+
return await launchBrowser(pw, {
|
|
84
|
+
headless: true,
|
|
85
|
+
featureName: "Verifying a video contract against an HTTP/HTTPS URL"
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
if (err instanceof VibecodeError && err.code === "ADAPTER_MISSING")
|
|
90
|
+
throw err;
|
|
91
|
+
throw new VibecodeError("ADAPTER_MISSING", `Verifying a video contract against an HTTP/HTTPS URL requires Playwright Chromium (${err instanceof Error ? err.message : String(err)}).`, {
|
|
92
|
+
adapter: "playwright",
|
|
93
|
+
installHint: PLAYWRIGHT_INSTALL_HINT,
|
|
94
|
+
fallbackHint: VIDEO_URL_FALLBACK_HINT
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async function captureUrlCandidateFrames(targetUrl, ctx, deps) {
|
|
99
|
+
const hasExplicitPw = Object.prototype.hasOwnProperty.call(deps, "playwright");
|
|
100
|
+
const rawPw = hasExplicitPw ? deps.playwright : await loadPlaywright({ cwd: ctx.cwd });
|
|
101
|
+
const pw = resolvePlaywright(rawPw);
|
|
102
|
+
if (!pw) {
|
|
103
|
+
throw new VibecodeError("ADAPTER_MISSING", "Verifying a video contract against an HTTP/HTTPS URL requires Playwright.", {
|
|
104
|
+
adapter: "playwright",
|
|
105
|
+
installHint: PLAYWRIGHT_INSTALL_HINT,
|
|
106
|
+
fallbackHint: VIDEO_URL_FALLBACK_HINT
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
const invariants = ctx.contract?.invariants || [];
|
|
110
|
+
const matchedInv = ctx.currentInvariantId
|
|
111
|
+
? invariants.find((inv) => inv.id === ctx.currentInvariantId)
|
|
112
|
+
: undefined;
|
|
113
|
+
const stateCount = matchedInv?.expected?.states?.length ??
|
|
114
|
+
invariants.find((inv) => Array.isArray(inv.expected?.states) && inv.expected.states.length > 0)?.expected?.states?.length ??
|
|
115
|
+
0;
|
|
116
|
+
const captureCount = Math.max(stateCount, 8);
|
|
117
|
+
const cacheDir = ctx.cacheDir || resolveWorkspace(ctx.cwd).cacheDir;
|
|
118
|
+
const outDir = path.join(cacheDir, "video-url-frames", shortHash(targetUrl));
|
|
119
|
+
ensureDir(outDir);
|
|
120
|
+
for (const entry of fs.readdirSync(outDir)) {
|
|
121
|
+
if (/^frame-\d+\.png$/i.test(entry)) {
|
|
122
|
+
fs.rmSync(path.join(outDir, entry), { force: true });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const viewport = { width: 1440, height: 900 };
|
|
126
|
+
const browser = await launchVideoBrowser(pw);
|
|
127
|
+
let page = null;
|
|
128
|
+
try {
|
|
129
|
+
page = await browser.newPage({ viewport });
|
|
130
|
+
try {
|
|
131
|
+
await page.goto(targetUrl, { waitUntil: "networkidle", timeout: 15000 });
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
try {
|
|
135
|
+
await page.goto(targetUrl, { waitUntil: "load", timeout: 15000 });
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
// Bounded fallback: proceed if DOM is already rendered
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const rawMetrics = await page.evaluate(() => ({
|
|
142
|
+
scrollHeight: typeof document !== "undefined"
|
|
143
|
+
? document.documentElement?.scrollHeight ||
|
|
144
|
+
document.body?.scrollHeight ||
|
|
145
|
+
(typeof window !== "undefined" ? window.innerHeight : 900) ||
|
|
146
|
+
900
|
|
147
|
+
: 900,
|
|
148
|
+
innerHeight: typeof window !== "undefined" ? window.innerHeight || 900 : 900
|
|
149
|
+
}));
|
|
150
|
+
const innerHeight = typeof rawMetrics?.innerHeight === "number" && Number.isFinite(rawMetrics.innerHeight) && rawMetrics.innerHeight > 0
|
|
151
|
+
? rawMetrics.innerHeight
|
|
152
|
+
: viewport.height;
|
|
153
|
+
const scrollHeight = typeof rawMetrics?.scrollHeight === "number" && Number.isFinite(rawMetrics.scrollHeight) && rawMetrics.scrollHeight > 0
|
|
154
|
+
? rawMetrics.scrollHeight
|
|
155
|
+
: innerHeight;
|
|
156
|
+
const maxScroll = scrollHeight - innerHeight;
|
|
157
|
+
const scrollable = maxScroll > 10;
|
|
158
|
+
const evalWithArg = page;
|
|
159
|
+
const frames = [];
|
|
160
|
+
for (let i = 0; i < captureCount; i++) {
|
|
161
|
+
if (scrollable) {
|
|
162
|
+
const frac = captureCount > 1 ? i / (captureCount - 1) : 0;
|
|
163
|
+
const scrollY = Math.round(frac * maxScroll);
|
|
164
|
+
await evalWithArg.evaluate((y) => {
|
|
165
|
+
if (typeof window !== "undefined" && typeof window.scrollTo === "function") {
|
|
166
|
+
window.scrollTo(0, y);
|
|
167
|
+
}
|
|
168
|
+
}, scrollY);
|
|
169
|
+
await page.waitForTimeout?.(100);
|
|
170
|
+
}
|
|
171
|
+
else if (i > 0) {
|
|
172
|
+
await page.waitForTimeout?.(150);
|
|
173
|
+
}
|
|
174
|
+
const framePath = path.join(outDir, `frame-${String(i).padStart(3, "0")}.png`);
|
|
175
|
+
const buf = await page.screenshot({ path: framePath });
|
|
176
|
+
if (!fs.existsSync(framePath) && buf instanceof Uint8Array) {
|
|
177
|
+
fs.writeFileSync(framePath, buf);
|
|
178
|
+
}
|
|
179
|
+
frames.push({ path: framePath, timestampMs: i * (scrollable ? 100 : 150) });
|
|
180
|
+
}
|
|
181
|
+
return frames;
|
|
182
|
+
}
|
|
183
|
+
finally {
|
|
184
|
+
try {
|
|
185
|
+
await page?.close?.();
|
|
186
|
+
}
|
|
187
|
+
catch { /* ignore */ }
|
|
188
|
+
try {
|
|
189
|
+
await browser.close();
|
|
190
|
+
}
|
|
191
|
+
catch { /* ignore */ }
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/** Load ordered candidate frames from a frame directory, video file, or HTTP/HTTPS URL. */
|
|
195
|
+
export async function loadCandidateFrames(target, ctx, deps = {}) {
|
|
196
|
+
if (!target)
|
|
197
|
+
throw new VibecodeError("TARGET_MISSING", "Missing --target <frames-dir-or-video> for video verification.");
|
|
198
|
+
const trimmed = target.trim();
|
|
199
|
+
const looksLikeUriScheme = /^[a-z][a-z0-9+.-]*:/i.test(trimmed) && !/^[a-z]:[\\/]/i.test(trimmed);
|
|
200
|
+
if (/^https?:\/\//i.test(trimmed) || looksLikeUriScheme || trimmed.startsWith("//")) {
|
|
201
|
+
let targetUrl;
|
|
202
|
+
try {
|
|
203
|
+
const baseUrl = parseSafeHttpBaseUrl(trimmed);
|
|
204
|
+
targetUrl = /^https?:\/\//i.test(trimmed) ? trimmed : baseUrl.toString();
|
|
205
|
+
}
|
|
206
|
+
catch (err) {
|
|
207
|
+
throw new VibecodeError("CONFIG_INVALID", redactSensitiveText(`Invalid video target URL: ${errorMessage(err)}`));
|
|
208
|
+
}
|
|
209
|
+
return captureUrlCandidateFrames(targetUrl, ctx, deps);
|
|
210
|
+
}
|
|
211
|
+
if (STRICT_CONTROL_CHARS_RE.test(trimmed)) {
|
|
212
|
+
throw new VibecodeError("CONFIG_INVALID", "Video target path contains control characters.");
|
|
213
|
+
}
|
|
214
|
+
const abs = path.resolve(ctx.cwd || process.cwd(), trimmed);
|
|
215
|
+
if (isInsideVaultDirectory(trimmed) || isInsideVaultDirectory(abs)) {
|
|
216
|
+
throw new VibecodeError("CONFIG_INVALID", "Target video path must not point inside a holdout vault directory.");
|
|
217
|
+
}
|
|
218
|
+
if (!fs.existsSync(abs))
|
|
219
|
+
throw new VibecodeError("TARGET_MISSING", `Target not found: ${redactSensitiveText(target)}`);
|
|
220
|
+
if (fs.statSync(abs).isDirectory()) {
|
|
221
|
+
const files = listFrameFiles(abs);
|
|
222
|
+
if (files.length === 0)
|
|
223
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `No frames found in directory: ${redactSensitiveText(target)}`);
|
|
224
|
+
for (const f of files) {
|
|
225
|
+
if (isInsideVaultDirectory(f)) {
|
|
226
|
+
throw new VibecodeError("CONFIG_INVALID", "Target video frame path must not point inside a holdout vault directory.");
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return listCandidateFrames(abs);
|
|
230
|
+
}
|
|
231
|
+
const ext = path.extname(abs).toLowerCase();
|
|
232
|
+
if (VIDEO_EXTS.has(ext)) {
|
|
233
|
+
const adapter = resolveFfmpegAdapter(deps);
|
|
234
|
+
if (!adapter)
|
|
235
|
+
throw ffmpegMissingError();
|
|
236
|
+
try {
|
|
237
|
+
const { frames } = extractVideoFrames(abs, {
|
|
238
|
+
cwd: ctx.cwd,
|
|
239
|
+
sceneThreshold: 0.18,
|
|
240
|
+
maxFrames: 48,
|
|
241
|
+
cacheKey: `verify-${ctx.currentInvariantId || "video"}-${shortHash(abs)}`
|
|
242
|
+
}, adapter);
|
|
243
|
+
for (const frame of frames) {
|
|
244
|
+
if (frame?.path && isInsideVaultDirectory(frame.path)) {
|
|
245
|
+
throw new VibecodeError("CONFIG_INVALID", "Extracted video frame path must not point inside a holdout vault directory.");
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return frames;
|
|
249
|
+
}
|
|
250
|
+
catch (err) {
|
|
251
|
+
if (err instanceof VibecodeError)
|
|
252
|
+
throw err;
|
|
253
|
+
throw new VibecodeError("EXEC_ERROR", redactSensitiveText(`Failed to extract candidate frames from ${path.basename(abs)}: ${err instanceof Error ? err.message : String(err)}`), {
|
|
254
|
+
adapter: "ffmpeg",
|
|
255
|
+
fallbackHint: "Pass a directory of PNG keyframes with --target ./frames/",
|
|
256
|
+
details: { source: redactSensitiveText(abs) }
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
if (IMAGE_EXTS.has(ext))
|
|
261
|
+
return [{ path: abs, timestampMs: 0 }];
|
|
262
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported video target: ${ext || "(none)"}`, {
|
|
263
|
+
fallbackHint: "Pass a directory of PNG keyframes with --target ./frames/"
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
function assertValidPngHeaderIfPng(filePath) {
|
|
267
|
+
if (path.extname(filePath).toLowerCase() !== ".png")
|
|
268
|
+
return;
|
|
269
|
+
const dims = readImageDimensions(fs.readFileSync(filePath));
|
|
270
|
+
if (!dims || dims.format !== "png" || !(dims.width > 0 && dims.height > 0)) {
|
|
271
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Corrupt or invalid PNG frame: ${path.basename(filePath)}`);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
function resolveReferenceState(state, ctx) {
|
|
275
|
+
if (!state || !state.keyframeArtifact || typeof state.keyframeArtifact !== "string" || isForbiddenObjectKey(state.keyframeArtifact)) {
|
|
276
|
+
throw new VibecodeError("CONTRACT_INVALID", "Video state missing keyframeArtifact");
|
|
277
|
+
}
|
|
278
|
+
const files = ctx.contract?.artifacts?.files || {};
|
|
279
|
+
const rel = Object.prototype.hasOwnProperty.call(files, state.keyframeArtifact) ? files[state.keyframeArtifact] : undefined;
|
|
280
|
+
if (!rel || typeof rel !== "string") {
|
|
281
|
+
throw new VibecodeError("CONTRACT_INVALID", `Keyframe artifact ${state.keyframeArtifact} not found in contract.artifacts.files`);
|
|
282
|
+
}
|
|
283
|
+
if (STRICT_CONTROL_CHARS_RE.test(rel) ||
|
|
284
|
+
path.isAbsolute(rel) ||
|
|
285
|
+
/^[A-Za-z]:/.test(rel) ||
|
|
286
|
+
isInsideVaultDirectory(rel)) {
|
|
287
|
+
throw new VibecodeError("CONFIG_INVALID", "Keyframe artifact path must remain inside .vibecode/artifacts and outside vault directories.");
|
|
288
|
+
}
|
|
289
|
+
const { artifactsDir } = resolveWorkspace(ctx.cwd);
|
|
290
|
+
const abs = artifactPath(rel, ctx.cwd);
|
|
291
|
+
if (!isPathWithinDir(abs, artifactsDir, { allowEqual: false }) || isInsideVaultDirectory(abs)) {
|
|
292
|
+
throw new VibecodeError("CONFIG_INVALID", "Keyframe artifact path must remain inside .vibecode/artifacts and outside vault directories.");
|
|
293
|
+
}
|
|
294
|
+
if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
|
|
295
|
+
throw new VibecodeError("CONTRACT_NOT_FOUND", `Keyframe artifact missing on disk: ${redactSensitiveText(rel)}`);
|
|
296
|
+
}
|
|
297
|
+
try {
|
|
298
|
+
const realArtifacts = fs.realpathSync(artifactsDir);
|
|
299
|
+
const realAbs = fs.realpathSync(abs);
|
|
300
|
+
if (!isPathWithinDir(realAbs, realArtifacts, { allowEqual: false }) || isInsideVaultDirectory(realAbs)) {
|
|
301
|
+
throw new VibecodeError("CONFIG_INVALID", "Keyframe artifact symlink must remain inside .vibecode/artifacts and outside vault directories.");
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
catch (err) {
|
|
305
|
+
if (err instanceof VibecodeError)
|
|
306
|
+
throw err;
|
|
307
|
+
throw new VibecodeError("CONFIG_INVALID", "Keyframe artifact path could not be verified safely.");
|
|
308
|
+
}
|
|
309
|
+
return abs;
|
|
310
|
+
}
|
|
311
|
+
function dHashSimilarity(a, b) {
|
|
312
|
+
return Math.max(0, 1 - hammingDistanceHex(a, b) / 64);
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Strictly monotone (j_0 < j_1 < ... < j_{K-1}) maximum-score alignment.
|
|
316
|
+
* O(K * M) via running prefix maximum, exactly as specified for the video oracle.
|
|
317
|
+
*
|
|
318
|
+
* @returns {{ score: number, alignment: Array<{ stateIndex: number, candidateIndex: number, similarity: number }>, complete: boolean }}
|
|
319
|
+
*/
|
|
320
|
+
export function alignMonotone(similarity, floor = 0.7) {
|
|
321
|
+
if (!Array.isArray(similarity) || similarity.length === 0) {
|
|
322
|
+
return { score: 0, alignment: [], complete: true };
|
|
323
|
+
}
|
|
324
|
+
const K = similarity.length;
|
|
325
|
+
const M = Array.isArray(similarity[0]) ? similarity[0].length : 0;
|
|
326
|
+
if (M === 0 || K > M)
|
|
327
|
+
return { score: 0, alignment: [], complete: false };
|
|
328
|
+
const NEG = -Infinity;
|
|
329
|
+
let prev = new Array(M).fill(NEG);
|
|
330
|
+
const parents = [];
|
|
331
|
+
for (let k = 0; k < K; k++) {
|
|
332
|
+
const cur = new Array(M).fill(NEG);
|
|
333
|
+
const parentsK = new Array(M).fill(-1);
|
|
334
|
+
let bestPrefix = k === 0 ? 0 : NEG; // score of best alignment ending before j
|
|
335
|
+
let bestPrefixIdx = -1;
|
|
336
|
+
const row = Array.isArray(similarity[k]) ? similarity[k] : [];
|
|
337
|
+
for (let j = 0; j < M; j++) {
|
|
338
|
+
const sim = row[j];
|
|
339
|
+
if (typeof sim === "number" && sim >= floor && bestPrefix > NEG) {
|
|
340
|
+
cur[j] = bestPrefix + sim;
|
|
341
|
+
parentsK[j] = bestPrefixIdx;
|
|
342
|
+
}
|
|
343
|
+
if (prev[j] > bestPrefix) {
|
|
344
|
+
bestPrefix = prev[j];
|
|
345
|
+
bestPrefixIdx = j;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
parents.push(parentsK);
|
|
349
|
+
prev = cur;
|
|
350
|
+
}
|
|
351
|
+
let endIdx = -1;
|
|
352
|
+
let bestScore = NEG;
|
|
353
|
+
for (let j = 0; j < M; j++) {
|
|
354
|
+
if (prev[j] > bestScore) {
|
|
355
|
+
bestScore = prev[j];
|
|
356
|
+
endIdx = j;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
if (endIdx < 0 || bestScore === NEG) {
|
|
360
|
+
return { score: 0, alignment: [], complete: false };
|
|
361
|
+
}
|
|
362
|
+
const alignment = [];
|
|
363
|
+
let j = endIdx;
|
|
364
|
+
for (let k = K - 1; k >= 0; k--) {
|
|
365
|
+
alignment.push({ stateIndex: k, candidateIndex: j, similarity: similarity[k][j] });
|
|
366
|
+
j = parents[k][j];
|
|
367
|
+
}
|
|
368
|
+
alignment.reverse();
|
|
369
|
+
return { score: bestScore, alignment, complete: alignment.length === K };
|
|
370
|
+
}
|
|
371
|
+
/** First required state that cannot be reached after the greedy prefix (diagnostics only). */
|
|
372
|
+
function describeBlockedState(similarity, floor) {
|
|
373
|
+
const K = Array.isArray(similarity) ? similarity.length : 0;
|
|
374
|
+
const M = K > 0 && Array.isArray(similarity[0]) ? similarity[0].length : 0;
|
|
375
|
+
let last = -1;
|
|
376
|
+
for (let k = 0; k < K; k++) {
|
|
377
|
+
const row = Array.isArray(similarity[k]) ? similarity[k] : [];
|
|
378
|
+
let found = -1;
|
|
379
|
+
for (let j = last + 1; j < M; j++) {
|
|
380
|
+
if (row[j] >= floor) {
|
|
381
|
+
found = j;
|
|
382
|
+
break;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
if (found < 0) {
|
|
386
|
+
let bestSim = -Infinity;
|
|
387
|
+
let bestAt = -1;
|
|
388
|
+
for (let j = 0; j < M; j++) {
|
|
389
|
+
if (typeof row[j] === "number" && row[j] > bestSim) {
|
|
390
|
+
bestSim = row[j];
|
|
391
|
+
bestAt = j;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
return {
|
|
395
|
+
stateIndex: k,
|
|
396
|
+
bestSimilarity: bestAt >= 0 ? bestSim : 0,
|
|
397
|
+
bestCandidateIndex: bestAt,
|
|
398
|
+
afterCandidateIndex: last
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
last = found;
|
|
402
|
+
}
|
|
403
|
+
return null;
|
|
404
|
+
}
|
|
405
|
+
async function decodeCached(filePath, ctx, deps) {
|
|
406
|
+
if (!ctx?.runtimeCache) {
|
|
407
|
+
const decoded = await decodeImage(filePath, deps);
|
|
408
|
+
assertValidDecodedImage(decoded, filePath);
|
|
409
|
+
return decoded;
|
|
410
|
+
}
|
|
411
|
+
const st = fs.statSync(filePath);
|
|
412
|
+
const key = `vidimg:${filePath}:${st.size}:${st.mtimeMs}:${depValueToken(deps?.sharp)}`;
|
|
413
|
+
const cached = ctx.runtimeCache[key];
|
|
414
|
+
if (!cached) {
|
|
415
|
+
const decoded = await decodeImage(filePath, deps);
|
|
416
|
+
assertValidDecodedImage(decoded, filePath);
|
|
417
|
+
ctx.runtimeCache[key] = decoded;
|
|
418
|
+
return decoded;
|
|
419
|
+
}
|
|
420
|
+
assertValidDecodedImage(cached, filePath);
|
|
421
|
+
return cached;
|
|
422
|
+
}
|
|
423
|
+
async function buildReferenceStates(invariant, ctx, deps) {
|
|
424
|
+
const states = [];
|
|
425
|
+
for (const state of invariant.expected?.states || []) {
|
|
426
|
+
const file = resolveReferenceState(state, ctx);
|
|
427
|
+
assertValidPngHeaderIfPng(file);
|
|
428
|
+
states.push({ ...state, abs: file, img: await decodeCached(file, ctx, deps) });
|
|
429
|
+
}
|
|
430
|
+
return states;
|
|
431
|
+
}
|
|
432
|
+
async function computeSimilarityMatrix(refStates, candStates) {
|
|
433
|
+
const matrix = [];
|
|
434
|
+
for (const ref of refStates) {
|
|
435
|
+
const row = [];
|
|
436
|
+
for (const cand of candStates) {
|
|
437
|
+
const ssim = computeSSIM(ref.img, cand.img).ssim;
|
|
438
|
+
const hashSim = dHashSimilarity(ref.dHash || computeDHash(ref.img), cand.dHash);
|
|
439
|
+
row.push(0.7 * ssim + 0.3 * hashSim);
|
|
440
|
+
}
|
|
441
|
+
matrix.push(row);
|
|
442
|
+
}
|
|
443
|
+
return matrix;
|
|
444
|
+
}
|
|
445
|
+
async function verifyTimeline(invariant, ctx, deps) {
|
|
446
|
+
const tolerance = invariant.tolerance || {};
|
|
447
|
+
const floor = typeof tolerance.stateMatchFloor === "number" ? tolerance.stateMatchFloor : 0.7;
|
|
448
|
+
const expected = invariant.expected || {};
|
|
449
|
+
const perceptualOnly = invariant.input?.perceptualOnly === true;
|
|
450
|
+
const refStates = await buildReferenceStates(invariant, ctx, deps);
|
|
451
|
+
if (refStates.length === 0) {
|
|
452
|
+
throw new VibecodeError("CONTRACT_INVALID", `Invariant ${invariant.id} has no expected.states`);
|
|
453
|
+
}
|
|
454
|
+
let candStates;
|
|
455
|
+
const trimmedTarget = ctx.target ? ctx.target.trim() : "";
|
|
456
|
+
const looksLikeUriScheme = /^[a-z][a-z0-9+.-]*:/i.test(trimmedTarget) && !/^[a-z]:[\\/]/i.test(trimmedTarget);
|
|
457
|
+
const targetIsUri = Boolean(trimmedTarget && (/^https?:\/\//i.test(trimmedTarget) || looksLikeUriScheme || trimmedTarget.startsWith("//")));
|
|
458
|
+
let targetIsUrl = false;
|
|
459
|
+
let normalizedTarget = null;
|
|
460
|
+
if (trimmedTarget) {
|
|
461
|
+
if (targetIsUri) {
|
|
462
|
+
try {
|
|
463
|
+
const baseUrl = parseSafeHttpBaseUrl(trimmedTarget);
|
|
464
|
+
targetIsUrl = true;
|
|
465
|
+
normalizedTarget = /^https?:\/\//i.test(trimmedTarget) ? trimmedTarget : baseUrl.toString();
|
|
466
|
+
}
|
|
467
|
+
catch (err) {
|
|
468
|
+
throw new VibecodeError("CONFIG_INVALID", redactSensitiveText(`Invalid video target URL: ${errorMessage(err)}`));
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
else {
|
|
472
|
+
if (STRICT_CONTROL_CHARS_RE.test(trimmedTarget)) {
|
|
473
|
+
throw new VibecodeError("CONFIG_INVALID", "Video target path contains control characters.");
|
|
474
|
+
}
|
|
475
|
+
normalizedTarget = path.resolve(ctx.cwd || process.cwd(), trimmedTarget);
|
|
476
|
+
if (isInsideVaultDirectory(trimmedTarget) || isInsideVaultDirectory(normalizedTarget)) {
|
|
477
|
+
throw new VibecodeError("CONFIG_INVALID", "Target video path must not point inside a holdout vault directory.");
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
const cacheToken = !normalizedTarget
|
|
482
|
+
? null
|
|
483
|
+
: targetIsUrl
|
|
484
|
+
? `url:${normalizedTarget}`
|
|
485
|
+
: targetCacheToken(normalizedTarget);
|
|
486
|
+
const cacheKey = cacheToken ? `video:${cacheToken}:${depsCacheToken(deps)}` : null;
|
|
487
|
+
if (ctx.runtimeCache && cacheKey && Array.isArray(ctx.runtimeCache[cacheKey])) {
|
|
488
|
+
candStates = ctx.runtimeCache[cacheKey];
|
|
489
|
+
}
|
|
490
|
+
else {
|
|
491
|
+
const frames = await loadCandidateFrames(ctx.target, { ...ctx, currentInvariantId: invariant.id }, deps);
|
|
492
|
+
for (const f of frames) {
|
|
493
|
+
if (!f || typeof f.path !== "string" || !fs.existsSync(f.path)) {
|
|
494
|
+
throw new VibecodeError("EXEC_ERROR", `Extracted candidate frame missing on disk: ${f?.path ? path.basename(f.path) : "(unknown)"}`, {
|
|
495
|
+
adapter: targetIsUrl ? "playwright" : "ffmpeg",
|
|
496
|
+
fallbackHint: "Pass a directory of PNG keyframes with --target ./frames/",
|
|
497
|
+
details: {
|
|
498
|
+
source: normalizedTarget ? redactSensitiveText(normalizedTarget) : null,
|
|
499
|
+
framePath: f?.path ? redactSensitiveText(f.path) : null
|
|
500
|
+
}
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
if (isInsideVaultDirectory(f.path)) {
|
|
504
|
+
throw new VibecodeError("CONFIG_INVALID", "Extracted video frame path must not point inside a holdout vault directory.");
|
|
505
|
+
}
|
|
506
|
+
assertValidPngHeaderIfPng(f.path);
|
|
507
|
+
}
|
|
508
|
+
const extracted = await extractStates(frames, { deps });
|
|
509
|
+
for (const state of extracted.states) {
|
|
510
|
+
assertValidDecodedImage(state.img, state.path);
|
|
511
|
+
}
|
|
512
|
+
candStates = extracted.states;
|
|
513
|
+
if (ctx.runtimeCache && cacheKey)
|
|
514
|
+
ctx.runtimeCache[cacheKey] = candStates;
|
|
515
|
+
}
|
|
516
|
+
if (candStates.length === 0) {
|
|
517
|
+
return {
|
|
518
|
+
status: "fail",
|
|
519
|
+
score: 0,
|
|
520
|
+
failures: ["candidate video produced no frames/states"],
|
|
521
|
+
metrics: { stateCount: 0 }
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
const simCacheKey = ctx.runtimeCache && cacheKey
|
|
525
|
+
? `vidsim:${refStates.map((s) => `${s.abs}:${s.dHash || ""}`).join("|")}:${cacheKey}`
|
|
526
|
+
: null;
|
|
527
|
+
let similarity;
|
|
528
|
+
if (simCacheKey && Array.isArray(ctx.runtimeCache?.[simCacheKey])) {
|
|
529
|
+
similarity = ctx.runtimeCache[simCacheKey];
|
|
530
|
+
}
|
|
531
|
+
else {
|
|
532
|
+
similarity = await computeSimilarityMatrix(refStates, candStates);
|
|
533
|
+
if (simCacheKey && ctx.runtimeCache)
|
|
534
|
+
ctx.runtimeCache[simCacheKey] = similarity;
|
|
535
|
+
}
|
|
536
|
+
const result = alignMonotone(similarity, floor);
|
|
537
|
+
const failures = [];
|
|
538
|
+
const metrics = {
|
|
539
|
+
referenceStates: refStates.length,
|
|
540
|
+
candidateStates: candStates.length,
|
|
541
|
+
stateMatchFloor: floor,
|
|
542
|
+
alignment: result.alignment.map((a) => ({
|
|
543
|
+
stateId: refStates[a.stateIndex].id,
|
|
544
|
+
candidateIndex: a.candidateIndex,
|
|
545
|
+
similarity: Number(a.similarity.toFixed(4))
|
|
546
|
+
}))
|
|
547
|
+
};
|
|
548
|
+
if (!result.complete) {
|
|
549
|
+
const blocked = describeBlockedState(similarity, floor);
|
|
550
|
+
const hardParity = result.alignment.length / refStates.length;
|
|
551
|
+
metrics.hardParity = hardParity;
|
|
552
|
+
if (blocked) {
|
|
553
|
+
const ref = refStates[blocked.stateIndex];
|
|
554
|
+
const where = blocked.bestCandidateIndex >= 0 ? `at candidate #${blocked.bestCandidateIndex}` : "no candidate frames";
|
|
555
|
+
failures.push(`state ${ref.id} not reachable in monotonic order (best similarity ${blocked.bestSimilarity.toFixed(3)} ` +
|
|
556
|
+
`${where}, floor ${floor})`);
|
|
557
|
+
}
|
|
558
|
+
else {
|
|
559
|
+
failures.push("state sequence is not a strictly monotonic subsequence of the candidate timeline");
|
|
560
|
+
}
|
|
561
|
+
if (perceptualOnly) {
|
|
562
|
+
// Soft invariant still reports the misalignment but scores any correctly aligned states.
|
|
563
|
+
const alignedScore = result.alignment.length
|
|
564
|
+
? result.alignment.reduce((sum, a) => sum + a.similarity, 0) / result.alignment.length
|
|
565
|
+
: 0;
|
|
566
|
+
return { status: "fail", score: alignedScore, failures, metrics };
|
|
567
|
+
}
|
|
568
|
+
return { status: "fail", score: hardParity, failures, metrics };
|
|
569
|
+
}
|
|
570
|
+
metrics.hardParity = 1;
|
|
571
|
+
if (!perceptualOnly) {
|
|
572
|
+
return { status: "pass", score: 1, failures, metrics };
|
|
573
|
+
}
|
|
574
|
+
// Soft perceptual checks on aligned pairs.
|
|
575
|
+
const minSSIM = typeof tolerance.minKeyframeSSIM === "number" ? tolerance.minKeyframeSSIM : 0.85;
|
|
576
|
+
const maxHamming = typeof tolerance.maxHammingDistance === "number" ? tolerance.maxHammingDistance : 14;
|
|
577
|
+
const minPalette = typeof tolerance.minPaletteSimilarity === "number" ? tolerance.minPaletteSimilarity : 0.8;
|
|
578
|
+
const minMotionIoU = typeof tolerance.minMotionRegionIoU === "number" ? tolerance.minMotionRegionIoU : 0.55;
|
|
579
|
+
const scores = [];
|
|
580
|
+
const keyframes = [];
|
|
581
|
+
for (const { stateIndex, candidateIndex } of result.alignment) {
|
|
582
|
+
const ref = refStates[stateIndex];
|
|
583
|
+
const cand = candStates[candidateIndex];
|
|
584
|
+
const ssim = Math.max(0, Math.min(1, computeSSIM(ref.img, cand.img).ssim));
|
|
585
|
+
const hamming = hammingDistanceHex(ref.dHash || computeDHash(ref.img), cand.dHash);
|
|
586
|
+
const palette = comparePalettes(ref.palette || [], cand.palette || []);
|
|
587
|
+
keyframes.push({
|
|
588
|
+
stateId: ref.id,
|
|
589
|
+
candidateIndex,
|
|
590
|
+
ssim: Number(ssim.toFixed(4)),
|
|
591
|
+
hammingDistance: hamming,
|
|
592
|
+
paletteSimilarity: Number(palette.toFixed(4))
|
|
593
|
+
});
|
|
594
|
+
if (ssim < minSSIM)
|
|
595
|
+
failures.push(`${ref.id}: ssim ${ssim.toFixed(4)} < ${minSSIM}`);
|
|
596
|
+
if (hamming > maxHamming)
|
|
597
|
+
failures.push(`${ref.id}: hammingDistance ${hamming} > ${maxHamming}`);
|
|
598
|
+
if (palette < minPalette)
|
|
599
|
+
failures.push(`${ref.id}: paletteSimilarity ${palette.toFixed(4)} < ${minPalette}`);
|
|
600
|
+
scores.push(Math.max(0, Math.min(1, Math.min(ssim, palette))));
|
|
601
|
+
}
|
|
602
|
+
metrics.keyframes = keyframes;
|
|
603
|
+
// Motion-region IoU across aligned transitions.
|
|
604
|
+
const indexByStateId = new Map(result.alignment.map((a) => [refStates[a.stateIndex].id, a.candidateIndex]));
|
|
605
|
+
const motion = [];
|
|
606
|
+
for (const transition of expected.transitions || []) {
|
|
607
|
+
const fromIdx = indexByStateId.get(transition.from);
|
|
608
|
+
const toIdx = indexByStateId.get(transition.to);
|
|
609
|
+
if (fromIdx == null || toIdx == null || !transition.changedRegion)
|
|
610
|
+
continue;
|
|
611
|
+
const { changedRegion } = changedRegionBetween(candStates[fromIdx].img, candStates[toIdx].img);
|
|
612
|
+
const iou = bboxIoU(transition.changedRegion, changedRegion);
|
|
613
|
+
motion.push({ from: transition.from, to: transition.to, iou: Number(iou.toFixed(4)) });
|
|
614
|
+
if (iou < minMotionIoU)
|
|
615
|
+
failures.push(`motion region ${transition.from}->${transition.to} IoU ${iou.toFixed(4)} < ${minMotionIoU}`);
|
|
616
|
+
scores.push(iou);
|
|
617
|
+
}
|
|
618
|
+
metrics.motionRegions = motion;
|
|
619
|
+
const score = scores.length ? Math.max(0, Math.min(1, scores.reduce((a, b) => a + b, 0) / scores.length)) : 1;
|
|
620
|
+
return { status: failures.length ? "fail" : "pass", score, failures, metrics };
|
|
621
|
+
}
|
|
622
|
+
export async function verifyInvariant(invariant, ctx, deps = {}) {
|
|
623
|
+
if (invariant.type !== "video_timeline") {
|
|
624
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported video invariant type: ${invariant.type}`);
|
|
625
|
+
}
|
|
626
|
+
return verifyTimeline(invariant, ctx, deps);
|
|
627
|
+
}
|