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
@@ -1,14 +1,39 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
1
4
  import path from "node:path";
2
- import { readContract, readRawContract, writeContract, writeLastReport, readLastReport, resolveWorkspace } from "../core/store.js";
5
+ import { CONTRACT_FILE, readContract, readHoldouts, readRawContract, writeContract, writeLastReport, readLastReport, resolveHoldoutVaultPath, resolveWorkspace } from "../core/store.js";
6
+ import { splitCommand } from "../core/exec.js";
7
+ import { writeSpecFile } from "../core/spec-writer.js";
8
+ import { writeHtmlReport } from "../core/html-report.js";
9
+ import { renderPrCommentMarkdown, writeParityBadgeSvg, writePrCommentMarkdown } from "../core/badge.js";
10
+ import { writeJunitXml, writeSarifReport } from "../core/ci-formats.js";
11
+ import { compareReports, renderRegressionMarkdown } from "../core/regression.js";
12
+ import { redactHoldoutResult } from "../core/parity.js";
13
+ import { readRunHistory } from "../core/run.js";
3
14
  import { detectDomain, ingest } from "../ingestors/index.js";
4
- import { verifyContract } from "../oracles/index.js";
15
+ import { isCurlCommandText } from "../ingestors/curl.js";
16
+ import { redactHeaders } from "../ingestors/trace.js";
17
+ import { redactRuntimeVarsDeep, verifyContract } from "../oracles/index.js";
18
+ import { redactRuntimeVars, validateRuntimeVarsObject, validateTargetMapObject } from "../core/target-map.js";
5
19
  import { probeAdapters } from "../core/adapters.js";
6
- import { resolveSliceInvariants, summarizeSlices, updateSliceProgress } from "../core/slices.js";
20
+ import { getContractSlices, resolveSliceInvariants, summarizeSlices, updateSliceProgress } from "../core/slices.js";
7
21
  import { runDoctor } from "../core/doctor.js";
22
+ import { discoverProject } from "../discovery/discover.js";
23
+ import { autoInferLockTarget, checkLockStatus, lockProject } from "../discovery/lock.js";
24
+ import { ingestFromTests } from "../discovery/test-importer.js";
25
+ import { diagnoseReport } from "../diagnostics/diagnose.js";
26
+ import { analyzeFlakes } from "../diagnostics/flake.js";
27
+ import { auditContractStrength } from "../diagnostics/mutation-audit.js";
28
+ import { analyzeTrends, appendTrendEntry, MAX_TREND_ENTRIES, readTrendEntries } from "../diagnostics/trends.js";
29
+ import { analyzeImpact, getGitChangedFiles } from "../core/impact.js";
8
30
  import { toDiagnostic, VibecodeError, errorCode, errorMessage } from "../core/errors.js";
9
- import { makeDefaultContract, VALID_DOMAINS } from "../core/schema.js";
31
+ import { defineOwnProp, hasCrossPlatformPathEscape, hasVaultOrHoldoutSegment, isForbiddenObjectKey, isHoldoutResultRecord, isInsideOrEqualDir, isInsideVaultDirectory, isPlainObjectSafe, isSecretRelativePath, isSensitiveKeyName, isSensitiveQueryParamName, parseSafeHttpBaseUrl, readBoundedFileUtf8, redactDeepValue, redactSensitiveTextWithOptions, resolvePathViaExistingAncestor, safeReadPlainObject } from "../core/security.js";
32
+ import { normalizeConcurrency } from "../core/scheduler.js";
33
+ import { VALID_VERIFY_MODES } from "../core/visual-semantic.js";
34
+ import { makeDefaultContract, SCHEMA_VERSION, VALID_DOMAINS } from "../core/schema.js";
10
35
  const SERVER_NAME = "vibecode-anything";
11
- const SERVER_VERSION = "0.3.0";
36
+ const SERVER_VERSION = "0.4.0";
12
37
  // Newest first. `initialize` echoes the client's version when we speak it.
13
38
  const SUPPORTED_PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
14
39
  const PARSE_ERROR = -32700;
@@ -43,16 +68,108 @@ const PROBES_SCHEMA = {
43
68
  ]
44
69
  }
45
70
  };
71
+ const DOMAIN_ENUM = [
72
+ "cli",
73
+ "script",
74
+ "web",
75
+ "url",
76
+ "api",
77
+ "repo",
78
+ "image",
79
+ "video",
80
+ "rea",
81
+ "cli-anything",
82
+ "postman",
83
+ "curl",
84
+ "graphql",
85
+ "http-file",
86
+ "insomnia",
87
+ "bruno",
88
+ "asyncapi",
89
+ "proto",
90
+ "openrpc"
91
+ ];
46
92
  const TOOLS = [
93
+ {
94
+ name: "vibecode_discover",
95
+ description: "Inspect the workspace (or a subdirectory inside it) to detect ecosystems, manifests, frameworks, entrypoints, HTTP/web routes, API specs, inferred ports, suggested domains/slices, and ready-to-run lock/ingest commands.",
96
+ inputSchema: {
97
+ type: "object",
98
+ properties: {
99
+ dir: {
100
+ type: "string",
101
+ description: "Optional workspace-contained directory to inspect (defaults to workspace root)."
102
+ },
103
+ maxDepth: {
104
+ type: "integer",
105
+ minimum: 0,
106
+ maximum: 12,
107
+ description: "Maximum directory traversal depth (0..12, default 6)."
108
+ },
109
+ maxFiles: {
110
+ type: "integer",
111
+ minimum: 1,
112
+ maximum: 2000,
113
+ description: "Maximum number of files to scan (1..2000, default 500)."
114
+ }
115
+ },
116
+ additionalProperties: false
117
+ }
118
+ },
119
+ {
120
+ name: "vibecode_lock",
121
+ description: "Create a refactor safety lock (.vibecode/contract.json, .vibecode/SPEC.md, external vault holdouts, and .vibecode/lock.json) with baseline verification, or check tamper & source drift with check=true.",
122
+ inputSchema: {
123
+ type: "object",
124
+ properties: {
125
+ check: {
126
+ type: "boolean",
127
+ description: "Check existing .vibecode/lock.json integrity, contract tampering, and source drift without mutating files."
128
+ },
129
+ source: {
130
+ type: "string",
131
+ description: "Command, URL, repo path, or spec file. Auto-inferred via project discovery when omitted."
132
+ },
133
+ domain: {
134
+ type: "string",
135
+ enum: DOMAIN_ENUM
136
+ },
137
+ target: {
138
+ type: "string",
139
+ description: "Optional verification target command or URL."
140
+ },
141
+ name: { type: "string" },
142
+ force: { type: "boolean", description: "Overwrite an existing lock or contract (default false)." },
143
+ strict: { type: "boolean", description: "Turn soft perceptual mismatches into hard baseline failures." },
144
+ noSpec: { type: "boolean", description: "Skip generating .vibecode/SPEC.md (default false)." },
145
+ noVerify: { type: "boolean", description: "Skip baseline self-verification when creating the lock (default false)." },
146
+ probes: PROBES_SCHEMA,
147
+ routes: { type: "array", items: { type: "string" } },
148
+ endpoints: { type: "array" },
149
+ baseUrl: { type: "string" },
150
+ headers: { type: "object", additionalProperties: { type: "string" } },
151
+ storageState: { type: "string" },
152
+ fsDiff: { type: "boolean" },
153
+ crawlDepth: { type: "integer", minimum: 1, maximum: 3, description: "Same-origin web BFS crawl depth (1..3, default 1)." },
154
+ holdoutRoutes: { type: "array", items: { type: "string" }, description: "Additional web routes stored as hidden holdouts." }
155
+ },
156
+ required: [],
157
+ additionalProperties: false
158
+ }
159
+ },
47
160
  {
48
161
  name: "vibecode_ingest",
49
162
  description: "Probe a reference and write a v0.2 .vibecode/contract.json. domain is auto-detected from source when omitted.",
50
163
  inputSchema: {
51
164
  type: "object",
52
165
  properties: {
53
- domain: { type: "string", enum: ["cli", "script", "web", "url", "api", "repo", "image", "video", "rea", "cli-anything"] },
166
+ domain: {
167
+ type: "string",
168
+ enum: DOMAIN_ENUM
169
+ },
54
170
  source: { type: "string", description: "Command, URL, repo path, image path, video path, or keyframe directory." },
55
171
  name: { type: "string" },
172
+ target: { type: "string", description: "Optional runtime target command or URL recorded when importing tests with fromTests." },
56
173
  force: { type: "boolean", description: "Overwrite an existing contract (default false)." },
57
174
  probes: PROBES_SCHEMA,
58
175
  routes: { type: "array", items: { type: "string" } },
@@ -60,9 +177,23 @@ const TOOLS = [
60
177
  endpoints: { type: "array" },
61
178
  baseUrl: { type: "string" },
62
179
  sceneThreshold: { type: "number" },
63
- maxFrames: { type: "integer" }
180
+ maxFrames: { type: "integer" },
181
+ noSpec: { type: "boolean", description: "Skip generating .vibecode/SPEC.md on ingest (default false)." },
182
+ crawlDepth: { type: "integer", minimum: 1, maximum: 3, description: "Same-origin web BFS crawl depth (1..3, default 1)." },
183
+ holdoutRoutes: { type: "array", items: { type: "string" }, description: "Additional web routes stored as hidden holdouts." },
184
+ crop: { type: "string" },
185
+ env: { type: "object", additionalProperties: { type: "string" } },
186
+ fsDiff: { type: "boolean" },
187
+ headers: { type: "object", additionalProperties: { type: "string" } },
188
+ storageState: { type: "string" },
189
+ fromCommands: { type: "string" },
190
+ fromHar: { type: "string" },
191
+ fromTests: {
192
+ type: "string",
193
+ description: "Workspace-contained test file or directory to statically import (node:test, Jest, Vitest, Supertest, pytest) without executing test code."
194
+ }
64
195
  },
65
- required: ["source"],
196
+ required: [],
66
197
  additionalProperties: false
67
198
  }
68
199
  },
@@ -72,27 +203,81 @@ const TOOLS = [
72
203
  inputSchema: {
73
204
  type: "object",
74
205
  properties: {
75
- target: { type: "string", description: "Command or URL of the build under test." },
206
+ target: { type: "string", description: "Command or URL of the build under test (optional when targets is given)." },
207
+ targets: {
208
+ type: "object",
209
+ additionalProperties: { type: "string" },
210
+ description: "Per-domain targets, e.g. { \"web\": \"http://localhost:3000\", \"cli\": \"node ./bin/app.mjs\" }; target is the fallback."
211
+ },
212
+ vars: {
213
+ type: "object",
214
+ additionalProperties: { type: "string" },
215
+ description: "Runtime workflow secrets for {{vars.NAME}} templates; never cached and redacted from all output."
216
+ },
217
+ mode: {
218
+ type: "string",
219
+ enum: ["exact", "structural", "functional", "reskin"],
220
+ description: "Semantic verification mode: exact (default), structural, functional, or reskin (enforces WCAG 2.1 contrast)."
221
+ },
222
+ concurrency: {
223
+ type: "integer",
224
+ minimum: 1,
225
+ maximum: 8,
226
+ description: "Bounded parallel invariant worker count (1..8, default 1; deterministic result ordering)."
227
+ },
76
228
  strict: { type: "boolean", description: "Turn soft perceptual mismatches into hard failures." },
229
+ affected: {
230
+ type: "boolean",
231
+ description: "Analyze git-changed files and verify only impacted invariants (fail-closed fallback to full run on config/contract/shared-hub changes)."
232
+ },
77
233
  invariantIds: { type: "array", items: { type: "string" } },
78
- sliceIds: { type: "array", items: { type: "string" }, description: "Incremental contract slice IDs to verify and update." }
234
+ sliceIds: { type: "array", items: { type: "string" }, description: "Incremental contract slice IDs to verify and update." },
235
+ useCache: { type: "boolean", description: "Reuse cached passing non-holdout invariant results when local target inputs match." },
236
+ noReport: { type: "boolean", description: "Skip generating .vibecode/report.html after verification." },
237
+ skipFixtures: { type: "boolean", description: "Skip contract.fixtures setup, teardown, and workspace rollback for this verification run." },
238
+ headers: { type: "object", additionalProperties: { type: "string" } },
239
+ storageState: { type: "string" }
79
240
  },
80
- required: ["target"],
241
+ required: [],
81
242
  additionalProperties: false
82
243
  }
83
244
  },
84
245
  {
85
246
  name: "vibecode_status",
86
- description: "Contract metadata, hard/soft counts, optional adapter availability, slice summary, and the last parity summary.",
87
- inputSchema: { type: "object", properties: {}, additionalProperties: false }
247
+ description: "Contract metadata, hard/soft counts, optional adapter availability, slice summary, last parity summary, and optional verification trend & hotspot analytics.",
248
+ inputSchema: {
249
+ type: "object",
250
+ properties: {
251
+ includeTrends: {
252
+ type: "boolean",
253
+ description: "Include verification trend analytics, sparklines, latency drift, and flaky hotspots from .vibecode/trends.ndjson (default false)."
254
+ },
255
+ trendWindow: {
256
+ type: "integer",
257
+ minimum: 1,
258
+ maximum: 200,
259
+ description: "Sliding window of recent verification runs to analyze when includeTrends is true (1..200, default 20)."
260
+ }
261
+ },
262
+ additionalProperties: false
263
+ }
88
264
  },
89
265
  {
90
266
  name: "vibecode_diff",
91
- description: "Full metrics/failures for one invariant from the last report (keeps agent context lean).",
267
+ description: "Full metrics/failures for one invariant from the last report, or regression comparison against a baseline ParityReport JSON.",
92
268
  inputSchema: {
93
269
  type: "object",
94
- properties: { invariantId: { type: "string" } },
95
- required: ["invariantId"],
270
+ properties: {
271
+ invariantId: { type: "string", description: "Invariant ID to inspect from .vibecode/last-report.json." },
272
+ baselinePath: {
273
+ type: "string",
274
+ description: "Optional workspace-relative path to a baseline ParityReport JSON to compare against the last report."
275
+ },
276
+ strict: {
277
+ type: "boolean",
278
+ description: "Treat warnings and pass_with_warnings transitions as regressions when comparing against baselinePath."
279
+ }
280
+ },
96
281
  additionalProperties: false
97
282
  }
98
283
  },
@@ -108,8 +293,200 @@ const TOOLS = [
108
293
  },
109
294
  additionalProperties: false
110
295
  }
296
+ },
297
+ {
298
+ name: "vibecode_diagnose",
299
+ description: "Run root-cause failure triage on .vibecode/last-report.json with 3x3 spatial pixel-diff heatmaps, bounding-box shift vectors, and a compact repair brief (holdouts strictly redacted).",
300
+ inputSchema: {
301
+ type: "object",
302
+ properties: {
303
+ includeVisualHeatmap: {
304
+ type: "boolean",
305
+ description: "Compute 3x3 spatial pixel-diff heatmaps for visual failures (default true)."
306
+ },
307
+ maxBriefChars: {
308
+ type: "integer",
309
+ minimum: 200,
310
+ maximum: 20000,
311
+ description: "Maximum character budget for the generated repairBrief markdown (200..20000, default 2400)."
312
+ },
313
+ briefOnly: {
314
+ type: "boolean",
315
+ description: "Return only summary counts and repairBrief without full per-item arrays (default false)."
316
+ },
317
+ includeStrength: {
318
+ type: "boolean",
319
+ description: "Also run static oracle strength & stub-bypass mutation audit on .vibecode/contract.json (default false)."
320
+ }
321
+ },
322
+ additionalProperties: false
323
+ }
324
+ },
325
+ {
326
+ name: "vibecode_flake",
327
+ description: "Run sequential multi-pass differential verification (bypassing cache) to detect flaky or nondeterministic invariants and suggest expected.normalize rules (holdouts always redacted).",
328
+ inputSchema: {
329
+ type: "object",
330
+ properties: {
331
+ target: { type: "string", description: "Command or URL of the build under test (optional when targets is given)." },
332
+ targets: {
333
+ type: "object",
334
+ additionalProperties: { type: "string" },
335
+ description: "Per-domain targets, e.g. { \"web\": \"http://localhost:3000\", \"cli\": \"node ./bin/app.mjs\" }; target is the fallback."
336
+ },
337
+ vars: {
338
+ type: "object",
339
+ additionalProperties: { type: "string" },
340
+ description: "Runtime workflow secrets for {{vars.NAME}} templates; redacted from all output."
341
+ },
342
+ runs: {
343
+ type: "integer",
344
+ minimum: 2,
345
+ maximum: 10,
346
+ description: "Number of sequential verification runs (2..10, default 3)."
347
+ },
348
+ invariantIds: {
349
+ type: "array",
350
+ items: { type: "string" },
351
+ description: "Optional invariant IDs to evaluate."
352
+ },
353
+ sliceIds: {
354
+ type: "array",
355
+ items: { type: "string" },
356
+ description: "Optional contract slice IDs to evaluate."
357
+ },
358
+ strict: {
359
+ type: "boolean",
360
+ description: "Treat soft warnings as failures during flake analysis."
361
+ },
362
+ skipFixtures: {
363
+ type: "boolean",
364
+ description: "Skip contract.fixtures setup, teardown, and workspace rollback during flake analysis."
365
+ },
366
+ headers: {
367
+ type: "object",
368
+ additionalProperties: { type: "string" },
369
+ description: "Optional HTTP request headers forwarded to the target."
370
+ },
371
+ storageState: {
372
+ type: "string",
373
+ description: "Optional workspace-contained Playwright storageState JSON file path."
374
+ }
375
+ },
376
+ required: [],
377
+ additionalProperties: false
378
+ }
379
+ },
380
+ {
381
+ name: "vibecode_report",
382
+ description: "Generate a self-contained visual HTML proof report, parity SVG badge, PR Markdown summary, SARIF 2.1.0 report, and/or JUnit XML from the last parity report.",
383
+ inputSchema: {
384
+ type: "object",
385
+ properties: {
386
+ outPath: { type: "string", description: "Output HTML path relative to workspace (default .vibecode/report.html)." },
387
+ badgePath: { type: "string", description: "Optional output parity SVG badge path relative to workspace." },
388
+ markdownPath: { type: "string", description: "Optional output PR Markdown summary path relative to workspace." },
389
+ sarifPath: { type: "string", description: "Optional output SARIF 2.1.0 report path relative to workspace." },
390
+ junitPath: { type: "string", description: "Optional output JUnit XML report path relative to workspace." },
391
+ noReport: { type: "boolean", description: "Skip writing HTML report when only badge/markdown/sarif/junit is desired." },
392
+ label: { type: "string", description: "Custom left-side label text for SVG badge." }
393
+ },
394
+ additionalProperties: false
395
+ }
396
+ }
397
+ ];
398
+ const ALLOWED_VERIFY_KEYS = new Set([
399
+ "target",
400
+ "targets",
401
+ "vars",
402
+ "mode",
403
+ "concurrency",
404
+ "strict",
405
+ "affected",
406
+ "invariantIds",
407
+ "sliceIds",
408
+ "useCache",
409
+ "noReport",
410
+ "skipFixtures",
411
+ "headers",
412
+ "storageState",
413
+ "revealHoldouts"
414
+ ]);
415
+ const ALLOWED_INGEST_KEYS = new Set([
416
+ "domain",
417
+ "source",
418
+ "name",
419
+ "target",
420
+ "force",
421
+ "probes",
422
+ "routes",
423
+ "flow",
424
+ "endpoints",
425
+ "baseUrl",
426
+ "sceneThreshold",
427
+ "maxFrames",
428
+ "noSpec",
429
+ "crawlDepth",
430
+ "holdoutRoutes",
431
+ "crop",
432
+ "env",
433
+ "fsDiff",
434
+ "headers",
435
+ "storageState",
436
+ "fromCommands",
437
+ "fromHar",
438
+ "fromTests"
439
+ ]);
440
+ const ALLOWED_DOCTOR_KEYS = new Set(["scope", "antigravityDir", "strict"]);
441
+ const ALLOWED_REPORT_KEYS = new Set([
442
+ "outPath",
443
+ "badgePath",
444
+ "markdownPath",
445
+ "sarifPath",
446
+ "junitPath",
447
+ "noReport",
448
+ "label"
449
+ ]);
450
+ const RESERVED_REPORT_OUTPUT_REL_PATHS = new Set([
451
+ ".vibecode/contract.json",
452
+ ".vibecode/lock.json",
453
+ ".vibecode/spec.md",
454
+ ".vibecode/last-report.json",
455
+ ".vibecode/trends.ndjson",
456
+ ".vibecode/history.json",
457
+ ".vibecode/holdouts.json"
458
+ ]);
459
+ const PROMPTS = [
460
+ {
461
+ name: "vibecode_rebuild_slice",
462
+ description: "Generate a deterministic fresh-context rebuild prompt for the next (or specified) contract slice.",
463
+ arguments: [
464
+ {
465
+ name: "sliceId",
466
+ description: "Optional slice ID (defaults to next incomplete slice)",
467
+ required: false
468
+ },
469
+ {
470
+ name: "target",
471
+ description: "Optional target build command or URL",
472
+ required: false
473
+ }
474
+ ]
475
+ },
476
+ {
477
+ name: "vibecode_fix_failures",
478
+ description: "Generate a focused fresh-context fix prompt summarizing visible failing invariants and repro commands from the last parity report.",
479
+ arguments: [
480
+ {
481
+ name: "target",
482
+ description: "Optional target build command or URL",
483
+ required: false
484
+ }
485
+ ]
111
486
  }
112
487
  ];
