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.
- package/LICENSE +21 -0
- package/README.md +235 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +452 -0
- package/dist/core/adapters.d.ts +8 -0
- package/dist/core/adapters.js +92 -0
- package/dist/core/diff.d.ts +10 -0
- package/dist/core/diff.js +207 -0
- package/dist/core/doctor.d.ts +50 -0
- package/dist/core/doctor.js +312 -0
- package/dist/core/errors.d.ts +32 -0
- package/dist/core/errors.js +81 -0
- package/dist/core/exec.d.ts +14 -0
- package/dist/core/exec.js +109 -0
- package/dist/core/parity.d.ts +9 -0
- package/dist/core/parity.js +138 -0
- package/dist/core/png.d.ts +7 -0
- package/dist/core/png.js +303 -0
- package/dist/core/schema.d.ts +17 -0
- package/dist/core/schema.js +614 -0
- package/dist/core/slices.d.ts +24 -0
- package/dist/core/slices.js +294 -0
- package/dist/core/store.d.ts +17 -0
- package/dist/core/store.js +97 -0
- package/dist/core/types.d.ts +751 -0
- package/dist/core/types.js +4 -0
- package/dist/core/visual.d.ts +34 -0
- package/dist/core/visual.js +459 -0
- package/dist/core/watch.d.ts +53 -0
- package/dist/core/watch.js +285 -0
- package/dist/ingestors/api-repo.d.ts +5 -0
- package/dist/ingestors/api-repo.js +722 -0
- package/dist/ingestors/bridges.d.ts +3 -0
- package/dist/ingestors/bridges.js +562 -0
- package/dist/ingestors/cli.d.ts +9 -0
- package/dist/ingestors/cli.js +266 -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 +97 -0
- package/dist/ingestors/video.d.ts +47 -0
- package/dist/ingestors/video.js +605 -0
- package/dist/ingestors/web.d.ts +25 -0
- package/dist/ingestors/web.js +397 -0
- package/dist/mcp/server.d.ts +2 -0
- package/dist/mcp/server.js +504 -0
- package/dist/oracles/api-repo.d.ts +2 -0
- package/dist/oracles/api-repo.js +214 -0
- package/dist/oracles/cli.d.ts +2 -0
- package/dist/oracles/cli.js +157 -0
- package/dist/oracles/image.d.ts +2 -0
- package/dist/oracles/image.js +279 -0
- package/dist/oracles/index.d.ts +4 -0
- package/dist/oracles/index.js +91 -0
- package/dist/oracles/video.d.ts +21 -0
- package/dist/oracles/video.js +411 -0
- package/dist/oracles/web.d.ts +2 -0
- package/dist/oracles/web.js +480 -0
- package/dist/setup/index.d.ts +7 -0
- package/dist/setup/index.js +186 -0
- package/package.json +47 -6
- package/skills/vibecode-anything/SKILL.md +52 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { scoreReport } from "../core/parity.js";
|
|
2
|
+
import { errorMessage, toDiagnostic } from "../core/errors.js";
|
|
3
|
+
import { verifyInvariant as verifyCli } from "./cli.js";
|
|
4
|
+
const DIRECT = {
|
|
5
|
+
command: verifyCli
|
|
6
|
+
};
|
|
7
|
+
const LAZY = {
|
|
8
|
+
image_layout: async () => (await import("./image.js")).verifyInvariant,
|
|
9
|
+
image_perceptual: async () => (await import("./image.js")).verifyInvariant,
|
|
10
|
+
web_route: async () => (await import("./web.js")).verifyInvariant,
|
|
11
|
+
web_flow: async () => (await import("./web.js")).verifyInvariant,
|
|
12
|
+
web_network: async () => (await import("./web.js")).verifyInvariant,
|
|
13
|
+
http: async () => (await import("./api-repo.js")).verifyInvariant,
|
|
14
|
+
repo_exports: async () => (await import("./api-repo.js")).verifyInvariant,
|
|
15
|
+
video_timeline: async () => (await import("./video.js")).verifyInvariant
|
|
16
|
+
};
|
|
17
|
+
export async function getOracle(type) {
|
|
18
|
+
if (DIRECT[type])
|
|
19
|
+
return DIRECT[type];
|
|
20
|
+
if (LAZY[type]) {
|
|
21
|
+
return LAZY[type]();
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
export async function verifyInvariant(invariant, ctx, deps = {}) {
|
|
26
|
+
const started = Date.now();
|
|
27
|
+
const fn = await getOracle(invariant.type);
|
|
28
|
+
if (!fn) {
|
|
29
|
+
return {
|
|
30
|
+
id: invariant.id,
|
|
31
|
+
type: invariant.type,
|
|
32
|
+
severity: invariant.severity,
|
|
33
|
+
status: "skipped",
|
|
34
|
+
score: 0,
|
|
35
|
+
failures: [],
|
|
36
|
+
reason: `Unsupported oracle type: ${invariant.type}`,
|
|
37
|
+
durationMs: Date.now() - started
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
try {
|
|
41
|
+
const result = await fn(invariant, ctx, deps);
|
|
42
|
+
return {
|
|
43
|
+
id: invariant.id,
|
|
44
|
+
type: invariant.type,
|
|
45
|
+
severity: invariant.severity,
|
|
46
|
+
status: result.status || "fail",
|
|
47
|
+
score: typeof result.score === "number" ? result.score : (result.status === "pass" ? 1 : 0),
|
|
48
|
+
...(result.failures ? { failures: result.failures } : {}),
|
|
49
|
+
...(result.diff ? { diff: result.diff } : {}),
|
|
50
|
+
...(result.metrics ? { metrics: result.metrics } : {}),
|
|
51
|
+
...(result.diagnostic ? { diagnostic: result.diagnostic } : {}),
|
|
52
|
+
durationMs: Date.now() - started
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
catch (err) {
|
|
56
|
+
const diag = toDiagnostic(err);
|
|
57
|
+
if (diag.code === "ADAPTER_MISSING") {
|
|
58
|
+
return {
|
|
59
|
+
id: invariant.id,
|
|
60
|
+
type: invariant.type,
|
|
61
|
+
severity: invariant.severity,
|
|
62
|
+
status: "skipped",
|
|
63
|
+
score: 0,
|
|
64
|
+
failures: [],
|
|
65
|
+
reason: diag.message,
|
|
66
|
+
diagnostic: diag,
|
|
67
|
+
durationMs: Date.now() - started
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
id: invariant.id,
|
|
72
|
+
type: invariant.type,
|
|
73
|
+
severity: invariant.severity,
|
|
74
|
+
status: "fail",
|
|
75
|
+
score: 0,
|
|
76
|
+
failures: [errorMessage(err)],
|
|
77
|
+
diagnostic: diag,
|
|
78
|
+
durationMs: Date.now() - started
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export async function verifyContract(contract, ctx, deps = {}) {
|
|
83
|
+
const results = [];
|
|
84
|
+
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));
|
|
89
|
+
}
|
|
90
|
+
return scoreReport(contract, results, { strict: Boolean(ctx.strict) });
|
|
91
|
+
}
|
|
@@ -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 or a video file. */
|
|
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,411 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { VibecodeError } from "../core/errors.js";
|
|
5
|
+
import { artifactPath } from "../core/store.js";
|
|
6
|
+
import { readImageDimensions } from "../core/png.js";
|
|
7
|
+
import { decodeImage, computeSSIM, computeDHash, hammingDistanceHex, comparePalettes, bboxIoU } from "../core/visual.js";
|
|
8
|
+
import { VIDEO_EXTS, IMAGE_EXTS, listFrameFiles, resolveFfmpegAdapter, extractVideoFrames, ffmpegMissingError, extractStates, changedRegionBetween } from "../ingestors/video.js";
|
|
9
|
+
const depObjectIds = new WeakMap();
|
|
10
|
+
let nextDepObjectId = 1;
|
|
11
|
+
function shortHash(input) {
|
|
12
|
+
return crypto.createHash("sha256").update(input).digest("hex").slice(0, 12);
|
|
13
|
+
}
|
|
14
|
+
function depValueToken(value) {
|
|
15
|
+
if (value === undefined)
|
|
16
|
+
return "u";
|
|
17
|
+
if (value === null)
|
|
18
|
+
return "n";
|
|
19
|
+
if (typeof value === "object" || typeof value === "function") {
|
|
20
|
+
let id = depObjectIds.get(value);
|
|
21
|
+
if (id === undefined) {
|
|
22
|
+
id = nextDepObjectId++;
|
|
23
|
+
depObjectIds.set(value, id);
|
|
24
|
+
}
|
|
25
|
+
return `o${id}`;
|
|
26
|
+
}
|
|
27
|
+
return `v:${String(value)}`;
|
|
28
|
+
}
|
|
29
|
+
function depsCacheToken(deps) {
|
|
30
|
+
if (!deps)
|
|
31
|
+
return "none";
|
|
32
|
+
const keys = Object.keys(deps).sort();
|
|
33
|
+
if (keys.length === 0)
|
|
34
|
+
return "empty";
|
|
35
|
+
const rec = deps;
|
|
36
|
+
return keys.map((k) => `${k}=${depValueToken(rec[k])}`).join(",");
|
|
37
|
+
}
|
|
38
|
+
function targetCacheToken(absTarget) {
|
|
39
|
+
try {
|
|
40
|
+
const st = fs.statSync(absTarget);
|
|
41
|
+
if (st.isDirectory()) {
|
|
42
|
+
const files = listFrameFiles(absTarget);
|
|
43
|
+
const sig = files
|
|
44
|
+
.map((f) => {
|
|
45
|
+
const fst = fs.statSync(f);
|
|
46
|
+
return `${path.basename(f)}:${fst.size}:${fst.mtimeMs}`;
|
|
47
|
+
})
|
|
48
|
+
.join("|");
|
|
49
|
+
return `dir:${absTarget}:${shortHash(sig)}`;
|
|
50
|
+
}
|
|
51
|
+
return `file:${absTarget}:${st.size}:${st.mtimeMs}`;
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return `missing:${absTarget}`;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function assertValidDecodedImage(img, filePath) {
|
|
58
|
+
if (!img || !(img.width > 0 && img.height > 0) || !(img.data instanceof Uint8Array) || img.data.length < img.width * img.height * 4) {
|
|
59
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Invalid decoded frame image: ${path.basename(filePath)}`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function listCandidateFrames(dir) {
|
|
63
|
+
return listFrameFiles(dir).map((p, i) => ({ path: p, timestampMs: i * 1000 }));
|
|
64
|
+
}
|
|
65
|
+
/** Load ordered candidate frames from a frame directory or a video file. */
|
|
66
|
+
export async function loadCandidateFrames(target, ctx, deps = {}) {
|
|
67
|
+
if (!target)
|
|
68
|
+
throw new VibecodeError("TARGET_MISSING", "Missing --target <frames-dir-or-video> for video verification.");
|
|
69
|
+
const abs = path.resolve(ctx.cwd || process.cwd(), target);
|
|
70
|
+
if (!fs.existsSync(abs))
|
|
71
|
+
throw new VibecodeError("TARGET_MISSING", `Target not found: ${target}`);
|
|
72
|
+
if (fs.statSync(abs).isDirectory()) {
|
|
73
|
+
const files = listFrameFiles(abs);
|
|
74
|
+
if (files.length === 0)
|
|
75
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `No frames found in directory: ${target}`);
|
|
76
|
+
return listCandidateFrames(abs);
|
|
77
|
+
}
|
|
78
|
+
const ext = path.extname(abs).toLowerCase();
|
|
79
|
+
if (VIDEO_EXTS.has(ext)) {
|
|
80
|
+
const adapter = resolveFfmpegAdapter(deps);
|
|
81
|
+
if (!adapter)
|
|
82
|
+
throw ffmpegMissingError();
|
|
83
|
+
try {
|
|
84
|
+
const { frames } = extractVideoFrames(abs, {
|
|
85
|
+
cwd: ctx.cwd,
|
|
86
|
+
sceneThreshold: 0.18,
|
|
87
|
+
maxFrames: 48,
|
|
88
|
+
cacheKey: `verify-${ctx.currentInvariantId || "video"}-${shortHash(abs)}`
|
|
89
|
+
}, adapter);
|
|
90
|
+
return frames;
|
|
91
|
+
}
|
|
92
|
+
catch (err) {
|
|
93
|
+
if (err instanceof VibecodeError)
|
|
94
|
+
throw err;
|
|
95
|
+
throw new VibecodeError("EXEC_ERROR", `Failed to extract candidate frames from ${path.basename(abs)}: ${err instanceof Error ? err.message : String(err)}`, {
|
|
96
|
+
adapter: "ffmpeg",
|
|
97
|
+
fallbackHint: "Pass a directory of PNG keyframes with --target ./frames/",
|
|
98
|
+
details: { source: abs }
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
if (IMAGE_EXTS.has(ext))
|
|
103
|
+
return [{ path: abs, timestampMs: 0 }];
|
|
104
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported video target: ${ext || "(none)"}`, {
|
|
105
|
+
fallbackHint: "Pass a directory of PNG keyframes with --target ./frames/"
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
function assertValidPngHeaderIfPng(filePath) {
|
|
109
|
+
if (path.extname(filePath).toLowerCase() !== ".png")
|
|
110
|
+
return;
|
|
111
|
+
const dims = readImageDimensions(fs.readFileSync(filePath));
|
|
112
|
+
if (!dims || dims.format !== "png" || !(dims.width > 0 && dims.height > 0)) {
|
|
113
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Corrupt or invalid PNG frame: ${path.basename(filePath)}`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function resolveReferenceState(state, ctx) {
|
|
117
|
+
if (!state || !state.keyframeArtifact) {
|
|
118
|
+
throw new VibecodeError("CONTRACT_INVALID", "Video state missing keyframeArtifact");
|
|
119
|
+
}
|
|
120
|
+
const files = ctx.contract?.artifacts?.files || {};
|
|
121
|
+
const rel = files[state.keyframeArtifact];
|
|
122
|
+
if (!rel) {
|
|
123
|
+
throw new VibecodeError("CONTRACT_INVALID", `Keyframe artifact ${state.keyframeArtifact} not found in contract.artifacts.files`);
|
|
124
|
+
}
|
|
125
|
+
const abs = artifactPath(rel, ctx.cwd);
|
|
126
|
+
if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
|
|
127
|
+
throw new VibecodeError("CONTRACT_NOT_FOUND", `Keyframe artifact missing on disk: ${rel}`);
|
|
128
|
+
}
|
|
129
|
+
return abs;
|
|
130
|
+
}
|
|
131
|
+
function dHashSimilarity(a, b) {
|
|
132
|
+
return Math.max(0, 1 - hammingDistanceHex(a, b) / 64);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Strictly monotone (j_0 < j_1 < ... < j_{K-1}) maximum-score alignment.
|
|
136
|
+
* O(K * M) via running prefix maximum, exactly as specified for the video oracle.
|
|
137
|
+
*
|
|
138
|
+
* @returns {{ score: number, alignment: Array<{ stateIndex: number, candidateIndex: number, similarity: number }>, complete: boolean }}
|
|
139
|
+
*/
|
|
140
|
+
export function alignMonotone(similarity, floor = 0.7) {
|
|
141
|
+
if (!Array.isArray(similarity) || similarity.length === 0) {
|
|
142
|
+
return { score: 0, alignment: [], complete: true };
|
|
143
|
+
}
|
|
144
|
+
const K = similarity.length;
|
|
145
|
+
const M = Array.isArray(similarity[0]) ? similarity[0].length : 0;
|
|
146
|
+
if (M === 0 || K > M)
|
|
147
|
+
return { score: 0, alignment: [], complete: false };
|
|
148
|
+
const NEG = -Infinity;
|
|
149
|
+
let prev = new Array(M).fill(NEG);
|
|
150
|
+
const parents = [];
|
|
151
|
+
for (let k = 0; k < K; k++) {
|
|
152
|
+
const cur = new Array(M).fill(NEG);
|
|
153
|
+
const parentsK = new Array(M).fill(-1);
|
|
154
|
+
let bestPrefix = k === 0 ? 0 : NEG; // score of best alignment ending before j
|
|
155
|
+
let bestPrefixIdx = -1;
|
|
156
|
+
const row = Array.isArray(similarity[k]) ? similarity[k] : [];
|
|
157
|
+
for (let j = 0; j < M; j++) {
|
|
158
|
+
const sim = row[j];
|
|
159
|
+
if (typeof sim === "number" && sim >= floor && bestPrefix > NEG) {
|
|
160
|
+
cur[j] = bestPrefix + sim;
|
|
161
|
+
parentsK[j] = bestPrefixIdx;
|
|
162
|
+
}
|
|
163
|
+
if (prev[j] > bestPrefix) {
|
|
164
|
+
bestPrefix = prev[j];
|
|
165
|
+
bestPrefixIdx = j;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
parents.push(parentsK);
|
|
169
|
+
prev = cur;
|
|
170
|
+
}
|
|
171
|
+
let endIdx = -1;
|
|
172
|
+
let bestScore = NEG;
|
|
173
|
+
for (let j = 0; j < M; j++) {
|
|
174
|
+
if (prev[j] > bestScore) {
|
|
175
|
+
bestScore = prev[j];
|
|
176
|
+
endIdx = j;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (endIdx < 0 || bestScore === NEG) {
|
|
180
|
+
return { score: 0, alignment: [], complete: false };
|
|
181
|
+
}
|
|
182
|
+
const alignment = [];
|
|
183
|
+
let j = endIdx;
|
|
184
|
+
for (let k = K - 1; k >= 0; k--) {
|
|
185
|
+
alignment.push({ stateIndex: k, candidateIndex: j, similarity: similarity[k][j] });
|
|
186
|
+
j = parents[k][j];
|
|
187
|
+
}
|
|
188
|
+
alignment.reverse();
|
|
189
|
+
return { score: bestScore, alignment, complete: alignment.length === K };
|
|
190
|
+
}
|
|
191
|
+
/** First required state that cannot be reached after the greedy prefix (diagnostics only). */
|
|
192
|
+
function describeBlockedState(similarity, floor) {
|
|
193
|
+
const K = Array.isArray(similarity) ? similarity.length : 0;
|
|
194
|
+
const M = K > 0 && Array.isArray(similarity[0]) ? similarity[0].length : 0;
|
|
195
|
+
let last = -1;
|
|
196
|
+
for (let k = 0; k < K; k++) {
|
|
197
|
+
const row = Array.isArray(similarity[k]) ? similarity[k] : [];
|
|
198
|
+
let found = -1;
|
|
199
|
+
for (let j = last + 1; j < M; j++) {
|
|
200
|
+
if (row[j] >= floor) {
|
|
201
|
+
found = j;
|
|
202
|
+
break;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (found < 0) {
|
|
206
|
+
let bestSim = -Infinity;
|
|
207
|
+
let bestAt = -1;
|
|
208
|
+
for (let j = 0; j < M; j++) {
|
|
209
|
+
if (typeof row[j] === "number" && row[j] > bestSim) {
|
|
210
|
+
bestSim = row[j];
|
|
211
|
+
bestAt = j;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return {
|
|
215
|
+
stateIndex: k,
|
|
216
|
+
bestSimilarity: bestAt >= 0 ? bestSim : 0,
|
|
217
|
+
bestCandidateIndex: bestAt,
|
|
218
|
+
afterCandidateIndex: last
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
last = found;
|
|
222
|
+
}
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
async function decodeCached(filePath, ctx, deps) {
|
|
226
|
+
if (!ctx?.runtimeCache) {
|
|
227
|
+
const decoded = await decodeImage(filePath, deps);
|
|
228
|
+
assertValidDecodedImage(decoded, filePath);
|
|
229
|
+
return decoded;
|
|
230
|
+
}
|
|
231
|
+
const st = fs.statSync(filePath);
|
|
232
|
+
const key = `vidimg:${filePath}:${st.size}:${st.mtimeMs}:${depValueToken(deps?.sharp)}`;
|
|
233
|
+
const cached = ctx.runtimeCache[key];
|
|
234
|
+
if (!cached) {
|
|
235
|
+
const decoded = await decodeImage(filePath, deps);
|
|
236
|
+
assertValidDecodedImage(decoded, filePath);
|
|
237
|
+
ctx.runtimeCache[key] = decoded;
|
|
238
|
+
return decoded;
|
|
239
|
+
}
|
|
240
|
+
assertValidDecodedImage(cached, filePath);
|
|
241
|
+
return cached;
|
|
242
|
+
}
|
|
243
|
+
async function buildReferenceStates(invariant, ctx, deps) {
|
|
244
|
+
const states = [];
|
|
245
|
+
for (const state of invariant.expected?.states || []) {
|
|
246
|
+
const file = resolveReferenceState(state, ctx);
|
|
247
|
+
assertValidPngHeaderIfPng(file);
|
|
248
|
+
states.push({ ...state, abs: file, img: await decodeCached(file, ctx, deps) });
|
|
249
|
+
}
|
|
250
|
+
return states;
|
|
251
|
+
}
|
|
252
|
+
async function computeSimilarityMatrix(refStates, candStates) {
|
|
253
|
+
const matrix = [];
|
|
254
|
+
for (const ref of refStates) {
|
|
255
|
+
const row = [];
|
|
256
|
+
for (const cand of candStates) {
|
|
257
|
+
const ssim = computeSSIM(ref.img, cand.img).ssim;
|
|
258
|
+
const hashSim = dHashSimilarity(ref.dHash || computeDHash(ref.img), cand.dHash);
|
|
259
|
+
row.push(0.7 * ssim + 0.3 * hashSim);
|
|
260
|
+
}
|
|
261
|
+
matrix.push(row);
|
|
262
|
+
}
|
|
263
|
+
return matrix;
|
|
264
|
+
}
|
|
265
|
+
async function verifyTimeline(invariant, ctx, deps) {
|
|
266
|
+
const tolerance = invariant.tolerance || {};
|
|
267
|
+
const floor = typeof tolerance.stateMatchFloor === "number" ? tolerance.stateMatchFloor : 0.7;
|
|
268
|
+
const expected = invariant.expected || {};
|
|
269
|
+
const perceptualOnly = invariant.input?.perceptualOnly === true;
|
|
270
|
+
const refStates = await buildReferenceStates(invariant, ctx, deps);
|
|
271
|
+
if (refStates.length === 0) {
|
|
272
|
+
throw new VibecodeError("CONTRACT_INVALID", `Invariant ${invariant.id} has no expected.states`);
|
|
273
|
+
}
|
|
274
|
+
let candStates;
|
|
275
|
+
const absTarget = ctx.target ? path.resolve(ctx.cwd || process.cwd(), ctx.target) : null;
|
|
276
|
+
const cacheKey = absTarget ? `video:${targetCacheToken(absTarget)}:${depsCacheToken(deps)}` : null;
|
|
277
|
+
if (ctx.runtimeCache && cacheKey && Array.isArray(ctx.runtimeCache[cacheKey])) {
|
|
278
|
+
candStates = ctx.runtimeCache[cacheKey];
|
|
279
|
+
}
|
|
280
|
+
else {
|
|
281
|
+
const frames = await loadCandidateFrames(ctx.target, { ...ctx, currentInvariantId: invariant.id }, deps);
|
|
282
|
+
for (const f of frames) {
|
|
283
|
+
if (!f || typeof f.path !== "string" || !fs.existsSync(f.path)) {
|
|
284
|
+
throw new VibecodeError("EXEC_ERROR", `Extracted candidate frame missing on disk: ${f?.path ? path.basename(f.path) : "(unknown)"}`, {
|
|
285
|
+
adapter: "ffmpeg",
|
|
286
|
+
fallbackHint: "Pass a directory of PNG keyframes with --target ./frames/",
|
|
287
|
+
details: { source: absTarget, framePath: f?.path ?? null }
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
assertValidPngHeaderIfPng(f.path);
|
|
291
|
+
}
|
|
292
|
+
const extracted = await extractStates(frames, { deps });
|
|
293
|
+
for (const state of extracted.states) {
|
|
294
|
+
assertValidDecodedImage(state.img, state.path);
|
|
295
|
+
}
|
|
296
|
+
candStates = extracted.states;
|
|
297
|
+
if (ctx.runtimeCache && cacheKey)
|
|
298
|
+
ctx.runtimeCache[cacheKey] = candStates;
|
|
299
|
+
}
|
|
300
|
+
if (candStates.length === 0) {
|
|
301
|
+
return {
|
|
302
|
+
status: "fail",
|
|
303
|
+
score: 0,
|
|
304
|
+
failures: ["candidate video produced no frames/states"],
|
|
305
|
+
metrics: { stateCount: 0 }
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
const simCacheKey = ctx.runtimeCache && cacheKey
|
|
309
|
+
? `vidsim:${refStates.map((s) => `${s.abs}:${s.dHash || ""}`).join("|")}:${cacheKey}`
|
|
310
|
+
: null;
|
|
311
|
+
let similarity;
|
|
312
|
+
if (simCacheKey && Array.isArray(ctx.runtimeCache?.[simCacheKey])) {
|
|
313
|
+
similarity = ctx.runtimeCache[simCacheKey];
|
|
314
|
+
}
|
|
315
|
+
else {
|
|
316
|
+
similarity = await computeSimilarityMatrix(refStates, candStates);
|
|
317
|
+
if (simCacheKey && ctx.runtimeCache)
|
|
318
|
+
ctx.runtimeCache[simCacheKey] = similarity;
|
|
319
|
+
}
|
|
320
|
+
const result = alignMonotone(similarity, floor);
|
|
321
|
+
const failures = [];
|
|
322
|
+
const metrics = {
|
|
323
|
+
referenceStates: refStates.length,
|
|
324
|
+
candidateStates: candStates.length,
|
|
325
|
+
stateMatchFloor: floor,
|
|
326
|
+
alignment: result.alignment.map((a) => ({
|
|
327
|
+
stateId: refStates[a.stateIndex].id,
|
|
328
|
+
candidateIndex: a.candidateIndex,
|
|
329
|
+
similarity: Number(a.similarity.toFixed(4))
|
|
330
|
+
}))
|
|
331
|
+
};
|
|
332
|
+
if (!result.complete) {
|
|
333
|
+
const blocked = describeBlockedState(similarity, floor);
|
|
334
|
+
const hardParity = result.alignment.length / refStates.length;
|
|
335
|
+
metrics.hardParity = hardParity;
|
|
336
|
+
if (blocked) {
|
|
337
|
+
const ref = refStates[blocked.stateIndex];
|
|
338
|
+
const where = blocked.bestCandidateIndex >= 0 ? `at candidate #${blocked.bestCandidateIndex}` : "no candidate frames";
|
|
339
|
+
failures.push(`state ${ref.id} not reachable in monotonic order (best similarity ${blocked.bestSimilarity.toFixed(3)} ` +
|
|
340
|
+
`${where}, floor ${floor})`);
|
|
341
|
+
}
|
|
342
|
+
else {
|
|
343
|
+
failures.push("state sequence is not a strictly monotonic subsequence of the candidate timeline");
|
|
344
|
+
}
|
|
345
|
+
if (perceptualOnly) {
|
|
346
|
+
// Soft invariant still reports the misalignment but scores any correctly aligned states.
|
|
347
|
+
const alignedScore = result.alignment.length
|
|
348
|
+
? result.alignment.reduce((sum, a) => sum + a.similarity, 0) / result.alignment.length
|
|
349
|
+
: 0;
|
|
350
|
+
return { status: "fail", score: alignedScore, failures, metrics };
|
|
351
|
+
}
|
|
352
|
+
return { status: "fail", score: hardParity, failures, metrics };
|
|
353
|
+
}
|
|
354
|
+
metrics.hardParity = 1;
|
|
355
|
+
if (!perceptualOnly) {
|
|
356
|
+
return { status: "pass", score: 1, failures, metrics };
|
|
357
|
+
}
|
|
358
|
+
// Soft perceptual checks on aligned pairs.
|
|
359
|
+
const minSSIM = typeof tolerance.minKeyframeSSIM === "number" ? tolerance.minKeyframeSSIM : 0.85;
|
|
360
|
+
const maxHamming = typeof tolerance.maxHammingDistance === "number" ? tolerance.maxHammingDistance : 14;
|
|
361
|
+
const minPalette = typeof tolerance.minPaletteSimilarity === "number" ? tolerance.minPaletteSimilarity : 0.8;
|
|
362
|
+
const minMotionIoU = typeof tolerance.minMotionRegionIoU === "number" ? tolerance.minMotionRegionIoU : 0.55;
|
|
363
|
+
const scores = [];
|
|
364
|
+
const keyframes = [];
|
|
365
|
+
for (const { stateIndex, candidateIndex } of result.alignment) {
|
|
366
|
+
const ref = refStates[stateIndex];
|
|
367
|
+
const cand = candStates[candidateIndex];
|
|
368
|
+
const ssim = Math.max(0, Math.min(1, computeSSIM(ref.img, cand.img).ssim));
|
|
369
|
+
const hamming = hammingDistanceHex(ref.dHash || computeDHash(ref.img), cand.dHash);
|
|
370
|
+
const palette = comparePalettes(ref.palette || [], cand.palette || []);
|
|
371
|
+
keyframes.push({
|
|
372
|
+
stateId: ref.id,
|
|
373
|
+
candidateIndex,
|
|
374
|
+
ssim: Number(ssim.toFixed(4)),
|
|
375
|
+
hammingDistance: hamming,
|
|
376
|
+
paletteSimilarity: Number(palette.toFixed(4))
|
|
377
|
+
});
|
|
378
|
+
if (ssim < minSSIM)
|
|
379
|
+
failures.push(`${ref.id}: ssim ${ssim.toFixed(4)} < ${minSSIM}`);
|
|
380
|
+
if (hamming > maxHamming)
|
|
381
|
+
failures.push(`${ref.id}: hammingDistance ${hamming} > ${maxHamming}`);
|
|
382
|
+
if (palette < minPalette)
|
|
383
|
+
failures.push(`${ref.id}: paletteSimilarity ${palette.toFixed(4)} < ${minPalette}`);
|
|
384
|
+
scores.push(Math.max(0, Math.min(1, Math.min(ssim, palette))));
|
|
385
|
+
}
|
|
386
|
+
metrics.keyframes = keyframes;
|
|
387
|
+
// Motion-region IoU across aligned transitions.
|
|
388
|
+
const indexByStateId = new Map(result.alignment.map((a) => [refStates[a.stateIndex].id, a.candidateIndex]));
|
|
389
|
+
const motion = [];
|
|
390
|
+
for (const transition of expected.transitions || []) {
|
|
391
|
+
const fromIdx = indexByStateId.get(transition.from);
|
|
392
|
+
const toIdx = indexByStateId.get(transition.to);
|
|
393
|
+
if (fromIdx == null || toIdx == null || !transition.changedRegion)
|
|
394
|
+
continue;
|
|
395
|
+
const { changedRegion } = changedRegionBetween(candStates[fromIdx].img, candStates[toIdx].img);
|
|
396
|
+
const iou = bboxIoU(transition.changedRegion, changedRegion);
|
|
397
|
+
motion.push({ from: transition.from, to: transition.to, iou: Number(iou.toFixed(4)) });
|
|
398
|
+
if (iou < minMotionIoU)
|
|
399
|
+
failures.push(`motion region ${transition.from}->${transition.to} IoU ${iou.toFixed(4)} < ${minMotionIoU}`);
|
|
400
|
+
scores.push(iou);
|
|
401
|
+
}
|
|
402
|
+
metrics.motionRegions = motion;
|
|
403
|
+
const score = scores.length ? Math.max(0, Math.min(1, scores.reduce((a, b) => a + b, 0) / scores.length)) : 1;
|
|
404
|
+
return { status: failures.length ? "fail" : "pass", score, failures, metrics };
|
|
405
|
+
}
|
|
406
|
+
export async function verifyInvariant(invariant, ctx, deps = {}) {
|
|
407
|
+
if (invariant.type !== "video_timeline") {
|
|
408
|
+
throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported video invariant type: ${invariant.type}`);
|
|
409
|
+
}
|
|
410
|
+
return verifyTimeline(invariant, ctx, deps);
|
|
411
|
+
}
|