vibecode-anything 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +407 -2
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +2519 -0
  5. package/dist/core/adapters.d.ts +31 -0
  6. package/dist/core/adapters.js +478 -0
  7. package/dist/core/agent-adapter.d.ts +67 -0
  8. package/dist/core/agent-adapter.js +312 -0
  9. package/dist/core/anti-cheat.d.ts +6 -0
  10. package/dist/core/anti-cheat.js +372 -0
  11. package/dist/core/badge.d.ts +18 -0
  12. package/dist/core/badge.js +360 -0
  13. package/dist/core/cache.d.ts +47 -0
  14. package/dist/core/cache.js +403 -0
  15. package/dist/core/ci-export.d.ts +35 -0
  16. package/dist/core/ci-export.js +796 -0
  17. package/dist/core/ci-formats.d.ts +21 -0
  18. package/dist/core/ci-formats.js +388 -0
  19. package/dist/core/client-codegen.d.ts +36 -0
  20. package/dist/core/client-codegen.js +2538 -0
  21. package/dist/core/compose.d.ts +71 -0
  22. package/dist/core/compose.js +1088 -0
  23. package/dist/core/diff.d.ts +10 -0
  24. package/dist/core/diff.js +207 -0
  25. package/dist/core/docs-export.d.ts +37 -0
  26. package/dist/core/docs-export.js +2706 -0
  27. package/dist/core/doctor.d.ts +70 -0
  28. package/dist/core/doctor.js +525 -0
  29. package/dist/core/errors.d.ts +32 -0
  30. package/dist/core/errors.js +81 -0
  31. package/dist/core/exec.d.ts +38 -0
  32. package/dist/core/exec.js +336 -0
  33. package/dist/core/fixtures.d.ts +153 -0
  34. package/dist/core/fixtures.js +2245 -0
  35. package/dist/core/format.d.ts +77 -0
  36. package/dist/core/format.js +632 -0
  37. package/dist/core/fs-snapshot.d.ts +37 -0
  38. package/dist/core/fs-snapshot.js +216 -0
  39. package/dist/core/graphql-export.d.ts +34 -0
  40. package/dist/core/graphql-export.js +2482 -0
  41. package/dist/core/har-export.d.ts +29 -0
  42. package/dist/core/har-export.js +988 -0
  43. package/dist/core/html-report.d.ts +27 -0
  44. package/dist/core/html-report.js +1535 -0
  45. package/dist/core/http-export.d.ts +31 -0
  46. package/dist/core/http-export.js +726 -0
  47. package/dist/core/impact.d.ts +80 -0
  48. package/dist/core/impact.js +1412 -0
  49. package/dist/core/lint.d.ts +38 -0
  50. package/dist/core/lint.js +1111 -0
  51. package/dist/core/load-export.d.ts +37 -0
  52. package/dist/core/load-export.js +1813 -0
  53. package/dist/core/mcp-export.d.ts +35 -0
  54. package/dist/core/mcp-export.js +1736 -0
  55. package/dist/core/mock-server.d.ts +47 -0
  56. package/dist/core/mock-server.js +1722 -0
  57. package/dist/core/openapi-export.d.ts +44 -0
  58. package/dist/core/openapi-export.js +1074 -0
  59. package/dist/core/parity.d.ts +14 -0
  60. package/dist/core/parity.js +173 -0
  61. package/dist/core/playwright-exporter.d.ts +23 -0
  62. package/dist/core/playwright-exporter.js +1343 -0
  63. package/dist/core/png.d.ts +7 -0
  64. package/dist/core/png.js +339 -0
  65. package/dist/core/regression.d.ts +54 -0
  66. package/dist/core/regression.js +529 -0
  67. package/dist/core/responsive.d.ts +86 -0
  68. package/dist/core/responsive.js +606 -0
  69. package/dist/core/run.d.ts +74 -0
  70. package/dist/core/run.js +696 -0
  71. package/dist/core/scheduler.d.ts +24 -0
  72. package/dist/core/scheduler.js +162 -0
  73. package/dist/core/schema-export.d.ts +29 -0
  74. package/dist/core/schema-export.js +2215 -0
  75. package/dist/core/schema.d.ts +18 -0
  76. package/dist/core/schema.js +1057 -0
  77. package/dist/core/security.d.ts +233 -0
  78. package/dist/core/security.js +1839 -0
  79. package/dist/core/server-export.d.ts +38 -0
  80. package/dist/core/server-export.js +3198 -0
  81. package/dist/core/slices.d.ts +24 -0
  82. package/dist/core/slices.js +294 -0
  83. package/dist/core/spec-writer.d.ts +9 -0
  84. package/dist/core/spec-writer.js +1202 -0
  85. package/dist/core/store.d.ts +26 -0
  86. package/dist/core/store.js +217 -0
  87. package/dist/core/target-map.d.ts +34 -0
  88. package/dist/core/target-map.js +262 -0
  89. package/dist/core/test-exporter.d.ts +25 -0
  90. package/dist/core/test-exporter.js +1918 -0
  91. package/dist/core/types.d.ts +919 -0
  92. package/dist/core/types.js +4 -0
  93. package/dist/core/visual-semantic.d.ts +67 -0
  94. package/dist/core/visual-semantic.js +673 -0
  95. package/dist/core/visual.d.ts +34 -0
  96. package/dist/core/visual.js +508 -0
  97. package/dist/core/watch.d.ts +78 -0
  98. package/dist/core/watch.js +495 -0
  99. package/dist/core/yaml.d.ts +5 -0
  100. package/dist/core/yaml.js +1009 -0
  101. package/dist/diagnostics/diagnose.d.ts +53 -0
  102. package/dist/diagnostics/diagnose.js +1083 -0
  103. package/dist/diagnostics/flake.d.ts +71 -0
  104. package/dist/diagnostics/flake.js +608 -0
  105. package/dist/diagnostics/mutation-audit.d.ts +69 -0
  106. package/dist/diagnostics/mutation-audit.js +769 -0
  107. package/dist/diagnostics/spatial.d.ts +42 -0
  108. package/dist/diagnostics/spatial.js +346 -0
  109. package/dist/diagnostics/trends.d.ts +122 -0
  110. package/dist/diagnostics/trends.js +1190 -0
  111. package/dist/discovery/discover.d.ts +111 -0
  112. package/dist/discovery/discover.js +2017 -0
  113. package/dist/discovery/lock.d.ts +116 -0
  114. package/dist/discovery/lock.js +1505 -0
  115. package/dist/discovery/routes.d.ts +36 -0
  116. package/dist/discovery/routes.js +1494 -0
  117. package/dist/discovery/test-importer.d.ts +92 -0
  118. package/dist/discovery/test-importer.js +4952 -0
  119. package/dist/index.d.ts +123 -0
  120. package/dist/index.js +99 -0
  121. package/dist/ingestors/api-collections.d.ts +28 -0
  122. package/dist/ingestors/api-collections.js +2335 -0
  123. package/dist/ingestors/api-repo.d.ts +6 -0
  124. package/dist/ingestors/api-repo.js +1120 -0
  125. package/dist/ingestors/asyncapi.d.ts +26 -0
  126. package/dist/ingestors/asyncapi.js +2105 -0
  127. package/dist/ingestors/bridges.d.ts +5 -0
  128. package/dist/ingestors/bridges.js +1264 -0
  129. package/dist/ingestors/cli.d.ts +10 -0
  130. package/dist/ingestors/cli.js +454 -0
  131. package/dist/ingestors/curl.d.ts +14 -0
  132. package/dist/ingestors/curl.js +1024 -0
  133. package/dist/ingestors/graphql.d.ts +56 -0
  134. package/dist/ingestors/graphql.js +1852 -0
  135. package/dist/ingestors/http-file.d.ts +20 -0
  136. package/dist/ingestors/http-file.js +923 -0
  137. package/dist/ingestors/image.d.ts +2 -0
  138. package/dist/ingestors/image.js +147 -0
  139. package/dist/ingestors/index.d.ts +5 -0
  140. package/dist/ingestors/index.js +577 -0
  141. package/dist/ingestors/openrpc.d.ts +29 -0
  142. package/dist/ingestors/openrpc.js +1807 -0
  143. package/dist/ingestors/proto.d.ts +47 -0
  144. package/dist/ingestors/proto.js +2690 -0
  145. package/dist/ingestors/trace.d.ts +10 -0
  146. package/dist/ingestors/trace.js +599 -0
  147. package/dist/ingestors/video.d.ts +50 -0
  148. package/dist/ingestors/video.js +655 -0
  149. package/dist/ingestors/web.d.ts +40 -0
  150. package/dist/ingestors/web.js +839 -0
  151. package/dist/mcp/server.d.ts +2 -0
  152. package/dist/mcp/server.js +3969 -0
  153. package/dist/oracles/api-repo.d.ts +2 -0
  154. package/dist/oracles/api-repo.js +286 -0
  155. package/dist/oracles/cli.d.ts +2 -0
  156. package/dist/oracles/cli.js +205 -0
  157. package/dist/oracles/http-workflow.d.ts +68 -0
  158. package/dist/oracles/http-workflow.js +828 -0
  159. package/dist/oracles/image.d.ts +2 -0
  160. package/dist/oracles/image.js +429 -0
  161. package/dist/oracles/index.d.ts +6 -0
  162. package/dist/oracles/index.js +320 -0
  163. package/dist/oracles/perf-budget.d.ts +90 -0
  164. package/dist/oracles/perf-budget.js +1329 -0
  165. package/dist/oracles/stream.d.ts +94 -0
  166. package/dist/oracles/stream.js +1268 -0
  167. package/dist/oracles/ui-states.d.ts +49 -0
  168. package/dist/oracles/ui-states.js +894 -0
  169. package/dist/oracles/video.d.ts +21 -0
  170. package/dist/oracles/video.js +627 -0
  171. package/dist/oracles/web.d.ts +2 -0
  172. package/dist/oracles/web.js +871 -0
  173. package/dist/plugins/builtins.d.ts +12 -0
  174. package/dist/plugins/builtins.js +1052 -0
  175. package/dist/plugins/registry.d.ts +86 -0
  176. package/dist/plugins/registry.js +554 -0
  177. package/dist/setup/index.d.ts +7 -0
  178. package/dist/setup/index.js +298 -0
  179. package/package.json +54 -4
  180. package/skills/vibecode-anything/SKILL.md +75 -0