488
+ const MAX_PROMPT_SPEC_CHARS = 12_000;
489
+ const MAX_PROMPT_DIFF_CHARS = 1_500;
113
490
  const RESOURCES = [
114
491
  {
115
492
  uri: "vibecode://contract",
@@ -117,11 +494,23 @@ const RESOURCES = [
117
494
  description: "The on-disk .vibecode/contract.json reference contract.",
118
495
  mimeType: "application/json"
119
496
  },
497
+ {
498
+ uri: "vibecode://spec",
499
+ name: "Zero-Assumption Spec",
500
+ description: "Deterministic re-implementation spec (.vibecode/SPEC.md), excluding holdouts.",
501
+ mimeType: "text/markdown"
502
+ },
120
503
  {
121
504
  uri: "vibecode://last-report",
122
505
  name: "Last parity report",
123
506
  description: "The most recent verify report (.vibecode/last-report.json).",
124
507
  mimeType: "application/json"
508
+ },
509
+ {
510
+ uri: "vibecode://report",
511
+ name: "Visual parity report",
512
+ description: "Self-contained HTML visual proof report (.vibecode/report.html).",
513
+ mimeType: "text/html"
125
514
  }
126
515
  ];
127
516
  function textResult(payload, { isError = false } = {}) {
@@ -131,6 +520,1637 @@ function textResult(payload, { isError = false } = {}) {
131
520
  ...(isError ? { isError: true } : {})
132
521
  };
133
522
  }
523
+ function parseMcpCrop(raw) {
524
+ if (raw === undefined)
525
+ return undefined;
526
+ if (typeof raw !== "string") {
527
+ throw new VibecodeError("CONTRACT_INVALID", "Invalid crop value; expected w:h:x:y with positive width and height.");
528
+ }
529
+ const match = raw.match(/^\s*(\d+):(\d+):(\d+):(\d+)\s*$/);
530
+ if (!match) {
531
+ throw new VibecodeError("CONTRACT_INVALID", "Invalid crop value; expected w:h:x:y with positive width and height.");
532
+ }
533
+ const w = Number(match[1]);
534
+ const h = Number(match[2]);
535
+ const x = Number(match[3]);
536
+ const y = Number(match[4]);
537
+ if (!Number.isSafeInteger(w) ||
538
+ !Number.isSafeInteger(h) ||
539
+ !Number.isSafeInteger(x) ||
540
+ !Number.isSafeInteger(y) ||
541
+ w <= 0 ||
542
+ h <= 0 ||
543
+ x < 0 ||
544
+ y < 0) {
545
+ throw new VibecodeError("CONTRACT_INVALID", "Invalid crop value; expected w:h:x:y with positive width and height.");
546
+ }
547
+ return `${w}:${h}:${x}:${y}`;
548
+ }
549
+ function parseMcpStringRecord(raw, fieldName) {
550
+ if (raw === undefined)
551
+ return undefined;
552
+ const read = safeReadPlainObject(raw, fieldName, {
553
+ forbiddenKeyPolicy: "reject",
554
+ includeNonEnumerable: false
555
+ });
556
+ if (!read.ok) {
557
+ if (read.kind === "forbidden_key") {
558
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} contains forbidden key: ${redactMcpText(read.key ?? "")}`);
559
+ }
560
+ if (read.kind === "not_plain") {
561
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must be an object mapping strings to strings.`);
562
+ }
563
+ throw new VibecodeError("CONTRACT_INVALID", redactMcpText(read.error));
564
+ }
565
+ const out = {};
566
+ for (const [rawKey, val] of read.entries) {
567
+ const key = rawKey.trim();
568
+ if (!key || typeof val !== "string") {
569
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} entries must have non-empty string keys and string values.`);
570
+ }
571
+ defineOwnProp(out, key, val);
572
+ }
573
+ return Object.keys(out).length > 0 ? out : undefined;
574
+ }
575
+ function parseMcpBoolean(raw, fieldName) {
576
+ if (raw === undefined)
577
+ return undefined;
578
+ if (typeof raw !== "boolean") {
579
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must be a boolean.`);
580
+ }
581
+ return raw;
582
+ }
583
+ function getCurrentUserInfoSafe() {
584
+ try {
585
+ const info = os.userInfo();
586
+ if (info && typeof info.username === "string" && info.username) {
587
+ return { username: info.username, homedir: info.homedir || os.homedir() };
588
+ }
589
+ }
590
+ catch {
591
+ // os.userInfo() can fail in minimal containers without a passwd entry.
592
+ }
593
+ return null;
594
+ }
595
+ function expandLeadingTilde(rawPath, rootDir) {
596
+ if (!rawPath.startsWith("~"))
597
+ return rawPath;
598
+ if (rawPath === "~")
599
+ return os.homedir();
600
+ if (rawPath.startsWith("~/") || rawPath.startsWith("~\\")) {
601
+ return path.join(os.homedir(), rawPath.slice(2));
602
+ }
603
+ if (rootDir) {
604
+ if (rawPath === "~+")
605
+ return path.resolve(rootDir);
606
+ if (rawPath.startsWith("~+/") || rawPath.startsWith("~+\\")) {
607
+ return path.join(path.resolve(rootDir), rawPath.slice(3));
608
+ }
609
+ }
610
+ const oldPwd = process.env.OLDPWD?.trim();
611
+ if (oldPwd) {
612
+ if (rawPath === "~-")
613
+ return path.resolve(oldPwd);
614
+ if (rawPath.startsWith("~-/") || rawPath.startsWith("~-\\")) {
615
+ return path.join(path.resolve(oldPwd), rawPath.slice(3));
616
+ }
617
+ }
618
+ const userInfo = getCurrentUserInfoSafe();
619
+ if (userInfo) {
620
+ const prefix = `~${userInfo.username}`;
621
+ if (rawPath === prefix)
622
+ return userInfo.homedir;
623
+ if (rawPath.startsWith(`${prefix}/`) || rawPath.startsWith(`${prefix}\\`)) {
624
+ return path.join(userInfo.homedir, rawPath.slice(prefix.length + 1));
625
+ }
626
+ }
627
+ return rawPath;
628
+ }
629
+ function expandLeadingTildeCandidates(rawPath, rootDir) {
630
+ const primary = expandLeadingTilde(rawPath, rootDir);
631
+ if (!rawPath.startsWith("~"))
632
+ return [primary];
633
+ const userInfo = getCurrentUserInfoSafe();
634
+ if (userInfo) {
635
+ const envHome = os.homedir();
636
+ if (envHome && envHome !== userInfo.homedir) {
637
+ const prefix = `~${userInfo.username}`;
638
+ if (rawPath === prefix)
639
+ return [primary, envHome];
640
+ if (rawPath.startsWith(`${prefix}/`) || rawPath.startsWith(`${prefix}\\`)) {
641
+ return [primary, path.join(envHome, rawPath.slice(prefix.length + 1))];
642
+ }
643
+ }
644
+ }
645
+ return [primary];
646
+ }
647
+ function isPureHttpUrlToken(raw) {
648
+ const s = raw.trim();
649
+ if (!/^https?:\/\/[^\s"'`;|<>()\r\n\\]+$/i.test(s))
650
+ return false;
651
+ if (s.includes("&&") || s.includes("$(") || s.includes("${") || /\$[A-Za-z_]/.test(s))
652
+ return false;
653
+ if (s.includes("&")) {
654
+ if (/[{}]/.test(s))
655
+ return false;
656
+ const qIdx = s.indexOf("?");
657
+ const hIdx = s.indexOf("#");
658
+ const cutoff = qIdx >= 0 && hIdx >= 0 ? Math.min(qIdx, hIdx) : Math.max(qIdx, hIdx);
659
+ if (cutoff < 0 || s.indexOf("&") < cutoff)
660
+ return false;
661
+ }
662
+ try {
663
+ const u = new URL(s);
664
+ return u.protocol === "http:" || u.protocol === "https:";
665
+ }
666
+ catch {
667
+ return false;
668
+ }
669
+ }
670
+ function safeRealpath(targetPath) {
671
+ try {
672
+ return fs.realpathSync(targetPath);
673
+ }
674
+ catch {
675
+ return path.resolve(targetPath);
676
+ }
677
+ }
678
+ function lstatExists(targetPath) {
679
+ try {
680
+ fs.lstatSync(targetPath);
681
+ return true;
682
+ }
683
+ catch {
684
+ return false;
685
+ }
686
+ }
687
+ function safeRealpathOrNearestAncestor(targetPath) {
688
+ return resolvePathViaExistingAncestor(targetPath) ?? path.resolve(targetPath);
689
+ }
690
+ function getVaultBaseDirs(rootDir) {
691
+ const dirs = new Set();
692
+ const addDir = (candidate) => {
693
+ if (!candidate || !candidate.trim())
694
+ return;
695
+ const resolved = path.resolve(expandLeadingTilde(candidate.trim(), rootDir));
696
+ dirs.add(resolved);
697
+ dirs.add(safeRealpathOrNearestAncestor(resolved));
698
+ };
699
+ addDir(process.env.VIBECODE_VAULT_DIR);
700
+ addDir(path.join(os.homedir(), ".vibecode-vault"));
701
+ if (rootDir) {
702
+ try {
703
+ const vaultFile = resolveHoldoutVaultPath(rootDir);
704
+ addDir(path.dirname(vaultFile));
705
+ addDir(path.dirname(path.dirname(vaultFile)));
706
+ }
707
+ catch {
708
+ // Ignore vault path derivation failures.
709
+ }
710
+ }
711
+ return [...dirs];
712
+ }
713
+ function isInsideVaultDir(targetPath, rootDir) {
714
+ const resolvedTarget = path.resolve(expandLeadingTilde(targetPath, rootDir));
715
+ const realTarget = safeRealpathOrNearestAncestor(resolvedTarget);
716
+ for (const vaultDir of getVaultBaseDirs(rootDir)) {
717
+ if (isInsideOrEqualDir(resolvedTarget, vaultDir) || isInsideOrEqualDir(realTarget, vaultDir)) {
718
+ return true;
719
+ }
720
+ }
721
+ return false;
722
+ }
723
+ function redactVaultOrText(rawText, isVaultTarget) {
724
+ const redacted = redactMcpText(rawText);
725
+ if (isVaultTarget && !redacted.includes("[REDACTED_VAULT_PATH]")) {
726
+ return "[REDACTED_VAULT_PATH]";
727
+ }
728
+ return redacted;
729
+ }
730
+ function isPathTargetingVaultOrHoldout(candidatePath, rootDir) {
731
+ const baseRoot = path.resolve(rootDir);
732
+ const realBase = safeRealpath(baseRoot);
733
+ const resolved = path.resolve(candidatePath);
734
+ const realTarget = safeRealpathOrNearestAncestor(resolved);
735
+ if (hasVaultOrHoldoutSegment(resolved) ||
736
+ hasVaultOrHoldoutSegment(realTarget) ||
737
+ isInsideVaultDirectory(resolved) ||
738
+ isInsideVaultDirectory(realTarget) ||
739
+ isInsideVaultDir(resolved, baseRoot) ||
740
+ isInsideVaultDir(realTarget, baseRoot)) {
741
+ return true;
742
+ }
743
+ if (isInsideOrEqualDir(resolved, baseRoot)) {
744
+ const rel = path.relative(baseRoot, resolved);
745
+ if (rel && hasVaultOrHoldoutSegment(rel))
746
+ return true;
747
+ }
748
+ if (isInsideOrEqualDir(realTarget, realBase)) {
749
+ const realRel = path.relative(realBase, realTarget);
750
+ if (realRel && hasVaultOrHoldoutSegment(realRel))
751
+ return true;
752
+ }
753
+ return false;
754
+ }
755
+ function assertContainedRelSecurity(rel, baseRoot, candidatePath, rawDisplay, fieldName, kind) {
756
+ if (!rel)
757
+ return;
758
+ if (hasVaultOrHoldoutSegment(rel) || isInsideVaultDirectory(candidatePath) || isPathTargetingVaultOrHoldout(candidatePath, baseRoot)) {
759
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} cannot access vault or holdout paths: ${redactVaultOrText(rawDisplay, true)}`);
760
+ }
761
+ if (kind !== "dir") {
762
+ const posixRel = rel.replace(/\\/g, "/");
763
+ if (isSecretRelativePath(posixRel, { ignoredSegments: new Set([".git"]) })) {
764
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} cannot access secret or credential files: ${redactMcpText(rawDisplay)}`);
765
+ }
766
+ if (kind === "output" && RESERVED_REPORT_OUTPUT_REL_PATHS.has(posixRel.toLowerCase())) {
767
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} cannot overwrite protected vibecode state file: ${redactMcpText(rawDisplay)}`);
768
+ }
769
+ }
770
+ }
771
+ function resolveMcpContainedPath(rootDir, raw, fieldName, kind) {
772
+ const baseRoot = path.resolve(rootDir);
773
+ if (kind === "dir" && raw === undefined)
774
+ return baseRoot;
775
+ const noun = kind === "dir" ? "directory" : kind === "input-path" ? "file or directory" : "file";
776
+ if (typeof raw !== "string" || !raw.trim()) {
777
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must be a non-empty ${noun} path string.`);
778
+ }
779
+ if (raw.includes("\0")) {
780
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must not contain NUL bytes.`);
781
+ }
782
+ const trimmed = raw.trim();
783
+ const allowRoot = kind === "dir" || kind === "input-path";
784
+ const resolved = path.resolve(baseRoot, expandLeadingTilde(trimmed, baseRoot));
785
+ if (hasVaultOrHoldoutSegment(trimmed) || isPathTargetingVaultOrHoldout(resolved, baseRoot)) {
786
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} cannot access vault or holdout paths: ${redactVaultOrText(trimmed, true)}`);
787
+ }
788
+ if (hasCrossPlatformPathEscape(trimmed) || !isInsideOrEqualDir(resolved, baseRoot)) {
789
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must stay within the workspace directory: ${redactMcpText(trimmed)}`);
790
+ }
791
+ const rel = path.relative(baseRoot, resolved);
792
+ if (!allowRoot && !rel) {
793
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must stay within the workspace directory: ${redactMcpText(trimmed)}`);
794
+ }
795
+ assertContainedRelSecurity(rel, baseRoot, resolved, trimmed, fieldName, kind);
796
+ const realBase = fs.existsSync(baseRoot) ? safeRealpath(baseRoot) : null;
797
+ if (realBase) {
798
+ const realTarget = safeRealpathOrNearestAncestor(resolved);
799
+ if (isPathTargetingVaultOrHoldout(realTarget, baseRoot)) {
800
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} cannot access vault or holdout paths: ${redactVaultOrText(trimmed, true)}`);
801
+ }
802
+ if (!isInsideOrEqualDir(realTarget, realBase)) {
803
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must stay within the workspace directory: ${redactMcpText(trimmed)}`);
804
+ }
805
+ const realTargetRel = path.relative(realBase, realTarget);
806
+ if (!allowRoot && !realTargetRel) {
807
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must stay within the workspace directory: ${redactMcpText(trimmed)}`);
808
+ }
809
+ assertContainedRelSecurity(realTargetRel, baseRoot, realTarget, trimmed, fieldName, kind);
810
+ }
811
+ if (kind === "output") {
812
+ try {
813
+ const lst = fs.lstatSync(resolved);
814
+ if (lst.isSymbolicLink()) {
815
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} cannot write through a symbolic link: ${redactMcpText(trimmed)}`);
816
+ }
817
+ if (lst.isDirectory()) {
818
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must point to a file, not a directory: ${redactMcpText(trimmed)}`);
819
+ }
820
+ }
821
+ catch (err) {
822
+ if (err instanceof VibecodeError)
823
+ throw err;
824
+ }
825
+ return resolved;
826
+ }
827
+ let st;
828
+ try {
829
+ st = fs.statSync(resolved);
830
+ }
831
+ catch {
832
+ if (kind === "dir") {
833
+ throw new VibecodeError("NOT_FOUND", `${fieldName} directory does not exist: ${redactMcpText(trimmed)}`);
834
+ }
835
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} ${kind === "input-file" ? "file" : "path"} does not exist: ${redactMcpText(trimmed)}`);
836
+ }
837
+ if (kind === "input-file" && st.isDirectory()) {
838
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must point to a file, not a directory: ${redactMcpText(trimmed)}`);
839
+ }
840
+ if (kind === "dir" && !st.isDirectory()) {
841
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must point to a directory: ${redactMcpText(trimmed)}`);
842
+ }
843
+ if (kind === "input-path" && !st.isFile() && !st.isDirectory()) {
844
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must point to a regular file or directory: ${redactMcpText(trimmed)}`);
845
+ }
846
+ if (realBase) {
847
+ const realResolved = safeRealpath(resolved);
848
+ if (isPathTargetingVaultOrHoldout(realResolved, baseRoot)) {
849
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} cannot access vault or holdout paths: ${redactVaultOrText(trimmed, true)}`);
850
+ }
851
+ if (!isInsideOrEqualDir(realResolved, realBase)) {
852
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must stay within the workspace directory: ${redactMcpText(trimmed)}`);
853
+ }
854
+ const realRel = path.relative(realBase, realResolved);
855
+ assertContainedRelSecurity(realRel, baseRoot, realResolved, trimmed, fieldName, kind);
856
+ }
857
+ return resolved;
858
+ }
859
+ function resolveMcpOutputPath(rootDir, raw, fieldName) {
860
+ return raw === undefined ? undefined : resolveMcpContainedPath(rootDir, raw, fieldName, "output");
861
+ }
862
+ function resolveMcpContainedInputFile(rootDir, raw, fieldName) {
863
+ return resolveMcpContainedPath(rootDir, raw, fieldName, "input-file");
864
+ }
865
+ function resolveMcpContainedDir(rootDir, raw, fieldName) {
866
+ return resolveMcpContainedPath(rootDir, raw, fieldName, "dir");
867
+ }
868
+ function resolveMcpContainedInputPath(rootDir, raw, fieldName) {
869
+ return resolveMcpContainedPath(rootDir, raw, fieldName, "input-path");
870
+ }
871
+ const STRICT_PATH_DOMAINS = new Set(["repo", "image", "video", "rea", "cli-anything"]);
872
+ const STRICT_SOURCE_FILE_DOMAINS = new Set(["image", "video", "rea", "cli-anything", "postman"]);
873
+ const HYBRID_PATH_OR_INLINE_DOMAINS = new Set([
874
+ "api",
875
+ "postman",
876
+ "curl",
877
+ "graphql",
878
+ "http-file",
879
+ "insomnia",
880
+ "bruno",
881
+ "asyncapi",
882
+ "openrpc",
883
+ "proto"
884
+ ]);
885
+ const NON_EXEC_DATA_EXTS = new Set([
886
+ ".json",
887
+ ".yaml",
888
+ ".yml",
889
+ ".har",
890
+ ".http",
891
+ ".rest",
892
+ ".graphql",
893
+ ".gql",
894
+ ".bru",
895
+ ".proto",
896
+ ".png",
897
+ ".jpg",
898
+ ".jpeg",
899
+ ".webp",
900
+ ".gif",
901
+ ".bmp",
902
+ ".mp4",
903
+ ".mov",
904
+ ".webm",
905
+ ".mkv",
906
+ ".avi",
907
+ ".m4v",
908
+ ".curl",
909
+ ".txt",
910
+ ".xml",
911
+ ".toml",
912
+ ".env",
913
+ ".ini",
914
+ ".conf",
915
+ ".log",
916
+ ".md",
917
+ ".csv"
918
+ ]);
919
+ const HOLDOUT_FILENAME_IN_TEXT_RE = /\bholdouts?(?:-[a-f0-9]+)?\.json\b/i;
920
+ const LEGACY_HOLDOUT_IN_TEXT_RE = /\.vibecode[\\/]holdouts?\b/i;
921
+ const VAULT_ENV_VAR_IN_TEXT_RE = /\bVIBECODE_VAULT_DIR\b/i;
922
+ const INLINE_SPEC_PREFIX_RE = /^\s*(?:\{|(?:openapi|swagger|asyncapi|openrpc|_type)\s*:|(?:syntax\s*=|package\s+[A-Za-z_][A-Za-z0-9_.]*\s*;|message\s+[A-Za-z_]\w*\s*\{|service\s+[A-Za-z_]\w*\s*\{)|(?:type|schema|input|interface|enum|union|scalar|query|mutation|subscription)\s+[A-Za-z_{]|meta\s*\{|(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+|curl(?:\.exe)?\s+)/i;
923
+ const CURL_INLINE_RE = /^\s*(?:[^\s"'`]*[\\/])?curl(?:\.exe)?\s+/i;
924
+ const PATH_TRAVERSAL_SEGMENT_RE = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
925
+ const MAX_COMMAND_TOKEN_DEPTH = 6;
926
+ const MAX_COMMAND_TOKEN_NODES = 512;
927
+ const MAX_NORMALIZE_PASSES = 16;
928
+ const SHELL_OPERATOR_SPLIT_RE = /[;|&<>()`\r\n,]+/;
929
+ const CURL_LONG_AT_FLAGS = new Set([
930
+ "--data",
931
+ "--data-binary",
932
+ "--data-raw",
933
+ "--data-ascii",
934
+ "--data-urlencode",
935
+ "--json",
936
+ "--header"
937
+ ]);
938
+ const CURL_LONG_FORM_FLAGS = new Set(["--form", "--form-string"]);
939
+ const CURL_LONG_FILE_FLAGS = new Set([
940
+ "--config",
941
+ "--cookie-jar",
942
+ "--upload-file",
943
+ "--output",
944
+ "--cacert",
945
+ "--cert",
946
+ "--key",
947
+ "--netrc-file",
948
+ "--proxy-cacert",
949
+ "--proxy-cert",
950
+ "--proxy-key",
951
+ "--trace",
952
+ "--trace-ascii",
953
+ "--dump-header"
954
+ ]);
955
+ const CURL_SHORT_AT_FLAGS = new Set(["d", "H"]);
956
+ const CURL_SHORT_FILE_FLAGS = new Set(["K", "c", "T", "o", "E", "D"]);
957
+ const CURL_SHORT_BOOL_FLAGS = new Set(["s", "S", "L", "i", "I", "k", "v", "f", "G", "g", "N", "O", "4", "6", "0"]);
958
+ const CURL_SHORT_NON_FILE_VALUE_FLAGS = new Set(["X", "u", "U", "A", "e", "w", "m", "x"]);
959
+ function detectDomainInWorkspace(rootDir, source) {
960
+ const trimmed = source.trim();
961
+ if (!trimmed || isPureHttpUrlToken(trimmed))
962
+ return detectDomain(trimmed);
963
+ if (!/[\r\n]/.test(trimmed)) {
964
+ const absCandidate = path.resolve(rootDir, trimmed);
965
+ if (fs.existsSync(absCandidate)) {
966
+ return detectDomain(absCandidate);
967
+ }
968
+ }
969
+ return detectDomain(trimmed);
970
+ }
971
+ function textMentionsVaultOrHoldout(rawText, rootDir) {
972
+ const lower = rawText.toLowerCase();
973
+ if (lower.includes(".vibecode-vault"))
974
+ return true;
975
+ if (HOLDOUT_FILENAME_IN_TEXT_RE.test(rawText) ||
976
+ LEGACY_HOLDOUT_IN_TEXT_RE.test(rawText) ||
977
+ VAULT_ENV_VAR_IN_TEXT_RE.test(rawText)) {
978
+ return true;
979
+ }
980
+ const envVault = process.env.VIBECODE_VAULT_DIR?.trim();
981
+ if (envVault) {
982
+ const resolvedVault = path.resolve(expandLeadingTilde(envVault, rootDir));
983
+ const realVault = safeRealpathOrNearestAncestor(resolvedVault);
984
+ for (const variant of [envVault, resolvedVault, realVault, resolvedVault.replace(/\\/g, "/"), realVault.replace(/\\/g, "/")]) {
985
+ if (variant && lower.includes(variant.toLowerCase()))
986
+ return true;
987
+ }
988
+ }
989
+ if (!/[\r\n]/.test(rawText)) {
990
+ for (const expanded of expandLeadingTildeCandidates(rawText, rootDir)) {
991
+ const candidate = path.resolve(rootDir, expanded);
992
+ if (isInsideVaultDirectory(candidate) ||
993
+ isInsideVaultDir(candidate, rootDir) ||
994
+ hasVaultOrHoldoutSegment(candidate) ||
995
+ hasVaultOrHoldoutSegment(safeRealpathOrNearestAncestor(candidate))) {
996
+ return true;
997
+ }
998
+ if ((rawText.includes("/") || rawText.includes("\\") || fs.existsSync(candidate) || lstatExists(candidate)) &&
999
+ isPathTargetingVaultOrHoldout(candidate, rootDir)) {
1000
+ return true;
1001
+ }
1002
+ }
1003
+ }
1004
+ return false;
1005
+ }
1006
+ function stripOuterMatchingQuotes(raw) {
1007
+ let cand = raw.trim();
1008
+ while (cand.length >= 2 &&
1009
+ ((cand.startsWith('"') && cand.endsWith('"')) || (cand.startsWith("'") && cand.endsWith("'")))) {
1010
+ cand = cand.slice(1, -1).trim();
1011
+ }
1012
+ return cand;
1013
+ }
1014
+ function expandCommandEnvVars(raw, rootDir) {
1015
+ const absRoot = path.resolve(rootDir);
1016
+ const absHome = os.homedir();
1017
+ const vaultBase = path.resolve(expandLeadingTilde(process.env.VIBECODE_VAULT_DIR?.trim() || "~/.vibecode-vault", absRoot));
1018
+ const oldPwd = process.env.OLDPWD?.trim();
1019
+ const absOldPwd = oldPwd ? path.resolve(oldPwd) : undefined;
1020
+ return raw.replace(/\$\{(PWD|HOME|VIBECODE_VAULT_DIR|OLDPWD)(?:(?::?[-=?]|[%#]+)[^}]*)?\}|\$(PWD|HOME|VIBECODE_VAULT_DIR|OLDPWD)(?![A-Za-z0-9_])/g, (match, braced, bare) => {
1021
+ const name = braced ?? bare;
1022
+ if (name === "PWD")
1023
+ return absRoot;
1024
+ if (name === "HOME")
1025
+ return absHome;
1026
+ if (name === "VIBECODE_VAULT_DIR")
1027
+ return vaultBase;
1028
+ if (name === "OLDPWD" && absOldPwd)
1029
+ return absOldPwd;
1030
+ return match;
1031
+ });
1032
+ }
1033
+ function normalizeCommandCandidatePath(rawCand, rootDir) {
1034
+ let cand = rawCand.trim();
1035
+ let converged = false;
1036
+ for (let pass = 0; pass < MAX_NORMALIZE_PASSES; pass++) {
1037
+ const prev = cand;
1038
+ cand = stripOuterMatchingQuotes(cand);
1039
+ cand = cand.replace(/^(?:\$\(|[0-9]+(?=[<>])|[<>]+|@)+/, "");
1040
+ cand = stripOuterMatchingQuotes(cand);
1041
+ cand = cand.replace(/\)+$/, "");
1042
+ if (/^file:\/\//i.test(cand)) {
1043
+ let fileRest = cand.replace(/^file:\/\//i, "").replace(/[?#].*$/, "");
1044
+ if (fileRest.includes("%")) {
1045
+ try {
1046
+ fileRest = decodeURIComponent(fileRest);
1047
+ }
1048
+ catch {
1049
+ // Keep raw remainder when percent-encoding is malformed.
1050
+ }
1051
+ }
1052
+ fileRest = fileRest.replace(/^(?:localhost|127\.0\.0\.1)(?=[\\/]|$)/i, "");
1053
+ cand = fileRest.replace(/^\/+(?=[$~])/, "");
1054
+ }
1055
+ cand = expandCommandEnvVars(cand, rootDir);
1056
+ cand = expandLeadingTilde(cand, rootDir);
1057
+ if (process.platform === "win32") {
1058
+ cand = cand.replace(/^[\\/.]+(?=[A-Za-z]:[\\/])/, "");
1059
+ }
1060
+ cand = cand.trim();
1061
+ if (cand === prev) {
1062
+ converged = true;
1063
+ break;
1064
+ }
1065
+ }
1066
+ if (!converged) {
1067
+ return { value: cand.trim(), converged: false };
1068
+ }
1069
+ cand = cand.replace(/^(?:\$\{|\$)+/, "");
1070
+ cand = cand.replace(/[)}]+$/, "");
1071
+ return { value: cand.trim(), converged: true };
1072
+ }
1073
+ function needsRecursiveTokenization(trimmed) {
1074
+ if (SHELL_OPERATOR_SPLIT_RE.test(trimmed))
1075
+ return true;
1076
+ const parts = splitCommand(trimmed);
1077
+ return parts.length > 1 || (parts.length === 1 && parts[0] !== trimmed);
1078
+ }
1079
+ function collectRecursiveCommandCandidates(rawText, rootDir) {
1080
+ const candidates = [];
1081
+ const seenCandidates = new Set();
1082
+ const visited = new Set();
1083
+ const queue = [];
1084
+ let truncated = false;
1085
+ let unconverged = false;
1086
+ const recordCandidate = (value) => {
1087
+ if (!value || isPureHttpUrlToken(value) || seenCandidates.has(value))
1088
+ return;
1089
+ seenCandidates.add(value);
1090
+ candidates.push(value);
1091
+ };
1092
+ const enqueue = (text, depth) => {
1093
+ const trimmed = text.trim();
1094
+ if (!trimmed || isPureHttpUrlToken(trimmed))
1095
+ return;
1096
+ if (depth > 0 && !needsRecursiveTokenization(trimmed))
1097
+ return;
1098
+ if (visited.has(trimmed))
1099
+ return;
1100
+ if (depth > MAX_COMMAND_TOKEN_DEPTH || visited.size >= MAX_COMMAND_TOKEN_NODES) {
1101
+ truncated = true;
1102
+ return;
1103
+ }
1104
+ visited.add(trimmed);
1105
+ queue.push({ text: trimmed, depth });
1106
+ };
1107
+ const addCandidate = (rawCand) => {
1108
+ const trimmed = rawCand.trim();
1109
+ if (!trimmed || isPureHttpUrlToken(trimmed))
1110
+ return;
1111
+ recordCandidate(trimmed);
1112
+ const { value: normalized, converged } = normalizeCommandCandidatePath(trimmed, rootDir);
1113
+ if (!converged) {
1114
+ unconverged = true;
1115
+ }
1116
+ recordCandidate(normalized);
1117
+ if (process.platform !== "win32" && normalized.includes("\\")) {
1118
+ let unescaped = normalized;
1119
+ for (let pass = 0; pass < MAX_NORMALIZE_PASSES && unescaped.includes("\\"); pass++) {
1120
+ const next = unescaped.replace(/\\(.)/g, "$1").trim();
1121
+ if (next === unescaped)
1122
+ break;
1123
+ unescaped = next;
1124
+ }
1125
+ unescaped = unescaped.replace(/\\+$/, "").trim();
1126
+ recordCandidate(unescaped);
1127
+ const unescapedNorm = normalizeCommandCandidatePath(unescaped, rootDir);
1128
+ if (!unescapedNorm.converged) {
1129
+ unconverged = true;
1130
+ }
1131
+ recordCandidate(unescapedNorm.value);
1132
+ }
1133
+ };
1134
+ enqueue(rawText, 0);
1135
+ while (queue.length > 0 && !truncated && !unconverged) {
1136
+ const { text, depth } = queue.shift();
1137
+ const splitToks = splitCommand(text);
1138
+ const opToks = text.split(SHELL_OPERATOR_SPLIT_RE);
1139
+ const combined = [...splitToks, ...opToks];
1140
+ for (const rawTok of combined) {
1141
+ if (truncated || unconverged)
1142
+ break;
1143
+ const tok = rawTok.trim();
1144
+ if (!tok || isPureHttpUrlToken(tok))
1145
+ continue;
1146
+ addCandidate(tok);
1147
+ const hasWhitespace = /\s/.test(tok);
1148
+ if (!hasWhitespace) {
1149
+ for (let eqIdx = tok.indexOf("="); eqIdx >= 0 && eqIdx < tok.length - 1; eqIdx = tok.indexOf("=", eqIdx + 1)) {
1150
+ const rhs = tok.slice(eqIdx + 1).trim();
1151
+ addCandidate(rhs);
1152
+ enqueue(rhs, depth + 1);
1153
+ }
1154
+ for (let atIdx = tok.indexOf("@"); atIdx >= 0 && atIdx < tok.length - 1; atIdx = tok.indexOf("@", atIdx + 1)) {
1155
+ const atPath = tok.slice(atIdx + 1).trim();
1156
+ addCandidate(atPath);
1157
+ enqueue(atPath, depth + 1);
1158
+ }
1159
+ }
1160
+ else {
1161
+ const firstSpace = tok.search(/\s/);
1162
+ const eqIdx = tok.indexOf("=");
1163
+ if (eqIdx >= 0 && eqIdx < firstSpace && eqIdx < tok.length - 1) {
1164
+ addCandidate(tok.slice(eqIdx + 1).trim());
1165
+ }
1166
+ const atIdx = tok.indexOf("@");
1167
+ if (atIdx >= 0 && atIdx < firstSpace && atIdx < tok.length - 1) {
1168
+ addCandidate(tok.slice(atIdx + 1).trim());
1169
+ }
1170
+ }
1171
+ if (/^file:\/\//i.test(tok)) {
1172
+ try {
1173
+ const u = new URL(tok);
1174
+ if (u.pathname) {
1175
+ let decodedPathname = u.pathname;
1176
+ if (decodedPathname.includes("%")) {
1177
+ try {
1178
+ decodedPathname = decodeURIComponent(decodedPathname);
1179
+ }
1180
+ catch {
1181
+ // Keep raw pathname when percent-encoding is malformed.
1182
+ }
1183
+ }
1184
+ addCandidate(decodedPathname);
1185
+ }
1186
+ }
1187
+ catch {
1188
+ // Ignore malformed file URL.
1189
+ }
1190
+ const strippedFile = tok.replace(/^file:\/\/(?:localhost|127\.0\.0\.1)?/i, "");
1191
+ if (strippedFile) {
1192
+ addCandidate(strippedFile);
1193
+ enqueue(strippedFile, depth + 1);
1194
+ }
1195
+ }
1196
+ const expandedTok = expandCommandEnvVars(tok.replace(/\$\{IFS\}|\$IFS(?![A-Za-z0-9_])/g, " "), rootDir);
1197
+ const stripped = expandedTok
1198
+ .replace(/^(?:\$\(|[0-9]+[<>]+|[<>]+)+/, "")
1199
+ .replace(/\)+$/, "")
1200
+ .trim();
1201
+ if (stripped && stripped !== tok) {
1202
+ addCandidate(stripped);
1203
+ enqueue(stripped, depth + 1);
1204
+ }
1205
+ if (tok !== text) {
1206
+ enqueue(tok, depth + 1);
1207
+ }
1208
+ }
1209
+ }
1210
+ return { candidates, truncated, unconverged };
1211
+ }
1212
+ function commandTokensTargetVaultOrHoldout(rawText, rootDir) {
1213
+ const { candidates, truncated, unconverged } = collectRecursiveCommandCandidates(rawText, rootDir);
1214
+ if (truncated || unconverged) {
1215
+ return true;
1216
+ }
1217
+ const envVault = process.env.VIBECODE_VAULT_DIR?.trim();
1218
+ const envVaultVariants = [];
1219
+ if (envVault) {
1220
+ const resolvedVault = path.resolve(expandLeadingTilde(envVault, rootDir));
1221
+ const realVault = safeRealpathOrNearestAncestor(resolvedVault);
1222
+ for (const variant of [envVault, resolvedVault, realVault, resolvedVault.replace(/\\/g, "/"), realVault.replace(/\\/g, "/")]) {
1223
+ if (variant)
1224
+ envVaultVariants.push(variant.toLowerCase());
1225
+ }
1226
+ }
1227
+ for (const cand of candidates) {
1228
+ const lowerCand = cand.toLowerCase();
1229
+ if (hasVaultOrHoldoutSegment(cand) ||
1230
+ HOLDOUT_FILENAME_IN_TEXT_RE.test(cand) ||
1231
+ LEGACY_HOLDOUT_IN_TEXT_RE.test(cand) ||
1232
+ VAULT_ENV_VAR_IN_TEXT_RE.test(cand) ||
1233
+ envVaultVariants.some((v) => lowerCand.includes(v))) {
1234
+ return true;
1235
+ }
1236
+ for (const expanded of expandLeadingTildeCandidates(cand, rootDir)) {
1237
+ const resolved = path.resolve(rootDir, expanded);
1238
+ const realTarget = safeRealpathOrNearestAncestor(resolved);
1239
+ if (isInsideVaultDirectory(resolved) ||
1240
+ isInsideVaultDirectory(realTarget) ||
1241
+ isInsideVaultDir(resolved, rootDir) ||
1242
+ isInsideVaultDir(realTarget, rootDir) ||
1243
+ hasVaultOrHoldoutSegment(resolved) ||
1244
+ hasVaultOrHoldoutSegment(realTarget)) {
1245
+ return true;
1246
+ }
1247
+ if ((cand.includes("/") || cand.includes("\\") || fs.existsSync(resolved) || lstatExists(resolved)) &&
1248
+ isPathTargetingVaultOrHoldout(resolved, rootDir)) {
1249
+ return true;
1250
+ }
1251
+ }
1252
+ }
1253
+ return false;
1254
+ }
1255
+ function assertNoVaultAccessInText(rootDir, rawText, fieldName) {
1256
+ if (rawText.includes("\0")) {
1257
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must not contain NUL bytes.`);
1258
+ }
1259
+ if (textMentionsVaultOrHoldout(rawText, rootDir)) {
1260
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} cannot access vault or holdout paths: ${redactVaultOrText(rawText, true)}`);
1261
+ }
1262
+ if (isPureHttpUrlToken(rawText))
1263
+ return;
1264
+ if (commandTokensTargetVaultOrHoldout(rawText, rootDir)) {
1265
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} cannot access vault or holdout paths: ${redactVaultOrText(rawText, true)}`);
1266
+ }
1267
+ }
1268
+ function assertMcpPathContainedInWorkspace(rootDir, rawPath, fieldName) {
1269
+ const trimmed = rawPath.trim();
1270
+ const baseRoot = path.resolve(rootDir);
1271
+ const realBase = safeRealpath(baseRoot);
1272
+ const resolved = path.resolve(baseRoot, expandLeadingTilde(trimmed, baseRoot));
1273
+ const realTarget = safeRealpathOrNearestAncestor(resolved);
1274
+ if (hasVaultOrHoldoutSegment(trimmed) || isPathTargetingVaultOrHoldout(resolved, baseRoot) || isPathTargetingVaultOrHoldout(realTarget, baseRoot)) {
1275
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} cannot access vault or holdout paths: ${redactVaultOrText(trimmed, true)}`);
1276
+ }
1277
+ if (hasCrossPlatformPathEscape(trimmed)) {
1278
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must stay within the workspace directory: ${redactMcpText(trimmed)}`);
1279
+ }
1280
+ if (!isInsideOrEqualDir(resolved, baseRoot) || !isInsideOrEqualDir(realTarget, realBase)) {
1281
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must stay within the workspace directory: ${redactMcpText(trimmed)}`);
1282
+ }
1283
+ }
1284
+ function validateMcpInlineCurlArgs(rootDir, rawText, fieldName) {
1285
+ const unfolded = rawText.replace(/\\\r?\n/g, " ");
1286
+ const lines = unfolded.split(/\r?\n/);
1287
+ const checkFileCandidate = (rawFilePath) => {
1288
+ if (!rawFilePath)
1289
+ return;
1290
+ const cleaned = rawFilePath.trim();
1291
+ if (!cleaned || cleaned === "-")
1292
+ return;
1293
+ assertMcpPathContainedInWorkspace(rootDir, cleaned, fieldName);
1294
+ if (/[;|&]/.test(cleaned)) {
1295
+ const beforeOp = cleaned.split(/[;|&]/)[0]?.trim();
1296
+ if (beforeOp && beforeOp !== "-") {
1297
+ assertMcpPathContainedInWorkspace(rootDir, beforeOp, fieldName);
1298
+ }
1299
+ }
1300
+ };
1301
+ const checkAtValue = (rawVal, allowNamedUrlencode = false) => {
1302
+ if (!rawVal)
1303
+ return;
1304
+ const val = rawVal.trim();
1305
+ if (val.startsWith("@")) {
1306
+ checkFileCandidate(val.slice(1));
1307
+ return;
1308
+ }
1309
+ if (allowNamedUrlencode && !val.startsWith("=")) {
1310
+ const atIdx = val.indexOf("@");
1311
+ const eqIdx = val.indexOf("=");
1312
+ if (atIdx >= 0 && (eqIdx < 0 || atIdx < eqIdx)) {
1313
+ checkFileCandidate(val.slice(atIdx + 1));
1314
+ }
1315
+ }
1316
+ };
1317
+ const checkFormValue = (rawVal) => {
1318
+ if (!rawVal)
1319
+ return;
1320
+ const val = rawVal.trim();
1321
+ const eqIdx = val.indexOf("=");
1322
+ const rhs = eqIdx >= 0 ? val.slice(eqIdx + 1).trim() : val;
1323
+ if (rhs.startsWith("@") || rhs.startsWith("<")) {
1324
+ const filePart = rhs.slice(1).split(";")[0];
1325
+ checkFileCandidate(filePart);
1326
+ }
1327
+ };
1328
+ const checkCookieValue = (rawVal) => {
1329
+ if (!rawVal)
1330
+ return;
1331
+ const val = rawVal.trim();
1332
+ if (!val || val === "-")
1333
+ return;
1334
+ const candidate = path.resolve(rootDir, expandLeadingTilde(val.replace(/^@/, ""), rootDir));
1335
+ const looksLikeFile = !val.includes("=") ||
1336
+ val.includes("/") ||
1337
+ val.includes("\\") ||
1338
+ val.startsWith("~") ||
1339
+ val.startsWith("@") ||
1340
+ PATH_TRAVERSAL_SEGMENT_RE.test(val) ||
1341
+ lstatExists(candidate) ||
1342
+ fs.existsSync(candidate);
1343
+ if (looksLikeFile) {
1344
+ checkFileCandidate(val.replace(/^@/, ""));
1345
+ }
1346
+ };
1347
+ for (const line of lines) {
1348
+ const trimmedLine = line.trim();
1349
+ if (!trimmedLine || trimmedLine.startsWith("#"))
1350
+ continue;
1351
+ const tokens = splitCommand(trimmedLine);
1352
+ for (let i = 0; i < tokens.length; i++) {
1353
+ const tok = tokens[i];
1354
+ if (!tok)
1355
+ continue;
1356
+ if (/^file:\/\//i.test(tok)) {
1357
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} cannot use file:// URLs: ${redactMcpText(tok)}`);
1358
+ }
1359
+ if (tok === "--")
1360
+ break;
1361
+ if (tok.startsWith("--")) {
1362
+ const eqIdx = tok.indexOf("=");
1363
+ const flag = eqIdx > 0 ? tok.slice(0, eqIdx) : tok;
1364
+ const inlineVal = eqIdx > 0 ? tok.slice(eqIdx + 1) : undefined;
1365
+ const consumeVal = () => (inlineVal !== undefined ? inlineVal : tokens[++i]);
1366
+ if (CURL_LONG_AT_FLAGS.has(flag)) {
1367
+ checkAtValue(consumeVal(), flag === "--data-urlencode");
1368
+ }
1369
+ else if (CURL_LONG_FORM_FLAGS.has(flag)) {
1370
+ checkFormValue(consumeVal());
1371
+ }
1372
+ else if (CURL_LONG_FILE_FLAGS.has(flag)) {
1373
+ checkFileCandidate(consumeVal());
1374
+ }
1375
+ else if (flag === "--cookie") {
1376
+ checkCookieValue(consumeVal());
1377
+ }
1378
+ continue;
1379
+ }
1380
+ if (tok.startsWith("-") && tok.length > 1) {
1381
+ for (let j = 1; j < tok.length; j++) {
1382
+ const ch = tok[j];
1383
+ if (CURL_SHORT_BOOL_FLAGS.has(ch))
1384
+ continue;
1385
+ const rest = j + 1 < tok.length ? tok.slice(j + 1) : undefined;
1386
+ const consumeShortVal = () => (rest !== undefined ? rest : tokens[++i]);
1387
+ if (CURL_SHORT_AT_FLAGS.has(ch)) {
1388
+ checkAtValue(consumeShortVal());
1389
+ }
1390
+ else if (ch === "F") {
1391
+ checkFormValue(consumeShortVal());
1392
+ }
1393
+ else if (CURL_SHORT_FILE_FLAGS.has(ch)) {
1394
+ checkFileCandidate(consumeShortVal());
1395
+ }
1396
+ else if (ch === "b") {
1397
+ checkCookieValue(consumeShortVal());
1398
+ }
1399
+ else if (CURL_SHORT_NON_FILE_VALUE_FLAGS.has(ch)) {
1400
+ consumeShortVal();
1401
+ }
1402
+ break;
1403
+ }
1404
+ }
1405
+ }
1406
+ }
1407
+ }
1408
+ const DISALLOWED_MCP_URL_SCHEME_RE = /^(?:file|javascript|data|vbscript|blob|about|mailto|ftp|ftps|gopher):/i;
1409
+ function assertNotDisallowedUrlScheme(rawValue, fieldName) {
1410
+ if (/^file:\/\//i.test(rawValue)) {
1411
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} cannot use file:// URLs: ${redactMcpText(rawValue)}`);
1412
+ }
1413
+ if (DISALLOWED_MCP_URL_SCHEME_RE.test(rawValue)) {
1414
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} uses unsupported URL scheme: ${redactMcpText(rawValue)}`);
1415
+ }
1416
+ }
1417
+ function validateMcpSource(rootDir, rawSource, explicitDomain, fieldName) {
1418
+ const trimmed = rawSource.trim();
1419
+ if (!trimmed)
1420
+ return;
1421
+ assertNoVaultAccessInText(rootDir, trimmed, fieldName);
1422
+ assertNotDisallowedUrlScheme(trimmed, fieldName);
1423
+ const domain = explicitDomain?.toLowerCase();
1424
+ if (domain !== "cli" && domain !== "script" && isPureHttpUrlToken(trimmed)) {
1425
+ try {
1426
+ parseSafeHttpBaseUrl(trimmed, { allowWs: domain === "api" });
1427
+ }
1428
+ catch (err) {
1429
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName}: ${redactMcpText(errorMessage(err))}`);
1430
+ }
1431
+ return;
1432
+ }
1433
+ if (domain === "repo") {
1434
+ resolveMcpContainedDir(rootDir, trimmed, fieldName);
1435
+ return;
1436
+ }
1437
+ if (domain && STRICT_SOURCE_FILE_DOMAINS.has(domain)) {
1438
+ assertMcpPathContainedInWorkspace(rootDir, trimmed, fieldName);
1439
+ return;
1440
+ }
1441
+ const hasNewline = /[\r\n]/.test(trimmed);
1442
+ const looksStrictlyInline = INLINE_SPEC_PREFIX_RE.test(trimmed);
1443
+ const looksInlineCurl = CURL_INLINE_RE.test(trimmed) || isCurlCommandText(trimmed);
1444
+ const candidate = !hasNewline ? path.resolve(rootDir, expandLeadingTilde(trimmed, rootDir)) : "";
1445
+ const existsOrSymlinkOnDisk = !hasNewline && (lstatExists(candidate) || fs.existsSync(candidate));
1446
+ const containsTraversal = !hasNewline &&
1447
+ (PATH_TRAVERSAL_SEGMENT_RE.test(trimmed) ||
1448
+ hasCrossPlatformPathEscape(trimmed) ||
1449
+ /^~(?:[+-]|[A-Za-z0-9._-]+)?(?:[\\/]|$)/.test(trimmed));
1450
+ if (domain && HYBRID_PATH_OR_INLINE_DOMAINS.has(domain)) {
1451
+ if (!hasNewline && (containsTraversal || existsOrSymlinkOnDisk || !looksStrictlyInline)) {
1452
+ assertMcpPathContainedInWorkspace(rootDir, trimmed, fieldName);
1453
+ if (existsOrSymlinkOnDisk) {
1454
+ for (const brunoEntry of ["bruno.json", "environments"]) {
1455
+ const brunoPath = path.join(candidate, brunoEntry);
1456
+ if (lstatExists(brunoPath)) {
1457
+ assertMcpPathContainedInWorkspace(rootDir, brunoPath, fieldName);
1458
+ }
1459
+ }
1460
+ }
1461
+ return;
1462
+ }
1463
+ if (domain === "curl" || looksInlineCurl) {
1464
+ validateMcpInlineCurlArgs(rootDir, trimmed, fieldName);
1465
+ }
1466
+ return;
1467
+ }
1468
+ if (!domain) {
1469
+ if (looksInlineCurl) {
1470
+ validateMcpInlineCurlArgs(rootDir, trimmed, fieldName);
1471
+ }
1472
+ if (!hasNewline) {
1473
+ const tokens = splitCommand(trimmed);
1474
+ const baseRoot = path.resolve(rootDir);
1475
+ const realBase = safeRealpath(baseRoot);
1476
+ const realCandidate = safeRealpathOrNearestAncestor(candidate);
1477
+ if (existsOrSymlinkOnDisk) {
1478
+ if (isInsideOrEqualDir(candidate, baseRoot) && !isInsideOrEqualDir(realCandidate, realBase)) {
1479
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must stay within the workspace directory: ${redactMcpText(trimmed)}`);
1480
+ }
1481
+ if (!isInsideOrEqualDir(candidate, baseRoot)) {
1482
+ let isDir = false;
1483
+ let isExecutableFile = false;
1484
+ try {
1485
+ const st = fs.statSync(candidate);
1486
+ isDir = st.isDirectory();
1487
+ isExecutableFile =
1488
+ st.isFile() &&
1489
+ (process.platform === "win32" ? /\.(exe|cmd|bat|com)$/i.test(candidate) : (st.mode & 0o111) !== 0);
1490
+ }
1491
+ catch {
1492
+ // Broken symlink outside workspace.
1493
+ }
1494
+ const ext = path.extname(candidate).toLowerCase();
1495
+ if (isDir || NON_EXEC_DATA_EXTS.has(ext) || !isExecutableFile) {
1496
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must stay within the workspace directory: ${redactMcpText(trimmed)}`);
1497
+ }
1498
+ }
1499
+ for (const brunoEntry of ["bruno.json", "environments"]) {
1500
+ const brunoPath = path.join(candidate, brunoEntry);
1501
+ if (lstatExists(brunoPath)) {
1502
+ assertMcpPathContainedInWorkspace(rootDir, brunoPath, fieldName);
1503
+ }
1504
+ }
1505
+ return;
1506
+ }
1507
+ if (tokens.length === 1 && (containsTraversal || !looksStrictlyInline)) {
1508
+ if (containsTraversal) {
1509
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must stay within the workspace directory: ${redactMcpText(trimmed)}`);
1510
+ }
1511
+ if (!isInsideOrEqualDir(candidate, baseRoot) || !isInsideOrEqualDir(realCandidate, realBase)) {
1512
+ throw new VibecodeError("CONTRACT_INVALID", `${fieldName} must stay within the workspace directory: ${redactMcpText(trimmed)}`);
1513
+ }
1514
+ }
1515
+ }
1516
+ }
1517
+ }
1518
+ function validateMcpEnv(rootDir, env) {
1519
+ if (!env)
1520
+ return;
1521
+ for (const [key, value] of Object.entries(env)) {
1522
+ if (key.toUpperCase() === "VIBECODE_VAULT_DIR") {
1523
+ throw new VibecodeError("CONTRACT_INVALID", "env cannot override VIBECODE_VAULT_DIR.");
1524
+ }
1525
+ assertNoVaultAccessInText(rootDir, value, `env.${key}`);
1526
+ }
1527
+ }
1528
+ function validateMcpProbes(rootDir, rawProbes) {
1529
+ if (!Array.isArray(rawProbes))
1530
+ return;
1531
+ for (let i = 0; i < rawProbes.length; i++) {
1532
+ const item = rawProbes[i];
1533
+ if (typeof item === "string") {
1534
+ assertNoVaultAccessInText(rootDir, item, `probes[${i}]`);
1535
+ }
1536
+ else if (isPlainObjectSafe(item)) {
1537
+ if (Array.isArray(item.args)) {
1538
+ for (let j = 0; j < item.args.length; j++) {
1539
+ if (typeof item.args[j] === "string") {
1540
+ assertNoVaultAccessInText(rootDir, item.args[j], `probes[${i}].args[${j}]`);
1541
+ }
1542
+ }
1543
+ }
1544
+ if (typeof item.stdin === "string") {
1545
+ assertNoVaultAccessInText(rootDir, item.stdin, `probes[${i}].stdin`);
1546
+ }
1547
+ if (isPlainObjectSafe(item.env)) {
1548
+ for (const [k, v] of Object.entries(item.env)) {
1549
+ if (k.toUpperCase() === "VIBECODE_VAULT_DIR") {
1550
+ throw new VibecodeError("CONTRACT_INVALID", `probes[${i}].env cannot override VIBECODE_VAULT_DIR.`);
1551
+ }
1552
+ if (typeof v === "string") {
1553
+ assertNoVaultAccessInText(rootDir, v, `probes[${i}].env.${k}`);
1554
+ }
1555
+ }
1556
+ }
1557
+ }
1558
+ }
1559
+ }
1560
+ function validateMcpCommandsFileContent(rootDir, commandsFilePath) {
1561
+ const read = readBoundedFileUtf8(commandsFilePath, 2 * 1024 * 1024, { noFollow: false, rejectBinary: false });
1562
+ if (!read.ok)
1563
+ return;
1564
+ for (const rawLine of read.text.split(/\r?\n/)) {
1565
+ const trimmed = rawLine.trim();
1566
+ if (!trimmed || trimmed.startsWith("#"))
1567
+ continue;
1568
+ assertNoVaultAccessInText(rootDir, trimmed, "fromCommands");
1569
+ }
1570
+ }
1571
+ function collectTargetConsumingDomains(rootDir, contract, options = {}) {
1572
+ const allContractInvs = [...(contract.invariants || []), ...readHoldouts(rootDir)];
1573
+ const filterIds = Array.isArray(options.invariantIds) && options.invariantIds.length > 0
1574
+ ? new Set(options.invariantIds)
1575
+ : null;
1576
+ let evaluated = filterIds ? allContractInvs.filter((inv) => filterIds.has(inv.id)) : allContractInvs;
1577
+ if (options.mode === "functional") {
1578
+ evaluated = evaluated.filter((inv) => inv.type !== "image_layout" && inv.type !== "image_perceptual");
1579
+ }
1580
+ const targetDomains = new Set();
1581
+ for (const inv of evaluated) {
1582
+ const t = String(inv.type || "").toLowerCase();
1583
+ if (t === "repo_exports") {
1584
+ targetDomains.add("repo");
1585
+ }
1586
+ else if (t === "image_layout" || t === "image_perceptual") {
1587
+ targetDomains.add("image");
1588
+ }
1589
+ else if (t === "video_timeline") {
1590
+ targetDomains.add("video");
1591
+ }
1592
+ else if (t === "command") {
1593
+ targetDomains.add("cli");
1594
+ }
1595
+ else if (t.startsWith("web_")) {
1596
+ targetDomains.add("web");
1597
+ }
1598
+ else if (t === "http" || t === "http_workflow" || t === "http_stream" || t === "ws_protocol" || t === "perf_budget") {
1599
+ targetDomains.add("api");
1600
+ }
1601
+ else if (t.startsWith("plugin_")) {
1602
+ // Plugin invariants consume input.path/workspace rather than treating fallback target as a repo directory.
1603
+ continue;
1604
+ }
1605
+ const dom = String(inv.domain || "").toLowerCase();
1606
+ if (dom === "rea" || dom === "cli-anything") {
1607
+ targetDomains.add(dom);
1608
+ }
1609
+ }
1610
+ if (allContractInvs.length === 0) {
1611
+ for (const d of contract.target?.domains || []) {
1612
+ targetDomains.add(String(d).toLowerCase());
1613
+ }
1614
+ }
1615
+ return targetDomains;
1616
+ }
1617
+ function validateMcpTargetForDomain(rootDir, domain, rawTarget, fieldName) {
1618
+ const trimmed = rawTarget.trim();
1619
+ if (!trimmed)
1620
+ return;
1621
+ assertNoVaultAccessInText(rootDir, trimmed, fieldName);
1622
+ assertNotDisallowedUrlScheme(trimmed, fieldName);
1623
+ const lowerDomain = domain.toLowerCase();
1624
+ if (lowerDomain === "repo") {
1625
+ resolveMcpContainedDir(rootDir, trimmed, fieldName);
1626
+ return;
1627
+ }
1628
+ if (STRICT_PATH_DOMAINS.has(lowerDomain) && !isPureHttpUrlToken(trimmed)) {
1629
+ assertMcpPathContainedInWorkspace(rootDir, trimmed, fieldName);
1630
+ return;
1631
+ }
1632
+ if (lowerDomain === "web" || lowerDomain === "url" || lowerDomain === "api") {
1633
+ try {
1634
+ parseSafeHttpBaseUrl(trimmed, { allowWs: lowerDomain === "api" });
1635
+ }
1636
+ catch (err) {
1637
+ throw new VibecodeError("CONFIG_INVALID", `${fieldName}: ${redactMcpText(errorMessage(err))}`);
1638
+ }
1639
+ }
1640
+ }
1641
+ function validateMcpFallbackTargetForContract(rootDir, rawTarget, targetDomains, fieldName, overriddenTargets) {
1642
+ const trimmed = rawTarget.trim();
1643
+ if (!trimmed)
1644
+ return;
1645
+ assertNoVaultAccessInText(rootDir, trimmed, fieldName);
1646
+ assertNotDisallowedUrlScheme(trimmed, fieldName);
1647
+ const isOverridden = (d) => Boolean(overriddenTargets && Object.prototype.hasOwnProperty.call(overriddenTargets, d));
1648
+ if (targetDomains.has("repo") && !isOverridden("repo")) {
1649
+ resolveMcpContainedDir(rootDir, trimmed, fieldName);
1650
+ }
1651
+ else if (((targetDomains.has("image") && !isOverridden("image")) ||
1652
+ (targetDomains.has("video") && !isOverridden("video")) ||
1653
+ (targetDomains.has("rea") && !isOverridden("rea")) ||
1654
+ (targetDomains.has("cli-anything") && !isOverridden("cli-anything"))) &&
1655
+ !isPureHttpUrlToken(trimmed)) {
1656
+ assertMcpPathContainedInWorkspace(rootDir, trimmed, fieldName);
1657
+ }
1658
+ }
1659
+ const MCP_EXAMPLE_SPEC_PATH_RE = /^(?:examples?|samples?|demos?|docs|tests?|__tests__|fixtures?|benchmarks?)\//i;
1660
+ const MCP_LOCK_SPEC_PRIORITY = {
1661
+ openapi: 0,
1662
+ asyncapi: 1,
1663
+ openrpc: 2,
1664
+ proto: 3,
1665
+ graphql: 4,
1666
+ postman: 5,
1667
+ insomnia: 6,
1668
+ bruno: 7,
1669
+ "http-file": 8
1670
+ };
1671
+ function isExistingMcpWorkspaceFile(rootDir, relPath, allowDir = false) {
1672
+ try {
1673
+ const st = fs.statSync(path.resolve(rootDir, relPath));
1674
+ return st.isFile() || (allowDir && st.isDirectory());
1675
+ }
1676
+ catch {
1677
+ return false;
1678
+ }
1679
+ }
1680
+ function buildMcpLockDiscoverHint(rootDir, report, explicitDomain, explicitTarget) {
1681
+ const entryFiles = [];
1682
+ const seen = new Set();
1683
+ const addFile = (rel) => {
1684
+ if (!rel || seen.has(rel) || entryFiles.length >= 25)
1685
+ return;
1686
+ seen.add(rel);
1687
+ entryFiles.push(rel);
1688
+ };
1689
+ for (const ep of report.entrypoints)
1690
+ addFile(ep.path);
1691
+ for (const sp of report.specs)
1692
+ addFile(sp.path);
1693
+ for (const mf of report.manifests)
1694
+ addFile(mf.path);
1695
+ const baseHint = {
1696
+ name: report.projectName,
1697
+ ...(entryFiles.length > 0 ? { entryFiles } : {})
1698
+ };
1699
+ const cliEntry = report.entrypoints.find((e) => e.kind === "cli" && typeof e.path === "string" && isExistingMcpWorkspaceFile(rootDir, e.path));
1700
+ const repoEntry = report.entrypoints.find((e) => e.kind === "repo" && typeof e.path === "string" && isExistingMcpWorkspaceFile(rootDir, e.path));
1701
+ const lockableSpecs = report.specs
1702
+ .filter((s) => {
1703
+ if (s.kind === "har")
1704
+ return false;
1705
+ if (!isExistingMcpWorkspaceFile(rootDir, s.path, s.kind === "bruno"))
1706
+ return false;
1707
+ try {
1708
+ validateMcpSource(rootDir, s.path, s.ingestDomain, "source");
1709
+ return true;
1710
+ }
1711
+ catch {
1712
+ return false;
1713
+ }
1714
+ })
1715
+ .sort((a, b) => {
1716
+ const aEx = MCP_EXAMPLE_SPEC_PATH_RE.test(a.path) ? 1 : 0;
1717
+ const bEx = MCP_EXAMPLE_SPEC_PATH_RE.test(b.path) ? 1 : 0;
1718
+ if (aEx !== bEx)
1719
+ return aEx - bEx;
1720
+ const pa = MCP_LOCK_SPEC_PRIORITY[a.kind] ?? 9;
1721
+ const pb = MCP_LOCK_SPEC_PRIORITY[b.kind] ?? 9;
1722
+ if (pa !== pb)
1723
+ return pa - pb;
1724
+ return a.path.localeCompare(b.path);
1725
+ });
1726
+ const primarySpec = lockableSpecs.find((s) => !MCP_EXAMPLE_SPEC_PATH_RE.test(s.path));
1727
+ const fallbackSpec = lockableSpecs[0];
1728
+ const isHttpTarget = typeof explicitTarget === "string" && isPureHttpUrlToken(explicitTarget);
1729
+ if (explicitDomain) {
1730
+ if (explicitDomain === "cli" || explicitDomain === "script") {
1731
+ if (cliEntry) {
1732
+ const cmd = cliEntry.command ?? `node ${cliEntry.path}`;
1733
+ return { ...baseHint, domain: explicitDomain, source: cmd, target: cmd };
1734
+ }
1735
+ return baseHint;
1736
+ }
1737
+ if (explicitDomain === "repo") {
1738
+ if (repoEntry) {
1739
+ return { ...baseHint, domain: "repo", source: rootDir, target: rootDir };
1740
+ }
1741
+ return baseHint;
1742
+ }
1743
+ if (explicitDomain === "api" ||
1744
+ explicitDomain === "graphql" ||
1745
+ explicitDomain === "postman" ||
1746
+ explicitDomain === "http-file" ||
1747
+ explicitDomain === "insomnia" ||
1748
+ explicitDomain === "bruno" ||
1749
+ explicitDomain === "asyncapi" ||
1750
+ explicitDomain === "proto" ||
1751
+ explicitDomain === "openrpc") {
1752
+ const matchedSpec = explicitDomain === "api"
1753
+ ? (primarySpec ?? fallbackSpec)
1754
+ : lockableSpecs.find((s) => s.ingestDomain === explicitDomain);
1755
+ if (matchedSpec) {
1756
+ return { ...baseHint, domain: matchedSpec.ingestDomain, source: path.resolve(rootDir, matchedSpec.path) };
1757
+ }
1758
+ return baseHint;
1759
+ }
1760
+ return baseHint;
1761
+ }
1762
+ if (isHttpTarget) {
1763
+ if (primarySpec) {
1764
+ return { ...baseHint, domain: primarySpec.ingestDomain, source: path.resolve(rootDir, primarySpec.path) };
1765
+ }
1766
+ return baseHint;
1767
+ }
1768
+ if (cliEntry) {
1769
+ const cmd = cliEntry.command ?? `node ${cliEntry.path}`;
1770
+ return { ...baseHint, domain: "cli", source: cmd, target: cmd };
1771
+ }
1772
+ if (primarySpec) {
1773
+ return { ...baseHint, domain: primarySpec.ingestDomain, source: path.resolve(rootDir, primarySpec.path) };
1774
+ }
1775
+ if (repoEntry) {
1776
+ return { ...baseHint, domain: "repo", source: rootDir, target: rootDir };
1777
+ }
1778
+ if (fallbackSpec) {
1779
+ return { ...baseHint, domain: fallbackSpec.ingestDomain, source: path.resolve(rootDir, fallbackSpec.path) };
1780
+ }
1781
+ return baseHint;
1782
+ }
1783
+ function redactMcpText(input) {
1784
+ const redacted = redactSensitiveTextWithOptions(input, { vaultToken: "[REDACTED_VAULT_PATH]" });
1785
+ return redacted.replace(/[^\s"'`<>()[\]{}]*\$\{?VIBECODE_VAULT_DIR\}?[^\s"'`<>()[\]{}]*/gi, "[REDACTED_VAULT_PATH]");
1786
+ }
1787
+ function redactMcpValue(value) {
1788
+ return redactDeepValue(value, {
1789
+ maxDepth: 12,
1790
+ redactText: redactMcpText,
1791
+ unwrapError: true,
1792
+ truncatedToken: "[Truncated]",
1793
+ circularToken: "[Circular]"
1794
+ });
1795
+ }
1796
+ function redactMcpDiagnostic(diag) {
1797
+ return {
1798
+ code: redactMcpText(diag.code),
1799
+ message: redactMcpText(diag.message),
1800
+ ...(diag.adapter !== undefined ? { adapter: redactMcpText(diag.adapter) } : {}),
1801
+ ...(diag.installHint !== undefined ? { installHint: redactMcpText(diag.installHint) } : {}),
1802
+ ...(diag.fallbackHint !== undefined ? { fallbackHint: redactMcpText(diag.fallbackHint) } : {}),
1803
+ ...(diag.details !== undefined ? { details: redactMcpValue(diag.details) } : {})
1804
+ };
1805
+ }
1806
+ function sanitizeHoldoutResultForMcp(result, holdoutInv) {
1807
+ const isHoldout = Boolean(holdoutInv) || isHoldoutResultRecord(result);
1808
+ if (!isHoldout)
1809
+ return result;
1810
+ if (result.status === "pass" || result.status === "skipped") {
1811
+ return {
1812
+ id: result.id,
1813
+ type: result.type,
1814
+ severity: result.severity,
1815
+ status: result.status,
1816
+ score: result.score,
1817
+ metrics: { redacted: true },
1818
+ ...(result.durationMs !== undefined ? { durationMs: result.durationMs } : {})
1819
+ };
1820
+ }
1821
+ const base = holdoutInv
1822
+ ? redactHoldoutResult({ ...holdoutInv, holdout: true }, result, false)
1823
+ : {
1824
+ id: result.id,
1825
+ type: result.type,
1826
+ severity: result.severity,
1827
+ status: result.status,
1828
+ score: result.status === "warn" ? result.score : 0,
1829
+ failures: result.metrics?.redacted === true &&
1830
+ Array.isArray(result.failures) &&
1831
+ typeof result.failures[0] === "string" &&
1832
+ result.failures[0].trim() &&
1833
+ !/\.vibecode-vault|holdouts?(?:-[a-f0-9]+)?\.json/i.test(result.failures[0])
1834
+ ? [redactMcpText(result.failures[0].trim())]
1835
+ : ["Holdout invariant failed (expected details redacted)"],
1836
+ metrics: {
1837
+ ...(result.metrics?.exitCode !== undefined ? { exitCode: result.metrics.exitCode } : {}),
1838
+ redacted: true
1839
+ },
1840
+ ...(result.durationMs !== undefined ? { durationMs: result.durationMs } : {})
1841
+ };
1842
+ const safeFailures = (base.failures || ["Holdout invariant failed (expected details redacted)"]).map((f) => {
1843
+ const cleaned = redactMcpText(f);
1844
+ return cleaned.includes("[REDACTED_VAULT_PATH]")
1845
+ ? "Holdout invariant failed (expected details redacted)"
1846
+ : cleaned;
1847
+ });
1848
+ return {
1849
+ id: base.id,
1850
+ type: base.type,
1851
+ severity: base.severity,
1852
+ status: base.status,
1853
+ score: base.score,
1854
+ failures: safeFailures,
1855
+ metrics: {
1856
+ ...(base.metrics?.exitCode !== undefined ? { exitCode: base.metrics.exitCode } : {}),
1857
+ redacted: true
1858
+ },
1859
+ ...(base.durationMs !== undefined ? { durationMs: base.durationMs } : {})
1860
+ };
1861
+ }
1862
+ function sanitizeVisibleResultForMcp(result) {
1863
+ const copy = {
1864
+ ...result,
1865
+ id: redactMcpText(result.id),
1866
+ type: redactMcpText(String(result.type))
1867
+ };
1868
+ if (Array.isArray(result.failures)) {
1869
+ copy.failures = result.failures.map((f) => redactMcpText(f));
1870
+ }
1871
+ if (typeof result.reason === "string") {
1872
+ copy.reason = redactMcpText(result.reason);
1873
+ }
1874
+ if (typeof result.repro === "string") {
1875
+ copy.repro = redactMcpText(result.repro);
1876
+ }
1877
+ if (result.diff !== undefined) {
1878
+ copy.diff = redactMcpValue(result.diff);
1879
+ }
1880
+ if (result.metrics !== undefined) {
1881
+ copy.metrics = redactMcpValue(result.metrics);
1882
+ }
1883
+ if (result.diagnostic) {
1884
+ copy.diagnostic = redactMcpDiagnostic(result.diagnostic);
1885
+ }
1886
+ return copy;
1887
+ }
1888
+ function sanitizeFixtureSummaryForMcp(summary) {
1889
+ return {
1890
+ ...summary,
1891
+ warnings: Array.isArray(summary.warnings) ? summary.warnings.map((w) => redactMcpText(w)) : [],
1892
+ records: Array.isArray(summary.records)
1893
+ ? summary.records.map((rec) => ({
1894
+ ...rec,
1895
+ target: redactMcpText(rec.target),
1896
+ ...(typeof rec.detail === "string" ? { detail: redactMcpText(rec.detail) } : {})
1897
+ }))
1898
+ : []
1899
+ };
1900
+ }
1901
+ function sanitizeReportForMcp(report, holdoutById) {
1902
+ return {
1903
+ ...report,
1904
+ ...(typeof report.timestamp === "string" ? { timestamp: redactMcpText(report.timestamp) } : {}),
1905
+ ...(report.gate
1906
+ ? {
1907
+ gate: {
1908
+ ...report.gate,
1909
+ reasons: Array.isArray(report.gate.reasons)
1910
+ ? report.gate.reasons.map((reason) => redactMcpText(reason))
1911
+ : report.gate.reasons
1912
+ }
1913
+ }
1914
+ : {}),
1915
+ ...(report.antiCheat
1916
+ ? {
1917
+ antiCheat: {
1918
+ ...report.antiCheat,
1919
+ reasons: Array.isArray(report.antiCheat.reasons)
1920
+ ? report.antiCheat.reasons.map((reason) => redactMcpText(reason))
1921
+ : report.antiCheat.reasons
1922
+ }
1923
+ }
1924
+ : {}),
1925
+ ...(report.fixtureSummary ? { fixtureSummary: sanitizeFixtureSummaryForMcp(report.fixtureSummary) } : {}),
1926
+ results: (report.results || []).map((r) => {
1927
+ const holdoutInv = holdoutById.get(r.id);
1928
+ const isHoldout = Boolean(holdoutInv) || isHoldoutResultRecord(r);
1929
+ return isHoldout ? sanitizeHoldoutResultForMcp(r, holdoutInv) : sanitizeVisibleResultForMcp(r);
1930
+ })
1931
+ };
1932
+ }
1933
+ function formatCompactDiffForPrompt(diff) {
1934
+ if (!diff || Object.keys(diff).length === 0)
1935
+ return undefined;
1936
+ const golden = diff.goldenStdout;
1937
+ const rawUnified = golden && typeof golden.unified === "string" && golden.unified.trim().length > 0
1938
+ ? golden.unified
1939
+ : typeof diff.unified === "string" && diff.unified.trim().length > 0
1940
+ ? diff.unified
1941
+ : undefined;
1942
+ let text;
1943
+ if (rawUnified) {
1944
+ text = redactMcpText(rawUnified);
1945
+ }
1946
+ else {
1947
+ try {
1948
+ const serialized = JSON.stringify(diff, null, 2);
1949
+ if (!serialized || serialized === "{}")
1950
+ return undefined;
1951
+ text = redactMcpText(serialized);
1952
+ }
1953
+ catch {
1954
+ return undefined;
1955
+ }
1956
+ }
1957
+ const normalized = text.replace(/\r\n?/g, "\n").trim();
1958
+ if (!normalized)
1959
+ return undefined;
1960
+ const truncated = normalized.length > MAX_PROMPT_DIFF_CHARS
1961
+ ? `${normalized.slice(0, MAX_PROMPT_DIFF_CHARS)}\n... [truncated]`
1962
+ : normalized;
1963
+ return truncated.replace(/`{3,}/g, (match) => match.split("").join(" "));
1964
+ }
1965
+ function sanitizeResult(result) {
1966
+ if (result.metrics?.redacted === true && "repro" in result) {
1967
+ const copy = { ...result };
1968
+ delete copy.repro;
1969
+ return copy;
1970
+ }
1971
+ return result;
1972
+ }
1973
+ function sanitizeHeadersRecord(headers) {
1974
+ if (!headers || typeof headers !== "object" || Array.isArray(headers))
1975
+ return headers;
1976
+ return redactHeaders(headers, "mask");
1977
+ }
1978
+ function sanitizeKeyedMaskRecord(raw, isMaskedKey) {
1979
+ if (!isPlainObjectSafe(raw))
1980
+ return raw;
1981
+ const out = {};
1982
+ for (const [rawKey, rawVal] of Object.entries(raw)) {
1983
+ const key = rawKey.trim();
1984
+ if (!key || isForbiddenObjectKey(key) || isForbiddenObjectKey(rawKey))
1985
+ continue;
1986
+ const safeKey = redactMcpText(key);
1987
+ if (isForbiddenObjectKey(safeKey))
1988
+ continue;
1989
+ defineOwnProp(out, safeKey, isMaskedKey(key) ? "[REDACTED]" : redactMcpValue(rawVal));
1990
+ }
1991
+ return out;
1992
+ }
1993
+ function sanitizeFixturesResource(rawFixtures) {
1994
+ if (!isPlainObjectSafe(rawFixtures))
1995
+ return rawFixtures;
1996
+ const copy = redactMcpValue(rawFixtures);
1997
+ for (const key of ["httpSetup", "httpTeardown"]) {
1998
+ if (Array.isArray(copy[key])) {
1999
+ copy[key] = copy[key].map((hook) => {
2000
+ if (!isPlainObjectSafe(hook))
2001
+ return hook;
2002
+ const h = { ...hook };
2003
+ if (h.headers)
2004
+ h.headers = sanitizeHeadersRecord(h.headers);
2005
+ return h;
2006
+ });
2007
+ }
2008
+ }
2009
+ for (const key of ["commandSetup", "commandTeardown"]) {
2010
+ if (Array.isArray(copy[key])) {
2011
+ copy[key] = copy[key].map((hook) => {
2012
+ if (!isPlainObjectSafe(hook))
2013
+ return hook;
2014
+ const h = { ...hook };
2015
+ if (h.env)
2016
+ h.env = sanitizeKeyedMaskRecord(h.env, isSensitiveKeyName);
2017
+ return h;
2018
+ });
2019
+ }
2020
+ }
2021
+ return copy;
2022
+ }
2023
+ function sanitizeContractResource(raw) {
2024
+ if (!isPlainObjectSafe(raw))
2025
+ return raw;
2026
+ if (!Array.isArray(raw.invariants))
2027
+ return redactMcpValue(raw);
2028
+ return {
2029
+ ...raw,
2030
+ ...(raw.target !== undefined ? { target: redactMcpValue(raw.target) } : {}),
2031
+ ...(raw.artifacts !== undefined ? { artifacts: redactMcpValue(raw.artifacts) } : {}),
2032
+ ...(raw.slices !== undefined ? { slices: redactMcpValue(raw.slices) } : {}),
2033
+ ...(raw.fixtures !== undefined ? { fixtures: sanitizeFixturesResource(raw.fixtures) } : {}),
2034
+ invariants: raw.invariants
2035
+ .filter((inv) => !(isPlainObjectSafe(inv) && (inv.holdout === true || isHoldoutResultRecord(inv))))
2036
+ .map((inv) => {
2037
+ if (!isPlainObjectSafe(inv))
2038
+ return redactMcpValue(inv);
2039
+ const item = redactMcpValue(inv);
2040
+ if (isPlainObjectSafe(inv.input)) {
2041
+ const inp = { ...item.input };
2042
+ if (inv.input.headers !== undefined)
2043
+ inp.headers = sanitizeHeadersRecord(inv.input.headers);
2044
+ if (inv.input.env !== undefined)
2045
+ inp.env = sanitizeKeyedMaskRecord(inv.input.env, isSensitiveKeyName);
2046
+ if (inv.input.query !== undefined) {
2047
+ inp.query = sanitizeKeyedMaskRecord(inv.input.query, (k) => isSensitiveQueryParamName(k) || isSensitiveKeyName(k));
2048
+ }
2049
+ item.input = inp;
2050
+ }
2051
+ if (isPlainObjectSafe(inv.expected)) {
2052
+ const exp = { ...item.expected };
2053
+ if (inv.expected.headers !== undefined)
2054
+ exp.headers = sanitizeHeadersRecord(inv.expected.headers);
2055
+ item.expected = exp;
2056
+ }
2057
+ return item;
2058
+ })
2059
+ };
2060
+ }
2061
+ function sanitizeImpactForMcp(impact) {
2062
+ return {
2063
+ ...impact,
2064
+ changedFiles: impact.changedFiles.map((f) => redactMcpText(f)),
2065
+ transitiveFiles: impact.transitiveFiles.map((f) => redactMcpText(f)),
2066
+ selectedInvariantIds: impact.selectedInvariantIds.map((id) => redactMcpText(id)),
2067
+ skippedInvariantIds: impact.skippedInvariantIds.map((id) => redactMcpText(id)),
2068
+ affectedSliceIds: impact.affectedSliceIds.map((id) => redactMcpText(id)),
2069
+ matches: impact.matches.map((m) => ({
2070
+ ...m,
2071
+ id: redactMcpText(m.id),
2072
+ files: m.files.map((f) => redactMcpText(f))
2073
+ }))
2074
+ };
2075
+ }
2076
+ function sanitizeMutationAuditForMcp(report) {
2077
+ return {
2078
+ ...report,
2079
+ hardeningBrief: redactMcpText(report.hardeningBrief),
2080
+ invariants: report.invariants.map((inv) => ({
2081
+ ...inv,
2082
+ id: redactMcpText(inv.id),
2083
+ type: redactMcpText(inv.type),
2084
+ risks: inv.risks.map((r) => ({
2085
+ ...r,
2086
+ ...(r.invariantId !== undefined ? { invariantId: redactMcpText(r.invariantId) } : {}),
2087
+ message: redactMcpText(r.message),
2088
+ mutantScenario: redactMcpText(r.mutantScenario),
2089
+ recommendation: redactMcpText(r.recommendation)
2090
+ }))
2091
+ })),
2092
+ contractRisks: report.contractRisks.map((r) => ({
2093
+ ...r,
2094
+ message: redactMcpText(r.message),
2095
+ mutantScenario: redactMcpText(r.mutantScenario),
2096
+ recommendation: redactMcpText(r.recommendation)
2097
+ })),
2098
+ topRisks: report.topRisks.map((r) => ({
2099
+ ...r,
2100
+ ...(r.invariantId !== undefined ? { invariantId: redactMcpText(r.invariantId) } : {}),
2101
+ message: redactMcpText(r.message),
2102
+ mutantScenario: redactMcpText(r.mutantScenario),
2103
+ recommendation: redactMcpText(r.recommendation)
2104
+ }))
2105
+ };
2106
+ }
2107
+ function resolveGitShortShaSafe(cwd) {
2108
+ try {
2109
+ const out = execFileSync("git", ["-c", "core.fsmonitor=false", "rev-parse", "--short=12", "HEAD"], {
2110
+ cwd,
2111
+ encoding: "utf8",
2112
+ stdio: ["ignore", "pipe", "ignore"],
2113
+ windowsHide: true,
2114
+ timeout: 2000,
2115
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0" }
2116
+ }).trim();
2117
+ return /^[0-9a-f]{4,40}$/i.test(out) ? out : undefined;
2118
+ }
2119
+ catch {
2120
+ return undefined;
2121
+ }
2122
+ }
2123
+ function sanitizeTrendsForMcp(report) {
2124
+ return {
2125
+ ...report,
2126
+ ...(report.latest
2127
+ ? {
2128
+ latest: {
2129
+ ...report.latest,
2130
+ timestamp: redactMcpText(report.latest.timestamp),
2131
+ ...(report.latest.gitSha !== undefined ? { gitSha: redactMcpText(report.latest.gitSha) } : {}),
2132
+ ...(report.latest.mode !== undefined ? { mode: redactMcpText(report.latest.mode) } : {}),
2133
+ visibleInvariants: report.latest.visibleInvariants.map((sample) => ({
2134
+ ...sample,
2135
+ id: redactMcpText(sample.id)
2136
+ }))
2137
+ }
2138
+ }
2139
+ : {}),
2140
+ latencyDrift: {
2141
+ ...report.latencyDrift,
2142
+ slowestInvariants: report.latencyDrift.slowestInvariants.map((item) => ({
2143
+ ...item,
2144
+ id: redactMcpText(item.id)
2145
+ }))
2146
+ },
2147
+ hotspots: report.hotspots.map((hotspot) => ({
2148
+ ...hotspot,
2149
+ id: redactMcpText(hotspot.id)
2150
+ })),
2151
+ summaryBrief: redactMcpText(report.summaryBrief)
2152
+ };
2153
+ }
134
2154
  function compactReport(report) {
135
2155
  return {
136
2156
  schemaVersion: report.schemaVersion,
@@ -143,6 +2163,8 @@ function compactReport(report) {
143
2163
  soft: report.soft,
144
2164
  gate: report.gate,
145
2165
  nextAction: report.nextAction,
2166
+ ...(report.antiCheat ? { antiCheat: report.antiCheat } : {}),
2167
+ ...(report.fixtureSummary?.applied ? { fixtureSummary: report.fixtureSummary } : {}),
146
2168
  results: (report.results || []).map((r) => ({
147
2169
  id: r.id,
148
2170
  type: r.type,
@@ -151,6 +2173,7 @@ function compactReport(report) {
151
2173
  score: r.score,
152
2174
  ...(Array.isArray(r.failures) && r.failures.length ? { failures: r.failures.slice(0, 5) } : {}),
153
2175
  ...(r.reason ? { reason: r.reason } : {}),
2176
+ ...(r.repro && r.metrics?.redacted !== true ? { repro: r.repro } : {}),
154
2177
  durationMs: r.durationMs
155
2178
  }))
156
2179
  };
@@ -164,7 +2187,27 @@ export function createMcpServer({ cwd = process.cwd(), stdin = process.stdin, st
164
2187
  const write = (message) => {
165
2188
  stdout.write(JSON.stringify(message) + "\n");
166
2189
  };
167
- async function statusPayload() {
2190
+ async function statusPayload(args = {}) {
2191
+ if (!args || typeof args !== "object" || Array.isArray(args)) {
2192
+ throw new VibecodeError("CONTRACT_INVALID", "vibecode_status arguments must be an object.");
2193
+ }
2194
+ const allowedKeys = new Set(["includeTrends", "trendWindow"]);
2195
+ for (const key of Object.getOwnPropertyNames(args)) {
2196
+ if (!allowedKeys.has(key)) {
2197
+ throw new VibecodeError("CONTRACT_INVALID", `Unexpected vibecode_status argument: ${redactMcpText(key)}`);
2198
+ }
2199
+ }
2200
+ const includeTrends = parseMcpBoolean(args.includeTrends, "includeTrends") === true;
2201
+ let trendWindow;
2202
+ if (args.trendWindow !== undefined) {
2203
+ if (typeof args.trendWindow !== "number" ||
2204
+ !Number.isInteger(args.trendWindow) ||
2205
+ args.trendWindow < 1 ||
2206
+ args.trendWindow > MAX_TREND_ENTRIES) {
2207
+ throw new VibecodeError("CONTRACT_INVALID", `trendWindow must be an integer between 1 and ${MAX_TREND_ENTRIES}.`);
2208
+ }
2209
+ trendWindow = args.trendWindow;
2210
+ }
168
2211
  let contract = null;
169
2212
  let contractError = null;
170
2213
  try {
@@ -172,84 +2215,333 @@ export function createMcpServer({ cwd = process.cwd(), stdin = process.stdin, st
172
2215
  }
173
2216
  catch (err) {
174
2217
  if (errorCode(err) !== "CONTRACT_NOT_FOUND")
175
- contractError = toDiagnostic(err);
2218
+ contractError = redactMcpDiagnostic(toDiagnostic(err));
176
2219
  }
177
2220
  const adapters = await (deps.probeAdapters || probeAdapters)();
178
2221
  const last = readLastReport(rootDir);
179
- const hard = contract ? contract.invariants.filter((i) => i.severity === "hard").length : 0;
180
- const soft = contract ? contract.invariants.filter((i) => i.severity === "soft").length : 0;
2222
+ const holdouts = contract ? readHoldouts(rootDir) : [];
2223
+ const allInvs = contract ? [...contract.invariants, ...holdouts] : [];
2224
+ const hard = allInvs.filter((i) => i.severity === "hard").length;
2225
+ const soft = allInvs.filter((i) => i.severity === "soft").length;
2226
+ const rawSlices = contract ? summarizeSlices(contract) : undefined;
2227
+ const safeSlices = rawSlices
2228
+ ? {
2229
+ ...rawSlices,
2230
+ ...(rawSlices.nextSlice ? { nextSlice: redactMcpText(rawSlices.nextSlice) } : {}),
2231
+ slices: rawSlices.slices.map((s) => ({
2232
+ ...s,
2233
+ id: redactMcpText(s.id),
2234
+ title: redactMcpText(s.title)
2235
+ }))
2236
+ }
2237
+ : undefined;
2238
+ let trends;
2239
+ if (includeTrends) {
2240
+ const holdoutIds = new Set(holdouts.map((h) => h.id));
2241
+ if (contract) {
2242
+ for (const inv of contract.invariants) {
2243
+ if (inv.holdout === true)
2244
+ holdoutIds.add(inv.id);
2245
+ }
2246
+ }
2247
+ const rawEntries = readTrendEntries(rootDir);
2248
+ const safeEntries = holdoutIds.size > 0
2249
+ ? rawEntries.map((entry) => ({
2250
+ ...entry,
2251
+ visibleInvariants: entry.visibleInvariants.filter((s) => !holdoutIds.has(s.id))
2252
+ }))
2253
+ : rawEntries;
2254
+ trends = sanitizeTrendsForMcp(analyzeTrends(safeEntries, trendWindow !== undefined ? { window: trendWindow } : undefined));
2255
+ }
181
2256
  return {
182
2257
  ok: true,
183
2258
  command: "status",
184
2259
  contract: contract
185
2260
  ? {
186
2261
  exists: true,
187
- schemaVersion: contract.schemaVersion,
188
- name: contract.target.name,
189
- domains: contract.target.domains,
190
- sources: contract.target.sources,
191
- invariants: contract.invariants.length,
2262
+ schemaVersion: redactMcpText(contract.schemaVersion),
2263
+ name: redactMcpText(contract.target.name),
2264
+ domains: contract.target.domains.map((d) => redactMcpText(String(d))),
2265
+ sources: redactMcpValue(contract.target.sources),
2266
+ invariants: allInvs.length,
2267
+ holdouts: holdouts.length,
192
2268
  hard,
193
2269
  soft,
194
2270
  thresholds: contract.thresholds,
195
- slices: summarizeSlices(contract)
2271
+ slices: safeSlices
196
2272
  }
197
- : { exists: false, ...(contractError ? { error: contractError } : {}) },
2273
+ : { exists: false, ...(contractError ? { error: redactMcpDiagnostic(contractError) } : {}) },
198
2274
  adapters,
199
2275
  lastReport: last
200
2276
  ? {
201
- timestamp: last.timestamp,
202
- gate: last.gate,
2277
+ timestamp: redactMcpText(last.timestamp),
2278
+ gate: {
2279
+ ...last.gate,
2280
+ reasons: Array.isArray(last.gate.reasons) ? last.gate.reasons.map((r) => redactMcpText(r)) : last.gate.reasons
2281
+ },
203
2282
  hard: last.hard,
204
2283
  soft: last.soft,
205
2284
  compositeScore: last.compositeScore,
206
2285
  parity: last.parity,
207
- nextAction: last.nextAction
2286
+ nextAction: typeof last.nextAction === "string" ? redactMcpText(last.nextAction) : last.nextAction
208
2287
  }
209
- : null
2288
+ : null,
2289
+ ...(trends ? { trends } : {})
210
2290
  };
211
2291
  }
212
2292
  async function toolIngest(args = {}) {
213
- const source = args.source;
214
- if (typeof source !== "string" || !source.trim()) {
215
- throw new VibecodeError("TARGET_MISSING", "vibecode_ingest requires a non-empty source");
2293
+ if (!isPlainObjectSafe(args)) {
2294
+ throw new VibecodeError("CONTRACT_INVALID", "vibecode_ingest arguments must be an object.");
2295
+ }
2296
+ for (const key of Object.getOwnPropertyNames(args)) {
2297
+ if (!ALLOWED_INGEST_KEYS.has(key)) {
2298
+ throw new VibecodeError("CONTRACT_INVALID", `Unexpected vibecode_ingest argument: ${redactMcpText(key)}`);
2299
+ }
2300
+ }
2301
+ if (args.source !== undefined && typeof args.source !== "string") {
2302
+ throw new VibecodeError("CONTRACT_INVALID", "vibecode_ingest source must be a string.");
2303
+ }
2304
+ if (args.domain !== undefined && typeof args.domain !== "string") {
2305
+ throw new VibecodeError("CONTRACT_INVALID", "vibecode_ingest domain must be a string.");
2306
+ }
2307
+ if (args.name !== undefined && typeof args.name !== "string") {
2308
+ throw new VibecodeError("CONTRACT_INVALID", "vibecode_ingest name must be a string.");
2309
+ }
2310
+ if (args.target !== undefined && typeof args.target !== "string") {
2311
+ throw new VibecodeError("CONTRACT_INVALID", "vibecode_ingest target must be a string.");
2312
+ }
2313
+ if (args.baseUrl !== undefined && typeof args.baseUrl !== "string") {
2314
+ throw new VibecodeError("CONTRACT_INVALID", "vibecode_ingest baseUrl must be a string.");
216
2315
  }
217
- const domain = typeof args.domain === "string" && args.domain.trim() ? args.domain.trim() : detectDomain(source);
2316
+ const rawSource = typeof args.source === "string" ? args.source.trim() : "";
2317
+ const fromCommands = args.fromCommands === undefined ? undefined : resolveMcpContainedInputFile(rootDir, args.fromCommands, "fromCommands");
2318
+ const fromHar = args.fromHar === undefined ? undefined : resolveMcpContainedInputFile(rootDir, args.fromHar, "fromHar");
2319
+ const fromTests = args.fromTests === undefined ? undefined : resolveMcpContainedInputPath(rootDir, args.fromTests, "fromTests");
2320
+ const multiImportCount = [fromCommands, fromHar, fromTests].filter(Boolean).length;
2321
+ if (multiImportCount > 1) {
2322
+ throw new VibecodeError("CONTRACT_INVALID", "Cannot combine fromCommands, fromHar, and fromTests in a single vibecode_ingest call.");
2323
+ }
2324
+ if (!rawSource && !fromCommands && !fromHar && !fromTests) {
2325
+ throw new VibecodeError("TARGET_MISSING", "vibecode_ingest requires source, fromCommands, fromHar, or fromTests");
2326
+ }
2327
+ const noSpec = parseMcpBoolean(args.noSpec, "noSpec") === true;
2328
+ const force = parseMcpBoolean(args.force, "force") === true;
2329
+ const explicitDomain = typeof args.domain === "string" && args.domain.trim() ? args.domain.trim() : undefined;
2330
+ const trimmedTarget = typeof args.target === "string" && args.target.trim() ? args.target.trim() : undefined;
2331
+ if (trimmedTarget) {
2332
+ assertNoVaultAccessInText(rootDir, trimmedTarget, "target");
2333
+ assertNotDisallowedUrlScheme(trimmedTarget, "target");
2334
+ }
2335
+ const baseUrl = typeof args.baseUrl === "string" && args.baseUrl.trim() ? args.baseUrl.trim() : undefined;
2336
+ if (baseUrl) {
2337
+ assertNoVaultAccessInText(rootDir, baseUrl, "baseUrl");
2338
+ assertNotDisallowedUrlScheme(baseUrl, "baseUrl");
2339
+ try {
2340
+ parseSafeHttpBaseUrl(baseUrl, { allowWs: explicitDomain === "api" });
2341
+ }
2342
+ catch (err) {
2343
+ throw new VibecodeError("CONTRACT_INVALID", `baseUrl: ${redactMcpText(errorMessage(err))}`);
2344
+ }
2345
+ }
2346
+ if (rawSource) {
2347
+ validateMcpSource(rootDir, rawSource, explicitDomain, "source");
2348
+ }
2349
+ if (fromTests) {
2350
+ const imported = await ingestFromTests(fromTests, {
2351
+ cwd: rootDir,
2352
+ ...(typeof args.name === "string" && args.name.trim() ? { name: args.name.trim() } : {}),
2353
+ ...(baseUrl ? { baseUrl } : {}),
2354
+ ...(trimmedTarget ? { target: trimmedTarget } : {}),
2355
+ force,
2356
+ noSpec
2357
+ });
2358
+ return {
2359
+ ok: true,
2360
+ command: "ingest",
2361
+ domain: imported.contract.target.domains[0] ?? "api",
2362
+ domains: imported.contract.target.domains,
2363
+ ...(imported.contractPath ? { contractPath: redactMcpText(imported.contractPath) } : {}),
2364
+ ...(imported.specPath ? { specPath: redactMcpText(imported.specPath) } : {}),
2365
+ invariants: imported.importedCount,
2366
+ visibleInvariants: imported.contract.invariants.length,
2367
+ holdouts: imported.holdoutCount,
2368
+ filesScanned: imported.filesScanned,
2369
+ frameworks: imported.frameworks,
2370
+ warnings: imported.warnings.map((w) => redactMcpText(w))
2371
+ };
2372
+ }
2373
+ const crop = parseMcpCrop(args.crop);
2374
+ const env = parseMcpStringRecord(args.env, "env");
2375
+ validateMcpEnv(rootDir, env);
2376
+ const fsDiff = parseMcpBoolean(args.fsDiff, "fsDiff");
2377
+ const headers = parseMcpStringRecord(args.headers, "headers");
2378
+ const storageState = args.storageState === undefined ? undefined : resolveMcpContainedInputFile(rootDir, args.storageState, "storageState");
2379
+ let crawlDepth;
2380
+ if (args.crawlDepth !== undefined) {
2381
+ if (typeof args.crawlDepth !== "number" ||
2382
+ !Number.isInteger(args.crawlDepth) ||
2383
+ args.crawlDepth < 1 ||
2384
+ args.crawlDepth > 3) {
2385
+ throw new VibecodeError("CONTRACT_INVALID", "crawlDepth must be an integer between 1 and 3");
2386
+ }
2387
+ crawlDepth = args.crawlDepth;
2388
+ }
2389
+ if (args.probes !== undefined && !Array.isArray(args.probes)) {
2390
+ throw new VibecodeError("CONTRACT_INVALID", "probes must be an array.");
2391
+ }
2392
+ if (args.routes !== undefined && !Array.isArray(args.routes)) {
2393
+ throw new VibecodeError("CONTRACT_INVALID", "routes must be an array.");
2394
+ }
2395
+ if (args.holdoutRoutes !== undefined && !Array.isArray(args.holdoutRoutes)) {
2396
+ throw new VibecodeError("CONTRACT_INVALID", "holdoutRoutes must be an array.");
2397
+ }
2398
+ if (args.flow !== undefined && !isPlainObjectSafe(args.flow)) {
2399
+ throw new VibecodeError("CONTRACT_INVALID", "flow must be an object.");
2400
+ }
2401
+ if (args.endpoints !== undefined && args.endpoints !== null && !Array.isArray(args.endpoints)) {
2402
+ throw new VibecodeError("CONTRACT_INVALID", "endpoints must be an array.");
2403
+ }
2404
+ const holdoutRoutes = Array.isArray(args.holdoutRoutes)
2405
+ ? args.holdoutRoutes.filter((r) => typeof r === "string")
2406
+ : [];
2407
+ for (let i = 0; i < holdoutRoutes.length; i++) {
2408
+ assertNoVaultAccessInText(rootDir, holdoutRoutes[i], `holdoutRoutes[${i}]`);
2409
+ assertNotDisallowedUrlScheme(holdoutRoutes[i], `holdoutRoutes[${i}]`);
2410
+ }
2411
+ if (fromCommands) {
2412
+ validateMcpCommandsFileContent(rootDir, fromCommands);
2413
+ }
2414
+ validateMcpProbes(rootDir, args.probes);
2415
+ if (!Boolean(args.force) && fs.existsSync(resolveWorkspace(rootDir).contractPath)) {
2416
+ throw new VibecodeError("CONTRACT_INVALID", `Contract already exists at ${CONTRACT_FILE}. Use --force to overwrite.`);
2417
+ }
2418
+ const effectiveSource = rawSource || fromCommands || fromHar || "";
218
2419
  const name = typeof args.name === "string" && args.name.trim() ? args.name.trim() : path.basename(rootDir);
219
2420
  const result = await ingest({
220
- domain,
221
- source,
2421
+ ...(explicitDomain ? { domain: explicitDomain } : (!fromCommands && !fromHar ? { domain: detectDomainInWorkspace(rootDir, rawSource) } : {})),
2422
+ ...(rawSource ? { source: rawSource } : {}),
222
2423
  name,
223
2424
  probes: Array.isArray(args.probes) ? args.probes : [],
224
2425
  routes: Array.isArray(args.routes) ? args.routes : [],
225
- flow: args.flow !== null && typeof args.flow === "object" && !Array.isArray(args.flow) ? args.flow : undefined,
2426
+ flow: isPlainObjectSafe(args.flow) ? args.flow : undefined,
226
2427
  endpoints: Array.isArray(args.endpoints) && args.endpoints.length ? args.endpoints : null,
227
2428
  baseUrl: typeof args.baseUrl === "string" ? args.baseUrl : undefined,
228
2429
  sceneThreshold: typeof args.sceneThreshold === "number" ? args.sceneThreshold : undefined,
229
2430
  maxFrames: typeof args.maxFrames === "number" ? args.maxFrames : undefined,
2431
+ noSpec,
2432
+ ...(crawlDepth !== undefined ? { crawlDepth } : {}),
2433
+ ...(holdoutRoutes.length > 0 ? { holdoutRoutes } : {}),
2434
+ ...(crop !== undefined ? { crop } : {}),
2435
+ ...(env !== undefined ? { env } : {}),
2436
+ ...(fsDiff !== undefined ? { fsDiff } : {}),
2437
+ ...(headers !== undefined ? { headers } : {}),
2438
+ ...(storageState !== undefined ? { storageState } : {}),
2439
+ ...(fromCommands !== undefined ? { fromCommands } : {}),
2440
+ ...(fromHar !== undefined ? { fromHar } : {}),
230
2441
  cwd: rootDir
231
2442
  }, deps.ingestDeps || {});
232
- const contract = makeDefaultContract({ name, domain: result.domain, source });
2443
+ const contract = makeDefaultContract({ name, domain: result.domain, source: effectiveSource });
233
2444
  const invDomains = (result.invariants || []).map((i) => i.domain).filter((d) => VALID_DOMAINS.has(d));
234
2445
  contract.target.domains = [...new Set([result.domain, ...invDomains].filter((d) => VALID_DOMAINS.has(d)))];
235
2446
  contract.target.sources = result.sources;
236
2447
  contract.artifacts = result.artifacts;
237
2448
  contract.invariants = result.invariants;
238
- const contractPath = writeContract(contract, rootDir, { force: Boolean(args.force) });
2449
+ const contractPath = writeContract(contract, rootDir, { force: Boolean(args.force), replaceHoldouts: true });
2450
+ const holdoutCount = (result.invariants || []).filter((i) => i.holdout === true).length;
2451
+ const specPath = noSpec ? undefined : writeSpecFile(rootDir, { contract, holdoutCount });
239
2452
  return {
240
2453
  ok: true,
241
2454
  command: "ingest",
242
2455
  domain: result.domain,
243
- contractPath,
2456
+ contractPath: redactMcpText(contractPath),
2457
+ ...(specPath ? { specPath: redactMcpText(specPath) } : {}),
244
2458
  invariants: result.invariants.length,
245
- warnings: result.warnings
2459
+ holdouts: holdoutCount,
2460
+ warnings: (result.warnings || []).map((w) => (typeof w === "string" ? redactMcpText(w) : redactMcpDiagnostic(w)))
246
2461
  };
247
2462
  }
248
2463
  async function toolVerify(args = {}) {
249
- const target = args.target;
250
- if (typeof target !== "string" || !target.trim()) {
2464
+ if (!isPlainObjectSafe(args)) {
2465
+ throw new VibecodeError("CONFIG_INVALID", "vibecode_verify arguments must be an object.");
2466
+ }
2467
+ if (Object.prototype.hasOwnProperty.call(args, "plugin") ||
2468
+ Object.prototype.hasOwnProperty.call(args, "plugins") ||
2469
+ Object.prototype.hasOwnProperty.call(args, "pluginRegistry")) {
2470
+ throw new VibecodeError("CONFIG_INVALID", "Custom local plugin loading is CLI-only and not permitted over MCP; built-in plugins run automatically.");
2471
+ }
2472
+ if (Object.prototype.hasOwnProperty.call(args, "allowFixtureCommands") ||
2473
+ Object.prototype.hasOwnProperty.call(args, "allowCommandHooks")) {
2474
+ throw new VibecodeError("CONFIG_INVALID", "Fixture command hooks are CLI-only (--allow-fixture-commands) and not permitted over MCP.");
2475
+ }
2476
+ for (const key of Object.getOwnPropertyNames(args)) {
2477
+ if (!ALLOWED_VERIFY_KEYS.has(key)) {
2478
+ throw new VibecodeError("CONFIG_INVALID", `Unexpected vibecode_verify argument: ${redactMcpText(key)}`);
2479
+ }
2480
+ }
2481
+ const rawTargets = args.targets !== undefined ? validateTargetMapObject(args.targets) : undefined;
2482
+ const targets = rawTargets && Object.keys(rawTargets).length > 0 ? rawTargets : undefined;
2483
+ if (targets) {
2484
+ for (const [domain, mappedTarget] of Object.entries(targets)) {
2485
+ if (typeof mappedTarget === "string") {
2486
+ validateMcpTargetForDomain(rootDir, domain, mappedTarget, `targets.${domain}`);
2487
+ }
2488
+ }
2489
+ }
2490
+ const rawVars = args.vars !== undefined ? validateRuntimeVarsObject(args.vars) : undefined;
2491
+ const vars = rawVars && Object.keys(rawVars).length > 0 ? rawVars : undefined;
2492
+ if (vars) {
2493
+ for (const [k, v] of Object.entries(vars)) {
2494
+ if (k.toUpperCase() === "VIBECODE_VAULT_DIR") {
2495
+ throw new VibecodeError("CONTRACT_INVALID", "vars cannot override VIBECODE_VAULT_DIR.");
2496
+ }
2497
+ assertNoVaultAccessInText(rootDir, v, `vars.${k}`);
2498
+ }
2499
+ }
2500
+ if (!vars)
2501
+ return toolVerifyWithRuntime(args, targets);
2502
+ try {
2503
+ return redactRuntimeVarsDeep(await toolVerifyWithRuntime(args, targets, vars), vars);
2504
+ }
2505
+ catch (err) {
2506
+ throw new VibecodeError(errorCode(err) ?? "INTERNAL_ERROR", redactMcpText(redactRuntimeVars(errorMessage(err), vars)));
2507
+ }
2508
+ }
2509
+ async function toolVerifyWithRuntime(args, targets, vars) {
2510
+ const rawTarget = args.target;
2511
+ if (rawTarget !== undefined && typeof rawTarget !== "string") {
251
2512
  throw new VibecodeError("TARGET_MISSING", "vibecode_verify requires a target command or URL");
252
2513
  }
2514
+ const target = typeof rawTarget === "string" && rawTarget.trim() ? rawTarget : "";
2515
+ if (!target && !targets) {
2516
+ throw new VibecodeError("TARGET_MISSING", "vibecode_verify requires a target command or URL (or a targets domain map)");
2517
+ }
2518
+ const trimmedTarget = target.trim();
2519
+ if (trimmedTarget) {
2520
+ assertNoVaultAccessInText(rootDir, trimmedTarget, "target");
2521
+ assertNotDisallowedUrlScheme(trimmedTarget, "target");
2522
+ }
2523
+ const headers = parseMcpStringRecord(args.headers, "headers");
2524
+ const storageState = args.storageState === undefined ? undefined : resolveMcpContainedInputFile(rootDir, args.storageState, "storageState");
2525
+ let mode;
2526
+ if (args.mode !== undefined) {
2527
+ if (typeof args.mode !== "string" || !VALID_VERIFY_MODES.has(args.mode.trim())) {
2528
+ throw new VibecodeError("CONFIG_INVALID", `Invalid verify mode: ${redactMcpText(String(args.mode))} (expected one of ${[...VALID_VERIFY_MODES].join(", ")})`);
2529
+ }
2530
+ mode = args.mode.trim();
2531
+ }
2532
+ let concurrency;
2533
+ if (args.concurrency !== undefined) {
2534
+ if (args.concurrency === null) {
2535
+ throw new VibecodeError("CONFIG_INVALID", "Invalid verify concurrency null: expected an integer between 1 and 8.");
2536
+ }
2537
+ concurrency = normalizeConcurrency(args.concurrency);
2538
+ }
2539
+ const strict = Boolean(args.strict);
2540
+ const affected = parseMcpBoolean(args.affected, "affected") === true;
2541
+ const useCache = parseMcpBoolean(args.useCache, "useCache") === true;
2542
+ const cacheBypassedReason = useCache && vars ? "runtime_vars_present" : undefined;
2543
+ const noReport = parseMcpBoolean(args.noReport, "noReport") === true;
2544
+ const skipFixtures = parseMcpBoolean(args.skipFixtures, "skipFixtures") === true;
253
2545
  const contract = readContract(rootDir);
254
2546
  const { artifactsDir, cacheDir } = resolveWorkspace(rootDir);
255
2547
  const sliceArgs = Array.isArray(args.sliceIds) ? args.sliceIds.map(String).filter(Boolean) : [];
@@ -273,36 +2565,479 @@ export function createMcpServer({ cwd = process.cwd(), stdin = process.stdin, st
273
2565
  invariantIds.push(id);
274
2566
  }
275
2567
  }
2568
+ const holdouts = readHoldouts(rootDir);
2569
+ const holdoutIds = new Set([...holdouts, ...contract.invariants.filter((i) => i.holdout === true)].map((i) => i.id));
2570
+ let impact;
2571
+ let effectiveInvariantIds = invariantIds;
2572
+ if (affected) {
2573
+ const safeContractForImpact = {
2574
+ ...contract,
2575
+ invariants: contract.invariants.filter((inv) => inv.holdout !== true)
2576
+ };
2577
+ const changedFiles = getGitChangedFiles(rootDir);
2578
+ const lastReport = readLastReport(rootDir);
2579
+ const failedIdsFromLastReport = (lastReport?.results ?? [])
2580
+ .filter((r) => r.status !== "pass" && r.status !== "skipped" && !holdoutIds.has(r.id))
2581
+ .map((r) => r.id);
2582
+ const rawImpact = analyzeImpact(safeContractForImpact, changedFiles, {
2583
+ cwd: rootDir,
2584
+ previousFailedIds: failedIdsFromLastReport,
2585
+ selectAllOnEmpty: false
2586
+ });
2587
+ impact = sanitizeImpactForMcp(rawImpact);
2588
+ if (!rawImpact.fallbackToFull) {
2589
+ if (invariantIds.length > 0) {
2590
+ const impactedSet = new Set(rawImpact.selectedInvariantIds);
2591
+ effectiveInvariantIds = invariantIds.filter((id) => impactedSet.has(id));
2592
+ }
2593
+ else {
2594
+ effectiveInvariantIds = [...rawImpact.selectedInvariantIds];
2595
+ }
2596
+ if (effectiveInvariantIds.length === 0) {
2597
+ const noImpactReport = {
2598
+ schemaVersion: contract.schemaVersion || SCHEMA_VERSION,
2599
+ timestamp: new Date().toISOString(),
2600
+ passed: 0,
2601
+ total: 0,
2602
+ parity: 1.0,
2603
+ compositeScore: 1.0,
2604
+ hard: { passed: 0, failed: 0, skipped: 0, evaluated: 0, total: 0, parity: 1.0 },
2605
+ soft: { passed: 0, warned: 0, failed: 0, skipped: 0, evaluated: 0, total: 0, meanScore: 1.0, parity: 1.0 },
2606
+ gate: {
2607
+ passed: true,
2608
+ status: "pass",
2609
+ exitCode: 0,
2610
+ reasons: ["No impacted invariants to re-run"]
2611
+ },
2612
+ nextAction: "none",
2613
+ results: []
2614
+ };
2615
+ return {
2616
+ ...compactReport(noImpactReport),
2617
+ ...(cacheBypassedReason ? { cacheBypassedReason } : {}),
2618
+ note: "No impacted invariants to re-run",
2619
+ impact
2620
+ };
2621
+ }
2622
+ }
2623
+ }
2624
+ if (trimmedTarget) {
2625
+ const targetDomains = collectTargetConsumingDomains(rootDir, contract, {
2626
+ invariantIds: effectiveInvariantIds,
2627
+ ...(mode ? { mode } : {})
2628
+ });
2629
+ validateMcpFallbackTargetForContract(rootDir, trimmedTarget, targetDomains, "target", targets);
2630
+ }
2631
+ const verifyStartedAt = Date.now();
276
2632
  const report = await verifyContract(contract, {
277
2633
  target,
2634
+ ...(targets ? { targets } : {}),
2635
+ ...(vars ? { vars } : {}),
278
2636
  cwd: rootDir,
279
2637
  contract,
280
2638
  artifactsDir,
281
2639
  cacheDir,
282
- strict: Boolean(args.strict),
283
- invariantIds,
2640
+ strict,
2641
+ ...(mode ? { mode } : {}),
2642
+ ...(concurrency !== undefined ? { concurrency } : {}),
2643
+ revealHoldouts: false,
2644
+ ...(useCache ? { useCache: true } : {}),
2645
+ invariantIds: effectiveInvariantIds,
2646
+ ...(headers !== undefined ? { headers } : {}),
2647
+ ...(storageState !== undefined ? { storageState } : {}),
2648
+ ...(skipFixtures ? { skipFixtures: true } : {}),
2649
+ allowFixtureCommands: false,
284
2650
  runtimeCache: {}
285
2651
  }, deps.verifyDeps || {});
286
- writeLastReport(report, rootDir);
2652
+ const totalDurationMs = Math.max(0, Date.now() - verifyStartedAt);
2653
+ const quote = (v) => (v.includes('"') && !v.includes("'") ? `'${v}'` : `"${v.replace(/"/g, '\\"')}"`);
2654
+ const reproPrefix = [
2655
+ "vibecode-anything verify",
2656
+ ...(target ? [`--target ${quote(target)}`] : []),
2657
+ ...Object.entries(targets ?? {}).map(([d, t]) => `--target-map ${quote(`${d}=${String(t)}`)}`)
2658
+ ].join(" ");
2659
+ const varFlags = Object.keys(vars ?? {}).map((name) => ` --var ${name}=<REDACTED>`).join("");
2660
+ const strictSuffix = strict ? " --strict" : "";
2661
+ const modeSuffix = mode && mode !== "exact" ? ` --mode ${mode}` : "";
2662
+ for (const r of report.results || []) {
2663
+ if ((r.status === "fail" || r.status === "error") && !holdoutIds.has(r.id) && r.metrics?.redacted !== true) {
2664
+ const repro = `${reproPrefix} --invariant ${r.id}${strictSuffix}${modeSuffix}`;
2665
+ r.repro = (vars ? redactRuntimeVars(repro, vars) : redactMcpText(repro)) + varFlags;
2666
+ }
2667
+ }
2668
+ const holdoutById = new Map();
2669
+ for (const h of holdouts)
2670
+ holdoutById.set(h.id, h);
2671
+ for (const inv of contract.invariants) {
2672
+ if (inv.holdout === true && !holdoutById.has(inv.id))
2673
+ holdoutById.set(inv.id, inv);
2674
+ }
2675
+ const safeReport = sanitizeReportForMcp(report, holdoutById);
2676
+ writeLastReport(safeReport, rootDir);
2677
+ if (!noReport) {
2678
+ try {
2679
+ const gitSha = resolveGitShortShaSafe(rootDir);
2680
+ const trendInput = vars ? redactRuntimeVarsDeep(safeReport, vars) : safeReport;
2681
+ appendTrendEntry(rootDir, trendInput, {
2682
+ ...(gitSha ? { gitSha } : {}),
2683
+ ...(mode ? { mode } : {}),
2684
+ ...(affected ? { affected: true } : {}),
2685
+ totalDurationMs
2686
+ });
2687
+ }
2688
+ catch {
2689
+ // Best-effort: trend persistence is non-fatal on read-only workspaces or confined symlink errors.
2690
+ }
2691
+ }
2692
+ let contractForReport = contract;
2693
+ let sliceSummary;
287
2694
  if (resolvedSliceIds.length > 0 || (Array.isArray(contract.slices) && contract.slices.length > 0)) {
288
- const updated = updateSliceProgress(contract, report, resolvedSliceIds.length > 0 ? { sliceIds: resolvedSliceIds } : {});
289
- writeContract(updated, rootDir, { force: true });
290
- return { ...compactReport(report), slices: summarizeSlices(updated) };
2695
+ const updated = updateSliceProgress(contract, safeReport, resolvedSliceIds.length > 0 ? { sliceIds: resolvedSliceIds } : {});
2696
+ writeContract(updated, rootDir, { force: true, preserveHoldouts: true });
2697
+ contractForReport = updated;
2698
+ sliceSummary = summarizeSlices(updated);
291
2699
  }
292
- return compactReport(report);
2700
+ const mergedForHtml = holdouts.length > 0
2701
+ ? {
2702
+ ...contractForReport,
2703
+ invariants: [
2704
+ ...contractForReport.invariants,
2705
+ ...holdouts.filter((h) => !contractForReport.invariants.some((v) => v.id === h.id))
2706
+ ]
2707
+ }
2708
+ : contractForReport;
2709
+ const reportHtmlPath = noReport
2710
+ ? undefined
2711
+ : writeHtmlReport(rootDir, {
2712
+ contract: mergedForHtml,
2713
+ report: safeReport,
2714
+ history: readRunHistory(rootDir),
2715
+ workspaceDir: rootDir
2716
+ });
2717
+ return {
2718
+ ...compactReport(safeReport),
2719
+ ...(cacheBypassedReason ? { cacheBypassedReason } : {}),
2720
+ ...(impact ? { impact } : {}),
2721
+ ...(sliceSummary ? { slices: sliceSummary } : {}),
2722
+ ...(reportHtmlPath ? { reportHtmlPath: redactMcpText(reportHtmlPath) } : {})
2723
+ };
293
2724
  }
