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.
- package/README.md +239 -67
- package/dist/cli.js +2140 -73
- package/dist/core/adapters.d.ts +26 -3
- package/dist/core/adapters.js +411 -25
- 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/docs-export.d.ts +37 -0
- package/dist/core/docs-export.js +2706 -0
- package/dist/core/doctor.d.ts +21 -1
- package/dist/core/doctor.js +234 -21
- package/dist/core/exec.d.ts +26 -2
- package/dist/core/exec.js +235 -8
- 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 +6 -1
- package/dist/core/parity.js +36 -1
- package/dist/core/playwright-exporter.d.ts +23 -0
- package/dist/core/playwright-exporter.js +1343 -0
- package/dist/core/png.js +45 -9
- 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 +3 -2
- package/dist/core/schema.js +460 -17
- 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/spec-writer.d.ts +9 -0
- package/dist/core/spec-writer.js +1202 -0
- package/dist/core/store.d.ts +11 -2
- package/dist/core/store.js +128 -8
- 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 +182 -14
- package/dist/core/visual-semantic.d.ts +67 -0
- package/dist/core/visual-semantic.js +673 -0
- package/dist/core/visual.js +65 -16
- package/dist/core/watch.d.ts +28 -3
- package/dist/core/watch.js +222 -12
- 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 +2 -1
- package/dist/ingestors/api-repo.js +483 -85
- package/dist/ingestors/asyncapi.d.ts +26 -0
- package/dist/ingestors/asyncapi.js +2105 -0
- package/dist/ingestors/bridges.d.ts +2 -0
- package/dist/ingestors/bridges.js +702 -0
- package/dist/ingestors/cli.d.ts +2 -1
- package/dist/ingestors/cli.js +234 -46
- 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/index.js +486 -6
- 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 +4 -1
- package/dist/ingestors/video.js +86 -36
- package/dist/ingestors/web.d.ts +16 -1
- package/dist/ingestors/web.js +474 -32
- package/dist/mcp/server.js +3532 -67
- package/dist/oracles/api-repo.js +102 -30
- package/dist/oracles/cli.js +65 -17
- package/dist/oracles/http-workflow.d.ts +68 -0
- package/dist/oracles/http-workflow.js +828 -0
- package/dist/oracles/image.js +178 -28
- package/dist/oracles/index.d.ts +3 -1
- package/dist/oracles/index.js +243 -14
- 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 +1 -1
- package/dist/oracles/video.js +232 -16
- package/dist/oracles/web.js +464 -73
- 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.js +145 -33
- package/package.json +56 -47
- package/skills/vibecode-anything/SKILL.md +75 -52
|
@@ -0,0 +1,1083 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zero-dependency root-cause failure triage, spatial visual enrichment,
|
|
3
|
+
* repair-brief generation, and terminal pretty formatting.
|
|
4
|
+
*/
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { hasCrossPlatformPathEscape, isInsideVaultDirectory, isPathWithinDir, isRecordSafe, redactSensitiveText, safeOwnProp, sanitizeSingleLine } from "../core/security.js";
|
|
8
|
+
import { computeBBoxShiftVectors, computeSpatialHeatmapFromFiles } from "./spatial.js";
|
|
9
|
+
const ANSI = {
|
|
10
|
+
reset: "\x1b[0m",
|
|
11
|
+
bold: "\x1b[1m",
|
|
12
|
+
dim: "\x1b[2m",
|
|
13
|
+
red: "\x1b[31m",
|
|
14
|
+
green: "\x1b[32m",
|
|
15
|
+
yellow: "\x1b[33m",
|
|
16
|
+
cyan: "\x1b[36m"
|
|
17
|
+
};
|
|
18
|
+
const DEFAULT_MAX_EVIDENCE = 4;
|
|
19
|
+
const MAX_EVIDENCE_ITEMS_CAP = 50;
|
|
20
|
+
const DEFAULT_MAX_BRIEF_CHARS = 2400;
|
|
21
|
+
const MAX_CLASSIFY_CHARS = 32_768;
|
|
22
|
+
const MAX_EVIDENCE_LINE_CHARS = 4096;
|
|
23
|
+
const MAX_DIFF_LINES = 200;
|
|
24
|
+
const MAX_DIFF_LINE_CHARS = 4096;
|
|
25
|
+
const MAX_BBOX_REGIONS = 256;
|
|
26
|
+
const REDACTED_HOLDOUT_TOKEN = "[REDACTED_HOLDOUT]";
|
|
27
|
+
// Linear-time classification patterns.
|
|
28
|
+
const ISO_TS_RE = /\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b/g;
|
|
29
|
+
const UUID_RE = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi;
|
|
30
|
+
const EPOCH_MS_RE = /\b1[6-9]\d{11}\b/g;
|
|
31
|
+
const TEMP_PATH_RE = /(?:\/(?:tmp|var\/folders)\/[^\s"'`,;]+|[A-Za-z]:\\Users\\[^\\\s"'`,;]+(?:\\AppData\\Local)?\\Temp\\[^\s"'`,;]+)/gi;
|
|
32
|
+
const PID_RE = /\bpid\s*[:=]\s*\d+\b/gi;
|
|
33
|
+
const INT_TOKEN_RE = /-?\d+/g;
|
|
34
|
+
const CLI_FLAG_TOKEN_RE = /(?:^|[\s"'`(])(--[A-Za-z0-9][A-Za-z0-9_-]*|-[A-Za-z])\b/;
|
|
35
|
+
const isRecord = isRecordSafe;
|
|
36
|
+
const ownProp = safeOwnProp;
|
|
37
|
+
function style(text, codes, useColor) {
|
|
38
|
+
return useColor ? `${codes}${text}${ANSI.reset}` : text;
|
|
39
|
+
}
|
|
40
|
+
function makeCls(category, confidence, headline, suggestedFix) {
|
|
41
|
+
return { category, confidence, headline: sanitizeSingleLine(headline), suggestedFix: sanitizeSingleLine(suggestedFix) };
|
|
42
|
+
}
|
|
43
|
+
function isRedactedHoldout(result, invariant) {
|
|
44
|
+
if (invariant?.holdout === true)
|
|
45
|
+
return true;
|
|
46
|
+
if (!isRecord(result))
|
|
47
|
+
return false;
|
|
48
|
+
const metrics = ownProp(result, "metrics");
|
|
49
|
+
return (ownProp(result, "redacted") === true ||
|
|
50
|
+
ownProp(result, "holdout") === true ||
|
|
51
|
+
ownProp(metrics, "redacted") === true ||
|
|
52
|
+
ownProp(metrics, "holdout") === true);
|
|
53
|
+
}
|
|
54
|
+
function extractUnifiedDiff(diff) {
|
|
55
|
+
if (!isRecord(diff))
|
|
56
|
+
return null;
|
|
57
|
+
const goldenStdout = ownProp(diff, "goldenStdout");
|
|
58
|
+
const stdout = ownProp(diff, "stdout");
|
|
59
|
+
const body = ownProp(diff, "body");
|
|
60
|
+
for (const c of [
|
|
61
|
+
ownProp(diff, "unified"),
|
|
62
|
+
ownProp(goldenStdout, "unified"),
|
|
63
|
+
ownProp(stdout, "unified"),
|
|
64
|
+
ownProp(body, "unified")
|
|
65
|
+
]) {
|
|
66
|
+
if (typeof c === "string" && c.trim())
|
|
67
|
+
return c;
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
function collectNestedPayloadDiffs(diff) {
|
|
72
|
+
if (!isRecord(diff))
|
|
73
|
+
return [];
|
|
74
|
+
const containers = [diff];
|
|
75
|
+
const steps = ownProp(diff, "steps");
|
|
76
|
+
if (Array.isArray(steps)) {
|
|
77
|
+
for (const entry of steps.slice(0, 64)) {
|
|
78
|
+
if (isRecord(entry))
|
|
79
|
+
containers.push(entry);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
else if (isRecord(steps)) {
|
|
83
|
+
for (const entry of Object.values(steps).slice(0, 64)) {
|
|
84
|
+
if (isRecord(entry))
|
|
85
|
+
containers.push(entry);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const orderedEvents = ownProp(diff, "orderedEvents");
|
|
89
|
+
if (Array.isArray(orderedEvents)) {
|
|
90
|
+
for (const entry of orderedEvents.slice(0, 64)) {
|
|
91
|
+
if (isRecord(entry))
|
|
92
|
+
containers.push(entry);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const terminalEvent = ownProp(diff, "terminalEvent");
|
|
96
|
+
if (isRecord(terminalEvent))
|
|
97
|
+
containers.push(terminalEvent);
|
|
98
|
+
return containers;
|
|
99
|
+
}
|
|
100
|
+
function extractDiffEntries(result) {
|
|
101
|
+
if (!isRecord(result))
|
|
102
|
+
return [];
|
|
103
|
+
const containers = collectNestedPayloadDiffs(ownProp(result, "diff"));
|
|
104
|
+
const out = [];
|
|
105
|
+
for (const container of containers) {
|
|
106
|
+
for (const key of ["jsonPaths", "jsonSubset"]) {
|
|
107
|
+
const arr = ownProp(container, key);
|
|
108
|
+
if (!Array.isArray(arr))
|
|
109
|
+
continue;
|
|
110
|
+
for (const entry of arr.slice(0, 64)) {
|
|
111
|
+
if (isRecord(entry))
|
|
112
|
+
out.push(entry);
|
|
113
|
+
if (out.length >= 64)
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
function parseUnifiedDiff(unified) {
|
|
121
|
+
const removed = [];
|
|
122
|
+
const added = [];
|
|
123
|
+
let contextCount = 0;
|
|
124
|
+
const bounded = unified.length > MAX_CLASSIFY_CHARS ? unified.slice(0, MAX_CLASSIFY_CHARS) : unified;
|
|
125
|
+
const lines = bounded.replace(/\r\n/g, "\n").split("\n");
|
|
126
|
+
const limit = Math.min(lines.length, MAX_DIFF_LINES);
|
|
127
|
+
for (let i = 0; i < limit; i++) {
|
|
128
|
+
const line = lines[i];
|
|
129
|
+
if (line.startsWith("---") || line.startsWith("+++") || line.startsWith("@@"))
|
|
130
|
+
continue;
|
|
131
|
+
const clipped = line.length > MAX_DIFF_LINE_CHARS ? line.slice(0, MAX_DIFF_LINE_CHARS) : line;
|
|
132
|
+
if (clipped.startsWith("-"))
|
|
133
|
+
removed.push(clipped.slice(1));
|
|
134
|
+
else if (clipped.startsWith("+"))
|
|
135
|
+
added.push(clipped.slice(1));
|
|
136
|
+
else if (clipped.startsWith(" "))
|
|
137
|
+
contextCount++;
|
|
138
|
+
}
|
|
139
|
+
return { removed, added, contextCount };
|
|
140
|
+
}
|
|
141
|
+
function getFailureStrings(result) {
|
|
142
|
+
if (!isRecord(result))
|
|
143
|
+
return [];
|
|
144
|
+
const raw = ownProp(result, "failures");
|
|
145
|
+
if (!Array.isArray(raw))
|
|
146
|
+
return [];
|
|
147
|
+
const out = [];
|
|
148
|
+
for (const f of raw) {
|
|
149
|
+
if (typeof f === "string" && f.trim())
|
|
150
|
+
out.push(f.trim());
|
|
151
|
+
}
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
function collectRawSignals(result) {
|
|
155
|
+
const failures = getFailureStrings(result);
|
|
156
|
+
const reason = ownProp(result, "reason");
|
|
157
|
+
if (typeof reason === "string" && reason.trim())
|
|
158
|
+
failures.push(reason.trim());
|
|
159
|
+
const diag = ownProp(result, "diagnostic");
|
|
160
|
+
const diagMsg = ownProp(diag, "message");
|
|
161
|
+
if (typeof diagMsg === "string" && diagMsg.trim()) {
|
|
162
|
+
failures.push(diagMsg.trim());
|
|
163
|
+
}
|
|
164
|
+
const unified = extractUnifiedDiff(ownProp(result, "diff"));
|
|
165
|
+
const parts = [];
|
|
166
|
+
let totalLen = 0;
|
|
167
|
+
for (const f of failures) {
|
|
168
|
+
if (totalLen >= MAX_CLASSIFY_CHARS)
|
|
169
|
+
break;
|
|
170
|
+
const take = f.slice(0, MAX_CLASSIFY_CHARS - totalLen);
|
|
171
|
+
parts.push(take);
|
|
172
|
+
totalLen += take.length + 1;
|
|
173
|
+
}
|
|
174
|
+
if (unified && totalLen < MAX_CLASSIFY_CHARS) {
|
|
175
|
+
parts.push(unified.slice(0, MAX_CLASSIFY_CHARS - totalLen));
|
|
176
|
+
}
|
|
177
|
+
return { failures, text: parts.join("\n"), unified };
|
|
178
|
+
}
|
|
179
|
+
function hasDistinctMatches(text, re, minCount = 2) {
|
|
180
|
+
const copy = new RegExp(re.source, re.flags);
|
|
181
|
+
const seen = new Set();
|
|
182
|
+
let m;
|
|
183
|
+
while ((m = copy.exec(text)) !== null) {
|
|
184
|
+
seen.add(m[0].toLowerCase());
|
|
185
|
+
if (seen.size >= minCount)
|
|
186
|
+
return true;
|
|
187
|
+
}
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
function matchesDynamicToken(value) {
|
|
191
|
+
return (typeof value === "string" &&
|
|
192
|
+
(new RegExp(ISO_TS_RE.source).test(value) ||
|
|
193
|
+
new RegExp(UUID_RE.source, "i").test(value) ||
|
|
194
|
+
new RegExp(TEMP_PATH_RE.source, "i").test(value)));
|
|
195
|
+
}
|
|
196
|
+
function hasDynamicDrift(result, text) {
|
|
197
|
+
if (/\blatency\s+\d+ms\s*>\s*maxLatencyMs\b/i.test(text) ||
|
|
198
|
+
/\b(?:stream|ws)\s+duration\s+\d+ms\s*>\s*maxDurationMs\b/i.test(text) ||
|
|
199
|
+
/\b(?:flaky|nondeterminis[a-z]*|non-determinis[a-z]*|intermittent|timestamp\s+drift|uuid\s+(?:drift|mismatch))\b/i.test(text)) {
|
|
200
|
+
return true;
|
|
201
|
+
}
|
|
202
|
+
if (hasDistinctMatches(text, ISO_TS_RE) ||
|
|
203
|
+
hasDistinctMatches(text, UUID_RE) ||
|
|
204
|
+
hasDistinctMatches(text, EPOCH_MS_RE) ||
|
|
205
|
+
hasDistinctMatches(text, TEMP_PATH_RE) ||
|
|
206
|
+
hasDistinctMatches(text, PID_RE)) {
|
|
207
|
+
return true;
|
|
208
|
+
}
|
|
209
|
+
return extractDiffEntries(result).some((e) => e.expected !== e.actual && matchesDynamicToken(e.expected) && matchesDynamicToken(e.actual));
|
|
210
|
+
}
|
|
211
|
+
function linePairOffByOne(a, b) {
|
|
212
|
+
if (a.length > MAX_DIFF_LINE_CHARS || b.length > MAX_DIFF_LINE_CHARS)
|
|
213
|
+
return null;
|
|
214
|
+
const numsA = [...a.matchAll(INT_TOKEN_RE)];
|
|
215
|
+
const numsB = [...b.matchAll(INT_TOKEN_RE)];
|
|
216
|
+
if (numsA.length === 0 || numsA.length !== numsB.length || numsA.length > 64)
|
|
217
|
+
return null;
|
|
218
|
+
if (a.replace(INT_TOKEN_RE, "#") !== b.replace(INT_TOKEN_RE, "#"))
|
|
219
|
+
return null;
|
|
220
|
+
let found = null;
|
|
221
|
+
for (let i = 0; i < numsA.length; i++) {
|
|
222
|
+
const va = Number.parseInt(numsA[i][0], 10);
|
|
223
|
+
const vb = Number.parseInt(numsB[i][0], 10);
|
|
224
|
+
if (va === vb)
|
|
225
|
+
continue;
|
|
226
|
+
if (Math.abs(va - vb) === 1 && !found)
|
|
227
|
+
found = { expected: va, actual: vb };
|
|
228
|
+
else
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
return found;
|
|
232
|
+
}
|
|
233
|
+
function safeStableSerialize(value, depth = 0, seen = new WeakSet(), budget = { count: 0 }) {
|
|
234
|
+
if (budget.count >= 256)
|
|
235
|
+
return '"[Truncated]"';
|
|
236
|
+
budget.count++;
|
|
237
|
+
if (value === null)
|
|
238
|
+
return "null";
|
|
239
|
+
if (value === undefined)
|
|
240
|
+
return "undefined";
|
|
241
|
+
if (typeof value === "string")
|
|
242
|
+
return JSON.stringify(value.length > 256 ? value.slice(0, 256) : value);
|
|
243
|
+
if (typeof value === "number" || typeof value === "boolean")
|
|
244
|
+
return String(value);
|
|
245
|
+
if (typeof value === "bigint")
|
|
246
|
+
return `${value.toString()}n`;
|
|
247
|
+
if (typeof value !== "object")
|
|
248
|
+
return JSON.stringify(String(value));
|
|
249
|
+
const obj = value;
|
|
250
|
+
if (seen.has(obj))
|
|
251
|
+
return '"[Circular]"';
|
|
252
|
+
if (depth >= 8)
|
|
253
|
+
return '"[MaxDepth]"';
|
|
254
|
+
seen.add(obj);
|
|
255
|
+
try {
|
|
256
|
+
if (Array.isArray(obj)) {
|
|
257
|
+
const items = obj.slice(0, 64).map((item) => safeStableSerialize(item, depth + 1, seen, budget));
|
|
258
|
+
return `[${items.join(",")}]`;
|
|
259
|
+
}
|
|
260
|
+
const rec = obj;
|
|
261
|
+
const keys = Object.keys(rec).slice(0, 64).sort();
|
|
262
|
+
const parts = [];
|
|
263
|
+
for (const k of keys) {
|
|
264
|
+
let v;
|
|
265
|
+
try {
|
|
266
|
+
v = rec[k];
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
v = "[Unreadable]";
|
|
270
|
+
}
|
|
271
|
+
parts.push(`${JSON.stringify(k)}:${safeStableSerialize(v, depth + 1, seen, budget)}`);
|
|
272
|
+
}
|
|
273
|
+
return `{${parts.join(",")}}`;
|
|
274
|
+
}
|
|
275
|
+
finally {
|
|
276
|
+
seen.delete(obj);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
function detectOffByOne(result, failures, unified) {
|
|
280
|
+
const diffObj = ownProp(result, "diff");
|
|
281
|
+
if (result.type === "http_stream") {
|
|
282
|
+
const ordered = ownProp(diffObj, "orderedEvents");
|
|
283
|
+
if ((Array.isArray(ordered) && ordered.length >= 2) ||
|
|
284
|
+
failures.some((line) => /\bevent\[\d+\]\.event:/i.test(line))) {
|
|
285
|
+
return null;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (result.type === "ws_protocol") {
|
|
289
|
+
const wsSteps = ownProp(diffObj, "steps");
|
|
290
|
+
if (Array.isArray(wsSteps) && wsSteps.length >= 2)
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
293
|
+
for (const e of extractDiffEntries(result)) {
|
|
294
|
+
if (typeof e.expected === "number" &&
|
|
295
|
+
typeof e.actual === "number" &&
|
|
296
|
+
Number.isInteger(e.expected) &&
|
|
297
|
+
Number.isInteger(e.actual) &&
|
|
298
|
+
Math.abs(e.expected - e.actual) === 1) {
|
|
299
|
+
const p = typeof e.path === "string" ? e.path : "$";
|
|
300
|
+
return { high: true, detail: `${p} expected ${e.expected}, got ${e.actual} (delta +/-1)` };
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
for (const line of failures) {
|
|
304
|
+
if (/(?:^|:\s*)(?:exitCode|status|closeCode)\s+expected\b/i.test(line))
|
|
305
|
+
continue;
|
|
306
|
+
const expGot = /\bexpected\s+(?:count\s+|length\s+)?(-?\d+)\s*,\s*(?:got|found|actual)\s+(-?\d+)\b/i.exec(line);
|
|
307
|
+
if (expGot && Math.abs(Number.parseInt(expGot[1], 10) - Number.parseInt(expGot[2], 10)) === 1) {
|
|
308
|
+
return { high: true, detail: `expected ${expGot[1]}, got ${expGot[2]} (off by 1)` };
|
|
309
|
+
}
|
|
310
|
+
const foundLt = /\bfound\s+(-?\d+)\s*<\s*(-?\d+)\b/i.exec(line);
|
|
311
|
+
if (foundLt) {
|
|
312
|
+
const a = Number.parseInt(foundLt[1], 10);
|
|
313
|
+
const b = Number.parseInt(foundLt[2], 10);
|
|
314
|
+
if (b >= 2 && Math.abs(a - b) === 1)
|
|
315
|
+
return { high: true, detail: `found ${a}, expected at least ${b} (off by 1)` };
|
|
316
|
+
}
|
|
317
|
+
if (/\b(?:off[- ]by[- ]one|fencepost|index\s+out\s+of\s+(?:bounds|range))\b/i.test(line)) {
|
|
318
|
+
return { high: true, detail: line };
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
if (unified) {
|
|
322
|
+
const { removed, added, contextCount } = parseUnifiedDiff(unified);
|
|
323
|
+
if (removed.length > 0 && removed.length === added.length && removed.length <= 4) {
|
|
324
|
+
for (let i = 0; i < removed.length; i++) {
|
|
325
|
+
const pair = linePairOffByOne(removed[i], added[i]);
|
|
326
|
+
if (pair)
|
|
327
|
+
return { high: true, detail: `output value expected ${pair.expected}, got ${pair.actual} (off by 1)` };
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
if (added.length + removed.length === 1 && contextCount >= 1) {
|
|
331
|
+
return { high: false, detail: `golden diff has ${removed.length === 1 ? "missing" : "extra"} 1 boundary line` };
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
const diff = ownProp(result, "diff");
|
|
335
|
+
if (isRecord(diff)) {
|
|
336
|
+
for (const h of [diff, ownProp(diff, "goldenStdout"), ownProp(diff, "stdout"), ownProp(diff, "body")]) {
|
|
337
|
+
const added = ownProp(h, "added");
|
|
338
|
+
const removed = ownProp(h, "removed");
|
|
339
|
+
if (typeof added === "number" && typeof removed === "number" && added + removed === 1) {
|
|
340
|
+
return { high: false, detail: `output boundary drift (${removed === 1 ? "1 line removed" : "1 line added"})` };
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return null;
|
|
345
|
+
}
|
|
346
|
+
function hasReorderedItems(result, unified) {
|
|
347
|
+
if (unified) {
|
|
348
|
+
const { removed, added } = parseUnifiedDiff(unified);
|
|
349
|
+
if (removed.length >= 2 && removed.length === added.length) {
|
|
350
|
+
const rSorted = [...removed].sort();
|
|
351
|
+
const aSorted = [...added].sort();
|
|
352
|
+
if (rSorted.every((line, i) => line === aSorted[i]))
|
|
353
|
+
return true;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
return extractDiffEntries(result).some((e) => {
|
|
357
|
+
const expected = ownProp(e, "expected");
|
|
358
|
+
const actual = ownProp(e, "actual");
|
|
359
|
+
if (!Array.isArray(expected) || !Array.isArray(actual) || expected.length < 2 || expected.length !== actual.length) {
|
|
360
|
+
return false;
|
|
361
|
+
}
|
|
362
|
+
if (expected.length > 200)
|
|
363
|
+
return false;
|
|
364
|
+
const eSorted = expected.map((v) => safeStableSerialize(v)).sort();
|
|
365
|
+
const aSorted = actual.map((v) => safeStableSerialize(v)).sort();
|
|
366
|
+
return eSorted.every((v, i) => v === aSorted[i]);
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
function primaryFailureLine(failures, fallback) {
|
|
370
|
+
const first = Array.isArray(failures)
|
|
371
|
+
? failures.find((f) => typeof f === "string" && f.trim().length > 0)
|
|
372
|
+
: undefined;
|
|
373
|
+
const raw = first || fallback;
|
|
374
|
+
const clean = sanitizeSingleLine(raw.length > 4096 ? raw.slice(0, 4096) : raw);
|
|
375
|
+
return clean.length > 140 ? `${clean.slice(0, 137)}...` : clean;
|
|
376
|
+
}
|
|
377
|
+
const UI_STATE_ORDER_KINDS = ["keyboard_tab", "disabled", "error_state"];
|
|
378
|
+
const UI_STATE_KINDS = new Set(["hover", "focus", "keyboard_tab", "disabled", "empty_state", "error_state", "storage"]);
|
|
379
|
+
/** Unique, ordered list of failing web_ui_states check kinds from metrics.checks and diff.checks. */
|
|
380
|
+
function collectFailedUiStateKinds(result) {
|
|
381
|
+
const kinds = new Set();
|
|
382
|
+
const add = (entry, requireFail) => {
|
|
383
|
+
const kind = ownProp(entry, "kind");
|
|
384
|
+
if (typeof kind !== "string" || !UI_STATE_KINDS.has(kind))
|
|
385
|
+
return;
|
|
386
|
+
if (requireFail && ownProp(entry, "status") !== "fail")
|
|
387
|
+
return;
|
|
388
|
+
kinds.add(kind);
|
|
389
|
+
};
|
|
390
|
+
const metricChecks = ownProp(ownProp(result, "metrics"), "checks");
|
|
391
|
+
if (Array.isArray(metricChecks))
|
|
392
|
+
for (const entry of metricChecks.slice(0, 200))
|
|
393
|
+
add(entry, true);
|
|
394
|
+
const diffChecks = ownProp(ownProp(result, "diff"), "checks");
|
|
395
|
+
if (isRecord(diffChecks))
|
|
396
|
+
for (const key of Object.keys(diffChecks).slice(0, 200))
|
|
397
|
+
add(ownProp(diffChecks, key), false);
|
|
398
|
+
return [...kinds];
|
|
399
|
+
}
|
|
400
|
+
export function classifyFailure(result, invariant) {
|
|
401
|
+
if (!isRecord(result)) {
|
|
402
|
+
return makeCls("BEHAVIORAL_MISMATCH", "low", "Behavioral mismatch: malformed invariant result", "Compare candidate output against the contract expectations and fix the diverging logic.");
|
|
403
|
+
}
|
|
404
|
+
const redacted = isRedactedHoldout(result, invariant);
|
|
405
|
+
const diag = ownProp(result, "diagnostic");
|
|
406
|
+
const diagCode = typeof ownProp(diag, "code") === "string" ? ownProp(diag, "code") : undefined;
|
|
407
|
+
const resultFailures = getFailureStrings(result);
|
|
408
|
+
const resultReason = typeof ownProp(result, "reason") === "string" ? ownProp(result, "reason") : undefined;
|
|
409
|
+
const resultMetrics = ownProp(result, "metrics");
|
|
410
|
+
// 1. Anti-cheat integrity violation.
|
|
411
|
+
if (result.type === "anti_cheat" ||
|
|
412
|
+
diagCode === "CONTRACT_TAMPERED" ||
|
|
413
|
+
(!redacted && /\b(?:STUB_CONSTANT_OUTPUT|HOLDOUT_OVERFIT_SUSPECTED|anti[-_ ]?cheat|tampered)\b/i.test(collectRawSignals(result).text))) {
|
|
414
|
+
const head = redacted
|
|
415
|
+
? "Anti-cheat integrity violation detected"
|
|
416
|
+
: `Anti-cheat violation: ${primaryFailureLine(resultFailures, resultReason || "suspected stubbing or tampering")}`;
|
|
417
|
+
return makeCls("ANTI_CHEAT_VIOLATION", "high", head, "Remove hardcoded/stubbed responses or contract tampering and implement real domain logic that generalizes across unseen inputs.");
|
|
418
|
+
}
|
|
419
|
+
// 2. Optional adapter unavailable.
|
|
420
|
+
if (diagCode === "ADAPTER_MISSING" ||
|
|
421
|
+
diagCode === "ADAPTER_DEGRADED" ||
|
|
422
|
+
(!redacted &&
|
|
423
|
+
result.status === "skipped" &&
|
|
424
|
+
/\b(?:ADAPTER_MISSING|requires\s+(?:playwright|ffmpeg|sharp)|without\s+the\s+optional\s+['"]?sharp|missing\s+adapter|not\s+installed)\b/i.test(collectRawSignals(result).text))) {
|
|
425
|
+
if (redacted) {
|
|
426
|
+
return makeCls("ADAPTER_UNAVAILABLE", "high", "Optional adapter unavailable (details redacted)", "Install the missing optional adapter (Playwright, ffmpeg, or sharp) or supply a supported fallback target.");
|
|
427
|
+
}
|
|
428
|
+
const diagAdapter = ownProp(diag, "adapter");
|
|
429
|
+
const diagInstall = ownProp(diag, "installHint");
|
|
430
|
+
const diagFallback = ownProp(diag, "fallbackHint");
|
|
431
|
+
const diagMsg = ownProp(diag, "message");
|
|
432
|
+
const adapter = typeof diagAdapter === "string" && diagAdapter.trim() ? sanitizeSingleLine(diagAdapter) : "optional adapter";
|
|
433
|
+
const fixParts = [
|
|
434
|
+
typeof diagInstall === "string" && diagInstall.trim() ? `Install via \`${sanitizeSingleLine(diagInstall)}\`.` : "",
|
|
435
|
+
typeof diagFallback === "string" && diagFallback.trim() ? sanitizeSingleLine(diagFallback) : ""
|
|
436
|
+
].filter(Boolean);
|
|
437
|
+
return makeCls("ADAPTER_UNAVAILABLE", "high", `Adapter unavailable (${adapter}): ${primaryFailureLine(resultFailures, resultReason || (typeof diagMsg === "string" ? diagMsg : "missing dependency"))}`, fixParts.join(" ") || "Install the missing optional adapter (Playwright, ffmpeg, or sharp) or supply a supported fallback target.");
|
|
438
|
+
}
|
|
439
|
+
// 3. Strict holdout guard: NEVER inspect failures, diff, repro, or expected values.
|
|
440
|
+
if (redacted) {
|
|
441
|
+
const hint = typeof invariant?.holdoutHint === "string" && invariant.holdoutHint.trim() ? sanitizeSingleLine(invariant.holdoutHint) : "";
|
|
442
|
+
const statusVal = ownProp(resultMetrics, "status");
|
|
443
|
+
const statusCode = typeof statusVal === "number" ? statusVal : null;
|
|
444
|
+
if (statusCode === 401 || statusCode === 403) {
|
|
445
|
+
return makeCls("AUTH_FAILURE", "medium", hint ? `Holdout auth failure (HTTP ${statusCode}): ${hint} (details redacted)` : `Holdout invariant failed with HTTP ${statusCode} (expected details redacted)`, "Verify authentication headers, session state, and route authorization handling without hardcoding probe paths.");
|
|
446
|
+
}
|
|
447
|
+
return makeCls("BEHAVIORAL_MISMATCH", "low", hint ? `Holdout invariant failed: ${hint} (details redacted)` : "Holdout invariant failed (expected details redacted)", hint
|
|
448
|
+
? `Address hidden holdout behavior (${hint}) with general logic rather than overfitting to visible probes.`
|
|
449
|
+
: "Generalize implementation behavior for unseen edge cases; avoid overfitting to visible probes.");
|
|
450
|
+
}
|
|
451
|
+
const { failures, text, unified } = collectRawSignals(result);
|
|
452
|
+
const firstLine = primaryFailureLine(failures, `invariant ${String(result.id ?? "unknown")} ${String(result.status ?? "fail")}`);
|
|
453
|
+
const statusMetric = ownProp(resultMetrics, "status");
|
|
454
|
+
const metricStatus = typeof statusMetric === "number" ? statusMetric : null;
|
|
455
|
+
// 3b. Interactive UI states: keyboard/focus/disabled/error-state progression vs. other behavioral drift.
|
|
456
|
+
if (result.type === "web_ui_states") {
|
|
457
|
+
const failedKinds = collectFailedUiStateKinds(result);
|
|
458
|
+
const orderBroken = UI_STATE_ORDER_KINDS.some((k) => failedKinds.includes(k)) ||
|
|
459
|
+
/\b(?:focus\s+trap|focus\s+order\s+mismatch|keyboard\s+Tab)\b/i.test(text);
|
|
460
|
+
const kindsLabel = failedKinds.length > 0 ? ` [${failedKinds.join(", ")}]` : "";
|
|
461
|
+
return orderBroken
|
|
462
|
+
? makeCls("STATE_ORDER_BROKEN", "high", `UI state progression broken${kindsLabel}: ${firstLine}`, "Fix keyboard Tab order (remove negative tabindex focus traps, match DOM order), disabled/enabled control states, and error-state rendering (role=\"alert\", aria-invalid) after the triggering interaction.")
|
|
463
|
+
: makeCls("BEHAVIORAL_MISMATCH", failures.length > 0 ? "medium" : "low", `UI state mismatch${kindsLabel}: ${firstLine}`, "Match hover/focus styling (classes, attributes, visible focus ring), empty-state copy, and browser storage keys/values with the reference UI.");
|
|
464
|
+
}
|
|
465
|
+
// 3c. Performance / payload budget regression.
|
|
466
|
+
const perfDiff = ownProp(result, "diff");
|
|
467
|
+
if (ownProp(perfDiff, "code") === "PERFORMANCE_REGRESSION" ||
|
|
468
|
+
result.type === "perf_budget" ||
|
|
469
|
+
/\b(?:p50|p95|p99|mean|maxDuration)\s+latency\s+[0-9.]+ms\s*>\s*max(?:P50|P95|P99|Mean|Duration)Ms\b/i.test(text) ||
|
|
470
|
+
/\bpayload\s+(?:maxBytes\s+[0-9.]+\s*>\s*maxBytes|minBytes\s+[0-9.]+\s*<\s*minBytes)\b/i.test(text)) {
|
|
471
|
+
const highConf = ownProp(perfDiff, "code") === "PERFORMANCE_REGRESSION" ||
|
|
472
|
+
/\b(?:latency|maxBytes|minBytes|errorRate|timed?\s*out)\b/i.test(text);
|
|
473
|
+
return makeCls("PERFORMANCE_REGRESSION", highConf ? "high" : "medium", `Performance budget regression: ${firstLine}`, "Optimize hot path / eliminate N+1 or payload bloat; profile slow handlers/queries, trim oversized responses, and ensure latency percentiles and byte sizes stay within budget.");
|
|
474
|
+
}
|
|
475
|
+
// 4. Authentication / authorization failure.
|
|
476
|
+
const workflowStepSummaries = ownProp(resultMetrics, "stepSummaries");
|
|
477
|
+
const workflowAuthStepFailed = result.type === "http_workflow" &&
|
|
478
|
+
Array.isArray(workflowStepSummaries) &&
|
|
479
|
+
workflowStepSummaries.some((s) => isRecord(s) && ownProp(s, "passed") === false && (ownProp(s, "status") === 401 || ownProp(s, "status") === 403));
|
|
480
|
+
const isHttpAuth = metricStatus === 401 ||
|
|
481
|
+
metricStatus === 403 ||
|
|
482
|
+
workflowAuthStepFailed ||
|
|
483
|
+
/\bstatus\s+expected\b[^\n]{0,120}\bgot\s+(?:401|403)\b/i.test(text) ||
|
|
484
|
+
/\bstatus\s+expected\s+\[?\s*(?:401|403)\b/i.test(text) ||
|
|
485
|
+
/\bexpected\s+HTTP\s+\d{3}\s*,\s*got\s+(?:401|403)\b/i.test(text);
|
|
486
|
+
if (isHttpAuth ||
|
|
487
|
+
/\b(?:unauthorized|forbidden|authentication\s+(?:failed|required)|invalid\s+(?:token|credentials?|api[_ -]?key)|missing\s+(?:authorization|auth\s+header|bearer|session|credentials?)|access\s+denied)\b/i.test(text)) {
|
|
488
|
+
const authFix = result.type === "http_workflow"
|
|
489
|
+
? "Check login/session step credentials, cookieJar Set-Cookie propagation, and extracted Authorization/API-key headers between workflow steps."
|
|
490
|
+
: result.type === "http_stream"
|
|
491
|
+
? "Check authentication headers/tokens and 401/403 enforcement on the streaming endpoint before emitting SSE/NDJSON chunks."
|
|
492
|
+
: result.type === "ws_protocol"
|
|
493
|
+
? "Check authentication headers, cookies, or query tokens required during the WebSocket HTTP 101 upgrade handshake."
|
|
494
|
+
: "Check auth middleware, Authorization/API-key headers, cookies/storageState, and 401/403 status enforcement.";
|
|
495
|
+
return makeCls("AUTH_FAILURE", isHttpAuth ? "high" : "medium", `Authentication/authorization failed: ${firstLine}`, authFix);
|
|
496
|
+
}
|
|
497
|
+
// 5. Timeout / stream truncation / premature EOF / premature WebSocket close.
|
|
498
|
+
const isStreamOrWsTruncated = /\b(?:stream\s+exceeded\s+maxBytes|event\s+count\s+\d+\s*<\s*minEvents\s+\d+|missing\s+expected\s+terminal\s+event|incomplete\s+(?:final\s+SSE\s+event|trailing\s+frame)|WebSocket\s+(?:socket\s+)?closed\s+before|Cannot\s+send\s+on\s+closed\s+WebSocket|WebSocket\s+(?:frame\s+length|fragmented\s+message)[^\n]{0,120}\bexceeds\s+maxMessageBytes|closeCode\s+expected\s+\d+\s*,\s*got\s+(?:none|1001|1002|1005|1006|1009|1011))\b/i.test(text) ||
|
|
499
|
+
(result.type === "http_stream" &&
|
|
500
|
+
/\bstream\s+request\s+failed:/i.test(text) &&
|
|
501
|
+
/\b(?:terminated|aborted|closed|reset|eof|hang\s+up|timeout)\b/i.test(text));
|
|
502
|
+
if (diagCode === "EXEC_TIMEOUT" ||
|
|
503
|
+
ownProp(resultMetrics, "timedOut") === true ||
|
|
504
|
+
ownProp(resultMetrics, "truncated") === true ||
|
|
505
|
+
isStreamOrWsTruncated ||
|
|
506
|
+
/\b(?:TIMEOUT:|timed?\s*out|exceeded\s+\d+\s*ms|AbortError|ETIMEDOUT|unexpected\s+end\s+of\s+(?:json|input|stream)|unexpected\s+eof|truncated|premature\s+close|stream\s+(?:ended|aborted|closed)|socket\s+hang\s+up|ECONNRESET)\b/i.test(text)) {
|
|
507
|
+
const streamFix = result.type === "http_stream"
|
|
508
|
+
? "Flush every SSE/NDJSON frame completely (including trailing blank lines for SSE), emit the expected terminalEvent before ending the response, and finish within timeoutMs and maxBytes."
|
|
509
|
+
: result.type === "ws_protocol"
|
|
510
|
+
? "Keep the WebSocket connection open until all expected frames are exchanged, reply to pings, stay within maxMessageBytes, and complete the closing handshake with the expected closeCode."
|
|
511
|
+
: result.type === "http_workflow"
|
|
512
|
+
? "Ensure every HTTP workflow step responds and flushes its body completely within step/workflow timeoutMs without dropping the connection."
|
|
513
|
+
: "Flush stdout/HTTP response streams completely, resolve hanging promises/handles cleanly, and finish within timeoutMs.";
|
|
514
|
+
return makeCls("STREAM_TRUNCATED", "high", `Execution timed out or stream truncated: ${firstLine}`, streamFix);
|
|
515
|
+
}
|
|
516
|
+
// 6. Missing or unrecognized CLI flag/option.
|
|
517
|
+
const explicitMissingFlag = /\b(?:unknown|unrecognized|invalid|unsupported|unexpected|missing)\s+(?:cli\s+)?(?:option|flag|switch|subcommand)\b/i.test(text) ||
|
|
518
|
+
/\b(?:no\s+such\s+option|bad\s+option|flag\s+provided\s+but\s+not\s+defined|requires\s+an?\s+argument|missing\s+required\s+(?:flag|option|argument))\b/i.test(text);
|
|
519
|
+
const rawInvArgs = Array.isArray(invariant?.input?.args) ? invariant.input.args : [];
|
|
520
|
+
const invFlagArgs = rawInvArgs.filter((a) => typeof a === "string" && /^--?[A-Za-z]/.test(a));
|
|
521
|
+
const exit2WithFlag = result.type === "command" &&
|
|
522
|
+
(ownProp(resultMetrics, "exitCode") === 2 || /\bexitCode\s+expected\s+\[?0\]?\s*,\s*got\s+2\b/i.test(text)) &&
|
|
523
|
+
(invFlagArgs.length > 0 || CLI_FLAG_TOKEN_RE.test(text) || /\busage:/i.test(text));
|
|
524
|
+
if (explicitMissingFlag || exit2WithFlag) {
|
|
525
|
+
const flagHint = CLI_FLAG_TOKEN_RE.exec(text)?.[1] || invFlagArgs[0];
|
|
526
|
+
return makeCls("MISSING_FLAG", explicitMissingFlag ? "high" : "medium", flagHint ? `Unrecognized or missing CLI flag ${flagHint}: ${firstLine}` : `CLI flag parsing failed: ${firstLine}`, flagHint
|
|
527
|
+
? `Add CLI argument parser support for \`${flagHint}\` and verify its usage/help handling.`
|
|
528
|
+
: "Implement missing CLI option/flag parsing and ensure unknown-flag errors match the reference.");
|
|
529
|
+
}
|
|
530
|
+
// 7. Nondeterministic token or timing drift.
|
|
531
|
+
if (hasDynamicDrift(result, text)) {
|
|
532
|
+
return makeCls("FLAKY_NONDETERMINISM", "high", `Nondeterministic output or timing drift: ${firstLine}`, 'Stabilize clocks/IDs/temp paths in the target, or configure contract normalize modes ("timestamps", "paths"), regex jsonPath matchers, or maxLatencyMs headroom.');
|
|
533
|
+
}
|
|
534
|
+
// 8. Off-by-one boundary error.
|
|
535
|
+
const offByOne = detectOffByOne(result, failures, unified);
|
|
536
|
+
if (offByOne) {
|
|
537
|
+
return makeCls("OFF_BY_ONE", offByOne.high ? "high" : "medium", `Off-by-one boundary error: ${offByOne.detail}`, "Audit loop bounds (< vs <=), 0-based vs 1-based indexing, slice/pagination limits, and inclusive/exclusive endpoints.");
|
|
538
|
+
}
|
|
539
|
+
// 9. JSON/payload schema drift.
|
|
540
|
+
const resultDiff = ownProp(result, "diff");
|
|
541
|
+
const payloadDiffContainers = collectNestedPayloadDiffs(resultDiff);
|
|
542
|
+
const malformedEventsDiff = ownProp(resultDiff, "malformedEvents");
|
|
543
|
+
const hasSchemaDiff = (Array.isArray(malformedEventsDiff) && malformedEventsDiff.length > 0) ||
|
|
544
|
+
payloadDiffContainers.some((c) => {
|
|
545
|
+
const js = ownProp(c, "jsonSchema");
|
|
546
|
+
return Array.isArray(js) && js.length > 0;
|
|
547
|
+
});
|
|
548
|
+
const hasSubsetTypeOrMissing = payloadDiffContainers.some((c) => {
|
|
549
|
+
const sub = ownProp(c, "jsonSubset");
|
|
550
|
+
return (Array.isArray(sub) &&
|
|
551
|
+
sub.some((e) => isRecord(e) && (ownProp(e, "actual") === undefined || typeof ownProp(e, "expected") !== typeof ownProp(e, "actual"))));
|
|
552
|
+
});
|
|
553
|
+
const schemaTextMatch = /\b(?:jsonSchema\b|not\s+valid\s+JSON|malformed\s+ndjson\b|schema\s+(?:drift|mismatch|error|validation)|missing\s+required\s+(?:property|field|key)|additionalProperties|unexpected\s+(?:property|field)|expected\s+type\b|type\s+mismatch)\b/i.test(text) || /\bjsonPath\s+[^:\r\n]{1,200}:\s*not\s+found\b/i.test(text);
|
|
554
|
+
if (hasSchemaDiff || hasSubsetTypeOrMissing || schemaTextMatch) {
|
|
555
|
+
const schemaFix = result.type === "http_workflow"
|
|
556
|
+
? "Align the failing HTTP workflow step response JSON structure, required fields, and value types with the step's expected schema."
|
|
557
|
+
: result.type === "http_stream"
|
|
558
|
+
? "Align SSE/NDJSON stream event payloads with the expected JSON schema, required keys, value types, and valid line-delimited JSON."
|
|
559
|
+
: result.type === "ws_protocol"
|
|
560
|
+
? "Align WebSocket message JSON payloads with the expected step schema, required fields, and value types."
|
|
561
|
+
: "Align response/output JSON structure, required field names, value types, and serialization with the contract schema.";
|
|
562
|
+
return makeCls("SCHEMA_DRIFT", hasSchemaDiff || schemaTextMatch ? "high" : "medium", `JSON/payload schema drift: ${firstLine}`, schemaFix);
|
|
563
|
+
}
|
|
564
|
+
// 10. Color / contrast / palette failure.
|
|
565
|
+
const hasExplicitContrast = /\b(?:contrast\s+ratio|color\s+contrast|wcag|luminance\s+contrast|insufficient\s+contrast)\b/i.test(text);
|
|
566
|
+
const hasPaletteSignal = /\b(?:paletteSimilarity|colorDelta|color\s+mismatch|palette\s+mismatch)\b/i.test(text);
|
|
567
|
+
const hasStrongLayoutSignal = ownProp(resultMetrics, "dimensionMismatch") === true ||
|
|
568
|
+
/\b(?:regionIoU|layoutIoU|dimensionMismatch|width\s+expected|height\s+expected|aspectRatio\s+delta|motion\s+region|layout\s+shift|bounding\s*box|candidate\s+image\s+is\s+blank)\b/i.test(text);
|
|
569
|
+
if (hasExplicitContrast || (hasPaletteSignal && !hasStrongLayoutSignal)) {
|
|
570
|
+
return makeCls("COLOR_CONTRAST_FAIL", "high", `Color/contrast parity failed: ${firstLine}`, "Match theme/palette hex tokens to the reference and verify foreground/background contrast ratios meet WCAG targets.");
|
|
571
|
+
}
|
|
572
|
+
// 11. Visual / layout shift (including multi-viewport responsive failures).
|
|
573
|
+
const hasResponsiveSignal = Array.isArray(ownProp(resultDiff, "responsiveIssues")) ||
|
|
574
|
+
/\b(?:HORIZONTAL_OVERFLOW|ELEMENT_OVERFLOW|ELEMENT_OVERLAP|CLIPPED_OR_COLLAPSED|INTERACTIVE_TARGET_TOO_SMALL|MISSING_VIEWPORT_META)\b|\bresponsive\s*\[/i.test(text);
|
|
575
|
+
if (hasStrongLayoutSignal ||
|
|
576
|
+
hasResponsiveSignal ||
|
|
577
|
+
/\b(?:ssim\s+[0-9.]+\s*<|diffRatio\s+[0-9.]+\s*>|hammingDistance\s+\d+\s*>|overlap|misalign)\b/i.test(text) ||
|
|
578
|
+
result.type === "image_layout" ||
|
|
579
|
+
result.type === "image_perceptual") {
|
|
580
|
+
return makeCls("LAYOUT_SHIFT", hasStrongLayoutSignal || hasResponsiveSignal || /\b(?:ssim|diffRatio)\b/i.test(text) ? "high" : "medium", `Visual/layout shift detected: ${firstLine}`, hasResponsiveSignal
|
|
581
|
+
? "Fix responsive viewport overflow, missing viewport meta, overlapping interactive controls, or undersized touch targets across mobile/tablet/desktop breakpoints."
|
|
582
|
+
: "Inspect the spatial heatmap quadrants and bbox shift vectors; fix element positioning, dimensions, spacing, and responsive layout.");
|
|
583
|
+
}
|
|
584
|
+
// 12. State progression / ordering failure.
|
|
585
|
+
const isWorkflowOrderFail = result.type === "http_workflow" ||
|
|
586
|
+
ownProp(resultDiff, "code") === "STATE_ORDER_BROKEN" ||
|
|
587
|
+
/\b(?:STATE_ORDER_BROKEN|unresolved\s+template\s+expression|extract\s+"[^"]+"[^:\r\n]*:\s*(?:not\s+found|invalid|unsupported|forbidden))\b/i.test(text);
|
|
588
|
+
const isStreamOrderFail = result.type === "http_stream" &&
|
|
589
|
+
(Array.isArray(ownProp(resultDiff, "orderedEvents")) ||
|
|
590
|
+
/\bevent\[\d+\](?:\.event\b|:|\.(?:jsonSubset|jsonPath)\b)/i.test(text));
|
|
591
|
+
const isWsOrderFail = result.type === "ws_protocol" &&
|
|
592
|
+
(Array.isArray(ownProp(resultDiff, "steps")) ||
|
|
593
|
+
/\bstep\[\d+\](?::|\.(?:jsonSubset|jsonPath)\b)/i.test(text));
|
|
594
|
+
if (result.type === "video_timeline" ||
|
|
595
|
+
result.type === "web_flow" ||
|
|
596
|
+
isWorkflowOrderFail ||
|
|
597
|
+
isStreamOrderFail ||
|
|
598
|
+
isWsOrderFail ||
|
|
599
|
+
/\b(?:monotonic|out\s+of\s+order|state\s+order|wrong\s+order|sequence\s+mismatch|transition\s+failed|step\s+\S+\s+failed|finalUrl\b[^\n]{0,200}does\s+not\s+include|state\s+\S+\s+not\s+reachable|sort\s+order)\b/i.test(text) ||
|
|
600
|
+
hasReorderedItems(result, unified)) {
|
|
601
|
+
const orderFix = result.type === "http_workflow"
|
|
602
|
+
? "Verify HTTP workflow step ordering, server-side state transitions across steps, cookieJar propagation, and step extract/template expressions (vars.* / steps.<id>.*)."
|
|
603
|
+
: result.type === "http_stream"
|
|
604
|
+
? "Verify stream producer ordering so SSE/NDJSON events are emitted in the exact expected sequence (event types, chunk order, and state progression)."
|
|
605
|
+
: result.type === "ws_protocol"
|
|
606
|
+
? "Verify WebSocket send/expect message ordering and server-side state transitions so frames arrive in the expected protocol sequence."
|
|
607
|
+
: "Verify state transitions, async step sequencing, route redirects, and deterministic sorting so states appear in the expected order.";
|
|
608
|
+
return makeCls("STATE_ORDER_BROKEN", result.type === "video_timeline" ||
|
|
609
|
+
isWorkflowOrderFail ||
|
|
610
|
+
isStreamOrderFail ||
|
|
611
|
+
isWsOrderFail ||
|
|
612
|
+
/\b(?:monotonic|order|step\s+\S+\s+failed)\b/i.test(text)
|
|
613
|
+
? "high"
|
|
614
|
+
: "medium", `State progression or ordering broken: ${firstLine}`, orderFix);
|
|
615
|
+
}
|
|
616
|
+
// 13. Fallback behavioral mismatch.
|
|
617
|
+
const fixByType = new Map([
|
|
618
|
+
["repo_exports", "Create the missing module files and export all expected symbols with matching kinds/signatures."],
|
|
619
|
+
["web_route", "Verify route rendering, title/landmark DOM structure, and expected background network requests."],
|
|
620
|
+
["web_network", "Verify route rendering, title/landmark DOM structure, and expected background network requests."],
|
|
621
|
+
["web_ui_states", "Match interactive UI states (hover/focus styling, keyboard Tab order, disabled/empty/error states, and browser storage) with the reference UI."],
|
|
622
|
+
["http", "Compare HTTP status code, headers, and response payload against the reference endpoint behavior."],
|
|
623
|
+
[
|
|
624
|
+
"http_workflow",
|
|
625
|
+
"Inspect each HTTP workflow step's request interpolation, cookies/session state, response status/payload, and finallySteps cleanup."
|
|
626
|
+
],
|
|
627
|
+
[
|
|
628
|
+
"http_stream",
|
|
629
|
+
"Inspect the streaming endpoint's HTTP status, Content-Type headers, SSE/NDJSON framing, event payloads, and completion behavior."
|
|
630
|
+
],
|
|
631
|
+
[
|
|
632
|
+
"ws_protocol",
|
|
633
|
+
"Inspect the WebSocket upgrade handshake, RFC 6455 frame handling, message payloads, and closing handshake behavior."
|
|
634
|
+
],
|
|
635
|
+
[
|
|
636
|
+
"perf_budget",
|
|
637
|
+
"Optimize hot path / eliminate N+1 or payload bloat and verify latency percentiles and byte budgets."
|
|
638
|
+
],
|
|
639
|
+
["command", "Compare CLI exit code, stdout/stderr, and filesystem side effects against the reference implementation."]
|
|
640
|
+
]);
|
|
641
|
+
const fallbackFix = metricStatus !== null && metricStatus >= 500
|
|
642
|
+
? "Inspect server error logs/stack traces for the HTTP 5xx response and handle the failing request path cleanly."
|
|
643
|
+
: (typeof result.type === "string" ? fixByType.get(result.type) : undefined) ||
|
|
644
|
+
"Compare candidate output against the contract expectations and fix the diverging logic.";
|
|
645
|
+
return makeCls("BEHAVIORAL_MISMATCH", failures.length > 0 ? "medium" : "low", `Behavioral mismatch: ${firstLine}`, fallbackFix);
|
|
646
|
+
}
|
|
647
|
+
function extractAntiCheatReasons(antiCheat) {
|
|
648
|
+
if (!antiCheat || typeof antiCheat !== "object")
|
|
649
|
+
return [];
|
|
650
|
+
const raw = antiCheat;
|
|
651
|
+
if (raw.status !== "suspected" && raw.passed !== false)
|
|
652
|
+
return [];
|
|
653
|
+
const reasons = [];
|
|
654
|
+
for (const list of [raw.reasons, raw.flags]) {
|
|
655
|
+
if (!Array.isArray(list))
|
|
656
|
+
continue;
|
|
657
|
+
for (const item of list) {
|
|
658
|
+
if (typeof item === "string" && item.trim() && !reasons.includes(item.trim()))
|
|
659
|
+
reasons.push(item.trim());
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
return reasons.length > 0 ? reasons : ["Anti-cheat flagged suspected stubbed outputs or holdout overfitting"];
|
|
663
|
+
}
|
|
664
|
+
function resolveSafeImagePath(candidate, cwd) {
|
|
665
|
+
if (typeof candidate !== "string" || hasCrossPlatformPathEscape(candidate))
|
|
666
|
+
return null;
|
|
667
|
+
const raw = candidate.trim();
|
|
668
|
+
if (!raw || isInsideVaultDirectory(raw))
|
|
669
|
+
return null;
|
|
670
|
+
const baseDir = path.resolve(cwd || process.cwd());
|
|
671
|
+
let realBase = baseDir;
|
|
672
|
+
try {
|
|
673
|
+
if (fs.existsSync(baseDir))
|
|
674
|
+
realBase = fs.realpathSync(baseDir);
|
|
675
|
+
}
|
|
676
|
+
catch {
|
|
677
|
+
realBase = baseDir;
|
|
678
|
+
}
|
|
679
|
+
const resolved = path.resolve(baseDir, raw);
|
|
680
|
+
// Pre-filesystem confinement check prevents probing host files or triggering Windows UNC/SMB requests.
|
|
681
|
+
if (!isPathWithinDir(resolved, baseDir, { allowEqual: false }) &&
|
|
682
|
+
!isPathWithinDir(resolved, realBase, { allowEqual: false })) {
|
|
683
|
+
return null;
|
|
684
|
+
}
|
|
685
|
+
try {
|
|
686
|
+
if (!fs.statSync(resolved).isFile())
|
|
687
|
+
return null;
|
|
688
|
+
const realTarget = fs.realpathSync(resolved);
|
|
689
|
+
if (!isPathWithinDir(realTarget, realBase, { allowEqual: false }) || isInsideVaultDirectory(realTarget)) {
|
|
690
|
+
return null;
|
|
691
|
+
}
|
|
692
|
+
return realTarget;
|
|
693
|
+
}
|
|
694
|
+
catch {
|
|
695
|
+
return null;
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
function toLayoutRegions(raw) {
|
|
699
|
+
if (!Array.isArray(raw))
|
|
700
|
+
return [];
|
|
701
|
+
const out = [];
|
|
702
|
+
const limit = Math.min(raw.length, MAX_BBOX_REGIONS);
|
|
703
|
+
for (let i = 0; i < limit; i++) {
|
|
704
|
+
const item = raw[i];
|
|
705
|
+
if (!isRecord(item))
|
|
706
|
+
continue;
|
|
707
|
+
const bboxRaw = ownProp(item, "bbox");
|
|
708
|
+
if (!isRecord(bboxRaw))
|
|
709
|
+
continue;
|
|
710
|
+
const x = ownProp(bboxRaw, "x");
|
|
711
|
+
const y = ownProp(bboxRaw, "y");
|
|
712
|
+
const w = ownProp(bboxRaw, "w");
|
|
713
|
+
const h = ownProp(bboxRaw, "h");
|
|
714
|
+
if (!(typeof x === "number" &&
|
|
715
|
+
typeof y === "number" &&
|
|
716
|
+
typeof w === "number" &&
|
|
717
|
+
typeof h === "number" &&
|
|
718
|
+
Number.isFinite(x) &&
|
|
719
|
+
Number.isFinite(y) &&
|
|
720
|
+
Number.isFinite(w) &&
|
|
721
|
+
Number.isFinite(h) &&
|
|
722
|
+
w >= 0 &&
|
|
723
|
+
h >= 0)) {
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
726
|
+
const rawId = ownProp(item, "id");
|
|
727
|
+
const rawSelector = ownProp(item, "selector");
|
|
728
|
+
const rawKind = ownProp(item, "kind");
|
|
729
|
+
const id = typeof rawId === "string" && rawId
|
|
730
|
+
? rawId
|
|
731
|
+
: typeof rawSelector === "string" && rawSelector
|
|
732
|
+
? rawSelector
|
|
733
|
+
: `box-${i}`;
|
|
734
|
+
out.push({
|
|
735
|
+
id,
|
|
736
|
+
bbox: { x, y, w, h },
|
|
737
|
+
...(typeof rawKind === "string" && (rawKind === "ui_chrome" || rawKind === "text_band" || rawKind === "media_block")
|
|
738
|
+
? { kind: rawKind }
|
|
739
|
+
: {})
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
return out;
|
|
743
|
+
}
|
|
744
|
+
function extractBBoxShiftVectors(result, invariant) {
|
|
745
|
+
const diff = ownProp(result, "diff");
|
|
746
|
+
const metrics = ownProp(result, "metrics");
|
|
747
|
+
const invExp = isRecord(invariant?.expected) ? invariant.expected : undefined;
|
|
748
|
+
const refSources = [
|
|
749
|
+
ownProp(diff, "refRegions"),
|
|
750
|
+
ownProp(diff, "expectedRegions"),
|
|
751
|
+
ownProp(diff, "expectedBoundingBoxes"),
|
|
752
|
+
invExp ? ownProp(invExp, "regions") : undefined,
|
|
753
|
+
invExp ? ownProp(invExp, "boundingBoxes") : undefined
|
|
754
|
+
];
|
|
755
|
+
const candSources = [
|
|
756
|
+
ownProp(diff, "candRegions"),
|
|
757
|
+
ownProp(diff, "candidateRegions"),
|
|
758
|
+
ownProp(diff, "actualRegions"),
|
|
759
|
+
ownProp(diff, "actualBoundingBoxes"),
|
|
760
|
+
ownProp(diff, "candBoundingBoxes"),
|
|
761
|
+
ownProp(metrics, "candidateRegions"),
|
|
762
|
+
ownProp(metrics, "actualRegions"),
|
|
763
|
+
ownProp(metrics, "actualBoundingBoxes")
|
|
764
|
+
];
|
|
765
|
+
const refRegions = refSources.map(toLayoutRegions).find((a) => a.length > 0) || [];
|
|
766
|
+
const candRegions = candSources.map(toLayoutRegions).find((a) => a.length > 0) || [];
|
|
767
|
+
if (refRegions.length === 0 || candRegions.length === 0)
|
|
768
|
+
return undefined;
|
|
769
|
+
const diffMatches = ownProp(diff, "matchedRegions");
|
|
770
|
+
const metricsMatches = ownProp(metrics, "matchedRegions");
|
|
771
|
+
const rawMatches = Array.isArray(diffMatches) ? diffMatches : Array.isArray(metricsMatches) ? metricsMatches : [];
|
|
772
|
+
const matches = [];
|
|
773
|
+
for (const m of rawMatches) {
|
|
774
|
+
if (!isRecord(m))
|
|
775
|
+
continue;
|
|
776
|
+
const refId = ownProp(m, "refId");
|
|
777
|
+
const candId = ownProp(m, "candId");
|
|
778
|
+
const iou = ownProp(m, "iou");
|
|
779
|
+
if (typeof refId === "string" && typeof candId === "string" && typeof iou === "number" && Number.isFinite(iou)) {
|
|
780
|
+
matches.push({ refId, candId, iou });
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
const shifts = computeBBoxShiftVectors(refRegions, candRegions, matches.length > 0 ? matches : undefined);
|
|
784
|
+
if (shifts.length === 0)
|
|
785
|
+
return undefined;
|
|
786
|
+
return shifts.map((s) => ({
|
|
787
|
+
...s,
|
|
788
|
+
refId: sanitizeSingleLine(s.refId),
|
|
789
|
+
candId: sanitizeSingleLine(s.candId)
|
|
790
|
+
}));
|
|
791
|
+
}
|
|
792
|
+
function collectEvidence(result, maxItems) {
|
|
793
|
+
const out = [];
|
|
794
|
+
const push = (raw) => {
|
|
795
|
+
if (out.length >= maxItems)
|
|
796
|
+
return;
|
|
797
|
+
const clean = sanitizeSingleLine(raw, MAX_EVIDENCE_LINE_CHARS);
|
|
798
|
+
if (clean && !out.includes(clean))
|
|
799
|
+
out.push(clean);
|
|
800
|
+
};
|
|
801
|
+
for (const f of getFailureStrings(result))
|
|
802
|
+
push(f);
|
|
803
|
+
const reason = ownProp(result, "reason");
|
|
804
|
+
if (typeof reason === "string")
|
|
805
|
+
push(reason);
|
|
806
|
+
const diag = ownProp(result, "diagnostic");
|
|
807
|
+
const diagMsg = ownProp(diag, "message");
|
|
808
|
+
const diagCode = ownProp(diag, "code");
|
|
809
|
+
if (typeof diagMsg === "string") {
|
|
810
|
+
push(`${typeof diagCode === "string" && diagCode ? `[${sanitizeSingleLine(diagCode)}] ` : ""}${diagMsg}`);
|
|
811
|
+
}
|
|
812
|
+
if (out.length < maxItems) {
|
|
813
|
+
const unified = extractUnifiedDiff(ownProp(result, "diff"));
|
|
814
|
+
if (unified) {
|
|
815
|
+
const boundedUnified = unified.length > MAX_CLASSIFY_CHARS ? unified.slice(0, MAX_CLASSIFY_CHARS) : unified;
|
|
816
|
+
const preview = boundedUnified
|
|
817
|
+
.replace(/\r\n/g, "\n")
|
|
818
|
+
.split("\n")
|
|
819
|
+
.filter((l) => (l.startsWith("-") || l.startsWith("+")) && !l.startsWith("---") && !l.startsWith("+++"))
|
|
820
|
+
.slice(0, 2)
|
|
821
|
+
.map((l) => (l.length > MAX_EVIDENCE_LINE_CHARS ? l.slice(0, MAX_EVIDENCE_LINE_CHARS) : l))
|
|
822
|
+
.join(" | ");
|
|
823
|
+
if (preview)
|
|
824
|
+
push(`diff: ${preview}`);
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
return out;
|
|
828
|
+
}
|
|
829
|
+
function priorityRank(item) {
|
|
830
|
+
if (item.category === "ANTI_CHEAT_VIOLATION")
|
|
831
|
+
return 0;
|
|
832
|
+
if (item.severity === "hard" && (item.status === "fail" || item.status === "error"))
|
|
833
|
+
return 1;
|
|
834
|
+
if (item.status === "fail" || item.status === "error")
|
|
835
|
+
return 2;
|
|
836
|
+
return item.status === "warn" ? 3 : 4;
|
|
837
|
+
}
|
|
838
|
+
function shouldDiagnoseResult(result) {
|
|
839
|
+
if (!isRecord(result))
|
|
840
|
+
return false;
|
|
841
|
+
if (result.status === "fail" || result.status === "error" || result.status === "warn")
|
|
842
|
+
return true;
|
|
843
|
+
if (result.status === "skipped") {
|
|
844
|
+
const diag = ownProp(result, "diagnostic");
|
|
845
|
+
const diagCode = ownProp(diag, "code");
|
|
846
|
+
const reason = ownProp(result, "reason");
|
|
847
|
+
return (diagCode === "ADAPTER_MISSING" ||
|
|
848
|
+
diagCode === "ADAPTER_DEGRADED" ||
|
|
849
|
+
(typeof reason === "string" && /\bADAPTER_MISSING\b/i.test(reason)));
|
|
850
|
+
}
|
|
851
|
+
return false;
|
|
852
|
+
}
|
|
853
|
+
function truncateBrief(text, maxChars) {
|
|
854
|
+
if (text.length <= maxChars)
|
|
855
|
+
return text;
|
|
856
|
+
const suffix = maxChars >= 24 ? "\n... (truncated)" : "...";
|
|
857
|
+
const budget = Math.max(0, maxChars - suffix.length);
|
|
858
|
+
if (budget === 0)
|
|
859
|
+
return text.slice(0, maxChars);
|
|
860
|
+
const slice = text.slice(0, budget);
|
|
861
|
+
const lastNewline = slice.lastIndexOf("\n");
|
|
862
|
+
const cut = lastNewline > budget * 0.5 ? slice.slice(0, lastNewline) : slice.trimEnd();
|
|
863
|
+
return `${cut}${suffix}`.slice(0, maxChars);
|
|
864
|
+
}
|
|
865
|
+
export function buildRepairBrief(items, report, maxBriefChars = DEFAULT_MAX_BRIEF_CHARS) {
|
|
866
|
+
const limit = Number.isFinite(maxBriefChars) && maxBriefChars > 0 ? Math.floor(maxBriefChars) : DEFAULT_MAX_BRIEF_CHARS;
|
|
867
|
+
const safeItems = Array.isArray(items) ? items.filter((it) => isRecord(it)) : [];
|
|
868
|
+
const gateStatus = isRecord(report) && isRecord(report.gate) && typeof report.gate.status === "string" ? report.gate.status : "unknown";
|
|
869
|
+
const gate = sanitizeSingleLine(gateStatus);
|
|
870
|
+
if (safeItems.length === 0) {
|
|
871
|
+
return truncateBrief(redactSensitiveText(`# Repair Brief\nNo failures, warnings, or missing adapters diagnosed (gate: ${gate}).`), limit);
|
|
872
|
+
}
|
|
873
|
+
const counts = new Map();
|
|
874
|
+
for (const it of safeItems)
|
|
875
|
+
counts.set(String(it.category), (counts.get(String(it.category)) || 0) + 1);
|
|
876
|
+
const lines = [
|
|
877
|
+
`# Repair Brief (gate: ${gate} | ${safeItems.length} issue${safeItems.length === 1 ? "" : "s"})`,
|
|
878
|
+
`Categories: ${[...counts.entries()].map(([k, v]) => `${sanitizeSingleLine(k)}: ${v}`).join(", ")}`
|
|
879
|
+
];
|
|
880
|
+
const isHardPriority = (it) => it.category === "ANTI_CHEAT_VIOLATION" || (it.severity === "hard" && (it.status === "fail" || it.status === "error"));
|
|
881
|
+
const groups = [
|
|
882
|
+
{ title: "## Priority: Anti-Cheat & Hard Failures", list: safeItems.filter(isHardPriority) },
|
|
883
|
+
{ title: "## Soft Warnings & Failures", list: safeItems.filter((it) => !isHardPriority(it) && it.status !== "skipped") },
|
|
884
|
+
{ title: "## Missing Adapters", list: safeItems.filter((it) => it.status === "skipped") }
|
|
885
|
+
];
|
|
886
|
+
const fieldCap = Math.min(Math.max(limit + 256, 512), MAX_EVIDENCE_LINE_CHARS);
|
|
887
|
+
for (const { title, list } of groups) {
|
|
888
|
+
if (list.length === 0)
|
|
889
|
+
continue;
|
|
890
|
+
lines.push("", title);
|
|
891
|
+
for (const item of list) {
|
|
892
|
+
const sev = sanitizeSingleLine(String(item.severity ?? "unknown"));
|
|
893
|
+
const stat = sanitizeSingleLine(String(item.status ?? "unknown"));
|
|
894
|
+
const tag = item.redacted ? `${sev}/${stat}, holdout-redacted` : `${sev}/${stat}`;
|
|
895
|
+
lines.push(`- **[${sanitizeSingleLine(String(item.category))}]** \`${sanitizeSingleLine(String(item.invariantId))}\` (${tag}): ${sanitizeSingleLine(String(item.headline ?? ""), fieldCap)}`);
|
|
896
|
+
lines.push(` - Fix: ${sanitizeSingleLine(String(item.suggestedFix ?? ""), fieldCap)}`);
|
|
897
|
+
if (!item.redacted && Array.isArray(item.evidence) && item.evidence.length > 0) {
|
|
898
|
+
lines.push(` - Evidence: ${sanitizeSingleLine(String(item.evidence[0]), fieldCap)}`);
|
|
899
|
+
}
|
|
900
|
+
if (!item.redacted && item.spatialHeatmap) {
|
|
901
|
+
lines.push(` - Spatial: ${sanitizeSingleLine(String(item.spatialHeatmap.summary), fieldCap)}`);
|
|
902
|
+
}
|
|
903
|
+
if (!item.redacted && Array.isArray(item.bboxShifts) && item.bboxShifts.length > 0) {
|
|
904
|
+
const top = item.bboxShifts[0];
|
|
905
|
+
lines.push(` - BBox shift: ${sanitizeSingleLine(String(top.refId))} -> ${sanitizeSingleLine(String(top.direction))} (IoU ${Number(top.iou).toFixed(2)})`);
|
|
906
|
+
}
|
|
907
|
+
if (!item.redacted && item.repro) {
|
|
908
|
+
lines.push(` - Repro: \`${sanitizeSingleLine(String(item.repro), fieldCap)}\``);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
return truncateBrief(redactSensitiveText(lines.join("\n")), limit);
|
|
913
|
+
}
|
|
914
|
+
export async function diagnoseReport(report, options = {}) {
|
|
915
|
+
const safeReport = isRecord(report) ? report : {};
|
|
916
|
+
const opts = isRecord(options) ? options : {};
|
|
917
|
+
const maxEvidence = typeof opts.maxEvidencePerItem === "number" && Number.isFinite(opts.maxEvidencePerItem) && opts.maxEvidencePerItem >= 1
|
|
918
|
+
? Math.min(MAX_EVIDENCE_ITEMS_CAP, Math.floor(opts.maxEvidencePerItem))
|
|
919
|
+
: DEFAULT_MAX_EVIDENCE;
|
|
920
|
+
const maxBriefChars = typeof opts.maxBriefChars === "number" && Number.isFinite(opts.maxBriefChars) && opts.maxBriefChars > 0
|
|
921
|
+
? Math.floor(opts.maxBriefChars)
|
|
922
|
+
: DEFAULT_MAX_BRIEF_CHARS;
|
|
923
|
+
const includeVisualHeatmap = opts.includeVisualHeatmap !== false;
|
|
924
|
+
const cwd = typeof opts.cwd === "string" ? opts.cwd : undefined;
|
|
925
|
+
const invById = new Map();
|
|
926
|
+
const contractInvs = opts.contract && isRecord(opts.contract) && Array.isArray(opts.contract.invariants)
|
|
927
|
+
? opts.contract.invariants
|
|
928
|
+
: [];
|
|
929
|
+
for (const inv of contractInvs) {
|
|
930
|
+
if (isRecord(inv) && typeof inv.id === "string") {
|
|
931
|
+
invById.set(inv.id, inv);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
const items = [];
|
|
935
|
+
const antiCheatReasons = extractAntiCheatReasons(safeReport.antiCheat);
|
|
936
|
+
for (let i = 0; i < antiCheatReasons.length; i++) {
|
|
937
|
+
const cleanReason = sanitizeSingleLine(antiCheatReasons[i], MAX_EVIDENCE_LINE_CHARS);
|
|
938
|
+
items.push({
|
|
939
|
+
invariantId: antiCheatReasons.length === 1 ? "anti-cheat" : `anti-cheat:${i + 1}`,
|
|
940
|
+
type: "anti_cheat",
|
|
941
|
+
severity: "hard",
|
|
942
|
+
status: "fail",
|
|
943
|
+
category: "ANTI_CHEAT_VIOLATION",
|
|
944
|
+
confidence: "high",
|
|
945
|
+
redacted: false,
|
|
946
|
+
headline: cleanReason,
|
|
947
|
+
evidence: [cleanReason],
|
|
948
|
+
suggestedFix: "Remove hardcoded/stubbed outputs or overfitted shortcuts and implement genuine general behavior for all probes."
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
const rawResults = Array.isArray(safeReport.results) ? safeReport.results : [];
|
|
952
|
+
for (const result of rawResults) {
|
|
953
|
+
if (!shouldDiagnoseResult(result))
|
|
954
|
+
continue;
|
|
955
|
+
const rawId = typeof result.id === "string" ? result.id : String(result.id ?? "unknown");
|
|
956
|
+
const invariant = invById.get(rawId);
|
|
957
|
+
const redacted = isRedactedHoldout(result, invariant);
|
|
958
|
+
const cls = classifyFailure(result, invariant);
|
|
959
|
+
if (redacted) {
|
|
960
|
+
const hint = typeof invariant?.holdoutHint === "string" && invariant.holdoutHint.trim()
|
|
961
|
+
? `Holdout hint: ${sanitizeSingleLine(invariant.holdoutHint)}`
|
|
962
|
+
: REDACTED_HOLDOUT_TOKEN;
|
|
963
|
+
items.push({
|
|
964
|
+
invariantId: sanitizeSingleLine(rawId),
|
|
965
|
+
type: sanitizeSingleLine(String(result.type ?? "unknown")),
|
|
966
|
+
severity: sanitizeSingleLine(String(result.severity ?? "unknown")),
|
|
967
|
+
status: sanitizeSingleLine(String(result.status ?? "fail")),
|
|
968
|
+
category: cls.category,
|
|
969
|
+
confidence: cls.confidence,
|
|
970
|
+
redacted: true,
|
|
971
|
+
headline: cls.headline,
|
|
972
|
+
evidence: [hint],
|
|
973
|
+
suggestedFix: cls.suggestedFix
|
|
974
|
+
});
|
|
975
|
+
continue;
|
|
976
|
+
}
|
|
977
|
+
const evidence = collectEvidence(result, maxEvidence);
|
|
978
|
+
const rawRepro = ownProp(result, "repro");
|
|
979
|
+
const repro = typeof rawRepro === "string" && rawRepro.trim()
|
|
980
|
+
? sanitizeSingleLine(rawRepro, MAX_EVIDENCE_LINE_CHARS)
|
|
981
|
+
: undefined;
|
|
982
|
+
let spatialHeatmap;
|
|
983
|
+
if (includeVisualHeatmap) {
|
|
984
|
+
const metrics = ownProp(result, "metrics");
|
|
985
|
+
const diff = ownProp(result, "diff");
|
|
986
|
+
const safeRef = resolveSafeImagePath(ownProp(metrics, "referencePath") ?? ownProp(diff, "referencePath"), cwd);
|
|
987
|
+
const safeCand = resolveSafeImagePath(ownProp(metrics, "candidatePath") ?? ownProp(diff, "candidatePath"), cwd);
|
|
988
|
+
if (safeRef && safeCand) {
|
|
989
|
+
const computed = await computeSpatialHeatmapFromFiles(safeRef, safeCand);
|
|
990
|
+
if (computed) {
|
|
991
|
+
spatialHeatmap = computed;
|
|
992
|
+
if (evidence.length < maxEvidence)
|
|
993
|
+
evidence.push(sanitizeSingleLine(`Spatial heatmap: ${computed.summary}`));
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
const bboxShifts = extractBBoxShiftVectors(result, invariant);
|
|
998
|
+
items.push({
|
|
999
|
+
invariantId: sanitizeSingleLine(rawId),
|
|
1000
|
+
type: sanitizeSingleLine(String(result.type ?? "unknown")),
|
|
1001
|
+
severity: sanitizeSingleLine(String(result.severity ?? "unknown")),
|
|
1002
|
+
status: sanitizeSingleLine(String(result.status ?? "fail")),
|
|
1003
|
+
category: cls.category,
|
|
1004
|
+
confidence: cls.confidence,
|
|
1005
|
+
redacted: false,
|
|
1006
|
+
headline: cls.headline,
|
|
1007
|
+
evidence,
|
|
1008
|
+
suggestedFix: cls.suggestedFix,
|
|
1009
|
+
...(repro ? { repro } : {}),
|
|
1010
|
+
...(spatialHeatmap ? { spatialHeatmap } : {}),
|
|
1011
|
+
...(bboxShifts ? { bboxShifts } : {})
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
items.sort((a, b) => priorityRank(a) - priorityRank(b));
|
|
1015
|
+
const categoryCountMap = new Map();
|
|
1016
|
+
for (const item of items) {
|
|
1017
|
+
categoryCountMap.set(item.category, (categoryCountMap.get(item.category) || 0) + 1);
|
|
1018
|
+
}
|
|
1019
|
+
const categoryCounts = {};
|
|
1020
|
+
for (const [k, v] of categoryCountMap.entries()) {
|
|
1021
|
+
categoryCounts[k] = v;
|
|
1022
|
+
}
|
|
1023
|
+
const gateObj = isRecord(safeReport.gate) ? safeReport.gate : undefined;
|
|
1024
|
+
const contractName = opts.contract && isRecord(opts.contract) && isRecord(opts.contract.target) && typeof opts.contract.target.name === "string"
|
|
1025
|
+
? opts.contract.target.name
|
|
1026
|
+
: "unknown";
|
|
1027
|
+
return {
|
|
1028
|
+
ok: items.length === 0 && gateObj?.passed === true,
|
|
1029
|
+
contractName: sanitizeSingleLine(contractName),
|
|
1030
|
+
gate: sanitizeSingleLine(typeof gateObj?.status === "string" ? gateObj.status : "fail"),
|
|
1031
|
+
totalDiagnosed: items.length,
|
|
1032
|
+
categoryCounts,
|
|
1033
|
+
items,
|
|
1034
|
+
repairBrief: buildRepairBrief(items, safeReport, maxBriefChars),
|
|
1035
|
+
generatedAt: new Date().toISOString()
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
export function formatPrettyDiagnosis(report, options = {}) {
|
|
1039
|
+
const opts = isRecord(options) ? options : {};
|
|
1040
|
+
const useColor = opts.color === true;
|
|
1041
|
+
const safeItems = Array.isArray(report?.items) ? report.items : [];
|
|
1042
|
+
const totalDiagnosed = typeof report?.totalDiagnosed === "number" ? report.totalDiagnosed : safeItems.length;
|
|
1043
|
+
const badge = report?.ok
|
|
1044
|
+
? style("[DIAGNOSE OK]", `${ANSI.bold}${ANSI.green}`, useColor)
|
|
1045
|
+
: style("[DIAGNOSE]", `${ANSI.bold}${ANSI.red}`, useColor);
|
|
1046
|
+
const lines = [
|
|
1047
|
+
`${badge} ${style(sanitizeSingleLine(String(report?.contractName ?? "unknown")), ANSI.bold, useColor)} ${style(`(gate: ${sanitizeSingleLine(String(report?.gate ?? "unknown"))}, ${totalDiagnosed} issue${totalDiagnosed === 1 ? "" : "s"})`, ANSI.dim, useColor)}`
|
|
1048
|
+
];
|
|
1049
|
+
if (totalDiagnosed === 0) {
|
|
1050
|
+
lines.push("No failures, warnings, or missing adapters to diagnose.");
|
|
1051
|
+
return lines.join("\n");
|
|
1052
|
+
}
|
|
1053
|
+
const counts = isRecord(report?.categoryCounts) ? report.categoryCounts : {};
|
|
1054
|
+
lines.push(`Categories: ${Object.entries(counts).map(([k, v]) => `${sanitizeSingleLine(k)}=${String(v)}`).join(", ")}`, "");
|
|
1055
|
+
for (const item of safeItems) {
|
|
1056
|
+
if (!isRecord(item))
|
|
1057
|
+
continue;
|
|
1058
|
+
const tone = item.category === "ANTI_CHEAT_VIOLATION" || item.status === "fail" || item.status === "error"
|
|
1059
|
+
? `${ANSI.bold}${ANSI.red}`
|
|
1060
|
+
: item.status === "warn"
|
|
1061
|
+
? `${ANSI.bold}${ANSI.yellow}`
|
|
1062
|
+
: `${ANSI.bold}${ANSI.cyan}`;
|
|
1063
|
+
const redactedSuffix = item.redacted ? ` ${style("[holdout redacted]", ANSI.dim, useColor)}` : "";
|
|
1064
|
+
lines.push(`- ${style(`[${sanitizeSingleLine(String(item.category))}]`, tone, useColor)} ${sanitizeSingleLine(String(item.invariantId))} ${style(`(${sanitizeSingleLine(String(item.severity))}, ${sanitizeSingleLine(String(item.status))}, ${sanitizeSingleLine(String(item.confidence))})`, ANSI.dim, useColor)}${redactedSuffix}`, ` ${sanitizeSingleLine(String(item.headline))}`);
|
|
1065
|
+
const evList = Array.isArray(item.evidence) ? item.evidence : [];
|
|
1066
|
+
for (const ev of evList.slice(0, 2))
|
|
1067
|
+
lines.push(` ${style("evidence:", ANSI.dim, useColor)} ${sanitizeSingleLine(String(ev))}`);
|
|
1068
|
+
if (!item.redacted && item.spatialHeatmap) {
|
|
1069
|
+
lines.push(` ${style("spatial:", ANSI.cyan, useColor)} ${sanitizeSingleLine(String(item.spatialHeatmap.summary))}`);
|
|
1070
|
+
for (const gridLine of String(item.spatialHeatmap.asciiGrid).split("\n"))
|
|
1071
|
+
lines.push(` ${redactSensitiveText(gridLine)}`);
|
|
1072
|
+
}
|
|
1073
|
+
if (!item.redacted && Array.isArray(item.bboxShifts) && item.bboxShifts.length > 0) {
|
|
1074
|
+
for (const s of item.bboxShifts.slice(0, 3)) {
|
|
1075
|
+
lines.push(` ${style("shift:", ANSI.cyan, useColor)} ${sanitizeSingleLine(String(s.refId))} -> ${sanitizeSingleLine(String(s.direction))} (IoU ${Number(s.iou).toFixed(2)})`);
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
lines.push(` ${style("fix:", ANSI.green, useColor)} ${sanitizeSingleLine(String(item.suggestedFix))}`);
|
|
1079
|
+
if (!item.redacted && item.repro)
|
|
1080
|
+
lines.push(` ${style("repro:", ANSI.dim, useColor)} ${sanitizeSingleLine(String(item.repro))}`);
|
|
1081
|
+
}
|
|
1082
|
+
return lines.join("\n");
|
|
1083
|
+
}
|