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,1088 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Multi-domain contract composition (`mergeContracts`), structural contract drift
|
|
3
|
+
* and anti-tamper auditing (`diffContracts`), plus sanitized terminal and Markdown
|
|
4
|
+
* formatters (`formatPrettyContractDiff`, `renderContractDiffMarkdown`).
|
|
5
|
+
*
|
|
6
|
+
* Zero external runtime dependencies; strictly erasable TypeScript.
|
|
7
|
+
*/
|
|
8
|
+
import { VibecodeError } from "./errors.js";
|
|
9
|
+
import { VALID_DOMAINS, validateContract } from "./schema.js";
|
|
10
|
+
const ANSI = {
|
|
11
|
+
reset: "\x1b[0m",
|
|
12
|
+
bold: "\x1b[1m",
|
|
13
|
+
dim: "\x1b[2m",
|
|
14
|
+
red: "\x1b[31m",
|
|
15
|
+
green: "\x1b[32m",
|
|
16
|
+
yellow: "\x1b[33m",
|
|
17
|
+
cyan: "\x1b[36m"
|
|
18
|
+
};
|
|
19
|
+
const MAX_LISTED_ITEMS = 25;
|
|
20
|
+
// Defense-in-depth sanitization patterns matching src/core/regression.ts (plus OSC sequences).
|
|
21
|
+
const ANSI_ESCAPE_RE = /\x1b(?:\[[0-9;?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\))/g;
|
|
22
|
+
const CONTROL_CHARS_RE = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g;
|
|
23
|
+
const VAULT_DIR_RE = /[^\s"'`<>()[\]{}]*\.vibecode-vault[^\s"'`<>()[\]{}]*/gi;
|
|
24
|
+
const VAULT_PATH_RE = /(?:[A-Za-z]:\\|\/|\.?\.?[\\/])[^\s"'`<>()[\]{}]*holdouts?(?:-[a-f0-9]+)?\.json/gi;
|
|
25
|
+
const HOLDOUT_FILENAME_RE = /\bholdouts?(?:-[a-f0-9]+)?\.json\b/gi;
|
|
26
|
+
const URL_CREDENTIALS_RE = /(https?:\/\/)([^:@\s"'`<>\/]+:[^@\s"'`<>\/]+)(@)/gi;
|
|
27
|
+
const SENSITIVE_QUERY_PARAM_RE = /([?&](?:access_token|id_token|refresh_token|token|api[_-]?key|apikey|secret|password|passwd|auth|jwt|session[_-]?id|sig|signature|client[_-]?secret)=)([^&#\s"'`<>]+)/gi;
|
|
28
|
+
const SENSITIVE_COOKIE_RE = /(["']?\b(?:set-cookie|cookie)\b["']?\s*[:=]\s*["']?)([^\r\n"'`}]+)/gi;
|
|
29
|
+
const SENSITIVE_QUOTED_HEADER_RE = /(["']\s*(?:authorization|proxy-authorization|x-api-key|x-auth-token|api[_-]?key|apikey)\s*[:=]\s*)(?:(?:bearer|basic|token|digest|apikey)\s+)?([^"'`\r\n]+)/gi;
|
|
30
|
+
const SENSITIVE_JSON_FIELD_RE = /(["']\b(?:authorization|proxy-authorization|x-api-key|x-auth-token|api[_-]?key|apikey|secret|client[_-]?secret|token|jwt|access[_-]?token|refresh[_-]?token|id[_-]?token|password|passwd|private[_-]?key|session[_-]?id)\b["']\s*[:=]\s*["'])([^"'\r\n]+)(["'])/gi;
|
|
31
|
+
const SENSITIVE_HEADER_VALUE_RE = /(\b(?:authorization|proxy-authorization|x-api-key|x-auth-token|api[_-]?key|apikey|client[_-]?secret|access[_-]?token|refresh[_-]?token|id[_-]?token|session[_-]?id)\b\s*[:=]\s*)(?:"[^"]*"|'[^']*'|(?:(?:bearer|basic|token|digest|apikey)\s+)?[^\s'",;})&#]+)/gi;
|
|
32
|
+
const BEARER_TOKEN_RE = /(\bBearer\s+)([A-Za-z0-9._~+/=-]{2,})/gi;
|
|
33
|
+
const STANDALONE_API_KEY_RE = /\b(?:sk-(?:proj-|live-|test-)?[A-Za-z0-9_-]{12,}|gh[pousr]_[A-Za-z0-9]{12,}|AIza[0-9A-Za-z_-]{20,}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,})\b/g;
|
|
34
|
+
const FLOOR_TOLERANCE_KEYS = new Set([
|
|
35
|
+
"minSSIM",
|
|
36
|
+
"minLayoutIoU",
|
|
37
|
+
"minPaletteSimilarity",
|
|
38
|
+
"stateMatchFloor",
|
|
39
|
+
"minKeyframeSSIM",
|
|
40
|
+
"minMotionRegionIoU",
|
|
41
|
+
"ssimMin",
|
|
42
|
+
"regionIoUMin",
|
|
43
|
+
"layoutIoUMin",
|
|
44
|
+
"perceptualMin",
|
|
45
|
+
"minMatchRatio",
|
|
46
|
+
"orderParityMin"
|
|
47
|
+
]);
|
|
48
|
+
const CEILING_TOLERANCE_KEYS = new Set([
|
|
49
|
+
"maxPixelDiffRatio",
|
|
50
|
+
"colorDelta",
|
|
51
|
+
"maxHammingDistance",
|
|
52
|
+
"maxDiffRatio",
|
|
53
|
+
"maxPixelDelta"
|
|
54
|
+
]);
|
|
55
|
+
const FLOOR_KEY_PATTERN = /^min[A-Z_]|Min$|Floor$/;
|
|
56
|
+
const CEILING_KEY_PATTERN = /^max[A-Z_]|Max$|Delta$|Tolerance$/;
|
|
57
|
+
const BOOLEAN_STRICT_EXPECTED_FIELDS = [
|
|
58
|
+
"noConsoleErrors",
|
|
59
|
+
"noUncaughtExceptions",
|
|
60
|
+
"noPageErrors",
|
|
61
|
+
"noServerErrors",
|
|
62
|
+
"nonBlank"
|
|
63
|
+
];
|
|
64
|
+
const SCALAR_OR_OBJECT_EXPECTED_FIELDS = [
|
|
65
|
+
"stdoutExact",
|
|
66
|
+
"stderrExact",
|
|
67
|
+
"goldenStdout",
|
|
68
|
+
"bodyExact",
|
|
69
|
+
"titleContains",
|
|
70
|
+
"finalUrlIncludes",
|
|
71
|
+
"jsonSchema",
|
|
72
|
+
"jsonSubset",
|
|
73
|
+
"referenceHash",
|
|
74
|
+
"dimensions"
|
|
75
|
+
];
|
|
76
|
+
const ARRAY_EXPECTED_FIELDS = [
|
|
77
|
+
"stdoutContains",
|
|
78
|
+
"stdoutNotContains",
|
|
79
|
+
"stdoutRegex",
|
|
80
|
+
"stderrContains",
|
|
81
|
+
"jsonPaths",
|
|
82
|
+
"landmarks",
|
|
83
|
+
"boundingBoxes",
|
|
84
|
+
"visibleText",
|
|
85
|
+
"hiddenText",
|
|
86
|
+
"domAssertions",
|
|
87
|
+
"networkCalls",
|
|
88
|
+
"filesPresent",
|
|
89
|
+
"exports",
|
|
90
|
+
"assertions",
|
|
91
|
+
"fsEffects",
|
|
92
|
+
"interactiveLandmarks",
|
|
93
|
+
"states",
|
|
94
|
+
"transitions"
|
|
95
|
+
];
|
|
96
|
+
function isPlainObject(v) {
|
|
97
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
98
|
+
}
|
|
99
|
+
function hasOwn(obj, key) {
|
|
100
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
101
|
+
}
|
|
102
|
+
function setOwn(obj, key, value) {
|
|
103
|
+
Object.defineProperty(obj, key, {
|
|
104
|
+
value,
|
|
105
|
+
enumerable: true,
|
|
106
|
+
writable: true,
|
|
107
|
+
configurable: true
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
function deepClone(value) {
|
|
111
|
+
if (value === null || typeof value !== "object") {
|
|
112
|
+
return value;
|
|
113
|
+
}
|
|
114
|
+
if (Array.isArray(value)) {
|
|
115
|
+
return value.map((item) => deepClone(item));
|
|
116
|
+
}
|
|
117
|
+
const src = value;
|
|
118
|
+
const out = {};
|
|
119
|
+
for (const key of Object.keys(src)) {
|
|
120
|
+
setOwn(out, key, deepClone(src[key]));
|
|
121
|
+
}
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
function canonicalJson(v, seen = new WeakSet()) {
|
|
125
|
+
if (v === null)
|
|
126
|
+
return "null";
|
|
127
|
+
if (typeof v === "boolean" || typeof v === "string")
|
|
128
|
+
return JSON.stringify(v);
|
|
129
|
+
if (typeof v === "number")
|
|
130
|
+
return Number.isFinite(v) ? JSON.stringify(v) : String(v);
|
|
131
|
+
if (typeof v === "undefined")
|
|
132
|
+
return "undefined";
|
|
133
|
+
if (Array.isArray(v)) {
|
|
134
|
+
if (seen.has(v))
|
|
135
|
+
return '"[Circular]"';
|
|
136
|
+
seen.add(v);
|
|
137
|
+
const parts = v.map((item) => (item === undefined ? "null" : canonicalJson(item, seen)));
|
|
138
|
+
seen.delete(v);
|
|
139
|
+
return `[${parts.join(",")}]`;
|
|
140
|
+
}
|
|
141
|
+
if (typeof v === "object") {
|
|
142
|
+
if (seen.has(v))
|
|
143
|
+
return '"[Circular]"';
|
|
144
|
+
seen.add(v);
|
|
145
|
+
const obj = v;
|
|
146
|
+
const keys = Object.keys(obj).sort();
|
|
147
|
+
const parts = [];
|
|
148
|
+
for (const k of keys) {
|
|
149
|
+
if (obj[k] === undefined)
|
|
150
|
+
continue;
|
|
151
|
+
parts.push(`${JSON.stringify(k)}:${canonicalJson(obj[k], seen)}`);
|
|
152
|
+
}
|
|
153
|
+
seen.delete(v);
|
|
154
|
+
return `{${parts.join(",")}}`;
|
|
155
|
+
}
|
|
156
|
+
return JSON.stringify(String(v));
|
|
157
|
+
}
|
|
158
|
+
function redactSecrets(input) {
|
|
159
|
+
return input
|
|
160
|
+
.replace(VAULT_DIR_RE, "[REDACTED_VAULT]")
|
|
161
|
+
.replace(VAULT_PATH_RE, "[REDACTED_VAULT]")
|
|
162
|
+
.replace(HOLDOUT_FILENAME_RE, "[REDACTED_VAULT]")
|
|
163
|
+
.replace(URL_CREDENTIALS_RE, "$1[REDACTED]$3")
|
|
164
|
+
.replace(SENSITIVE_QUERY_PARAM_RE, "$1[REDACTED]")
|
|
165
|
+
.replace(SENSITIVE_COOKIE_RE, "$1[REDACTED]")
|
|
166
|
+
.replace(SENSITIVE_QUOTED_HEADER_RE, "$1[REDACTED]")
|
|
167
|
+
.replace(SENSITIVE_JSON_FIELD_RE, "$1[REDACTED]$3")
|
|
168
|
+
.replace(SENSITIVE_HEADER_VALUE_RE, "$1[REDACTED]")
|
|
169
|
+
.replace(BEARER_TOKEN_RE, "$1[REDACTED]")
|
|
170
|
+
.replace(STANDALONE_API_KEY_RE, "[REDACTED]");
|
|
171
|
+
}
|
|
172
|
+
function sanitizeText(input) {
|
|
173
|
+
const preRedacted = redactSecrets(String(input));
|
|
174
|
+
const stripped = preRedacted
|
|
175
|
+
.replace(ANSI_ESCAPE_RE, "")
|
|
176
|
+
.replace(CONTROL_CHARS_RE, "");
|
|
177
|
+
return redactSecrets(stripped);
|
|
178
|
+
}
|
|
179
|
+
function sanitizeLine(input) {
|
|
180
|
+
return sanitizeText(input)
|
|
181
|
+
.replace(/\r?\n/g, " ")
|
|
182
|
+
.replace(/\s+/g, " ")
|
|
183
|
+
.trim();
|
|
184
|
+
}
|
|
185
|
+
function escapeMarkdownInline(input) {
|
|
186
|
+
return sanitizeLine(input)
|
|
187
|
+
.replace(/</g, "<")
|
|
188
|
+
.replace(/>/g, ">")
|
|
189
|
+
.replace(/\[/g, "\\[")
|
|
190
|
+
.replace(/\]/g, "\\]")
|
|
191
|
+
.replace(/\|/g, "\\|");
|
|
192
|
+
}
|
|
193
|
+
function formatCodeSpan(input) {
|
|
194
|
+
const clean = sanitizeLine(input);
|
|
195
|
+
if (clean.length === 0)
|
|
196
|
+
return "`(empty)`";
|
|
197
|
+
const longestBackticks = (clean.match(/`+/g) ?? []).reduce((max, s) => Math.max(max, s.length), 0);
|
|
198
|
+
const fence = "`".repeat(longestBackticks + 1);
|
|
199
|
+
const needsSpace = clean.startsWith("`") || clean.endsWith("`");
|
|
200
|
+
return needsSpace ? `${fence} ${clean} ${fence}` : `${fence}${clean}${fence}`;
|
|
201
|
+
}
|
|
202
|
+
function style(text, codes, useColor) {
|
|
203
|
+
return useColor ? `${codes}${text}${ANSI.reset}` : text;
|
|
204
|
+
}
|
|
205
|
+
function slugifySegment(raw) {
|
|
206
|
+
return raw
|
|
207
|
+
.trim()
|
|
208
|
+
.toLowerCase()
|
|
209
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
210
|
+
.replace(/^-+|-+$/g, "");
|
|
211
|
+
}
|
|
212
|
+
function resolveMergePrefix(incoming, explicitPrefix) {
|
|
213
|
+
if (typeof explicitPrefix === "string" && explicitPrefix.trim().length > 0) {
|
|
214
|
+
const cleaned = explicitPrefix
|
|
215
|
+
.trim()
|
|
216
|
+
.replace(/[^A-Za-z0-9_-]+/g, "-")
|
|
217
|
+
.replace(/^-+|-+$/g, "");
|
|
218
|
+
if (cleaned.length > 0)
|
|
219
|
+
return cleaned;
|
|
220
|
+
}
|
|
221
|
+
const firstDomain = Array.isArray(incoming.target?.domains) ? incoming.target.domains[0] : undefined;
|
|
222
|
+
if (typeof firstDomain === "string" && firstDomain.trim().length > 0) {
|
|
223
|
+
const slug = slugifySegment(firstDomain);
|
|
224
|
+
if (slug.length > 0)
|
|
225
|
+
return slug;
|
|
226
|
+
}
|
|
227
|
+
if (typeof incoming.target?.name === "string" && incoming.target.name.trim().length > 0) {
|
|
228
|
+
const slug = slugifySegment(incoming.target.name);
|
|
229
|
+
if (slug.length > 0)
|
|
230
|
+
return slug;
|
|
231
|
+
}
|
|
232
|
+
return "merged";
|
|
233
|
+
}
|
|
234
|
+
function allocateUniqueId(candidate, used) {
|
|
235
|
+
if (!used.has(candidate))
|
|
236
|
+
return candidate;
|
|
237
|
+
let suffix = 2;
|
|
238
|
+
while (used.has(`${candidate}-${suffix}`)) {
|
|
239
|
+
suffix += 1;
|
|
240
|
+
}
|
|
241
|
+
return `${candidate}-${suffix}`;
|
|
242
|
+
}
|
|
243
|
+
function clampUnit(value, fallback) {
|
|
244
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
245
|
+
return fallback;
|
|
246
|
+
return Math.max(0, Math.min(1, value));
|
|
247
|
+
}
|
|
248
|
+
function normalizeThresholdDefaults(raw) {
|
|
249
|
+
const d = isPlainObject(raw) ? raw : {};
|
|
250
|
+
return {
|
|
251
|
+
minSSIM: typeof d.minSSIM === "number" && Number.isFinite(d.minSSIM) ? d.minSSIM : 0.85,
|
|
252
|
+
maxPixelDiffRatio: typeof d.maxPixelDiffRatio === "number" && Number.isFinite(d.maxPixelDiffRatio) ? d.maxPixelDiffRatio : 0.1,
|
|
253
|
+
colorDelta: typeof d.colorDelta === "number" && Number.isFinite(d.colorDelta) ? d.colorDelta : 0.1,
|
|
254
|
+
minLayoutIoU: typeof d.minLayoutIoU === "number" && Number.isFinite(d.minLayoutIoU) ? d.minLayoutIoU : 0.75,
|
|
255
|
+
minPaletteSimilarity: typeof d.minPaletteSimilarity === "number" && Number.isFinite(d.minPaletteSimilarity)
|
|
256
|
+
? d.minPaletteSimilarity
|
|
257
|
+
: 0.8,
|
|
258
|
+
stateMatchFloor: typeof d.stateMatchFloor === "number" && Number.isFinite(d.stateMatchFloor) ? d.stateMatchFloor : 0.7,
|
|
259
|
+
minMotionRegionIoU: typeof d.minMotionRegionIoU === "number" && Number.isFinite(d.minMotionRegionIoU) ? d.minMotionRegionIoU : 0.55
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
function mergeThresholds(base, incoming) {
|
|
263
|
+
const baseHard = clampUnit(base?.hardBehavioralParity, 1.0);
|
|
264
|
+
const incHard = clampUnit(incoming?.hardBehavioralParity, 1.0);
|
|
265
|
+
const baseSoft = clampUnit(base?.softPerceptualParity, 0.85);
|
|
266
|
+
const incSoft = clampUnit(incoming?.softPerceptualParity, 0.85);
|
|
267
|
+
const rawBaseMode = base?.softGateMode;
|
|
268
|
+
const rawIncMode = incoming?.softGateMode;
|
|
269
|
+
const isStrictMode = (m) => m === "fail" || m === "strict";
|
|
270
|
+
const softGateMode = isStrictMode(rawBaseMode) || isStrictMode(rawIncMode) ? "fail" : "warn";
|
|
271
|
+
const bDef = normalizeThresholdDefaults(base?.defaults);
|
|
272
|
+
const iDef = normalizeThresholdDefaults(incoming?.defaults);
|
|
273
|
+
return {
|
|
274
|
+
hardBehavioralParity: Math.max(baseHard, incHard),
|
|
275
|
+
softPerceptualParity: Math.max(baseSoft, incSoft),
|
|
276
|
+
softGateMode,
|
|
277
|
+
defaults: {
|
|
278
|
+
minSSIM: Math.max(bDef.minSSIM, iDef.minSSIM),
|
|
279
|
+
maxPixelDiffRatio: Math.min(bDef.maxPixelDiffRatio, iDef.maxPixelDiffRatio),
|
|
280
|
+
colorDelta: Math.min(bDef.colorDelta, iDef.colorDelta),
|
|
281
|
+
minLayoutIoU: Math.max(bDef.minLayoutIoU, iDef.minLayoutIoU),
|
|
282
|
+
minPaletteSimilarity: Math.max(bDef.minPaletteSimilarity, iDef.minPaletteSimilarity),
|
|
283
|
+
stateMatchFloor: Math.max(bDef.stateMatchFloor, iDef.stateMatchFloor),
|
|
284
|
+
minMotionRegionIoU: Math.max(bDef.minMotionRegionIoU, iDef.minMotionRegionIoU)
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
function assertContractInput(contract, label) {
|
|
289
|
+
if (!isPlainObject(contract)) {
|
|
290
|
+
throw new VibecodeError("CONTRACT_INVALID", `${label} contract must be a non-null object`);
|
|
291
|
+
}
|
|
292
|
+
const validation = validateContract(contract);
|
|
293
|
+
if (!validation.ok) {
|
|
294
|
+
const first = validation.errors[0];
|
|
295
|
+
throw new VibecodeError("CONTRACT_INVALID", `${label} contract is invalid: ${first ? `${first.path} ${first.message}` : "validation failed"}`, { details: validation.errors });
|
|
296
|
+
}
|
|
297
|
+
return contract;
|
|
298
|
+
}
|
|
299
|
+
function canonicalFixtureRelKey(relPath) {
|
|
300
|
+
const norm = relPath.replace(/\\/g, "/");
|
|
301
|
+
return process.platform === "win32" ? norm.toLowerCase() : norm;
|
|
302
|
+
}
|
|
303
|
+
function mergeFixtureHookArrays(baseHooks, incomingHooks) {
|
|
304
|
+
if (!Array.isArray(baseHooks) && !Array.isArray(incomingHooks))
|
|
305
|
+
return undefined;
|
|
306
|
+
const merged = [];
|
|
307
|
+
const seen = new Set();
|
|
308
|
+
for (const list of [baseHooks, incomingHooks]) {
|
|
309
|
+
if (!Array.isArray(list))
|
|
310
|
+
continue;
|
|
311
|
+
for (const hook of list) {
|
|
312
|
+
const sig = canonicalJson(hook);
|
|
313
|
+
if (seen.has(sig))
|
|
314
|
+
continue;
|
|
315
|
+
seen.add(sig);
|
|
316
|
+
merged.push(hook);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return merged;
|
|
320
|
+
}
|
|
321
|
+
function mergeFixtures(baseFixtures, incomingFixtures, onConflict) {
|
|
322
|
+
if (!baseFixtures && !incomingFixtures)
|
|
323
|
+
return undefined;
|
|
324
|
+
const out = {};
|
|
325
|
+
const b = isPlainObject(baseFixtures) ? baseFixtures : {};
|
|
326
|
+
const inc = isPlainObject(incomingFixtures) ? incomingFixtures : {};
|
|
327
|
+
if (Array.isArray(b.seedFiles) || Array.isArray(inc.seedFiles)) {
|
|
328
|
+
const seeds = [];
|
|
329
|
+
const idxByPath = new Map();
|
|
330
|
+
if (Array.isArray(b.seedFiles)) {
|
|
331
|
+
for (const seed of b.seedFiles) {
|
|
332
|
+
const key = canonicalFixtureRelKey(seed.path);
|
|
333
|
+
const existing = idxByPath.get(key);
|
|
334
|
+
if (existing === undefined) {
|
|
335
|
+
idxByPath.set(key, seeds.length);
|
|
336
|
+
seeds.push(seed);
|
|
337
|
+
}
|
|
338
|
+
else {
|
|
339
|
+
seeds[existing] = seed;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
if (Array.isArray(inc.seedFiles)) {
|
|
344
|
+
for (const seed of inc.seedFiles) {
|
|
345
|
+
const key = canonicalFixtureRelKey(seed.path);
|
|
346
|
+
const existing = idxByPath.get(key);
|
|
347
|
+
if (existing === undefined) {
|
|
348
|
+
idxByPath.set(key, seeds.length);
|
|
349
|
+
seeds.push(seed);
|
|
350
|
+
}
|
|
351
|
+
else if (onConflict === "overwrite") {
|
|
352
|
+
seeds[existing] = seed;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
out.seedFiles = seeds;
|
|
357
|
+
}
|
|
358
|
+
if (Array.isArray(b.snapshotPaths) || Array.isArray(inc.snapshotPaths)) {
|
|
359
|
+
const snaps = [];
|
|
360
|
+
const seen = new Set();
|
|
361
|
+
for (const list of [b.snapshotPaths, inc.snapshotPaths]) {
|
|
362
|
+
if (!Array.isArray(list))
|
|
363
|
+
continue;
|
|
364
|
+
for (const p of list) {
|
|
365
|
+
const key = canonicalFixtureRelKey(p);
|
|
366
|
+
if (seen.has(key))
|
|
367
|
+
continue;
|
|
368
|
+
seen.add(key);
|
|
369
|
+
snaps.push(p);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
out.snapshotPaths = snaps;
|
|
373
|
+
}
|
|
374
|
+
const httpSetup = mergeFixtureHookArrays(b.httpSetup, inc.httpSetup);
|
|
375
|
+
if (httpSetup !== undefined)
|
|
376
|
+
out.httpSetup = httpSetup;
|
|
377
|
+
const httpTeardown = mergeFixtureHookArrays(b.httpTeardown, inc.httpTeardown);
|
|
378
|
+
if (httpTeardown !== undefined)
|
|
379
|
+
out.httpTeardown = httpTeardown;
|
|
380
|
+
const commandSetup = mergeFixtureHookArrays(b.commandSetup, inc.commandSetup);
|
|
381
|
+
if (commandSetup !== undefined)
|
|
382
|
+
out.commandSetup = commandSetup;
|
|
383
|
+
const commandTeardown = mergeFixtureHookArrays(b.commandTeardown, inc.commandTeardown);
|
|
384
|
+
if (commandTeardown !== undefined)
|
|
385
|
+
out.commandTeardown = commandTeardown;
|
|
386
|
+
return out;
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Compose two contracts (`base` + `incoming`) into a single multi-domain `ContractV02`.
|
|
390
|
+
*
|
|
391
|
+
* - Never mutates `base` or `incoming`.
|
|
392
|
+
* - Strips `holdout: true` invariants from `incoming` so vault holdouts never leak.
|
|
393
|
+
* - Resolves invariant, source, slice, and artifact key collisions deterministically.
|
|
394
|
+
*/
|
|
395
|
+
export function mergeContracts(base, incoming, options) {
|
|
396
|
+
assertContractInput(base, "Base");
|
|
397
|
+
assertContractInput(incoming, "Incoming");
|
|
398
|
+
if (options !== undefined && (options === null || typeof options !== "object" || Array.isArray(options))) {
|
|
399
|
+
throw new VibecodeError("CONTRACT_INVALID", "Merge options must be an object");
|
|
400
|
+
}
|
|
401
|
+
const onConflict = options?.onConflict ?? "prefix";
|
|
402
|
+
if (onConflict !== "prefix" && onConflict !== "overwrite" && onConflict !== "skip") {
|
|
403
|
+
throw new VibecodeError("CONTRACT_INVALID", `Invalid onConflict strategy "${String(onConflict)}": expected "prefix", "overwrite", or "skip"`);
|
|
404
|
+
}
|
|
405
|
+
const baseClone = deepClone(base);
|
|
406
|
+
const incomingClone = deepClone(incoming);
|
|
407
|
+
const prefix = resolveMergePrefix(incomingClone, options?.prefix);
|
|
408
|
+
// Merge target.name
|
|
409
|
+
const mergedName = typeof options?.name === "string" && options.name.trim().length > 0
|
|
410
|
+
? options.name.trim()
|
|
411
|
+
: baseClone.target.name;
|
|
412
|
+
// Merge target.sources with collision avoidance
|
|
413
|
+
const mergedSources = [];
|
|
414
|
+
const sourcesById = new Map();
|
|
415
|
+
const baseSources = Array.isArray(baseClone.target.sources) ? baseClone.target.sources : [];
|
|
416
|
+
for (const src of baseSources) {
|
|
417
|
+
mergedSources.push(src);
|
|
418
|
+
sourcesById.set(src.id, src);
|
|
419
|
+
}
|
|
420
|
+
const sourceIdMap = new Map();
|
|
421
|
+
const incomingSources = Array.isArray(incomingClone.target.sources) ? incomingClone.target.sources : [];
|
|
422
|
+
for (const src of incomingSources) {
|
|
423
|
+
const existing = sourcesById.get(src.id);
|
|
424
|
+
if (!existing) {
|
|
425
|
+
mergedSources.push(src);
|
|
426
|
+
sourcesById.set(src.id, src);
|
|
427
|
+
sourceIdMap.set(src.id, src.id);
|
|
428
|
+
}
|
|
429
|
+
else if (existing.kind === src.kind && existing.ref === src.ref) {
|
|
430
|
+
// Deduplicate identical source references
|
|
431
|
+
sourceIdMap.set(src.id, existing.id);
|
|
432
|
+
}
|
|
433
|
+
else {
|
|
434
|
+
const newSourceId = allocateUniqueId(`${prefix}-${src.id}`, sourcesById);
|
|
435
|
+
const renamedSource = { ...src, id: newSourceId };
|
|
436
|
+
mergedSources.push(renamedSource);
|
|
437
|
+
sourcesById.set(newSourceId, renamedSource);
|
|
438
|
+
sourceIdMap.set(src.id, newSourceId);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
// Merge artifacts.files without losing base keys
|
|
442
|
+
const baseRoot = typeof baseClone.artifacts?.root === "string" && baseClone.artifacts.root.length > 0
|
|
443
|
+
? baseClone.artifacts.root
|
|
444
|
+
: ".vibecode/artifacts";
|
|
445
|
+
const mergedFiles = {};
|
|
446
|
+
const usedArtifactKeys = new Set();
|
|
447
|
+
const baseFiles = isPlainObject(baseClone.artifacts?.files) ? baseClone.artifacts.files : {};
|
|
448
|
+
for (const key of Object.keys(baseFiles)) {
|
|
449
|
+
const val = baseFiles[key];
|
|
450
|
+
if (typeof val === "string") {
|
|
451
|
+
setOwn(mergedFiles, key, val);
|
|
452
|
+
usedArtifactKeys.add(key);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
const incomingFiles = isPlainObject(incomingClone.artifacts?.files) ? incomingClone.artifacts.files : {};
|
|
456
|
+
for (const key of Object.keys(incomingFiles)) {
|
|
457
|
+
const val = incomingFiles[key];
|
|
458
|
+
if (typeof val !== "string")
|
|
459
|
+
continue;
|
|
460
|
+
if (!usedArtifactKeys.has(key)) {
|
|
461
|
+
setOwn(mergedFiles, key, val);
|
|
462
|
+
usedArtifactKeys.add(key);
|
|
463
|
+
}
|
|
464
|
+
else if (Object.getOwnPropertyDescriptor(mergedFiles, key)?.value !== val) {
|
|
465
|
+
const remappedKey = allocateUniqueId(`${prefix}-${key}`, usedArtifactKeys);
|
|
466
|
+
setOwn(mergedFiles, remappedKey, val);
|
|
467
|
+
usedArtifactKeys.add(remappedKey);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
// Merge invariants using Map for prototype-pollution safety
|
|
471
|
+
const mergedInvariants = [];
|
|
472
|
+
const indexById = new Map();
|
|
473
|
+
for (const inv of baseClone.invariants) {
|
|
474
|
+
indexById.set(inv.id, mergedInvariants.length);
|
|
475
|
+
mergedInvariants.push(inv);
|
|
476
|
+
}
|
|
477
|
+
let addedInvariants = 0;
|
|
478
|
+
let skippedInvariants = 0;
|
|
479
|
+
let excludedHoldouts = 0;
|
|
480
|
+
const renamedIds = [];
|
|
481
|
+
const incomingIdMap = new Map();
|
|
482
|
+
const excludedIncomingIds = new Set();
|
|
483
|
+
const skippedIncomingIds = new Set();
|
|
484
|
+
for (const rawInv of incomingClone.invariants) {
|
|
485
|
+
// Strip holdout invariants from incoming so vault holdouts never leak
|
|
486
|
+
if (rawInv.holdout === true) {
|
|
487
|
+
excludedHoldouts += 1;
|
|
488
|
+
excludedIncomingIds.add(rawInv.id);
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
const inv = rawInv;
|
|
492
|
+
if (typeof inv.sourceId === "string" && sourceIdMap.has(inv.sourceId)) {
|
|
493
|
+
inv.sourceId = sourceIdMap.get(inv.sourceId);
|
|
494
|
+
}
|
|
495
|
+
const existingIdx = indexById.get(inv.id);
|
|
496
|
+
if (existingIdx === undefined) {
|
|
497
|
+
indexById.set(inv.id, mergedInvariants.length);
|
|
498
|
+
mergedInvariants.push(inv);
|
|
499
|
+
incomingIdMap.set(inv.id, inv.id);
|
|
500
|
+
addedInvariants += 1;
|
|
501
|
+
}
|
|
502
|
+
else if (onConflict === "skip") {
|
|
503
|
+
skippedInvariants += 1;
|
|
504
|
+
skippedIncomingIds.add(inv.id);
|
|
505
|
+
}
|
|
506
|
+
else if (onConflict === "overwrite") {
|
|
507
|
+
mergedInvariants[existingIdx] = inv;
|
|
508
|
+
incomingIdMap.set(inv.id, inv.id);
|
|
509
|
+
}
|
|
510
|
+
else {
|
|
511
|
+
const fromId = inv.id;
|
|
512
|
+
const newId = allocateUniqueId(`${prefix}-${fromId}`, indexById);
|
|
513
|
+
inv.id = newId;
|
|
514
|
+
indexById.set(newId, mergedInvariants.length);
|
|
515
|
+
mergedInvariants.push(inv);
|
|
516
|
+
incomingIdMap.set(fromId, newId);
|
|
517
|
+
renamedIds.push({ from: fromId, to: newId });
|
|
518
|
+
addedInvariants += 1;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
// Merge domains (unique valid domains preserving base order then incoming, plus invariant domains)
|
|
522
|
+
const domainSet = new Set();
|
|
523
|
+
const addValidDomain = (d) => {
|
|
524
|
+
if (typeof d === "string" && VALID_DOMAINS.has(d)) {
|
|
525
|
+
domainSet.add(d);
|
|
526
|
+
}
|
|
527
|
+
};
|
|
528
|
+
for (const d of baseClone.target.domains)
|
|
529
|
+
addValidDomain(d);
|
|
530
|
+
for (const d of incomingClone.target.domains)
|
|
531
|
+
addValidDomain(d);
|
|
532
|
+
for (const inv of mergedInvariants)
|
|
533
|
+
addValidDomain(inv.domain);
|
|
534
|
+
const mergedDomains = Array.from(domainSet);
|
|
535
|
+
// Merge slices when base or incoming defines slices
|
|
536
|
+
let mergedSlices;
|
|
537
|
+
if (Array.isArray(baseClone.slices) || Array.isArray(incomingClone.slices)) {
|
|
538
|
+
const slices = [];
|
|
539
|
+
const usedSliceIds = new Set();
|
|
540
|
+
if (Array.isArray(baseClone.slices)) {
|
|
541
|
+
for (const slice of baseClone.slices) {
|
|
542
|
+
slices.push(slice);
|
|
543
|
+
usedSliceIds.add(slice.id);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
if (Array.isArray(incomingClone.slices)) {
|
|
547
|
+
const sliceIdMap = new Map();
|
|
548
|
+
for (const slice of incomingClone.slices) {
|
|
549
|
+
const finalSliceId = usedSliceIds.has(slice.id)
|
|
550
|
+
? allocateUniqueId(`${prefix}-${slice.id}`, usedSliceIds)
|
|
551
|
+
: slice.id;
|
|
552
|
+
usedSliceIds.add(finalSliceId);
|
|
553
|
+
sliceIdMap.set(slice.id, finalSliceId);
|
|
554
|
+
}
|
|
555
|
+
for (const slice of incomingClone.slices) {
|
|
556
|
+
const remappedInvIds = [];
|
|
557
|
+
const seenInvIds = new Set();
|
|
558
|
+
for (const origInvId of slice.invariantIds) {
|
|
559
|
+
if (excludedIncomingIds.has(origInvId) || skippedIncomingIds.has(origInvId)) {
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
562
|
+
const mapped = incomingIdMap.get(origInvId) ?? origInvId;
|
|
563
|
+
if (!indexById.has(mapped) || seenInvIds.has(mapped)) {
|
|
564
|
+
continue;
|
|
565
|
+
}
|
|
566
|
+
seenInvIds.add(mapped);
|
|
567
|
+
remappedInvIds.push(mapped);
|
|
568
|
+
}
|
|
569
|
+
const nextSlice = {
|
|
570
|
+
...slice,
|
|
571
|
+
id: sliceIdMap.get(slice.id) ?? slice.id,
|
|
572
|
+
invariantIds: remappedInvIds
|
|
573
|
+
};
|
|
574
|
+
if (Array.isArray(slice.dependsOn)) {
|
|
575
|
+
const remappedDeps = [];
|
|
576
|
+
const seenDeps = new Set();
|
|
577
|
+
for (const dep of slice.dependsOn) {
|
|
578
|
+
const mappedDep = sliceIdMap.get(dep) ?? dep;
|
|
579
|
+
if (!usedSliceIds.has(mappedDep) || seenDeps.has(mappedDep))
|
|
580
|
+
continue;
|
|
581
|
+
seenDeps.add(mappedDep);
|
|
582
|
+
remappedDeps.push(mappedDep);
|
|
583
|
+
}
|
|
584
|
+
nextSlice.dependsOn = remappedDeps;
|
|
585
|
+
}
|
|
586
|
+
slices.push(nextSlice);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
mergedSlices = slices;
|
|
590
|
+
}
|
|
591
|
+
const mergedFixtures = mergeFixtures(baseClone.fixtures, incomingClone.fixtures, onConflict);
|
|
592
|
+
const mergedContract = {
|
|
593
|
+
schemaVersion: baseClone.schemaVersion || "0.2.0",
|
|
594
|
+
createdAt: new Date().toISOString(),
|
|
595
|
+
generator: isPlainObject(baseClone.generator)
|
|
596
|
+
? baseClone.generator
|
|
597
|
+
: { name: "vibecode-anything", version: "0.2.0", adapter: mergedDomains[0] ?? "cli" },
|
|
598
|
+
target: {
|
|
599
|
+
name: mergedName,
|
|
600
|
+
domains: mergedDomains,
|
|
601
|
+
sources: mergedSources
|
|
602
|
+
},
|
|
603
|
+
artifacts: {
|
|
604
|
+
root: baseRoot,
|
|
605
|
+
files: mergedFiles
|
|
606
|
+
},
|
|
607
|
+
thresholds: mergeThresholds(baseClone.thresholds, incomingClone.thresholds),
|
|
608
|
+
invariants: mergedInvariants,
|
|
609
|
+
...(mergedSlices !== undefined ? { slices: mergedSlices } : {}),
|
|
610
|
+
...(mergedFixtures !== undefined ? { fixtures: mergedFixtures } : {})
|
|
611
|
+
};
|
|
612
|
+
const finalCheck = validateContract(mergedContract);
|
|
613
|
+
if (!finalCheck.ok) {
|
|
614
|
+
const first = finalCheck.errors[0];
|
|
615
|
+
throw new VibecodeError("CONTRACT_INVALID", `Merged contract failed validation: ${first ? `${first.path} ${first.message}` : "unknown error"}`, { details: finalCheck.errors });
|
|
616
|
+
}
|
|
617
|
+
return {
|
|
618
|
+
contract: mergedContract,
|
|
619
|
+
addedInvariants,
|
|
620
|
+
skippedInvariants,
|
|
621
|
+
renamedIds,
|
|
622
|
+
excludedHoldouts,
|
|
623
|
+
mergedDomains: [...mergedDomains]
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
function isFloorToleranceKey(key) {
|
|
627
|
+
return FLOOR_TOLERANCE_KEYS.has(key) || FLOOR_KEY_PATTERN.test(key);
|
|
628
|
+
}
|
|
629
|
+
function isCeilingToleranceKey(key) {
|
|
630
|
+
return CEILING_TOLERANCE_KEYS.has(key) || CEILING_KEY_PATTERN.test(key);
|
|
631
|
+
}
|
|
632
|
+
function normalizeAllowedCodeSet(value) {
|
|
633
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
634
|
+
return new Set([value]);
|
|
635
|
+
}
|
|
636
|
+
if (Array.isArray(value)) {
|
|
637
|
+
const nums = value.filter((n) => typeof n === "number" && Number.isFinite(n));
|
|
638
|
+
return nums.length > 0 ? new Set(nums) : null;
|
|
639
|
+
}
|
|
640
|
+
return null;
|
|
641
|
+
}
|
|
642
|
+
function isCodeSetWidened(beforeVal, afterVal) {
|
|
643
|
+
const beforeCodes = normalizeAllowedCodeSet(beforeVal);
|
|
644
|
+
if (!beforeCodes || beforeCodes.size === 0)
|
|
645
|
+
return false;
|
|
646
|
+
const afterCodes = normalizeAllowedCodeSet(afterVal);
|
|
647
|
+
if (!afterCodes || afterCodes.size === 0)
|
|
648
|
+
return true;
|
|
649
|
+
if (afterCodes.size <= beforeCodes.size)
|
|
650
|
+
return false;
|
|
651
|
+
for (const code of beforeCodes) {
|
|
652
|
+
if (!afterCodes.has(code))
|
|
653
|
+
return false;
|
|
654
|
+
}
|
|
655
|
+
return true;
|
|
656
|
+
}
|
|
657
|
+
function isPresentAssertion(value) {
|
|
658
|
+
return value !== undefined && value !== null;
|
|
659
|
+
}
|
|
660
|
+
function toCanonicalArray(value) {
|
|
661
|
+
if (!Array.isArray(value))
|
|
662
|
+
return [];
|
|
663
|
+
return value.map((item) => canonicalJson(item));
|
|
664
|
+
}
|
|
665
|
+
function isAssertionListShrunk(beforeArr, afterArr) {
|
|
666
|
+
if (beforeArr.length === 0)
|
|
667
|
+
return false;
|
|
668
|
+
if (afterArr.length === 0)
|
|
669
|
+
return true;
|
|
670
|
+
if (afterArr.length >= beforeArr.length)
|
|
671
|
+
return false;
|
|
672
|
+
const beforeSet = new Set(beforeArr);
|
|
673
|
+
return afterArr.every((item) => beforeSet.has(item));
|
|
674
|
+
}
|
|
675
|
+
function normalizeBodyContains(value) {
|
|
676
|
+
if (typeof value === "string")
|
|
677
|
+
return value.length > 0 ? [JSON.stringify(value)] : [];
|
|
678
|
+
if (Array.isArray(value)) {
|
|
679
|
+
return value
|
|
680
|
+
.filter((v) => typeof v === "string")
|
|
681
|
+
.map((v) => JSON.stringify(v));
|
|
682
|
+
}
|
|
683
|
+
return [];
|
|
684
|
+
}
|
|
685
|
+
function getDefaultToleranceValue(defaults, key) {
|
|
686
|
+
if (!defaults)
|
|
687
|
+
return undefined;
|
|
688
|
+
const rec = defaults;
|
|
689
|
+
if (!hasOwn(rec, key))
|
|
690
|
+
return undefined;
|
|
691
|
+
const val = rec[key];
|
|
692
|
+
return typeof val === "number" && Number.isFinite(val) ? val : undefined;
|
|
693
|
+
}
|
|
694
|
+
function isToleranceLoosened(beforeInv, afterInv, beforeDefaults, afterDefaults) {
|
|
695
|
+
const prevTol = isPlainObject(beforeInv.tolerance) ? beforeInv.tolerance : {};
|
|
696
|
+
const nextTol = isPlainObject(afterInv.tolerance) ? afterInv.tolerance : {};
|
|
697
|
+
for (const key of Object.keys(prevTol)) {
|
|
698
|
+
const prevVal = prevTol[key];
|
|
699
|
+
if (typeof prevVal !== "number" || !Number.isFinite(prevVal))
|
|
700
|
+
continue;
|
|
701
|
+
const hasNext = hasOwn(nextTol, key);
|
|
702
|
+
const nextVal = hasNext ? nextTol[key] : undefined;
|
|
703
|
+
if (isFloorToleranceKey(key)) {
|
|
704
|
+
if (typeof nextVal !== "number" || !Number.isFinite(nextVal)) {
|
|
705
|
+
const afterDef = getDefaultToleranceValue(afterDefaults, key);
|
|
706
|
+
if (afterDef === undefined || prevVal > afterDef)
|
|
707
|
+
return true;
|
|
708
|
+
}
|
|
709
|
+
else if (nextVal < prevVal) {
|
|
710
|
+
return true;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
else if (isCeilingToleranceKey(key)) {
|
|
714
|
+
if (typeof nextVal !== "number" || !Number.isFinite(nextVal)) {
|
|
715
|
+
const afterDef = getDefaultToleranceValue(afterDefaults, key);
|
|
716
|
+
if (afterDef === undefined || prevVal < afterDef)
|
|
717
|
+
return true;
|
|
718
|
+
}
|
|
719
|
+
else if (nextVal > prevVal) {
|
|
720
|
+
return true;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
else {
|
|
724
|
+
if (typeof nextVal !== "number" || !Number.isFinite(nextVal))
|
|
725
|
+
return true;
|
|
726
|
+
if (nextVal > prevVal)
|
|
727
|
+
return true;
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
// Check keys newly introduced in afterInv.tolerance that loosen contract defaults
|
|
731
|
+
for (const key of Object.keys(nextTol)) {
|
|
732
|
+
if (hasOwn(prevTol, key))
|
|
733
|
+
continue;
|
|
734
|
+
const nextVal = nextTol[key];
|
|
735
|
+
if (typeof nextVal !== "number" || !Number.isFinite(nextVal))
|
|
736
|
+
continue;
|
|
737
|
+
const beforeDef = getDefaultToleranceValue(beforeDefaults, key);
|
|
738
|
+
if (beforeDef === undefined)
|
|
739
|
+
continue;
|
|
740
|
+
if (isFloorToleranceKey(key) && nextVal < beforeDef)
|
|
741
|
+
return true;
|
|
742
|
+
if (isCeilingToleranceKey(key) && nextVal > beforeDef)
|
|
743
|
+
return true;
|
|
744
|
+
}
|
|
745
|
+
const prevExp = isPlainObject(beforeInv.expected) ? beforeInv.expected : {};
|
|
746
|
+
const nextExp = isPlainObject(afterInv.expected) ? afterInv.expected : {};
|
|
747
|
+
// Widening allowed exitCode or HTTP status (e.g. 0 -> [0, 1], [200] -> [200, 500]) or removing them
|
|
748
|
+
if (isCodeSetWidened(prevExp.exitCode, nextExp.exitCode))
|
|
749
|
+
return true;
|
|
750
|
+
if (isCodeSetWidened(prevExp.status, nextExp.status))
|
|
751
|
+
return true;
|
|
752
|
+
// Loosening or removing expected.maxLatencyMs
|
|
753
|
+
if (typeof prevExp.maxLatencyMs === "number" && Number.isFinite(prevExp.maxLatencyMs)) {
|
|
754
|
+
const nextLatency = hasOwn(nextExp, "maxLatencyMs") ? nextExp.maxLatencyMs : undefined;
|
|
755
|
+
if (typeof nextLatency !== "number" || !Number.isFinite(nextLatency) || nextLatency > prevExp.maxLatencyMs) {
|
|
756
|
+
return true;
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
// Loosening or removing expected.dimensions.aspectRatioTolerance
|
|
760
|
+
if (isPlainObject(prevExp.dimensions) && typeof prevExp.dimensions.aspectRatioTolerance === "number") {
|
|
761
|
+
const prevArt = prevExp.dimensions.aspectRatioTolerance;
|
|
762
|
+
if (Number.isFinite(prevArt)) {
|
|
763
|
+
const nextDim = isPlainObject(nextExp.dimensions) ? nextExp.dimensions : undefined;
|
|
764
|
+
const nextArt = nextDim && hasOwn(nextDim, "aspectRatioTolerance") ? nextDim.aspectRatioTolerance : undefined;
|
|
765
|
+
if (typeof nextArt !== "number" || !Number.isFinite(nextArt) || nextArt > prevArt) {
|
|
766
|
+
return true;
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
// Relaxing boolean strictness flags (true -> false/undefined)
|
|
771
|
+
for (const flag of BOOLEAN_STRICT_EXPECTED_FIELDS) {
|
|
772
|
+
if (prevExp[flag] === true && nextExp[flag] !== true) {
|
|
773
|
+
return true;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
// Removing scalar/object assertions entirely
|
|
777
|
+
for (const field of SCALAR_OR_OBJECT_EXPECTED_FIELDS) {
|
|
778
|
+
if (isPresentAssertion(prevExp[field]) && !isPresentAssertion(nextExp[field])) {
|
|
779
|
+
return true;
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
// Removing header assertions
|
|
783
|
+
if (isPlainObject(prevExp.headers)) {
|
|
784
|
+
const prevHeaderKeys = Object.keys(prevExp.headers);
|
|
785
|
+
if (prevHeaderKeys.length > 0) {
|
|
786
|
+
if (!isPlainObject(nextExp.headers))
|
|
787
|
+
return true;
|
|
788
|
+
const nextHeaderKeys = Object.keys(nextExp.headers);
|
|
789
|
+
if (nextHeaderKeys.length === 0 ||
|
|
790
|
+
(nextHeaderKeys.length < prevHeaderKeys.length &&
|
|
791
|
+
nextHeaderKeys.every((k) => hasOwn(prevExp.headers, k)))) {
|
|
792
|
+
return true;
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
// Shrinking or removing bodyContains assertions
|
|
797
|
+
if (isAssertionListShrunk(normalizeBodyContains(prevExp.bodyContains), normalizeBodyContains(nextExp.bodyContains))) {
|
|
798
|
+
return true;
|
|
799
|
+
}
|
|
800
|
+
// Shrinking or removing array assertion lists
|
|
801
|
+
for (const field of ARRAY_EXPECTED_FIELDS) {
|
|
802
|
+
if (isAssertionListShrunk(toCanonicalArray(prevExp[field]), toCanonicalArray(nextExp[field]))) {
|
|
803
|
+
return true;
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
return false;
|
|
807
|
+
}
|
|
808
|
+
function computeChangedInvariantFields(beforeInv, afterInv) {
|
|
809
|
+
const changed = [];
|
|
810
|
+
if (beforeInv.severity !== afterInv.severity)
|
|
811
|
+
changed.push("severity");
|
|
812
|
+
if ((beforeInv.description ?? "") !== (afterInv.description ?? ""))
|
|
813
|
+
changed.push("description");
|
|
814
|
+
if (canonicalJson(beforeInv.input ?? {}) !== canonicalJson(afterInv.input ?? {}))
|
|
815
|
+
changed.push("input");
|
|
816
|
+
if (canonicalJson(beforeInv.expected ?? {}) !== canonicalJson(afterInv.expected ?? {}))
|
|
817
|
+
changed.push("expected");
|
|
818
|
+
if (canonicalJson(beforeInv.tolerance ?? {}) !== canonicalJson(afterInv.tolerance ?? {}))
|
|
819
|
+
changed.push("tolerance");
|
|
820
|
+
if (beforeInv.domain !== afterInv.domain)
|
|
821
|
+
changed.push("domain");
|
|
822
|
+
if (beforeInv.type !== afterInv.type)
|
|
823
|
+
changed.push("type");
|
|
824
|
+
if (canonicalJson(beforeInv.tags ?? []) !== canonicalJson(afterInv.tags ?? []))
|
|
825
|
+
changed.push("tags");
|
|
826
|
+
if (Boolean(beforeInv.holdout) !== Boolean(afterInv.holdout))
|
|
827
|
+
changed.push("holdout");
|
|
828
|
+
if ((beforeInv.sourceId ?? undefined) !== (afterInv.sourceId ?? undefined))
|
|
829
|
+
changed.push("sourceId");
|
|
830
|
+
if ((beforeInv.holdoutHint ?? undefined) !== (afterInv.holdoutHint ?? undefined))
|
|
831
|
+
changed.push("holdoutHint");
|
|
832
|
+
return changed;
|
|
833
|
+
}
|
|
834
|
+
function extractValidDomains(contract) {
|
|
835
|
+
const seen = new Set();
|
|
836
|
+
const rawDomains = Array.isArray(contract.target?.domains) ? contract.target.domains : [];
|
|
837
|
+
for (const d of rawDomains) {
|
|
838
|
+
if (typeof d === "string" && VALID_DOMAINS.has(d)) {
|
|
839
|
+
seen.add(d);
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
return Array.from(seen);
|
|
843
|
+
}
|
|
844
|
+
function indexInvariants(contract) {
|
|
845
|
+
const map = new Map();
|
|
846
|
+
if (!Array.isArray(contract.invariants))
|
|
847
|
+
return map;
|
|
848
|
+
for (const inv of contract.invariants) {
|
|
849
|
+
if (!isPlainObject(inv))
|
|
850
|
+
continue;
|
|
851
|
+
if (typeof inv.id !== "string" || inv.id.length === 0)
|
|
852
|
+
continue;
|
|
853
|
+
map.set(inv.id, inv);
|
|
854
|
+
}
|
|
855
|
+
return map;
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Structurally diff two `ContractV02` snapshots for contract drift and anti-tamper auditing.
|
|
859
|
+
*
|
|
860
|
+
* Flags breaking changes whenever invariants or domains are removed, a `hard` invariant is
|
|
861
|
+
* downgraded to `soft`, or tolerances/expectations are loosened.
|
|
862
|
+
*/
|
|
863
|
+
export function diffContracts(before, after) {
|
|
864
|
+
if (!isPlainObject(before) || !isPlainObject(after)) {
|
|
865
|
+
throw new VibecodeError("CONTRACT_INVALID", "diffContracts requires valid before and after contract objects");
|
|
866
|
+
}
|
|
867
|
+
const beforeDomains = extractValidDomains(before);
|
|
868
|
+
const afterDomains = extractValidDomains(after);
|
|
869
|
+
const beforeDomainSet = new Set(beforeDomains);
|
|
870
|
+
const afterDomainSet = new Set(afterDomains);
|
|
871
|
+
const domainsAdded = afterDomains.filter((d) => !beforeDomainSet.has(d));
|
|
872
|
+
const domainsRemoved = beforeDomains.filter((d) => !afterDomainSet.has(d));
|
|
873
|
+
const beforeMap = indexInvariants(before);
|
|
874
|
+
const afterMap = indexInvariants(after);
|
|
875
|
+
const removedInvariants = [];
|
|
876
|
+
const addedInvariants = [];
|
|
877
|
+
const modifiedInvariants = [];
|
|
878
|
+
const severityDowngrades = [];
|
|
879
|
+
const toleranceLoosened = [];
|
|
880
|
+
const beforeDefaults = isPlainObject(before.thresholds?.defaults)
|
|
881
|
+
? normalizeThresholdDefaults(before.thresholds.defaults)
|
|
882
|
+
: undefined;
|
|
883
|
+
const afterDefaults = isPlainObject(after.thresholds?.defaults)
|
|
884
|
+
? normalizeThresholdDefaults(after.thresholds.defaults)
|
|
885
|
+
: undefined;
|
|
886
|
+
for (const [id, prevInv] of beforeMap.entries()) {
|
|
887
|
+
const nextInv = afterMap.get(id);
|
|
888
|
+
if (!nextInv) {
|
|
889
|
+
removedInvariants.push(id);
|
|
890
|
+
continue;
|
|
891
|
+
}
|
|
892
|
+
const changedFields = computeChangedInvariantFields(prevInv, nextInv);
|
|
893
|
+
const severityBefore = String(prevInv.severity ?? "");
|
|
894
|
+
const severityAfter = String(nextInv.severity ?? "");
|
|
895
|
+
const severityDowngraded = severityBefore === "hard" && severityAfter === "soft";
|
|
896
|
+
const loosened = isToleranceLoosened(prevInv, nextInv, beforeDefaults, afterDefaults);
|
|
897
|
+
if (changedFields.length > 0 || severityDowngraded || loosened) {
|
|
898
|
+
modifiedInvariants.push({
|
|
899
|
+
id,
|
|
900
|
+
severityBefore,
|
|
901
|
+
severityAfter,
|
|
902
|
+
severityDowngraded,
|
|
903
|
+
toleranceLoosened: loosened,
|
|
904
|
+
changedFields
|
|
905
|
+
});
|
|
906
|
+
if (severityDowngraded)
|
|
907
|
+
severityDowngrades.push(id);
|
|
908
|
+
if (loosened)
|
|
909
|
+
toleranceLoosened.push(id);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
for (const id of afterMap.keys()) {
|
|
913
|
+
if (!beforeMap.has(id)) {
|
|
914
|
+
addedInvariants.push(id);
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
const breaking = removedInvariants.length > 0 ||
|
|
918
|
+
severityDowngrades.length > 0 ||
|
|
919
|
+
toleranceLoosened.length > 0 ||
|
|
920
|
+
domainsRemoved.length > 0;
|
|
921
|
+
const changed = domainsAdded.length > 0 ||
|
|
922
|
+
domainsRemoved.length > 0 ||
|
|
923
|
+
addedInvariants.length > 0 ||
|
|
924
|
+
removedInvariants.length > 0 ||
|
|
925
|
+
modifiedInvariants.length > 0;
|
|
926
|
+
let summary;
|
|
927
|
+
if (!changed) {
|
|
928
|
+
summary = "No contract changes detected";
|
|
929
|
+
}
|
|
930
|
+
else {
|
|
931
|
+
const parts = [];
|
|
932
|
+
if (domainsAdded.length > 0)
|
|
933
|
+
parts.push(`+${domainsAdded.length} domain(s)`);
|
|
934
|
+
if (domainsRemoved.length > 0)
|
|
935
|
+
parts.push(`-${domainsRemoved.length} domain(s)`);
|
|
936
|
+
if (addedInvariants.length > 0)
|
|
937
|
+
parts.push(`+${addedInvariants.length} added`);
|
|
938
|
+
if (removedInvariants.length > 0)
|
|
939
|
+
parts.push(`-${removedInvariants.length} removed`);
|
|
940
|
+
if (modifiedInvariants.length > 0)
|
|
941
|
+
parts.push(`${modifiedInvariants.length} modified`);
|
|
942
|
+
if (severityDowngrades.length > 0)
|
|
943
|
+
parts.push(`${severityDowngrades.length} severity downgrade(s)`);
|
|
944
|
+
if (toleranceLoosened.length > 0)
|
|
945
|
+
parts.push(`${toleranceLoosened.length} tolerance loosened`);
|
|
946
|
+
const header = breaking ? "Breaking contract drift detected" : "Contract updated (non-breaking)";
|
|
947
|
+
summary = sanitizeLine(`${header}: ${parts.join(", ")}`);
|
|
948
|
+
}
|
|
949
|
+
return {
|
|
950
|
+
changed,
|
|
951
|
+
breaking,
|
|
952
|
+
domainsAdded,
|
|
953
|
+
domainsRemoved,
|
|
954
|
+
addedInvariants,
|
|
955
|
+
removedInvariants,
|
|
956
|
+
modifiedInvariants,
|
|
957
|
+
severityDowngrades,
|
|
958
|
+
toleranceLoosened,
|
|
959
|
+
summary
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
function formatIdListPretty(items) {
|
|
963
|
+
const shown = items.slice(0, MAX_LISTED_ITEMS).map(sanitizeLine);
|
|
964
|
+
const extra = items.length > MAX_LISTED_ITEMS ? ` (+${items.length - MAX_LISTED_ITEMS} more)` : "";
|
|
965
|
+
return `${shown.join(", ")}${extra}`;
|
|
966
|
+
}
|
|
967
|
+
/**
|
|
968
|
+
* Format a `ContractDiffResult` for terminal display.
|
|
969
|
+
* Emits zero ANSI escape codes unless `options.color === true`.
|
|
970
|
+
*/
|
|
971
|
+
export function formatPrettyContractDiff(diff, options = {}) {
|
|
972
|
+
const useColor = options.color === true;
|
|
973
|
+
const lines = [];
|
|
974
|
+
const badgeText = diff.breaking ? "BREAKING" : diff.changed ? "CHANGED" : "UNCHANGED";
|
|
975
|
+
const badgeColor = diff.breaking
|
|
976
|
+
? `${ANSI.bold}${ANSI.red}`
|
|
977
|
+
: diff.changed
|
|
978
|
+
? `${ANSI.bold}${ANSI.cyan}`
|
|
979
|
+
: `${ANSI.bold}${ANSI.green}`;
|
|
980
|
+
lines.push(`${style(`[${badgeText}]`, badgeColor, useColor)} Contract Structural Diff`);
|
|
981
|
+
lines.push(`Summary: ${sanitizeLine(diff.summary)}`);
|
|
982
|
+
if (diff.domainsAdded.length > 0) {
|
|
983
|
+
lines.push(`Domains Added: ${formatIdListPretty(diff.domainsAdded)}`);
|
|
984
|
+
}
|
|
985
|
+
if (diff.domainsRemoved.length > 0) {
|
|
986
|
+
lines.push(`${style("Domains Removed:", ANSI.red, useColor)} ${formatIdListPretty(diff.domainsRemoved)}`);
|
|
987
|
+
}
|
|
988
|
+
lines.push(`Invariants: +${diff.addedInvariants.length} added, -${diff.removedInvariants.length} removed, ${diff.modifiedInvariants.length} modified`);
|
|
989
|
+
if (diff.severityDowngrades.length > 0) {
|
|
990
|
+
lines.push(`${style(`Severity Downgrades (${diff.severityDowngrades.length}):`, `${ANSI.bold}${ANSI.red}`, useColor)} ${formatIdListPretty(diff.severityDowngrades)}`);
|
|
991
|
+
}
|
|
992
|
+
if (diff.toleranceLoosened.length > 0) {
|
|
993
|
+
lines.push(`${style(`Tolerance Loosened (${diff.toleranceLoosened.length}):`, `${ANSI.bold}${ANSI.red}`, useColor)} ${formatIdListPretty(diff.toleranceLoosened)}`);
|
|
994
|
+
}
|
|
995
|
+
if (diff.removedInvariants.length > 0) {
|
|
996
|
+
lines.push(`${style(`Removed Invariants (${diff.removedInvariants.length}):`, `${ANSI.bold}${ANSI.red}`, useColor)} ${formatIdListPretty(diff.removedInvariants)}`);
|
|
997
|
+
}
|
|
998
|
+
if (diff.modifiedInvariants.length > 0) {
|
|
999
|
+
lines.push(`${style(`Modified Invariants (${diff.modifiedInvariants.length}):`, ANSI.bold, useColor)}`);
|
|
1000
|
+
const shown = diff.modifiedInvariants.slice(0, MAX_LISTED_ITEMS);
|
|
1001
|
+
for (const mod of shown) {
|
|
1002
|
+
const id = sanitizeLine(mod.id);
|
|
1003
|
+
const flags = [];
|
|
1004
|
+
if (mod.severityDowngraded) {
|
|
1005
|
+
flags.push(style(`DOWNGRADE ${sanitizeLine(mod.severityBefore)}->${sanitizeLine(mod.severityAfter)}`, `${ANSI.bold}${ANSI.red}`, useColor));
|
|
1006
|
+
}
|
|
1007
|
+
if (mod.toleranceLoosened) {
|
|
1008
|
+
flags.push(style("LOOSENED", `${ANSI.bold}${ANSI.red}`, useColor));
|
|
1009
|
+
}
|
|
1010
|
+
const fields = mod.changedFields.map(sanitizeLine).join(", ");
|
|
1011
|
+
const flagSuffix = flags.length > 0 ? ` [${flags.join(", ")}]` : "";
|
|
1012
|
+
lines.push(` - ${id}: ${fields || "modified"}${flagSuffix}`);
|
|
1013
|
+
}
|
|
1014
|
+
if (diff.modifiedInvariants.length > MAX_LISTED_ITEMS) {
|
|
1015
|
+
lines.push(` ${style(`... and ${diff.modifiedInvariants.length - MAX_LISTED_ITEMS} more`, ANSI.dim, useColor)}`);
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
if (diff.addedInvariants.length > 0) {
|
|
1019
|
+
lines.push(`Added Invariants (${diff.addedInvariants.length}): ${formatIdListPretty(diff.addedInvariants)}`);
|
|
1020
|
+
}
|
|
1021
|
+
return lines.join("\n");
|
|
1022
|
+
}
|
|
1023
|
+
function renderMarkdownIdList(heading, items) {
|
|
1024
|
+
if (items.length === 0)
|
|
1025
|
+
return [];
|
|
1026
|
+
const shown = items.slice(0, MAX_LISTED_ITEMS).map(formatCodeSpan);
|
|
1027
|
+
const overflow = items.length > MAX_LISTED_ITEMS ? ` _(+${items.length - MAX_LISTED_ITEMS} more)_` : "";
|
|
1028
|
+
return [`**${heading} (${items.length}):** ${shown.join(", ")}${overflow}`, ""];
|
|
1029
|
+
}
|
|
1030
|
+
/**
|
|
1031
|
+
* Render a self-contained, injection-safe PR/CI Markdown summary for a `ContractDiffResult`.
|
|
1032
|
+
*/
|
|
1033
|
+
export function renderContractDiffMarkdown(diff) {
|
|
1034
|
+
const lines = [];
|
|
1035
|
+
const statusBadge = diff.breaking
|
|
1036
|
+
? "❌ **BREAKING DRIFT**"
|
|
1037
|
+
: diff.changed
|
|
1038
|
+
? "🔄 **NON-BREAKING CHANGES**"
|
|
1039
|
+
: "✅ **UNCHANGED**";
|
|
1040
|
+
lines.push("### Vibecode Contract Structural Diff");
|
|
1041
|
+
lines.push("");
|
|
1042
|
+
lines.push(`**Status:** ${statusBadge}`);
|
|
1043
|
+
lines.push("");
|
|
1044
|
+
lines.push(escapeMarkdownInline(diff.summary));
|
|
1045
|
+
lines.push("");
|
|
1046
|
+
lines.push("| Category | Count |");
|
|
1047
|
+
lines.push("| --- | --- |");
|
|
1048
|
+
lines.push(`| Domains Added | ${diff.domainsAdded.length} |`);
|
|
1049
|
+
lines.push(`| Domains Removed | ${diff.domainsRemoved.length} |`);
|
|
1050
|
+
lines.push(`| Added Invariants | ${diff.addedInvariants.length} |`);
|
|
1051
|
+
lines.push(`| Removed Invariants | ${diff.removedInvariants.length} |`);
|
|
1052
|
+
lines.push(`| Modified Invariants | ${diff.modifiedInvariants.length} |`);
|
|
1053
|
+
lines.push(`| Severity Downgrades | ${diff.severityDowngrades.length} |`);
|
|
1054
|
+
lines.push(`| Tolerance Loosened | ${diff.toleranceLoosened.length} |`);
|
|
1055
|
+
lines.push("");
|
|
1056
|
+
lines.push(...renderMarkdownIdList("Domains Added", diff.domainsAdded));
|
|
1057
|
+
lines.push(...renderMarkdownIdList("Domains Removed", diff.domainsRemoved));
|
|
1058
|
+
lines.push(...renderMarkdownIdList("Severity Downgrades", diff.severityDowngrades));
|
|
1059
|
+
lines.push(...renderMarkdownIdList("Tolerance Loosened", diff.toleranceLoosened));
|
|
1060
|
+
lines.push(...renderMarkdownIdList("Removed Invariants", diff.removedInvariants));
|
|
1061
|
+
if (diff.modifiedInvariants.length > 0) {
|
|
1062
|
+
lines.push(`#### Modified Invariants (${diff.modifiedInvariants.length})`);
|
|
1063
|
+
lines.push("");
|
|
1064
|
+
const shown = diff.modifiedInvariants.slice(0, MAX_LISTED_ITEMS);
|
|
1065
|
+
for (const mod of shown) {
|
|
1066
|
+
const idSpan = formatCodeSpan(mod.id);
|
|
1067
|
+
const sevBefore = escapeMarkdownInline(mod.severityBefore);
|
|
1068
|
+
const sevAfter = escapeMarkdownInline(mod.severityAfter);
|
|
1069
|
+
const fieldSpans = mod.changedFields.length > 0
|
|
1070
|
+
? mod.changedFields.map(formatCodeSpan).join(", ")
|
|
1071
|
+
: escapeMarkdownInline("modified");
|
|
1072
|
+
const flags = [];
|
|
1073
|
+
if (mod.severityDowngraded)
|
|
1074
|
+
flags.push(`⚠️ severity downgrade (${sevBefore} -> ${sevAfter})`);
|
|
1075
|
+
if (mod.toleranceLoosened)
|
|
1076
|
+
flags.push("⚠️ tolerance loosened");
|
|
1077
|
+
const flagText = flags.length > 0 ? ` — ${flags.join("; ")}` : "";
|
|
1078
|
+
lines.push(`- ${idSpan}: changed ${fieldSpans}${flagText}`);
|
|
1079
|
+
}
|
|
1080
|
+
if (diff.modifiedInvariants.length > MAX_LISTED_ITEMS) {
|
|
1081
|
+
lines.push("");
|
|
1082
|
+
lines.push(`_... and ${diff.modifiedInvariants.length - MAX_LISTED_ITEMS} more._`);
|
|
1083
|
+
}
|
|
1084
|
+
lines.push("");
|
|
1085
|
+
}
|
|
1086
|
+
lines.push(...renderMarkdownIdList("Added Invariants", diff.addedInvariants));
|
|
1087
|
+
return lines.join("\n").trimEnd() + "\n";
|
|
1088
|
+
}
|