294
2725
  async function toolDoctor(args = {}) {
2726
+ if (!isPlainObjectSafe(args)) {
2727
+ throw new VibecodeError("CONTRACT_INVALID", "vibecode_doctor arguments must be an object.");
2728
+ }
2729
+ for (const key of Object.getOwnPropertyNames(args)) {
2730
+ if (!ALLOWED_DOCTOR_KEYS.has(key)) {
2731
+ throw new VibecodeError("CONTRACT_INVALID", `Unexpected vibecode_doctor argument: ${redactMcpText(key)}`);
2732
+ }
2733
+ }
2734
+ let scope = "project";
2735
+ if (args.scope !== undefined) {
2736
+ if (args.scope !== "project" && args.scope !== "global") {
2737
+ throw new VibecodeError("CONTRACT_INVALID", 'scope must be "project" or "global".');
2738
+ }
2739
+ scope = args.scope;
2740
+ }
2741
+ const strict = parseMcpBoolean(args.strict, "strict") === true;
2742
+ let antigravityDir;
2743
+ if (args.antigravityDir !== undefined) {
2744
+ if (typeof args.antigravityDir !== "string") {
2745
+ throw new VibecodeError("CONTRACT_INVALID", "antigravityDir must be a string.");
2746
+ }
2747
+ const trimmed = args.antigravityDir.trim();
2748
+ if (trimmed) {
2749
+ assertNoVaultAccessInText(rootDir, trimmed, "antigravityDir");
2750
+ antigravityDir = trimmed;
2751
+ }
2752
+ }
295
2753
  return runDoctor({
296
2754
  cwd: rootDir,
297
- scope: typeof args.scope === "string" ? args.scope : "project",
298
- ...(typeof args.antigravityDir === "string" ? { antigravityDir: args.antigravityDir } : {}),
299
- strict: Boolean(args.strict)
2755
+ scope,
2756
+ ...(antigravityDir ? { antigravityDir } : {}),
2757
+ strict
300
2758
  });
301
2759
  }
