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,312 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { VibecodeError } from "./errors.js";
5
+ import { spawnBoundedCommand } from "./exec.js";
6
+ import { redactSensitiveText } from "./security.js";
7
+ export const CLI_AGENT_ORDER = ["claude", "codex", "agy", "opencode"];
8
+ export const QUOTA_EXCEEDED_RE = /quota\s*exceeded|rate\s*limit|free\s*usage\s*limit|429\b|too\s*many\s*requests/i;
9
+ const MAX_DIFF_SUMMARY_CHARS = 1500;
10
+ const MAX_DIAGNOSIS_BRIEF_CHARS = 1500;
11
+ const DEFAULT_TIMEOUT_MS = 120_000;
12
+ const INSTALL_HINTS = {
13
+ claude: "Install Claude Code CLI: npm install -g @anthropic-ai/claude-code",
14
+ codex: "Install OpenAI Codex CLI: npm install -g @openai/codex",
15
+ agy: "Install Antigravity CLI (agy) and ensure it is on PATH",
16
+ opencode: "Install OpenCode CLI: npm install -g opencode-ai"
17
+ };
18
+ const ALL_AGENTS_INSTALL_HINT = "Install a supported coding-agent CLI (claude, codex, agy, or opencode) or pass --agent mock:<script> for offline testing. " +
19
+ "Examples: npm install -g @anthropic-ai/claude-code | npm install -g @openai/codex";
20
+ function isCliAgentKind(value) {
21
+ return value === "claude" || value === "codex" || value === "agy" || value === "opencode";
22
+ }
23
+ function getPathEnvValue(env, platform) {
24
+ if (platform === "win32") {
25
+ let resolved = "";
26
+ for (const key of Object.keys(env)) {
27
+ if (key.toLowerCase() === "path" && env[key]) {
28
+ resolved = env[key];
29
+ }
30
+ }
31
+ return resolved;
32
+ }
33
+ return env.PATH ?? "";
34
+ }
35
+ function getPathExtList(env) {
36
+ let raw = ".COM;.EXE;.BAT;.CMD";
37
+ for (const key of Object.keys(env)) {
38
+ if (key.toLowerCase() === "pathext" && env[key]) {
39
+ raw = env[key];
40
+ }
41
+ }
42
+ const exts = raw
43
+ .split(";")
44
+ .map((e) => e.trim())
45
+ .filter((e) => e.length > 0)
46
+ .map((e) => (e.startsWith(".") ? e.toLowerCase() : `.${e.toLowerCase()}`));
47
+ return exts.length > 0 ? exts : [".exe", ".cmd", ".bat", ".com"];
48
+ }
49
+ function isRegularFile(filePath) {
50
+ try {
51
+ return fs.statSync(filePath).isFile();
52
+ }
53
+ catch {
54
+ return false;
55
+ }
56
+ }
57
+ export function findExecutableInPath(name, env = process.env, platform = process.platform) {
58
+ const pathVal = getPathEnvValue(env, platform);
59
+ if (!pathVal)
60
+ return null;
61
+ const sep = platform === "win32" ? ";" : ":";
62
+ const dirs = pathVal
63
+ .split(sep)
64
+ .map((d) => d.trim().replace(/^"(.*)"$/, "$1"))
65
+ .filter((d) => d.length > 0);
66
+ if (platform === "win32") {
67
+ const exts = getPathExtList(env);
68
+ const hasKnownExt = exts.some((ext) => name.toLowerCase().endsWith(ext));
69
+ for (const dir of dirs) {
70
+ if (hasKnownExt) {
71
+ const exact = path.win32.join(dir, name);
72
+ if (isRegularFile(exact))
73
+ return exact;
74
+ }
75
+ else {
76
+ for (const ext of exts) {
77
+ const candidate = path.win32.join(dir, `${name}${ext}`);
78
+ if (isRegularFile(candidate))
79
+ return candidate;
80
+ }
81
+ }
82
+ }
83
+ return null;
84
+ }
85
+ for (const dir of dirs) {
86
+ const candidate = path.posix.join(dir, name);
87
+ if (!isRegularFile(candidate))
88
+ continue;
89
+ try {
90
+ fs.accessSync(candidate, fs.constants.X_OK);
91
+ return candidate;
92
+ }
93
+ catch {
94
+ // Not executable; keep scanning PATH.
95
+ }
96
+ }
97
+ return null;
98
+ }
99
+ export function parseAgentSpec(spec) {
100
+ if (spec === undefined || spec === null || !spec.trim()) {
101
+ return { kind: "auto" };
102
+ }
103
+ const trimmed = spec.trim();
104
+ if (/^mock:/i.test(trimmed)) {
105
+ const mockScript = trimmed.slice(5).trim();
106
+ if (!mockScript) {
107
+ throw new VibecodeError("CONTRACT_INVALID", "Mock agent spec must include a script path: mock:<script>");
108
+ }
109
+ return { kind: "mock", mockScript };
110
+ }
111
+ const lower = trimmed.toLowerCase();
112
+ if (lower === "auto")
113
+ return { kind: "auto" };
114
+ if (isCliAgentKind(lower))
115
+ return { kind: lower };
116
+ if (lower === "mock") {
117
+ throw new VibecodeError("CONTRACT_INVALID", "Mock agent requires a script path: mock:<script>");
118
+ }
119
+ throw new VibecodeError("CONTRACT_INVALID", `Unsupported agent "${trimmed}". Expected one of: auto, claude, codex, agy, opencode, mock:<script>.`);
120
+ }
121
+ export function detectAvailableAgent(preferred, options = {}) {
122
+ if (preferred === "mock")
123
+ return "mock";
124
+ const env = options.env ?? process.env;
125
+ const platform = options.platform ?? process.platform;
126
+ const probe = options.probeCommand ?? ((cmd) => findExecutableInPath(cmd, env, platform) !== null);
127
+ if (preferred && preferred !== "auto") {
128
+ return probe(preferred) ? preferred : null;
129
+ }
130
+ for (const candidate of CLI_AGENT_ORDER) {
131
+ if (probe(candidate))
132
+ return candidate;
133
+ }
134
+ return null;
135
+ }
136
+ function sanitizePromptText(text) {
137
+ return redactSensitiveText(text);
138
+ }
139
+ function escapeFences(text) {
140
+ return text.replace(/`{3,}/g, (match) => match.split("").join(" "));
141
+ }
142
+ function formatSpecDisplayPath(workspaceDir, specPath) {
143
+ const rel = path.relative(path.resolve(workspaceDir), path.resolve(specPath)).replace(/\\/g, "/");
144
+ if (rel && !rel.startsWith("..") && !path.isAbsolute(rel)) {
145
+ return sanitizePromptText(rel);
146
+ }
147
+ return ".vibecode/SPEC.md";
148
+ }
149
+ export function buildGoldfishPrompt(ctx) {
150
+ const displaySpecPath = formatSpecDisplayPath(ctx.workspaceDir, ctx.specPath);
151
+ const safeTarget = sanitizePromptText(ctx.target);
152
+ const lines = [
153
+ `# Vibecode Closed-Loop Fix Task (Iteration ${ctx.iteration}/${ctx.maxIterations})`,
154
+ "",
155
+ `- Specification: \`${displaySpecPath}\``,
156
+ `- Target: \`${safeTarget}\``
157
+ ];
158
+ if (ctx.targets && typeof ctx.targets === "object") {
159
+ const entries = Object.entries(ctx.targets).filter(([, val]) => typeof val === "string" && val.trim().length > 0);
160
+ if (entries.length > 0) {
161
+ const formatted = entries.map(([dom, val]) => `${dom}=${sanitizePromptText(val)}`).join(", ");
162
+ lines.push(`- Targets: \`${formatted}\``);
163
+ }
164
+ }
165
+ if (ctx.sliceId) {
166
+ lines.push(`- Active Slice: \`${sanitizePromptText(ctx.sliceId)}\``);
167
+ }
168
+ lines.push("", "## Rules", `- Read \`${displaySpecPath}\` as the single source of truth for required behavior.`, "- Fix ONLY the target implementation so all failing invariants below pass.", "- Do NOT modify `.vibecode/contract.json`, `.vibecode/SPEC.md`, or `.vibecode/history.json`.", "- Do NOT search for or attempt to access holdout tests outside this workspace.", "- Implement general specification-compliant behavior; do not hardcode specific test outputs.");
169
+ if (typeof ctx.diagnosisBrief === "string" && ctx.diagnosisBrief.trim().length > 0) {
170
+ const cleanBrief = sanitizePromptText(ctx.diagnosisBrief).replace(/\r\n?/g, "\n").trim();
171
+ const boundedBrief = cleanBrief.length > MAX_DIAGNOSIS_BRIEF_CHARS
172
+ ? `${cleanBrief.slice(0, MAX_DIAGNOSIS_BRIEF_CHARS)}\n... [truncated]`
173
+ : cleanBrief;
174
+ lines.push("", "## Root-Cause Triage Brief", "```text", escapeFences(boundedBrief), "```");
175
+ }
176
+ lines.push("", "## Failing Invariants");
177
+ if (ctx.failingSummary.length === 0) {
178
+ lines.push("No failing invariants reported.");
179
+ }
180
+ else {
181
+ for (const item of ctx.failingSummary) {
182
+ lines.push("", `### ${sanitizePromptText(item.id)} (${item.severity} | ${item.status})`);
183
+ const failures = item.failures.length > 0 ? item.failures : ["Invariant failed"];
184
+ for (const failure of failures) {
185
+ lines.push(`- ${sanitizePromptText(failure)}`);
186
+ }
187
+ if (item.repro && !/\.vibecode-vault|holdouts\.json/i.test(item.repro)) {
188
+ lines.push(`- Repro: \`${sanitizePromptText(item.repro)}\``);
189
+ }
190
+ if (item.diffSummary && item.diffSummary.trim().length > 0) {
191
+ const sanitizedDiff = sanitizePromptText(item.diffSummary).replace(/\r\n?/g, "\n");
192
+ const truncated = sanitizedDiff.length > MAX_DIFF_SUMMARY_CHARS
193
+ ? `${sanitizedDiff.slice(0, MAX_DIFF_SUMMARY_CHARS)}\n... [truncated]`
194
+ : sanitizedDiff;
195
+ lines.push("- Diff:");
196
+ lines.push("```text");
197
+ lines.push(escapeFences(truncated));
198
+ lines.push("```");
199
+ }
200
+ }
201
+ }
202
+ return `${lines.join("\n")}\n`;
203
+ }
204
+ export function buildAgentCliArgs(agent, prompt) {
205
+ switch (agent) {
206
+ case "claude":
207
+ return ["-p", prompt];
208
+ case "codex":
209
+ return ["exec", prompt];
210
+ case "agy":
211
+ return ["-p", prompt];
212
+ case "opencode":
213
+ return ["run", prompt];
214
+ }
215
+ }
216
+ export async function defaultAgentCommandRunner(input) {
217
+ return spawnBoundedCommand(input.command, input.args, {
218
+ cwd: input.cwd,
219
+ env: input.env,
220
+ stdin: input.stdin,
221
+ timeoutMs: input.timeoutMs,
222
+ shell: false,
223
+ flattenWindowsCmdNewlines: true
224
+ });
225
+ }
226
+ function detectQuotaExceeded(result) {
227
+ if (QUOTA_EXCEEDED_RE.test(result.stderr))
228
+ return true;
229
+ if (result.exitCode !== 0 && QUOTA_EXCEEDED_RE.test(result.stdout))
230
+ return true;
231
+ return false;
232
+ }
233
+ export async function invokeAgent(spec, ctx, options = {}) {
234
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
235
+ const runner = options.commandRunner ?? defaultAgentCommandRunner;
236
+ const prompt = buildGoldfishPrompt(ctx);
237
+ if (spec.kind === "mock") {
238
+ const rawScript = spec.mockScript?.trim();
239
+ if (!rawScript) {
240
+ throw new VibecodeError("CONTRACT_INVALID", "Mock agent spec must include a script path: mock:<script>");
241
+ }
242
+ const resolvedMockScript = path.isAbsolute(rawScript)
243
+ ? rawScript
244
+ : path.resolve(ctx.workspaceDir, rawScript);
245
+ if (!fs.existsSync(resolvedMockScript)) {
246
+ throw new VibecodeError("ADAPTER_MISSING", `Mock agent script not found: ${resolvedMockScript}`, {
247
+ adapter: "mock",
248
+ installHint: "Provide an existing Node.js script path via --agent mock:<script>"
249
+ });
250
+ }
251
+ const promptFile = path.join(os.tmpdir(), `vibecode-prompt-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}.md`);
252
+ fs.writeFileSync(promptFile, prompt, "utf8");
253
+ const stdinPayload = JSON.stringify({ prompt, context: ctx });
254
+ try {
255
+ const run = await runner({
256
+ command: process.execPath,
257
+ args: [resolvedMockScript],
258
+ cwd: ctx.workspaceDir,
259
+ stdin: stdinPayload,
260
+ env: { VIBECODE_PROMPT_FILE: promptFile },
261
+ timeoutMs
262
+ });
263
+ const quotaExceeded = detectQuotaExceeded(run);
264
+ return {
265
+ ok: !run.timedOut && !run.error && run.exitCode === 0 && !quotaExceeded,
266
+ agent: "mock",
267
+ exitCode: run.exitCode,
268
+ stdout: run.stdout,
269
+ stderr: run.stderr,
270
+ durationMs: run.durationMs,
271
+ timedOut: run.timedOut,
272
+ quotaExceeded
273
+ };
274
+ }
275
+ finally {
276
+ fs.rmSync(promptFile, { force: true });
277
+ }
278
+ }
279
+ const env = options.env ?? process.env;
280
+ const platform = options.platform ?? process.platform;
281
+ const detect = options.detectAgent ?? ((pref) => detectAvailableAgent(pref, { env, platform }));
282
+ const resolved = detect(spec.kind);
283
+ if (!resolved || resolved === "auto" || resolved === "mock") {
284
+ const requested = spec.kind === "auto" ? "agent" : spec.kind;
285
+ const installHint = isCliAgentKind(spec.kind) ? INSTALL_HINTS[spec.kind] : ALL_AGENTS_INSTALL_HINT;
286
+ throw new VibecodeError("ADAPTER_MISSING", spec.kind === "auto"
287
+ ? `No supported coding-agent CLI found on PATH (checked: ${CLI_AGENT_ORDER.join(", ")}).`
288
+ : `Requested coding-agent CLI "${spec.kind}" was not found on PATH.`, {
289
+ adapter: requested,
290
+ installHint
291
+ });
292
+ }
293
+ const executable = findExecutableInPath(resolved, env, platform) ?? resolved;
294
+ const args = buildAgentCliArgs(resolved, prompt);
295
+ const run = await runner({
296
+ command: executable,
297
+ args,
298
+ cwd: ctx.workspaceDir,
299
+ timeoutMs
300
+ });
301
+ const quotaExceeded = detectQuotaExceeded(run);
302
+ return {
303
+ ok: !run.timedOut && !run.error && run.exitCode === 0 && !quotaExceeded,
304
+ agent: resolved,
305
+ exitCode: run.exitCode,
306
+ stdout: run.stdout,
307
+ stderr: run.stderr,
308
+ durationMs: run.durationMs,
309
+ timedOut: run.timedOut,
310
+ quotaExceeded
311
+ };
312
+ }
@@ -0,0 +1,6 @@
1
+ import type { AntiCheatReport, Invariant, InvariantResult } from "./types.js";
2
+ /**
3
+ * Evaluate runtime verification results for stubbed constant outputs or holdout overfitting.
4
+ * Never embeds holdout IDs, holdout expected payloads, or external vault paths in its output.
5
+ */
6
+ export declare function evaluateAntiCheat(invariants: readonly Invariant[], results: readonly InvariantResult[], candidateHashes?: ReadonlyMap<string, string>): AntiCheatReport;
@@ -0,0 +1,372 @@
1
+ import { isPlainObjectSafe } from "./security.js";
2
+ const STUB_PROBE_TYPES = ["command", "http", "web_route", "http_workflow", "http_stream", "perf_budget"];
3
+ function stableStringify(value) {
4
+ if (Array.isArray(value)) {
5
+ return `[${value.map((item) => stableStringify(item)).join(",")}]`;
6
+ }
7
+ if (isPlainObjectSafe(value)) {
8
+ const keys = Object.keys(value)
9
+ .filter((k) => value[k] !== undefined)
10
+ .sort();
11
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(",")}}`;
12
+ }
13
+ return JSON.stringify(value) ?? "null";
14
+ }
15
+ function uniqueSortedStrings(values) {
16
+ if (!Array.isArray(values))
17
+ return [];
18
+ const out = new Set();
19
+ for (const v of values) {
20
+ if (typeof v === "string" && v.length > 0)
21
+ out.add(v);
22
+ }
23
+ return [...out].sort();
24
+ }
25
+ function normalizeBodyContains(value) {
26
+ if (typeof value === "string")
27
+ return value.length > 0 ? [value] : [];
28
+ return Array.isArray(value) ? uniqueSortedStrings(value) : [];
29
+ }
30
+ function isStringSubset(small, large) {
31
+ if (small.length === 0)
32
+ return true;
33
+ const largeSet = new Set(large);
34
+ return small.every((item) => largeSet.has(item));
35
+ }
36
+ function canonicalLandmarks(exp) {
37
+ if (!Array.isArray(exp.landmarks))
38
+ return [];
39
+ const out = new Set();
40
+ for (const l of exp.landmarks) {
41
+ if (!l || typeof l.tag !== "string")
42
+ continue;
43
+ const item = {
44
+ tag: l.tag.toLowerCase(),
45
+ required: l.required !== false,
46
+ ...(typeof l.textContains === "string" && l.textContains.length > 0 ? { textContains: l.textContains } : {})
47
+ };
48
+ out.add(stableStringify(item));
49
+ }
50
+ return [...out].sort();
51
+ }
52
+ function canonicalInteractiveLandmarks(exp) {
53
+ if (!Array.isArray(exp.interactiveLandmarks))
54
+ return [];
55
+ const out = new Set();
56
+ for (const l of exp.interactiveLandmarks) {
57
+ if (!l || typeof l.role !== "string" || typeof l.tag !== "string")
58
+ continue;
59
+ const item = {
60
+ role: l.role.toLowerCase(),
61
+ tag: l.tag.toLowerCase(),
62
+ ...(typeof l.name === "string" && l.name.length > 0 ? { name: l.name } : {})
63
+ };
64
+ out.add(stableStringify(item));
65
+ }
66
+ return [...out].sort();
67
+ }
68
+ function probeInputKey(inv) {
69
+ const inp = inv.input || {};
70
+ if (inv.type === "command") {
71
+ return stableStringify({
72
+ args: Array.isArray(inp.args) ? inp.args : [],
73
+ stdin: inp.stdin ?? null,
74
+ env: isPlainObjectSafe(inp.env) ? inp.env : {}
75
+ });
76
+ }
77
+ if (inv.type === "http" || inv.type === "http_stream") {
78
+ return stableStringify({
79
+ ...(inv.type === "http_stream" ? { format: inp.format ?? "auto" } : {}),
80
+ method: String(inp.method || "GET").toUpperCase(),
81
+ path: typeof inp.path === "string" && inp.path ? inp.path : "/",
82
+ query: inp.query ?? null,
83
+ body: inp.body ?? null
84
+ });
85
+ }
86
+ if (inv.type === "http_workflow") {
87
+ const steps = Array.isArray(inp.steps)
88
+ ? inp.steps.map((s) => ({
89
+ method: String(s?.method || "GET").toUpperCase(),
90
+ path: typeof s?.path === "string" && s.path ? s.path : "/",
91
+ query: s?.query ?? null,
92
+ body: s?.body ?? null
93
+ }))
94
+ : [];
95
+ return stableStringify({ steps });
96
+ }
97
+ if (inv.type === "perf_budget") {
98
+ return stableStringify({
99
+ kind: inp.kind ?? inv.domain ?? "http",
100
+ method: String(inp.method || "GET").toUpperCase(),
101
+ path: typeof inp.path === "string" && inp.path ? inp.path : "/",
102
+ query: inp.query ?? null,
103
+ args: Array.isArray(inp.args) ? inp.args : []
104
+ });
105
+ }
106
+ return stableStringify({
107
+ path: typeof inp.path === "string" && inp.path ? inp.path : "/"
108
+ });
109
+ }
110
+ function buildReferenceSignature(inv) {
111
+ const exp = inv.expected || {};
112
+ const sig = {};
113
+ if (inv.type === "command") {
114
+ if (typeof exp.goldenStdout === "string")
115
+ sig.goldenStdout = exp.goldenStdout;
116
+ if (typeof exp.stdoutExact === "string")
117
+ sig.stdoutExact = exp.stdoutExact;
118
+ const stdoutContains = uniqueSortedStrings(exp.stdoutContains);
119
+ if (stdoutContains.length > 0)
120
+ sig.stdoutContains = stdoutContains;
121
+ const stdoutRegex = uniqueSortedStrings(exp.stdoutRegex);
122
+ if (stdoutRegex.length > 0)
123
+ sig.stdoutRegex = stdoutRegex;
124
+ if (exp.jsonSubset !== undefined)
125
+ sig.jsonSubset = exp.jsonSubset;
126
+ if (Array.isArray(exp.jsonPaths) && exp.jsonPaths.length > 0) {
127
+ sig.jsonPaths = exp.jsonPaths.map((jp) => stableStringify(jp)).sort();
128
+ }
129
+ if (isPlainObjectSafe(exp.jsonSchema) && Object.keys(exp.jsonSchema).length > 0) {
130
+ sig.jsonSchema = exp.jsonSchema;
131
+ }
132
+ }
133
+ else if (inv.type === "http") {
134
+ if (typeof exp.bodyExact === "string")
135
+ sig.bodyExact = exp.bodyExact;
136
+ const bodyContains = normalizeBodyContains(exp.bodyContains);
137
+ if (bodyContains.length > 0)
138
+ sig.bodyContains = bodyContains;
139
+ if (exp.jsonSubset !== undefined)
140
+ sig.jsonSubset = exp.jsonSubset;
141
+ if (Array.isArray(exp.jsonPaths) && exp.jsonPaths.length > 0) {
142
+ sig.jsonPaths = exp.jsonPaths.map((jp) => stableStringify(jp)).sort();
143
+ }
144
+ if (isPlainObjectSafe(exp.jsonSchema) && Object.keys(exp.jsonSchema).length > 0) {
145
+ sig.jsonSchema = exp.jsonSchema;
146
+ }
147
+ }
148
+ else if (inv.type === "http_workflow") {
149
+ const steps = Array.isArray(inv.input?.steps) ? inv.input.steps : [];
150
+ const stepSigs = [];
151
+ for (const s of steps) {
152
+ const se = s?.expected;
153
+ if (!isPlainObjectSafe(se))
154
+ continue;
155
+ const entry = {};
156
+ if (typeof se.bodyExact === "string")
157
+ entry.bodyExact = se.bodyExact;
158
+ const bodyContains = normalizeBodyContains(se.bodyContains);
159
+ if (bodyContains.length > 0)
160
+ entry.bodyContains = bodyContains;
161
+ if (se.jsonSubset !== undefined)
162
+ entry.jsonSubset = se.jsonSubset;
163
+ if (Array.isArray(se.jsonPaths) && se.jsonPaths.length > 0) {
164
+ entry.jsonPaths = se.jsonPaths.map((jp) => stableStringify(jp)).sort();
165
+ }
166
+ if (isPlainObjectSafe(se.jsonSchema) && Object.keys(se.jsonSchema).length > 0) {
167
+ entry.jsonSchema = se.jsonSchema;
168
+ }
169
+ if (Object.keys(entry).length > 0)
170
+ stepSigs.push(entry);
171
+ }
172
+ if (stepSigs.length > 0)
173
+ sig.steps = stepSigs;
174
+ }
175
+ else if (inv.type === "http_stream") {
176
+ if (Array.isArray(exp.orderedEvents) && exp.orderedEvents.length > 0)
177
+ sig.orderedEvents = exp.orderedEvents;
178
+ if (Array.isArray(exp.unorderedEvents) && exp.unorderedEvents.length > 0)
179
+ sig.unorderedEvents = exp.unorderedEvents;
180
+ if (isPlainObjectSafe(exp.terminalEvent))
181
+ sig.terminalEvent = exp.terminalEvent;
182
+ if (typeof exp.bodyExact === "string")
183
+ sig.bodyExact = exp.bodyExact;
184
+ const bodyContains = normalizeBodyContains(exp.bodyContains);
185
+ if (bodyContains.length > 0)
186
+ sig.bodyContains = bodyContains;
187
+ if (Array.isArray(exp.jsonPaths) && exp.jsonPaths.length > 0) {
188
+ sig.jsonPaths = exp.jsonPaths.map((jp) => stableStringify(jp)).sort();
189
+ }
190
+ if (isPlainObjectSafe(exp.jsonSchema) && Object.keys(exp.jsonSchema).length > 0) {
191
+ sig.jsonSchema = exp.jsonSchema;
192
+ }
193
+ }
194
+ else if (inv.type === "perf_budget") {
195
+ if (typeof exp.minBytes === "number")
196
+ sig.minBytes = exp.minBytes;
197
+ if (typeof exp.maxBytes === "number")
198
+ sig.maxBytes = exp.maxBytes;
199
+ if (exp.status !== undefined)
200
+ sig.status = exp.status;
201
+ }
202
+ else if (inv.type === "web_route") {
203
+ if (typeof exp.titleContains === "string" && exp.titleContains.length > 0) {
204
+ sig.titleContains = exp.titleContains;
205
+ }
206
+ const landmarks = canonicalLandmarks(exp);
207
+ if (landmarks.length > 0)
208
+ sig.landmarks = landmarks;
209
+ const interactive = canonicalInteractiveLandmarks(exp);
210
+ if (interactive.length > 0)
211
+ sig.interactiveLandmarks = interactive;
212
+ if (Array.isArray(exp.boundingBoxes) && exp.boundingBoxes.length > 0) {
213
+ sig.boundingBoxes = exp.boundingBoxes.map((bb) => stableStringify(bb)).sort();
214
+ }
215
+ }
216
+ return Object.keys(sig).length > 0 ? stableStringify(sig) : null;
217
+ }
218
+ function hasStrictCommandExpectations(exp) {
219
+ return (typeof exp.goldenStdout === "string" ||
220
+ typeof exp.stdoutExact === "string" ||
221
+ exp.jsonSubset !== undefined ||
222
+ (Array.isArray(exp.jsonPaths) && exp.jsonPaths.length > 0) ||
223
+ (isPlainObjectSafe(exp.jsonSchema) && Object.keys(exp.jsonSchema).length > 0));
224
+ }
225
+ function hasStrictHttpExpectations(exp) {
226
+ return (typeof exp.bodyExact === "string" ||
227
+ exp.jsonSubset !== undefined ||
228
+ (Array.isArray(exp.jsonPaths) && exp.jsonPaths.length > 0) ||
229
+ (isPlainObjectSafe(exp.jsonSchema) && Object.keys(exp.jsonSchema).length > 0));
230
+ }
231
+ function webRouteSubsumes(broader, narrower) {
232
+ const nTitle = typeof narrower.titleContains === "string" ? narrower.titleContains : "";
233
+ const bTitle = typeof broader.titleContains === "string" ? broader.titleContains : "";
234
+ if (nTitle.length > 0 && (!bTitle || !bTitle.includes(nTitle))) {
235
+ return false;
236
+ }
237
+ if (!isStringSubset(canonicalLandmarks(narrower), canonicalLandmarks(broader))) {
238
+ return false;
239
+ }
240
+ if (!isStringSubset(canonicalInteractiveLandmarks(narrower), canonicalInteractiveLandmarks(broader))) {
241
+ return false;
242
+ }
243
+ return true;
244
+ }
245
+ function isSubsetCompatible(invA, invB) {
246
+ if (invA.type !== invB.type)
247
+ return false;
248
+ const expA = invA.expected || {};
249
+ const expB = invB.expected || {};
250
+ if (invA.type === "command") {
251
+ if (hasStrictCommandExpectations(expA) || hasStrictCommandExpectations(expB)) {
252
+ return false;
253
+ }
254
+ const cA = uniqueSortedStrings(expA.stdoutContains);
255
+ const cB = uniqueSortedStrings(expB.stdoutContains);
256
+ const rA = uniqueSortedStrings(expA.stdoutRegex);
257
+ const rB = uniqueSortedStrings(expB.stdoutRegex);
258
+ return (isStringSubset(cA, cB) && isStringSubset(rA, rB)) || (isStringSubset(cB, cA) && isStringSubset(rB, rA));
259
+ }
260
+ if (invA.type === "http") {
261
+ if (hasStrictHttpExpectations(expA) || hasStrictHttpExpectations(expB)) {
262
+ return false;
263
+ }
264
+ const cA = normalizeBodyContains(expA.bodyContains);
265
+ const cB = normalizeBodyContains(expB.bodyContains);
266
+ return isStringSubset(cA, cB) || isStringSubset(cB, cA);
267
+ }
268
+ if (invA.type === "web_route") {
269
+ if ((Array.isArray(expA.boundingBoxes) && expA.boundingBoxes.length > 0) ||
270
+ (Array.isArray(expB.boundingBoxes) && expB.boundingBoxes.length > 0)) {
271
+ return false;
272
+ }
273
+ return webRouteSubsumes(expA, expB) || webRouteSubsumes(expB, expA);
274
+ }
275
+ if (invA.type === "perf_budget") {
276
+ // Two passing perf_budget endpoints returning identical status/bytes are legitimate unless one failed.
277
+ return true;
278
+ }
279
+ return false;
280
+ }
281
+ /**
282
+ * Evaluate runtime verification results for stubbed constant outputs or holdout overfitting.
283
+ * Never embeds holdout IDs, holdout expected payloads, or external vault paths in its output.
284
+ */
285
+ export function evaluateAntiCheat(invariants, results, candidateHashes) {
286
+ const invById = new Map();
287
+ for (const inv of invariants) {
288
+ invById.set(inv.id, inv);
289
+ }
290
+ const reasons = [];
291
+ for (const type of STUB_PROBE_TYPES) {
292
+ const byHash = new Map();
293
+ for (const result of results) {
294
+ if (result.status === "skipped" || result.status === "warn")
295
+ continue;
296
+ const inv = invById.get(result.id);
297
+ if (!inv || inv.type !== type)
298
+ continue;
299
+ const metricHash = typeof result.metrics?.candidateOutputHash === "string" ? result.metrics.candidateOutputHash : "";
300
+ const hash = candidateHashes?.get(inv.id) || metricHash;
301
+ if (!hash)
302
+ continue;
303
+ const sig = buildReferenceSignature(inv);
304
+ if (sig === null)
305
+ continue;
306
+ let group = byHash.get(hash);
307
+ if (!group) {
308
+ group = [];
309
+ byHash.set(hash, group);
310
+ }
311
+ group.push({ invariant: inv, result, sig });
312
+ }
313
+ let maxSuspiciousCount = 0;
314
+ for (const group of byHash.values()) {
315
+ if (group.length < 2)
316
+ continue;
317
+ const suspiciousIds = new Set();
318
+ for (let i = 0; i < group.length; i++) {
319
+ for (let j = i + 1; j < group.length; j++) {
320
+ const a = group[i];
321
+ const b = group[j];
322
+ if (probeInputKey(a.invariant) === probeInputKey(b.invariant))
323
+ continue;
324
+ if (a.sig === b.sig)
325
+ continue;
326
+ const anyFailed = a.result.status === "fail" ||
327
+ a.result.status === "error" ||
328
+ b.result.status === "fail" ||
329
+ b.result.status === "error";
330
+ if (anyFailed || !isSubsetCompatible(a.invariant, b.invariant)) {
331
+ suspiciousIds.add(a.invariant.id);
332
+ suspiciousIds.add(b.invariant.id);
333
+ }
334
+ }
335
+ }
336
+ if (suspiciousIds.size > maxSuspiciousCount) {
337
+ maxSuspiciousCount = suspiciousIds.size;
338
+ }
339
+ }
340
+ if (maxSuspiciousCount >= 2) {
341
+ reasons.push(`STUB_CONSTANT_OUTPUT: ${maxSuspiciousCount} distinct ${type} probes returned identical candidate output`);
342
+ }
343
+ }
344
+ let visibleTotal = 0;
345
+ let visiblePassed = 0;
346
+ let holdoutTotal = 0;
347
+ let holdoutPassed = 0;
348
+ for (const result of results) {
349
+ if (result.status === "skipped")
350
+ continue;
351
+ const inv = invById.get(result.id);
352
+ if (!inv || inv.severity !== "hard")
353
+ continue;
354
+ if (inv.holdout === true) {
355
+ holdoutTotal++;
356
+ if (result.status === "pass")
357
+ holdoutPassed++;
358
+ }
359
+ else {
360
+ visibleTotal++;
361
+ if (result.status === "pass")
362
+ visiblePassed++;
363
+ }
364
+ }
365
+ if (visibleTotal >= 3 && visiblePassed === visibleTotal && holdoutTotal >= 2 && holdoutPassed === 0) {
366
+ reasons.push("HOLDOUT_OVERFIT_SUSPECTED: all visible hard invariants passed (100%) while all holdout hard invariants failed (0%)");
367
+ }
368
+ return {
369
+ status: reasons.length > 0 ? "suspected" : "clean",
370
+ reasons
371
+ };
372
+ }