vibecode-anything 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +239 -67
  2. package/dist/cli.js +2140 -73
  3. package/dist/core/adapters.d.ts +26 -3
  4. package/dist/core/adapters.js +411 -25
  5. package/dist/core/agent-adapter.d.ts +67 -0
  6. package/dist/core/agent-adapter.js +312 -0
  7. package/dist/core/anti-cheat.d.ts +6 -0
  8. package/dist/core/anti-cheat.js +372 -0
  9. package/dist/core/badge.d.ts +18 -0
  10. package/dist/core/badge.js +360 -0
  11. package/dist/core/cache.d.ts +47 -0
  12. package/dist/core/cache.js +403 -0
  13. package/dist/core/ci-export.d.ts +35 -0
  14. package/dist/core/ci-export.js +796 -0
  15. package/dist/core/ci-formats.d.ts +21 -0
  16. package/dist/core/ci-formats.js +388 -0
  17. package/dist/core/client-codegen.d.ts +36 -0
  18. package/dist/core/client-codegen.js +2538 -0
  19. package/dist/core/compose.d.ts +71 -0
  20. package/dist/core/compose.js +1088 -0
  21. package/dist/core/docs-export.d.ts +37 -0
  22. package/dist/core/docs-export.js +2706 -0
  23. package/dist/core/doctor.d.ts +21 -1
  24. package/dist/core/doctor.js +234 -21
  25. package/dist/core/exec.d.ts +26 -2
  26. package/dist/core/exec.js +235 -8
  27. package/dist/core/fixtures.d.ts +153 -0
  28. package/dist/core/fixtures.js +2245 -0
  29. package/dist/core/format.d.ts +77 -0
  30. package/dist/core/format.js +632 -0
  31. package/dist/core/fs-snapshot.d.ts +37 -0
  32. package/dist/core/fs-snapshot.js +216 -0
  33. package/dist/core/graphql-export.d.ts +34 -0
  34. package/dist/core/graphql-export.js +2482 -0
  35. package/dist/core/har-export.d.ts +29 -0
  36. package/dist/core/har-export.js +988 -0
  37. package/dist/core/html-report.d.ts +27 -0
  38. package/dist/core/html-report.js +1535 -0
  39. package/dist/core/http-export.d.ts +31 -0
  40. package/dist/core/http-export.js +726 -0
  41. package/dist/core/impact.d.ts +80 -0
  42. package/dist/core/impact.js +1412 -0
  43. package/dist/core/lint.d.ts +38 -0
  44. package/dist/core/lint.js +1111 -0
  45. package/dist/core/load-export.d.ts +37 -0
  46. package/dist/core/load-export.js +1813 -0
  47. package/dist/core/mcp-export.d.ts +35 -0
  48. package/dist/core/mcp-export.js +1736 -0
  49. package/dist/core/mock-server.d.ts +47 -0
  50. package/dist/core/mock-server.js +1722 -0
  51. package/dist/core/openapi-export.d.ts +44 -0
  52. package/dist/core/openapi-export.js +1074 -0
  53. package/dist/core/parity.d.ts +6 -1
  54. package/dist/core/parity.js +36 -1
  55. package/dist/core/playwright-exporter.d.ts +23 -0
  56. package/dist/core/playwright-exporter.js +1343 -0
  57. package/dist/core/png.js +45 -9
  58. package/dist/core/regression.d.ts +54 -0
  59. package/dist/core/regression.js +529 -0
  60. package/dist/core/responsive.d.ts +86 -0
  61. package/dist/core/responsive.js +606 -0
  62. package/dist/core/run.d.ts +74 -0
  63. package/dist/core/run.js +696 -0
  64. package/dist/core/scheduler.d.ts +24 -0
  65. package/dist/core/scheduler.js +162 -0
  66. package/dist/core/schema-export.d.ts +29 -0
  67. package/dist/core/schema-export.js +2215 -0
  68. package/dist/core/schema.d.ts +3 -2
  69. package/dist/core/schema.js +460 -17
  70. package/dist/core/security.d.ts +233 -0
  71. package/dist/core/security.js +1839 -0
  72. package/dist/core/server-export.d.ts +38 -0
  73. package/dist/core/server-export.js +3198 -0
  74. package/dist/core/spec-writer.d.ts +9 -0
  75. package/dist/core/spec-writer.js +1202 -0
  76. package/dist/core/store.d.ts +11 -2
  77. package/dist/core/store.js +128 -8
  78. package/dist/core/target-map.d.ts +34 -0
  79. package/dist/core/target-map.js +262 -0
  80. package/dist/core/test-exporter.d.ts +25 -0
  81. package/dist/core/test-exporter.js +1918 -0
  82. package/dist/core/types.d.ts +182 -14
  83. package/dist/core/visual-semantic.d.ts +67 -0
  84. package/dist/core/visual-semantic.js +673 -0
  85. package/dist/core/visual.js +65 -16
  86. package/dist/core/watch.d.ts +28 -3
  87. package/dist/core/watch.js +222 -12
  88. package/dist/core/yaml.d.ts +5 -0
  89. package/dist/core/yaml.js +1009 -0
  90. package/dist/diagnostics/diagnose.d.ts +53 -0
  91. package/dist/diagnostics/diagnose.js +1083 -0
  92. package/dist/diagnostics/flake.d.ts +71 -0
  93. package/dist/diagnostics/flake.js +608 -0
  94. package/dist/diagnostics/mutation-audit.d.ts +69 -0
  95. package/dist/diagnostics/mutation-audit.js +769 -0
  96. package/dist/diagnostics/spatial.d.ts +42 -0
  97. package/dist/diagnostics/spatial.js +346 -0
  98. package/dist/diagnostics/trends.d.ts +122 -0
  99. package/dist/diagnostics/trends.js +1190 -0
  100. package/dist/discovery/discover.d.ts +111 -0
  101. package/dist/discovery/discover.js +2017 -0
  102. package/dist/discovery/lock.d.ts +116 -0
  103. package/dist/discovery/lock.js +1505 -0
  104. package/dist/discovery/routes.d.ts +36 -0
  105. package/dist/discovery/routes.js +1494 -0
  106. package/dist/discovery/test-importer.d.ts +92 -0
  107. package/dist/discovery/test-importer.js +4952 -0
  108. package/dist/index.d.ts +123 -0
  109. package/dist/index.js +99 -0
  110. package/dist/ingestors/api-collections.d.ts +28 -0
  111. package/dist/ingestors/api-collections.js +2335 -0
  112. package/dist/ingestors/api-repo.d.ts +2 -1
  113. package/dist/ingestors/api-repo.js +483 -85
  114. package/dist/ingestors/asyncapi.d.ts +26 -0
  115. package/dist/ingestors/asyncapi.js +2105 -0
  116. package/dist/ingestors/bridges.d.ts +2 -0
  117. package/dist/ingestors/bridges.js +702 -0
  118. package/dist/ingestors/cli.d.ts +2 -1
  119. package/dist/ingestors/cli.js +234 -46
  120. package/dist/ingestors/curl.d.ts +14 -0
  121. package/dist/ingestors/curl.js +1024 -0
  122. package/dist/ingestors/graphql.d.ts +56 -0
  123. package/dist/ingestors/graphql.js +1852 -0
  124. package/dist/ingestors/http-file.d.ts +20 -0
  125. package/dist/ingestors/http-file.js +923 -0
  126. package/dist/ingestors/index.js +486 -6
  127. package/dist/ingestors/openrpc.d.ts +29 -0
  128. package/dist/ingestors/openrpc.js +1807 -0
  129. package/dist/ingestors/proto.d.ts +47 -0
  130. package/dist/ingestors/proto.js +2690 -0
  131. package/dist/ingestors/trace.d.ts +10 -0
  132. package/dist/ingestors/trace.js +599 -0
  133. package/dist/ingestors/video.d.ts +4 -1
  134. package/dist/ingestors/video.js +86 -36
  135. package/dist/ingestors/web.d.ts +16 -1
  136. package/dist/ingestors/web.js +474 -32
  137. package/dist/mcp/server.js +3532 -67
  138. package/dist/oracles/api-repo.js +102 -30
  139. package/dist/oracles/cli.js +65 -17
  140. package/dist/oracles/http-workflow.d.ts +68 -0
  141. package/dist/oracles/http-workflow.js +828 -0
  142. package/dist/oracles/image.js +178 -28
  143. package/dist/oracles/index.d.ts +3 -1
  144. package/dist/oracles/index.js +243 -14
  145. package/dist/oracles/perf-budget.d.ts +90 -0
  146. package/dist/oracles/perf-budget.js +1329 -0
  147. package/dist/oracles/stream.d.ts +94 -0
  148. package/dist/oracles/stream.js +1268 -0
  149. package/dist/oracles/ui-states.d.ts +49 -0
  150. package/dist/oracles/ui-states.js +894 -0
  151. package/dist/oracles/video.d.ts +1 -1
  152. package/dist/oracles/video.js +232 -16
  153. package/dist/oracles/web.js +464 -73
  154. package/dist/plugins/builtins.d.ts +12 -0
  155. package/dist/plugins/builtins.js +1052 -0
  156. package/dist/plugins/registry.d.ts +86 -0
  157. package/dist/plugins/registry.js +554 -0
  158. package/dist/setup/index.js +145 -33
  159. package/package.json +56 -47
  160. package/skills/vibecode-anything/SKILL.md +75 -52