2760
+ function toolDiscover(args = {}) {
2761
+ if (!args || typeof args !== "object" || Array.isArray(args)) {
2762
+ throw new VibecodeError("CONTRACT_INVALID", "vibecode_discover arguments must be an object.");
2763
+ }
2764
+ const allowedKeys = new Set(["dir", "maxDepth", "maxFiles"]);
2765
+ for (const key of Object.getOwnPropertyNames(args)) {
2766
+ if (!allowedKeys.has(key)) {
2767
+ throw new VibecodeError("CONTRACT_INVALID", `Unexpected vibecode_discover argument: ${redactMcpText(key)}`);
2768
+ }
2769
+ }
2770
+ const targetDir = resolveMcpContainedDir(rootDir, args.dir, "dir");
2771
+ let maxDepth;
2772
+ if (args.maxDepth !== undefined) {
2773
+ if (typeof args.maxDepth !== "number" || !Number.isInteger(args.maxDepth) || args.maxDepth < 0 || args.maxDepth > 12) {
2774
+ throw new VibecodeError("CONTRACT_INVALID", "maxDepth must be an integer between 0 and 12.");
2775
+ }
2776
+ maxDepth = args.maxDepth;
2777
+ }
2778
+ let maxFiles;
2779
+ if (args.maxFiles !== undefined) {
2780
+ if (typeof args.maxFiles !== "number" || !Number.isInteger(args.maxFiles) || args.maxFiles < 1 || args.maxFiles > 2000) {
2781
+ throw new VibecodeError("CONTRACT_INVALID", "maxFiles must be an integer between 1 and 2000.");
2782
+ }
2783
+ maxFiles = args.maxFiles;
2784
+ }
2785
+ const report = discoverProject(targetDir, {
2786
+ ...(maxDepth !== undefined ? { maxDepth } : {}),
2787
+ ...(maxFiles !== undefined ? { maxFiles } : {})
2788
+ });
2789
+ return {
2790
+ ...report,
2791
+ tool: "vibecode_discover",
2792
+ warnings: report.warnings.map((w) => redactMcpText(w))
2793
+ };
2794
+ }
2795
+ async function toolLock(args = {}) {
2796
+ if (!args || typeof args !== "object" || Array.isArray(args)) {
2797
+ throw new VibecodeError("CONTRACT_INVALID", "vibecode_lock arguments must be an object.");
2798
+ }
2799
+ const allowedKeys = new Set([
2800
+ "check",
2801
+ "source",
2802
+ "domain",
2803
+ "target",
2804
+ "name",
2805
+ "force",
2806
+ "strict",
2807
+ "noSpec",
2808
+ "noVerify",
2809
+ "probes",
2810
+ "routes",
2811
+ "endpoints",
2812
+ "baseUrl",
2813
+ "headers",
2814
+ "storageState",
2815
+ "fsDiff",
2816
+ "crawlDepth",
2817
+ "holdoutRoutes"
2818
+ ]);
2819
+ for (const key of Object.getOwnPropertyNames(args)) {
2820
+ if (!allowedKeys.has(key)) {
2821
+ throw new VibecodeError("CONTRACT_INVALID", `Unexpected vibecode_lock argument: ${redactMcpText(key)}`);
2822
+ }
2823
+ }
2824
+ const check = parseMcpBoolean(args.check, "check") === true;
2825
+ if (check) {
2826
+ const status = checkLockStatus(rootDir);
2827
+ return {
2828
+ ok: status.exists && status.valid && !status.contractTampered,
2829
+ tool: "vibecode_lock",
2830
+ mode: "check",
2831
+ ...status,
2832
+ issues: status.issues.map((item) => redactMcpText(item))
2833
+ };
2834
+ }
2835
+ const parseOptStr = (key) => {
2836
+ const val = args[key];
2837
+ if (val === undefined)
2838
+ return undefined;
2839
+ if (typeof val !== "string" || !val.trim()) {
2840
+ throw new VibecodeError("CONTRACT_INVALID", `vibecode_lock ${key} must be a non-empty string.`);
2841
+ }
2842
+ return val.trim();
2843
+ };
2844
+ const source = parseOptStr("source");
2845
+ const domain = parseOptStr("domain");
2846
+ const target = parseOptStr("target");
2847
+ const name = parseOptStr("name");
2848
+ const baseUrl = parseOptStr("baseUrl");
2849
+ if (baseUrl) {
2850
+ assertNoVaultAccessInText(rootDir, baseUrl, "baseUrl");
2851
+ assertNotDisallowedUrlScheme(baseUrl, "baseUrl");
2852
+ try {
2853
+ parseSafeHttpBaseUrl(baseUrl, { allowWs: domain?.toLowerCase() === "api" });
2854
+ }
2855
+ catch (err) {
2856
+ throw new VibecodeError("CONTRACT_INVALID", `baseUrl: ${redactMcpText(errorMessage(err))}`);
2857
+ }
2858
+ }
2859
+ const force = parseMcpBoolean(args.force, "force") === true;
2860
+ const strict = parseMcpBoolean(args.strict, "strict") === true;
2861
+ const noSpec = parseMcpBoolean(args.noSpec, "noSpec") === true;
2862
+ const noVerify = parseMcpBoolean(args.noVerify, "noVerify") === true;
2863
+ const fsDiff = parseMcpBoolean(args.fsDiff, "fsDiff") === true;
2864
+ const headers = parseMcpStringRecord(args.headers, "headers");
2865
+ const storageState = args.storageState === undefined ? undefined : resolveMcpContainedInputFile(rootDir, args.storageState, "storageState");
2866
+ let crawlDepth;
2867
+ if (args.crawlDepth !== undefined) {
2868
+ if (typeof args.crawlDepth !== "number" ||
2869
+ !Number.isInteger(args.crawlDepth) ||
2870
+ args.crawlDepth < 1 ||
2871
+ args.crawlDepth > 3) {
2872
+ throw new VibecodeError("CONTRACT_INVALID", "crawlDepth must be an integer between 1 and 3");
2873
+ }
2874
+ crawlDepth = args.crawlDepth;
2875
+ }
2876
+ if (args.probes !== undefined && !Array.isArray(args.probes)) {
2877
+ throw new VibecodeError("CONTRACT_INVALID", "probes must be an array.");
2878
+ }
2879
+ if (args.routes !== undefined && !Array.isArray(args.routes)) {
2880
+ throw new VibecodeError("CONTRACT_INVALID", "routes must be an array.");
2881
+ }
2882
+ if (args.endpoints !== undefined && args.endpoints !== null && !Array.isArray(args.endpoints)) {
2883
+ throw new VibecodeError("CONTRACT_INVALID", "endpoints must be an array.");
2884
+ }
2885
+ if (args.holdoutRoutes !== undefined && !Array.isArray(args.holdoutRoutes)) {
2886
+ throw new VibecodeError("CONTRACT_INVALID", "holdoutRoutes must be an array of strings.");
2887
+ }
2888
+ if (source) {
2889
+ validateMcpSource(rootDir, source, domain, "source");
2890
+ }
2891
+ if (target) {
2892
+ assertNoVaultAccessInText(rootDir, target, "target");
2893
+ assertNotDisallowedUrlScheme(target, "target");
2894
+ }
2895
+ validateMcpProbes(rootDir, args.probes);
2896
+ const holdoutRoutes = Array.isArray(args.holdoutRoutes)
2897
+ ? args.holdoutRoutes.filter((r) => typeof r === "string")
2898
+ : [];
2899
+ let discoverHint;
2900
+ if (!source) {
2901
+ const discovered = discoverProject(rootDir);
2902
+ discoverHint = buildMcpLockDiscoverHint(rootDir, discovered, domain, target);
2903
+ }
2904
+ const effectiveDomain = (domain ??
2905
+ (source
2906
+ ? detectDomainInWorkspace(rootDir, source)
2907
+ : discoverHint?.domain ??
2908
+ (() => {
2909
+ try {
2910
+ return autoInferLockTarget(rootDir, {
2911
+ ...(domain ? { domain } : {}),
2912
+ ...(target ? { target } : {}),
2913
+ ...(discoverHint ? { discoverHint } : {})
2914
+ }).domain;
2915
+ }
2916
+ catch {
2917
+ return undefined;
2918
+ }
2919
+ })()))?.toLowerCase();
2920
+ if (target) {
2921
+ if (effectiveDomain === "repo") {
2922
+ resolveMcpContainedDir(rootDir, target, "target");
2923
+ }
2924
+ else if (effectiveDomain && STRICT_PATH_DOMAINS.has(effectiveDomain) && !isPureHttpUrlToken(target)) {
2925
+ if (/^file:\/\//i.test(target)) {
2926
+ throw new VibecodeError("CONTRACT_INVALID", `target cannot use file:// URLs: ${redactMcpText(target)}`);
2927
+ }
2928
+ assertMcpPathContainedInWorkspace(rootDir, target, "target");
2929
+ }
2930
+ }
2931
+ const lockOptions = {
2932
+ cwd: rootDir,
2933
+ ...(source ? { source } : {}),
2934
+ ...(domain ? { domain } : {}),
2935
+ ...(target ? { target } : {}),
2936
+ ...(name ? { name } : {}),
2937
+ force,
2938
+ strict,
2939
+ noSpec,
2940
+ noVerify,
2941
+ ...(Array.isArray(args.probes) ? { probes: args.probes } : {}),
2942
+ ...(Array.isArray(args.routes) ? { routes: args.routes } : {}),
2943
+ ...(Array.isArray(args.endpoints) ? { endpoints: args.endpoints } : {}),
2944
+ ...(baseUrl ? { baseUrl } : {}),
2945
+ ...(headers !== undefined ? { headers } : {}),
2946
+ ...(storageState !== undefined ? { storageState } : {}),
2947
+ ...(fsDiff ? { fsDiff: true } : {}),
2948
+ ...(crawlDepth !== undefined ? { crawlDepth } : {}),
2949
+ ...(holdoutRoutes.length > 0 ? { holdoutRoutes } : {}),
2950
+ ...(discoverHint ? { discoverHint } : {})
2951
+ };
2952
+ const result = await lockProject(lockOptions, {
2953
+ ...(deps.verifyDeps ?? {}),
2954
+ ...(deps.ingestDeps ? { ingestDeps: deps.ingestDeps } : {})
2955
+ });
2956
+ const holdoutById = loadHoldoutMap();
2957
+ const safeBaselineReport = result.baselineReport
2958
+ ? compactReport(sanitizeReportForMcp(result.baselineReport, holdoutById))
2959
+ : undefined;
2960
+ return {
2961
+ ok: result.ok,
2962
+ tool: "vibecode_lock",
2963
+ mode: "lock",
2964
+ manifest: redactMcpValue(result.manifest),
2965
+ contractPath: redactMcpText(result.contractPath),
2966
+ lockPath: redactMcpText(result.lockPath),
2967
+ ...(result.specPath ? { specPath: redactMcpText(result.specPath) } : {}),
2968
+ ...(safeBaselineReport ? { baselineReport: safeBaselineReport } : {}),
2969
+ warnings: result.warnings.map((w) => redactMcpText(w)),
2970
+ nextSteps: result.nextSteps.map((s) => redactMcpText(s))
2971
+ };
2972
+ }
2973
+ function loadHoldoutMap() {
2974
+ let contract = null;
2975
+ try {
2976
+ contract = readContract(rootDir);
2977
+ }
2978
+ catch (err) {
2979
+ if (errorCode(err) !== "CONTRACT_NOT_FOUND")
2980
+ throw err;
2981
+ }
2982
+ const holdouts = readHoldouts(rootDir);
2983
+ const holdoutById = new Map();
2984
+ for (const h of holdouts)
2985
+ holdoutById.set(h.id, h);
2986
+ if (contract) {
2987
+ for (const inv of contract.invariants) {
2988
+ if (inv.holdout === true && !holdoutById.has(inv.id))
2989
+ holdoutById.set(inv.id, inv);
2990
+ }
2991
+ }
2992
+ return holdoutById;
2993
+ }
302
2994
  function toolDiff(args = {}) {
2995
+ if (!isPlainObjectSafe(args)) {
2996
+ throw new VibecodeError("CONTRACT_INVALID", "vibecode_diff arguments must be an object.");
2997
+ }
2998
+ const allowedKeys = new Set(["invariantId", "baselinePath", "strict"]);
2999
+ for (const key of Object.getOwnPropertyNames(args)) {
3000
+ if (!allowedKeys.has(key)) {
3001
+ throw new VibecodeError("CONTRACT_INVALID", `Unexpected vibecode_diff argument: ${redactMcpText(key)}`);
3002
+ }
3003
+ }
3004
+ if (args.invariantId !== undefined && args.baselinePath !== undefined) {
3005
+ throw new VibecodeError("CONTRACT_INVALID", "Cannot combine invariantId and baselinePath in a single vibecode_diff call.");
3006
+ }
3007
+ const strict = parseMcpBoolean(args.strict, "strict") === true;
3008
+ if (args.baselinePath !== undefined) {
3009
+ const baselineFile = resolveMcpContainedInputFile(rootDir, args.baselinePath, "baselinePath");
3010
+ let parsedBaseline;
3011
+ try {
3012
+ parsedBaseline = JSON.parse(fs.readFileSync(baselineFile, "utf8"));
3013
+ }
3014
+ catch (err) {
3015
+ throw new VibecodeError("CONTRACT_INVALID", `Invalid baselinePath report JSON: ${redactMcpText(errorMessage(err))}`);
3016
+ }
3017
+ if (!isPlainObjectSafe(parsedBaseline) ||
3018
+ (!Array.isArray(parsedBaseline.results) && !isPlainObjectSafe(parsedBaseline.gate))) {
3019
+ throw new VibecodeError("CONTRACT_INVALID", 'baselinePath must contain a ParityReport JSON object with "results" or "gate".');
3020
+ }
3021
+ const last = readLastReport(rootDir);
3022
+ if (!last) {
3023
+ throw new VibecodeError("CONTRACT_NOT_FOUND", "No .vibecode/last-report.json yet. Run vibecode_verify first.");
3024
+ }
3025
+ const holdoutById = loadHoldoutMap();
3026
+ const safeBaseline = sanitizeReportForMcp(parsedBaseline, holdoutById);
3027
+ const safeLast = sanitizeReportForMcp(last, holdoutById);
3028
+ const comparison = compareReports(safeBaseline, safeLast, { strict });
3029
+ const { ok, ...comparisonFields } = comparison;
3030
+ return {
3031
+ ok,
3032
+ tool: "vibecode_diff",
3033
+ mode: "baseline",
3034
+ ...comparisonFields,
3035
+ markdownSummary: redactMcpText(renderRegressionMarkdown(comparison))
3036
+ };
3037
+ }
303
3038
  const id = args.invariantId;
304
- if (typeof id !== "string" || !id) {
305
- throw new VibecodeError("TARGET_MISSING", "vibecode_diff requires invariantId");
3039
+ if (typeof id !== "string" || !id.trim()) {
3040
+ throw new VibecodeError("TARGET_MISSING", "vibecode_diff requires invariantId or baselinePath");
306
3041
  }
307
3042
  const last = readLastReport(rootDir);
308
3043
  if (!last) {
@@ -310,36 +3045,709 @@ export function createMcpServer({ cwd = process.cwd(), stdin = process.stdin, st
310
3045
  }
311
3046
  const result = (last.results || []).find((r) => r.id === id);
312
3047
  if (!result)
313
- throw new VibecodeError("NOT_FOUND", `No result for invariant ${id} in the last report.`);
314
- return result;
3048
+ throw new VibecodeError("NOT_FOUND", `No result for invariant ${redactMcpText(id)} in the last report.`);
3049
+ const holdoutById = loadHoldoutMap();
3050
+ const holdoutInv = holdoutById.get(result.id);
3051
+ const isHoldout = Boolean(holdoutInv) || isHoldoutResultRecord(result);
3052
+ return sanitizeResult(isHoldout ? sanitizeHoldoutResultForMcp(result, holdoutInv) : sanitizeVisibleResultForMcp(result));
3053
+ }
3054
+ function toolReport(args = {}) {
3055
+ if (!isPlainObjectSafe(args)) {
3056
+ throw new VibecodeError("CONTRACT_INVALID", "vibecode_report arguments must be an object.");
3057
+ }
3058
+ for (const key of Object.getOwnPropertyNames(args)) {
3059
+ if (!ALLOWED_REPORT_KEYS.has(key)) {
3060
+ throw new VibecodeError("CONTRACT_INVALID", `Unexpected vibecode_report argument: ${redactMcpText(key)}`);
3061
+ }
3062
+ }
3063
+ const outPath = resolveMcpOutputPath(rootDir, args.outPath, "outPath");
3064
+ const badgePath = resolveMcpOutputPath(rootDir, args.badgePath, "badgePath");
3065
+ const markdownPath = resolveMcpOutputPath(rootDir, args.markdownPath, "markdownPath");
3066
+ const sarifPath = resolveMcpOutputPath(rootDir, args.sarifPath, "sarifPath");
3067
+ const junitPath = resolveMcpOutputPath(rootDir, args.junitPath, "junitPath");
3068
+ const noReport = parseMcpBoolean(args.noReport, "noReport") === true;
3069
+ let label;
3070
+ if (args.label !== undefined) {
3071
+ if (typeof args.label !== "string") {
3072
+ throw new VibecodeError("CONTRACT_INVALID", "label must be a string.");
3073
+ }
3074
+ const trimmedLabel = args.label.trim();
3075
+ if (trimmedLabel)
3076
+ label = trimmedLabel;
3077
+ }
3078
+ const contract = readContract(rootDir);
3079
+ const report = readLastReport(rootDir);
3080
+ if (!report) {
3081
+ throw new VibecodeError("CONTRACT_NOT_FOUND", "Missing .vibecode/last-report.json. Run 'vibecode_verify' first.");
3082
+ }
3083
+ const holdouts = readHoldouts(rootDir);
3084
+ const holdoutById = new Map();
3085
+ for (const h of holdouts)
3086
+ holdoutById.set(h.id, h);
3087
+ for (const inv of contract.invariants) {
3088
+ if (inv.holdout === true && !holdoutById.has(inv.id))
3089
+ holdoutById.set(inv.id, inv);
3090
+ }
3091
+ const safeReport = sanitizeReportForMcp(report, holdoutById);
3092
+ const mergedForHtml = holdouts.length > 0
3093
+ ? {
3094
+ ...contract,
3095
+ invariants: [
3096
+ ...contract.invariants,
3097
+ ...holdouts.filter((h) => !contract.invariants.some((v) => v.id === h.id))
3098
+ ]
3099
+ }
3100
+ : contract;
3101
+ const history = readRunHistory(rootDir);
3102
+ const slices = summarizeSlices(contract);
3103
+ const writtenReportPath = noReport
3104
+ ? undefined
3105
+ : writeHtmlReport(rootDir, {
3106
+ contract: mergedForHtml,
3107
+ report: safeReport,
3108
+ history,
3109
+ workspaceDir: rootDir,
3110
+ ...(outPath ? { outPath } : {})
3111
+ });
3112
+ const reportTarget = report.target;
3113
+ const safeTarget = typeof reportTarget === "string" && reportTarget.trim() ? redactMcpText(reportTarget.trim()) : undefined;
3114
+ const prOptions = {
3115
+ contractName: contract.target.name,
3116
+ ...(safeTarget ? { target: safeTarget } : {}),
3117
+ ...(slices.total > 0 ? { slices } : {}),
3118
+ ...(writtenReportPath
3119
+ ? { reportHtmlPath: path.relative(rootDir, writtenReportPath).replace(/\\/g, "/") }
3120
+ : {}),
3121
+ holdoutCount: holdouts.length
3122
+ };
3123
+ const markdownSummary = redactMcpText(renderPrCommentMarkdown(safeReport, prOptions));
3124
+ const writtenMarkdownPath = markdownPath
3125
+ ? writePrCommentMarkdown(markdownPath, safeReport, prOptions)
3126
+ : undefined;
3127
+ const writtenBadgePath = badgePath
3128
+ ? writeParityBadgeSvg(badgePath, safeReport, label !== undefined ? { label } : {})
3129
+ : undefined;
3130
+ const writtenSarifPath = sarifPath
3131
+ ? writeSarifReport(safeReport, sarifPath, {
3132
+ contractName: redactMcpText(contract.target.name),
3133
+ toolVersion: SERVER_VERSION,
3134
+ ...(safeTarget ? { target: safeTarget } : {})
3135
+ })
3136
+ : undefined;
3137
+ const writtenJunitPath = junitPath
3138
+ ? writeJunitXml(safeReport, junitPath, {
3139
+ suiteName: redactMcpText(contract.target.name),
3140
+ ...(safeTarget ? { target: safeTarget } : {})
3141
+ })
3142
+ : undefined;
3143
+ return {
3144
+ ok: true,
3145
+ tool: "vibecode_report",
3146
+ gate: safeReport.gate,
3147
+ ...(writtenReportPath ? { reportHtmlPath: redactMcpText(writtenReportPath) } : {}),
3148
+ ...(writtenBadgePath ? { badgePath: redactMcpText(writtenBadgePath) } : {}),
3149
+ ...(writtenMarkdownPath ? { markdownPath: redactMcpText(writtenMarkdownPath) } : {}),
3150
+ ...(writtenSarifPath ? { sarifPath: redactMcpText(writtenSarifPath) } : {}),
3151
+ ...(writtenJunitPath ? { junitPath: redactMcpText(writtenJunitPath) } : {}),
3152
+ markdownSummary
3153
+ };
3154
+ }
3155
+ async function toolDiagnose(args = {}) {
3156
+ if (!args || typeof args !== "object" || Array.isArray(args)) {
3157
+ throw new VibecodeError("CONTRACT_INVALID", "vibecode_diagnose arguments must be an object.");
3158
+ }
3159
+ const allowedKeys = new Set(["includeVisualHeatmap", "maxBriefChars", "briefOnly", "includeStrength"]);
3160
+ for (const key of Object.getOwnPropertyNames(args)) {
3161
+ if (!allowedKeys.has(key)) {
3162
+ throw new VibecodeError("CONTRACT_INVALID", `Unexpected vibecode_diagnose argument: ${redactMcpText(key)}`);
3163
+ }
3164
+ }
3165
+ const includeVisualHeatmap = parseMcpBoolean(args.includeVisualHeatmap, "includeVisualHeatmap");
3166
+ const briefOnly = parseMcpBoolean(args.briefOnly, "briefOnly") === true;
3167
+ const includeStrength = parseMcpBoolean(args.includeStrength, "includeStrength") === true;
3168
+ let maxBriefChars;
3169
+ if (args.maxBriefChars !== undefined) {
3170
+ if (typeof args.maxBriefChars !== "number" ||
3171
+ !Number.isInteger(args.maxBriefChars) ||
3172
+ args.maxBriefChars < 200 ||
3173
+ args.maxBriefChars > 20000) {
3174
+ throw new VibecodeError("CONTRACT_INVALID", "maxBriefChars must be an integer between 200 and 20000.");
3175
+ }
3176
+ maxBriefChars = args.maxBriefChars;
3177
+ }
3178
+ const lastReport = readLastReport(rootDir);
3179
+ if (!lastReport) {
3180
+ throw new VibecodeError("NOT_FOUND", "No .vibecode/last-report.json found. Run vibecode_verify first.");
3181
+ }
3182
+ let contract;
3183
+ try {
3184
+ contract = readContract(rootDir);
3185
+ }
3186
+ catch (err) {
3187
+ if (errorCode(err) !== "CONTRACT_NOT_FOUND")
3188
+ throw err;
3189
+ }
3190
+ const holdoutById = loadHoldoutMap();
3191
+ const safeLastReport = sanitizeReportForMcp(lastReport, holdoutById);
3192
+ const safeContract = contract
3193
+ ? {
3194
+ ...contract,
3195
+ invariants: contract.invariants.filter((inv) => inv.holdout !== true)
3196
+ }
3197
+ : undefined;
3198
+ const diagnosis = await diagnoseReport(safeLastReport, {
3199
+ ...(safeContract ? { contract: safeContract } : {}),
3200
+ cwd: rootDir,
3201
+ ...(includeVisualHeatmap !== undefined ? { includeVisualHeatmap } : {}),
3202
+ ...(maxBriefChars !== undefined ? { maxBriefChars } : {})
3203
+ });
3204
+ const redactedBrief = redactMcpText(diagnosis.repairBrief);
3205
+ const safeBrief = maxBriefChars !== undefined && redactedBrief.length > maxBriefChars
3206
+ ? redactedBrief.slice(0, maxBriefChars)
3207
+ : redactedBrief;
3208
+ const safeContractName = redactMcpText(diagnosis.contractName);
3209
+ const safeGate = redactMcpText(diagnosis.gate);
3210
+ const strength = includeStrength
3211
+ ? sanitizeMutationAuditForMcp(auditContractStrength((safeContract ?? { invariants: [] }), {
3212
+ holdoutCount: holdoutById.size,
3213
+ ...(maxBriefChars !== undefined ? { maxBriefChars } : {})
3214
+ }))
3215
+ : undefined;
3216
+ if (briefOnly) {
3217
+ return {
3218
+ ok: diagnosis.ok,
3219
+ tool: "vibecode_diagnose",
3220
+ contractName: safeContractName,
3221
+ gate: safeGate,
3222
+ totalDiagnosed: diagnosis.totalDiagnosed,
3223
+ categoryCounts: diagnosis.categoryCounts,
3224
+ repairBrief: safeBrief,
3225
+ ...(strength ? { strength } : {}),
3226
+ generatedAt: diagnosis.generatedAt
3227
+ };
3228
+ }
3229
+ const safeItems = diagnosis.items.map((item) => ({
3230
+ invariantId: redactMcpText(item.invariantId),
3231
+ type: redactMcpText(item.type),
3232
+ severity: redactMcpText(item.severity),
3233
+ status: redactMcpText(item.status),
3234
+ category: item.category,
3235
+ confidence: item.confidence,
3236
+ redacted: item.redacted,
3237
+ headline: redactMcpText(item.headline),
3238
+ evidence: item.redacted ? ["[REDACTED_HOLDOUT]"] : item.evidence.map((e) => redactMcpText(e)),
3239
+ suggestedFix: redactMcpText(item.suggestedFix),
3240
+ ...(!item.redacted && item.repro ? { repro: redactMcpText(item.repro) } : {}),
3241
+ ...(!item.redacted && item.spatialHeatmap
3242
+ ? {
3243
+ spatialHeatmap: {
3244
+ ...item.spatialHeatmap,
3245
+ summary: redactMcpText(item.spatialHeatmap.summary),
3246
+ asciiGrid: redactMcpText(item.spatialHeatmap.asciiGrid)
3247
+ }
3248
+ }
3249
+ : {}),
3250
+ ...(!item.redacted && item.bboxShifts
3251
+ ? {
3252
+ bboxShifts: item.bboxShifts.map((s) => ({
3253
+ ...s,
3254
+ refId: redactMcpText(s.refId),
3255
+ candId: redactMcpText(s.candId),
3256
+ direction: redactMcpText(s.direction)
3257
+ }))
3258
+ }
3259
+ : {})
3260
+ }));
3261
+ return {
3262
+ ok: diagnosis.ok,
3263
+ tool: "vibecode_diagnose",
3264
+ contractName: safeContractName,
3265
+ gate: safeGate,
3266
+ totalDiagnosed: diagnosis.totalDiagnosed,
3267
+ categoryCounts: diagnosis.categoryCounts,
3268
+ items: safeItems,
3269
+ repairBrief: safeBrief,
3270
+ ...(strength ? { strength } : {}),
3271
+ generatedAt: diagnosis.generatedAt
3272
+ };
3273
+ }
3274
+ async function toolFlake(args = {}) {
3275
+ if (!isPlainObjectSafe(args)) {
3276
+ throw new VibecodeError("CONTRACT_INVALID", "vibecode_flake arguments must be an object.");
3277
+ }
3278
+ if (Object.prototype.hasOwnProperty.call(args, "plugin") ||
3279
+ Object.prototype.hasOwnProperty.call(args, "plugins") ||
3280
+ Object.prototype.hasOwnProperty.call(args, "pluginRegistry")) {
3281
+ throw new VibecodeError("CONFIG_INVALID", "Custom local plugin loading is CLI-only and not permitted over MCP; built-in plugins run automatically.");
3282
+ }
3283
+ if (Object.prototype.hasOwnProperty.call(args, "allowFixtureCommands") ||
3284
+ Object.prototype.hasOwnProperty.call(args, "allowCommandHooks")) {
3285
+ throw new VibecodeError("CONFIG_INVALID", "Fixture command hooks are CLI-only (--allow-fixture-commands) and not permitted over MCP.");
3286
+ }
3287
+ const allowedKeys = new Set([
3288
+ "target",
3289
+ "targets",
3290
+ "vars",
3291
+ "runs",
3292
+ "invariantIds",
3293
+ "sliceIds",
3294
+ "strict",
3295
+ "skipFixtures",
3296
+ "headers",
3297
+ "storageState"
3298
+ ]);
3299
+ for (const key of Object.getOwnPropertyNames(args)) {
3300
+ if (!allowedKeys.has(key)) {
3301
+ throw new VibecodeError("CONTRACT_INVALID", `Unexpected vibecode_flake argument: ${redactMcpText(key)}`);
3302
+ }
3303
+ }
3304
+ const rawTargets = args.targets !== undefined ? validateTargetMapObject(args.targets) : undefined;
3305
+ const targets = rawTargets && Object.keys(rawTargets).length > 0 ? rawTargets : undefined;
3306
+ if (targets) {
3307
+ for (const [domain, mappedTarget] of Object.entries(targets)) {
3308
+ if (typeof mappedTarget === "string") {
3309
+ validateMcpTargetForDomain(rootDir, domain, mappedTarget, `targets.${domain}`);
3310
+ }
3311
+ }
3312
+ }
3313
+ const rawVars = args.vars !== undefined ? validateRuntimeVarsObject(args.vars) : undefined;
3314
+ const vars = rawVars && Object.keys(rawVars).length > 0 ? rawVars : undefined;
3315
+ if (vars) {
3316
+ for (const [k, v] of Object.entries(vars)) {
3317
+ if (k.toUpperCase() === "VIBECODE_VAULT_DIR") {
3318
+ throw new VibecodeError("CONTRACT_INVALID", "vars cannot override VIBECODE_VAULT_DIR.");
3319
+ }
3320
+ assertNoVaultAccessInText(rootDir, v, `vars.${k}`);
3321
+ }
3322
+ }
3323
+ const runFlakeWithRuntime = async () => {
3324
+ const rawTarget = args.target;
3325
+ if (rawTarget !== undefined && typeof rawTarget !== "string") {
3326
+ throw new VibecodeError("TARGET_MISSING", "vibecode_flake requires a target command or URL (or a targets domain map).");
3327
+ }
3328
+ const trimmedTarget = typeof rawTarget === "string" && rawTarget.trim() ? rawTarget.trim() : "";
3329
+ if (!trimmedTarget && !targets) {
3330
+ throw new VibecodeError("TARGET_MISSING", "vibecode_flake requires a target command or URL (or a targets domain map).");
3331
+ }
3332
+ if (trimmedTarget) {
3333
+ assertNoVaultAccessInText(rootDir, trimmedTarget, "target");
3334
+ assertNotDisallowedUrlScheme(trimmedTarget, "target");
3335
+ }
3336
+ let runs;
3337
+ if (args.runs !== undefined) {
3338
+ if (typeof args.runs !== "number" || !Number.isInteger(args.runs) || args.runs < 2 || args.runs > 10) {
3339
+ throw new VibecodeError("CONTRACT_INVALID", "runs must be an integer between 2 and 10.");
3340
+ }
3341
+ runs = args.runs;
3342
+ }
3343
+ if (args.invariantIds !== undefined &&
3344
+ (!Array.isArray(args.invariantIds) || args.invariantIds.some((id) => typeof id !== "string" || !id.trim()))) {
3345
+ throw new VibecodeError("CONTRACT_INVALID", "invariantIds must be an array of non-empty strings.");
3346
+ }
3347
+ if (args.sliceIds !== undefined &&
3348
+ (!Array.isArray(args.sliceIds) || args.sliceIds.some((id) => typeof id !== "string" || !id.trim()))) {
3349
+ throw new VibecodeError("CONTRACT_INVALID", "sliceIds must be an array of non-empty strings.");
3350
+ }
3351
+ const strict = parseMcpBoolean(args.strict, "strict") === true;
3352
+ const skipFixtures = parseMcpBoolean(args.skipFixtures, "skipFixtures") === true;
3353
+ const headers = parseMcpStringRecord(args.headers, "headers");
3354
+ const storageState = args.storageState !== undefined
3355
+ ? resolveMcpContainedInputFile(rootDir, args.storageState, "storageState")
3356
+ : undefined;
3357
+ const contract = readContract(rootDir);
3358
+ const sliceArgs = Array.isArray(args.sliceIds) ? args.sliceIds.map((s) => String(s).trim()).filter(Boolean) : [];
3359
+ const explicitIds = Array.isArray(args.invariantIds)
3360
+ ? args.invariantIds.map((s) => String(s).trim()).filter(Boolean)
3361
+ : [];
3362
+ const invariantIds = [];
3363
+ const seenIds = new Set();
3364
+ if (sliceArgs.length > 0) {
3365
+ const resolved = resolveSliceInvariants(contract, sliceArgs);
3366
+ for (const id of resolved.invariantIds) {
3367
+ if (!seenIds.has(id)) {
3368
+ seenIds.add(id);
3369
+ invariantIds.push(id);
3370
+ }
3371
+ }
3372
+ }
3373
+ for (const id of explicitIds) {
3374
+ if (!seenIds.has(id)) {
3375
+ seenIds.add(id);
3376
+ invariantIds.push(id);
3377
+ }
3378
+ }
3379
+ if (trimmedTarget) {
3380
+ const targetDomains = collectTargetConsumingDomains(rootDir, contract, { invariantIds });
3381
+ validateMcpFallbackTargetForContract(rootDir, trimmedTarget, targetDomains, "target", targets);
3382
+ }
3383
+ const report = await analyzeFlakes(contract, {
3384
+ ...(runs !== undefined ? { runs } : {}),
3385
+ cwd: rootDir,
3386
+ target: trimmedTarget,
3387
+ ...(targets ? { targets } : {}),
3388
+ ...(vars ? { vars } : {}),
3389
+ ...(skipFixtures ? { skipFixtures: true } : {}),
3390
+ strict,
3391
+ ...(invariantIds.length > 0 ? { invariantIds } : {}),
3392
+ ...(headers !== undefined ? { headers } : {}),
3393
+ ...(storageState !== undefined ? { storageState } : {}),
3394
+ revealHoldouts: false
3395
+ }, deps.verifyDeps || {});
3396
+ return {
3397
+ tool: "vibecode_flake",
3398
+ ...report,
3399
+ contractName: redactMcpText(report.contractName),
3400
+ invariants: report.invariants.map((inv) => ({
3401
+ ...inv,
3402
+ id: redactMcpText(inv.id),
3403
+ type: redactMcpText(inv.type),
3404
+ severity: redactMcpText(inv.severity),
3405
+ distinctOutputHashes: inv.redacted ? 0 : inv.distinctOutputHashes,
3406
+ distinctFailureSignatures: inv.redacted ? 0 : inv.distinctFailureSignatures,
3407
+ nondeterminismKinds: inv.redacted ? [] : inv.nondeterminismKinds,
3408
+ suggestedRules: inv.redacted
3409
+ ? []
3410
+ : inv.suggestedRules.map((rule) => ({
3411
+ ...rule,
3412
+ description: redactMcpText(rule.description),
3413
+ contractHint: redactMcpText(rule.contractHint)
3414
+ })),
3415
+ sampleFailures: inv.redacted ? [] : inv.sampleFailures.map((f) => redactMcpText(f))
3416
+ }))
3417
+ };
3418
+ };
3419
+ if (!vars)
3420
+ return runFlakeWithRuntime();
3421
+ try {
3422
+ return redactRuntimeVarsDeep(await runFlakeWithRuntime(), vars);
3423
+ }
3424
+ catch (err) {
3425
+ throw new VibecodeError(errorCode(err) ?? "INTERNAL_ERROR", redactMcpText(redactRuntimeVars(errorMessage(err), vars)));
3426
+ }
3427
+ }
3428
+ function loadPromptContext() {
3429
+ let contract = null;
3430
+ try {
3431
+ contract = readContract(rootDir);
3432
+ }
3433
+ catch (err) {
3434
+ if (errorCode(err) !== "CONTRACT_NOT_FOUND")
3435
+ throw err;
3436
+ }
3437
+ const holdouts = contract ? readHoldouts(rootDir) : [];
3438
+ const holdoutById = new Map();
3439
+ for (const h of holdouts)
3440
+ holdoutById.set(h.id, h);
3441
+ if (contract) {
3442
+ for (const inv of contract.invariants) {
3443
+ if (inv.holdout === true && !holdoutById.has(inv.id))
3444
+ holdoutById.set(inv.id, inv);
3445
+ }
3446
+ }
3447
+ const rawReport = readLastReport(rootDir);
3448
+ const report = rawReport ? sanitizeReportForMcp(rawReport, holdoutById) : null;
3449
+ const { specPath } = resolveWorkspace(rootDir);
3450
+ let specText = null;
3451
+ if (fs.existsSync(specPath)) {
3452
+ try {
3453
+ const rawSpec = redactMcpText(fs.readFileSync(specPath, "utf8")).trim();
3454
+ if (rawSpec) {
3455
+ specText =
3456
+ rawSpec.length > MAX_PROMPT_SPEC_CHARS
3457
+ ? `${rawSpec.slice(0, MAX_PROMPT_SPEC_CHARS)}\n\n... [truncated; read vibecode://spec for full specification]`
3458
+ : rawSpec;
3459
+ }
3460
+ }
3461
+ catch {
3462
+ specText = null;
3463
+ }
3464
+ }
3465
+ return { contract, holdouts, holdoutById, report, specText };
3466
+ }
3467
+ function buildPromptText(promptName, args) {
3468
+ const parseOptString = (key) => {
3469
+ const val = args[key];
3470
+ if (val === undefined)
3471
+ return { ok: true };
3472
+ if (typeof val !== "string") {
3473
+ return { ok: false, message: `prompts/get argument "${key}" must be a string` };
3474
+ }
3475
+ const trimmed = val.trim();
3476
+ return { ok: true, ...(trimmed ? { value: trimmed } : {}) };
3477
+ };
3478
+ const targetRes = parseOptString("target");
3479
+ if (!targetRes.ok)
3480
+ return targetRes;
3481
+ const safeTarget = targetRes.value ? redactMcpText(targetRes.value) : undefined;
3482
+ const { contract, holdouts, holdoutById, report, specText } = loadPromptContext();
3483
+ if (promptName === "vibecode_rebuild_slice") {
3484
+ const sliceIdRes = parseOptString("sliceId");
3485
+ if (!sliceIdRes.ok)
3486
+ return sliceIdRes;
3487
+ const requestedSliceId = sliceIdRes.value;
3488
+ const lines = ["# Vibecode Fresh-Context Rebuild Prompt", ""];
3489
+ if (!contract) {
3490
+ lines.push("No `.vibecode/contract.json` found in this workspace yet.", "", "## Next Steps", "- Run `vibecode_ingest` against your reference source first to create `.vibecode/contract.json` and `.vibecode/SPEC.md`.", "- Then call `prompts/get` for `vibecode_rebuild_slice` again to get the slice-scoped rebuild instructions.");
3491
+ return { ok: true, text: `${lines.join("\n")}\n` };
3492
+ }
3493
+ const sliceSummary = summarizeSlices(contract);
3494
+ const allSlices = getContractSlices(contract);
3495
+ let selectedSlice = requestedSliceId
3496
+ ? allSlices.find((s) => s.id === requestedSliceId)
3497
+ : sliceSummary.nextSlice
3498
+ ? allSlices.find((s) => s.id === sliceSummary.nextSlice)
3499
+ : allSlices.find((s) => s.status !== "passed");
3500
+ if (requestedSliceId && !selectedSlice) {
3501
+ const validIds = allSlices.map((s) => s.id);
3502
+ return {
3503
+ ok: false,
3504
+ message: `Unknown sliceId "${redactMcpText(requestedSliceId)}". Valid slice IDs: ${validIds.length > 0 ? validIds.join(", ") : "(none)"}`
3505
+ };
3506
+ }
3507
+ lines.push(`- Contract: \`${redactMcpText(contract.target.name)}\``);
3508
+ lines.push(`- Domains: ${contract.target.domains.join(", ")}`);
3509
+ if (safeTarget)
3510
+ lines.push(`- Target: \`${safeTarget}\``);
3511
+ lines.push(`- Slices Progress: ${sliceSummary.passed}/${sliceSummary.total} passed`);
3512
+ if (holdouts.length > 0) {
3513
+ lines.push(`- Hidden Holdouts: ${holdouts.length} (details withheld for anti-overfitting integrity)`);
3514
+ }
3515
+ lines.push("");
3516
+ lines.push("## Rules");
3517
+ lines.push("- Treat `.vibecode/SPEC.md` and the visible contract invariants as the single source of truth.");
3518
+ lines.push("- Do NOT edit `.vibecode/contract.json`, `.vibecode/SPEC.md`, or search for holdout tests.");
3519
+ lines.push("- Implement general specification-compliant behavior; never hardcode probe outputs.");
3520
+ lines.push("");
3521
+ if (sliceSummary.slices.length > 0) {
3522
+ lines.push("## Contract Slices");
3523
+ for (const s of sliceSummary.slices) {
3524
+ const scoreStr = typeof s.lastScore === "number" ? ` (score ${(s.lastScore * 100).toFixed(1)}%)` : "";
3525
+ lines.push(`- \`${redactMcpText(s.id)}\` — ${redactMcpText(s.title)} [${s.status}, ${s.invariantCount} invariants]${scoreStr}`);
3526
+ }
3527
+ lines.push("");
3528
+ }
3529
+ if (selectedSlice) {
3530
+ const invById = new Map(contract.invariants.map((inv) => [inv.id, inv]));
3531
+ const visibleSliceInvs = selectedSlice.invariantIds
3532
+ .filter((id) => !holdoutById.has(id))
3533
+ .map((id) => invById.get(id))
3534
+ .filter((inv) => inv !== undefined && inv.holdout !== true);
3535
+ lines.push(`## Target Slice: \`${redactMcpText(selectedSlice.id)}\` (${redactMcpText(selectedSlice.title)})`);
3536
+ lines.push(`- Status: \`${selectedSlice.status}\``);
3537
+ if (selectedSlice.dependsOn && selectedSlice.dependsOn.length > 0) {
3538
+ lines.push(`- Depends On: ${selectedSlice.dependsOn.map((d) => `\`${redactMcpText(d)}\``).join(", ")}`);
3539
+ }
3540
+ lines.push("");
3541
+ if (visibleSliceInvs.length > 0) {
3542
+ lines.push("### Visible Invariants in Slice");
3543
+ for (const inv of visibleSliceInvs) {
3544
+ const desc = inv.description ? ` — ${redactMcpText(inv.description)}` : "";
3545
+ lines.push(`- \`${redactMcpText(inv.id)}\` (${inv.severity}, ${inv.type})${desc}`);
3546
+ }
3547
+ lines.push("");
3548
+ }
3549
+ if (report) {
3550
+ const sliceIdSet = new Set(selectedSlice.invariantIds);
3551
+ const sliceFailures = (report.results || []).filter((r) => sliceIdSet.has(r.id) &&
3552
+ !holdoutById.has(r.id) &&
3553
+ r.metrics?.redacted !== true &&
3554
+ (r.status === "fail" || r.status === "error" || r.status === "warn"));
3555
+ if (sliceFailures.length > 0) {
3556
+ lines.push("### Current Failures in This Slice");
3557
+ for (const item of sliceFailures) {
3558
+ const reason = (Array.isArray(item.failures) && item.failures[0]) ||
3559
+ item.reason ||
3560
+ item.diagnostic?.message ||
3561
+ `status=${item.status}`;
3562
+ lines.push(`- \`${redactMcpText(item.id)}\` (${item.severity}, ${item.status}): ${redactMcpText(reason)}`);
3563
+ if (item.repro) {
3564
+ lines.push(` - Repro: \`${redactMcpText(item.repro)}\``);
3565
+ }
3566
+ }
3567
+ lines.push("");
3568
+ }
3569
+ }
3570
+ lines.push("## Verification");
3571
+ const verifyTarget = safeTarget ?? "<your-target-command-or-url>";
3572
+ lines.push(`- Run MCP \`vibecode_verify\` with \`{ "target": "${verifyTarget}", "sliceIds": ["${redactMcpText(selectedSlice.id)}"] }\`.`);
3573
+ lines.push("- Use `vibecode_diff` on any failing invariant ID to inspect full metrics and diffs.");
3574
+ lines.push("");
3575
+ }
3576
+ else {
3577
+ lines.push("## All Slices Passed");
3578
+ lines.push("- Every contract slice currently has status `passed`.");
3579
+ lines.push("- Run a full `vibecode_verify` (without `sliceIds`) to verify all visible and hidden holdout invariants.");
3580
+ lines.push("");
3581
+ }
3582
+ if (specText) {
3583
+ lines.push("## Workspace Specification (`.vibecode/SPEC.md`)");
3584
+ lines.push("");
3585
+ lines.push(specText);
3586
+ lines.push("");
3587
+ }
3588
+ return { ok: true, text: `${lines.join("\n").trimEnd()}\n` };
3589
+ }
3590
+ if (promptName === "vibecode_fix_failures") {
3591
+ const lines = ["# Vibecode Fresh-Context Fix Failures Prompt", ""];
3592
+ if (contract) {
3593
+ lines.push(`- Contract: \`${redactMcpText(contract.target.name)}\``);
3594
+ }
3595
+ if (safeTarget) {
3596
+ lines.push(`- Target: \`${safeTarget}\``);
3597
+ }
3598
+ if (report) {
3599
+ lines.push(`- Last Gate: \`${report.gate.status}\` (hard ${report.hard.passed}/${report.hard.total}, composite ${(report.compositeScore * 100).toFixed(1)}%)`);
3600
+ if (report.nextAction && report.nextAction !== "none") {
3601
+ lines.push(`- Next Action: \`${report.nextAction}\``);
3602
+ }
3603
+ }
3604
+ lines.push("");
3605
+ lines.push("## Rules");
3606
+ lines.push("- Read `.vibecode/SPEC.md` (or resource `vibecode://spec`) as the source of truth.");
3607
+ lines.push("- Fix ONLY the target implementation so all failing invariants below pass.");
3608
+ lines.push("- Do NOT edit `.vibecode/contract.json` or `.vibecode/SPEC.md`, and do NOT search for holdout tests.");
3609
+ lines.push("- After fixing, re-run `vibecode_verify` until `gate.passed` is `true`.");
3610
+ lines.push("");
3611
+ if (!report) {
3612
+ lines.push("## Last Parity Report");
3613
+ lines.push("No `.vibecode/last-report.json` exists yet. Run `vibecode_verify` first, then request this prompt again.");
3614
+ lines.push("");
3615
+ }
3616
+ else {
3617
+ const issues = (report.results || []).filter((r) => r.status === "fail" || r.status === "error" || r.status === "warn");
3618
+ const visibleIssues = issues.filter((r) => !holdoutById.has(r.id) && r.metrics?.redacted !== true);
3619
+ const holdoutIssues = issues.filter((r) => holdoutById.has(r.id) || r.metrics?.redacted === true);
3620
+ if (visibleIssues.length === 0 && holdoutIssues.length === 0) {
3621
+ lines.push("## Failing Invariants");
3622
+ lines.push("All evaluated invariants in the last parity report passed.");
3623
+ lines.push("");
3624
+ }
3625
+ else {
3626
+ if (visibleIssues.length > 0) {
3627
+ lines.push(`## Visible Failing & Warned Invariants (${visibleIssues.length})`);
3628
+ for (const item of visibleIssues) {
3629
+ lines.push("", `### \`${redactMcpText(item.id)}\` (${item.severity} | ${item.type} | ${item.status})`);
3630
+ const failures = Array.isArray(item.failures) && item.failures.length > 0
3631
+ ? item.failures
3632
+ : [item.reason || item.diagnostic?.message || `Invariant ${item.status}`];
3633
+ for (const f of failures.slice(0, 8)) {
3634
+ lines.push(`- ${redactMcpText(f)}`);
3635
+ }
3636
+ if (typeof item.repro === "string" && item.repro.trim()) {
3637
+ lines.push(`- Repro: \`${redactMcpText(item.repro.trim())}\``);
3638
+ }
3639
+ const diffExcerpt = formatCompactDiffForPrompt(item.diff);
3640
+ if (diffExcerpt) {
3641
+ lines.push("- Diff:");
3642
+ lines.push("```text");
3643
+ lines.push(diffExcerpt);
3644
+ lines.push("```");
3645
+ }
3646
+ }
3647
+ lines.push("");
3648
+ }
3649
+ if (holdoutIssues.length > 0) {
3650
+ lines.push(`## Redacted Holdout Failures (${holdoutIssues.length})`);
3651
+ lines.push("Expected values, inputs, diffs, and repro commands are withheld for holdout integrity.");
3652
+ for (const item of holdoutIssues) {
3653
+ const hint = Array.isArray(item.failures) && item.failures[0]
3654
+ ? redactMcpText(item.failures[0])
3655
+ : "Holdout invariant failed (expected details redacted)";
3656
+ lines.push(`- \`${redactMcpText(item.id)}\` (${item.severity}, ${item.status}) [holdout redacted]: ${hint}`);
3657
+ }
3658
+ lines.push("");
3659
+ }
3660
+ }
3661
+ }
3662
+ if (specText) {
3663
+ lines.push("## Workspace Specification (`.vibecode/SPEC.md`)");
3664
+ lines.push("");
3665
+ lines.push(specText);
3666
+ lines.push("");
3667
+ }
3668
+ return { ok: true, text: `${lines.join("\n").trimEnd()}\n` };
3669
+ }
3670
+ return { ok: false, message: `Unknown prompt: ${promptName}` };
315
3671
  }
