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.
Files changed (160) hide show
  1. package/README.md +239 -67
  2. package/dist/cli.js +2140 -73
  3. package/dist/core/adapters.d.ts +26 -3
  4. package/dist/core/adapters.js +411 -25
  5. package/dist/core/agent-adapter.d.ts +67 -0
  6. package/dist/core/agent-adapter.js +312 -0
  7. package/dist/core/anti-cheat.d.ts +6 -0
  8. package/dist/core/anti-cheat.js +372 -0
  9. package/dist/core/badge.d.ts +18 -0
  10. package/dist/core/badge.js +360 -0
  11. package/dist/core/cache.d.ts +47 -0
  12. package/dist/core/cache.js +403 -0
  13. package/dist/core/ci-export.d.ts +35 -0
  14. package/dist/core/ci-export.js +796 -0
  15. package/dist/core/ci-formats.d.ts +21 -0
  16. package/dist/core/ci-formats.js +388 -0
  17. package/dist/core/client-codegen.d.ts +36 -0
  18. package/dist/core/client-codegen.js +2538 -0
  19. package/dist/core/compose.d.ts +71 -0
  20. package/dist/core/compose.js +1088 -0
  21. package/dist/core/docs-export.d.ts +37 -0
  22. package/dist/core/docs-export.js +2706 -0
  23. package/dist/core/doctor.d.ts +21 -1
  24. package/dist/core/doctor.js +234 -21
  25. package/dist/core/exec.d.ts +26 -2
  26. package/dist/core/exec.js +235 -8
  27. package/dist/core/fixtures.d.ts +153 -0
  28. package/dist/core/fixtures.js +2245 -0
  29. package/dist/core/format.d.ts +77 -0
  30. package/dist/core/format.js +632 -0
  31. package/dist/core/fs-snapshot.d.ts +37 -0
  32. package/dist/core/fs-snapshot.js +216 -0
  33. package/dist/core/graphql-export.d.ts +34 -0
  34. package/dist/core/graphql-export.js +2482 -0
  35. package/dist/core/har-export.d.ts +29 -0
  36. package/dist/core/har-export.js +988 -0
  37. package/dist/core/html-report.d.ts +27 -0
  38. package/dist/core/html-report.js +1535 -0
  39. package/dist/core/http-export.d.ts +31 -0
  40. package/dist/core/http-export.js +726 -0
  41. package/dist/core/impact.d.ts +80 -0
  42. package/dist/core/impact.js +1412 -0
  43. package/dist/core/lint.d.ts +38 -0
  44. package/dist/core/lint.js +1111 -0
  45. package/dist/core/load-export.d.ts +37 -0
  46. package/dist/core/load-export.js +1813 -0
  47. package/dist/core/mcp-export.d.ts +35 -0
  48. package/dist/core/mcp-export.js +1736 -0
  49. package/dist/core/mock-server.d.ts +47 -0
  50. package/dist/core/mock-server.js +1722 -0
  51. package/dist/core/openapi-export.d.ts +44 -0
  52. package/dist/core/openapi-export.js +1074 -0
  53. package/dist/core/parity.d.ts +6 -1
  54. package/dist/core/parity.js +36 -1
  55. package/dist/core/playwright-exporter.d.ts +23 -0
  56. package/dist/core/playwright-exporter.js +1343 -0
  57. package/dist/core/png.js +45 -9
  58. package/dist/core/regression.d.ts +54 -0
  59. package/dist/core/regression.js +529 -0
  60. package/dist/core/responsive.d.ts +86 -0
  61. package/dist/core/responsive.js +606 -0
  62. package/dist/core/run.d.ts +74 -0
  63. package/dist/core/run.js +696 -0
  64. package/dist/core/scheduler.d.ts +24 -0
  65. package/dist/core/scheduler.js +162 -0
  66. package/dist/core/schema-export.d.ts +29 -0
  67. package/dist/core/schema-export.js +2215 -0
  68. package/dist/core/schema.d.ts +3 -2
  69. package/dist/core/schema.js +460 -17
  70. package/dist/core/security.d.ts +233 -0
  71. package/dist/core/security.js +1839 -0
  72. package/dist/core/server-export.d.ts +38 -0
  73. package/dist/core/server-export.js +3198 -0
  74. package/dist/core/spec-writer.d.ts +9 -0
  75. package/dist/core/spec-writer.js +1202 -0
  76. package/dist/core/store.d.ts +11 -2
  77. package/dist/core/store.js +128 -8
  78. package/dist/core/target-map.d.ts +34 -0
  79. package/dist/core/target-map.js +262 -0
  80. package/dist/core/test-exporter.d.ts +25 -0
  81. package/dist/core/test-exporter.js +1918 -0
  82. package/dist/core/types.d.ts +182 -14
  83. package/dist/core/visual-semantic.d.ts +67 -0
  84. package/dist/core/visual-semantic.js +673 -0
  85. package/dist/core/visual.js +65 -16
  86. package/dist/core/watch.d.ts +28 -3
  87. package/dist/core/watch.js +222 -12
  88. package/dist/core/yaml.d.ts +5 -0
  89. package/dist/core/yaml.js +1009 -0
  90. package/dist/diagnostics/diagnose.d.ts +53 -0
  91. package/dist/diagnostics/diagnose.js +1083 -0
  92. package/dist/diagnostics/flake.d.ts +71 -0
  93. package/dist/diagnostics/flake.js +608 -0
  94. package/dist/diagnostics/mutation-audit.d.ts +69 -0
  95. package/dist/diagnostics/mutation-audit.js +769 -0
  96. package/dist/diagnostics/spatial.d.ts +42 -0
  97. package/dist/diagnostics/spatial.js +346 -0
  98. package/dist/diagnostics/trends.d.ts +122 -0
  99. package/dist/diagnostics/trends.js +1190 -0
  100. package/dist/discovery/discover.d.ts +111 -0
  101. package/dist/discovery/discover.js +2017 -0
  102. package/dist/discovery/lock.d.ts +116 -0
  103. package/dist/discovery/lock.js +1505 -0
  104. package/dist/discovery/routes.d.ts +36 -0
  105. package/dist/discovery/routes.js +1494 -0
  106. package/dist/discovery/test-importer.d.ts +92 -0
  107. package/dist/discovery/test-importer.js +4952 -0
  108. package/dist/index.d.ts +123 -0
  109. package/dist/index.js +99 -0
  110. package/dist/ingestors/api-collections.d.ts +28 -0
  111. package/dist/ingestors/api-collections.js +2335 -0
  112. package/dist/ingestors/api-repo.d.ts +2 -1
  113. package/dist/ingestors/api-repo.js +483 -85
  114. package/dist/ingestors/asyncapi.d.ts +26 -0
  115. package/dist/ingestors/asyncapi.js +2105 -0
  116. package/dist/ingestors/bridges.d.ts +2 -0
  117. package/dist/ingestors/bridges.js +702 -0
  118. package/dist/ingestors/cli.d.ts +2 -1
  119. package/dist/ingestors/cli.js +234 -46
  120. package/dist/ingestors/curl.d.ts +14 -0
  121. package/dist/ingestors/curl.js +1024 -0
  122. package/dist/ingestors/graphql.d.ts +56 -0
  123. package/dist/ingestors/graphql.js +1852 -0
  124. package/dist/ingestors/http-file.d.ts +20 -0
  125. package/dist/ingestors/http-file.js +923 -0
  126. package/dist/ingestors/index.js +486 -6
  127. package/dist/ingestors/openrpc.d.ts +29 -0
  128. package/dist/ingestors/openrpc.js +1807 -0
  129. package/dist/ingestors/proto.d.ts +47 -0
  130. package/dist/ingestors/proto.js +2690 -0
  131. package/dist/ingestors/trace.d.ts +10 -0
  132. package/dist/ingestors/trace.js +599 -0
  133. package/dist/ingestors/video.d.ts +4 -1
  134. package/dist/ingestors/video.js +86 -36
  135. package/dist/ingestors/web.d.ts +16 -1
  136. package/dist/ingestors/web.js +474 -32
  137. package/dist/mcp/server.js +3532 -67
  138. package/dist/oracles/api-repo.js +102 -30
  139. package/dist/oracles/cli.js +65 -17
  140. package/dist/oracles/http-workflow.d.ts +68 -0
  141. package/dist/oracles/http-workflow.js +828 -0
  142. package/dist/oracles/image.js +178 -28
  143. package/dist/oracles/index.d.ts +3 -1
  144. package/dist/oracles/index.js +243 -14
  145. package/dist/oracles/perf-budget.d.ts +90 -0
  146. package/dist/oracles/perf-budget.js +1329 -0
  147. package/dist/oracles/stream.d.ts +94 -0
  148. package/dist/oracles/stream.js +1268 -0
  149. package/dist/oracles/ui-states.d.ts +49 -0
  150. package/dist/oracles/ui-states.js +894 -0
  151. package/dist/oracles/video.d.ts +1 -1
  152. package/dist/oracles/video.js +232 -16
  153. package/dist/oracles/web.js +464 -73
  154. package/dist/plugins/builtins.d.ts +12 -0
  155. package/dist/plugins/builtins.js +1052 -0
  156. package/dist/plugins/registry.d.ts +86 -0
  157. package/dist/plugins/registry.js +554 -0
  158. package/dist/setup/index.js +145 -33
  159. package/package.json +56 -47
  160. package/skills/vibecode-anything/SKILL.md +75 -52
package/dist/cli.js CHANGED
@@ -1,16 +1,11 @@
1
1
  #!/usr/bin/env node
2
+ import { execFileSync } from "node:child_process";
2
3
  import fs from "node:fs";
3
4
  import path from "node:path";
4
- import { readContract, writeContract, writeLastReport, readLastReport, resolveWorkspace } from "./core/store.js";
5
- import { detectDomain, ingest } from "./ingestors/index.js";
6
- import { verifyContract } from "./oracles/index.js";
7
- import { probeAdapters } from "./core/adapters.js";
8
- import { resolveSliceInvariants, summarizeSlices, updateSliceProgress } from "./core/slices.js";
9
- import { startWatch, formatWatchEvent } from "./core/watch.js";
10
- import { runDoctor } from "./core/doctor.js";
11
5
  import { VibecodeError, errorCode, toDiagnostic } from "./core/errors.js";
12
- import { makeDefaultContract, VALID_DOMAINS } from "./core/schema.js";
13
- const VERSION = "0.3.0";
6
+ import { ANSI, VALID_DOMAINS, isHoldoutResultRecord, isInsideVaultDirectory, isPlainObjectSafe, redactDeepValue, styleAnsi } from "./core/security.js";
7
+ import { parseRuntimeVarEntries, parseTargetMapEntries, redactRuntimeVars } from "./core/target-map.js";
8
+ const VERSION = "0.4.0";
14
9
  const CONTRACT_DIR = ".vibecode";
15
10
  const CONTRACT_FILE = path.join(CONTRACT_DIR, "contract.json");
