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,796 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { VibecodeError } from "./errors.js";
5
+ import { serializeYaml } from "./openapi-export.js";
6
+ import { isSensitiveHeader, isSensitiveQueryParam } from "../ingestors/trace.js";
7
+ const DEFAULT_FORMAT = "github-actions";
8
+ const DEFAULT_NODE_VERSION = "22";
9
+ const DEFAULT_TITLE = "Vibecode Parity";
10
+ const MAX_TITLE_LEN = 120;
11
+ const MAX_TARGET_LEN = 256;
12
+ const MAX_SLICE_ID_LEN = 80;
13
+ const MAX_PRETTY_SLICES = 12;
14
+ const MAX_PRETTY_WARNINGS = 10;
15
+ const VALID_FORMATS = new Set(["github-actions", "gitlab-ci", "makefile"]);
16
+ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
17
+ const SAFE_NODE_VERSION_RE = /^v?([1-9]\d?(?:\.\d{1,3}){0,2})$/;
18
+ const ANSI_ESCAPE_RE = /\x1B\[[0-?]*[ -/]*[@-~]/g;
19
+ const BIDI_AND_BOM_RE = /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g;
20
+ const CONTROL_CHAR_RE = /[\0\r\n\u0085\u2028\u2029\x00-\x1f\x7f-\x9f]+/g;
21
+ const SENSITIVE_HEADER_NAME_RE = /(?:authorization|proxy[-_]?authorization|cookie|set[-_]?cookie|api[-_]?key|apikey|token|secret|bearer|csrf|xsrf|password|passwd|passphrase|credential|private[-_]?key|session[-_]?id|jwt|hmac|signature|signing[-_]?key|webhook[-_]?secret|(?:^|[-_])auth(?:$|[-_]))/i;
22
+ const SENSITIVE_QUERY_NAME_RE = /(?:access[_-]?token|id[_-]?token|refresh[_-]?token|auth[_-]?token|token|api[_-]?key|apikey|secret|client[_-]?secret|webhook[-_]?secret|signing[_-]?key|password|passwd|passphrase|jwt|session[_-]?id|private[_-]?key|authorization|cookie|csrf|xsrf|bearer|credential|hmac|(?:^|[_-])(?:auth|sig|signature)(?:$|[_-]))/i;
23
+ const AUTH_SCHEME_VALUE_RE = /(?:^|\s)(?:bearer|basic|token|apikey|oauth|hmac)\s+\S+|(?:^|\s)digest\s+(?:[a-z0-9_-]+=(?:[^\s,"'`<>]+|"(?:\\.|[^"\\\r\n])*")|[a-z0-9._~+/:-]{6,})/i;
24
+ const VAULT_PATH_RE = /(?:~|[A-Za-z]:|\\\\[^\s"'`<>]+)?[^\s"'`<>()[\]{}]*\.vibecode-vault[^\s"'`<>()[\]{}]*/gi;
25
+ const URL_IN_TEXT_RE = /(?:[a-zA-Z][a-zA-Z0-9+.-]*:\/\/|(?<=^|[\s"'`(\[{=,;|])\/\/)[^\s"'`<>]+/g;
26
+ // Greedy match up to the final `@` in the authority (before `/`, `?`, or `#`) so multi-`@` passwords are fully stripped.
27
+ const URL_BASIC_AUTH_RE = /([a-zA-Z][a-zA-Z0-9+.-]*:\/\/|(?<=^|[\s"'`(\[{=,;|])\/\/)([^/?#\s"'`<>]+)@/g;
28
+ // Scheme-before-header inline redaction patterns.
29
+ // Digest kv-first branch matches multi-pair RFC 7616 params before falling back to single token.
30
+ const INLINE_DIGEST_RE = /\b(Digest)\s+(?:[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"(?:\\.|[^"\\\r\n])*")(?:\s*,\s*[A-Za-z0-9_-]+=(?:[^\s,"'`<>]+|"(?:\\.|[^"\\\r\n])*"))*|[A-Za-z0-9._~+/:-]{6,}={0,2})/gi;
31
+ const INLINE_BEARER_RE = /\b(Bearer)\s+[^\s"'`<>]+/gi;
32
+ const INLINE_BASIC_RE = /\b(Basic)\s+[A-Za-z0-9._~+/=-]{4,}/gi;
33
+ const INLINE_SCHEME_TOKEN_RE = /\b(Token|ApiKey|OAuth)\s+[A-Za-z0-9._~+/=:-]{4,}/gi;
34
+ const INLINE_COOKIE_RE = /\b(Cookie|Set-Cookie)\s*[:=]\s*[^\s,\r\n;|]+(?:\s*;\s*[A-Za-z0-9_.-]+(?:=[^\s,\r\n;|]+)?)*/gi;
35
+ const INLINE_SENSITIVE_HEADER_RE = /\b(Authorization|Proxy-Authorization|X-API-Key|X-Auth-Token|X-Access-Token|X-Session-Token|X-Secret|X-Webhook-Secret|X-Hub-Signature(?:-256)?|X-Webhook-Signature|X-Signature(?:-256|-sha256|-hmac)?|X-Hmac(?:-Signature|-Sha256)?|X-CSRF-Token|X-XSRF-Token|CSRF-Token|XSRF-Token)\s*[:=]\s*(?:(?:[A-Za-z][A-Za-z0-9._-]{1,31})\s+(?:\[REDACTED\]|[^\s,;|]+)|[^\s,;|]+)/gi;
36
+ const INLINE_SENSITIVE_QUERY_RE = /([?&])([^=&\s#]+)=([^&\s#]+)/g;
37
+ const INLINE_KV_SECRET_RE = /\b([A-Za-z0-9_.-]*(?:aws[_-]?secret[_-]?access[_-]?key|aws[_-]?access[_-]?key[_-]?id|aws[_-]?session[_-]?token|stripe[_-]?secret[_-]?key|api[_-]?key|apikey|access[_-]?token|refresh[_-]?token|id[_-]?token|auth[_-]?token|client[_-]?secret|private[_-]?key|access[_-]?key|secret[_-]?key|signing[_-]?key|encryption[_-]?key|master[_-]?key|session[_-]?id|session[_-]?secret|jwt[_-]?secret|webhook[_-]?secret|password|passwd|passphrase|secret|token|jwt|hmac|signature|credentials?|authorization|cookie|csrf[_-]?token|xsrf[_-]?token)[A-Za-z0-9_.-]*)(["']?)\s*([:=])\s*(?:"((?:\\.|[^"\\\r\n])*)"|'((?:\\.|[^'\\\r\n])*)'|([^\s,;&"'`<>]+))/gi;
38
+ const BARE_SECRET_TOKEN_RE = /\b(?:sk_(?:live|test)_[A-Za-z0-9]{8,}|pk_(?:live|test)_[A-Za-z0-9]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|glpat-[A-Za-z0-9_-]{12,}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,}|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})\b/g;
39
+ const REPORT_COMMAND = "npx vibecode-anything report --out .vibecode/report.html --sarif .vibecode/results.sarif --junit .vibecode/junit.xml --badge .vibecode/parity-badge.svg --markdown .vibecode/pr-comment.md";
40
+ const REPORT_ARTIFACT_PATHS = [
41
+ ".vibecode/report.html",
42
+ ".vibecode/results.sarif",
43
+ ".vibecode/junit.xml",
44
+ ".vibecode/parity-badge.svg",
45
+ ".vibecode/pr-comment.md",
46
+ ".vibecode/last-report.json"
47
+ ];
48
+ const ANSI = {
49
+ reset: "\x1b[0m",
50
+ bold: "\x1b[1m",
51
+ dim: "\x1b[2m",
52
+ green: "\x1b[32m",
53
+ yellow: "\x1b[33m",
54
+ cyan: "\x1b[36m"
55
+ };
56
+ function isRecord(value) {
57
+ return value !== null && typeof value === "object" && !Array.isArray(value);
58
+ }
59
+ function isForbiddenKey(key) {
60
+ return FORBIDDEN_KEYS.has(key);
61
+ }
62
+ function stripControlsAndBidi(raw) {
63
+ return String(raw)
64
+ .replace(ANSI_ESCAPE_RE, "")
65
+ .replace(BIDI_AND_BOM_RE, "")
66
+ .replace(CONTROL_CHAR_RE, " ");
67
+ }
68
+ function isSensitiveHeaderName(name) {
69
+ const normalized = stripControlsAndBidi(name).trim();
70
+ if (!normalized)
71
+ return false;
72
+ return isSensitiveHeader(normalized) || SENSITIVE_HEADER_NAME_RE.test(normalized);
73
+ }
74
+ function isSensitiveQueryName(name) {
75
+ const normalized = stripControlsAndBidi(name).trim();
76
+ if (!normalized)
77
+ return false;
78
+ return (isSensitiveQueryParam(normalized) ||
79
+ SENSITIVE_QUERY_NAME_RE.test(normalized) ||
80
+ isSensitiveHeaderName(normalized));
81
+ }
82
+ function hasAuthSchemeValue(value) {
83
+ return AUTH_SCHEME_VALUE_RE.test(value);
84
+ }
85
+ function redactVaultPaths(text) {
86
+ return text.replace(VAULT_PATH_RE, "[REDACTED_VAULT]");
87
+ }
88
+ function stripUntrustedExpressions(text) {
89
+ let out = text;
90
+ let outerPrev = "";
91
+ while (out !== outerPrev) {
92
+ outerPrev = out;
93
+ // Strip complete expressions to fixed-point first so nested payloads like
94
+ // `${$(shell id){ secrets.PWN }}` collapse to `${{ secrets.PWN }}` before opener stripping.
95
+ let closedPrev = "";
96
+ while (out !== closedPrev) {
97
+ closedPrev = out;
98
+ out = out.replace(/\$\{\{[\s\S]*?\}\}/g, "");
99
+ out = out.replace(/\$\([^()]*\)/g, "");
100
+ out = out.replace(/\$\{[^{}]*\}/g, "");
101
+ out = out.replace(/`[^`]*`/g, "");
102
+ }
103
+ out = out
104
+ .replace(/\$\{\{/g, "")
105
+ .replace(/\$\(/g, "")
106
+ .replace(/\$\{/g, "")
107
+ .replace(/`/g, "");
108
+ }
109
+ return out;
110
+ }
111
+ function scrubInlineKvSecrets(text) {
112
+ return text.replace(INLINE_KV_SECRET_RE, (full, key, q, sep, dq, sq, bare) => {
113
+ const val = dq ?? sq ?? bare ?? "";
114
+ if (val === "[REDACTED]" || val === "[REDACTED_VAULT]")
115
+ return full;
116
+ if (dq !== undefined)
117
+ return `${key}${q}${sep}"[REDACTED]"`;
118
+ if (sq !== undefined)
119
+ return `${key}${q}${sep}'[REDACTED]'`;
120
+ return `${key}${q}${sep}[REDACTED]`;
121
+ });
122
+ }
123
+ function hasEmbeddedCredentialOrVault(text) {
124
+ const clean = stripControlsAndBidi(text);
125
+ if (!clean)
126
+ return false;
127
+ if (/\.vibecode-vault/i.test(clean))
128
+ return true;
129
+ if (clean.search(URL_BASIC_AUTH_RE) >= 0)
130
+ return true;
131
+ if (hasAuthSchemeValue(clean))
132
+ return true;
133
+ return false;
134
+ }
135
+ function sanitizeUrlInText(rawUrl) {
136
+ const withoutVault = redactVaultPaths(rawUrl);
137
+ const withoutAuth = withoutVault.replace(URL_BASIC_AUTH_RE, "$1");
138
+ const filterParams = (entries) => {
139
+ const safeParams = new URLSearchParams();
140
+ for (const [k, v] of entries) {
141
+ const cleanK = stripControlsAndBidi(k).trim();
142
+ if (!cleanK || isForbiddenKey(cleanK) || isSensitiveQueryName(cleanK))
143
+ continue;
144
+ if (hasEmbeddedCredentialOrVault(cleanK) || hasEmbeddedCredentialOrVault(v))
145
+ continue;
146
+ const scrubbedVal = scrubSecrets(v);
147
+ if (/\[REDACTED/i.test(scrubbedVal))
148
+ continue;
149
+ safeParams.append(cleanK, scrubbedVal);
150
+ }
151
+ return safeParams.toString();
152
+ };
153
+ const isProtoRelative = withoutAuth.startsWith("//");
154
+ try {
155
+ const parsed = new URL(isProtoRelative ? `https:${withoutAuth}` : withoutAuth);
156
+ if (!isProtoRelative && parsed.protocol !== "http:" && parsed.protocol !== "https:") {
157
+ return "[REDACTED_URL]";
158
+ }
159
+ parsed.username = "";
160
+ parsed.password = "";
161
+ const serialized = filterParams(parsed.searchParams.entries());
162
+ parsed.search = serialized ? `?${serialized}` : "";
163
+ parsed.hash = "";
164
+ if (isProtoRelative) {
165
+ const basePath = parsed.pathname === "/" && !parsed.search && !withoutAuth.endsWith("/") ? "" : parsed.pathname;
166
+ return `//${parsed.host}${basePath}${parsed.search}`;
167
+ }
168
+ const formatted = parsed.toString();
169
+ // Preserve compact origin form when original had no trailing slash on root path.
170
+ if (parsed.pathname === "/" && !parsed.search && !withoutAuth.endsWith("/")) {
171
+ return formatted.replace(/\/$/, "");
172
+ }
173
+ return formatted;
174
+ }
175
+ catch {
176
+ const cleanFallback = withoutAuth.replace(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/|\/\/)[^/?#\s"'`<>]*@+/, "$1");
177
+ if (!/^(?:https?:)?\/\//i.test(cleanFallback)) {
178
+ return "[REDACTED_URL]";
179
+ }
180
+ const hashIdx = cleanFallback.indexOf("#");
181
+ const noHash = hashIdx >= 0 ? cleanFallback.slice(0, hashIdx) : cleanFallback;
182
+ const qIdx = noHash.indexOf("?");
183
+ if (qIdx < 0)
184
+ return noHash;
185
+ const basePart = noHash.slice(0, qIdx);
186
+ const serialized = filterParams(new URLSearchParams(noHash.slice(qIdx + 1)).entries());
187
+ return serialized ? `${basePart}?${serialized}` : basePart;
188
+ }
189
+ }
190
+ function scrubSecrets(raw) {
191
+ const noVault = redactVaultPaths(raw);
192
+ const noUrls = noVault.replace(URL_IN_TEXT_RE, (match) => sanitizeUrlInText(match));
193
+ const noBasicAuth = noUrls.replace(URL_BASIC_AUTH_RE, "$1");
194
+ const noSensQuery = noBasicAuth.replace(INLINE_SENSITIVE_QUERY_RE, (match, sep, key) => isSensitiveQueryName(key) ? `${sep}${key}=[REDACTED]` : match);
195
+ // Scheme-before-header redaction ensures Digest (kv-first), Bearer, Basic, Token, ApiKey are scrubbed first.
196
+ const noDigest = noSensQuery.replace(INLINE_DIGEST_RE, "$1 [REDACTED]");
197
+ const noBearer = noDigest.replace(INLINE_BEARER_RE, "$1 [REDACTED]");
198
+ const noBasic = noBearer.replace(INLINE_BASIC_RE, "$1 [REDACTED]");
199
+ const noScheme = noBasic.replace(INLINE_SCHEME_TOKEN_RE, "$1 [REDACTED]");
200
+ const noCookie = noScheme.replace(INLINE_COOKIE_RE, "$1: [REDACTED]");
201
+ const noSensHeader = noCookie.replace(INLINE_SENSITIVE_HEADER_RE, "$1: [REDACTED]");
202
+ const noKv = scrubInlineKvSecrets(noSensHeader);
203
+ return noKv.replace(BARE_SECRET_TOKEN_RE, "[REDACTED]");
204
+ }
205
+ function sanitizeUntrustedSingleLine(raw, maxLen) {
206
+ const noControls = stripControlsAndBidi(String(raw));
207
+ const noExpr = stripUntrustedExpressions(noControls);
208
+ const scrubbed = scrubSecrets(noExpr);
209
+ const cleaned = stripUntrustedExpressions(scrubbed)
210
+ .replace(CONTROL_CHAR_RE, " ")
211
+ .replace(/\s+/g, " ")
212
+ .trim();
213
+ if (cleaned.length <= maxLen)
214
+ return cleaned;
215
+ return cleaned.slice(0, Math.max(1, maxLen)).trim();
216
+ }
217
+ function sanitizeMakefileComment(raw) {
218
+ return sanitizeUntrustedSingleLine(raw, MAX_TITLE_LEN)
219
+ .replace(/\\+$/, "")
220
+ .trim();
221
+ }
222
+ function escapeMakeDollar(raw) {
223
+ return raw.replace(/\$/g, () => "$$");
224
+ }
225
+ function shellSingleQuote(raw) {
226
+ return `'${raw.replace(/'/g, "'\\''")}'`;
227
+ }
228
+ function makefileShellSingleQuote(raw) {
229
+ // Double any `$` for Make before single-quoting for POSIX sh.
230
+ return escapeMakeDollar(shellSingleQuote(raw));
231
+ }
232
+ function validateNodeVersion(raw) {
233
+ if (raw === undefined)
234
+ return DEFAULT_NODE_VERSION;
235
+ if (typeof raw !== "string") {
236
+ throw new VibecodeError("CONTRACT_INVALID", "exportCiPipeline option \"nodeVersion\" must be a valid Node.js version string (e.g. \"22\" or \"20.18.0\").");
237
+ }
238
+ const trimmed = raw.trim();
239
+ if (!trimmed || /[\0\r\n]/.test(trimmed)) {
240
+ throw new VibecodeError("CONTRACT_INVALID", "exportCiPipeline option \"nodeVersion\" must be a valid Node.js version string (e.g. \"22\" or \"20.18.0\").");
241
+ }
242
+ const match = SAFE_NODE_VERSION_RE.exec(trimmed);
243
+ if (!match) {
244
+ throw new VibecodeError("CONTRACT_INVALID", `Invalid nodeVersion "${sanitizeUntrustedSingleLine(trimmed, 40)}". Expected a numeric Node.js version such as "22" or "20.18.0".`);
245
+ }
246
+ return match[1];
247
+ }
248
+ function sanitizeTargetOption(rawTarget, warnings) {
249
+ if (rawTarget === undefined)
250
+ return undefined;
251
+ const trimmed = String(rawTarget).trim();
252
+ if (!trimmed)
253
+ return undefined;
254
+ const compactRaw = stripControlsAndBidi(trimmed).replace(/\s+/g, "");
255
+ if (/^(?:javascript|data|vbscript):/i.test(compactRaw)) {
256
+ warnings.push("Rejected unsafe URI scheme in target option; falling back to VIBECODE_TARGET environment variable.");
257
+ return undefined;
258
+ }
259
+ const cleaned = sanitizeUntrustedSingleLine(trimmed, MAX_TARGET_LEN);
260
+ if (!cleaned ||
261
+ cleaned === "[REDACTED]" ||
262
+ /\[REDACTED_VAULT\]/i.test(cleaned) ||
263
+ /\[REDACTED_URL\]/i.test(cleaned) ||
264
+ /^(?:javascript|data|vbscript):/i.test(cleaned)) {
265
+ warnings.push("Rejected unsafe or fully redacted target option; falling back to VIBECODE_TARGET environment variable.");
266
+ return undefined;
267
+ }
268
+ return cleaned;
269
+ }
270
+ function fileMetadataFor(format) {
271
+ switch (format) {
272
+ case "github-actions":
273
+ return { fileExtension: ".yml", defaultFileName: "vibecode-parity.yml" };
274
+ case "gitlab-ci":
275
+ return { fileExtension: ".yml", defaultFileName: ".gitlab-ci.yml" };
276
+ case "makefile":
277
+ return { fileExtension: ".mk", defaultFileName: "Makefile.vibecode" };
278
+ }
279
+ }
280
+ function buildVerifyCommand(target, strict, cache, sliceArg) {
281
+ const parts = ["npx vibecode-anything verify"];
282
+ if (target) {
283
+ parts.push(`--target ${shellSingleQuote(target)}`);
284
+ }
285
+ else {
286
+ parts.push('--target "${VIBECODE_TARGET}"');
287
+ }
288
+ if (sliceArg) {
289
+ parts.push(`--slice ${sliceArg}`);
290
+ }
291
+ if (strict) {
292
+ parts.push("--strict");
293
+ }
294
+ if (cache) {
295
+ parts.push("--cache");
296
+ }
297
+ parts.push("--pretty");
298
+ return parts.join(" ");
299
+ }
300
+ function emitGithubActions(model) {
301
+ const verifyCmd = buildVerifyCommand(model.target, model.strict, model.cache);
302
+ const lintCmd = `npx vibecode-anything lint${model.strict ? " --strict" : ""} --pretty`;
303
+ const jobEnv = {};
304
+ if (!model.target) {
305
+ jobEnv.VIBECODE_TARGET = "${{ vars.VIBECODE_TARGET }}";
306
+ }
307
+ jobEnv.VIBECODE_AUTH_TOKEN = "${{ secrets.VIBECODE_AUTH_TOKEN }}";
308
+ jobEnv.VIBECODE_API_KEY = "${{ secrets.VIBECODE_API_KEY }}";
309
+ const setupNodeWith = {
310
+ "node-version": model.nodeVersion
311
+ };
312
+ if (model.cache) {
313
+ setupNodeWith.cache = "npm";
314
+ }
315
+ const paritySteps = [
316
+ {
317
+ name: "Checkout repository",
318
+ uses: "actions/checkout@v4"
319
+ },
320
+ {
321
+ name: "Setup Node.js",
322
+ uses: "actions/setup-node@v4",
323
+ with: setupNodeWith
324
+ }
325
+ ];
326
+ if (model.cache) {
327
+ paritySteps.push({
328
+ name: "Cache vibecode verification state",
329
+ uses: "actions/cache@v4",
330
+ with: {
331
+ path: ".vibecode/cache",
332
+ key: "vibecode-cache-${{ runner.os }}-${{ hashFiles('.vibecode/contract.json') }}",
333
+ "restore-keys": "vibecode-cache-${{ runner.os }}-"
334
+ }
335
+ });
336
+ }
337
+ paritySteps.push({
338
+ name: "Install dependencies",
339
+ run: "npm ci || npm install"
340
+ }, {
341
+ name: "Lint contract",
342
+ run: lintCmd
343
+ }, {
344
+ name: "Verify contract parity",
345
+ id: "verify",
346
+ run: verifyCmd
347
+ }, {
348
+ name: "Generate parity reports",
349
+ if: "always()",
350
+ run: REPORT_COMMAND
351
+ }, {
352
+ name: "Upload parity artifacts",
353
+ if: "always()",
354
+ uses: "actions/upload-artifact@v4",
355
+ with: {
356
+ name: "vibecode-parity-reports",
357
+ path: REPORT_ARTIFACT_PATHS.join("\n"),
358
+ "if-no-files-found": "warn"
359
+ }
360
+ });
361
+ const jobs = {
362
+ parity: {
363
+ name: "Verify Contract Parity",
364
+ "runs-on": "ubuntu-latest",
365
+ env: jobEnv,
366
+ steps: paritySteps
367
+ }
368
+ };
369
+ if (model.slices.length > 0) {
370
+ const sliceIds = model.slices.map((s) => s.id);
371
+ const sliceEnv = {
372
+ ...jobEnv,
373
+ VIBECODE_SLICE: "${{ matrix.slice }}"
374
+ };
375
+ const sliceVerifyCmd = buildVerifyCommand(model.target, model.strict, model.cache, '"${VIBECODE_SLICE}"');
376
+ const sliceSteps = [
377
+ {
378
+ name: "Checkout repository",
379
+ uses: "actions/checkout@v4"
380
+ },
381
+ {
382
+ name: "Setup Node.js",
383
+ uses: "actions/setup-node@v4",
384
+ with: setupNodeWith
385
+ },
386
+ {
387
+ name: "Install dependencies",
388
+ run: "npm ci || npm install"
389
+ },
390
+ {
391
+ name: "Verify contract slice",
392
+ run: sliceVerifyCmd
393
+ }
394
+ ];
395
+ jobs["verify-slices"] = {
396
+ name: "Verify Slice (${{ matrix.slice }})",
397
+ "runs-on": "ubuntu-latest",
398
+ needs: ["parity"],
399
+ strategy: {
400
+ "fail-fast": false,
401
+ matrix: {
402
+ slice: sliceIds
403
+ }
404
+ },
405
+ env: sliceEnv,
406
+ steps: sliceSteps
407
+ };
408
+ }
409
+ const workflow = {
410
+ name: model.title,
411
+ on: {
412
+ push: {
413
+ branches: ["main"]
414
+ },
415
+ pull_request: {
416
+ branches: ["main"]
417
+ },
418
+ workflow_dispatch: {}
419
+ },
420
+ permissions: {
421
+ contents: "read"
422
+ },
423
+ concurrency: {
424
+ group: "vibecode-parity-${{ github.ref }}",
425
+ "cancel-in-progress": true
426
+ },
427
+ jobs
428
+ };
429
+ const headerLines = [
430
+ "# Generated by vibecode-anything ci-export (github-actions)",
431
+ `# Workflow: ${model.title}`,
432
+ `# Domains: ${model.domainSummary.length > 0 ? model.domainSummary.join(", ") : "none"}`,
433
+ `# Visible invariants: ${model.invariantCount}`
434
+ ];
435
+ return `${headerLines.join("\n")}\n${serializeYaml(workflow)}`;
436
+ }
437
+ function emitGitlabCi(model) {
438
+ const verifyCmd = buildVerifyCommand(model.target, model.strict, model.cache);
439
+ const lintCmd = `npx vibecode-anything lint${model.strict ? " --strict" : ""} --pretty`;
440
+ const variables = {
441
+ VIBECODE_STRICT: model.strict ? "true" : "false"
442
+ };
443
+ if (model.cache) {
444
+ variables.VIBECODE_CACHE = "true";
445
+ }
446
+ const doc = {
447
+ image: `node:${model.nodeVersion}-alpine`,
448
+ stages: ["lint", "verify"],
449
+ variables
450
+ };
451
+ if (model.cache) {
452
+ doc.cache = {
453
+ key: "vibecode-${CI_COMMIT_REF_SLUG}",
454
+ paths: ["node_modules/", ".vibecode/cache/"]
455
+ };
456
+ }
457
+ doc["vibecode-lint"] = {
458
+ stage: "lint",
459
+ script: ["npm ci || npm install", lintCmd]
460
+ };
461
+ doc["vibecode-parity"] = {
462
+ stage: "verify",
463
+ script: [
464
+ "npm ci || npm install",
465
+ "set +e",
466
+ verifyCmd,
467
+ "VERIFY_EXIT=$?",
468
+ `${REPORT_COMMAND} || true`,
469
+ "exit $VERIFY_EXIT"
470
+ ],
471
+ artifacts: {
472
+ when: "always",
473
+ paths: [...REPORT_ARTIFACT_PATHS],
474
+ reports: {
475
+ junit: ".vibecode/junit.xml"
476
+ }
477
+ }
478
+ };
479
+ if (model.slices.length > 0) {
480
+ const sliceVerifyCmd = buildVerifyCommand(model.target, model.strict, model.cache, '"${VIBECODE_SLICE}"');
481
+ doc["vibecode-parity-slices"] = {
482
+ stage: "verify",
483
+ parallel: {
484
+ matrix: [
485
+ {
486
+ VIBECODE_SLICE: model.slices.map((s) => s.id)
487
+ }
488
+ ]
489
+ },
490
+ script: ["npm ci || npm install", sliceVerifyCmd]
491
+ };
492
+ }
493
+ const headerLines = [
494
+ "# Generated by vibecode-anything ci-export (gitlab-ci)",
495
+ `# Pipeline: ${model.title}`,
496
+ `# Domains: ${model.domainSummary.length > 0 ? model.domainSummary.join(", ") : "none"}`,
497
+ `# Visible invariants: ${model.invariantCount}`,
498
+ "# Configure secrets (VIBECODE_AUTH_TOKEN, VIBECODE_API_KEY) as masked GitLab CI/CD Variables."
499
+ ];
500
+ return `${headerLines.join("\n")}\n${serializeYaml(doc)}`;
501
+ }
502
+ function emitMakefile(model) {
503
+ const safeTitle = sanitizeMakefileComment(model.title) || DEFAULT_TITLE;
504
+ const quotedTitle = makefileShellSingleQuote(safeTitle);
505
+ const safeMakeVarTitle = quotedTitle.replace(/#/g, "\\#");
506
+ const domainsLabel = model.domainSummary.length > 0
507
+ ? sanitizeMakefileComment(model.domainSummary.join(", ")) || "none"
508
+ : "none";
509
+ const verifyFlagsParts = [];
510
+ if (model.strict)
511
+ verifyFlagsParts.push("--strict");
512
+ if (model.cache)
513
+ verifyFlagsParts.push("--cache");
514
+ const verifyFlagsSuffix = verifyFlagsParts.length > 0 ? ` ${verifyFlagsParts.join(" ")}` : "";
515
+ const strictVerifyFlagsSuffix = model.cache ? " --strict --cache" : " --strict";
516
+ const lintFlagsSuffix = model.strict ? " --strict" : "";
517
+ const targetResolveExpr = (flagsSuffix) => {
518
+ if (model.target) {
519
+ const quotedTarget = makefileShellSingleQuote(model.target);
520
+ return (`\t@printf '[vibecode] %s\\n' ${quotedTitle}; ` +
521
+ 'target="$${VIBECODE_TARGET:-}"; ' +
522
+ `if [ -z "$$target" ]; then target=${quotedTarget}; fi; ` +
523
+ `$(VIBECODE_BIN) verify --target "$$target"${flagsSuffix} --pretty`);
524
+ }
525
+ return (`\t@printf '[vibecode] %s\\n' ${quotedTitle}; ` +
526
+ 'if [ -z "$${VIBECODE_TARGET:-}" ]; then echo "Error: set VIBECODE_TARGET" >&2; exit 2; fi; ' +
527
+ '$(VIBECODE_BIN) verify --target "$${VIBECODE_TARGET}"' + `${flagsSuffix} --pretty`);
528
+ };
529
+ const lines = [
530
+ "# Generated by vibecode-anything ci-export (makefile)",
531
+ `# Pipeline: ${safeTitle}`,
532
+ `# Domains: ${domainsLabel}`,
533
+ `# Visible invariants: ${model.invariantCount}`,
534
+ `# Node.js: ${model.nodeVersion}`,
535
+ "",
536
+ "VIBECODE_BIN ?= npx vibecode-anything",
537
+ `VIBECODE_TITLE := ${safeMakeVarTitle}`,
538
+ `VIBECODE_NODE_VERSION := ${model.nodeVersion}`,
539
+ "",
540
+ ".PHONY: verify verify-strict report lint clean",
541
+ "",
542
+ "verify:",
543
+ targetResolveExpr(verifyFlagsSuffix),
544
+ "",
545
+ "verify-strict:",
546
+ targetResolveExpr(strictVerifyFlagsSuffix),
547
+ "",
548
+ "report:",
549
+ `\t$(VIBECODE_BIN) report --out .vibecode/report.html --sarif .vibecode/results.sarif --junit .vibecode/junit.xml --badge .vibecode/parity-badge.svg --markdown .vibecode/pr-comment.md`,
550
+ "",
551
+ "lint:",
552
+ `\t$(VIBECODE_BIN) lint${lintFlagsSuffix} --pretty`,
553
+ "",
554
+ "clean:",
555
+ "\trm -rf .vibecode/report.html .vibecode/results.sarif .vibecode/junit.xml .vibecode/parity-badge.svg .vibecode/pr-comment.md .vibecode/cache"
556
+ ];
557
+ if (model.slices.length > 0) {
558
+ const quotedSlices = model.slices
559
+ .map((s) => makefileShellSingleQuote(s.id))
560
+ .join(" ");
561
+ const sliceRecipe = model.target
562
+ ? '\t@target="$${VIBECODE_TARGET:-}"; ' +
563
+ `if [ -z "$$target" ]; then target=${makefileShellSingleQuote(model.target)}; fi; ` +
564
+ `for slice in ${quotedSlices}; do printf '[vibecode] slice: %s\\n' "$$slice"; $(VIBECODE_BIN) verify --target "$$target" --slice "$$slice"${verifyFlagsSuffix} --pretty || exit $$?; done`
565
+ : '\t@if [ -z "$${VIBECODE_TARGET:-}" ]; then echo "Error: set VIBECODE_TARGET" >&2; exit 2; fi; ' +
566
+ `for slice in ${quotedSlices}; do printf '[vibecode] slice: %s\\n' "$$slice"; ` +
567
+ '$(VIBECODE_BIN) verify --target "$${VIBECODE_TARGET}" --slice "$$slice"' +
568
+ `${verifyFlagsSuffix} --pretty || exit $$?; done`;
569
+ lines.push("", ".PHONY: verify-slices", "", "verify-slices:", sliceRecipe);
570
+ }
571
+ lines.push("");
572
+ return lines.join("\n");
573
+ }
574
+ /**
575
+ * Compile a ContractV02 into a zero-dependency CI/CD parity pipeline
576
+ * (`github-actions`, `gitlab-ci`, or `makefile`) with 100% holdout invisibility
577
+ * and hardened secret/injection sanitization.
578
+ */
579
+ export function exportCiPipeline(contract, options = {}) {
580
+ if (!isRecord(contract) || !Array.isArray(contract.invariants)) {
581
+ throw new VibecodeError("CONTRACT_INVALID", "exportCiPipeline requires a valid contract object with an invariants array.", { fallbackHint: "Load or normalize a ContractV02 object before exporting a CI pipeline." });
582
+ }
583
+ if (options !== undefined && !isRecord(options)) {
584
+ throw new VibecodeError("CONTRACT_INVALID", "exportCiPipeline options must be a plain object when provided.", { fallbackHint: 'Pass an options object such as { format: "github-actions" } or omit options.' });
585
+ }
586
+ const opts = options ?? {};
587
+ const formatRaw = opts.format ?? DEFAULT_FORMAT;
588
+ if (typeof formatRaw !== "string" || !VALID_FORMATS.has(formatRaw)) {
589
+ throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported CI export format "${sanitizeUntrustedSingleLine(String(formatRaw), 48)}". Supported formats: github-actions, gitlab-ci, makefile.`, { fallbackHint: 'Pass format: "github-actions", "gitlab-ci", or "makefile".' });
590
+ }
591
+ const format = formatRaw;
592
+ const strict = opts.strict === true;
593
+ const cache = opts.cache === true;
594
+ const nodeVersion = validateNodeVersion(opts.nodeVersion);
595
+ const warnings = [];
596
+ const contractNameRaw = isRecord(contract.target) &&
597
+ typeof contract.target.name === "string" &&
598
+ contract.target.name.trim()
599
+ ? contract.target.name.trim()
600
+ : "";
601
+ const contractName = sanitizeUntrustedSingleLine(contractNameRaw, MAX_TITLE_LEN);
602
+ const rawTitle = typeof opts.title === "string" && opts.title.trim()
603
+ ? opts.title.trim()
604
+ : contractName
605
+ ? `${contractName} Parity`
606
+ : DEFAULT_TITLE;
607
+ const title = sanitizeUntrustedSingleLine(rawTitle, MAX_TITLE_LEN) || DEFAULT_TITLE;
608
+ const target = sanitizeTargetOption(opts.target, warnings);
609
+ // 100% Holdout Invisibility: holdout invariants never contribute to counts, domains, slices, or warnings.
610
+ const visibleInvariantIds = new Set();
611
+ const domainSet = new Set();
612
+ let visibleCount = 0;
613
+ for (const inv of contract.invariants) {
614
+ if (!isRecord(inv))
615
+ continue;
616
+ if (inv.holdout === true)
617
+ continue;
618
+ visibleCount += 1;
619
+ if (typeof inv.id === "string" && inv.id.trim()) {
620
+ visibleInvariantIds.add(inv.id.trim());
621
+ }
622
+ if (typeof inv.domain === "string" && inv.domain.trim()) {
623
+ const cleanDomain = sanitizeUntrustedSingleLine(inv.domain.trim(), 32).toLowerCase();
624
+ if (cleanDomain && !isForbiddenKey(cleanDomain) && !cleanDomain.includes("[redacted")) {
625
+ domainSet.add(cleanDomain);
626
+ }
627
+ }
628
+ }
629
+ const domainSummary = [...domainSet].sort();
630
+ // 100% Holdout Invisibility for slices: drop any slice that contains zero visible invariants.
631
+ const slices = [];
632
+ const seenSliceIds = new Set();
633
+ if (Array.isArray(contract.slices)) {
634
+ for (const rawSlice of contract.slices) {
635
+ if (!isRecord(rawSlice))
636
+ continue;
637
+ if (!Array.isArray(rawSlice.invariantIds))
638
+ continue;
639
+ const hasVisibleInvariant = rawSlice.invariantIds.some((id) => typeof id === "string" && visibleInvariantIds.has(id.trim()));
640
+ if (!hasVisibleInvariant)
641
+ continue;
642
+ const rawId = typeof rawSlice.id === "string" ? rawSlice.id : "";
643
+ const cleanId = sanitizeUntrustedSingleLine(rawId, MAX_SLICE_ID_LEN);
644
+ if (!cleanId ||
645
+ isForbiddenKey(cleanId) ||
646
+ seenSliceIds.has(cleanId) ||
647
+ cleanId === "[REDACTED]" ||
648
+ cleanId === "[REDACTED_VAULT]" ||
649
+ cleanId === "[REDACTED_URL]") {
650
+ continue;
651
+ }
652
+ seenSliceIds.add(cleanId);
653
+ const rawSliceTitle = typeof rawSlice.title === "string" ? rawSlice.title : cleanId;
654
+ const cleanSliceTitle = sanitizeUntrustedSingleLine(rawSliceTitle, MAX_TITLE_LEN) || cleanId;
655
+ slices.push({ id: cleanId, title: cleanSliceTitle });
656
+ }
657
+ }
658
+ if (visibleCount === 0) {
659
+ warnings.push("No visible invariants found in contract.");
660
+ }
661
+ const dedupedWarnings = [...new Set(warnings)];
662
+ const model = {
663
+ format,
664
+ title,
665
+ ...(target ? { target } : {}),
666
+ strict,
667
+ cache,
668
+ nodeVersion,
669
+ invariantCount: visibleCount,
670
+ domainSummary,
671
+ slices,
672
+ warnings: dedupedWarnings
673
+ };
674
+ let content;
675
+ if (format === "github-actions") {
676
+ content = emitGithubActions(model);
677
+ }
678
+ else if (format === "gitlab-ci") {
679
+ content = emitGitlabCi(model);
680
+ }
681
+ else {
682
+ content = emitMakefile(model);
683
+ }
684
+ const { fileExtension, defaultFileName } = fileMetadataFor(format);
685
+ return {
686
+ format,
687
+ content,
688
+ fileExtension,
689
+ defaultFileName,
690
+ invariantCount: visibleCount,
691
+ domainSummary,
692
+ sliceIds: slices.map((s) => s.id),
693
+ warnings: dedupedWarnings
694
+ };
695
+ }
696
+ /**
697
+ * Generate and atomically write a CI/CD parity pipeline to disk (temp file + rename).
698
+ */
699
+ export function writeCiPipeline(contract, outPath, options = {}) {
700
+ if (typeof outPath !== "string" || !outPath.trim() || outPath.includes("\0")) {
701
+ throw new VibecodeError("CONTRACT_INVALID", "writeCiPipeline requires a valid non-empty outPath without NUL bytes.", { fallbackHint: "Pass a file path such as .github/workflows/vibecode-parity.yml." });
702
+ }
703
+ const resolvedOut = path.resolve(outPath.trim());
704
+ if (fs.existsSync(resolvedOut) && fs.statSync(resolvedOut).isDirectory()) {
705
+ throw new VibecodeError("CONTRACT_INVALID", `Cannot write CI pipeline: "${sanitizeUntrustedSingleLine(resolvedOut, 240)}" is a directory.`, { fallbackHint: "Pass a file path rather than a directory." });
706
+ }
707
+ const result = exportCiPipeline(contract, options);
708
+ const parentDir = path.dirname(resolvedOut);
709
+ fs.mkdirSync(parentDir, { recursive: true });
710
+ const tmpPath = path.join(parentDir, `.${path.basename(resolvedOut)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
711
+ try {
712
+ fs.writeFileSync(tmpPath, result.content, "utf8");
713
+ fs.renameSync(tmpPath, resolvedOut);
714
+ }
715
+ catch (err) {
716
+ try {
717
+ if (fs.existsSync(tmpPath)) {
718
+ fs.rmSync(tmpPath, { force: true });
719
+ }
720
+ }
721
+ catch {
722
+ // ignore cleanup error
723
+ }
724
+ throw err;
725
+ }
726
+ return {
727
+ ...result,
728
+ outPath: resolvedOut
729
+ };
730
+ }
731
+ function style(text, codes, useColor) {
732
+ return useColor ? `${codes}${text}${ANSI.reset}` : text;
733
+ }
734
+ /**
735
+ * Format a concise, sanitized terminal summary for a CI pipeline export result.
736
+ */
737
+ export function formatPrettyCiExport(result, outPath, color = false) {
738
+ const useColor = color === true;
739
+ const lines = [];
740
+ const banner = style("[CI EXPORT]", `${ANSI.bold}${ANSI.cyan}`, useColor);
741
+ const fmtLabel = result.format === "github-actions"
742
+ ? "GitHub Actions"
743
+ : result.format === "gitlab-ci"
744
+ ? "GitLab CI"
745
+ : "Makefile";
746
+ const safeExt = sanitizeUntrustedSingleLine(result.fileExtension || "", 16);
747
+ const safeDefaultName = sanitizeUntrustedSingleLine(result.defaultFileName || "", 64);
748
+ lines.push(`${banner} ${style(fmtLabel, ANSI.bold, useColor)} (${safeExt}, ${safeDefaultName})`);
749
+ const effectiveOut = (typeof outPath === "string" && outPath.trim()) ||
750
+ (typeof result.outPath === "string" && result.outPath.trim()) ||
751
+ "";
752
+ if (effectiveOut) {
753
+ lines.push(`Output: ${sanitizeUntrustedSingleLine(effectiveOut, 240)}`);
754
+ }
755
+ const totalBytes = Buffer.byteLength(result.content || "", "utf8");
756
+ const invCount = Number.isInteger(result.invariantCount) && result.invariantCount >= 0
757
+ ? result.invariantCount
758
+ : 0;
759
+ const invLabel = style(`${invCount} ${invCount === 1 ? "invariant" : "invariants"}`, invCount > 0 ? ANSI.green : ANSI.yellow, useColor);
760
+ const safeDomains = Array.isArray(result.domainSummary)
761
+ ? result.domainSummary
762
+ .map((d) => sanitizeUntrustedSingleLine(String(d), 32))
763
+ .filter(Boolean)
764
+ : [];
765
+ const safeSlices = Array.isArray(result.sliceIds)
766
+ ? result.sliceIds
767
+ .map((s) => sanitizeUntrustedSingleLine(String(s), MAX_SLICE_ID_LEN))
768
+ .filter(Boolean)
769
+ : [];
770
+ const summaryParts = [
771
+ invLabel,
772
+ `domains: ${safeDomains.length > 0 ? safeDomains.join(", ") : "none"}`
773
+ ];
774
+ if (safeSlices.length > 0) {
775
+ summaryParts.push(`${safeSlices.length} ${safeSlices.length === 1 ? "slice" : "slices"}`);
776
+ }
777
+ summaryParts.push(`${totalBytes} bytes`);
778
+ lines.push(`Summary: ${summaryParts.join(", ")}`);
779
+ if (safeSlices.length > 0) {
780
+ const shown = safeSlices.slice(0, MAX_PRETTY_SLICES).join(", ");
781
+ const extra = safeSlices.length > MAX_PRETTY_SLICES
782
+ ? ` (+${safeSlices.length - MAX_PRETTY_SLICES} more)`
783
+ : "";
784
+ lines.push(`Slices: ${shown}${extra}`);
785
+ }
786
+ if (Array.isArray(result.warnings) && result.warnings.length > 0) {
787
+ lines.push("Warnings:");
788
+ for (const warning of result.warnings.slice(0, MAX_PRETTY_WARNINGS)) {
789
+ lines.push(` - ${style(sanitizeUntrustedSingleLine(String(warning), 200), ANSI.yellow, useColor)}`);
790
+ }
791
+ if (result.warnings.length > MAX_PRETTY_WARNINGS) {
792
+ lines.push(` ${style(`... and ${result.warnings.length - MAX_PRETTY_WARNINGS} more`, ANSI.dim, useColor)}`);
793
+ }
794
+ }
795
+ return lines.join("\n");
796
+ }