316
3672
  async function callTool(name, args) {
317
3673
  switch (name) {
3674
+ case "vibecode_discover":
3675
+ return toolDiscover(args);
3676
+ case "vibecode_lock":
3677
+ return toolLock(args);
318
3678
  case "vibecode_ingest":
319
3679
  return toolIngest(args);
320
3680
  case "vibecode_verify":
321
3681
  return toolVerify(args);
322
3682
  case "vibecode_status":
323
- return statusPayload();
3683
+ return statusPayload(args);
324
3684
  case "vibecode_diff":
325
3685
  return toolDiff(args);
326
3686
  case "vibecode_doctor":
327
3687
  return toolDoctor(args);
3688
+ case "vibecode_diagnose":
3689
+ return toolDiagnose(args);
3690
+ case "vibecode_flake":
3691
+ return toolFlake(args);
3692
+ case "vibecode_report":
3693
+ return toolReport(args);
328
3694
  default:
329
3695
  throw new VibecodeError("UNSUPPORTED_FORMAT", `Unknown tool: ${name}`);
330
3696
  }
331
3697
  }
332
3698
  function readResource(uri) {
333
3699
  if (uri === "vibecode://contract") {
3700
+ const { contractPath } = resolveWorkspace(rootDir);
3701
+ if (!fs.existsSync(contractPath) && !lstatExists(contractPath)) {
3702
+ throw new VibecodeError("CONTRACT_NOT_FOUND", "No .vibecode/contract.json yet. Run vibecode_ingest first.");
3703
+ }
3704
+ resolveMcpContainedInputFile(rootDir, path.relative(rootDir, contractPath), "contract");
334
3705
  const raw = readRawContract(rootDir);
335
- return { uri, mimeType: "application/json", text: JSON.stringify(raw, null, 2) };
3706
+ const safe = sanitizeContractResource(raw);
3707
+ return { uri, mimeType: "application/json", text: JSON.stringify(safe, null, 2) };
3708
+ }
3709
+ if (uri === "vibecode://spec") {
3710
+ const { specPath } = resolveWorkspace(rootDir);
3711
+ if (!fs.existsSync(specPath) && !lstatExists(specPath)) {
3712
+ throw new VibecodeError("CONTRACT_NOT_FOUND", "No .vibecode/SPEC.md yet. Run vibecode_ingest first.");
3713
+ }
3714
+ const safeSpecPath = resolveMcpContainedInputFile(rootDir, path.relative(rootDir, specPath), "spec");
3715
+ const read = readBoundedFileUtf8(safeSpecPath, 8 * 1024 * 1024, { noFollow: true, rejectBinary: false });
3716
+ if (!read.ok) {
3717
+ throw new VibecodeError("CONTRACT_INVALID", redactMcpText(read.reason));
3718
+ }
3719
+ return { uri, mimeType: "text/markdown", text: redactMcpText(read.text) };
336
3720
  }
337
3721
  if (uri === "vibecode://last-report") {
3722
+ const { reportPath } = resolveWorkspace(rootDir);
3723
+ if (!fs.existsSync(reportPath) && !lstatExists(reportPath)) {
3724
+ throw new VibecodeError("CONTRACT_NOT_FOUND", "No .vibecode/last-report.json yet. Run vibecode_verify first.");
3725
+ }
3726
+ resolveMcpContainedInputFile(rootDir, path.relative(rootDir, reportPath), "lastReport");
338
3727
  const report = readLastReport(rootDir);
339
3728
  if (!report) {
340
3729
  throw new VibecodeError("CONTRACT_NOT_FOUND", "No .vibecode/last-report.json yet. Run vibecode_verify first.");
341
3730
  }
342
- return { uri, mimeType: "application/json", text: JSON.stringify(report, null, 2) };
3731
+ const holdoutById = loadHoldoutMap();
3732
+ const sanitized = sanitizeReportForMcp(report, holdoutById);
3733
+ const safeReport = {
3734
+ ...sanitized,
3735
+ results: (sanitized.results || []).map(sanitizeResult)
3736
+ };
3737
+ return { uri, mimeType: "application/json", text: JSON.stringify(safeReport, null, 2) };
3738
+ }
3739
+ if (uri === "vibecode://report") {
3740
+ const { reportHtmlPath } = resolveWorkspace(rootDir);
3741
+ const htmlTarget = reportHtmlPath || path.join(rootDir, ".vibecode", "report.html");
3742
+ if (!fs.existsSync(htmlTarget) && !lstatExists(htmlTarget)) {
3743
+ throw new VibecodeError("CONTRACT_NOT_FOUND", "No .vibecode/report.html yet. Run vibecode_verify first.");
3744
+ }
3745
+ const safeHtmlPath = resolveMcpContainedInputFile(rootDir, path.relative(rootDir, htmlTarget), "report");
3746
+ const read = readBoundedFileUtf8(safeHtmlPath, 32 * 1024 * 1024, { noFollow: true, rejectBinary: false });
3747
+ if (!read.ok) {
3748
+ throw new VibecodeError("CONTRACT_INVALID", redactMcpText(read.reason));
3749
+ }
3750
+ return { uri, mimeType: "text/html", text: read.text };
343
3751
  }
344
3752
  throw new VibecodeError("NOT_FOUND", `Unknown resource: ${uri}`);
345
3753
  }