16
11
  const VALUE_FLAGS = new Set([
@@ -21,6 +16,8 @@ const VALUE_FLAGS = new Set([
21
16
  "probe",
22
17
  "probes",
23
18
  "route",
19
+ "crawl-depth",
20
+ "holdout-route",
24
21
  "flow",
25
22
  "endpoints",
26
23
  "base-url",
@@ -33,9 +30,37 @@ const VALUE_FLAGS = new Set([
33
30
  "id",
34
31
  "clients",
35
32
  "scope",
36
- "antigravity-dir"
33
+ "antigravity-dir",
34
+ "crop",
35
+ "env",
36
+ "header",
37
+ "storage-state",
38
+ "from-commands",
39
+ "from-har",
40
+ "from-tests",
41
+ "agent",
42
+ "max-iterations",
43
+ "max-minutes",
44
+ "out",
45
+ "badge",
46
+ "markdown",
47
+ "sarif",
48
+ "junit",
49
+ "baseline",
50
+ "dir",
51
+ "port",
52
+ "format",
53
+ "with",
54
+ "prefix",
55
+ "on-conflict",
56
+ "runs",
57
+ "mode",
58
+ "concurrency",
59
+ "plugin",
60
+ "target-map",
61
+ "var"
37
62
  ]);
38
- const BOOL_FLAGS = new Set(["force", "strict", "dry-run", "local", "help", "h"]);
63
+ const BOOL_FLAGS = new Set(["force", "strict", "dry-run", "local", "fs-diff", "no-spec", "no-verify", "check", "reveal-holdouts", "no-report", "no-fixtures", "allow-fixture-commands", "cache", "pretty", "brief", "affected", "smart", "strength", "trends", "help", "h"]);
39
64
  function parseArgs(argv) {
40
65
  const [command = "help", ...rest] = argv;
41
66
  const flags = {};
@@ -105,8 +130,244 @@ function splitCsvFlags(values) {
105
130
  }
106
131
  return out;
107
132
  }
133
+ /** Runtime workflow vars for this process; every stdout/stderr write is scrubbed of their values. */
134
+ let outputRuntimeVars;
135
+ function scrubOutput(text) {
136
+ return outputRuntimeVars && Object.keys(outputRuntimeVars).length > 0 ? redactRuntimeVars(text, outputRuntimeVars) : text;
137
+ }
138
+ const PRESERVE_HASH_KEYS = new Set(["candidateOutputHash"]);
139
+ function scrubJsonValue(obj) {
140
+ if (!outputRuntimeVars || Object.keys(outputRuntimeVars).length === 0)
141
+ return obj;
142
+ const vars = outputRuntimeVars;
143
+ return redactDeepValue(obj, {
144
+ maxDepth: 32,
145
+ redactText: (s) => redactRuntimeVars(s, vars),
146
+ preserveKeys: PRESERVE_HASH_KEYS
147
+ });
148
+ }
108
149
  function emit(obj) {
109
- process.stdout.write(JSON.stringify(obj, null, 2) + "\n");
150
+ process.stdout.write(JSON.stringify(scrubJsonValue(obj), null, 2) + "\n");
151
+ }
152
+ function parseCropArg(flags) {
153
+ if (flags.crop === undefined)
154
+ return undefined;
155
+ if (typeof flags.crop !== "string") {
156
+ throw new VibecodeError("CONTRACT_INVALID", "Invalid --crop value; expected w:h:x:y with positive width and height.");
157
+ }
158
+ const match = flags.crop.match(/^\s*(\d+):(\d+):(\d+):(\d+)\s*$/);
159
+ if (!match) {
160
+ throw new VibecodeError("CONTRACT_INVALID", "Invalid --crop value; expected w:h:x:y with positive width and height.");
161
+ }
162
+ const w = Number(match[1]);
163
+ const h = Number(match[2]);
164
+ const x = Number(match[3]);
165
+ const y = Number(match[4]);
166
+ if (!Number.isSafeInteger(w) ||
167
+ !Number.isSafeInteger(h) ||
168
+ !Number.isSafeInteger(x) ||
169
+ !Number.isSafeInteger(y) ||
170
+ w <= 0 ||
171
+ h <= 0 ||
172
+ x < 0 ||
173
+ y < 0) {
174
+ throw new VibecodeError("CONTRACT_INVALID", "Invalid --crop value; expected w:h:x:y with positive width and height.");
175
+ }
176
+ return `${w}:${h}:${x}:${y}`;
177
+ }
178
+ function parseEnvFlags(flags) {
179
+ const raw = flagList(flags, "env");
180
+ if (raw.length === 0)
181
+ return undefined;
182
+ const env = {};
183
+ for (const entry of raw) {
184
+ if (typeof entry !== "string") {
185
+ throw new VibecodeError("CONTRACT_INVALID", "--env requires a \"KEY=VALUE\" string.");
186
+ }
187
+ const eq = entry.indexOf("=");
188
+ if (eq < 0) {
189
+ throw new VibecodeError("CONTRACT_INVALID", "--env must use \"KEY=VALUE\" format.");
190
+ }
191
+ const key = entry.slice(0, eq).trim();
192
+ if (!key) {
193
+ throw new VibecodeError("CONTRACT_INVALID", "--env key cannot be empty.");
194
+ }
195
+ env[key] = entry.slice(eq + 1);
196
+ }
197
+ return env;
198
+ }
199
+ function parseHeaderFlags(flags) {
200
+ const raw = flagList(flags, "header");
201
+ if (raw.length === 0)
202
+ return undefined;
203
+ const headers = {};
204
+ for (const entry of raw) {
205
+ if (typeof entry !== "string") {
206
+ throw new VibecodeError("CONTRACT_INVALID", "--header requires a \"Name: Value\" string.");
207
+ }
208
+ const colon = entry.indexOf(":");
209
+ if (colon < 0) {
210
+ throw new VibecodeError("CONTRACT_INVALID", "--header must use \"Name: Value\" format.");
211
+ }
212
+ const name = entry.slice(0, colon).trim();
213
+ if (!name) {
214
+ throw new VibecodeError("CONTRACT_INVALID", "--header name cannot be empty.");
215
+ }
216
+ headers[name] = entry.slice(colon + 1).trim();
217
+ }
218
+ return headers;
219
+ }
220
+ function parseFileFlag(flags, flagName, options = {}) {
221
+ const raw = flags[flagName];
222
+ if (raw === undefined)
223
+ return undefined;
224
+ if (typeof raw !== "string" || !raw.trim()) {
225
+ throw new VibecodeError("CONTRACT_INVALID", `--${flagName} requires a valid ${options.allowDirectory ? "file or directory " : "file "}path.`);
226
+ }
227
+ const resolved = path.resolve(process.cwd(), raw.trim());
228
+ let st;
229
+ try {
230
+ st = fs.statSync(resolved);
231
+ }
232
+ catch {
233
+ throw new VibecodeError("CONTRACT_INVALID", `--${flagName} ${options.allowDirectory ? "path" : "file"} does not exist: ${raw.trim()}`);
234
+ }
235
+ if (!options.allowDirectory && st.isDirectory()) {
236
+ throw new VibecodeError("CONTRACT_INVALID", `--${flagName} must point to a file, not a directory: ${raw.trim()}`);
237
+ }
238
+ return resolved;
239
+ }
240
+ async function parseVerifyModeFlag(flags) {
241
+ const raw = flags.mode;
242
+ if (raw === undefined)
243
+ return undefined;
244
+ const { VALID_VERIFY_MODES } = await import("./core/visual-semantic.js");
245
+ if (typeof raw !== "string" || !VALID_VERIFY_MODES.has(raw.trim())) {
246
+ const display = Array.isArray(raw) ? raw.map(String).join(", ") : String(raw);
247
+ throw new VibecodeError("CONFIG_INVALID", `Invalid --mode value: ${display} (expected one of ${[...VALID_VERIFY_MODES].join(", ")})`);
248
+ }
249
+ return raw.trim();
250
+ }
251
+ async function parseConcurrencyFlag(flags) {
252
+ const raw = flags.concurrency;
253
+ if (raw === undefined)
254
+ return undefined;
255
+ if (typeof raw !== "string") {
256
+ const display = Array.isArray(raw) ? raw.map(String).join(", ") : String(raw);
257
+ throw new VibecodeError("CONFIG_INVALID", `Invalid --concurrency value: ${display} (expected an integer between 1 and 8)`);
258
+ }
259
+ const trimmed = raw.trim();
260
+ if (!/^\d+$/.test(trimmed)) {
261
+ throw new VibecodeError("CONFIG_INVALID", `Invalid --concurrency value: ${trimmed || "(empty)"} (expected an integer between 1 and 8)`);
262
+ }
263
+ const { normalizeConcurrency } = await import("./core/scheduler.js");
264
+ return normalizeConcurrency(Number.parseInt(trimmed, 10));
265
+ }
266
+ function parsePluginFlags(flags) {
267
+ const rawList = flagList(flags, "plugin");
268
+ if (rawList.length === 0)
269
+ return [];
270
+ const paths = [];
271
+ for (const entry of rawList) {
272
+ if (typeof entry !== "string" || !entry.trim()) {
273
+ throw new VibecodeError("CONFIG_INVALID", "--plugin requires a non-empty .mjs or .js file path.");
274
+ }
275
+ paths.push(entry.trim());
276
+ }
277
+ return paths;
278
+ }
279
+ async function loadCliPluginRegistry(flags) {
280
+ const pluginPaths = parsePluginFlags(flags);
281
+ if (pluginPaths.length === 0)
282
+ return { pluginPaths };
283
+ const [{ createDefaultPluginRegistry }, { loadLocalPlugins }] = await Promise.all([
284
+ import("./plugins/builtins.js"),
285
+ import("./plugins/registry.js")
286
+ ]);
287
+ const registry = createDefaultPluginRegistry();
288
+ await loadLocalPlugins(process.cwd(), pluginPaths, { registry });
289
+ return { pluginPaths, pluginRegistry: registry };
290
+ }
291
+ function stringFlagEntries(flags, key, usage) {
292
+ return flagList(flags, key).map((entry) => {
293
+ if (typeof entry !== "string" || !entry.trim())
294
+ throw new VibecodeError("CONFIG_INVALID", `--${key} requires ${usage}.`);
295
+ return entry;
296
+ });
297
+ }
298
+ /** Parse --target-map (repeatable), --var (repeatable) and VIBECODE_VAR_* env; registers vars for output scrubbing. */
299
+ function parseRuntimeTargetFlags(flags) {
300
+ const mapEntries = stringFlagEntries(flags, "target-map", "<domain=target> or a JSON object");
301
+ const varEntries = stringFlagEntries(flags, "var", "<KEY=VAL>");
302
+ const targets = mapEntries.length > 0 ? parseTargetMapEntries(mapEntries) : undefined;
303
+ const vars = parseRuntimeVarEntries(varEntries, process.env);
304
+ const hasVars = Object.keys(vars).length > 0;
305
+ if (hasVars)
306
+ outputRuntimeVars = vars;
307
+ const target = typeof flags.target === "string" && flags.target.trim() ? flags.target : undefined;
308
+ return {
309
+ ...(target ? { target } : {}),
310
+ ...(targets && Object.keys(targets).length > 0 ? { targets } : {}),
311
+ ...(hasVars ? { vars } : {}),
312
+ varNames: [...new Set(varEntries.map((e) => e.slice(0, e.indexOf("="))))]
313
+ };
314
+ }
315
+ function requireTargetOrMap(rt, what) {
316
+ if (!rt.target && !rt.targets) {
317
+ throw new VibecodeError("TARGET_MISSING", `Missing --target "<command-or-url>" (or --target-map <domain=target>) for ${what}.`);
318
+ }
319
+ }
320
+ function quoteArg(value) {
321
+ if (value.includes('"') && !value.includes("'")) {
322
+ return `'${value}'`;
323
+ }
324
+ return `"${value.replace(/"/g, '\\"')}"`;
325
+ }
326
+ /** Secret-safe repro command: --var values are always replaced by <REDACTED>. */
327
+ function buildVerifyRepro(rt, result, opts) {
328
+ const parts = ["vibecode-anything verify"];
329
+ if (rt.target)
330
+ parts.push(`--target ${quoteArg(rt.target)}`);
331
+ for (const [domain, t] of Object.entries(rt.targets ?? {}))
332
+ if (typeof t === "string")
333
+ parts.push(`--target-map ${quoteArg(`${domain}=${t}`)}`);
334
+ if (typeof result.type === "string" && result.type.startsWith("plugin_")) {
335
+ for (const p of opts.pluginPaths)
336
+ parts.push(`--plugin ${quoteArg(p)}`);
337
+ }
338
+ parts.push(`--invariant ${result.id}`);
339
+ if (opts.strict)
340
+ parts.push("--strict");
341
+ if (opts.mode && opts.mode !== "exact")
342
+ parts.push(`--mode ${opts.mode}`);
343
+ const head = parts.join(" ");
344
+ // Var placeholders are appended after scrubbing so the literal `<REDACTED>` marker survives.
345
+ const varFlags = rt.varNames.map((name) => ` --var ${name}=<REDACTED>`).join("");
346
+ return (rt.vars ? redactRuntimeVars(head, rt.vars) : head) + varFlags;
347
+ }
348
+ function resolveGitShortShaSafe(cwd) {
349
+ try {
350
+ const out = execFileSync("git", ["-c", "core.fsmonitor=false", "rev-parse", "--short=12", "HEAD"], {
351
+ cwd,
352
+ encoding: "utf8",
353
+ stdio: ["ignore", "pipe", "ignore"],
354
+ windowsHide: true,
355
+ timeout: 2000,
356
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0" }
357
+ }).trim();
358
+ return /^[0-9a-f]{4,40}$/i.test(out) ? out : undefined;
359
+ }
360
+ catch {
361
+ return undefined;
362
+ }
363
+ }
364
+ function sanitizeReportResult(result) {
365
+ if (result.metrics?.redacted === true && "repro" in result) {
366
+ const copy = { ...result };
367
+ delete copy.repro;
368
+ return copy;
369
+ }
370
+ return result;
110
371
  }
111
372
  function fail(err, fallbackCode = 1) {
112
373
  const diag = toDiagnostic(err);
@@ -117,7 +378,7 @@ function fail(err, fallbackCode = 1) {
117
378
  diag.code === "NOT_FOUND"
118
379
  ? 2
119
380
  : fallbackCode;
120
- process.stderr.write(JSON.stringify({ error: diag }, null, 2) + "\n");
381
+ process.stderr.write(JSON.stringify(scrubJsonValue({ error: diag }), null, 2) + "\n");
121
382
  process.exitCode = code;
122
383
  }
123
384
  function cmdInit(flags) {
@@ -149,11 +410,55 @@ function cmdInit(flags) {
149
410
  process.stdout.write(`Initialized ${CONTRACT_FILE} (domain=${domain}, source=${source})\n`);
150
411
  }
151
412
  async function cmdIngest(flags) {
152
- const source = flags.source;
153
- if (typeof source !== "string" || !source) {
154
- throw new VibecodeError("TARGET_MISSING", "ingest requires --source <reference>");
413
+ const crop = parseCropArg(flags);
414
+ const env = parseEnvFlags(flags);
415
+ const fsDiff = flags["fs-diff"] === true;
416
+ const headers = parseHeaderFlags(flags);
417
+ const storageState = parseFileFlag(flags, "storage-state");
418
+ const fromCommands = parseFileFlag(flags, "from-commands");
419
+ const fromHar = parseFileFlag(flags, "from-har");
420
+ const fromTests = parseFileFlag(flags, "from-tests", { allowDirectory: true });
421
+ const multiImportCount = [fromCommands, fromHar, fromTests].filter(Boolean).length;
422
+ if (multiImportCount > 1) {
423
+ throw new VibecodeError("CONTRACT_INVALID", "Cannot combine --from-commands, --from-har, and --from-tests in a single ingest.");
424
+ }
425
+ const rawSource = typeof flags.source === "string" ? flags.source.trim() : "";
426
+ if (!rawSource && !fromCommands && !fromHar && !fromTests) {
427
+ throw new VibecodeError("TARGET_MISSING", "ingest requires --source <reference>, --from-commands <file>, --from-har <file>, or --from-tests <path>");
428
+ }
429
+ const noSpec = flags["no-spec"] === true;
430
+ if (fromTests) {
431
+ const { formatPrettyTestImport, ingestFromTests } = await import("./discovery/test-importer.js");
432
+ const imported = await ingestFromTests(fromTests, {
433
+ cwd: process.cwd(),
434
+ ...(typeof flags.name === "string" && flags.name.trim() ? { name: flags.name.trim() } : {}),
435
+ ...(typeof flags["base-url"] === "string" && flags["base-url"].trim() ? { baseUrl: flags["base-url"].trim() } : {}),
436
+ ...(typeof flags.target === "string" && flags.target.trim() ? { target: flags.target.trim() } : {}),
437
+ force: flags.force === true,
438
+ noSpec
439
+ });
440
+ if (flags.pretty === true) {
441
+ process.stdout.write(formatPrettyTestImport(imported, { color: Boolean(process.stdout.isTTY) }) + "\n");
442
+ return;
443
+ }
444
+ emit({
445
+ ok: true,
446
+ command: "ingest",
447
+ domain: imported.contract.target.domains[0] ?? "api",
448
+ domains: imported.contract.target.domains,
449
+ ...(imported.contractPath ? { contractPath: imported.contractPath } : {}),
450
+ ...(imported.specPath ? { specPath: imported.specPath } : {}),
451
+ invariants: imported.importedCount,
452
+ visibleInvariants: imported.contract.invariants.length,
453
+ holdouts: imported.holdoutCount,
454
+ filesScanned: imported.filesScanned,
455
+ frameworks: imported.frameworks,
456
+ warnings: imported.warnings
457
+ });
458
+ return;
155
459
  }
156
- const domain = typeof flags.domain === "string" ? flags.domain : detectDomain(source);
460
+ const effectiveSource = rawSource || fromCommands || fromHar || "";
461
+ const explicitDomain = typeof flags.domain === "string" && flags.domain.trim() ? flags.domain.trim() : undefined;
157
462
  const probes = flagList(flags, "probe").filter((p) => typeof p === "string");
158
463
  if (typeof flags.probes === "string") {
159
464
  const file = path.resolve(process.cwd(), flags.probes);
@@ -171,15 +476,35 @@ async function cmdIngest(flags) {
171
476
  let endpoints = null;
172
477
  if (typeof flags.endpoints === "string") {
173
478
  const parsed = JSON.parse(fs.readFileSync(path.resolve(process.cwd(), flags.endpoints), "utf8"));
174
- const parsedObj = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
479
+ const parsedObj = isPlainObjectSafe(parsed) ? parsed : null;
175
480
  endpoints = Array.isArray(parsed)
176
481
  ? parsed
177
482
  : (parsedObj && Array.isArray(parsedObj.endpoints) ? parsedObj.endpoints : []);
178
483
  }
179
- const contractName = typeof flags.name === "string" && flags.name.trim() ? flags.name.trim() : path.basename(process.cwd());
180
- const result = await ingest({
181
- domain,
182
- source,
484
+ let crawlDepth;
485
+ if (flags["crawl-depth"] !== undefined) {
486
+ if (typeof flags["crawl-depth"] !== "string" || !/^\d+$/.test(flags["crawl-depth"].trim())) {
487
+ throw new VibecodeError("CONTRACT_INVALID", "--crawl-depth must be an integer between 1 and 3");
488
+ }
489
+ const parsedDepth = Number.parseInt(flags["crawl-depth"].trim(), 10);
490
+ if (!Number.isInteger(parsedDepth) || parsedDepth < 1 || parsedDepth > 3) {
491
+ throw new VibecodeError("CONTRACT_INVALID", "--crawl-depth must be an integer between 1 and 3");
492
+ }
493
+ crawlDepth = parsedDepth;
494
+ }
495
+ const holdoutRoutes = flagList(flags, "holdout-route").filter((r) => typeof r === "string");
496
+ const contractName = typeof flags.name === "string" && flags.name.trim()
497
+ ? flags.name.trim()
498
+ : (path.basename(process.cwd()) || path.basename(effectiveSource) || "unknown");
499
+ const [{ detectDomain, ingest }, { makeDefaultContract }, { writeContract }, specMod] = await Promise.all([
500
+ import("./ingestors/index.js"),
501
+ import("./core/schema.js"),
502
+ import("./core/store.js"),
503
+ noSpec ? Promise.resolve(null) : import("./core/spec-writer.js")
504
+ ]);
505
+ const ingestOptions = {
506
+ ...(explicitDomain ? { domain: explicitDomain } : (!fromCommands && !fromHar ? { domain: detectDomain(rawSource) } : {})),
507
+ ...(rawSource ? { source: rawSource } : {}),
183
508
  name: contractName,
184
509
  probes,
185
510
  routes,
@@ -188,29 +513,82 @@ async function cmdIngest(flags) {
188
513
  baseUrl: typeof flags["base-url"] === "string" ? flags["base-url"] : undefined,
189
514
  sceneThreshold: flags["scene-threshold"] !== undefined ? Number(flags["scene-threshold"]) : undefined,
190
515
  maxFrames: flags["max-frames"] !== undefined ? Number(flags["max-frames"]) : undefined,
516
+ noSpec,
517
+ ...(crawlDepth !== undefined ? { crawlDepth } : {}),
518
+ ...(holdoutRoutes.length > 0 ? { holdoutRoutes } : {}),
519
+ ...(crop !== undefined ? { crop } : {}),
520
+ ...(env !== undefined ? { env } : {}),
521
+ ...(fsDiff ? { fsDiff: true } : {}),
522
+ ...(headers !== undefined ? { headers } : {}),
523
+ ...(storageState !== undefined ? { storageState } : {}),
524
+ ...(fromCommands !== undefined ? { fromCommands } : {}),
525
+ ...(fromHar !== undefined ? { fromHar } : {}),
191
526
  cwd: process.cwd()
192
- }, {});
193
- const contract = makeDefaultContract({ name: contractName, domain: result.domain, source });
527
+ };
528
+ const result = await ingest(ingestOptions, {});
529
+ const contract = makeDefaultContract({ name: contractName, domain: result.domain, source: effectiveSource });
194
530
  const invDomains = (result.invariants || []).map((i) => i.domain).filter((d) => VALID_DOMAINS.has(d));
195
531
  contract.target.domains = [...new Set([result.domain, ...invDomains].filter((d) => VALID_DOMAINS.has(d)))];
196
532
  contract.target.sources = result.sources;
197
533
  contract.artifacts = result.artifacts;
198
534
  contract.invariants = result.invariants;
199
- const contractPath = writeContract(contract, process.cwd(), { force: Boolean(flags.force) });
535
+ const contractPath = writeContract(contract, process.cwd(), { force: Boolean(flags.force), replaceHoldouts: true });
536
+ const holdoutCount = (result.invariants || []).filter((i) => i.holdout === true).length;
537
+ const specPath = specMod ? specMod.writeSpecFile(process.cwd(), { contract, holdoutCount }) : undefined;
200
538
  emit({
201
539
  ok: true,
202
540
  command: "ingest",
203
541
  domain: result.domain,
204
542
  contractPath,
543
+ ...(specPath ? { specPath } : {}),
205
544
  invariants: result.invariants.length,
545
+ holdouts: holdoutCount,
206
546
  warnings: result.warnings
207
547
  });
208
548
  }
209
549
  async function cmdVerify(flags) {
550
+ let mode;
551
+ let concurrency;
552
+ let pluginPaths = [];
553
+ let rt;
554
+ try {
555
+ mode = await parseVerifyModeFlag(flags);
556
+ concurrency = await parseConcurrencyFlag(flags);
557
+ pluginPaths = parsePluginFlags(flags);
558
+ rt = parseRuntimeTargetFlags(flags);
559
+ }
560
+ catch (err) {
561
+ fail(err, 2);
562
+ return;
563
+ }
564
+ const [storeMod, oraclesMod, schemaMod] = await Promise.all([
565
+ import("./core/store.js"),
566
+ import("./oracles/index.js"),
567
+ import("./core/schema.js")
568
+ ]);
569
+ const { readContract, readHoldouts, readLastReport, resolveWorkspace, writeContract, writeLastReport } = storeMod;
570
+ const { redactRuntimeVarsDeep, verifyContract } = oraclesMod;
571
+ const { SCHEMA_VERSION } = schemaMod;
210
572
  const contract = readContract(process.cwd());
211
- const target = flags.target;
212
- if (typeof target !== "string" || !target) {
213
- throw new VibecodeError("TARGET_MISSING", "Missing --target \"<command-or-url>\" for verification.");
573
+ requireTargetOrMap(rt, "verification");
574
+ const target = rt.target ?? "";
575
+ const headers = parseHeaderFlags(flags);
576
+ const storageState = parseFileFlag(flags, "storage-state");
577
+ let pluginRegistry;
578
+ if (pluginPaths.length > 0) {
579
+ const [{ createDefaultPluginRegistry }, { loadLocalPlugins }] = await Promise.all([
580
+ import("./plugins/builtins.js"),
581
+ import("./plugins/registry.js")
582
+ ]);
583
+ const registry = createDefaultPluginRegistry();
584
+ try {
585
+ await loadLocalPlugins(process.cwd(), pluginPaths, { registry });
586
+ }
587
+ catch (err) {
588
+ fail(err, errorCode(err) === "CONFIG_INVALID" ? 2 : 1);
589
+ return;
590
+ }
591
+ pluginRegistry = registry;
214
592
  }
215
593
  const { artifactsDir, cacheDir } = resolveWorkspace(process.cwd());
216
594
  const sliceArgs = splitCsvFlags(flagList(flags, "slice"));
@@ -218,8 +596,11 @@ async function cmdVerify(flags) {
218
596
  let resolvedSliceIds = [];
219
597
  const invariantIds = [];
220
598
  const seenIds = new Set();
221
- if (sliceArgs.length > 0) {
222
- const resolved = resolveSliceInvariants(contract, sliceArgs);
599
+ const slicesMod = sliceArgs.length > 0 || (Array.isArray(contract.slices) && contract.slices.length > 0)
600
+ ? await import("./core/slices.js")
601
+ : null;
602
+ if (sliceArgs.length > 0 && slicesMod) {
603
+ const resolved = slicesMod.resolveSliceInvariants(contract, sliceArgs);
223
604
  resolvedSliceIds = resolved.slices.map((s) => s.id);
224
605
  for (const id of resolved.invariantIds) {
225
606
  if (!seenIds.has(id)) {
@@ -234,33 +615,440 @@ async function cmdVerify(flags) {
234
615
  invariantIds.push(id);
235
616
  }
236
617
  }
618
+ const cacheBypassedReason = flags.cache === true && rt.vars ? "runtime_vars_present" : undefined;
619
+ const cacheBypassNote = cacheBypassedReason
620
+ ? `Note: replay cache bypassed (${cacheBypassedReason}) for secret safety.`
621
+ : undefined;
622
+ const holdouts = readHoldouts(process.cwd());
623
+ const holdoutIds = new Set([...holdouts, ...contract.invariants.filter((i) => i.holdout === true)].map((i) => i.id));
624
+ let impact;
625
+ let impactMod = null;
626
+ let effectiveInvariantIds = invariantIds;
627
+ if (flags.affected === true) {
628
+ impactMod = await import("./core/impact.js");
629
+ const safeContractForImpact = {
630
+ ...contract,
631
+ invariants: contract.invariants.filter((inv) => inv.holdout !== true && !holdoutIds.has(inv.id))
632
+ };
633
+ const changedFiles = impactMod.getGitChangedFiles(process.cwd());
634
+ const lastReport = readLastReport(process.cwd());
635
+ const failedIdsFromLastReport = (lastReport?.results ?? [])
636
+ .filter((r) => r.status !== "pass" && r.status !== "skipped" && !holdoutIds.has(r.id) && !isHoldoutResultRecord(r))
637
+ .map((r) => r.id);
638
+ impact = impactMod.analyzeImpact(safeContractForImpact, changedFiles, {
639
+ cwd: process.cwd(),
640
+ previousFailedIds: failedIdsFromLastReport,
641
+ selectAllOnEmpty: false
642
+ });
643
+ if (!impact.fallbackToFull) {
644
+ if (invariantIds.length > 0) {
645
+ const impactedSet = new Set(impact.selectedInvariantIds);
646
+ effectiveInvariantIds = invariantIds.filter((id) => impactedSet.has(id));
647
+ }
648
+ else {
649
+ effectiveInvariantIds = [...impact.selectedInvariantIds];
650
+ }
651
+ if (effectiveInvariantIds.length === 0) {
652
+ const noImpactReport = {
653
+ schemaVersion: contract.schemaVersion || SCHEMA_VERSION,
654
+ timestamp: new Date().toISOString(),
655
+ passed: 0,
656
+ total: 0,
657
+ parity: 1.0,
658
+ compositeScore: 1.0,
659
+ hard: { passed: 0, failed: 0, skipped: 0, evaluated: 0, total: 0, parity: 1.0 },
660
+ soft: { passed: 0, warned: 0, failed: 0, skipped: 0, evaluated: 0, total: 0, meanScore: 1.0, parity: 1.0 },
661
+ gate: {
662
+ passed: true,
663
+ status: "pass",
664
+ exitCode: 0,
665
+ reasons: ["No impacted invariants to re-run"]
666
+ },
667
+ nextAction: "none",
668
+ results: []
669
+ };
670
+ if (flags.pretty === true) {
671
+ const { formatPrettyReport } = await import("./core/format.js");
672
+ const color = Boolean(process.stdout.isTTY);
673
+ const impactText = impactMod.formatPrettyImpact(impact, { color }).trimEnd();
674
+ const reportText = formatPrettyReport(noImpactReport, {
675
+ target: target || Object.entries(rt.targets ?? {}).map(([d, t]) => `${d}=${t}`).join(", "),
676
+ contractName: contract.target.name,
677
+ color
678
+ }).trimEnd();
679
+ const combined = `${impactText}\n\n${reportText}` + (cacheBypassNote ? `\n${cacheBypassNote}` : "");
680
+ process.stdout.write(scrubOutput(combined) + "\n");
681
+ }
682
+ else {
683
+ emit({
684
+ ...noImpactReport,
685
+ ...(cacheBypassedReason ? { cacheBypassedReason } : {}),
686
+ note: "No impacted invariants to re-run",
687
+ impact
688
+ });
689
+ }
690
+ process.exitCode = 0;
691
+ return;
692
+ }
693
+ }
694
+ }
237
695
  const ctx = {
238
696
  target,
697
+ ...(rt.targets ? { targets: rt.targets } : {}),
698
+ ...(rt.vars ? { vars: rt.vars } : {}),
239
699
  cwd: process.cwd(),
240
700
  contract,
241
701
  artifactsDir,
242
702
  cacheDir,
243
703
  strict: flags.strict === true,
244
- invariantIds,
704
+ ...(mode ? { mode } : {}),
705
+ ...(concurrency !== undefined ? { concurrency } : {}),
706
+ ...(pluginRegistry ? { pluginRegistry } : {}),
707
+ revealHoldouts: flags["reveal-holdouts"] === true,
708
+ useCache: flags.cache === true,
709
+ invariantIds: effectiveInvariantIds,
710
+ ...(headers !== undefined ? { headers } : {}),
711
+ ...(storageState !== undefined ? { storageState } : {}),
712
+ ...(flags["no-fixtures"] === true ? { skipFixtures: true } : {}),
713
+ ...(flags["allow-fixture-commands"] === true ? { allowFixtureCommands: true } : {}),
245
714
  runtimeCache: {}
246
715
  };
247
- const report = await verifyContract(contract, ctx, {});
716
+ const verifyStartedAt = Date.now();
717
+ let report;
718
+ try {
719
+ report = await verifyContract(contract, ctx, {});
720
+ }
721
+ catch (err) {
722
+ if (errorCode(err) === "CONFIG_INVALID") {
723
+ fail(err, 2);
724
+ return;
725
+ }
726
+ throw err;
727
+ }
728
+ const totalDurationMs = Math.max(0, Date.now() - verifyStartedAt);
729
+ const safeReproByIndex = new Map();
730
+ const strictRepro = flags.strict === true;
731
+ const resultsList = report.results || [];
732
+ for (let i = 0; i < resultsList.length; i++) {
733
+ const r = resultsList[i];
734
+ if ((r.status === "fail" || r.status === "error") && !holdoutIds.has(r.id) && r.metrics?.redacted !== true) {
735
+ const repro = buildVerifyRepro(rt, r, { strict: strictRepro, ...(mode ? { mode } : {}), pluginPaths });
736
+ r.repro = repro;
737
+ safeReproByIndex.set(i, repro);
738
+ }
739
+ }
248
740
  writeLastReport(report, process.cwd());
249
- if (resolvedSliceIds.length > 0 || (Array.isArray(contract.slices) && contract.slices.length > 0)) {
250
- const updated = updateSliceProgress(contract, report, resolvedSliceIds.length > 0 ? { sliceIds: resolvedSliceIds } : {});
251
- writeContract(updated, process.cwd(), { force: true });
252
- emit({ ...report, slices: summarizeSlices(updated) });
741
+ const noReport = flags["no-report"] === true;
742
+ if (!noReport) {
743
+ try {
744
+ const { appendTrendEntry } = await import("./diagnostics/trends.js");
745
+ const gitSha = resolveGitShortShaSafe(process.cwd());
746
+ const reportForTrends = holdoutIds.size > 0
747
+ ? {
748
+ ...report,
749
+ results: (report.results || []).map((r) => holdoutIds.has(r.id)
750
+ ? { ...r, metrics: { ...(r.metrics ?? {}), redacted: true, holdout: true } }
751
+ : r)
752
+ }
753
+ : report;
754
+ const safeReportForTrends = rt.vars ? redactRuntimeVarsDeep(reportForTrends, rt.vars) : reportForTrends;
755
+ appendTrendEntry(process.cwd(), safeReportForTrends, {
756
+ ...(gitSha ? { gitSha } : {}),
757
+ ...(mode ? { mode } : {}),
758
+ ...(flags.affected === true ? { affected: true } : {}),
759
+ totalDurationMs
760
+ });
761
+ }
762
+ catch {
763
+ // Best-effort: trend persistence is non-fatal on read-only workspaces or confined symlink errors.
764
+ }
765
+ }
766
+ let contractForReport = contract;
767
+ let sliceSummary;
768
+ if (slicesMod && (resolvedSliceIds.length > 0 || (Array.isArray(contract.slices) && contract.slices.length > 0))) {
769
+ const updated = slicesMod.updateSliceProgress(contract, report, resolvedSliceIds.length > 0 ? { sliceIds: resolvedSliceIds } : {});
770
+ writeContract(updated, process.cwd(), { force: true, preserveHoldouts: true });
771
+ contractForReport = updated;
772
+ sliceSummary = slicesMod.summarizeSlices(updated);
773
+ }
774
+ const mergedForHtml = holdouts.length > 0
775
+ ? {
776
+ ...contractForReport,
777
+ invariants: [
778
+ ...contractForReport.invariants,
779
+ ...holdouts.filter((h) => !contractForReport.invariants.some((v) => v.id === h.id))
780
+ ]
781
+ }
782
+ : contractForReport;
783
+ let reportHtmlPath;
784
+ if (!noReport) {
785
+ const [{ writeHtmlReport }, { readRunHistory }] = await Promise.all([
786
+ import("./core/html-report.js"),
787
+ import("./core/run.js")
788
+ ]);
789
+ reportHtmlPath = writeHtmlReport(process.cwd(), {
790
+ contract: mergedForHtml,
791
+ report,
792
+ history: readRunHistory(process.cwd()),
793
+ workspaceDir: process.cwd()
794
+ });
795
+ }
796
+ if (flags.pretty === true) {
797
+ const [{ formatPrettyReport }, fixturesMod] = await Promise.all([
798
+ import("./core/format.js"),
799
+ report.fixtureSummary?.applied ? import("./core/fixtures.js") : Promise.resolve(null)
800
+ ]);
801
+ const color = Boolean(process.stdout.isTTY);
802
+ const reportText = formatPrettyReport(report, {
803
+ target: target || Object.entries(rt.targets ?? {}).map(([d, t]) => `${d}=${t}`).join(", "),
804
+ contractName: contract.target.name,
805
+ ...(reportHtmlPath ? { reportHtmlPath } : {}),
806
+ color,
807
+ ...(sliceSummary ? { slices: sliceSummary } : {})
808
+ }).trimEnd();
809
+ const fixtureBlock = report.fixtureSummary?.applied && fixturesMod
810
+ ? `\n\n${fixturesMod.formatPrettyFixtureSummary(report.fixtureSummary, { color }).trimEnd()}`
811
+ : "";
812
+ const combined = (impact && impactMod ? `${impactMod.formatPrettyImpact(impact, { color }).trimEnd()}\n\n${reportText}` : reportText) +
813
+ fixtureBlock +
814
+ (cacheBypassNote ? `\n${cacheBypassNote}` : "");
815
+ process.stdout.write(scrubOutput(combined) + "\n");
253
816
  }
254
817
  else {
255
- emit(report);
818
+ const payload = scrubJsonValue({
819
+ ...report,
820
+ ...(cacheBypassedReason ? { cacheBypassedReason } : {}),
821
+ ...(impact ? { impact } : {}),
822
+ ...(sliceSummary ? { slices: sliceSummary } : {}),
823
+ ...(reportHtmlPath ? { reportHtmlPath } : {})
824
+ });
825
+ if (safeReproByIndex.size > 0 && Array.isArray(payload.results)) {
826
+ for (const [idx, repro] of safeReproByIndex) {
827
+ if (payload.results[idx]) {
828
+ payload.results[idx] = { ...payload.results[idx], repro };
829
+ }
830
+ }
831
+ }
832
+ process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
256
833
  }
257
834
  process.exitCode = report.gate.exitCode;
258
835
  }
836
+ async function cmdReport(flags) {
837
+ const [{ readContract, readHoldouts, readLastReport }, { redactHoldoutResult }, { redactSensitiveText }] = await Promise.all([import("./core/store.js"), import("./core/parity.js"), import("./core/security.js")]);
838
+ const contract = readContract(process.cwd());
839
+ const last = readLastReport(process.cwd());
840
+ if (!last) {
841
+ throw new VibecodeError("CONTRACT_NOT_FOUND", "No .vibecode/last-report.json yet. Run 'vibecode-anything verify' first.");
842
+ }
843
+ const resolveSafeReportOut = (flagName) => {
844
+ const raw = flags[flagName];
845
+ if (raw === undefined)
846
+ return undefined;
847
+ if (typeof raw !== "string" || !raw.trim()) {
848
+ throw new VibecodeError("CONTRACT_INVALID", `--${flagName} requires a non-empty file path.`);
849
+ }
850
+ const resolved = path.resolve(process.cwd(), raw.trim());
851
+ if (isInsideVaultDirectory(resolved)) {
852
+ throw new VibecodeError("CONTRACT_INVALID", `--${flagName} path must not point inside a holdout vault directory.`);
853
+ }
854
+ return resolved;
855
+ };
856
+ const outPath = resolveSafeReportOut("out");
857
+ const badgeOutPath = resolveSafeReportOut("badge");
858
+ const markdownOutPath = resolveSafeReportOut("markdown");
859
+ const sarifOutPath = resolveSafeReportOut("sarif");
860
+ const junitOutPath = resolveSafeReportOut("junit");
861
+ const holdoutById = loadHoldoutMap(readContract, readHoldouts, process.cwd());
862
+ const safeLast = sanitizeReportForDisplay(last, holdoutById, false, redactHoldoutResult, redactSensitiveText);
863
+ const safeContract = {
864
+ ...contract,
865
+ invariants: contract.invariants.filter((inv) => inv.holdout !== true && !holdoutById.has(inv.id)),
866
+ ...(Array.isArray(contract.slices)
867
+ ? {
868
+ slices: contract.slices.map((s) => ({
869
+ ...s,
870
+ invariantIds: s.invariantIds.filter((id) => !holdoutById.has(id))
871
+ }))
872
+ }
873
+ : {})
874
+ };
875
+ const safeContractName = redactSensitiveText(safeContract.target.name);
876
+ const noReport = flags["no-report"] === true;
877
+ let reportHtmlPath;
878
+ if (!noReport) {
879
+ const [{ writeHtmlReport }, { readRunHistory }] = await Promise.all([
880
+ import("./core/html-report.js"),
881
+ import("./core/run.js")
882
+ ]);
883
+ reportHtmlPath = writeHtmlReport(process.cwd(), {
884
+ contract: safeContract,
885
+ report: safeLast,
886
+ history: readRunHistory(process.cwd()),
887
+ workspaceDir: process.cwd(),
888
+ ...(outPath ? { outPath } : {})
889
+ });
890
+ }
891
+ const badgeMod = badgeOutPath || markdownOutPath ? await import("./core/badge.js") : null;
892
+ const badgeSvgPath = badgeOutPath && badgeMod ? badgeMod.writeParityBadgeSvg(badgeOutPath, safeLast) : undefined;
893
+ const markdownPath = markdownOutPath && badgeMod
894
+ ? badgeMod.writePrCommentMarkdown(markdownOutPath, safeLast, {
895
+ contractName: safeContractName,
896
+ ...(safeContract.slices?.length
897
+ ? { slices: (await import("./core/slices.js")).summarizeSlices(safeContract) }
898
+ : {}),
899
+ ...(reportHtmlPath ? { reportHtmlPath } : {}),
900
+ holdoutCount: holdoutById.size
901
+ })
902
+ : undefined;
903
+ const ciFormatsMod = sarifOutPath || junitOutPath ? await import("./core/ci-formats.js") : null;
904
+ const sarifPath = sarifOutPath && ciFormatsMod
905
+ ? ciFormatsMod.writeSarifReport(safeLast, sarifOutPath, {
906
+ contractName: safeContractName,
907
+ toolVersion: VERSION
908
+ })
909
+ : undefined;
910
+ const junitPath = junitOutPath && ciFormatsMod
911
+ ? ciFormatsMod.writeJunitXml(safeLast, junitOutPath, {
912
+ suiteName: safeContractName
913
+ })
914
+ : undefined;
915
+ emit({
916
+ ok: true,
917
+ command: "report",
918
+ ...(reportHtmlPath ? { reportHtmlPath } : {}),
919
+ ...(badgeSvgPath ? { badgeSvgPath } : {}),
920
+ ...(markdownPath ? { markdownPath } : {}),
921
+ ...(sarifPath ? { sarifPath } : {}),
922
+ ...(junitPath ? { junitPath } : {}),
923
+ gate: safeLast.gate
924
+ });
925
+ }
926
+ async function cmdRun(flags) {
927
+ let mode;
928
+ let concurrency;
929
+ let pluginRegistry;
930
+ let rt;
931
+ try {
932
+ mode = await parseVerifyModeFlag(flags);
933
+ concurrency = await parseConcurrencyFlag(flags);
934
+ ({ pluginRegistry } = await loadCliPluginRegistry(flags));
935
+ rt = parseRuntimeTargetFlags(flags);
936
+ }
937
+ catch (err) {
938
+ fail(err, errorCode(err) === "CONFIG_INVALID" ? 2 : 1);
939
+ return;
940
+ }
941
+ requireTargetOrMap(rt, "run");
942
+ const headers = parseHeaderFlags(flags);
943
+ const storageState = parseFileFlag(flags, "storage-state");
944
+ let maxIterations;
945
+ if (flags["max-iterations"] !== undefined) {
946
+ if (typeof flags["max-iterations"] !== "string" || !/^\d+$/.test(flags["max-iterations"].trim())) {
947
+ throw new VibecodeError("CONTRACT_INVALID", "--max-iterations must be a positive integer.");
948
+ }
949
+ maxIterations = Number.parseInt(flags["max-iterations"].trim(), 10);
950
+ if (!Number.isInteger(maxIterations) || maxIterations < 1) {
951
+ throw new VibecodeError("CONTRACT_INVALID", "--max-iterations must be a positive integer.");
952
+ }
953
+ }
954
+ let maxMinutes;
955
+ if (flags["max-minutes"] !== undefined) {
956
+ if (typeof flags["max-minutes"] !== "string" || !flags["max-minutes"].trim()) {
957
+ throw new VibecodeError("CONTRACT_INVALID", "--max-minutes must be a positive number.");
958
+ }
959
+ maxMinutes = Number(flags["max-minutes"].trim());
960
+ if (!Number.isFinite(maxMinutes) || maxMinutes <= 0) {
961
+ throw new VibecodeError("CONTRACT_INVALID", "--max-minutes must be a positive number.");
962
+ }
963
+ }
964
+ let agent = "auto";
965
+ if (flags.agent !== undefined) {
966
+ if (typeof flags.agent !== "string" || !flags.agent.trim()) {
967
+ throw new VibecodeError("CONTRACT_INVALID", "--agent requires a non-empty agent specification.");
968
+ }
969
+ agent = flags.agent.trim();
970
+ }
971
+ const sliceIds = splitCsvFlags(flagList(flags, "slice"));
972
+ const { runClosedLoop } = await import("./core/run.js");
973
+ let result;
974
+ try {
975
+ result = await runClosedLoop({
976
+ ...(rt.target ? { target: rt.target } : {}),
977
+ ...(rt.targets ? { targets: rt.targets } : {}),
978
+ ...(rt.vars ? { vars: rt.vars } : {}),
979
+ ...(mode ? { mode } : {}),
980
+ ...(concurrency !== undefined ? { concurrency } : {}),
981
+ ...(pluginRegistry ? { pluginRegistry } : {}),
982
+ ...(flags["no-fixtures"] === true ? { skipFixtures: true } : {}),
983
+ ...(flags["allow-fixture-commands"] === true ? { allowFixtureCommands: true } : {}),
984
+ cwd: process.cwd(),
985
+ ...(typeof flags.source === "string" && flags.source.trim() ? { source: flags.source.trim() } : {}),
986
+ ...(typeof flags.domain === "string" && flags.domain.trim() ? { domain: flags.domain.trim() } : {}),
987
+ agent,
988
+ ...(maxIterations !== undefined ? { maxIterations } : {}),
989
+ ...(maxMinutes !== undefined ? { maxMinutes } : {}),
990
+ ...(sliceIds.length > 0 ? { sliceIds } : {}),
991
+ strict: flags.strict === true,
992
+ dryRun: flags["dry-run"] === true,
993
+ forceIngest: flags.force === true,
994
+ ...(flags.cache === true ? { useCache: true } : {}),
995
+ ...(headers !== undefined ? { headers } : {}),
996
+ ...(storageState !== undefined ? { storageState } : {})
997
+ });
998
+ }
999
+ catch (err) {
1000
+ if (errorCode(err) === "CONFIG_INVALID") {
1001
+ fail(err, 2);
1002
+ return;
1003
+ }
1004
+ throw err;
1005
+ }
1006
+ let reportHtmlPath;
1007
+ if (!result.dryRun && flags["no-report"] !== true && result.finalReport) {
1008
+ const [{ readContractWithHoldouts }, { writeHtmlReport }] = await Promise.all([
1009
+ import("./core/store.js"),
1010
+ import("./core/html-report.js")
1011
+ ]);
1012
+ const contractWithHoldouts = readContractWithHoldouts(process.cwd());
1013
+ reportHtmlPath = writeHtmlReport(process.cwd(), {
1014
+ contract: contractWithHoldouts,
1015
+ report: result.finalReport,
1016
+ history: result.iterations,
1017
+ workspaceDir: process.cwd()
1018
+ });
1019
+ }
1020
+ if (flags.pretty === true) {
1021
+ const { formatPrettyRun } = await import("./core/format.js");
1022
+ process.stdout.write(scrubOutput(formatPrettyRun(result, {
1023
+ ...(reportHtmlPath ? { reportHtmlPath } : {}),
1024
+ color: Boolean(process.stdout.isTTY)
1025
+ })) + "\n");
1026
+ }
1027
+ else {
1028
+ emit({
1029
+ command: "run",
1030
+ ...result,
1031
+ ...(reportHtmlPath ? { reportHtmlPath } : {})
1032
+ });
1033
+ }
1034
+ process.exitCode = result.ok ? 0 : result.stoppedReason === "adapter_missing" ? 2 : 1;
1035
+ }
259
1036
  async function cmdWatch(flags) {
260
- const target = flags.target;
261
- if (typeof target !== "string" || !target.trim()) {
262
- throw new VibecodeError("TARGET_MISSING", "Missing --target \"<command-or-url>\" for watch.");
1037
+ let mode;
1038
+ let concurrency;
1039
+ let pluginRegistry;
1040
+ let rt;
1041
+ try {
1042
+ mode = await parseVerifyModeFlag(flags);
1043
+ concurrency = await parseConcurrencyFlag(flags);
1044
+ ({ pluginRegistry } = await loadCliPluginRegistry(flags));
1045
+ rt = parseRuntimeTargetFlags(flags);
1046
+ }
1047
+ catch (err) {
1048
+ fail(err, errorCode(err) === "CONFIG_INVALID" ? 2 : 1);
1049
+ return;
263
1050
  }
1051
+ requireTargetOrMap(rt, "watch");
264
1052
  let debounceMs;
265
1053
  if (flags.debounce !== undefined) {
266
1054
  if (typeof flags.debounce !== "string" || !flags.debounce.trim()) {
@@ -274,22 +1062,40 @@ async function cmdWatch(flags) {
274
1062
  const sliceIds = splitCsvFlags(flagList(flags, "slice"));
275
1063
  const invariantIds = flagList(flags, "invariant").filter((x) => typeof x === "string");
276
1064
  const watchPaths = flagList(flags, "watch-path").filter((x) => typeof x === "string");
1065
+ const headers = parseHeaderFlags(flags);
1066
+ const storageState = parseFileFlag(flags, "storage-state");
1067
+ const usePretty = flags.pretty === true;
1068
+ const { startWatch, formatWatchEvent, formatPrettyWatchEvent } = await import("./core/watch.js");
277
1069
  const controller = new AbortController();
278
1070
  const stop = () => controller.abort();
279
1071
  process.on("SIGINT", stop);
280
1072
  process.on("SIGTERM", stop);
281
1073
  try {
282
1074
  const handle = await startWatch({
283
- target,
1075
+ ...(rt.target ? { target: rt.target } : {}),
1076
+ ...(rt.targets ? { targets: rt.targets } : {}),
1077
+ ...(rt.vars ? { vars: rt.vars } : {}),
1078
+ ...(mode ? { mode } : {}),
1079
+ ...(concurrency !== undefined ? { concurrency } : {}),
1080
+ ...(pluginRegistry ? { pluginRegistry } : {}),
1081
+ ...(flags.smart === true ? { smart: true } : {}),
284
1082
  cwd: process.cwd(),
285
1083
  ...(watchPaths.length > 0 ? { watchPaths } : {}),
286
1084
  ...(debounceMs !== undefined ? { debounceMs } : {}),
287
1085
  strict: flags.strict === true,
1086
+ ...(flags.cache === true ? { useCache: true } : {}),
1087
+ ...(headers !== undefined ? { headers } : {}),
1088
+ ...(storageState !== undefined ? { storageState } : {}),
1089
+ ...(flags["no-fixtures"] === true ? { skipFixtures: true } : {}),
1090
+ ...(flags["allow-fixture-commands"] === true ? { allowFixtureCommands: true } : {}),
288
1091
  ...(sliceIds.length > 0 ? { sliceIds } : {}),
289
1092
  ...(invariantIds.length > 0 ? { invariantIds } : {}),
290
1093
  signal: controller.signal,
291
1094
  onRun: (event) => {
292
- process.stdout.write(formatWatchEvent(event) + "\n");
1095
+ const line = usePretty
1096
+ ? formatPrettyWatchEvent(event, { color: Boolean(process.stdout.isTTY), ...(rt.vars ? { vars: rt.vars } : {}) })
1097
+ : formatWatchEvent(event, rt.vars ? { vars: rt.vars } : {});
1098
+ process.stdout.write(scrubOutput(line) + "\n");
293
1099
  process.exitCode = event.report.gate.exitCode;
294
1100
  },
295
1101
  onError: (err) => {
@@ -304,6 +1110,7 @@ async function cmdWatch(flags) {
304
1110
  }
305
1111
  }
306
1112
  async function cmdDoctor(flags) {
1113
+ const { formatPrettyDoctor, runDoctor } = await import("./core/doctor.js");
307
1114
  const scope = typeof flags.scope === "string" ? flags.scope : "project";
308
1115
  const antigravityDir = typeof flags["antigravity-dir"] === "string" ? flags["antigravity-dir"] : undefined;
309
1116
  const strict = flags.strict === true;
@@ -313,10 +1120,20 @@ async function cmdDoctor(flags) {
313
1120
  ...(antigravityDir ? { antigravityDir } : {}),
314
1121
  strict
315
1122
  });
316
- emit(report);
1123
+ if (flags.pretty === true) {
1124
+ process.stdout.write(formatPrettyDoctor(report, { color: Boolean(process.stdout.isTTY) }) + "\n");
1125
+ }
1126
+ else {
1127
+ emit(report);
1128
+ }
317
1129
  process.exitCode = report.exitCode;
318
1130
  }
319
- async function cmdStatus() {
1131
+ async function cmdStatus(flags = {}) {
1132
+ const [{ readContract, readHoldouts, readLastReport }, { probeAdapters }, { summarizeSlices }] = await Promise.all([
1133
+ import("./core/store.js"),
1134
+ import("./core/adapters.js"),
1135
+ import("./core/slices.js")
1136
+ ]);
320
1137
  let contract = null;
321
1138
  try {
322
1139
  contract = readContract(process.cwd());
@@ -327,9 +1144,31 @@ async function cmdStatus() {
327
1144
  }
328
1145
  const adapters = await probeAdapters();
329
1146
  const last = readLastReport(process.cwd());
330
- const hard = contract ? contract.invariants.filter((i) => i.severity === "hard").length : 0;
331
- const soft = contract ? contract.invariants.filter((i) => i.severity === "soft").length : 0;
332
- emit({
1147
+ const holdouts = contract ? readHoldouts(process.cwd()) : [];
1148
+ const allInvs = contract ? [...contract.invariants, ...holdouts] : [];
1149
+ const hard = allInvs.filter((i) => i.severity === "hard").length;
1150
+ const soft = allInvs.filter((i) => i.severity === "soft").length;
1151
+ let trendsMod = null;
1152
+ let trends;
1153
+ if (flags.trends === true) {
1154
+ trendsMod = await import("./diagnostics/trends.js");
1155
+ const holdoutIds = new Set(holdouts.map((h) => h.id));
1156
+ if (contract) {
1157
+ for (const inv of contract.invariants) {
1158
+ if (inv.holdout === true)
1159
+ holdoutIds.add(inv.id);
1160
+ }
1161
+ }
1162
+ const rawTrendEntries = trendsMod.readTrendEntries(process.cwd());
1163
+ const safeTrendEntries = holdoutIds.size > 0
1164
+ ? rawTrendEntries.map((entry) => ({
1165
+ ...entry,
1166
+ visibleInvariants: entry.visibleInvariants.filter((s) => !holdoutIds.has(s.id))
1167
+ }))
1168
+ : rawTrendEntries;
1169
+ trends = trendsMod.analyzeTrends(safeTrendEntries);
1170
+ }
1171
+ const statusPayload = {
333
1172
  ok: true,
334
1173
  command: "status",
335
1174
  contract: contract
@@ -339,7 +1178,8 @@ async function cmdStatus() {
339
1178
  name: contract.target.name,
340
1179
  domains: contract.target.domains,
341
1180
  sources: contract.target.sources,
342
- invariants: contract.invariants.length,
1181
+ invariants: allInvs.length,
1182
+ holdouts: holdouts.length,
343
1183
  hard,
344
1184
  soft,
345
1185
  thresholds: contract.thresholds,
@@ -357,17 +1197,174 @@ async function cmdStatus() {
357
1197
  parity: last.parity,
358
1198
  nextAction: last.nextAction
359
1199
  }
360
- : null
361
- });
1200
+ : null,
1201
+ ...(trends ? { trends } : {})
1202
+ };
1203
+ if (flags.pretty === true) {
1204
+ const { formatPrettyStatus } = await import("./core/format.js");
1205
+ const color = Boolean(process.stdout.isTTY);
1206
+ const statusText = formatPrettyStatus(statusPayload, { color }).trimEnd();
1207
+ const combined = trends && trendsMod
1208
+ ? `${statusText}\n\n${trendsMod.formatPrettyTrends(trends, { color }).trimEnd()}`
1209
+ : statusText;
1210
+ process.stdout.write(combined + "\n");
1211
+ return;
1212
+ }
1213
+ emit(statusPayload);
1214
+ }
1215
+ function loadHoldoutMap(readContractFn, readHoldoutsFn, cwd) {
1216
+ let contract = null;
1217
+ try {
1218
+ contract = readContractFn(cwd);
1219
+ }
1220
+ catch (err) {
1221
+ if (errorCode(err) !== "CONTRACT_NOT_FOUND")
1222
+ throw err;
1223
+ }
1224
+ const holdouts = readHoldoutsFn(cwd);
1225
+ const holdoutById = new Map();
1226
+ for (const h of holdouts)
1227
+ holdoutById.set(h.id, h);
1228
+ if (contract) {
1229
+ for (const inv of contract.invariants) {
1230
+ if (inv.holdout === true && !holdoutById.has(inv.id))
1231
+ holdoutById.set(inv.id, inv);
1232
+ }
1233
+ }
1234
+ return holdoutById;
1235
+ }
1236
+ function sanitizeDiffResult(result, holdoutById, revealHoldouts, redactHoldoutResultFn, redactSensitiveTextFn) {
1237
+ if (revealHoldouts)
1238
+ return sanitizeReportResult(result);
1239
+ const holdoutInv = holdoutById.get(result.id);
1240
+ const isHoldout = Boolean(holdoutInv) || isHoldoutResultRecord(result);
1241
+ if (!isHoldout)
1242
+ return sanitizeReportResult(result);
1243
+ if (result.status === "pass" || result.status === "skipped") {
1244
+ return {
1245
+ id: result.id,
1246
+ type: result.type,
1247
+ severity: result.severity,
1248
+ status: result.status,
1249
+ score: result.score,
1250
+ metrics: { redacted: true, holdout: true },
1251
+ ...(result.durationMs !== undefined ? { durationMs: result.durationMs } : {})
1252
+ };
1253
+ }
1254
+ if (holdoutInv && (result.status === "fail" || result.status === "error")) {
1255
+ const redacted = redactHoldoutResultFn({ ...holdoutInv, holdout: true }, result, false);
1256
+ const firstFailure = Array.isArray(redacted.failures) && typeof redacted.failures[0] === "string" ? redacted.failures[0] : "";
1257
+ const safeFailures = firstFailure && !/\[REDACTED_VAULT(?:_PATH)?\]/.test(firstFailure)
1258
+ ? [firstFailure]
1259
+ : ["Holdout invariant failed (expected details redacted)"];
1260
+ return {
1261
+ ...redacted,
1262
+ failures: safeFailures,
1263
+ metrics: { ...(redacted.metrics ?? {}), redacted: true, holdout: true }
1264
+ };
1265
+ }
1266
+ const rawHint = holdoutInv && typeof holdoutInv.holdoutHint === "string"
1267
+ ? redactSensitiveTextFn(holdoutInv.holdoutHint).trim()
1268
+ : "";
1269
+ const safeHint = rawHint && !/\[REDACTED_VAULT(?:_PATH)?\]/.test(rawHint) ? rawHint : "";
1270
+ const safeFailures = safeHint
1271
+ ? [safeHint]
1272
+ : result.metrics?.redacted === true &&
1273
+ Array.isArray(result.failures) &&
1274
+ typeof result.failures[0] === "string" &&
1275
+ result.failures[0].trim() &&
1276
+ !/\.vibecode-vault|holdouts?(?:-[a-f0-9]+)?\.json/i.test(result.failures[0]) &&
1277
+ !/\[REDACTED_VAULT(?:_PATH)?\]/.test(redactSensitiveTextFn(result.failures[0].trim()))
1278
+ ? [redactSensitiveTextFn(result.failures[0].trim())]
1279
+ : ["Holdout invariant failed (expected details redacted)"];
1280
+ return {
1281
+ id: result.id,
1282
+ type: result.type,
1283
+ severity: result.severity,
1284
+ status: result.status,
1285
+ score: result.status === "warn" ? result.score : 0,
1286
+ failures: safeFailures,
1287
+ metrics: {
1288
+ ...(result.metrics?.exitCode !== undefined ? { exitCode: result.metrics.exitCode } : {}),
1289
+ redacted: true,
1290
+ holdout: true
1291
+ },
1292
+ ...(result.durationMs !== undefined ? { durationMs: result.durationMs } : {})
1293
+ };
362
1294
  }
363
- function cmdDiff(flags) {
1295
+ function sanitizeReportForDisplay(report, holdoutById, revealHoldouts, redactHoldoutResultFn, redactSensitiveTextFn) {
1296
+ return {
1297
+ ...report,
1298
+ ...(typeof report.timestamp === "string" ? { timestamp: redactSensitiveTextFn(report.timestamp) } : {}),
1299
+ ...(report.gate
1300
+ ? {
1301
+ gate: {
1302
+ ...report.gate,
1303
+ reasons: Array.isArray(report.gate.reasons)
1304
+ ? report.gate.reasons.map((r) => redactSensitiveTextFn(r))
1305
+ : report.gate.reasons
1306
+ }
1307
+ }
1308
+ : {}),
1309
+ ...(report.antiCheat
1310
+ ? {
1311
+ antiCheat: {
1312
+ ...report.antiCheat,
1313
+ reasons: Array.isArray(report.antiCheat.reasons)
1314
+ ? report.antiCheat.reasons.map((r) => redactSensitiveTextFn(r))
1315
+ : report.antiCheat.reasons
1316
+ }
1317
+ }
1318
+ : {}),
1319
+ results: (report.results || []).map((r) => sanitizeDiffResult(r, holdoutById, revealHoldouts, redactHoldoutResultFn, redactSensitiveTextFn))
1320
+ };
1321
+ }
1322
+ async function cmdDiff(flags) {
1323
+ const [{ readContract, readHoldouts, readLastReport }, { redactHoldoutResult }, { redactSensitiveText }] = await Promise.all([import("./core/store.js"), import("./core/parity.js"), import("./core/security.js")]);
364
1324
  const last = readLastReport(process.cwd());
365
1325
  if (!last) {
366
1326
  throw new VibecodeError("CONTRACT_NOT_FOUND", "No .vibecode/last-report.json yet. Run 'vibecode-anything verify' first.");
367
1327
  }
1328
+ const revealHoldouts = flags["reveal-holdouts"] === true;
1329
+ const holdoutById = loadHoldoutMap(readContract, readHoldouts, process.cwd());
1330
+ const sanitizeReport = (rep) => sanitizeReportForDisplay(rep, holdoutById, revealHoldouts, redactHoldoutResult, redactSensitiveText);
1331
+ const baselinePath = parseFileFlag(flags, "baseline");
1332
+ if (baselinePath) {
1333
+ let parsedBaseline;
1334
+ try {
1335
+ parsedBaseline = JSON.parse(fs.readFileSync(baselinePath, "utf8"));
1336
+ }
1337
+ catch (err) {
1338
+ throw new VibecodeError("CONTRACT_INVALID", `Invalid --baseline report JSON (${baselinePath}): ${err?.message ?? String(err)}`);
1339
+ }
1340
+ if (!isPlainObjectSafe(parsedBaseline) ||
1341
+ (!Array.isArray(parsedBaseline.results) && !isPlainObjectSafe(parsedBaseline.gate))) {
1342
+ throw new VibecodeError("CONTRACT_INVALID", `--baseline file must contain a ParityReport JSON object with "results" or "gate": ${baselinePath}`);
1343
+ }
1344
+ const { compareReports, formatPrettyRegression } = await import("./core/regression.js");
1345
+ const safeBaseline = sanitizeReport(parsedBaseline);
1346
+ const safeLast = sanitizeReport(last);
1347
+ const comparison = compareReports(safeBaseline, safeLast, {
1348
+ strict: flags.strict === true
1349
+ });
1350
+ if (flags.pretty === true) {
1351
+ process.stdout.write(formatPrettyRegression(comparison, { color: Boolean(process.stdout.isTTY) }) + "\n");
1352
+ }
1353
+ else {
1354
+ emit({ command: "diff", ...comparison });
1355
+ }
1356
+ process.exitCode = comparison.regressed ? 1 : 0;
1357
+ return;
1358
+ }
368
1359
  const id = flags.invariant || flags.id;
369
1360
  if (!id || id === true) {
370
- emit(last);
1361
+ const sanitizedReport = sanitizeReport(last);
1362
+ if (flags.pretty === true) {
1363
+ const { formatPrettyDiff } = await import("./core/format.js");
1364
+ process.stdout.write(formatPrettyDiff(sanitizedReport, { color: Boolean(process.stdout.isTTY) }) + "\n");
1365
+ return;
1366
+ }
1367
+ emit(sanitizedReport);
371
1368
  return;
372
1369
  }
373
1370
  const result = (last.results || []).find((r) => r.id === id);
@@ -376,27 +1373,1055 @@ function cmdDiff(flags) {
376
1373
  process.exitCode = 2;
377
1374
  return;
378
1375
  }
379
- emit(result);
1376
+ const sanitized = sanitizeDiffResult(result, holdoutById, revealHoldouts, redactHoldoutResult, redactSensitiveText);
1377
+ if (flags.pretty === true) {
1378
+ const { formatPrettyDiff } = await import("./core/format.js");
1379
+ process.stdout.write(formatPrettyDiff(sanitized, { color: Boolean(process.stdout.isTTY) }) + "\n");
1380
+ return;
1381
+ }
1382
+ emit(sanitized);
1383
+ }
1384
+ function formatLintStrengthBanner(lintOk, strengthOk, exitCode, color) {
1385
+ const combinedOk = lintOk && strengthOk;
1386
+ const label = combinedOk ? "PASS" : "FAIL";
1387
+ const detail = combinedOk
1388
+ ? `exit ${exitCode}`
1389
+ : lintOk && !strengthOk
1390
+ ? `lint passed, strength audit failed; exit ${exitCode}`
1391
+ : !lintOk && strengthOk
1392
+ ? `lint failed, strength audit passed; exit ${exitCode}`
1393
+ : `lint and strength audit failed; exit ${exitCode}`;
1394
+ if (!color)
1395
+ return `Combined Gate: ${label} (${detail})`;
1396
+ const badge = styleAnsi(label, `${ANSI.bold}${combinedOk ? ANSI.green : ANSI.red}`, color);
1397
+ return `${styleAnsi("Combined Gate:", ANSI.bold, color)} ${badge} (${detail})`;
1398
+ }
1399
+ async function cmdLint(flags) {
1400
+ const [{ readHoldouts, readRawContract }, { lintContract, formatPrettyLint }] = await Promise.all([
1401
+ import("./core/store.js"),
1402
+ import("./core/lint.js")
1403
+ ]);
1404
+ let rawContract;
1405
+ try {
1406
+ rawContract = readRawContract(process.cwd());
1407
+ }
1408
+ catch (err) {
1409
+ if (err instanceof VibecodeError)
1410
+ throw err;
1411
+ throw new VibecodeError("CONTRACT_INVALID", `Failed to parse .vibecode/contract.json: ${err?.message ?? String(err)}`);
1412
+ }
1413
+ const strict = flags.strict === true;
1414
+ const report = lintContract(rawContract, { strict });
1415
+ let strength;
1416
+ let auditMod = null;
1417
+ if (flags.strength === true) {
1418
+ const [{ normalizeContract }, mod] = await Promise.all([
1419
+ import("./core/schema.js"),
1420
+ import("./diagnostics/mutation-audit.js")
1421
+ ]);
1422
+ auditMod = mod;
1423
+ let contractForAudit = rawContract;
1424
+ try {
1425
+ if (isPlainObjectSafe(rawContract) && Array.isArray(rawContract.invariants)) {
1426
+ contractForAudit = normalizeContract(rawContract);
1427
+ }
1428
+ }
1429
+ catch {
1430
+ contractForAudit = rawContract;
1431
+ }
1432
+ strength = auditMod.auditContractStrength(contractForAudit, {
1433
+ strict,
1434
+ holdoutCount: readHoldouts(process.cwd()).length
1435
+ });
1436
+ }
1437
+ const combinedOk = strength ? report.ok && strength.ok : report.ok;
1438
+ const combinedExitCode = strength ? (combinedOk ? 0 : 1) : report.exitCode;
1439
+ if (flags.pretty === true) {
1440
+ const color = Boolean(process.stdout.isTTY);
1441
+ const lintText = formatPrettyLint(report, { color });
1442
+ if (strength && auditMod) {
1443
+ const strengthText = auditMod.formatPrettyMutationAudit(strength, { color }).trimEnd();
1444
+ const banner = formatLintStrengthBanner(report.ok, strength.ok, combinedExitCode, color);
1445
+ process.stdout.write(`${lintText}\n\n${strengthText}\n\n${banner}\n`);
1446
+ }
1447
+ else {
1448
+ process.stdout.write(`${lintText}\n`);
1449
+ }
1450
+ }
1451
+ else {
1452
+ emit({
1453
+ command: "lint",
1454
+ ...report,
1455
+ ...(strength ? { ok: combinedOk, exitCode: combinedExitCode, strength } : {})
1456
+ });
1457
+ }
1458
+ process.exitCode = combinedExitCode;
1459
+ }
1460
+ const EXAMPLE_SPEC_PATH_RE = /^(?:examples?|samples?|demos?|docs|tests?|__tests__|fixtures?|benchmarks?)\//i;
1461
+ const LOCK_SPEC_PRIORITY = {
1462
+ openapi: 0,
1463
+ asyncapi: 1,
1464
+ openrpc: 2,
1465
+ proto: 3,
1466
+ graphql: 4,
1467
+ postman: 5,
1468
+ insomnia: 6,
1469
+ bruno: 7,
1470
+ "http-file": 8
1471
+ };
1472
+ function isExistingWorkspaceFile(cwd, relPath, allowDir = false) {
1473
+ try {
1474
+ const st = fs.statSync(path.resolve(cwd, relPath));
1475
+ return st.isFile() || (allowDir && st.isDirectory());
1476
+ }
1477
+ catch {
1478
+ return false;
1479
+ }
1480
+ }
1481
+ function buildLockDiscoverHint(cwd, report, explicitDomain, explicitTarget) {
1482
+ const entryFiles = [];
1483
+ const seen = new Set();
1484
+ const addFile = (rel) => {
1485
+ if (!rel || seen.has(rel) || entryFiles.length >= 25)
1486
+ return;
1487
+ seen.add(rel);
1488
+ entryFiles.push(rel);
1489
+ };
1490
+ for (const ep of report.entrypoints)
1491
+ addFile(ep.path);
1492
+ for (const sp of report.specs)
1493
+ addFile(sp.path);
1494
+ for (const mf of report.manifests)
1495
+ addFile(mf.path);
1496
+ const baseHint = {
1497
+ name: report.projectName,
1498
+ ...(entryFiles.length > 0 ? { entryFiles } : {})
1499
+ };
1500
+ const cliEntry = report.entrypoints.find((e) => e.kind === "cli" && typeof e.path === "string" && isExistingWorkspaceFile(cwd, e.path));
1501
+ const repoEntry = report.entrypoints.find((e) => e.kind === "repo" && typeof e.path === "string" && isExistingWorkspaceFile(cwd, e.path));
1502
+ const lockableSpecs = report.specs
1503
+ .filter((s) => s.kind !== "har" && isExistingWorkspaceFile(cwd, s.path, s.kind === "bruno"))
1504
+ .sort((a, b) => {
1505
+ const aEx = EXAMPLE_SPEC_PATH_RE.test(a.path) ? 1 : 0;
1506
+ const bEx = EXAMPLE_SPEC_PATH_RE.test(b.path) ? 1 : 0;
1507
+ if (aEx !== bEx)
1508
+ return aEx - bEx;
1509
+ const pa = LOCK_SPEC_PRIORITY[a.kind] ?? 9;
1510
+ const pb = LOCK_SPEC_PRIORITY[b.kind] ?? 9;
1511
+ if (pa !== pb)
1512
+ return pa - pb;
1513
+ return a.path.localeCompare(b.path);
1514
+ });
1515
+ const primarySpec = lockableSpecs.find((s) => !EXAMPLE_SPEC_PATH_RE.test(s.path));
1516
+ const fallbackSpec = lockableSpecs[0];
1517
+ const isHttpTarget = typeof explicitTarget === "string" && /^https?:\/\//i.test(explicitTarget.trim());
1518
+ if (explicitDomain) {
1519
+ if (explicitDomain === "cli" || explicitDomain === "script") {
1520
+ if (cliEntry) {
1521
+ const cmd = cliEntry.command ?? `node ${cliEntry.path}`;
1522
+ return { ...baseHint, domain: explicitDomain, source: cmd, target: cmd };
1523
+ }
1524
+ return baseHint;
1525
+ }
1526
+ if (explicitDomain === "repo") {
1527
+ if (repoEntry) {
1528
+ return { ...baseHint, domain: "repo", source: cwd, target: cwd };
1529
+ }
1530
+ return baseHint;
1531
+ }
1532
+ if (explicitDomain === "api" ||
1533
+ explicitDomain === "graphql" ||
1534
+ explicitDomain === "postman" ||
1535
+ explicitDomain === "http-file" ||
1536
+ explicitDomain === "insomnia" ||
1537
+ explicitDomain === "bruno" ||
1538
+ explicitDomain === "asyncapi" ||
1539
+ explicitDomain === "proto" ||
1540
+ explicitDomain === "openrpc") {
1541
+ const matchedSpec = explicitDomain === "api"
1542
+ ? (primarySpec ?? fallbackSpec)
1543
+ : lockableSpecs.find((s) => s.ingestDomain === explicitDomain);
1544
+ if (matchedSpec) {
1545
+ return { ...baseHint, domain: matchedSpec.ingestDomain, source: path.resolve(cwd, matchedSpec.path) };
1546
+ }
1547
+ return baseHint;
1548
+ }
1549
+ return baseHint;
1550
+ }
1551
+ if (isHttpTarget) {
1552
+ if (primarySpec) {
1553
+ return { ...baseHint, domain: primarySpec.ingestDomain, source: path.resolve(cwd, primarySpec.path) };
1554
+ }
1555
+ return baseHint;
1556
+ }
1557
+ if (cliEntry) {
1558
+ const cmd = cliEntry.command ?? `node ${cliEntry.path}`;
1559
+ return { ...baseHint, domain: "cli", source: cmd, target: cmd };
1560
+ }
1561
+ if (primarySpec) {
1562
+ return { ...baseHint, domain: primarySpec.ingestDomain, source: path.resolve(cwd, primarySpec.path) };
1563
+ }
1564
+ if (repoEntry) {
1565
+ return { ...baseHint, domain: "repo", source: cwd, target: cwd };
1566
+ }
1567
+ if (fallbackSpec) {
1568
+ return { ...baseHint, domain: fallbackSpec.ingestDomain, source: path.resolve(cwd, fallbackSpec.path) };
1569
+ }
1570
+ return baseHint;
1571
+ }
1572
+ function parseOptionalStringFlag(flags, flagName) {
1573
+ const raw = flags[flagName];
1574
+ if (raw === undefined)
1575
+ return undefined;
1576
+ if (typeof raw !== "string" || !raw.trim()) {
1577
+ throw new VibecodeError("CONTRACT_INVALID", `--${flagName} requires a non-empty value.`);
1578
+ }
1579
+ return raw.trim();
1580
+ }
1581
+ async function cmdDiscover(flags, positionals) {
1582
+ let rawDir = process.cwd();
1583
+ if (flags.dir !== undefined) {
1584
+ if (typeof flags.dir !== "string" || !flags.dir.trim() || flags.dir.includes("\0")) {
1585
+ fail(new VibecodeError("CONFIG_INVALID", "--dir requires a valid non-empty directory path."), 2);
1586
+ return;
1587
+ }
1588
+ rawDir = flags.dir.trim();
1589
+ }
1590
+ else if (positionals[0] !== undefined) {
1591
+ if (!positionals[0].trim() || positionals[0].includes("\0")) {
1592
+ fail(new VibecodeError("CONFIG_INVALID", "Discovery directory path must be a valid non-empty path."), 2);
1593
+ return;
1594
+ }
1595
+ rawDir = positionals[0].trim();
1596
+ }
1597
+ const targetDir = path.resolve(process.cwd(), rawDir);
1598
+ let stat;
1599
+ try {
1600
+ stat = fs.statSync(targetDir);
1601
+ }
1602
+ catch {
1603
+ fail(new VibecodeError("NOT_FOUND", `Discovery directory not found: ${targetDir}`), 2);
1604
+ return;
1605
+ }
1606
+ if (!stat.isDirectory()) {
1607
+ fail(new VibecodeError("CONFIG_INVALID", `Discovery path is not a directory: ${targetDir}`), 2);
1608
+ return;
1609
+ }
1610
+ const { discoverProject, formatPrettyDiscovery } = await import("./discovery/discover.js");
1611
+ const report = discoverProject(targetDir);
1612
+ if (flags.pretty === true) {
1613
+ process.stdout.write(formatPrettyDiscovery(report, { color: Boolean(process.stdout.isTTY) }) + "\n");
1614
+ }
1615
+ else {
1616
+ emit(report);
1617
+ }
1618
+ }
1619
+ async function cmdLock(flags) {
1620
+ const cwd = process.cwd();
1621
+ if (flags.check === true) {
1622
+ const { checkLockStatus, formatPrettyLockCheck } = await import("./discovery/lock.js");
1623
+ const status = checkLockStatus(cwd);
1624
+ if (flags.pretty === true) {
1625
+ process.stdout.write(formatPrettyLockCheck(status, { color: Boolean(process.stdout.isTTY) }) + "\n");
1626
+ }
1627
+ else {
1628
+ emit(status);
1629
+ }
1630
+ process.exitCode = !status.exists ? 2 : status.valid && !status.contractTampered ? 0 : 1;
1631
+ return;
1632
+ }
1633
+ const source = parseOptionalStringFlag(flags, "source");
1634
+ const domain = parseOptionalStringFlag(flags, "domain");
1635
+ const target = parseOptionalStringFlag(flags, "target");
1636
+ const name = parseOptionalStringFlag(flags, "name");
1637
+ const baseUrl = parseOptionalStringFlag(flags, "base-url");
1638
+ const env = parseEnvFlags(flags);
1639
+ const headers = parseHeaderFlags(flags);
1640
+ const storageState = parseFileFlag(flags, "storage-state");
1641
+ const fsDiff = flags["fs-diff"] === true;
1642
+ const probes = flagList(flags, "probe").filter((p) => typeof p === "string");
1643
+ if (flags.probes !== undefined) {
1644
+ const probesFile = parseFileFlag(flags, "probes");
1645
+ let parsed;
1646
+ try {
1647
+ parsed = JSON.parse(fs.readFileSync(probesFile, "utf8"));
1648
+ }
1649
+ catch (err) {
1650
+ throw new VibecodeError("CONTRACT_INVALID", `Invalid JSON in --probes file: ${err?.message ?? String(err)}`);
1651
+ }
1652
+ if (!Array.isArray(parsed))
1653
+ throw new VibecodeError("CONTRACT_INVALID", "--probes file must contain a JSON array");
1654
+ for (const p of parsed)
1655
+ probes.push(p);
1656
+ }
1657
+ const routes = flagList(flags, "route").filter((r) => typeof r === "string");
1658
+ let endpoints;
1659
+ if (flags.endpoints !== undefined) {
1660
+ const endpointsFile = parseFileFlag(flags, "endpoints");
1661
+ let parsed;
1662
+ try {
1663
+ parsed = JSON.parse(fs.readFileSync(endpointsFile, "utf8"));
1664
+ }
1665
+ catch (err) {
1666
+ throw new VibecodeError("CONTRACT_INVALID", `Invalid JSON in --endpoints file: ${err?.message ?? String(err)}`);
1667
+ }
1668
+ const parsedObj = isPlainObjectSafe(parsed) ? parsed : null;
1669
+ endpoints = Array.isArray(parsed)
1670
+ ? parsed
1671
+ : (parsedObj && Array.isArray(parsedObj.endpoints) ? parsedObj.endpoints : []);
1672
+ }
1673
+ let crawlDepth;
1674
+ if (flags["crawl-depth"] !== undefined) {
1675
+ if (typeof flags["crawl-depth"] !== "string" || !/^\d+$/.test(flags["crawl-depth"].trim())) {
1676
+ throw new VibecodeError("CONTRACT_INVALID", "--crawl-depth must be an integer between 1 and 3");
1677
+ }
1678
+ const parsedDepth = Number.parseInt(flags["crawl-depth"].trim(), 10);
1679
+ if (!Number.isInteger(parsedDepth) || parsedDepth < 1 || parsedDepth > 3) {
1680
+ throw new VibecodeError("CONTRACT_INVALID", "--crawl-depth must be an integer between 1 and 3");
1681
+ }
1682
+ crawlDepth = parsedDepth;
1683
+ }
1684
+ const holdoutRoutes = flagList(flags, "holdout-route").filter((r) => typeof r === "string");
1685
+ const [{ lockProject, formatPrettyLock }, discoverMod] = await Promise.all([
1686
+ import("./discovery/lock.js"),
1687
+ !source ? import("./discovery/discover.js") : Promise.resolve(null)
1688
+ ]);
1689
+ let discoverHint;
1690
+ if (!source && discoverMod) {
1691
+ const discovered = discoverMod.discoverProject(cwd);
1692
+ discoverHint = buildLockDiscoverHint(cwd, discovered, domain, target);
1693
+ }
1694
+ const lockOptions = {
1695
+ cwd,
1696
+ ...(source ? { source } : {}),
1697
+ ...(domain ? { domain } : {}),
1698
+ ...(target ? { target } : {}),
1699
+ ...(name ? { name } : {}),
1700
+ force: flags.force === true,
1701
+ strict: flags.strict === true,
1702
+ noSpec: flags["no-spec"] === true,
1703
+ noVerify: flags["no-verify"] === true,
1704
+ ...(probes.length > 0 ? { probes } : {}),
1705
+ ...(routes.length > 0 ? { routes } : {}),
1706
+ ...(endpoints !== undefined ? { endpoints } : {}),
1707
+ ...(baseUrl ? { baseUrl } : {}),
1708
+ ...(headers !== undefined ? { headers } : {}),
1709
+ ...(storageState !== undefined ? { storageState } : {}),
1710
+ ...(fsDiff ? { fsDiff: true } : {}),
1711
+ ...(crawlDepth !== undefined ? { crawlDepth } : {}),
1712
+ ...(holdoutRoutes.length > 0 ? { holdoutRoutes } : {}),
1713
+ ...(env !== undefined ? { env } : {}),
1714
+ ...(discoverHint ? { discoverHint } : {})
1715
+ };
1716
+ const result = await lockProject(lockOptions, {});
1717
+ if (flags.pretty === true) {
1718
+ process.stdout.write(formatPrettyLock(result, { color: Boolean(process.stdout.isTTY) }) + "\n");
1719
+ }
1720
+ else {
1721
+ emit(result);
1722
+ }
1723
+ process.exitCode = result.ok ? 0 : 1;
1724
+ }
1725
+ const VALID_EXPORT_FORMATS = new Set(["node-test", "vitest", "pytest", "shell", "playwright"]);
1726
+ const VALID_OPENAPI_FORMATS = new Set(["yaml", "json"]);
1727
+ const VALID_HTTP_EXPORT_FORMATS = new Set(["http-file", "curl", "postman"]);
1728
+ const VALID_ON_CONFLICT = new Set(["prefix", "overwrite", "skip"]);
1729
+ async function cmdExportTests(flags) {
1730
+ const [{ readContract }, { exportContractTests, writeExportedTests }] = await Promise.all([
1731
+ import("./core/store.js"),
1732
+ import("./core/test-exporter.js")
1733
+ ]);
1734
+ const contract = readContract(process.cwd());
1735
+ let format = "node-test";
1736
+ if (flags.format !== undefined) {
1737
+ if (typeof flags.format !== "string" || !VALID_EXPORT_FORMATS.has(flags.format.trim())) {
1738
+ throw new VibecodeError("CONTRACT_INVALID", `Invalid --format value; expected node-test, vitest, pytest, shell, or playwright`);
1739
+ }
1740
+ format = flags.format.trim();
1741
+ }
1742
+ const target = typeof flags.target === "string" && flags.target.trim() ? flags.target.trim() : undefined;
1743
+ if (flags.out !== undefined) {
1744
+ if (typeof flags.out !== "string" || !flags.out.trim()) {
1745
+ throw new VibecodeError("CONTRACT_INVALID", "--out requires a non-empty file path");
1746
+ }
1747
+ const result = writeExportedTests(contract, {
1748
+ format,
1749
+ target,
1750
+ outPath: path.resolve(process.cwd(), flags.out.trim())
1751
+ });
1752
+ emit({ ok: true, command: "export-tests", ...result });
1753
+ return;
1754
+ }
1755
+ const result = exportContractTests(contract, { format, target });
1756
+ emit({ ok: true, command: "export-tests", ...result });
1757
+ }
1758
+ async function cmdExportOpenApi(flags) {
1759
+ const [{ readContract }, { exportOpenApiSpec, writeOpenApiSpec }] = await Promise.all([
1760
+ import("./core/store.js"),
1761
+ import("./core/openapi-export.js")
1762
+ ]);
1763
+ const contract = readContract(process.cwd());
1764
+ let format = "yaml";
1765
+ if (flags.format !== undefined) {
1766
+ if (typeof flags.format !== "string" || !VALID_OPENAPI_FORMATS.has(flags.format.trim())) {
1767
+ throw new VibecodeError("CONTRACT_INVALID", `Invalid --format value; expected yaml or json`);
1768
+ }
1769
+ format = flags.format.trim();
1770
+ }
1771
+ const title = typeof flags.name === "string" && flags.name.trim() ? flags.name.trim() : undefined;
1772
+ const serverUrl = typeof flags["base-url"] === "string" && flags["base-url"].trim() ? flags["base-url"].trim() : undefined;
1773
+ if (flags.out !== undefined) {
1774
+ if (typeof flags.out !== "string" || !flags.out.trim()) {
1775
+ throw new VibecodeError("CONTRACT_INVALID", "--out requires a non-empty file path");
1776
+ }
1777
+ const result = writeOpenApiSpec(contract, {
1778
+ format,
1779
+ title,
1780
+ serverUrl,
1781
+ outPath: path.resolve(process.cwd(), flags.out.trim())
1782
+ });
1783
+ emit({ ok: true, command: "export-openapi", ...result });
1784
+ return;
1785
+ }
1786
+ const result = exportOpenApiSpec(contract, { format, title, serverUrl });
1787
+ emit({ ok: true, command: "export-openapi", ...result });
1788
+ }
1789
+ async function cmdExportHttp(flags) {
1790
+ const [{ readContract }, { exportHttpCollection, writeHttpCollection }] = await Promise.all([
1791
+ import("./core/store.js"),
1792
+ import("./core/http-export.js")
1793
+ ]);
1794
+ const contract = readContract(process.cwd());
1795
+ let format = "http-file";
1796
+ if (flags.format !== undefined) {
1797
+ if (typeof flags.format !== "string" || !VALID_HTTP_EXPORT_FORMATS.has(flags.format.trim())) {
1798
+ throw new VibecodeError("CONTRACT_INVALID", `Invalid --format value; expected http-file, curl, or postman`);
1799
+ }
1800
+ format = flags.format.trim();
1801
+ }
1802
+ const title = typeof flags.name === "string" && flags.name.trim() ? flags.name.trim() : undefined;
1803
+ const baseUrl = typeof flags["base-url"] === "string" && flags["base-url"].trim() ? flags["base-url"].trim() : undefined;
1804
+ if (flags.out !== undefined) {
1805
+ if (typeof flags.out !== "string" || !flags.out.trim()) {
1806
+ throw new VibecodeError("CONTRACT_INVALID", "--out requires a non-empty file path");
1807
+ }
1808
+ const result = writeHttpCollection(contract, {
1809
+ format,
1810
+ title,
1811
+ baseUrl,
1812
+ outPath: path.resolve(process.cwd(), flags.out.trim())
1813
+ });
1814
+ emit({ ok: true, command: "export-http", ...result });
1815
+ return;
1816
+ }
1817
+ const result = exportHttpCollection(contract, { format, title, baseUrl });
1818
+ emit({ ok: true, command: "export-http", ...result });
1819
+ }
1820
+ const VALID_CLIENT_EXPORT_FORMATS = new Set(["ts-fetch", "python", "go"]);
1821
+ async function cmdExportClient(flags) {
1822
+ const [{ readContract }, { exportClientCode, writeClientCode, formatPrettyClientExport }] = await Promise.all([
1823
+ import("./core/store.js"),
1824
+ import("./core/client-codegen.js")
1825
+ ]);
1826
+ const contract = readContract(process.cwd());
1827
+ let format = "ts-fetch";
1828
+ if (flags.format !== undefined) {
1829
+ if (typeof flags.format !== "string" || !VALID_CLIENT_EXPORT_FORMATS.has(flags.format.trim())) {
1830
+ throw new VibecodeError("CONTRACT_INVALID", "Invalid --format value; expected ts-fetch, python, or go");
1831
+ }
1832
+ format = flags.format.trim();
1833
+ }
1834
+ const title = typeof flags.name === "string" && flags.name.trim() ? flags.name.trim() : undefined;
1835
+ const baseUrl = typeof flags["base-url"] === "string" && flags["base-url"].trim() ? flags["base-url"].trim() : undefined;
1836
+ let outPath;
1837
+ if (flags.out !== undefined) {
1838
+ if (typeof flags.out !== "string" || !flags.out.trim()) {
1839
+ throw new VibecodeError("CONTRACT_INVALID", "--out requires a non-empty file path");
1840
+ }
1841
+ outPath = path.resolve(process.cwd(), flags.out.trim());
1842
+ }
1843
+ const result = outPath
1844
+ ? writeClientCode(contract, outPath, { format, title, baseUrl })
1845
+ : exportClientCode(contract, { format, title, baseUrl });
1846
+ if (flags.pretty === true) {
1847
+ process.stdout.write(formatPrettyClientExport(result, outPath, process.stdout.isTTY) + "\n");
1848
+ return;
1849
+ }
1850
+ emit({ ok: true, command: "export-client", ...(outPath ? { outPath } : {}), ...result });
1851
+ }
1852
+ async function cmdExportHar(flags) {
1853
+ const [{ readContract }, { exportHarArchive, writeHarArchive, formatPrettyHarExport }] = await Promise.all([
1854
+ import("./core/store.js"),
1855
+ import("./core/har-export.js")
1856
+ ]);
1857
+ const contract = readContract(process.cwd());
1858
+ const title = typeof flags.name === "string" && flags.name.trim() ? flags.name.trim() : undefined;
1859
+ const baseUrl = typeof flags["base-url"] === "string" && flags["base-url"].trim() ? flags["base-url"].trim() : undefined;
1860
+ let outPath;
1861
+ if (flags.out !== undefined) {
1862
+ if (typeof flags.out !== "string" || !flags.out.trim()) {
1863
+ throw new VibecodeError("CONTRACT_INVALID", "--out requires a non-empty file path");
1864
+ }
1865
+ outPath = path.resolve(process.cwd(), flags.out.trim());
1866
+ }
1867
+ const result = outPath
1868
+ ? writeHarArchive(contract, outPath, { title, baseUrl, pretty: true })
1869
+ : exportHarArchive(contract, { title, baseUrl });
1870
+ if (flags.pretty === true) {
1871
+ process.stdout.write(formatPrettyHarExport(result, outPath, process.stdout.isTTY) + "\n");
1872
+ return;
1873
+ }
1874
+ emit({ ok: true, command: "export-har", ...(outPath ? { outPath } : {}), ...result });
1875
+ }
1876
+ const VALID_GRAPHQL_EXPORT_FORMATS = new Set(["sdl", "introspection"]);
1877
+ const VALID_MCP_EXPORT_FORMATS = new Set(["node-mjs", "ts"]);
1878
+ const VALID_SCHEMA_EXPORT_FORMATS = new Set(["zod", "json-schema", "typescript"]);
1879
+ const VALID_LOAD_EXPORT_FORMATS = new Set(["k6", "artillery", "node-bench"]);
1880
+ const VALID_DOCS_EXPORT_FORMATS = new Set(["markdown", "html", "llms-txt"]);
1881
+ const VALID_CI_EXPORT_FORMATS = new Set(["github-actions", "gitlab-ci", "makefile"]);
1882
+ const VALID_SERVER_EXPORT_FORMATS = new Set(["node-http", "express-ts", "python-http"]);
1883
+ function resolveOptionalOutFlag(flags) {
1884
+ if (flags.out === undefined)
1885
+ return undefined;
1886
+ if (typeof flags.out !== "string" || !flags.out.trim()) {
1887
+ throw new VibecodeError("CONTRACT_INVALID", "--out requires a non-empty file path");
1888
+ }
1889
+ return path.resolve(process.cwd(), flags.out.trim());
1890
+ }
1891
+ async function cmdExportGraphql(flags) {
1892
+ const [{ readContract }, { exportGraphqlSchema, writeGraphqlSchema, formatPrettyGraphqlExport }] = await Promise.all([
1893
+ import("./core/store.js"),
1894
+ import("./core/graphql-export.js")
1895
+ ]);
1896
+ const contract = readContract(process.cwd());
1897
+ let format = "sdl";
1898
+ if (flags.format !== undefined) {
1899
+ if (typeof flags.format !== "string" || !VALID_GRAPHQL_EXPORT_FORMATS.has(flags.format.trim())) {
1900
+ throw new VibecodeError("CONTRACT_INVALID", "Invalid --format value; expected sdl or introspection");
1901
+ }
1902
+ format = flags.format.trim();
1903
+ }
1904
+ const title = typeof flags.name === "string" && flags.name.trim() ? flags.name.trim() : undefined;
1905
+ const outPath = resolveOptionalOutFlag(flags);
1906
+ const result = outPath
1907
+ ? writeGraphqlSchema(contract, outPath, { format, title })
1908
+ : exportGraphqlSchema(contract, { format, title });
1909
+ if (flags.pretty === true) {
1910
+ process.stdout.write(formatPrettyGraphqlExport(result, outPath, process.stdout.isTTY) + "\n");
1911
+ return;
1912
+ }
1913
+ emit({ ok: true, command: "export-graphql", ...(outPath ? { outPath } : {}), ...result });
1914
+ }
1915
+ async function cmdExportMcp(flags) {
1916
+ const [{ readContract }, { exportMcpServer, writeMcpServer, formatPrettyMcpExport }] = await Promise.all([
1917
+ import("./core/store.js"),
1918
+ import("./core/mcp-export.js")
1919
+ ]);
1920
+ const contract = readContract(process.cwd());
1921
+ let format = "node-mjs";
1922
+ if (flags.format !== undefined) {
1923
+ if (typeof flags.format !== "string" || !VALID_MCP_EXPORT_FORMATS.has(flags.format.trim())) {
1924
+ throw new VibecodeError("CONTRACT_INVALID", "Invalid --format value; expected node-mjs or ts");
1925
+ }
1926
+ format = flags.format.trim();
1927
+ }
1928
+ const title = typeof flags.name === "string" && flags.name.trim() ? flags.name.trim() : undefined;
1929
+ const baseUrl = typeof flags["base-url"] === "string" && flags["base-url"].trim() ? flags["base-url"].trim() : undefined;
1930
+ const outPath = resolveOptionalOutFlag(flags);
1931
+ const result = outPath
1932
+ ? writeMcpServer(contract, outPath, { format, title, baseUrl })
1933
+ : exportMcpServer(contract, { format, title, baseUrl });
1934
+ if (flags.pretty === true) {
1935
+ process.stdout.write(formatPrettyMcpExport(result, outPath, process.stdout.isTTY) + "\n");
1936
+ return;
1937
+ }
1938
+ emit({ ok: true, command: "export-mcp", ...(outPath ? { outPath } : {}), ...result });
1939
+ }
1940
+ async function cmdExportSchema(flags) {
1941
+ const [{ readContract }, { exportContractSchemas, writeContractSchemas, formatPrettySchemaExport }] = await Promise.all([
1942
+ import("./core/store.js"),
1943
+ import("./core/schema-export.js")
1944
+ ]);
1945
+ const contract = readContract(process.cwd());
1946
+ let format = "zod";
1947
+ if (flags.format !== undefined) {
1948
+ if (typeof flags.format !== "string" || !VALID_SCHEMA_EXPORT_FORMATS.has(flags.format.trim())) {
1949
+ throw new VibecodeError("CONTRACT_INVALID", "Invalid --format value; expected zod, json-schema, or typescript");
1950
+ }
1951
+ format = flags.format.trim();
1952
+ }
1953
+ const title = typeof flags.name === "string" && flags.name.trim() ? flags.name.trim() : undefined;
1954
+ const strict = flags.strict === true;
1955
+ const outPath = resolveOptionalOutFlag(flags);
1956
+ const result = outPath
1957
+ ? writeContractSchemas(contract, outPath, { format, title, strict })
1958
+ : exportContractSchemas(contract, { format, title, strict });
1959
+ if (flags.pretty === true) {
1960
+ process.stdout.write(formatPrettySchemaExport(result, outPath, process.stdout.isTTY) + "\n");
1961
+ return;
1962
+ }
1963
+ emit({ ok: true, command: "export-schema", ...(outPath ? { outPath } : {}), ...result });
1964
+ }
1965
+ async function cmdExportLoad(flags) {
1966
+ const [{ readContract }, { exportLoadSuite, writeLoadSuite, formatPrettyLoadExport }] = await Promise.all([
1967
+ import("./core/store.js"),
1968
+ import("./core/load-export.js")
1969
+ ]);
1970
+ const contract = readContract(process.cwd());
1971
+ let format = "k6";
1972
+ if (flags.format !== undefined) {
1973
+ if (typeof flags.format !== "string" || !VALID_LOAD_EXPORT_FORMATS.has(flags.format.trim())) {
1974
+ throw new VibecodeError("CONTRACT_INVALID", "Invalid --format value; expected k6, artillery, or node-bench");
1975
+ }
1976
+ format = flags.format.trim();
1977
+ }
1978
+ const title = typeof flags.name === "string" && flags.name.trim() ? flags.name.trim() : undefined;
1979
+ const baseUrl = typeof flags["base-url"] === "string" && flags["base-url"].trim() ? flags["base-url"].trim() : undefined;
1980
+ const strict = flags.strict === true;
1981
+ const outPath = resolveOptionalOutFlag(flags);
1982
+ const result = outPath
1983
+ ? writeLoadSuite(contract, outPath, { format, title, baseUrl, strict })
1984
+ : exportLoadSuite(contract, { format, title, baseUrl, strict });
1985
+ if (flags.pretty === true) {
1986
+ process.stdout.write(formatPrettyLoadExport(result, outPath, process.stdout.isTTY) + "\n");
1987
+ return;
1988
+ }
1989
+ emit({ ok: true, command: "export-load", ...(outPath ? { outPath } : {}), ...result });
1990
+ }
1991
+ async function cmdExportDocs(flags) {
1992
+ const [{ readContract }, { exportContractDocs, writeContractDocs, formatPrettyDocsExport }] = await Promise.all([
1993
+ import("./core/store.js"),
1994
+ import("./core/docs-export.js")
1995
+ ]);
1996
+ const contract = readContract(process.cwd());
1997
+ let format = "markdown";
1998
+ if (flags.format !== undefined) {
1999
+ if (typeof flags.format !== "string" || !VALID_DOCS_EXPORT_FORMATS.has(flags.format.trim())) {
2000
+ throw new VibecodeError("CONTRACT_INVALID", "Invalid --format value; expected markdown, html, or llms-txt");
2001
+ }
2002
+ format = flags.format.trim();
2003
+ }
2004
+ const title = typeof flags.name === "string" && flags.name.trim() ? flags.name.trim() : undefined;
2005
+ const baseUrl = typeof flags["base-url"] === "string" && flags["base-url"].trim() ? flags["base-url"].trim() : undefined;
2006
+ const strict = flags.strict === true;
2007
+ const outPath = resolveOptionalOutFlag(flags);
2008
+ const result = outPath
2009
+ ? writeContractDocs(contract, outPath, { format, title, baseUrl, strict })
2010
+ : exportContractDocs(contract, { format, title, baseUrl, strict });
2011
+ if (flags.pretty === true) {
2012
+ process.stdout.write(formatPrettyDocsExport(result, outPath, process.stdout.isTTY) + "\n");
2013
+ return;
2014
+ }
2015
+ emit({ ok: true, command: "export-docs", ...(outPath ? { outPath } : {}), ...result });
2016
+ }
2017
+ async function cmdExportCi(flags) {
2018
+ const [{ readContract }, { exportCiPipeline, writeCiPipeline, formatPrettyCiExport }] = await Promise.all([
2019
+ import("./core/store.js"),
2020
+ import("./core/ci-export.js")
2021
+ ]);
2022
+ const contract = readContract(process.cwd());
2023
+ let format = "github-actions";
2024
+ if (flags.format !== undefined) {
2025
+ if (typeof flags.format !== "string" || !VALID_CI_EXPORT_FORMATS.has(flags.format.trim())) {
2026
+ throw new VibecodeError("CONTRACT_INVALID", "Invalid --format value; expected github-actions, gitlab-ci, or makefile");
2027
+ }
2028
+ format = flags.format.trim();
2029
+ }
2030
+ const title = typeof flags.name === "string" && flags.name.trim() ? flags.name.trim() : undefined;
2031
+ const target = typeof flags.target === "string" && flags.target.trim() ? flags.target.trim() : undefined;
2032
+ const strict = flags.strict === true;
2033
+ const cache = flags.cache === true;
2034
+ const outPath = resolveOptionalOutFlag(flags);
2035
+ const result = outPath
2036
+ ? writeCiPipeline(contract, outPath, { format, title, target, strict, cache })
2037
+ : exportCiPipeline(contract, { format, title, target, strict, cache });
2038
+ if (flags.pretty === true) {
2039
+ process.stdout.write(formatPrettyCiExport(result, outPath, process.stdout.isTTY) + "\n");
2040
+ return;
2041
+ }
2042
+ emit({ ok: true, command: "export-ci", ...(outPath ? { outPath } : {}), ...result });
2043
+ }
2044
+ async function cmdExportServer(flags) {
2045
+ const [{ readContract }, { exportServerScaffold, writeServerScaffold, formatPrettyServerExport }] = await Promise.all([
2046
+ import("./core/store.js"),
2047
+ import("./core/server-export.js")
2048
+ ]);
2049
+ const contract = readContract(process.cwd());
2050
+ let format = "node-http";
2051
+ if (flags.format !== undefined) {
2052
+ if (typeof flags.format !== "string" || !VALID_SERVER_EXPORT_FORMATS.has(flags.format.trim())) {
2053
+ throw new VibecodeError("CONTRACT_INVALID", "Invalid --format value; expected node-http, express-ts, or python-http");
2054
+ }
2055
+ format = flags.format.trim();
2056
+ }
2057
+ let port;
2058
+ if (flags.port !== undefined) {
2059
+ if (typeof flags.port !== "string" || !/^\d+$/.test(flags.port.trim())) {
2060
+ throw new VibecodeError("CONTRACT_INVALID", "--port must be an integer between 0 and 65535");
2061
+ }
2062
+ port = Number.parseInt(flags.port.trim(), 10);
2063
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
2064
+ throw new VibecodeError("CONTRACT_INVALID", "--port must be between 0 and 65535");
2065
+ }
2066
+ }
2067
+ const title = typeof flags.name === "string" && flags.name.trim() ? flags.name.trim() : undefined;
2068
+ const strict = flags.strict === true;
2069
+ const outPath = resolveOptionalOutFlag(flags);
2070
+ const result = outPath
2071
+ ? writeServerScaffold(contract, outPath, { format, title, port, strict })
2072
+ : exportServerScaffold(contract, { format, title, port, strict });
2073
+ if (flags.pretty === true) {
2074
+ process.stdout.write(formatPrettyServerExport(result, outPath, process.stdout.isTTY) + "\n");
2075
+ return;
2076
+ }
2077
+ emit({ ok: true, command: "export-server", ...(outPath ? { outPath } : {}), ...result });
2078
+ }
2079
+ async function cmdMock(flags) {
2080
+ const [{ readContract }, { compileMockRoutes, formatPrettyMockServer, startContractMockServer }] = await Promise.all([
2081
+ import("./core/store.js"),
2082
+ import("./core/mock-server.js")
2083
+ ]);
2084
+ const contract = readContract(process.cwd());
2085
+ let port = 0;
2086
+ if (flags.port !== undefined) {
2087
+ if (typeof flags.port !== "string" || !/^\d+$/.test(flags.port.trim())) {
2088
+ throw new VibecodeError("CONTRACT_INVALID", "--port must be an integer between 0 and 65535");
2089
+ }
2090
+ port = Number.parseInt(flags.port.trim(), 10);
2091
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
2092
+ throw new VibecodeError("CONTRACT_INVALID", "--port must be between 0 and 65535");
2093
+ }
2094
+ }
2095
+ if (flags["dry-run"] === true) {
2096
+ const compiled = compileMockRoutes(contract);
2097
+ const previewUrl = `http://127.0.0.1:${port}`;
2098
+ if (flags.pretty === true) {
2099
+ process.stdout.write(formatPrettyMockServer({ url: previewUrl, ...compiled }, { color: Boolean(process.stdout.isTTY) }) + "\n");
2100
+ return;
2101
+ }
2102
+ emit({
2103
+ ok: true,
2104
+ command: "mock",
2105
+ dryRun: true,
2106
+ url: previewUrl,
2107
+ routes: compiled.routes,
2108
+ skippedIds: compiled.skippedIds,
2109
+ excludedHoldoutCount: compiled.excludedHoldoutCount
2110
+ });
2111
+ return;
2112
+ }
2113
+ const handle = await startContractMockServer(contract, { host: "127.0.0.1", port });
2114
+ if (flags.pretty === true) {
2115
+ process.stdout.write(formatPrettyMockServer(handle, { color: Boolean(process.stdout.isTTY) }) + "\n");
2116
+ }
2117
+ else {
2118
+ emit({
2119
+ ok: true,
2120
+ command: "mock",
2121
+ url: handle.url,
2122
+ host: handle.host,
2123
+ port: handle.port,
2124
+ routeCount: handle.routes.length,
2125
+ routes: handle.routes.map((r) => ({ invariantId: r.invariantId, method: r.method, path: r.path, status: r.status })),
2126
+ skippedIds: handle.skippedIds,
2127
+ excludedHoldoutCount: handle.excludedHoldoutCount
2128
+ });
2129
+ }
2130
+ await new Promise((resolve) => {
2131
+ let closed = false;
2132
+ const shutdown = () => {
2133
+ if (closed)
2134
+ return;
2135
+ closed = true;
2136
+ process.removeListener("SIGINT", shutdown);
2137
+ process.removeListener("SIGTERM", shutdown);
2138
+ void handle.close().finally(resolve);
2139
+ };
2140
+ process.on("SIGINT", shutdown);
2141
+ process.on("SIGTERM", shutdown);
2142
+ });
2143
+ }
2144
+ async function cmdMerge(flags) {
2145
+ const withPath = parseFileFlag(flags, "with");
2146
+ if (!withPath) {
2147
+ throw new VibecodeError("CONTRACT_INVALID", "merge requires --with <contract.json>");
2148
+ }
2149
+ const [{ readContract, readHoldouts, writeContract }, { normalizeContract, validateContract }, { diffContracts, formatPrettyContractDiff, mergeContracts }] = await Promise.all([import("./core/store.js"), import("./core/schema.js"), import("./core/compose.js")]);
2150
+ const base = readContract(process.cwd());
2151
+ let parsedIncomingRaw;
2152
+ try {
2153
+ const rawText = fs.readFileSync(withPath, "utf8");
2154
+ const cleanText = rawText.startsWith("\uFEFF") ? rawText.slice(1) : rawText;
2155
+ parsedIncomingRaw = JSON.parse(cleanText);
2156
+ }
2157
+ catch (err) {
2158
+ throw new VibecodeError("CONTRACT_INVALID", `Invalid --with contract JSON (${withPath}): ${err?.message ?? String(err)}`);
2159
+ }
2160
+ const incoming = normalizeContract(parsedIncomingRaw);
2161
+ const incomingValidation = validateContract(incoming);
2162
+ if (!incomingValidation.ok) {
2163
+ throw new VibecodeError("CONTRACT_INVALID", `Invalid --with contract (${withPath}): ${incomingValidation.errors.map((e) => e.message).join("; ")}`);
2164
+ }
2165
+ let onConflict = "prefix";
2166
+ if (flags["on-conflict"] !== undefined) {
2167
+ if (typeof flags["on-conflict"] !== "string" || !VALID_ON_CONFLICT.has(flags["on-conflict"].trim())) {
2168
+ throw new VibecodeError("CONTRACT_INVALID", "Invalid --on-conflict value; expected prefix, overwrite, or skip");
2169
+ }
2170
+ onConflict = flags["on-conflict"].trim();
2171
+ }
2172
+ const prefix = typeof flags.prefix === "string" && flags.prefix.trim() ? flags.prefix.trim() : undefined;
2173
+ const name = typeof flags.name === "string" && flags.name.trim() ? flags.name.trim() : undefined;
2174
+ const merged = mergeContracts(base, incoming, { prefix, name, onConflict });
2175
+ const diff = diffContracts(base, merged.contract);
2176
+ let contractPath;
2177
+ let specPath;
2178
+ const dryRun = flags["dry-run"] === true;
2179
+ if (!dryRun) {
2180
+ if (flags.out !== undefined) {
2181
+ if (typeof flags.out !== "string" || !flags.out.trim()) {
2182
+ throw new VibecodeError("CONTRACT_INVALID", "--out requires a non-empty file path");
2183
+ }
2184
+ const outResolved = path.resolve(process.cwd(), flags.out.trim());
2185
+ fs.mkdirSync(path.dirname(outResolved), { recursive: true });
2186
+ const tmpOut = `${outResolved}.${process.pid}.tmp`;
2187
+ fs.writeFileSync(tmpOut, JSON.stringify(merged.contract, null, 2) + "\n", "utf8");
2188
+ fs.renameSync(tmpOut, outResolved);
2189
+ contractPath = outResolved;
2190
+ }
2191
+ else {
2192
+ contractPath = writeContract(merged.contract, process.cwd(), { force: true });
2193
+ if (flags["no-spec"] !== true) {
2194
+ const [{ writeSpecFile }] = await Promise.all([import("./core/spec-writer.js")]);
2195
+ const holdouts = readHoldouts(process.cwd());
2196
+ specPath = writeSpecFile(process.cwd(), { contract: merged.contract, holdoutCount: holdouts.length });
2197
+ }
2198
+ }
2199
+ }
2200
+ if (flags.pretty === true) {
2201
+ process.stdout.write(formatPrettyContractDiff(diff, { color: Boolean(process.stdout.isTTY) }) + "\n");
2202
+ return;
2203
+ }
2204
+ emit({
2205
+ ok: true,
2206
+ command: "merge",
2207
+ dryRun,
2208
+ ...(contractPath ? { contractPath } : {}),
2209
+ ...(specPath ? { specPath } : {}),
2210
+ addedInvariants: merged.addedInvariants,
2211
+ skippedInvariants: merged.skippedInvariants,
2212
+ renamedIds: merged.renamedIds,
2213
+ excludedHoldouts: merged.excludedHoldouts,
2214
+ mergedDomains: merged.mergedDomains,
2215
+ diff
2216
+ });
2217
+ }
2218
+ async function cmdDiagnose(flags) {
2219
+ const [{ readContract, readHoldouts, readLastReport }, { redactHoldoutResult }, { redactSensitiveText }, { diagnoseReport, formatPrettyDiagnosis }] = await Promise.all([
2220
+ import("./core/store.js"),
2221
+ import("./core/parity.js"),
2222
+ import("./core/security.js"),
2223
+ import("./diagnostics/diagnose.js")
2224
+ ]);
2225
+ const lastReport = readLastReport(process.cwd());
2226
+ if (!lastReport) {
2227
+ throw new VibecodeError("NOT_FOUND", "No .vibecode/last-report.json found. Run 'vibecode-anything verify' first.");
2228
+ }
2229
+ let contract;
2230
+ try {
2231
+ contract = readContract(process.cwd());
2232
+ }
2233
+ catch (err) {
2234
+ if (errorCode(err) !== "CONTRACT_NOT_FOUND")
2235
+ throw err;
2236
+ }
2237
+ const holdoutById = loadHoldoutMap(readContract, readHoldouts, process.cwd());
2238
+ const safeLastReport = sanitizeReportForDisplay(lastReport, holdoutById, false, redactHoldoutResult, redactSensitiveText);
2239
+ const safeContract = contract
2240
+ ? {
2241
+ ...contract,
2242
+ invariants: contract.invariants.filter((inv) => inv.holdout !== true && !holdoutById.has(inv.id)),
2243
+ ...(Array.isArray(contract.slices)
2244
+ ? {
2245
+ slices: contract.slices.map((s) => ({
2246
+ ...s,
2247
+ invariantIds: s.invariantIds.filter((id) => !holdoutById.has(id))
2248
+ }))
2249
+ }
2250
+ : {})
2251
+ }
2252
+ : undefined;
2253
+ const diagnosis = await diagnoseReport(safeLastReport, {
2254
+ ...(safeContract ? { contract: safeContract } : {}),
2255
+ cwd: process.cwd()
2256
+ });
2257
+ if (flags.brief === true) {
2258
+ process.stdout.write(diagnosis.repairBrief + "\n");
2259
+ }
2260
+ else if (flags.pretty === true) {
2261
+ process.stdout.write(formatPrettyDiagnosis(diagnosis, { color: Boolean(process.stdout.isTTY) }) + "\n");
2262
+ }
2263
+ else {
2264
+ emit({ command: "diagnose", ...diagnosis });
2265
+ }
2266
+ process.exitCode = !diagnosis.ok || (flags.strict === true && diagnosis.totalDiagnosed > 0) ? 1 : 0;
2267
+ }
2268
+ async function cmdFlake(flags) {
2269
+ let rt;
2270
+ try {
2271
+ rt = parseRuntimeTargetFlags(flags);
2272
+ }
2273
+ catch (err) {
2274
+ fail(err, 2);
2275
+ return;
2276
+ }
2277
+ requireTargetOrMap(rt, "flake analysis");
2278
+ const target = rt.target ?? "";
2279
+ let runs;
2280
+ if (flags.runs !== undefined) {
2281
+ if (typeof flags.runs !== "string" || !/^\d+$/.test(flags.runs.trim())) {
2282
+ fail(new VibecodeError("CONFIG_INVALID", "--runs must be an integer between 2 and 10."), 2);
2283
+ return;
2284
+ }
2285
+ const parsedRuns = Number.parseInt(flags.runs.trim(), 10);
2286
+ if (!Number.isInteger(parsedRuns) || parsedRuns < 2 || parsedRuns > 10) {
2287
+ fail(new VibecodeError("CONFIG_INVALID", "--runs must be an integer between 2 and 10."), 2);
2288
+ return;
2289
+ }
2290
+ runs = parsedRuns;
2291
+ }
2292
+ const headers = parseHeaderFlags(flags);
2293
+ const storageState = parseFileFlag(flags, "storage-state");
2294
+ const sliceArgs = splitCsvFlags(flagList(flags, "slice"));
2295
+ const [{ readContract }, { analyzeFlakes, formatPrettyFlake }, slicesMod] = await Promise.all([
2296
+ import("./core/store.js"),
2297
+ import("./diagnostics/flake.js"),
2298
+ sliceArgs.length > 0 ? import("./core/slices.js") : Promise.resolve(null)
2299
+ ]);
2300
+ const contract = readContract(process.cwd());
2301
+ const explicitIds = flagList(flags, "invariant").filter((x) => typeof x === "string");
2302
+ const invariantIds = [];
2303
+ const seenIds = new Set();
2304
+ if (sliceArgs.length > 0 && slicesMod) {
2305
+ const resolved = slicesMod.resolveSliceInvariants(contract, sliceArgs);
2306
+ for (const id of resolved.invariantIds) {
2307
+ if (!seenIds.has(id)) {
2308
+ seenIds.add(id);
2309
+ invariantIds.push(id);
2310
+ }
2311
+ }
2312
+ }
2313
+ for (const id of explicitIds) {
2314
+ if (!seenIds.has(id)) {
2315
+ seenIds.add(id);
2316
+ invariantIds.push(id);
2317
+ }
2318
+ }
2319
+ const skipFixtures = flags["no-fixtures"] === true;
2320
+ const allowFixtureCommands = flags["allow-fixture-commands"] === true;
2321
+ const report = await analyzeFlakes(contract, {
2322
+ ...(runs !== undefined ? { runs } : {}),
2323
+ cwd: process.cwd(),
2324
+ target: target.trim(),
2325
+ ...(rt.targets ? { targets: rt.targets } : {}),
2326
+ ...(rt.vars ? { vars: rt.vars } : {}),
2327
+ ...(skipFixtures ? { skipFixtures: true } : {}),
2328
+ strict: flags.strict === true,
2329
+ ...(invariantIds.length > 0 ? { invariantIds } : {}),
2330
+ ...(headers !== undefined ? { headers } : {}),
2331
+ ...(storageState !== undefined ? { storageState } : {}),
2332
+ revealHoldouts: flags["reveal-holdouts"] === true
2333
+ }, allowFixtureCommands
2334
+ ? {
2335
+ verifyContract: async (c, flakeCtx, flakeDeps) => {
2336
+ const { verifyContract } = await import("./oracles/index.js");
2337
+ return verifyContract(c, {
2338
+ ...flakeCtx,
2339
+ allowFixtureCommands: true
2340
+ }, flakeDeps);
2341
+ }
2342
+ }
2343
+ : {});
2344
+ if (flags.pretty === true) {
2345
+ process.stdout.write(scrubOutput(formatPrettyFlake(report, { color: Boolean(process.stdout.isTTY) })) + "\n");
2346
+ }
2347
+ else {
2348
+ emit({ command: "flake", ...report });
2349
+ }
2350
+ const allSkipped = report.invariants.length > 0 && report.skipped === report.invariants.length;
2351
+ process.exitCode = allSkipped ? 2 : report.ok ? 0 : 1;
380
2352
  }
381
2353
  function cmdHelp() {
382
- process.stdout.write(`vibecode-anything v${VERSION}
383
-
384
- Commands:
385
- init --domain <cli|web|api> --source <ref> Create .vibecode/contract.json (v0.1 compatible)
386
- ingest --domain <cli|web|image|video|api|repo|rea|cli-anything> --source <ref>
387
- Probe a reference and write a v0.2 contract
388
- verify --target "<command-or-url>" [--strict] [--invariant <id>] [--slice <id>]
389
- Run the differential oracle & parity gate
390
- watch --target "<command-or-url>" [--slice <id>] [--watch-path <dir>] [--debounce <ms>] [--strict]
391
- Re-run verification automatically on file changes
392
- status Show contract metadata, adapters, slices, and last report
393
- diff --invariant <id> Show the last result/diff for one invariant
394
- doctor [--scope project|global] [--strict] [--antigravity-dir <dir>]
395
- Check Node, adapters, optional CLIs, and MCP registration
396
- mcp Start the stdio MCP server
397
- setup [--clients ...] [--scope project|global] [--dry-run]
398
- Register MCP + SKILL.md for coding agents
399
- help Show this help
2354
+ process.stdout.write(`vibecode-anything v${VERSION}
2355
+
2356
+ Commands:
2357
+ discover [--dir <path>] [--pretty] Inspect a project for frameworks, routes, specs, entrypoints & lock commands
2358
+ lock [--source <ref>] [--domain <d>] [--target <cmd-or-url>] [--name <id>] [--force] [--strict]
2359
+ [--no-spec] [--no-verify] [--check] [--pretty] [--probe <args>] [--probes <file.json>]
2360
+ [--route <path>] [--crawl-depth <1-3>] [--holdout-route <path>] [--endpoints <file.json>]
2361
+ [--base-url <url>] [--header <Key: Value>] [--storage-state <file>] [--env <KEY=VAL>] [--fs-diff]
2362
+ Snapshot golden baseline into contract + lock.json (or check tamper/drift)
2363
+ init --domain <cli|web|api> --source <ref> Create .vibecode/contract.json (v0.1 compatible)
2364
+ ingest --domain <cli|web|image|video|api|repo|rea|cli-anything|postman|curl|graphql|http-file|insomnia|bruno|asyncapi|proto|openrpc> --source <ref> [--no-spec] [--crawl-depth <1-3>] [--holdout-route <path>]
2365
+ Probe a reference and write .vibecode/contract.json + SPEC.md
2366
+ Options: --crop <w:h:x:y>, --env <KEY=VAL>, --fs-diff,
2367
+ --header <Key: Value>, --storage-state <file>,
2368
+ --from-commands <file>, --from-har <file>, --from-tests <path>
2369
+ verify --target "<command-or-url>" [--target-map <domain=target>] [--var <KEY=VAL>] [--mode <exact|structural|functional|reskin>] [--concurrency <1-8>] [--plugin <file.mjs>] [--strict] [--invariant <id>] [--slice <id>]
2370
+ [--affected] [--reveal-holdouts] [--no-report] [--no-fixtures] [--allow-fixture-commands] [--cache] [--pretty] [--header <Key: Value>] [--storage-state <file>]
2371
+ Run the differential oracle, parity gate & report.html
2372
+ --affected verifies only git-changed impacted invariants (fail-closed full fallback);
2373
+ --target-map routes domains (web=http://localhost:3000, cli=./bin/app; repeatable,
2374
+ --target optional when given); --var / VIBECODE_VAR_* inject redacted {{vars.*}} secrets
2375
+ run --target "<command-or-url>" [--target-map <domain=target>] [--var <KEY=VAL>] [--mode <exact|structural|functional|reskin>] [--concurrency <1-8>] [--plugin <file.mjs>] [--source <ref>] [--domain <d>] [--agent <auto|claude|codex|agy|opencode|mock:script>]
2376
+ [--max-iterations <n>] [--max-minutes <m>] [--slice <id>] [--strict] [--dry-run] [--force]
2377
+ [--no-report] [--no-fixtures] [--allow-fixture-commands] [--cache] [--pretty] [--header <Key: Value>] [--storage-state <file>]
2378
+ Closed-loop fresh-context agent build & verification
2379
+ report [--out <file>] [--badge <file.svg>] [--markdown <file.md>] [--sarif <file.sarif>] [--junit <file.xml>] [--no-report]
2380
+ Generate visual HTML proof, SVG parity badge, PR Markdown, SARIF 2.1.0, or JUnit XML
2381
+ export-tests [--format <node-test|vitest|pytest|shell|playwright>] [--out <file>] [--target <cmd-or-url>]
2382
+ Export visible invariants to standalone zero-dep regression tests
2383
+ export-openapi [--format <yaml|json>] [--out <file>] [--name <title>] [--base-url <url>]
2384
+ Compile visible HTTP invariants into OpenAPI 3.0.3 YAML/JSON
2385
+ export-http [--format <http-file|curl|postman>] [--out <file>] [--name <title>] [--base-url <url>]
2386
+ Export visible HTTP invariants as .http, cURL, or Postman v2.1 collection
2387
+ export-client [--format <ts-fetch|python|go>] [--out <file>] [--name <title>] [--base-url <url>] [--pretty]
2388
+ Compile visible HTTP invariants into typed TypeScript, Python, or Go clients
2389
+ export-har [--out <file>] [--name <title>] [--base-url <url>] [--pretty]
2390
+ Export visible HTTP and web invariants into a W3C HAR 1.2 archive
2391
+ export-graphql [--format <sdl|introspection>] [--out <file>] [--name <title>] [--pretty]
2392
+ Compile visible GraphQL & REST HTTP invariants into GraphQL SDL or Introspection JSON
2393
+ export-mcp [--format <node-mjs|ts>] [--out <file>] [--name <title>] [--base-url <url>] [--pretty]
2394
+ Compile visible HTTP and CLI invariants into a standalone zero-dep stdio MCP server
2395
+ export-schema [--format <zod|json-schema|typescript>] [--out <file>] [--name <title>] [--strict] [--pretty]
2396
+ Compile visible HTTP and CLI schemas into Zod, JSON Schema, or TypeScript guards
2397
+ export-load [--format <k6|artillery|node-bench>] [--out <file>] [--name <title>] [--base-url <url>] [--strict] [--pretty]
2398
+ Compile visible HTTP/web invariants into k6, Artillery, or Node load suites
2399
+ export-docs [--format <markdown|html|llms-txt>] [--out <file>] [--name <title>] [--base-url <url>] [--strict] [--pretty]
2400
+ Export visible API/web/CLI invariants as Markdown, zero-CDN HTML, or llms.txt
2401
+ export-ci [--format <github-actions|gitlab-ci|makefile>] [--out <file>] [--name <title>] [--target <cmd-or-url>] [--strict] [--cache] [--pretty]
2402
+ Generate GitHub Actions, GitLab CI, or Makefile parity verification pipelines
2403
+ export-server [--format <node-http|express-ts|python-http>] [--out <file>] [--name <title>] [--port <n>] [--strict] [--pretty]
2404
+ Generate runnable Node HTTP, Express TypeScript, or Python HTTP server scaffolds
2405
+ mock [--port <n>] [--dry-run] [--pretty] Serve a deterministic HTTP/web mock server from .vibecode/contract.json
2406
+ merge --with <contract.json> [--out <file>] [--prefix <p>] [--on-conflict <prefix|overwrite|skip>] [--dry-run] [--no-spec] [--pretty]
2407
+ Compose multi-domain contracts and inspect structural contract drift
2408
+ watch --target "<command-or-url>" [--target-map <domain=target>] [--var <KEY=VAL>] [--mode <exact|structural|functional|reskin>] [--concurrency <1-8>] [--plugin <file.mjs>] [--slice <id>] [--watch-path <dir>]
2409
+ [--debounce <ms>] [--smart] [--strict] [--no-fixtures] [--allow-fixture-commands] [--cache] [--pretty] [--header <Key: Value>] [--storage-state <file>]
2410
+ Re-run verification automatically on file changes (--smart runs only impacted invariants)
2411
+ status [--trends] [--pretty] Show contract metadata, adapters, slices, last report & verification trends
2412
+ diff [--invariant <id>] [--baseline <report.json>] [--reveal-holdouts] [--strict] [--pretty]
2413
+ Compare vs baseline report or show last result/diff
2414
+ diagnose [--brief] [--strict] [--pretty] Root-cause failure triage, spatial heatmap & minimal repair brief
2415
+ flake --target "<command-or-url>" [--target-map <domain=target>] [--var <KEY=VAL>] [--runs <2-10>] [--invariant <id>] [--slice <id>] [--strict]
2416
+ [--reveal-holdouts] [--no-fixtures] [--allow-fixture-commands] [--pretty] [--header <Key: Value>] [--storage-state <file>]
2417
+ Run multi-pass flake & nondeterminism detection with normalize hints
2418
+ lint [--strength] [--strict] [--pretty] Audit .vibecode/contract.json for secret leaks, weak checks, slice issues & oracle strength
2419
+ doctor [--scope project|global] [--strict] [--antigravity-dir <dir>] [--pretty]
2420
+ Check Node, adapters, agent CLIs, and MCP registration
2421
+ mcp Start the stdio MCP server
2422
+ setup [--clients auto|all|claude-code,cursor,antigravity,codex,opencode,windsurf,cline] [--scope project|global] [--dry-run]
2423
+ Register MCP + SKILL.md for coding agents
2424
+ help Show this help
400
2425
  `);
401
2426
  }
402
2427
  async function main() {
@@ -409,16 +2434,58 @@ async function main() {
409
2434
  }
410
2435
  if (command === "init")
411
2436
  cmdInit(flags);
2437
+ else if (command === "discover")
2438
+ await cmdDiscover(flags, positionals);
2439
+ else if (command === "lock")
2440
+ await cmdLock(flags);
412
2441
  else if (command === "ingest")
413
2442
  await cmdIngest(flags);
414
2443
  else if (command === "verify")
415
2444
  await cmdVerify(flags);
2445
+ else if (command === "run")
2446
+ await cmdRun(flags);
2447
+ else if (command === "report")
2448
+ await cmdReport(flags);
2449
+ else if (command === "export-tests")
2450
+ await cmdExportTests(flags);
2451
+ else if (command === "export-openapi")
2452
+ await cmdExportOpenApi(flags);
2453
+ else if (command === "export-http")
2454
+ await cmdExportHttp(flags);
2455
+ else if (command === "export-client")
2456
+ await cmdExportClient(flags);
2457
+ else if (command === "export-har")
2458
+ await cmdExportHar(flags);
2459
+ else if (command === "export-graphql")
2460
+ await cmdExportGraphql(flags);
2461
+ else if (command === "export-mcp")
2462
+ await cmdExportMcp(flags);
2463
+ else if (command === "export-schema")
2464
+ await cmdExportSchema(flags);
2465
+ else if (command === "export-load")
2466
+ await cmdExportLoad(flags);
2467
+ else if (command === "export-docs")
2468
+ await cmdExportDocs(flags);
2469
+ else if (command === "export-ci")
2470
+ await cmdExportCi(flags);
2471
+ else if (command === "export-server")
2472
+ await cmdExportServer(flags);
2473
+ else if (command === "mock")
2474
+ await cmdMock(flags);
2475
+ else if (command === "merge")
2476
+ await cmdMerge(flags);
416
2477
  else if (command === "watch")
417
2478
  await cmdWatch(flags);
418
2479
  else if (command === "status")
419
- await cmdStatus();
2480
+ await cmdStatus(flags);
420
2481
  else if (command === "diff")
421
- cmdDiff(flags);
2482
+ await cmdDiff(flags);
2483
+ else if (command === "diagnose")
2484
+ await cmdDiagnose(flags);
2485
+ else if (command === "flake")
2486
+ await cmdFlake(flags);
2487
+ else if (command === "lint")
2488
+ await cmdLint(flags);
422
2489
  else if (command === "doctor")
423
2490
  await cmdDoctor(flags);
424
2491
  else if (command === "mcp") {