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
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Zero-dependency multi-run flake & nondeterminism detector for vibecode-anything.
3
+ */
4
+ import { type TargetMap } from "../core/target-map.js";
5
+ import { verifyContract } from "../oracles/index.js";
6
+ import type { ContractV02, NormalizeMode, VerifyDeps } from "../core/types.js";
7
+ export type FlakeClassification = "deterministic_pass" | "deterministic_fail" | "flaky_intermittent" | "nondeterministic_output" | "skipped";
8
+ export type NondeterminismKind = "timestamps" | "uuids_or_ids" | "paths_or_pids" | "line_or_array_order" | "latency_jitter" | "ansi_or_crlf";
9
+ export interface SuggestedNormalizeRule {
10
+ kind: NondeterminismKind;
11
+ normalizeModes: NormalizeMode[];
12
+ description: string;
13
+ contractHint: string;
14
+ }
15
+ export interface InvariantFlakeReport {
16
+ id: string;
17
+ type: string;
18
+ severity: string;
19
+ redacted: boolean;
20
+ runs: number;
21
+ passCount: number;
22
+ failCount: number;
23
+ skippedCount: number;
24
+ classification: FlakeClassification;
25
+ distinctOutputHashes: number;
26
+ distinctFailureSignatures: number;
27
+ nondeterminismKinds: NondeterminismKind[];
28
+ suggestedRules: SuggestedNormalizeRule[];
29
+ sampleFailures: string[];
30
+ }
31
+ export interface FlakeAnalysisReport {
32
+ ok: boolean;
33
+ contractName: string;
34
+ runs: number;
35
+ evaluated: number;
36
+ deterministicPass: number;
37
+ deterministicFail: number;
38
+ flakyIntermittent: number;
39
+ nondeterministicOutput: number;
40
+ skipped: number;
41
+ hasFlakes: boolean;
42
+ invariants: InvariantFlakeReport[];
43
+ suggestedNormalizeModes: NormalizeMode[];
44
+ generatedAt: string;
45
+ }
46
+ export interface AnalyzeFlakesOptions {
47
+ runs?: number;
48
+ cwd?: string;
49
+ target?: string;
50
+ targets?: TargetMap;
51
+ vars?: Record<string, string>;
52
+ skipFixtures?: boolean;
53
+ strict?: boolean;
54
+ invariantIds?: string[];
55
+ headers?: Record<string, string>;
56
+ storageState?: string;
57
+ revealHoldouts?: boolean;
58
+ }
59
+ export interface FormatPrettyFlakeOptions {
60
+ color?: boolean;
61
+ }
62
+ /** Pure linear-time detector for nondeterminism signals across failure/diff/output samples. */
63
+ export declare function detectNondeterminismKinds(samples: readonly string[]): NondeterminismKind[];
64
+ /** Synthesizes actionable `expected.normalize` modes and contract hints, omitting modes already configured. */
65
+ export declare function synthesizeNormalizeRules(kinds: readonly NondeterminismKind[], existingNormalize?: readonly NormalizeMode[]): SuggestedNormalizeRule[];
66
+ /** Runs `verifyContract` sequentially (always bypassing replay cache) to detect flakes and nondeterminism. */
67
+ export declare function analyzeFlakes(contract: ContractV02, options?: AnalyzeFlakesOptions, deps?: VerifyDeps & {
68
+ verifyContract?: typeof verifyContract;
69
+ }): Promise<FlakeAnalysisReport>;
70
+ /** Formats a FlakeAnalysisReport for human-readable terminal display (plain or ANSI color). */
71
+ export declare function formatPrettyFlake(report: FlakeAnalysisReport, options?: FormatPrettyFlakeOptions): string;
@@ -0,0 +1,608 @@
1
+ /**
2
+ * Zero-dependency multi-run flake & nondeterminism detector for vibecode-anything.
3
+ */
4
+ import { VibecodeError } from "../core/errors.js";
5
+ import { ANSI, isForbiddenObjectKey, isRecordSafe, redactSensitiveText, safeOwnProp, sanitizeSingleLine, styleAnsi } from "../core/security.js";
6
+ import { resolveWorkspace } from "../core/store.js";
7
+ import { redactRuntimeVars, validateRuntimeVarsObject, validateTargetMapObject } from "../core/target-map.js";
8
+ import { verifyContract } from "../oracles/index.js";
9
+ const DEFAULT_RUNS = 3;
10
+ const MIN_RUNS = 2;
11
+ const MAX_RUNS = 10;
12
+ const MAX_SAMPLE_FAILURES = 3;
13
+ const MAX_SAMPLE_FAILURE_CHARS = 4096;
14
+ const MAX_SCAN_SAMPLES = 64;
15
+ const MAX_SCAN_CHARS = 32_768;
16
+ const MAX_ORDER_ITEMS = 200;
17
+ const KIND_ORDER = [
18
+ "timestamps", "uuids_or_ids", "paths_or_pids", "line_or_array_order", "latency_jitter", "ansi_or_crlf"
19
+ ];
20
+ const NORMALIZE_MODE_ORDER = ["timestamps", "paths", "ansi", "crlf", "trim"];
21
+ const SKIPPED_DIFF_KEYS = new Set(["diffPng", "diffPath", "diffPngPath", "candidatePath", "referencePath"]);
22
+ const ALWAYS_DYNAMIC_ID_KEYS = new Set([
23
+ "req_id", "req-id", "reqid", "request_id", "request-id", "requestid",
24
+ "trace_id", "trace-id", "traceid", "span_id", "span-id", "spanid",
25
+ "corr_id", "correlation_id", "correlation-id", "correlationid", "nonce"
26
+ ]);
27
+ // Linear-time (ReDoS-safe) nondeterminism patterns.
28
+ const ISO_OR_SQL_TS_RE = /\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:?\d{2})?\b/;
29
+ const EPOCH_MS_RE = /\b[12]\d{12}\b/;
30
+ const LABELED_EPOCH_RE = /\b(?:timestamp|ts|time|epoch|created_at|updated_at)["']?\s*[:=]\s*["']?1\d{9}(?:\d{3})?\b/i;
31
+ const RFC_DATE_RE = /\b(?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s+\d{1,2}\s+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+\d{1,2},?|\d{1,2}\s+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\s+\d{4}\s+\d{2}:\d{2}:\d{2}\b/i;
32
+ const UUID_RE = /\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i;
33
+ const PREFIXED_ID_RE = /\b(?:req|request|trace|span|corr|correlation|job|txn|nonce)_[A-Za-z0-9_-]{6,64}\b/i;
34
+ const LONG_HEX_RE = /\b[0-9a-f]{24,64}\b/gi;
35
+ const KV_ID_RE = /\b(id|req(?:uest)?[_-]?id|trace[_-]?id|span[_-]?id|corr(?:elation)?[_-]?id|session[_-]?id|run[_-]?id|job[_-]?id|nonce)["']?\s*[:=]\s*["']?([A-Za-z0-9._-]{3,64})/gi;
36
+ const UNIX_TEMP_PATH_RE = /(?:^|[\s"'`(=:,])(?:\/private\/tmp\/|\/tmp\/|\/var\/tmp\/|\/var\/folders\/)[^\s"'`<>()[\]{}]+/;
37
+ const WIN_TEMP_PATH_RE = /[A-Za-z]:[\\/](?:Users[\\/][^\\/"'`<>\r\n]{1,64}[\\/](?:AppData[\\/]Local[\\/])?Temp|Windows[\\/]Temp|Temp)[\\/][^\s"'`<>]+/i;
38
+ const PID_RE = /\b(?:(?:pid|ppid|process[_-]?id)["']?\s*[:=]\s*["']?\d{2,7}|pid\s+#?\d{2,7})\b/i;
39
+ // eslint-disable-next-line no-control-regex
40
+ const ANSI_SIGNAL_RE = /\x1b\[[0-?]*[ -/]*[@-~]|\\u001b\[|\\x1b\[/i;
41
+ const CRLF_MENTION_RE = /\bcrlf\b|line endings?/i;
42
+ const LATENCY_JITTER_RE = /\blatency\s+\d+(?:\.\d+)?\s*ms\s*>\s*maxLatencyMs(?:\s+\d+(?:\.\d+)?\s*ms)?\b/i;
43
+ const ORDER_MISMATCH_RE = /\b(?:order(?:ing)?\s+mismatch|out\s+of\s+order|array\s+order|line\s+order|index\s+mismatch)\b/i;
44
+ const EXPECTED_ARRAY_PAIR_RE = /expected\s+(\[[^\r\n]{1,500}\]),\s*got\s+(\[[^\r\n]{1,500}\])/i;
45
+ function isPermutation(a, b) {
46
+ if (a.length < 2 || a.length !== b.length || a.every((v, i) => v === b[i]))
47
+ return false;
48
+ const sa = [...a].sort();
49
+ const sb = [...b].sort();
50
+ return sa.every((v, i) => v === sb[i]);
51
+ }
52
+ function hasUnifiedDiffReorder(sample) {
53
+ const removed = [];
54
+ const added = [];
55
+ for (const line of sample.replace(/\r\n/g, "\n").split("\n")) {
56
+ if (line.startsWith("--- ") || line.startsWith("+++ "))
57
+ continue;
58
+ if (line.startsWith("-"))
59
+ removed.push(line.slice(1).trim());
60
+ else if (line.startsWith("+"))
61
+ added.push(line.slice(1).trim());
62
+ if (removed.length > MAX_ORDER_ITEMS || added.length > MAX_ORDER_ITEMS)
63
+ return false;
64
+ }
65
+ return isPermutation(removed, added);
66
+ }
67
+ function hasExpectedArrayReorder(sample) {
68
+ const match = EXPECTED_ARRAY_PAIR_RE.exec(sample);
69
+ if (!match)
70
+ return false;
71
+ try {
72
+ const exp = JSON.parse(match[1]);
73
+ const act = JSON.parse(match[2]);
74
+ if (!Array.isArray(exp) || !Array.isArray(act) || exp.length < 2 || exp.length !== act.length)
75
+ return false;
76
+ return isPermutation(exp.map((v) => JSON.stringify(v)), act.map((v) => JSON.stringify(v)));
77
+ }
78
+ catch {
79
+ return false;
80
+ }
81
+ }
82
+ function hasCrossSampleReorder(samples) {
83
+ if (samples.length < 2)
84
+ return false;
85
+ const lineGroups = [];
86
+ const tokenGroups = [];
87
+ for (const raw of samples) {
88
+ const lines = raw.replace(/\r\n/g, "\n").split("\n").map((l) => l.trim())
89
+ .filter((l) => l.length > 0 && l !== "--- expected" && l !== "+++ actual" && l !== "@@")
90
+ .slice(0, MAX_ORDER_ITEMS);
91
+ if (lines.length >= 2)
92
+ lineGroups.push(lines);
93
+ const lower = raw.toLowerCase();
94
+ if (!(lower.includes("expected") && lower.includes("got"))) {
95
+ const tokens = raw.split(/[\s,[\]{}"']+/).map((t) => t.trim()).filter(Boolean).slice(0, MAX_ORDER_ITEMS);
96
+ if (tokens.length >= 2)
97
+ tokenGroups.push(tokens);
98
+ }
99
+ }
100
+ const check = (groups) => groups.some((g, i) => groups.slice(i + 1).some((other) => isPermutation(g, other)));
101
+ return check(lineGroups) || check(tokenGroups);
102
+ }
103
+ function hasLongRandomHex(text) {
104
+ LONG_HEX_RE.lastIndex = 0;
105
+ let m;
106
+ while ((m = LONG_HEX_RE.exec(text)) !== null) {
107
+ if (/[0-9]/.test(m[0]) && /[a-f]/i.test(m[0]))
108
+ return true;
109
+ }
110
+ return false;
111
+ }
112
+ /** Pure linear-time detector for nondeterminism signals across failure/diff/output samples. */
113
+ export function detectNondeterminismKinds(samples) {
114
+ if (!Array.isArray(samples))
115
+ return [];
116
+ const found = new Set();
117
+ const bounded = [];
118
+ const idValuesByKey = new Map();
119
+ for (const raw of samples) {
120
+ if (typeof raw !== "string" || raw.length === 0)
121
+ continue;
122
+ bounded.push(raw.length > MAX_SCAN_CHARS ? raw.slice(0, MAX_SCAN_CHARS) : raw);
123
+ if (bounded.length >= MAX_SCAN_SAMPLES)
124
+ break;
125
+ }
126
+ for (const text of bounded) {
127
+ if (!found.has("timestamps") && (ISO_OR_SQL_TS_RE.test(text) || EPOCH_MS_RE.test(text) || LABELED_EPOCH_RE.test(text) || RFC_DATE_RE.test(text))) {
128
+ found.add("timestamps");
129
+ }
130
+ if (!found.has("uuids_or_ids")) {
131
+ if (UUID_RE.test(text) || PREFIXED_ID_RE.test(text) || hasLongRandomHex(text)) {
132
+ found.add("uuids_or_ids");
133
+ }
134
+ else {
135
+ KV_ID_RE.lastIndex = 0;
136
+ let m;
137
+ while ((m = KV_ID_RE.exec(text)) !== null) {
138
+ const key = m[1].toLowerCase();
139
+ const val = m[2];
140
+ if (!val || val.startsWith("[REDACTED"))
141
+ continue;
142
+ if (ALWAYS_DYNAMIC_ID_KEYS.has(key) && val.length >= 6) {
143
+ found.add("uuids_or_ids");
144
+ break;
145
+ }
146
+ const seen = idValuesByKey.get(key) ?? new Set();
147
+ seen.add(val);
148
+ idValuesByKey.set(key, seen);
149
+ if (seen.size >= 2) {
150
+ found.add("uuids_or_ids");
151
+ break;
152
+ }
153
+ }
154
+ }
155
+ }
156
+ if (!found.has("paths_or_pids") && (UNIX_TEMP_PATH_RE.test(text) || WIN_TEMP_PATH_RE.test(text) || PID_RE.test(text))) {
157
+ found.add("paths_or_pids");
158
+ }
159
+ if (!found.has("ansi_or_crlf") && (ANSI_SIGNAL_RE.test(text) || text.includes("\r\n") || text.includes("\\r\\n") || CRLF_MENTION_RE.test(text))) {
160
+ found.add("ansi_or_crlf");
161
+ }
162
+ if (!found.has("latency_jitter") && LATENCY_JITTER_RE.test(text)) {
163
+ found.add("latency_jitter");
164
+ }
165
+ if (!found.has("line_or_array_order") && (ORDER_MISMATCH_RE.test(text) || hasUnifiedDiffReorder(text) || hasExpectedArrayReorder(text))) {
166
+ found.add("line_or_array_order");
167
+ }
168
+ }
169
+ if (!found.has("line_or_array_order") && hasCrossSampleReorder(bounded)) {
170
+ found.add("line_or_array_order");
171
+ }
172
+ return KIND_ORDER.filter((kind) => found.has(kind));
173
+ }
174
+ const RULE_SPECS = {
175
+ timestamps: {
176
+ modes: ["timestamps"],
177
+ description: "Output contains volatile timestamps or epoch values across runs.",
178
+ hintMissing: () => 'Add "timestamps" to expected.normalize (or assert dynamic timestamps via expected.stdoutRegex / expected.jsonPaths matches).',
179
+ hintConfigured: 'Timestamps still vary with "timestamps" enabled; use expected.stdoutRegex or expected.jsonPaths matches for custom date formats.'
180
+ },
181
+ uuids_or_ids: {
182
+ modes: [],
183
+ description: "Output contains volatile UUIDs or dynamic request/trace IDs across runs.",
184
+ hintMissing: () => 'Use expected.jsonPaths regex ("matches") or expected.stdoutRegex assertions instead of exact matching for dynamic UUIDs/IDs.',
185
+ hintConfigured: 'Use expected.jsonPaths regex ("matches") or expected.stdoutRegex assertions instead of exact matching for dynamic UUIDs/IDs.'
186
+ },
187
+ paths_or_pids: {
188
+ modes: ["paths"],
189
+ description: "Output contains volatile temp paths or process IDs across runs.",
190
+ hintMissing: () => 'Add "paths" to expected.normalize and replace raw temp directory/PID literals with expected.stdoutRegex or expected.jsonPaths matches.',
191
+ hintConfigured: "Volatile temp paths or PIDs still vary; replace exact path/PID assertions with expected.stdoutRegex or expected.jsonPaths matches."
192
+ },
193
+ ansi_or_crlf: {
194
+ modes: ["ansi", "crlf"],
195
+ description: "Output contains ANSI escape sequences or CRLF/LF line-ending drift.",
196
+ hintMissing: (modes) => `Add ${modes.map((m) => `"${m}"`).join(" and ")} to expected.normalize (and "trim" if trailing whitespace drifts).`,
197
+ hintConfigured: 'ANSI/CRLF normalization is already enabled; add "trim" to expected.normalize or inspect control characters.'
198
+ },
199
+ latency_jitter: {
200
+ modes: [],
201
+ description: "Observed request latency exceeded expected.maxLatencyMs intermittently.",
202
+ hintMissing: () => "Increase expected.maxLatencyMs headroom or warm up the target before verification.",
203
+ hintConfigured: "Increase expected.maxLatencyMs headroom or warm up the target before verification."
204
+ },
205
+ line_or_array_order: {
206
+ modes: [],
207
+ description: "Output lines or array elements appear in nondeterministic order across runs.",
208
+ hintMissing: () => "Sort output deterministically in the target, or use order-insensitive expected.stdoutContains / expected.jsonSchema assertions.",
209
+ hintConfigured: "Sort output deterministically in the target, or use order-insensitive expected.stdoutContains / expected.jsonSchema assertions."
210
+ }
211
+ };
212
+ function isNondeterminismKind(value) {
213
+ return typeof value === "string" && Object.hasOwn(RULE_SPECS, value);
214
+ }
215
+ /** Synthesizes actionable `expected.normalize` modes and contract hints, omitting modes already configured. */
216
+ export function synthesizeNormalizeRules(kinds, existingNormalize = []) {
217
+ if (!Array.isArray(kinds))
218
+ return [];
219
+ const existing = new Set(Array.isArray(existingNormalize) ? existingNormalize : []);
220
+ const seen = new Set();
221
+ const rules = [];
222
+ for (const rawKind of kinds) {
223
+ if (!isNondeterminismKind(rawKind) || seen.has(rawKind))
224
+ continue;
225
+ seen.add(rawKind);
226
+ const spec = RULE_SPECS[rawKind];
227
+ const normalizeModes = spec.modes.filter((m) => !existing.has(m));
228
+ const contractHint = sanitizeSingleLine(normalizeModes.length > 0 ? spec.hintMissing(normalizeModes) : spec.hintConfigured);
229
+ rules.push({ kind: rawKind, normalizeModes, description: spec.description, contractHint });
230
+ }
231
+ return rules;
232
+ }
233
+ function safeJsonPreview(value, depth = 0, seen = new WeakSet(), budget = { count: 0 }) {
234
+ if (budget.count >= 128)
235
+ return '"[Truncated]"';
236
+ budget.count++;
237
+ if (value === null)
238
+ return "null";
239
+ if (value === undefined)
240
+ return "undefined";
241
+ if (typeof value === "string")
242
+ return JSON.stringify(value.length > 256 ? value.slice(0, 256) : value);
243
+ if (typeof value === "number" || typeof value === "boolean")
244
+ return String(value);
245
+ if (typeof value === "bigint")
246
+ return `${value.toString()}n`;
247
+ if (typeof value !== "object")
248
+ return JSON.stringify(String(value));
249
+ const obj = value;
250
+ if (seen.has(obj))
251
+ return '"[Circular]"';
252
+ if (depth >= 4)
253
+ return '"[MaxDepth]"';
254
+ seen.add(obj);
255
+ try {
256
+ if (Array.isArray(obj)) {
257
+ const items = obj.slice(0, 24).map((item) => safeJsonPreview(item, depth + 1, seen, budget));
258
+ return `[${items.join(",")}]`;
259
+ }
260
+ const rec = obj;
261
+ const keys = Object.keys(rec).slice(0, 24);
262
+ const parts = [];
263
+ for (const k of keys) {
264
+ if (isForbiddenObjectKey(k))
265
+ continue;
266
+ let v;
267
+ try {
268
+ v = rec[k];
269
+ }
270
+ catch {
271
+ v = "[Unreadable]";
272
+ }
273
+ parts.push(`${JSON.stringify(k)}:${safeJsonPreview(v, depth + 1, seen, budget)}`);
274
+ }
275
+ return `{${parts.join(",")}}`;
276
+ }
277
+ finally {
278
+ seen.delete(obj);
279
+ }
280
+ }
281
+ function extractDiffSignals(diff, out, depth = 0, seen = new WeakSet()) {
282
+ if (depth > 3 || diff === null || diff === undefined || out.length >= MAX_SCAN_SAMPLES)
283
+ return;
284
+ if (typeof diff === "string") {
285
+ if (diff.length > 0)
286
+ out.push(diff.length > MAX_SCAN_CHARS ? diff.slice(0, MAX_SCAN_CHARS) : diff);
287
+ return;
288
+ }
289
+ if (typeof diff !== "object")
290
+ return;
291
+ if (seen.has(diff))
292
+ return;
293
+ seen.add(diff);
294
+ try {
295
+ if (Array.isArray(diff)) {
296
+ for (const item of diff.slice(0, 12)) {
297
+ if (out.length >= MAX_SCAN_SAMPLES)
298
+ break;
299
+ if (isRecordSafe(item)) {
300
+ const parts = [];
301
+ const itemPath = safeOwnProp(item, "path");
302
+ const itemMsg = safeOwnProp(item, "message");
303
+ if (typeof itemPath === "string")
304
+ parts.push(itemPath);
305
+ if (typeof itemMsg === "string")
306
+ parts.push(itemMsg);
307
+ if (Object.hasOwn(item, "expected") || Object.hasOwn(item, "actual")) {
308
+ parts.push(`expected ${safeJsonPreview(item.expected)}, got ${safeJsonPreview(item.actual)}`);
309
+ }
310
+ if (parts.length > 0)
311
+ out.push(parts.join(": "));
312
+ }
313
+ else {
314
+ extractDiffSignals(item, out, depth + 1, seen);
315
+ }
316
+ }
317
+ return;
318
+ }
319
+ if (isRecordSafe(diff)) {
320
+ let keysVisited = 0;
321
+ for (const [k, v] of Object.entries(diff)) {
322
+ if (out.length >= MAX_SCAN_SAMPLES || keysVisited >= 64)
323
+ break;
324
+ keysVisited++;
325
+ if (SKIPPED_DIFF_KEYS.has(k) || isForbiddenObjectKey(k))
326
+ continue;
327
+ extractDiffSignals(v, out, depth + 1, seen);
328
+ }
329
+ }
330
+ }
331
+ finally {
332
+ seen.delete(diff);
333
+ }
334
+ }
335
+ /** Runs `verifyContract` sequentially (always bypassing replay cache) to detect flakes and nondeterminism. */
336
+ export async function analyzeFlakes(contract, options = {}, deps = {}) {
337
+ const opts = isRecordSafe(options) ? options : {};
338
+ const safeDeps = isRecordSafe(deps) ? deps : {};
339
+ const runs = opts.runs === undefined ? DEFAULT_RUNS : opts.runs;
340
+ if (typeof runs !== "number" || !Number.isInteger(runs) || runs < MIN_RUNS || runs > MAX_RUNS) {
341
+ throw new VibecodeError("CONFIG_INVALID", `Invalid runs=${String(opts.runs)}: expected integer ${MIN_RUNS}..${MAX_RUNS}.`);
342
+ }
343
+ const validatedTargets = opts.targets !== undefined ? validateTargetMapObject(opts.targets) : undefined;
344
+ const targets = validatedTargets && Object.keys(validatedTargets).length > 0 ? validatedTargets : undefined;
345
+ const validatedVars = opts.vars !== undefined ? validateRuntimeVarsObject(opts.vars) : undefined;
346
+ const vars = validatedVars && Object.keys(validatedVars).length > 0 ? validatedVars : undefined;
347
+ const skipFixtures = Boolean(opts.skipFixtures);
348
+ const scrubText = (value) => redactSensitiveText(vars ? redactRuntimeVars(value, vars) : value);
349
+ const safeContract = isRecordSafe(contract) ? contract : { invariants: [] };
350
+ const revealHoldouts = Boolean(opts.revealHoldouts);
351
+ const strict = Boolean(opts.strict);
352
+ const contractInvById = new Map();
353
+ const contractInvs = Array.isArray(safeContract.invariants) ? safeContract.invariants : [];
354
+ for (const inv of contractInvs) {
355
+ if (isRecordSafe(inv) && typeof inv.id === "string") {
356
+ contractInvById.set(inv.id, inv);
357
+ }
358
+ }
359
+ const workspace = typeof opts.cwd === "string" && opts.cwd ? resolveWorkspace(opts.cwd) : null;
360
+ const baseCtx = {
361
+ target: typeof opts.target === "string" ? opts.target : "",
362
+ ...(targets ? { targets } : {}),
363
+ ...(vars ? { vars } : {}),
364
+ ...(skipFixtures ? { skipFixtures: true } : {}),
365
+ contract: safeContract,
366
+ strict,
367
+ useCache: false,
368
+ revealHoldouts,
369
+ ...(typeof opts.cwd === "string" && opts.cwd ? { cwd: opts.cwd } : {}),
370
+ ...(workspace ? { artifactsDir: workspace.artifactsDir, cacheDir: workspace.cacheDir } : {}),
371
+ ...(Array.isArray(opts.invariantIds) ? { invariantIds: opts.invariantIds } : {}),
372
+ ...(isRecordSafe(opts.headers) ? { headers: opts.headers } : {}),
373
+ ...(typeof opts.storageState === "string" && opts.storageState ? { storageState: opts.storageState } : {})
374
+ };
375
+ const runVerify = typeof safeDeps.verifyContract === "function" ? safeDeps.verifyContract : verifyContract;
376
+ const accumulators = new Map();
377
+ for (let runIdx = 0; runIdx < runs; runIdx++) {
378
+ const report = await runVerify(safeContract, { ...baseCtx, runtimeCache: {} }, safeDeps);
379
+ const results = isRecordSafe(report) && Array.isArray(report.results) ? report.results : [];
380
+ for (const res of results) {
381
+ if (!isRecordSafe(res) || typeof res.id !== "string")
382
+ continue;
383
+ let acc = accumulators.get(res.id);
384
+ if (!acc) {
385
+ acc = {
386
+ id: res.id,
387
+ type: String(res.type ?? "unknown"),
388
+ severity: String(res.severity ?? "hard"),
389
+ redacted: false,
390
+ passCount: 0,
391
+ failCount: 0,
392
+ skippedCount: 0,
393
+ statusesSeen: new Set(),
394
+ outputHashes: new Set(),
395
+ failureSignatures: new Set(),
396
+ rawSignals: [],
397
+ sampleFailures: [],
398
+ sampleFailureSet: new Set()
399
+ };
400
+ accumulators.set(res.id, acc);
401
+ }
402
+ const contractInv = contractInvById.get(res.id);
403
+ const resMetrics = safeOwnProp(res, "metrics");
404
+ const isHoldout = !revealHoldouts &&
405
+ (contractInv?.holdout === true ||
406
+ !contractInvById.has(res.id) ||
407
+ safeOwnProp(res, "redacted") === true ||
408
+ safeOwnProp(res, "holdout") === true ||
409
+ safeOwnProp(resMetrics, "holdout") === true);
410
+ if (isHoldout || safeOwnProp(resMetrics, "redacted") === true)
411
+ acc.redacted = true;
412
+ const status = typeof res.status === "string" ? res.status : "fail";
413
+ acc.statusesSeen.add(status);
414
+ if (status === "pass" || (status === "warn" && !strict))
415
+ acc.passCount++;
416
+ else if (status === "skipped")
417
+ acc.skippedCount++;
418
+ else
419
+ acc.failCount++;
420
+ if (acc.redacted)
421
+ continue;
422
+ const candHash = safeOwnProp(resMetrics, "candidateOutputHash");
423
+ if (typeof candHash === "string" && candHash.length > 0) {
424
+ acc.outputHashes.add(candHash);
425
+ }
426
+ if (status === "fail" || status === "error" || status === "warn") {
427
+ const runSignals = [];
428
+ const failureLines = [];
429
+ const scrubSignal = (raw) => (vars ? redactRuntimeVars(raw, vars) : raw);
430
+ const rawFailures = safeOwnProp(res, "failures");
431
+ if (Array.isArray(rawFailures)) {
432
+ for (const f of rawFailures) {
433
+ if (typeof f === "string" && f.length > 0) {
434
+ runSignals.push(scrubSignal(f));
435
+ failureLines.push(f);
436
+ }
437
+ }
438
+ }
439
+ const reason = safeOwnProp(res, "reason");
440
+ if (typeof reason === "string" && reason.length > 0) {
441
+ runSignals.push(scrubSignal(reason));
442
+ if (failureLines.length === 0)
443
+ failureLines.push(reason);
444
+ }
445
+ const diagMsg = safeOwnProp(safeOwnProp(res, "diagnostic"), "message");
446
+ if (typeof diagMsg === "string" && diagMsg.length > 0) {
447
+ runSignals.push(scrubSignal(diagMsg));
448
+ if (failureLines.length === 0)
449
+ failureLines.push(diagMsg);
450
+ }
451
+ const diffSignals = [];
452
+ extractDiffSignals(safeOwnProp(res, "diff"), diffSignals);
453
+ for (const ds of diffSignals)
454
+ runSignals.push(scrubSignal(ds));
455
+ for (const sig of runSignals) {
456
+ if (acc.rawSignals.length < MAX_SCAN_SAMPLES)
457
+ acc.rawSignals.push(sig);
458
+ }
459
+ acc.failureSignatures.add(runSignals.length > 0 ? `${status}:${runSignals.join("\n---\n")}` : `status:${status}`);
460
+ if (status !== "warn" || strict) {
461
+ for (const line of failureLines) {
462
+ if (acc.sampleFailures.length >= MAX_SAMPLE_FAILURES)
463
+ break;
464
+ const clean = sanitizeSingleLine(scrubText(line), MAX_SAMPLE_FAILURE_CHARS);
465
+ if (clean.length > 0 && !acc.sampleFailureSet.has(clean)) {
466
+ acc.sampleFailureSet.add(clean);
467
+ acc.sampleFailures.push(clean);
468
+ }
469
+ }
470
+ }
471
+ }
472
+ }
473
+ }
474
+ const invariants = [];
475
+ const allSuggestedModes = new Set();
476
+ let deterministicPass = 0, deterministicFail = 0, flakyIntermittent = 0, nondeterministicOutput = 0, skipped = 0;
477
+ for (const acc of accumulators.values()) {
478
+ const distinctOutputHashes = acc.redacted ? 0 : acc.outputHashes.size;
479
+ const distinctFailureSignatures = acc.redacted ? 0 : acc.failureSignatures.size;
480
+ const nondeterminismKinds = acc.redacted ? [] : detectNondeterminismKinds(acc.rawSignals);
481
+ const existingNorm = contractInvById.get(acc.id)?.expected?.normalize;
482
+ const suggestedRules = acc.redacted ? [] : synthesizeNormalizeRules(nondeterminismKinds, existingNorm);
483
+ const sampleFailures = acc.redacted ? [] : acc.sampleFailures;
484
+ const sawStatusDrift = acc.statusesSeen.size > 1;
485
+ const totalSeen = acc.passCount + acc.failCount + acc.skippedCount;
486
+ let classification;
487
+ if (acc.skippedCount === runs && totalSeen === runs) {
488
+ classification = "skipped";
489
+ skipped++;
490
+ }
491
+ else if ((acc.passCount > 0 && acc.failCount > 0) ||
492
+ (acc.skippedCount > 0 && (acc.passCount > 0 || acc.failCount > 0)) ||
493
+ totalSeen !== runs) {
494
+ classification = "flaky_intermittent";
495
+ flakyIntermittent++;
496
+ }
497
+ else if (acc.passCount === runs &&
498
+ (distinctOutputHashes > 1 || sawStatusDrift || (!acc.redacted && (distinctFailureSignatures > 1 || nondeterminismKinds.length > 0)))) {
499
+ classification = "nondeterministic_output";
500
+ nondeterministicOutput++;
501
+ }
502
+ else if (acc.failCount === runs &&
503
+ (distinctOutputHashes > 1 || distinctFailureSignatures > 1 || nondeterminismKinds.length > 0 || sawStatusDrift)) {
504
+ classification = "nondeterministic_output";
505
+ nondeterministicOutput++;
506
+ }
507
+ else if (acc.passCount === runs) {
508
+ classification = "deterministic_pass";
509
+ deterministicPass++;
510
+ }
511
+ else {
512
+ classification = "deterministic_fail";
513
+ deterministicFail++;
514
+ }
515
+ for (const rule of suggestedRules)
516
+ for (const m of rule.normalizeModes)
517
+ allSuggestedModes.add(m);
518
+ invariants.push({
519
+ id: sanitizeSingleLine(scrubText(acc.id)),
520
+ type: sanitizeSingleLine(scrubText(acc.type)),
521
+ severity: sanitizeSingleLine(scrubText(acc.severity)),
522
+ redacted: acc.redacted,
523
+ runs,
524
+ passCount: acc.passCount,
525
+ failCount: acc.failCount,
526
+ skippedCount: acc.skippedCount,
527
+ classification,
528
+ distinctOutputHashes,
529
+ distinctFailureSignatures,
530
+ nondeterminismKinds,
531
+ suggestedRules,
532
+ sampleFailures
533
+ });
534
+ }
535
+ const hasFlakes = flakyIntermittent > 0 || nondeterministicOutput > 0;
536
+ const targetName = isRecordSafe(safeContract.target) && typeof safeContract.target.name === "string"
537
+ ? safeContract.target.name
538
+ : "unknown";
539
+ return {
540
+ ok: !hasFlakes && deterministicFail === 0,
541
+ contractName: sanitizeSingleLine(scrubText(targetName)),
542
+ runs,
543
+ evaluated: invariants.length - skipped,
544
+ deterministicPass,
545
+ deterministicFail,
546
+ flakyIntermittent,
547
+ nondeterministicOutput,
548
+ skipped,
549
+ hasFlakes,
550
+ invariants,
551
+ suggestedNormalizeModes: NORMALIZE_MODE_ORDER.filter((m) => allSuggestedModes.has(m)),
552
+ generatedAt: new Date().toISOString()
553
+ };
554
+ }
555
+ function classificationBadge(classification, useColor) {
556
+ switch (classification) {
557
+ case "deterministic_pass": return styleAnsi("[PASS]", `${ANSI.bold}${ANSI.green}`, useColor);
558
+ case "deterministic_fail": return styleAnsi("[FAIL]", `${ANSI.bold}${ANSI.red}`, useColor);
559
+ case "flaky_intermittent": return styleAnsi("[FLAKY]", `${ANSI.bold}${ANSI.yellow}`, useColor);
560
+ case "nondeterministic_output": return styleAnsi("[NONDET]", `${ANSI.bold}${ANSI.yellow}`, useColor);
561
+ case "skipped": return styleAnsi("[SKIP]", `${ANSI.bold}${ANSI.dim}`, useColor);
562
+ }
563
+ }
564
+ /** Formats a FlakeAnalysisReport for human-readable terminal display (plain or ANSI color). */
565
+ export function formatPrettyFlake(report, options = {}) {
566
+ const opts = isRecordSafe(options) ? options : {};
567
+ const useColor = opts.color === true;
568
+ const bannerText = report?.ok ? "STABLE" : report?.hasFlakes ? "FLAKY" : "DETERMINISTIC FAIL";
569
+ const bannerColor = report?.ok ? `${ANSI.bold}${ANSI.green}` : report?.hasFlakes ? `${ANSI.bold}${ANSI.yellow}` : `${ANSI.bold}${ANSI.red}`;
570
+ const lines = [
571
+ `${styleAnsi(`[${bannerText}]`, bannerColor, useColor)} ${styleAnsi(sanitizeSingleLine(String(report?.contractName ?? "unknown")), ANSI.bold, useColor)} (${report?.runs ?? 0} runs)`,
572
+ `Summary: evaluated=${report?.evaluated ?? 0}, pass=${report?.deterministicPass ?? 0}, fail=${report?.deterministicFail ?? 0}, flaky=${report?.flakyIntermittent ?? 0}, nondeterministic=${report?.nondeterministicOutput ?? 0}, skipped=${report?.skipped ?? 0}`
573
+ ];
574
+ const suggestedModes = Array.isArray(report?.suggestedNormalizeModes) ? report.suggestedNormalizeModes : [];
575
+ if (suggestedModes.length > 0) {
576
+ lines.push(`Normalize Modes: ${styleAnsi(suggestedModes.map((m) => sanitizeSingleLine(String(m))).join(", "), ANSI.cyan, useColor)}`);
577
+ }
578
+ const invs = Array.isArray(report?.invariants) ? report.invariants : [];
579
+ if (invs.length > 0) {
580
+ lines.push(`Invariants (${invs.length}):`);
581
+ for (const inv of invs) {
582
+ if (!isRecordSafe(inv))
583
+ continue;
584
+ const counts = `${inv.passCount}/${inv.runs} pass, ${inv.failCount} fail${inv.skippedCount > 0 ? `, ${inv.skippedCount} skipped` : ""}`;
585
+ const redactedTag = inv.redacted ? ` ${styleAnsi("[holdout redacted]", ANSI.dim, useColor)}` : "";
586
+ lines.push(` - ${classificationBadge(inv.classification, useColor)} ${sanitizeSingleLine(String(inv.id))} ${styleAnsi(`(${sanitizeSingleLine(String(inv.type))}, ${sanitizeSingleLine(String(inv.severity))})`, ANSI.dim, useColor)} ${counts}${redactedTag}`);
587
+ if (inv.redacted)
588
+ continue;
589
+ const signals = [];
590
+ if (inv.distinctOutputHashes > 1)
591
+ signals.push(`hashes=${inv.distinctOutputHashes}`);
592
+ const kinds = Array.isArray(inv.nondeterminismKinds) ? inv.nondeterminismKinds : [];
593
+ if (kinds.length > 0)
594
+ signals.push(`kinds=${kinds.join(", ")}`);
595
+ if (signals.length > 0)
596
+ lines.push(` ${styleAnsi("signals:", ANSI.dim, useColor)} ${signals.join("; ")}`);
597
+ const rules = Array.isArray(inv.suggestedRules) ? inv.suggestedRules : [];
598
+ for (const rule of rules) {
599
+ if (isRecordSafe(rule))
600
+ lines.push(` ${styleAnsi("hint:", ANSI.dim, useColor)} ${sanitizeSingleLine(String(rule.contractHint ?? ""))}`);
601
+ }
602
+ const samples = Array.isArray(inv.sampleFailures) ? inv.sampleFailures : [];
603
+ for (const sample of samples)
604
+ lines.push(` ${styleAnsi("failure:", ANSI.dim, useColor)} ${sanitizeSingleLine(String(sample))}`);
605
+ }
606
+ }
607
+ return lines.join("\n");
608
+ }