@@ -373,7 +3781,8 @@ export function createMcpServer({ cwd = process.cwd(), stdin = process.stdin, st
373
3781
  protocolVersion,
374
3782
  capabilities: {
375
3783
  tools: { listChanged: false },
376
- resources: { subscribe: false, listChanged: false }
3784
+ resources: { subscribe: false, listChanged: false },
3785
+ prompts: { listChanged: false }
377
3786
  },
378
3787
  serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
379
3788
  instructions: INSTRUCTIONS
@@ -405,7 +3814,7 @@ export function createMcpServer({ cwd = process.cwd(), stdin = process.stdin, st
405
3814
  return reply(textResult(payload));
406
3815
  }
407
3816
  catch (err) {
408
- const diag = toDiagnostic(err);
3817
+ const diag = redactMcpDiagnostic(toDiagnostic(err));
409
3818
  log(`tool ${name} failed: ${diag.code} ${diag.message}`);
410
3819
  return reply(textResult({ ok: false, tool: name, error: diag }, { isError: true }));
411
3820
  }
@@ -423,10 +3832,55 @@ export function createMcpServer({ cwd = process.cwd(), stdin = process.stdin, st
423
3832
  return reply({ contents: [readResource(uri)] });
424
3833
  }
425
3834
  catch (err) {
426
- const diag = toDiagnostic(err);
3835
+ const diag = redactMcpDiagnostic(toDiagnostic(err));
427
3836
  return fail(RESOURCE_UNAVAILABLE, diag.message, diag);
428
3837
  }
429
3838
  }
3839
+ case "prompts/list":
3840
+ return reply({ prompts: PROMPTS });
3841
+ case "prompts/get": {
3842
+ const params = rec.params;
3843
+ if (params === null || typeof params !== "object" || Array.isArray(params)) {
3844
+ return fail(INVALID_PARAMS, "prompts/get params must be an object");
3845
+ }
3846
+ const paramsObj = params;
3847
+ const name = paramsObj.name;
3848
+ if (typeof name !== "string" || !name) {
3849
+ return fail(INVALID_PARAMS, "prompts/get requires params.name");
3850
+ }
3851
+ const rawArgs = paramsObj.arguments;
3852
+ if (rawArgs !== undefined && (rawArgs === null || typeof rawArgs !== "object" || Array.isArray(rawArgs))) {
3853
+ return fail(INVALID_PARAMS, "prompts/get params.arguments must be a plain object");
3854
+ }
3855
+ const promptDef = PROMPTS.find((p) => p.name === name);
3856
+ if (!promptDef) {
3857
+ return fail(INVALID_PARAMS, `Unknown prompt: ${redactMcpText(name)}`);
3858
+ }
3859
+ const promptArgs = rawArgs || {};
3860
+ try {
3861
+ const rendered = buildPromptText(promptDef.name, promptArgs);
3862
+ if (!rendered.ok) {
3863
+ return fail(INVALID_PARAMS, redactMcpText(rendered.message));
3864
+ }
3865
+ return reply({
3866
+ description: promptDef.description,
3867
+ messages: [
3868
+ {
3869
+ role: "user",
3870
+ content: {
3871
+ type: "text",
3872
+ text: rendered.text
3873
+ }
3874
+ }
3875
+ ]
3876
+ });
3877
+ }
3878
+ catch (err) {
3879
+ const diag = redactMcpDiagnostic(toDiagnostic(err));
3880
+ log(`prompt ${name} failed: ${diag.code} ${diag.message}`);
3881
+ return fail(INTERNAL_ERROR, diag.message, diag);
3882
+ }
3883
+ }
430
3884
  default:
431
3885
  return fail(METHOD_NOT_FOUND, `Method not found: ${rec.method}`);
432
3886
  }
@@ -452,7 +3906,7 @@ export function createMcpServer({ cwd = process.cwd(), stdin = process.stdin, st
452
3906
  msg = JSON.parse(line);
453
3907
  }
454
3908
  catch (err) {
455
- write({ jsonrpc: "2.0", id: null, error: { code: PARSE_ERROR, message: `Parse error: ${errorMessage(err)}` } });
3909
+ write({ jsonrpc: "2.0", id: null, error: { code: PARSE_ERROR, message: `Parse error: ${redactMcpText(errorMessage(err))}` } });
456
3910
  return;
457
3911
  }
458
3912
  try {
@@ -465,7 +3919,7 @@ export function createMcpServer({ cwd = process.cwd(), stdin = process.stdin, st
465
3919
  (typeof msg.id === "string" || typeof msg.id === "number")
466
3920
  ? msg.id
467
3921
  : null;
468
- write({ jsonrpc: "2.0", id, error: { code: INTERNAL_ERROR, message: `Internal error: ${errorMessage(err)}` } });
3922
+ write({ jsonrpc: "2.0", id, error: { code: INTERNAL_ERROR, message: `Internal error: ${redactMcpText(errorMessage(err))}` } });
469
3923
  }
470
3924
  }
471
3925
  function start() {
@@ -492,7 +3946,18 @@ export function createMcpServer({ cwd = process.cwd(), stdin = process.stdin, st
492
3946
  enqueue(buffer.replace(/\r$/, ""));
493
3947
  buffer = "";
494
3948
  if (stdin === process.stdin) {
495
- void lineQueue.finally(() => process.exit(process.exitCode || 0));
3949
+ void lineQueue.finally(() => {
3950
+ // Pause/unref stdin so Node exits naturally (avoids Windows libuv UV_HANDLE_CLOSING aborts
3951
+ // when calling process.exit() immediately after execFileSync + fetch); keep a short unref'd
3952
+ // safety timer in case an external ref'd handle lingers.
3953
+ if (typeof stdin.pause === "function")
3954
+ stdin.pause();
3955
+ const unrefable = stdin;
3956
+ if (typeof unrefable.unref === "function")
3957
+ unrefable.unref();
3958
+ const forceTimer = setTimeout(() => process.exit(process.exitCode || 0), 250);
3959
+ forceTimer.unref();
3960
+ });
496
3961
  }
497
3962
  });
498
3963
  stdin.on("error", (err) => log(`stdin error: ${err.message}`));