@@ -0,0 +1,1057 @@
1
+ import { VibecodeError } from "./errors.js";
2
+ import { validateContractFixtures } from "./fixtures.js";
3
+ import { VALID_DOMAINS, isForbiddenObjectKey } from "./security.js";
4
+ export const SCHEMA_VERSION = "0.2.0";
5
+ export const VALID_SLICE_STATUSES = new Set(["pending", "in_progress", "passed", "failed", "skipped"]);
6
+ const VALID_SEVERITIES = new Set(["hard", "soft"]);
7
+ const VALID_FS_EFFECT_STATUSES = new Set(["created", "modified", "deleted"]);
8
+ const VALID_STREAM_FORMATS = new Set(["sse", "ndjson", "auto"]);
9
+ const VALID_WS_STEP_ACTIONS = new Set(["send", "expect", "close"]);
10
+ const VALID_UI_STATE_CHECK_KINDS = new Set(["hover", "focus", "keyboard_tab", "disabled", "empty_state", "error_state", "storage"]);
11
+ const VALID_TYPES = new Set([
12
+ "command",
13
+ "web_route",
14
+ "web_flow",
15
+ "web_network",
16
+ "web_ui_states",
17
+ "image_layout",
18
+ "image_perceptual",
19
+ "video_timeline",
20
+ "http",
21
+ "http_workflow",
22
+ "http_stream",
23
+ "ws_protocol",
24
+ "perf_budget",
25
+ "repo_exports"
26
+ ]);
27
+ const VALID_PERF_BUDGET_KINDS = new Set(["http", "command"]);
28
+ const PERF_BUDGET_NONNEG_KEYS = [
29
+ "maxP50Ms",
30
+ "maxP95Ms",
31
+ "maxP99Ms",
32
+ "maxMeanMs",
33
+ "maxDurationMs",
34
+ "maxBytes",
35
+ "minBytes"
36
+ ];
37
+ const PLUGIN_INVARIANT_TYPE_RE = /^plugin_[a-z][a-z0-9_-]{0,47}$/;
38
+ function isValidInvariantType(type) {
39
+ return typeof type === "string" && (VALID_TYPES.has(type) || PLUGIN_INVARIANT_TYPE_RE.test(type));
40
+ }
41
+ function isObject(v) {
42
+ return v !== null && typeof v === "object" && !Array.isArray(v);
43
+ }
44
+ function clone(v) {
45
+ return JSON.parse(JSON.stringify(v));
46
+ }
47
+ function defaultThresholds(d = {}) {
48
+ return {
49
+ minSSIM: typeof d.minSSIM === "number" ? d.minSSIM : 0.85,
50
+ maxPixelDiffRatio: typeof d.maxPixelDiffRatio === "number" ? d.maxPixelDiffRatio : 0.1,
51
+ colorDelta: typeof d.colorDelta === "number" ? d.colorDelta : 0.1,
52
+ minLayoutIoU: typeof d.minLayoutIoU === "number" ? d.minLayoutIoU : 0.75,
53
+ minPaletteSimilarity: typeof d.minPaletteSimilarity === "number" ? d.minPaletteSimilarity : 0.8,
54
+ stateMatchFloor: typeof d.stateMatchFloor === "number" ? d.stateMatchFloor : 0.7,
55
+ minMotionRegionIoU: typeof d.minMotionRegionIoU === "number" ? d.minMotionRegionIoU : 0.55
56
+ };
57
+ }
58
+ function normalizeSlices(rawSlices) {
59
+ return rawSlices.map((entry) => {
60
+ const s = isObject(entry) ? entry : {};
61
+ const slice = {
62
+ id: typeof s.id === "string" ? s.id : "",
63
+ title: typeof s.title === "string" ? s.title : "",
64
+ invariantIds: Array.isArray(s.invariantIds) ? s.invariantIds.map(String) : [],
65
+ status: typeof s.status === "string" && VALID_SLICE_STATUSES.has(s.status)
66
+ ? s.status
67
+ : "pending"
68
+ };
69
+ if (typeof s.description === "string")
70
+ slice.description = s.description;
71
+ if (Array.isArray(s.dependsOn))
72
+ slice.dependsOn = s.dependsOn.map(String);
73
+ if (typeof s.lastVerifiedAt === "string")
74
+ slice.lastVerifiedAt = s.lastVerifiedAt;
75
+ if (typeof s.lastScore === "number" && Number.isFinite(s.lastScore))
76
+ slice.lastScore = s.lastScore;
77
+ if (typeof s.notes === "string")
78
+ slice.notes = s.notes;
79
+ return slice;
80
+ });
81
+ }
82
+ function normalizeV01(raw) {
83
+ const rawTarget = isObject(raw.target) ? raw.target : {};
84
+ const rawDomain = typeof rawTarget.domain === "string" && rawTarget.domain ? rawTarget.domain : "cli";
85
+ const rawThresholds = isObject(raw.thresholds) ? raw.thresholds : {};
86
+ const contract = {
87
+ schemaVersion: SCHEMA_VERSION,
88
+ createdAt: new Date().toISOString(),
89
+ generator: {
90
+ name: "vibecode-anything",
91
+ version: "0.1.0-migrated",
92
+ adapter: "manual"
93
+ },
94
+ target: {
95
+ name: typeof rawTarget.name === "string" && rawTarget.name ? rawTarget.name : "unknown",
96
+ domains: [rawDomain],
97
+ sources: [
98
+ {
99
+ id: "src-1",
100
+ kind: rawDomain,
101
+ ref: typeof rawTarget.source === "string" && rawTarget.source ? rawTarget.source : "unknown",
102
+ meta: {}
103
+ }
104
+ ]
105
+ },
106
+ artifacts: { root: ".vibecode/artifacts", files: {} },
107
+ thresholds: {
108
+ hardBehavioralParity: 1.0,
109
+ softPerceptualParity: 0.85,
110
+ softGateMode: "warn",
111
+ defaults: defaultThresholds()
112
+ },
113
+ invariants: [],
114
+ ...(Array.isArray(raw.slices) ? { slices: normalizeSlices(raw.slices) } : {}),
115
+ ...(raw.fixtures !== undefined ? { fixtures: clone(raw.fixtures) } : {})
116
+ };
117
+ // v0.1 thresholds.behavioralParity maps to hardBehavioralParity
118
+ if (typeof rawThresholds.behavioralParity === "number") {
119
+ contract.thresholds.hardBehavioralParity = rawThresholds.behavioralParity;
120
+ }
121
+ if (typeof rawThresholds.visualSimilarity === "number") {
122
+ contract.thresholds.softPerceptualParity = rawThresholds.visualSimilarity;
123
+ }
124
+ const invs = Array.isArray(raw.invariants) ? raw.invariants : [];
125
+ contract.invariants = invs.map((item, i) => {
126
+ const inv = isObject(item) ? item : {};
127
+ const domain = (typeof inv.domain === "string" && inv.domain ? inv.domain : rawDomain);
128
+ const type = (typeof inv.type === "string" && inv.type
129
+ ? inv.type
130
+ : domain === "cli"
131
+ ? "command"
132
+ : domain === "api"
133
+ ? "http"
134
+ : "command");
135
+ const v2 = {
136
+ id: typeof inv.id === "string" && inv.id ? inv.id : `inv-${i + 1}`,
137
+ domain,
138
+ type,
139
+ severity: (typeof inv.severity === "string" && inv.severity ? inv.severity : "hard"),
140
+ description: typeof inv.description === "string" ? inv.description : "",
141
+ tags: Array.isArray(inv.tags) ? inv.tags.map(String) : [],
142
+ sourceId: typeof inv.sourceId === "string" && inv.sourceId ? inv.sourceId : "src-1",
143
+ ...(inv.holdout !== undefined ? { holdout: inv.holdout } : {}),
144
+ ...(inv.holdoutHint !== undefined ? { holdoutHint: inv.holdoutHint } : {}),
145
+ input: isObject(inv.input) ? clone(inv.input) : {},
146
+ expected: isObject(inv.expected) ? clone(inv.expected) : {},
147
+ tolerance: isObject(inv.tolerance) ? clone(inv.tolerance) : {}
148
+ };
149
+ // v0.1 top-level args -> input.args
150
+ if (Array.isArray(inv.args) && !Array.isArray(v2.input.args)) {
151
+ v2.input.args = clone(inv.args);
152
+ }
153
+ return v2;
154
+ });
155
+ return contract;
156
+ }
157
+ export function normalizeContract(raw) {
158
+ if (!isObject(raw)) {
159
+ throw new VibecodeError("CONTRACT_INVALID", "Contract must be a JSON object");
160
+ }
161
+ // Detect v0.1
162
+ if (raw.version === "0.1.0" || (!raw.schemaVersion && raw.version && String(raw.version).startsWith("0.1"))) {
163
+ return normalizeV01(raw);
164
+ }
165
+ // v0.2+: normalize in-memory without mutating raw
166
+ const c = clone(raw);
167
+ const rawGen = isObject(c.generator) ? c.generator : {};
168
+ const generator = {
169
+ name: typeof rawGen.name === "string" && rawGen.name ? rawGen.name : "vibecode-anything",
170
+ version: typeof rawGen.version === "string" && rawGen.version ? rawGen.version : "0.2.0",
171
+ adapter: typeof rawGen.adapter === "string" && rawGen.adapter ? rawGen.adapter : "manual"
172
+ };
173
+ const rawTarget = isObject(c.target) ? c.target : {};
174
+ const targetName = typeof rawTarget.name === "string" && rawTarget.name ? rawTarget.name : "unknown";
175
+ let domains;
176
+ if (Array.isArray(rawTarget.domains)) {
177
+ domains = rawTarget.domains;
178
+ }
179
+ else if (typeof rawTarget.domain === "string") {
180
+ domains = [rawTarget.domain];
181
+ }
182
+ else {
183
+ domains = ["cli"];
184
+ }
185
+ let rawSources = Array.isArray(rawTarget.sources) ? rawTarget.sources : [];
186
+ // v0.1 compat: top-level source string
187
+ if (rawSources.length === 0 && typeof rawTarget.source === "string") {
188
+ rawSources = [{ id: "src-1", kind: domains[0] || "cli", ref: rawTarget.source, meta: {} }];
189
+ }
190
+ const sources = rawSources.map((entry, i) => {
191
+ const s = isObject(entry) ? entry : {};
192
+ return {
193
+ id: typeof s.id === "string" && s.id ? s.id : `src-${i + 1}`,
194
+ kind: typeof s.kind === "string" && s.kind ? s.kind : domains[0] || "cli",
195
+ ref: typeof s.ref === "string" ? s.ref : "",
196
+ meta: isObject(s.meta) ? s.meta : {}
197
+ };
198
+ });
199
+ const rawArtifacts = isObject(c.artifacts) ? c.artifacts : {};
200
+ const artifactsFiles = {};
201
+ if (isObject(rawArtifacts.files)) {
202
+ for (const [k, v] of Object.entries(rawArtifacts.files)) {
203
+ if (typeof v === "string")
204
+ artifactsFiles[k] = v;
205
+ }
206
+ }
207
+ const artifacts = {
208
+ root: typeof rawArtifacts.root === "string" && rawArtifacts.root ? rawArtifacts.root : ".vibecode/artifacts",
209
+ files: artifactsFiles
210
+ };
211
+ const t = isObject(c.thresholds) ? c.thresholds : {};
212
+ const d = isObject(t.defaults) ? t.defaults : {};
213
+ const thresholds = {
214
+ hardBehavioralParity: t.hardBehavioralParity === undefined ? 1.0 : t.hardBehavioralParity,
215
+ softPerceptualParity: t.softPerceptualParity === undefined ? 0.85 : t.softPerceptualParity,
216
+ softGateMode: (t.softGateMode === undefined ? "warn" : t.softGateMode),
217
+ defaults: defaultThresholds(d)
218
+ };
219
+ const defaultTypeByDomain = {
220
+ cli: "command",
221
+ web: "web_route",
222
+ image: "image_layout",
223
+ video: "video_timeline",
224
+ api: "http",
225
+ repo: "repo_exports"
226
+ };
227
+ const rawInvs = Array.isArray(c.invariants) ? c.invariants : [];
228
+ const invariants = rawInvs.map((inv, i) => {
229
+ const n = isObject(inv) ? clone(inv) : {};
230
+ const domain = (typeof n.domain === "string" && n.domain ? n.domain : domains[0] || "cli");
231
+ const type = (typeof n.type === "string" && n.type ? n.type : defaultTypeByDomain[domain] || "command");
232
+ const input = isObject(n.input) ? n.input : {};
233
+ // v0.1 compat: top-level args
234
+ if (Array.isArray(n.args) && !Array.isArray(input.args)) {
235
+ input.args = clone(n.args);
236
+ }
237
+ const out = {
238
+ id: typeof n.id === "string" && n.id ? n.id : `inv-${i + 1}`,
239
+ domain,
240
+ type,
241
+ severity: (typeof n.severity === "string" && n.severity ? n.severity : "hard"),
242
+ description: typeof n.description === "string" ? n.description : "",
243
+ tags: Array.isArray(n.tags) ? n.tags.map(String) : [],
244
+ ...(typeof n.sourceId === "string" && n.sourceId ? { sourceId: n.sourceId } : {}),
245
+ ...(n.holdout !== undefined ? { holdout: n.holdout } : {}),
246
+ ...(n.holdoutHint !== undefined ? { holdoutHint: n.holdoutHint } : {}),
247
+ input,
248
+ expected: isObject(n.expected) ? n.expected : {},
249
+ tolerance: isObject(n.tolerance) ? n.tolerance : {}
250
+ };
251
+ return out;
252
+ });
253
+ return {
254
+ schemaVersion: typeof c.schemaVersion === "string" && c.schemaVersion ? c.schemaVersion : SCHEMA_VERSION,
255
+ createdAt: typeof c.createdAt === "string" && c.createdAt ? c.createdAt : new Date().toISOString(),
256
+ generator,
257
+ target: {
258
+ name: targetName,
259
+ domains,
260
+ sources
261
+ },
262
+ artifacts,
263
+ thresholds,
264
+ invariants,
265
+ ...(Array.isArray(c.slices) ? { slices: normalizeSlices(c.slices) } : {}),
266
+ ...(c.fixtures !== undefined ? { fixtures: c.fixtures } : {})
267
+ };
268
+ }
269
+ export function validateContract(contract) {
270
+ const errors = [];
271
+ if (!isObject(contract)) {
272
+ return { ok: false, errors: [{ path: "$", message: "Contract must be an object" }] };
273
+ }
274
+ if (typeof contract.schemaVersion !== "string") {
275
+ errors.push({ path: "$.schemaVersion", message: "schemaVersion must be a string" });
276
+ }
277
+ if (!isObject(contract.target)) {
278
+ errors.push({ path: "$.target", message: "target must be an object" });
279
+ }
280
+ else {
281
+ if (typeof contract.target.name !== "string")
282
+ errors.push({ path: "$.target.name", message: "target.name must be a string" });
283
+ if (!Array.isArray(contract.target.domains) || contract.target.domains.length === 0) {
284
+ errors.push({ path: "$.target.domains", message: "target.domains must be a non-empty array" });
285
+ }
286
+ else {
287
+ contract.target.domains.forEach((d, i) => {
288
+ if (typeof d !== "string" || !VALID_DOMAINS.has(d)) {
289
+ errors.push({ path: `$.target.domains[${i}]`, message: `Invalid domain: ${String(d)}` });
290
+ }
291
+ });
292
+ }
293
+ }
294
+ if (!isObject(contract.thresholds)) {
295
+ errors.push({ path: "$.thresholds", message: "thresholds must be an object" });
296
+ }
297
+ else {
298
+ for (const k of ["hardBehavioralParity", "softPerceptualParity"]) {
299
+ const v = contract.thresholds[k];
300
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > 1) {
301
+ errors.push({ path: `$.thresholds.${k}`, message: `${k} must be a number in [0,1]` });
302
+ }
303
+ }
304
+ const mode = contract.thresholds.softGateMode;
305
+ if (mode !== undefined && mode !== null && (typeof mode !== "string" || !["warn", "fail"].includes(mode))) {
306
+ errors.push({ path: "$.thresholds.softGateMode", message: "softGateMode must be 'warn' or 'fail'" });
307
+ }
308
+ }
309
+ if (!Array.isArray(contract.invariants)) {
310
+ errors.push({ path: "$.invariants", message: "invariants must be an array" });
311
+ }
312
+ else {
313
+ const seen = new Set();
314
+ contract.invariants.forEach((inv, i) => {
315
+ const p = `$.invariants[${i}]`;
316
+ if (!isObject(inv)) {
317
+ errors.push({ path: p, message: "invariant must be an object" });
318
+ return;
319
+ }
320
+ if (typeof inv.id !== "string" || !inv.id) {
321
+ errors.push({ path: `${p}.id`, message: "id must be a non-empty string" });
322
+ }
323
+ else if (seen.has(inv.id)) {
324
+ errors.push({ path: `${p}.id`, message: `Duplicate invariant id: ${inv.id}` });
325
+ }
326
+ else {
327
+ seen.add(inv.id);
328
+ }
329
+ if (typeof inv.domain !== "string" || !VALID_DOMAINS.has(inv.domain)) {
330
+ errors.push({ path: `${p}.domain`, message: `Invalid domain: ${String(inv.domain)}` });
331
+ }
332
+ if (!isValidInvariantType(inv.type)) {
333
+ errors.push({ path: `${p}.type`, message: `Invalid type: ${String(inv.type)}` });
334
+ }
335
+ if (typeof inv.severity !== "string" || !VALID_SEVERITIES.has(inv.severity)) {
336
+ errors.push({ path: `${p}.severity`, message: `Invalid severity: ${String(inv.severity)}` });
337
+ }
338
+ if (!isObject(inv.input)) {
339
+ errors.push({ path: `${p}.input`, message: "input must be an object" });
340
+ }
341
+ else {
342
+ if (inv.type === "http_workflow") {
343
+ if (!Array.isArray(inv.input.steps) || inv.input.steps.length === 0) {
344
+ errors.push({ path: `${p}.input.steps`, message: "http_workflow requires a non-empty steps array" });
345
+ }
346
+ else {
347
+ inv.input.steps.forEach((step, j) => {
348
+ const sp = `${p}.input.steps[${j}]`;
349
+ if (!isObject(step)) {
350
+ errors.push({ path: sp, message: "http_workflow step must be an object" });
351
+ return;
352
+ }
353
+ if (typeof step.id !== "string" || !step.id.trim()) {
354
+ errors.push({ path: `${sp}.id`, message: "http_workflow step.id must be a non-empty string" });
355
+ }
356
+ if (typeof step.path !== "string") {
357
+ errors.push({ path: `${sp}.path`, message: "http_workflow step.path must be a string" });
358
+ }
359
+ });
360
+ }
361
+ if (inv.input.finallySteps !== undefined) {
362
+ if (!Array.isArray(inv.input.finallySteps)) {
363
+ errors.push({ path: `${p}.input.finallySteps`, message: "http_workflow finallySteps must be an array" });
364
+ }
365
+ else {
366
+ inv.input.finallySteps.forEach((step, j) => {
367
+ const sp = `${p}.input.finallySteps[${j}]`;
368
+ if (!isObject(step)) {
369
+ errors.push({ path: sp, message: "http_workflow finallyStep must be an object" });
370
+ return;
371
+ }
372
+ if (typeof step.id !== "string" || !step.id.trim()) {
373
+ errors.push({ path: `${sp}.id`, message: "http_workflow finallyStep.id must be a non-empty string" });
374
+ }
375
+ if (typeof step.path !== "string") {
376
+ errors.push({ path: `${sp}.path`, message: "http_workflow finallyStep.path must be a string" });
377
+ }
378
+ });
379
+ }
380
+ }
381
+ }
382
+ else if (inv.type === "ws_protocol") {
383
+ if (!Array.isArray(inv.input.steps) || inv.input.steps.length === 0) {
384
+ errors.push({ path: `${p}.input.steps`, message: "ws_protocol requires a non-empty steps array" });
385
+ }
386
+ else {
387
+ inv.input.steps.forEach((step, j) => {
388
+ const sp = `${p}.input.steps[${j}]`;
389
+ if (!isObject(step)) {
390
+ errors.push({ path: sp, message: "ws_protocol step must be an object" });
391
+ return;
392
+ }
393
+ if (typeof step.action !== "string" || !VALID_WS_STEP_ACTIONS.has(step.action)) {
394
+ errors.push({ path: `${sp}.action`, message: "ws_protocol step.action must be 'send', 'expect', or 'close'" });
395
+ }
396
+ });
397
+ }
398
+ }
399
+ else if (inv.type === "web_ui_states") {
400
+ if (!Array.isArray(inv.input.checks) || inv.input.checks.length === 0) {
401
+ errors.push({ path: `${p}.input.checks`, message: "web_ui_states requires a non-empty checks array" });
402
+ }
403
+ else {
404
+ inv.input.checks.forEach((check, j) => {
405
+ const cp = `${p}.input.checks[${j}]`;
406
+ if (!isObject(check)) {
407
+ errors.push({ path: cp, message: "web_ui_states check must be an object" });
408
+ }
409
+ else if (typeof check.kind !== "string" || !VALID_UI_STATE_CHECK_KINDS.has(check.kind)) {
410
+ errors.push({ path: `${cp}.kind`, message: `web_ui_states check.kind must be one of ${[...VALID_UI_STATE_CHECK_KINDS].join(", ")}` });
411
+ }
412
+ });
413
+ }
414
+ }
415
+ else if (inv.type === "http_stream" && inv.input.format !== undefined) {
416
+ if (typeof inv.input.format !== "string" || !VALID_STREAM_FORMATS.has(inv.input.format)) {
417
+ errors.push({ path: `${p}.input.format`, message: "http_stream format must be 'sse', 'ndjson', or 'auto'" });
418
+ }
419
+ }
420
+ else if (inv.type === "perf_budget") {
421
+ if (inv.input.kind !== undefined && (typeof inv.input.kind !== "string" || !VALID_PERF_BUDGET_KINDS.has(inv.input.kind))) {
422
+ errors.push({ path: `${p}.input.kind`, message: "perf_budget kind must be 'http' or 'command'" });
423
+ }
424
+ if (inv.input.runs !== undefined &&
425
+ (typeof inv.input.runs !== "number" || !Number.isInteger(inv.input.runs) || inv.input.runs < 1)) {
426
+ errors.push({ path: `${p}.input.runs`, message: "perf_budget runs must be an integer >= 1" });
427
+ }
428
+ if (inv.input.warmupRuns !== undefined &&
429
+ (typeof inv.input.warmupRuns !== "number" || !Number.isInteger(inv.input.warmupRuns) || inv.input.warmupRuns < 0)) {
430
+ errors.push({ path: `${p}.input.warmupRuns`, message: "perf_budget warmupRuns must be an integer >= 0" });
431
+ }
432
+ if (inv.input.timeoutMs !== undefined &&
433
+ (typeof inv.input.timeoutMs !== "number" || !Number.isFinite(inv.input.timeoutMs) || inv.input.timeoutMs <= 0)) {
434
+ errors.push({ path: `${p}.input.timeoutMs`, message: "perf_budget timeoutMs must be a positive finite number" });
435
+ }
436
+ }
437
+ }
438
+ if (!isObject(inv.expected)) {
439
+ errors.push({ path: `${p}.expected`, message: "expected must be an object" });
440
+ }
441
+ else {
442
+ if (inv.type === "perf_budget") {
443
+ for (const key of PERF_BUDGET_NONNEG_KEYS) {
444
+ const v = inv.expected[key];
445
+ if (v !== undefined && (typeof v !== "number" || !Number.isFinite(v) || v < 0)) {
446
+ errors.push({ path: `${p}.expected.${key}`, message: `perf_budget ${key} must be a finite number >= 0` });
447
+ }
448
+ }
449
+ const minB = inv.expected.minBytes;
450
+ const maxB = inv.expected.maxBytes;
451
+ if (typeof minB === "number" &&
452
+ Number.isFinite(minB) &&
453
+ minB >= 0 &&
454
+ typeof maxB === "number" &&
455
+ Number.isFinite(maxB) &&
456
+ maxB >= 0 &&
457
+ minB > maxB) {
458
+ errors.push({ path: `${p}.expected.minBytes`, message: `perf_budget minBytes (${minB}) cannot exceed maxBytes (${maxB})` });
459
+ }
460
+ if (inv.expected.maxErrorRate !== undefined &&
461
+ (typeof inv.expected.maxErrorRate !== "number" ||
462
+ !Number.isFinite(inv.expected.maxErrorRate) ||
463
+ inv.expected.maxErrorRate < 0 ||
464
+ inv.expected.maxErrorRate > 1)) {
465
+ errors.push({ path: `${p}.expected.maxErrorRate`, message: "perf_budget maxErrorRate must be a finite number in [0, 1]" });
466
+ }
467
+ }
468
+ if (inv.expected.fsEffects !== undefined) {
469
+ if (!Array.isArray(inv.expected.fsEffects)) {
470
+ errors.push({ path: `${p}.expected.fsEffects`, message: "fsEffects must be an array" });
471
+ }
472
+ else {
473
+ inv.expected.fsEffects.forEach((entry, j) => {
474
+ const ep = `${p}.expected.fsEffects[${j}]`;
475
+ if (!isObject(entry)) {
476
+ errors.push({ path: ep, message: "fsEffects entry must be an object" });
477
+ return;
478
+ }
479
+ if (typeof entry.path !== "string" || !entry.path.trim()) {
480
+ errors.push({ path: `${ep}.path`, message: "path must be a non-empty string" });
481
+ }
482
+ if (typeof entry.status !== "string" || !VALID_FS_EFFECT_STATUSES.has(entry.status)) {
483
+ errors.push({ path: `${ep}.status`, message: "status must be 'created', 'modified', or 'deleted'" });
484
+ }
485
+ if (entry.sha256 !== undefined && typeof entry.sha256 !== "string") {
486
+ errors.push({ path: `${ep}.sha256`, message: "sha256 must be a string" });
487
+ }
488
+ if (entry.size !== undefined &&
489
+ (typeof entry.size !== "number" || !Number.isFinite(entry.size) || entry.size < 0)) {
490
+ errors.push({ path: `${ep}.size`, message: "size must be a finite number >= 0" });
491
+ }
492
+ if (entry.preview !== undefined && typeof entry.preview !== "string") {
493
+ errors.push({ path: `${ep}.preview`, message: "preview must be a string" });
494
+ }
495
+ });
496
+ }
497
+ }
498
+ }
499
+ if (inv.holdout !== undefined && typeof inv.holdout !== "boolean") {
500
+ errors.push({ path: `${p}.holdout`, message: "holdout must be a boolean" });
501
+ }
502
+ if (inv.holdoutHint !== undefined && typeof inv.holdoutHint !== "string") {
503
+ errors.push({ path: `${p}.holdoutHint`, message: "holdoutHint must be a string" });
504
+ }
505
+ });
506
+ }
507
+ if (contract.slices !== undefined) {
508
+ if (!Array.isArray(contract.slices)) {
509
+ errors.push({ path: "$.slices", message: "slices must be an array" });
510
+ }
511
+ else {
512
+ const slices = contract.slices;
513
+ const knownInvariantIds = new Set();
514
+ if (Array.isArray(contract.invariants)) {
515
+ for (const inv of contract.invariants) {
516
+ if (isObject(inv) && typeof inv.id === "string" && inv.id)
517
+ knownInvariantIds.add(inv.id);
518
+ }
519
+ }
520
+ const seenSliceIds = new Set();
521
+ const sliceIndexById = new Map();
522
+ const dependencyLists = [];
523
+ slices.forEach((entry, i) => {
524
+ const p = `$.slices[${i}]`;
525
+ const dependencies = [];
526
+ dependencyLists.push(dependencies);
527
+ if (!isObject(entry)) {
528
+ errors.push({ path: p, message: "slice must be an object" });
529
+ return;
530
+ }
531
+ if (typeof entry.id !== "string" || !entry.id) {
532
+ errors.push({ path: `${p}.id`, message: "id must be a non-empty string" });
533
+ }
534
+ else if (seenSliceIds.has(entry.id)) {
535
+ errors.push({ path: `${p}.id`, message: `Duplicate slice id: ${entry.id}` });
536
+ }
537
+ else {
538
+ seenSliceIds.add(entry.id);
539
+ sliceIndexById.set(entry.id, i);
540
+ }
541
+ if (typeof entry.title !== "string" || !entry.title) {
542
+ errors.push({ path: `${p}.title`, message: "title must be a non-empty string" });
543
+ }
544
+ if (!Array.isArray(entry.invariantIds)) {
545
+ errors.push({ path: `${p}.invariantIds`, message: "invariantIds must be an array of strings" });
546
+ }
547
+ else {
548
+ entry.invariantIds.forEach((id, j) => {
549
+ if (typeof id !== "string" || !id) {
550
+ errors.push({ path: `${p}.invariantIds[${j}]`, message: "invariant id must be a non-empty string" });
551
+ return;
552
+ }
553
+ if (Array.isArray(contract.invariants) && !knownInvariantIds.has(id)) {
554
+ errors.push({ path: `${p}.invariantIds[${j}]`, message: `Unknown invariant id: ${id}` });
555
+ }
556
+ });
557
+ }
558
+ if (entry.status === undefined) {
559
+ // Missing status is allowed; normalization supplies "pending".
560
+ }
561
+ else if (typeof entry.status !== "string" || !VALID_SLICE_STATUSES.has(entry.status)) {
562
+ errors.push({ path: `${p}.status`, message: `Invalid slice status: ${String(entry.status)}` });
563
+ }
564
+ if (entry.lastScore !== undefined) {
565
+ const score = entry.lastScore;
566
+ if (typeof score !== "number" || !Number.isFinite(score) || score < 0 || score > 1) {
567
+ errors.push({ path: `${p}.lastScore`, message: "lastScore must be a finite number in [0,1]" });
568
+ }
569
+ }
570
+ if (entry.dependsOn !== undefined) {
571
+ if (!Array.isArray(entry.dependsOn)) {
572
+ errors.push({ path: `${p}.dependsOn`, message: "dependsOn must be an array of strings" });
573
+ }
574
+ else {
575
+ entry.dependsOn.forEach((dep, j) => {
576
+ if (typeof dep !== "string" || !dep) {
577
+ errors.push({ path: `${p}.dependsOn[${j}]`, message: "dependency id must be a non-empty string" });
578
+ return;
579
+ }
580
+ dependencies.push(dep);
581
+ });
582
+ }
583
+ }
584
+ });
585
+ dependencyLists.forEach((dependencies, i) => {
586
+ const entry = slices[i];
587
+ if (!isObject(entry) || !Array.isArray(entry.dependsOn))
588
+ return;
589
+ for (const dep of dependencies) {
590
+ if (!sliceIndexById.has(dep)) {
591
+ errors.push({ path: `$.slices[${i}].dependsOn`, message: `Unknown slice dependency: ${dep}` });
592
+ }
593
+ }
594
+ });
595
+ const visiting = new Map();
596
+ const stack = [];
597
+ const reportedCycles = new Set();
598
+ const visit = (id) => {
599
+ visiting.set(id, 1);
600
+ stack.push(id);
601
+ const index = sliceIndexById.get(id);
602
+ for (const dep of index === undefined ? [] : (dependencyLists[index] || [])) {
603
+ if (!sliceIndexById.has(dep))
604
+ continue;
605
+ const state = visiting.get(dep) ?? 0;
606
+ if (state === 0) {
607
+ visit(dep);
608
+ }
609
+ else if (state === 1) {
610
+ const start = stack.indexOf(dep);
611
+ const cycle = start >= 0 ? [...stack.slice(start), dep] : [dep, dep];
612
+ const key = [...new Set(cycle)].sort().join("|");
613
+ if (!reportedCycles.has(key)) {
614
+ reportedCycles.add(key);
615
+ const at = sliceIndexById.get(id) ?? 0;
616
+ errors.push({
617
+ path: `$.slices[${at}].dependsOn`,
618
+ message: `Dependency cycle detected: ${cycle.join(" -> ")}`
619
+ });
620
+ }
621
+ }
622
+ }
623
+ stack.pop();
624
+ visiting.set(id, 2);
625
+ };
626
+ for (const id of sliceIndexById.keys()) {
627
+ if ((visiting.get(id) ?? 0) === 0)
628
+ visit(id);
629
+ }
630
+ }
631
+ }
632
+ if (contract.fixtures !== undefined) {
633
+ const fixValidation = validateContractFixtures(contract.fixtures);
634
+ if (!fixValidation.valid) {
635
+ for (const rawErr of fixValidation.errors) {
636
+ const match = rawErr.match(/^(fixtures(?:\.[A-Za-z0-9_]+|\[\d+\]|\[[^\]]+\])*):\s*(.*)$/);
637
+ errors.push({
638
+ path: match ? `$.${match[1]}` : "$.fixtures",
639
+ message: match && match[2] ? match[2] : rawErr
640
+ });
641
+ }
642
+ }
643
+ }
644
+ return { ok: errors.length === 0, errors };
645
+ }
646
+ export function assertValidContract(contract) {
647
+ const res = validateContract(contract);
648
+ if (!res.ok) {
649
+ throw new VibecodeError("CONTRACT_INVALID", `Contract invalid: ${res.errors[0].path} ${res.errors[0].message}`, { details: res.errors });
650
+ }
651
+ return contract;
652
+ }
653
+ const MAX_SCHEMA_DEPTH = 32;
654
+ const MULTIPLE_OF_EPSILON = 1e-9;
655
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
656
+ const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
657
+ const DATE_TIME_RE = /^(\d{4})-(\d{2})-(\d{2})[Tt ](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|([+-])(\d{2}):(\d{2}))$/;
658
+ const IPV4_RE = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
659
+ function hasOwn(obj, key) {
660
+ return Object.prototype.hasOwnProperty.call(obj, key);
661
+ }
662
+ function isValidCalendarDate(year, month, day) {
663
+ if (month < 1 || month > 12 || day < 1)
664
+ return false;
665
+ const isLeap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
666
+ const daysInMonth = [31, isLeap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
667
+ return day <= daysInMonth[month - 1];
668
+ }
669
+ function isValidEmail(value) {
670
+ if (value.length > 254 || /\s/.test(value))
671
+ return false;
672
+ const at = value.indexOf("@");
673
+ if (at <= 0 || at !== value.lastIndexOf("@"))
674
+ return false;
675
+ const local = value.slice(0, at);
676
+ const domain = value.slice(at + 1);
677
+ if (local.length > 64 || domain.length < 3)
678
+ return false;
679
+ if (local.startsWith(".") || local.endsWith(".") || local.includes(".."))
680
+ return false;
681
+ if (!/^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+$/.test(local))
682
+ return false;
683
+ const labels = domain.split(".");
684
+ if (labels.length < 2)
685
+ return false;
686
+ for (const label of labels) {
687
+ if (label.length === 0 || label.length > 63)
688
+ return false;
689
+ if (label.startsWith("-") || label.endsWith("-"))
690
+ return false;
691
+ if (!/^[A-Za-z0-9-]+$/.test(label))
692
+ return false;
693
+ }
694
+ const tld = labels[labels.length - 1];
695
+ if (tld.length < 2 || /^\d+$/.test(tld))
696
+ return false;
697
+ return true;
698
+ }
699
+ function isValidDate(value) {
700
+ const m = DATE_RE.exec(value);
701
+ if (!m)
702
+ return false;
703
+ return isValidCalendarDate(Number(m[1]), Number(m[2]), Number(m[3]));
704
+ }
705
+ function isValidDateTime(value) {
706
+ const m = DATE_TIME_RE.exec(value);
707
+ if (!m)
708
+ return false;
709
+ if (!isValidCalendarDate(Number(m[1]), Number(m[2]), Number(m[3])))
710
+ return false;
711
+ const hour = Number(m[4]);
712
+ const minute = Number(m[5]);
713
+ const second = Number(m[6]);
714
+ if (hour > 23 || minute > 59 || second > 59)
715
+ return false;
716
+ if (m[7] !== undefined) {
717
+ const tzHour = Number(m[8]);
718
+ const tzMinute = Number(m[9]);
719
+ if (tzHour > 23 || tzMinute > 59)
720
+ return false;
721
+ }
722
+ return true;
723
+ }
724
+ function isValidUri(value) {
725
+ if (!value || /\s/.test(value))
726
+ return false;
727
+ try {
728
+ const parsed = new URL(value);
729
+ return /^[A-Za-z][A-Za-z0-9+.-]*:$/.test(parsed.protocol);
730
+ }
731
+ catch {
732
+ return false;
733
+ }
734
+ }
735
+ function isValidIpv4(value) {
736
+ const m = IPV4_RE.exec(value);
737
+ if (!m)
738
+ return false;
739
+ for (let i = 1; i <= 4; i++) {
740
+ const part = m[i];
741
+ if (part.length > 1 && part.startsWith("0"))
742
+ return false;
743
+ const n = Number(part);
744
+ if (n < 0 || n > 255)
745
+ return false;
746
+ }
747
+ return true;
748
+ }
749
+ function validateStringFormat(value, format) {
750
+ switch (format) {
751
+ case "email": return isValidEmail(value);
752
+ case "uuid": return UUID_RE.test(value);
753
+ case "date": return isValidDate(value);
754
+ case "date-time": return isValidDateTime(value);
755
+ case "uri": return isValidUri(value);
756
+ case "ipv4": return isValidIpv4(value);
757
+ default: return true;
758
+ }
759
+ }
760
+ function canonicalJson(v, seen = new WeakSet()) {
761
+ if (v === null)
762
+ return "null";
763
+ if (typeof v === "boolean" || typeof v === "string")
764
+ return JSON.stringify(v);
765
+ if (typeof v === "number")
766
+ return Number.isFinite(v) ? JSON.stringify(v) : String(v);
767
+ if (typeof v === "undefined")
768
+ return "undefined";
769
+ if (Array.isArray(v)) {
770
+ if (seen.has(v))
771
+ return '"[Circular]"';
772
+ seen.add(v);
773
+ const parts = v.map((item) => (item === undefined ? "null" : canonicalJson(item, seen)));
774
+ seen.delete(v);
775
+ return `[${parts.join(",")}]`;
776
+ }
777
+ if (typeof v === "object") {
778
+ if (seen.has(v))
779
+ return '"[Circular]"';
780
+ seen.add(v);
781
+ const obj = v;
782
+ const keys = Object.keys(obj).sort();
783
+ const parts = [];
784
+ for (const k of keys) {
785
+ if (obj[k] === undefined)
786
+ continue;
787
+ parts.push(`${JSON.stringify(k)}:${canonicalJson(obj[k], seen)}`);
788
+ }
789
+ seen.delete(v);
790
+ return `{${parts.join(",")}}`;
791
+ }
792
+ return JSON.stringify(String(v));
793
+ }
794
+ export function validateJsonSchema(value, schema, path = "$") {
795
+ return validateJsonSchemaInternal(value, schema, path, 0);
796
+ }
797
+ function validateJsonSchemaInternal(value, schema, path, depth) {
798
+ const errors = [];
799
+ if (depth > MAX_SCHEMA_DEPTH) {
800
+ errors.push({ path, message: `Maximum schema depth (${MAX_SCHEMA_DEPTH}) exceeded` });
801
+ return errors;
802
+ }
803
+ if (!isObject(schema))
804
+ return errors;
805
+ const s = schema;
806
+ const p = path;
807
+ if (s.nullable === true && value === null) {
808
+ return errors;
809
+ }
810
+ if (s.const !== undefined) {
811
+ if (canonicalJson(value) !== canonicalJson(s.const)) {
812
+ errors.push({ path: p, message: `Expected const ${JSON.stringify(s.const)}` });
813
+ }
814
+ return errors;
815
+ }
816
+ if (Array.isArray(s.enum)) {
817
+ const valCanon = canonicalJson(value);
818
+ const ok = s.enum.some((e) => canonicalJson(e) === valCanon);
819
+ if (!ok)
820
+ errors.push({ path: p, message: `Expected one of ${JSON.stringify(s.enum)}` });
821
+ }
822
+ if (s.type !== undefined) {
823
+ const types = Array.isArray(s.type) ? s.type : [s.type];
824
+ const matches = types.some((t) => typeMatches(value, t));
825
+ if (!matches) {
826
+ errors.push({ path: p, message: `Expected type ${types.join("|")}, got ${jsType(value)}` });
827
+ return errors; // further checks likely meaningless
828
+ }
829
+ }
830
+ if (typeof value === "string") {
831
+ if (typeof s.minLength === "number" && value.length < s.minLength)
832
+ errors.push({ path: p, message: `minLength ${s.minLength}` });
833
+ if (typeof s.maxLength === "number" && value.length > s.maxLength)
834
+ errors.push({ path: p, message: `maxLength ${s.maxLength}` });
835
+ if (typeof s.pattern === "string") {
836
+ try {
837
+ if (!new RegExp(s.pattern).test(value))
838
+ errors.push({ path: p, message: `pattern ${s.pattern}` });
839
+ }
840
+ catch {
841
+ errors.push({ path: p, message: `invalid pattern ${s.pattern}` });
842
+ }
843
+ }
844
+ if (typeof s.format === "string" && !validateStringFormat(value, s.format)) {
845
+ errors.push({ path: p, message: `Invalid format "${s.format}"` });
846
+ }
847
+ }
848
+ if (typeof value === "number") {
849
+ if (typeof s.minimum === "number" && value < s.minimum)
850
+ errors.push({ path: p, message: `minimum ${s.minimum}` });
851
+ if (typeof s.maximum === "number" && value > s.maximum)
852
+ errors.push({ path: p, message: `maximum ${s.maximum}` });
853
+ if (typeof s.exclusiveMinimum === "number" && value <= s.exclusiveMinimum) {
854
+ errors.push({ path: p, message: `exclusiveMinimum ${s.exclusiveMinimum}` });
855
+ }
856
+ if (typeof s.exclusiveMaximum === "number" && value >= s.exclusiveMaximum) {
857
+ errors.push({ path: p, message: `exclusiveMaximum ${s.exclusiveMaximum}` });
858
+ }
859
+ if (typeof s.multipleOf === "number" && Number.isFinite(s.multipleOf) && s.multipleOf > 0) {
860
+ const quotient = value / s.multipleOf;
861
+ if (!Number.isFinite(quotient) || Math.abs(quotient - Math.round(quotient)) > MULTIPLE_OF_EPSILON) {
862
+ errors.push({ path: p, message: `multipleOf ${s.multipleOf}` });
863
+ }
864
+ }
865
+ }
866
+ if (Array.isArray(value)) {
867
+ if (typeof s.minItems === "number" && value.length < s.minItems)
868
+ errors.push({ path: p, message: `minItems ${s.minItems}` });
869
+ if (typeof s.maxItems === "number" && value.length > s.maxItems)
870
+ errors.push({ path: p, message: `maxItems ${s.maxItems}` });
871
+ if (s.uniqueItems === true) {
872
+ const seenItems = new Set();
873
+ for (const item of value) {
874
+ const key = canonicalJson(item);
875
+ if (seenItems.has(key)) {
876
+ errors.push({ path: p, message: "Array items must be unique" });
877
+ break;
878
+ }
879
+ seenItems.add(key);
880
+ }
881
+ }
882
+ if (isObject(s.items)) {
883
+ const itemSchema = s.items;
884
+ value.forEach((item, i) => {
885
+ errors.push(...validateJsonSchemaInternal(item, itemSchema, `${p}[${i}]`, depth + 1));
886
+ });
887
+ }
888
+ }
889
+ if (isObject(value)) {
890
+ const keys = Object.keys(value);
891
+ if (typeof s.minProperties === "number" && keys.length < s.minProperties) {
892
+ errors.push({ path: p, message: `minProperties ${s.minProperties}` });
893
+ }
894
+ if (typeof s.maxProperties === "number" && keys.length > s.maxProperties) {
895
+ errors.push({ path: p, message: `maxProperties ${s.maxProperties}` });
896
+ }
897
+ if (Array.isArray(s.required)) {
898
+ for (const k of s.required) {
899
+ if (!hasOwn(value, k))
900
+ errors.push({ path: `${p}.${k}`, message: "required" });
901
+ }
902
+ }
903
+ const declaredProps = isObject(s.properties) ? s.properties : undefined;
904
+ if (declaredProps) {
905
+ for (const [k, subSchema] of Object.entries(declaredProps)) {
906
+ if (hasOwn(value, k)) {
907
+ errors.push(...validateJsonSchemaInternal(value[k], subSchema, `${p}.${k}`, depth + 1));
908
+ }
909
+ }
910
+ }
911
+ if (s.additionalProperties === false) {
912
+ for (const k of keys) {
913
+ if (!declaredProps || !hasOwn(declaredProps, k)) {
914
+ errors.push({ path: `${p}.${k}`, message: `Unexpected additional property "${k}"` });
915
+ }
916
+ }
917
+ }
918
+ else if (isObject(s.additionalProperties)) {
919
+ const additionalSchema = s.additionalProperties;
920
+ for (const k of keys) {
921
+ if (!declaredProps || !hasOwn(declaredProps, k)) {
922
+ errors.push(...validateJsonSchemaInternal(value[k], additionalSchema, `${p}.${k}`, depth + 1));
923
+ }
924
+ }
925
+ }
926
+ }
927
+ if (Array.isArray(s.allOf)) {
928
+ for (const subSchema of s.allOf) {
929
+ errors.push(...validateJsonSchemaInternal(value, subSchema, p, depth + 1));
930
+ }
931
+ }
932
+ if (Array.isArray(s.anyOf) && s.anyOf.length > 0) {
933
+ const anyMatched = s.anyOf.some((subSchema) => validateJsonSchemaInternal(value, subSchema, p, depth + 1).length === 0);
934
+ if (!anyMatched) {
935
+ errors.push({ path: p, message: `Value did not match any schema in anyOf (${s.anyOf.length} candidates)` });
936
+ }
937
+ }
938
+ if (Array.isArray(s.oneOf) && s.oneOf.length > 0) {
939
+ let matchCount = 0;
940
+ for (const subSchema of s.oneOf) {
941
+ if (validateJsonSchemaInternal(value, subSchema, p, depth + 1).length === 0) {
942
+ matchCount++;
943
+ }
944
+ }
945
+ if (matchCount !== 1) {
946
+ errors.push({ path: p, message: `Expected value to match exactly 1 schema in oneOf, matched ${matchCount}` });
947
+ }
948
+ }
949
+ if (isObject(s.not)) {
950
+ const notErrors = validateJsonSchemaInternal(value, s.not, p, depth + 1);
951
+ if (notErrors.length === 0) {
952
+ errors.push({ path: p, message: 'Value must not match "not" schema' });
953
+ }
954
+ }
955
+ return errors;
956
+ }
957
+ function jsType(v) {
958
+ if (v === null)
959
+ return "null";
960
+ if (Array.isArray(v))
961
+ return "array";
962
+ return typeof v;
963
+ }
964
+ function typeMatches(v, t) {
965
+ switch (t) {
966
+ case "null": return v === null;
967
+ case "array": return Array.isArray(v);
968
+ case "object": return isObject(v);
969
+ case "integer": return typeof v === "number" && Number.isInteger(v);
970
+ case "number": return typeof v === "number" && Number.isFinite(v);
971
+ case "string": return typeof v === "string";
972
+ case "boolean": return typeof v === "boolean";
973
+ default: return false;
974
+ }
975
+ }
976
+ export function queryJsonPath(obj, expr) {
977
+ if (typeof expr !== "string" || !expr.startsWith("$") || expr.length > 2048) {
978
+ return { found: false, value: undefined };
979
+ }
980
+ let cur = obj;
981
+ // Tokenize: .key, ["key"], [0]
982
+ const tokens = [];
983
+ const re = /\.([A-Za-z_$][A-Za-z0-9_$-]*)|\[(\d+)\]|\[(?:"([^"]*)"|'([^']*)')\]/g;
984
+ let i = 1; // skip $
985
+ while (i < expr.length) {
986
+ if (tokens.length >= 64)
987
+ return { found: false, value: undefined };
988
+ re.lastIndex = i;
989
+ const m = re.exec(expr);
990
+ if (!m || m.index !== i) {
991
+ // fallback: unsupported path syntax
992
+ return { found: false, value: undefined };
993
+ }
994
+ if (m[1] !== undefined)
995
+ tokens.push(m[1]);
996
+ else if (m[2] !== undefined)
997
+ tokens.push(Number(m[2]));
998
+ else if (m[3] !== undefined)
999
+ tokens.push(m[3]);
1000
+ else if (m[4] !== undefined)
1001
+ tokens.push(m[4]);
1002
+ i = re.lastIndex;
1003
+ }
1004
+ for (const t of tokens) {
1005
+ if (cur === null || cur === undefined)
1006
+ return { found: false, value: undefined };
1007
+ if (typeof t === "number") {
1008
+ if (!Array.isArray(cur) || t < 0 || t >= cur.length)
1009
+ return { found: false, value: undefined };
1010
+ cur = cur[t];
1011
+ }
1012
+ else {
1013
+ if (isForbiddenObjectKey(t))
1014
+ return { found: false, value: undefined };
1015
+ if (typeof cur !== "object" || !Object.prototype.hasOwnProperty.call(cur, t)) {
1016
+ return { found: false, value: undefined };
1017
+ }
1018
+ cur = cur[t];
1019
+ }
1020
+ }
1021
+ return { found: true, value: cur };
1022
+ }
1023
+ export function makeDefaultContract({ name, domain = "cli", source = "unknown" } = {}) {
1024
+ const dom = (VALID_DOMAINS.has(domain) ? domain : "cli");
1025
+ return {
1026
+ schemaVersion: SCHEMA_VERSION,
1027
+ createdAt: new Date().toISOString(),
1028
+ generator: { name: "vibecode-anything", version: "0.2.0", adapter: dom },
1029
+ target: {
1030
+ name: name || "unknown",
1031
+ domains: [dom],
1032
+ sources: [{ id: "src-1", kind: dom, ref: source, meta: {} }]
1033
+ },
1034
+ artifacts: { root: ".vibecode/artifacts", files: {} },
1035
+ thresholds: {
1036
+ hardBehavioralParity: 1.0,
1037
+ softPerceptualParity: 0.85,
1038
+ softGateMode: "warn",
1039
+ defaults: defaultThresholds()
1040
+ },
1041
+ invariants: [
1042
+ {
1043
+ id: "inv-help",
1044
+ domain: "cli",
1045
+ type: "command",
1046
+ severity: "hard",
1047
+ description: "Target responds cleanly to --help",
1048
+ tags: [],
1049
+ sourceId: "src-1",
1050
+ input: { args: ["--help"] },
1051
+ expected: { exitCode: 0, stdoutContains: [] },
1052
+ tolerance: {}
1053
+ }
1054
+ ]
1055
+ };
1056
+ }
1057
+ export { VALID_DOMAINS, VALID_SEVERITIES, VALID_TYPES, VALID_TYPES as VALID_INVARIANT_TYPES, VALID_UI_STATE_CHECK_KINDS };