@@ -0,0 +1,696 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { diagnoseReport } from "../diagnostics/diagnose.js";
4
+ import { appendTrendEntry } from "../diagnostics/trends.js";
5
+ import { ingest } from "../ingestors/index.js";
6
+ import { redactRuntimeVarsDeep, verifyContract } from "../oracles/index.js";
7
+ import { detectAvailableAgent, invokeAgent, parseAgentSpec } from "./agent-adapter.js";
8
+ import { VibecodeError, toDiagnostic } from "./errors.js";
9
+ import { sha256Text } from "./fs-snapshot.js";
10
+ import { normalizeConcurrency } from "./scheduler.js";
11
+ import { makeDefaultContract, VALID_DOMAINS } from "./schema.js";
12
+ import { isHoldoutResultRecord, redactSensitiveText } from "./security.js";
13
+ import { deriveDefaultSlices } from "./slices.js";
14
+ import { writeSpecFile } from "./spec-writer.js";
15
+ import { ensureDir, readContract, readHoldouts, resolveWorkspace, writeContract, writeLastReport } from "./store.js";
16
+ import { redactRuntimeVars, validateRuntimeVarsObject, validateTargetMapObject } from "./target-map.js";
17
+ import { VALID_VERIFY_MODES } from "./visual-semantic.js";
18
+ const DEFAULT_MAX_ITERATIONS = 10;
19
+ const DEFAULT_MAX_MINUTES = 30;
20
+ const DEFAULT_PLATEAU_LIMIT = 3;
21
+ const DEFAULT_TIMEOUT_MS = 120_000;
22
+ const MAX_DIFF_JSON_CHARS = 1500;
23
+ function sha256File(filePath) {
24
+ if (!fs.existsSync(filePath))
25
+ return null;
26
+ try {
27
+ return sha256Text(fs.readFileSync(filePath, "utf8"));
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ function snapshotProtectedFiles(workspace) {
34
+ return {
35
+ contractHash: sha256File(workspace.contractPath),
36
+ specHash: sha256File(workspace.specPath),
37
+ holdoutsHash: sha256File(workspace.holdoutsPath)
38
+ };
39
+ }
40
+ function detectTamperedFiles(before, workspace) {
41
+ const after = snapshotProtectedFiles(workspace);
42
+ const tampered = [];
43
+ if (before.contractHash !== after.contractHash) {
44
+ tampered.push(".vibecode/contract.json");
45
+ }
46
+ if (before.specHash !== after.specHash) {
47
+ tampered.push(".vibecode/SPEC.md");
48
+ }
49
+ if (before.holdoutsHash !== null && before.holdoutsHash !== after.holdoutsHash) {
50
+ tampered.push("holdout-vault");
51
+ }
52
+ return tampered;
53
+ }
54
+ export function sortSlicesTopologically(slices) {
55
+ if (slices.length <= 1)
56
+ return slices.map((s) => ({ ...s, invariantIds: [...s.invariantIds] }));
57
+ const orderIndex = new Map();
58
+ const byId = new Map();
59
+ slices.forEach((slice, idx) => {
60
+ orderIndex.set(slice.id, idx);
61
+ byId.set(slice.id, slice);
62
+ });
63
+ const inDegree = new Map();
64
+ const dependents = new Map();
65
+ for (const slice of slices) {
66
+ inDegree.set(slice.id, 0);
67
+ dependents.set(slice.id, []);
68
+ }
69
+ for (const slice of slices) {
70
+ const seenDeps = new Set();
71
+ for (const dep of slice.dependsOn ?? []) {
72
+ if (!byId.has(dep) || dep === slice.id || seenDeps.has(dep))
73
+ continue;
74
+ seenDeps.add(dep);
75
+ inDegree.set(slice.id, (inDegree.get(slice.id) ?? 0) + 1);
76
+ dependents.get(dep).push(slice.id);
77
+ }
78
+ }
79
+ const ready = [];
80
+ for (const slice of slices) {
81
+ if ((inDegree.get(slice.id) ?? 0) === 0) {
82
+ ready.push(slice.id);
83
+ }
84
+ }
85
+ const ordered = [];
86
+ const visited = new Set();
87
+ while (ready.length > 0) {
88
+ ready.sort((a, b) => (orderIndex.get(a) ?? 0) - (orderIndex.get(b) ?? 0));
89
+ const currentId = ready.shift();
90
+ if (visited.has(currentId))
91
+ continue;
92
+ visited.add(currentId);
93
+ const slice = byId.get(currentId);
94
+ ordered.push({ ...slice, invariantIds: [...slice.invariantIds] });
95
+ for (const nextId of dependents.get(currentId) ?? []) {
96
+ const nextDeg = (inDegree.get(nextId) ?? 1) - 1;
97
+ inDegree.set(nextId, nextDeg);
98
+ if (nextDeg === 0 && !visited.has(nextId)) {
99
+ ready.push(nextId);
100
+ }
101
+ }
102
+ }
103
+ // Fallback for cyclic graphs: preserve original order for any unvisited slices.
104
+ for (const slice of slices) {
105
+ if (!visited.has(slice.id)) {
106
+ ordered.push({ ...slice, invariantIds: [...slice.invariantIds] });
107
+ }
108
+ }
109
+ return ordered;
110
+ }
111
+ export function resolveHistoryPath(workspaceDir) {
112
+ const workspace = resolveWorkspace(workspaceDir);
113
+ return path.join(workspace.rootDir, ".vibecode", "history.json");
114
+ }
115
+ export function readRunHistory(workspaceDir) {
116
+ const historyPath = resolveHistoryPath(workspaceDir);
117
+ if (!fs.existsSync(historyPath))
118
+ return [];
119
+ try {
120
+ const raw = JSON.parse(fs.readFileSync(historyPath, "utf8"));
121
+ return Array.isArray(raw) ? raw : [];
122
+ }
123
+ catch {
124
+ return [];
125
+ }
126
+ }
127
+ export function writeRunHistory(workspaceDir, entries) {
128
+ const historyPath = resolveHistoryPath(workspaceDir);
129
+ ensureDir(path.dirname(historyPath));
130
+ const tmp = `${historyPath}.tmp`;
131
+ fs.writeFileSync(tmp, JSON.stringify(entries, null, 2) + "\n", "utf8");
132
+ fs.renameSync(tmp, historyPath);
133
+ return historyPath;
134
+ }
135
+ function resolvePlannedSlices(contract, holdoutIds, requestedSliceIds) {
136
+ const visibleIds = contract.invariants.filter((inv) => !holdoutIds.has(inv.id)).map((inv) => inv.id);
137
+ const visibleSet = new Set(visibleIds);
138
+ let baseSlices;
139
+ if (Array.isArray(contract.slices) && contract.slices.length > 0) {
140
+ baseSlices = contract.slices.map((s) => ({
141
+ ...s,
142
+ invariantIds: s.invariantIds.filter((id) => visibleSet.has(id))
143
+ }));
144
+ }
145
+ else {
146
+ const derived = deriveDefaultSlices({
147
+ ...contract,
148
+ invariants: contract.invariants.filter((inv) => !holdoutIds.has(inv.id))
149
+ });
150
+ baseSlices =
151
+ derived.length > 0
152
+ ? derived
153
+ : [
154
+ {
155
+ id: "all",
156
+ title: "All Invariants",
157
+ invariantIds: visibleIds,
158
+ status: "pending"
159
+ }
160
+ ];
161
+ }
162
+ let selected = baseSlices;
163
+ if (Array.isArray(requestedSliceIds) && requestedSliceIds.length > 0) {
164
+ const normalizedIds = requestedSliceIds.map((s) => s.trim()).filter((s) => s.length > 0);
165
+ if (normalizedIds.length > 0) {
166
+ const byId = new Map(baseSlices.map((s) => [s.id, s]));
167
+ const unknown = normalizedIds.filter((id) => !byId.has(id));
168
+ if (unknown.length > 0) {
169
+ const valid = baseSlices.map((s) => s.id);
170
+ throw new VibecodeError("NOT_FOUND", `Unknown slice id(s): ${unknown.join(", ")}. Valid slice ids: ${valid.length > 0 ? valid.join(", ") : "(none)"}`, { details: { unknown, valid } });
171
+ }
172
+ const uniqueIds = [...new Set(normalizedIds)];
173
+ selected = uniqueIds.map((id) => byId.get(id));
174
+ }
175
+ }
176
+ return sortSlicesTopologically(selected);
177
+ }
178
+ function isFailingResult(result, strict) {
179
+ if (result.status === "fail" || result.status === "error")
180
+ return true;
181
+ if (strict && result.status === "warn")
182
+ return true;
183
+ return false;
184
+ }
185
+ function scrubRunText(text, vars) {
186
+ return vars && Object.keys(vars).length > 0 ? redactRuntimeVars(text, vars) : redactSensitiveText(text);
187
+ }
188
+ function scrubTargetMapForDisplay(targets, vars) {
189
+ if (!targets)
190
+ return undefined;
191
+ const out = {};
192
+ for (const [k, v] of Object.entries(targets)) {
193
+ if (typeof v === "string" && v.trim().length > 0) {
194
+ out[k] = scrubRunText(v, vars);
195
+ }
196
+ }
197
+ return Object.keys(out).length > 0 ? out : undefined;
198
+ }
199
+ function attachVisibleReproCommands(report, target, targets, strict, holdoutIds, vars) {
200
+ const safeTarget = target.trim() ? scrubRunText(target, vars) : "";
201
+ const safeTargetMapFlag = !safeTarget && targets
202
+ ? Object.entries(scrubTargetMapForDisplay(targets, vars) ?? {})
203
+ .map(([d, t]) => `--target-map "${String(d)}=${String(t).replace(/"/g, '\\"')}"`)
204
+ .join(" ")
205
+ : "";
206
+ const targetFlag = safeTarget
207
+ ? `--target "${safeTarget.replace(/"/g, '\\"')}"`
208
+ : safeTargetMapFlag;
209
+ const strictSuffix = strict ? " --strict" : "";
210
+ for (const r of report.results || []) {
211
+ if (r.metrics?.redacted === true || holdoutIds.has(r.id)) {
212
+ if ("repro" in r)
213
+ delete r.repro;
214
+ continue;
215
+ }
216
+ if ((r.status === "fail" || r.status === "error") && targetFlag) {
217
+ r.repro = `vibecode-anything verify ${targetFlag} --invariant ${r.id}${strictSuffix}`;
218
+ }
219
+ }
220
+ }
221
+ function extractDiffPngPaths(report, holdoutIds) {
222
+ const paths = [];
223
+ const seen = new Set();
224
+ const add = (value) => {
225
+ if (typeof value === "string" && value.trim().length > 0 && !seen.has(value)) {
226
+ seen.add(value);
227
+ paths.push(value);
228
+ }
229
+ };
230
+ for (const r of report.results || []) {
231
+ if (r.metrics?.redacted === true || holdoutIds.has(r.id))
232
+ continue;
233
+ add(r.metrics?.diffPng);
234
+ add(r.metrics?.diffPngPath);
235
+ add(r.diff?.diffPng);
236
+ add(r.diff?.diffPath);
237
+ }
238
+ return paths;
239
+ }
240
+ function formatDiffSummary(diff, vars) {
241
+ if (!diff || Object.keys(diff).length === 0)
242
+ return undefined;
243
+ const golden = diff.goldenStdout;
244
+ if (golden && typeof golden.unified === "string" && golden.unified.trim().length > 0) {
245
+ const clean = scrubRunText(golden.unified, vars);
246
+ return clean.slice(0, MAX_DIFF_JSON_CHARS);
247
+ }
248
+ try {
249
+ const serialized = JSON.stringify(diff, null, 2);
250
+ if (!serialized || serialized === "{}")
251
+ return undefined;
252
+ const clean = scrubRunText(serialized, vars);
253
+ return clean.length > MAX_DIFF_JSON_CHARS
254
+ ? `${clean.slice(0, MAX_DIFF_JSON_CHARS)}\n... [truncated]`
255
+ : clean;
256
+ }
257
+ catch {
258
+ return undefined;
259
+ }
260
+ }
261
+ function buildFailingSummary(report, holdoutIds, strict, vars) {
262
+ const summary = [];
263
+ for (const r of report.results || []) {
264
+ if (!isFailingResult(r, strict))
265
+ continue;
266
+ const isRedacted = holdoutIds.has(r.id) || r.metrics?.redacted === true;
267
+ if (isRedacted) {
268
+ summary.push({
269
+ id: r.id,
270
+ severity: r.severity,
271
+ status: r.status,
272
+ failures: r.failures && r.failures.length > 0
273
+ ? r.failures.map((f) => scrubRunText(f, vars))
274
+ : ["Holdout invariant failed (expected details redacted)"]
275
+ });
276
+ continue;
277
+ }
278
+ const diffSummary = formatDiffSummary(r.diff, vars);
279
+ summary.push({
280
+ id: r.id,
281
+ severity: r.severity,
282
+ status: r.status,
283
+ failures: r.failures && r.failures.length > 0
284
+ ? r.failures.map((f) => scrubRunText(f, vars))
285
+ : [scrubRunText(r.reason || "Invariant failed", vars)],
286
+ ...(r.repro ? { repro: scrubRunText(r.repro, vars) } : {}),
287
+ ...(diffSummary ? { diffSummary } : {})
288
+ });
289
+ }
290
+ return summary;
291
+ }
292
+ function buildHistoryEntry(iteration, report, durationMs, strict, holdoutIds, sliceId, agent) {
293
+ const failingInvariantIds = (report.results || [])
294
+ .filter((r) => isFailingResult(r, strict))
295
+ .map((r) => r.id);
296
+ const diffPngPaths = extractDiffPngPaths(report, holdoutIds);
297
+ return {
298
+ iteration,
299
+ ...(sliceId ? { sliceId } : {}),
300
+ ...(agent ? { agent } : {}),
301
+ timestamp: report.timestamp || new Date().toISOString(),
302
+ durationMs,
303
+ parity: report.parity,
304
+ compositeScore: report.compositeScore,
305
+ hardPassed: report.hard.passed,
306
+ hardTotal: report.hard.total,
307
+ gateStatus: report.gate.status,
308
+ failingInvariantIds,
309
+ ...(diffPngPaths.length > 0 ? { diffPngPaths } : {})
310
+ };
311
+ }
312
+ function isStagnant(previous, current) {
313
+ if (current.compositeScore > previous.compositeScore + 1e-9)
314
+ return false;
315
+ if (current.hardPassed > previous.hardPassed)
316
+ return false;
317
+ if (previous.failingInvariantIds.length !== current.failingInvariantIds.length)
318
+ return false;
319
+ const prevSorted = [...previous.failingInvariantIds].sort();
320
+ const currSorted = [...current.failingInvariantIds].sort();
321
+ for (let i = 0; i < prevSorted.length; i++) {
322
+ if (prevSorted[i] !== currSorted[i])
323
+ return false;
324
+ }
325
+ return true;
326
+ }
327
+ function validateOptions(options) {
328
+ const target = typeof options.target === "string" ? options.target.trim() : "";
329
+ const targets = options.targets !== undefined ? validateTargetMapObject(options.targets) : undefined;
330
+ const hasTargets = Boolean(targets && Object.keys(targets).length > 0);
331
+ if (!target && !hasTargets) {
332
+ throw new VibecodeError("TARGET_MISSING", "Missing target (or targets map) for closed-loop run.");
333
+ }
334
+ const vars = options.vars !== undefined ? validateRuntimeVarsObject(options.vars) : undefined;
335
+ if (options.mode !== undefined && !VALID_VERIFY_MODES.has(options.mode)) {
336
+ throw new VibecodeError("CONFIG_INVALID", `Invalid verify mode: ${String(options.mode)} (expected one of ${[...VALID_VERIFY_MODES].join(", ")})`);
337
+ }
338
+ const concurrency = options.concurrency !== undefined ? normalizeConcurrency(options.concurrency) : undefined;
339
+ const maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS;
340
+ if (!Number.isInteger(maxIterations) || maxIterations < 1) {
341
+ throw new VibecodeError("CONTRACT_INVALID", `maxIterations must be an integer >= 1 (got ${String(options.maxIterations)}).`);
342
+ }
343
+ const maxMinutes = options.maxMinutes ?? DEFAULT_MAX_MINUTES;
344
+ if (typeof maxMinutes !== "number" || !Number.isFinite(maxMinutes) || maxMinutes <= 0) {
345
+ throw new VibecodeError("CONTRACT_INVALID", `maxMinutes must be a positive number (got ${String(options.maxMinutes)}).`);
346
+ }
347
+ const plateauLimit = options.plateauLimit ?? DEFAULT_PLATEAU_LIMIT;
348
+ if (!Number.isInteger(plateauLimit) || plateauLimit < 1) {
349
+ throw new VibecodeError("CONTRACT_INVALID", `plateauLimit must be an integer >= 1 (got ${String(options.plateauLimit)}).`);
350
+ }
351
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
352
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
353
+ throw new VibecodeError("CONTRACT_INVALID", `timeoutMs must be a positive number (got ${String(options.timeoutMs)}).`);
354
+ }
355
+ return {
356
+ target,
357
+ ...(hasTargets ? { targets } : {}),
358
+ ...(vars ? { vars } : {}),
359
+ ...(options.mode !== undefined ? { mode: options.mode } : {}),
360
+ ...(concurrency !== undefined ? { concurrency } : {}),
361
+ maxIterations,
362
+ maxMinutes,
363
+ plateauLimit,
364
+ timeoutMs
365
+ };
366
+ }
367
+ export async function runClosedLoop(options, deps = {}) {
368
+ const { target, targets, vars, mode, concurrency, maxIterations, maxMinutes, plateauLimit, timeoutMs } = validateOptions(options);
369
+ const parsedAgent = parseAgentSpec(options.agent);
370
+ const workspace = resolveWorkspace(options.cwd ?? process.cwd());
371
+ const historyPath = resolveHistoryPath(workspace.rootDir);
372
+ const strict = Boolean(options.strict);
373
+ const dryRun = Boolean(options.dryRun);
374
+ const detectFn = deps.detectAgent ?? ((pref) => detectAvailableAgent(pref));
375
+ if (options.source && !dryRun && (options.forceIngest || !fs.existsSync(workspace.contractPath))) {
376
+ const ingestResult = await ingest({
377
+ source: options.source,
378
+ ...(options.domain ? { domain: options.domain } : {}),
379
+ cwd: workspace.rootDir,
380
+ ...(options.headers ? { headers: options.headers } : {}),
381
+ ...(options.storageState ? { storageState: options.storageState } : {})
382
+ }, deps.ingestDeps ?? {});
383
+ const contractName = path.basename(workspace.rootDir) || path.basename(options.source) || "unknown";
384
+ const built = makeDefaultContract({
385
+ name: contractName,
386
+ domain: ingestResult.domain,
387
+ source: options.source
388
+ });
389
+ const invDomains = ingestResult.invariants.map((i) => i.domain).filter((d) => VALID_DOMAINS.has(d));
390
+ built.target.domains = [...new Set([ingestResult.domain, ...invDomains].filter((d) => VALID_DOMAINS.has(d)))];
391
+ built.target.sources = ingestResult.sources;
392
+ built.artifacts = ingestResult.artifacts;
393
+ built.invariants = ingestResult.invariants;
394
+ writeContract(built, workspace.rootDir, { force: Boolean(options.forceIngest), replaceHoldouts: true });
395
+ const holdoutCount = ingestResult.invariants.filter((i) => i.holdout === true).length;
396
+ writeSpecFile(workspace.rootDir, { contract: built, holdoutCount });
397
+ }
398
+ const contract = readContract(workspace.rootDir);
399
+ const holdouts = readHoldouts(workspace.rootDir);
400
+ const holdoutIds = new Set([
401
+ ...holdouts.map((inv) => inv.id),
402
+ ...contract.invariants.filter((inv) => inv.holdout === true).map((inv) => inv.id)
403
+ ]);
404
+ const orderedSlices = resolvePlannedSlices(contract, holdoutIds, options.sliceIds);
405
+ const plannedSlices = orderedSlices.map((s) => ({
406
+ id: s.id,
407
+ title: s.title,
408
+ invariantIds: [...s.invariantIds]
409
+ }));
410
+ let resolvedAgentName = parsedAgent.kind === "mock" ? "mock" : (detectFn(parsedAgent.kind) ?? parsedAgent.kind);
411
+ if (dryRun) {
412
+ return {
413
+ ok: true,
414
+ dryRun: true,
415
+ agent: resolvedAgentName,
416
+ specPath: workspace.specPath,
417
+ historyPath,
418
+ iterations: [],
419
+ plannedSlices,
420
+ finalReport: null,
421
+ stoppedReason: "dry_run"
422
+ };
423
+ }
424
+ if (!fs.existsSync(workspace.specPath)) {
425
+ writeSpecFile(workspace.rootDir, { contract, holdoutCount: holdouts.length });
426
+ }
427
+ const iterations = [];
428
+ const deadlineMs = Date.now() + maxMinutes * 60_000;
429
+ let agentAttempts = 0;
430
+ let lastRecordedInvariantCount = -1;
431
+ const safeTargetsForPrompt = scrubTargetMapForDisplay(targets, vars);
432
+ const safeDisplayTarget = target
433
+ ? scrubRunText(target, vars)
434
+ : safeTargetsForPrompt
435
+ ? JSON.stringify(safeTargetsForPrompt)
436
+ : "";
437
+ const verifyScope = async (invariantIds) => {
438
+ const started = Date.now();
439
+ const ctx = {
440
+ target,
441
+ ...(targets ? { targets } : {}),
442
+ ...(vars ? { vars } : {}),
443
+ ...(mode !== undefined ? { mode } : {}),
444
+ ...(concurrency !== undefined ? { concurrency } : {}),
445
+ ...(options.skipFixtures ? { skipFixtures: true } : {}),
446
+ ...(options.allowFixtureCommands ? { allowFixtureCommands: true } : {}),
447
+ ...(options.pluginRegistry ? { pluginRegistry: options.pluginRegistry } : {}),
448
+ cwd: workspace.rootDir,
449
+ contract,
450
+ artifactsDir: workspace.artifactsDir,
451
+ cacheDir: workspace.cacheDir,
452
+ strict,
453
+ revealHoldouts: false,
454
+ ...(options.useCache ? { useCache: true } : {}),
455
+ ...(invariantIds && invariantIds.length > 0 ? { invariantIds } : {}),
456
+ ...(options.headers ? { headers: options.headers } : {}),
457
+ ...(options.storageState ? { storageState: options.storageState } : {}),
458
+ runtimeCache: {}
459
+ };
460
+ const report = await verifyContract(contract, ctx, deps.verifyDeps ?? {});
461
+ attachVisibleReproCommands(report, target, targets, strict, holdoutIds, vars);
462
+ return { report, durationMs: Date.now() - started };
463
+ };
464
+ const persistState = (reportToSave, stoppedReason) => {
465
+ if (iterations.length > 0) {
466
+ writeRunHistory(workspace.rootDir, iterations);
467
+ }
468
+ if (reportToSave) {
469
+ writeLastReport(reportToSave, workspace.rootDir);
470
+ if (options.recordTrends !== false && stoppedReason !== "contract_tampered") {
471
+ try {
472
+ const activeHoldoutIds = new Set(holdoutIds);
473
+ try {
474
+ for (const h of readHoldouts(workspace.rootDir)) {
475
+ activeHoldoutIds.add(h.id);
476
+ }
477
+ }
478
+ catch {
479
+ // Keep preloaded holdoutIds if vault cannot be re-read.
480
+ }
481
+ const reportForTrends = activeHoldoutIds.size > 0
482
+ ? {
483
+ ...reportToSave,
484
+ results: (reportToSave.results || []).map((r) => activeHoldoutIds.has(r.id) || isHoldoutResultRecord(r)
485
+ ? { ...r, metrics: { ...(r.metrics ?? {}), holdout: true, redacted: true } }
486
+ : r)
487
+ }
488
+ : reportToSave;
489
+ const safeReportForTrends = vars ? redactRuntimeVarsDeep(reportForTrends, vars) : reportForTrends;
490
+ appendTrendEntry(workspace.rootDir, safeReportForTrends, {
491
+ ...(mode !== undefined ? { mode } : {})
492
+ });
493
+ }
494
+ catch {
495
+ // Non-fatal if workspace trends path is disallowed or inaccessible.
496
+ }
497
+ }
498
+ }
499
+ };
500
+ const makeStopResult = (stoppedReason, ok, reportToSave, extra = {}) => {
501
+ persistState(reportToSave, stoppedReason);
502
+ return {
503
+ ok,
504
+ dryRun: false,
505
+ agent: resolvedAgentName,
506
+ specPath: workspace.specPath,
507
+ historyPath,
508
+ iterations,
509
+ plannedSlices,
510
+ finalReport: reportToSave,
511
+ stoppedReason,
512
+ ...(extra.tamperedFiles ? { tamperedFiles: extra.tamperedFiles } : {}),
513
+ ...(extra.diagnostic ? { diagnostic: extra.diagnostic } : {})
514
+ };
515
+ };
516
+ const runRefinementLoop = async (initialReport, initialDurationMs, scopeInvariantIds, sliceId, recordInitialEntry) => {
517
+ let currentReport = initialReport;
518
+ let prevEntry;
519
+ if (recordInitialEntry) {
520
+ prevEntry = buildHistoryEntry(iterations.length + 1, currentReport, initialDurationMs, strict, holdoutIds, sliceId);
521
+ iterations.push(prevEntry);
522
+ lastRecordedInvariantCount = currentReport.total;
523
+ writeRunHistory(workspace.rootDir, iterations);
524
+ }
525
+ else {
526
+ prevEntry = iterations[iterations.length - 1];
527
+ }
528
+ let plateauCount = 0;
529
+ while (!currentReport.gate.passed) {
530
+ if (Date.now() >= deadlineMs) {
531
+ return {
532
+ passed: false,
533
+ report: currentReport,
534
+ stopResult: makeStopResult("max_minutes", false, currentReport)
535
+ };
536
+ }
537
+ if (agentAttempts >= maxIterations) {
538
+ return {
539
+ passed: false,
540
+ report: currentReport,
541
+ stopResult: makeStopResult("max_iterations", false, currentReport)
542
+ };
543
+ }
544
+ agentAttempts += 1;
545
+ const beforeHashes = snapshotProtectedFiles(workspace);
546
+ let diagnosisBrief;
547
+ try {
548
+ const diag = await diagnoseReport(currentReport, {
549
+ contract,
550
+ cwd: workspace.rootDir,
551
+ includeVisualHeatmap: false,
552
+ maxBriefChars: 1200
553
+ });
554
+ if (diag.repairBrief && diag.repairBrief.trim()) {
555
+ diagnosisBrief = scrubRunText(diag.repairBrief, vars);
556
+ }
557
+ }
558
+ catch {
559
+ // Non-fatal: proceed with failingSummary only.
560
+ }
561
+ const invokeCtx = {
562
+ workspaceDir: workspace.rootDir,
563
+ specPath: workspace.specPath,
564
+ target: safeDisplayTarget,
565
+ ...(safeTargetsForPrompt ? { targets: safeTargetsForPrompt } : {}),
566
+ ...(sliceId ? { sliceId } : {}),
567
+ iteration: agentAttempts,
568
+ maxIterations,
569
+ failingSummary: buildFailingSummary(currentReport, holdoutIds, strict, vars),
570
+ ...(diagnosisBrief ? { diagnosisBrief } : {})
571
+ };
572
+ let agentResult;
573
+ try {
574
+ agentResult = await invokeAgent(parsedAgent, invokeCtx, {
575
+ timeoutMs,
576
+ commandRunner: deps.commandRunner,
577
+ detectAgent: deps.detectAgent
578
+ });
579
+ }
580
+ catch (err) {
581
+ const diag = toDiagnostic(err);
582
+ if (diag.code === "ADAPTER_MISSING") {
583
+ return {
584
+ passed: false,
585
+ report: currentReport,
586
+ stopResult: makeStopResult("adapter_missing", false, currentReport, { diagnostic: diag })
587
+ };
588
+ }
589
+ throw err;
590
+ }
591
+ resolvedAgentName = agentResult.agent;
592
+ const tamperedFiles = detectTamperedFiles(beforeHashes, workspace);
593
+ if (tamperedFiles.length > 0) {
594
+ return {
595
+ passed: false,
596
+ report: currentReport,
597
+ stopResult: makeStopResult("contract_tampered", false, currentReport, {
598
+ tamperedFiles,
599
+ diagnostic: {
600
+ code: "CONTRACT_TAMPERED",
601
+ message: `Contract integrity violation: agent modified protected file(s): ${tamperedFiles.join(", ")}`,
602
+ details: { tamperedFiles }
603
+ }
604
+ })
605
+ };
606
+ }
607
+ if (agentResult.quotaExceeded) {
608
+ return {
609
+ passed: false,
610
+ report: currentReport,
611
+ stopResult: makeStopResult("quota_exceeded", false, currentReport, {
612
+ diagnostic: {
613
+ code: "QUOTA_EXCEEDED",
614
+ message: `Agent "${agentResult.agent}" stopped due to quota or rate limit.`,
615
+ details: {
616
+ exitCode: agentResult.exitCode,
617
+ stderr: scrubRunText(agentResult.stderr.slice(0, 500), vars)
618
+ }
619
+ }
620
+ })
621
+ };
622
+ }
623
+ if (!agentResult.ok) {
624
+ return {
625
+ passed: false,
626
+ report: currentReport,
627
+ stopResult: makeStopResult("agent_error", false, currentReport, {
628
+ diagnostic: {
629
+ code: agentResult.timedOut ? "EXEC_TIMEOUT" : "EXEC_ERROR",
630
+ message: agentResult.timedOut
631
+ ? `Agent "${agentResult.agent}" timed out after ${timeoutMs}ms.`
632
+ : `Agent "${agentResult.agent}" exited with code ${String(agentResult.exitCode)}.`,
633
+ details: {
634
+ exitCode: agentResult.exitCode,
635
+ stderr: scrubRunText(agentResult.stderr.slice(0, 500), vars)
636
+ }
637
+ }
638
+ })
639
+ };
640
+ }
641
+ const nextCheck = await verifyScope(scopeInvariantIds);
642
+ currentReport = nextCheck.report;
643
+ const nextEntry = buildHistoryEntry(iterations.length + 1, currentReport, nextCheck.durationMs + agentResult.durationMs, strict, holdoutIds, sliceId, resolvedAgentName);
644
+ iterations.push(nextEntry);
645
+ lastRecordedInvariantCount = currentReport.total;
646
+ writeRunHistory(workspace.rootDir, iterations);
647
+ if (currentReport.gate.passed) {
648
+ return { passed: true, report: currentReport };
649
+ }
650
+ if (isStagnant(prevEntry, nextEntry)) {
651
+ plateauCount += 1;
652
+ }
653
+ else {
654
+ plateauCount = 0;
655
+ }
656
+ prevEntry = nextEntry;
657
+ if (plateauCount >= plateauLimit) {
658
+ return {
659
+ passed: false,
660
+ report: currentReport,
661
+ stopResult: makeStopResult("plateau", false, currentReport)
662
+ };
663
+ }
664
+ }
665
+ return { passed: true, report: currentReport };
666
+ };
667
+ for (const slice of orderedSlices) {
668
+ if (slice.invariantIds.length === 0)
669
+ continue;
670
+ const initial = await verifyScope(slice.invariantIds);
671
+ if (initial.report.gate.passed) {
672
+ continue;
673
+ }
674
+ const sliceOutcome = await runRefinementLoop(initial.report, initial.durationMs, slice.invariantIds, slice.id, true);
675
+ if (sliceOutcome.stopResult) {
676
+ return sliceOutcome.stopResult;
677
+ }
678
+ }
679
+ // Final full verification across all invariants (visible + holdouts).
680
+ const finalCheck = await verifyScope(undefined);
681
+ let finalReport = finalCheck.report;
682
+ const shouldRecordFinal = iterations.length === 0 || !finalReport.gate.passed || finalReport.total !== lastRecordedInvariantCount;
683
+ if (shouldRecordFinal) {
684
+ iterations.push(buildHistoryEntry(iterations.length + 1, finalReport, finalCheck.durationMs, strict, holdoutIds));
685
+ lastRecordedInvariantCount = finalReport.total;
686
+ writeRunHistory(workspace.rootDir, iterations);
687
+ }
688
+ if (!finalReport.gate.passed) {
689
+ const finalOutcome = await runRefinementLoop(finalReport, finalCheck.durationMs, undefined, undefined, false);
690
+ if (finalOutcome.stopResult) {
691
+ return finalOutcome.stopResult;
692
+ }
693
+ finalReport = finalOutcome.report;
694
+ }
695
+ return makeStopResult("passed", true, finalReport);
696
+ }