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.
- package/README.md +239 -67
- package/dist/cli.js +2140 -73
- package/dist/core/adapters.d.ts +26 -3
- package/dist/core/adapters.js +411 -25
- package/dist/core/agent-adapter.d.ts +67 -0
- package/dist/core/agent-adapter.js +312 -0
- package/dist/core/anti-cheat.d.ts +6 -0
- package/dist/core/anti-cheat.js +372 -0
- package/dist/core/badge.d.ts +18 -0
- package/dist/core/badge.js +360 -0
- package/dist/core/cache.d.ts +47 -0
- package/dist/core/cache.js +403 -0
- package/dist/core/ci-export.d.ts +35 -0
- package/dist/core/ci-export.js +796 -0
- package/dist/core/ci-formats.d.ts +21 -0
- package/dist/core/ci-formats.js +388 -0
- package/dist/core/client-codegen.d.ts +36 -0
- package/dist/core/client-codegen.js +2538 -0
- package/dist/core/compose.d.ts +71 -0
- package/dist/core/compose.js +1088 -0
- package/dist/core/docs-export.d.ts +37 -0
- package/dist/core/docs-export.js +2706 -0
- package/dist/core/doctor.d.ts +21 -1
- package/dist/core/doctor.js +234 -21
- package/dist/core/exec.d.ts +26 -2
- package/dist/core/exec.js +235 -8
- package/dist/core/fixtures.d.ts +153 -0
- package/dist/core/fixtures.js +2245 -0
- package/dist/core/format.d.ts +77 -0
- package/dist/core/format.js +632 -0
- package/dist/core/fs-snapshot.d.ts +37 -0
- package/dist/core/fs-snapshot.js +216 -0
- package/dist/core/graphql-export.d.ts +34 -0
- package/dist/core/graphql-export.js +2482 -0
- package/dist/core/har-export.d.ts +29 -0
- package/dist/core/har-export.js +988 -0
- package/dist/core/html-report.d.ts +27 -0
- package/dist/core/html-report.js +1535 -0
- package/dist/core/http-export.d.ts +31 -0
- package/dist/core/http-export.js +726 -0
- package/dist/core/impact.d.ts +80 -0
- package/dist/core/impact.js +1412 -0
- package/dist/core/lint.d.ts +38 -0
- package/dist/core/lint.js +1111 -0
- package/dist/core/load-export.d.ts +37 -0
- package/dist/core/load-export.js +1813 -0
- package/dist/core/mcp-export.d.ts +35 -0
- package/dist/core/mcp-export.js +1736 -0
- package/dist/core/mock-server.d.ts +47 -0
- package/dist/core/mock-server.js +1722 -0
- package/dist/core/openapi-export.d.ts +44 -0
- package/dist/core/openapi-export.js +1074 -0
- package/dist/core/parity.d.ts +6 -1
- package/dist/core/parity.js +36 -1
- package/dist/core/playwright-exporter.d.ts +23 -0
- package/dist/core/playwright-exporter.js +1343 -0
- package/dist/core/png.js +45 -9
- package/dist/core/regression.d.ts +54 -0
- package/dist/core/regression.js +529 -0
- package/dist/core/responsive.d.ts +86 -0
- package/dist/core/responsive.js +606 -0
- package/dist/core/run.d.ts +74 -0
- package/dist/core/run.js +696 -0
- package/dist/core/scheduler.d.ts +24 -0
- package/dist/core/scheduler.js +162 -0
- package/dist/core/schema-export.d.ts +29 -0
- package/dist/core/schema-export.js +2215 -0
- package/dist/core/schema.d.ts +3 -2
- package/dist/core/schema.js +460 -17
- package/dist/core/security.d.ts +233 -0
- package/dist/core/security.js +1839 -0
- package/dist/core/server-export.d.ts +38 -0
- package/dist/core/server-export.js +3198 -0
- package/dist/core/spec-writer.d.ts +9 -0
- package/dist/core/spec-writer.js +1202 -0
- package/dist/core/store.d.ts +11 -2
- package/dist/core/store.js +128 -8
- package/dist/core/target-map.d.ts +34 -0
- package/dist/core/target-map.js +262 -0
- package/dist/core/test-exporter.d.ts +25 -0
- package/dist/core/test-exporter.js +1918 -0
- package/dist/core/types.d.ts +182 -14
- package/dist/core/visual-semantic.d.ts +67 -0
- package/dist/core/visual-semantic.js +673 -0
- package/dist/core/visual.js +65 -16
- package/dist/core/watch.d.ts +28 -3
- package/dist/core/watch.js +222 -12
- package/dist/core/yaml.d.ts +5 -0
- package/dist/core/yaml.js +1009 -0
- package/dist/diagnostics/diagnose.d.ts +53 -0
- package/dist/diagnostics/diagnose.js +1083 -0
- package/dist/diagnostics/flake.d.ts +71 -0
- package/dist/diagnostics/flake.js +608 -0
- package/dist/diagnostics/mutation-audit.d.ts +69 -0
- package/dist/diagnostics/mutation-audit.js +769 -0
- package/dist/diagnostics/spatial.d.ts +42 -0
- package/dist/diagnostics/spatial.js +346 -0
- package/dist/diagnostics/trends.d.ts +122 -0
- package/dist/diagnostics/trends.js +1190 -0
- package/dist/discovery/discover.d.ts +111 -0
- package/dist/discovery/discover.js +2017 -0
- package/dist/discovery/lock.d.ts +116 -0
- package/dist/discovery/lock.js +1505 -0
- package/dist/discovery/routes.d.ts +36 -0
- package/dist/discovery/routes.js +1494 -0
- package/dist/discovery/test-importer.d.ts +92 -0
- package/dist/discovery/test-importer.js +4952 -0
- package/dist/index.d.ts +123 -0
- package/dist/index.js +99 -0
- package/dist/ingestors/api-collections.d.ts +28 -0
- package/dist/ingestors/api-collections.js +2335 -0
- package/dist/ingestors/api-repo.d.ts +2 -1
- package/dist/ingestors/api-repo.js +483 -85
- package/dist/ingestors/asyncapi.d.ts +26 -0
- package/dist/ingestors/asyncapi.js +2105 -0
- package/dist/ingestors/bridges.d.ts +2 -0
- package/dist/ingestors/bridges.js +702 -0
- package/dist/ingestors/cli.d.ts +2 -1
- package/dist/ingestors/cli.js +234 -46
- package/dist/ingestors/curl.d.ts +14 -0
- package/dist/ingestors/curl.js +1024 -0
- package/dist/ingestors/graphql.d.ts +56 -0
- package/dist/ingestors/graphql.js +1852 -0
- package/dist/ingestors/http-file.d.ts +20 -0
- package/dist/ingestors/http-file.js +923 -0
- package/dist/ingestors/index.js +486 -6
- package/dist/ingestors/openrpc.d.ts +29 -0
- package/dist/ingestors/openrpc.js +1807 -0
- package/dist/ingestors/proto.d.ts +47 -0
- package/dist/ingestors/proto.js +2690 -0
- package/dist/ingestors/trace.d.ts +10 -0
- package/dist/ingestors/trace.js +599 -0
- package/dist/ingestors/video.d.ts +4 -1
- package/dist/ingestors/video.js +86 -36
- package/dist/ingestors/web.d.ts +16 -1
- package/dist/ingestors/web.js +474 -32
- package/dist/mcp/server.js +3532 -67
- package/dist/oracles/api-repo.js +102 -30
- package/dist/oracles/cli.js +65 -17
- package/dist/oracles/http-workflow.d.ts +68 -0
- package/dist/oracles/http-workflow.js +828 -0
- package/dist/oracles/image.js +178 -28
- package/dist/oracles/index.d.ts +3 -1
- package/dist/oracles/index.js +243 -14
- package/dist/oracles/perf-budget.d.ts +90 -0
- package/dist/oracles/perf-budget.js +1329 -0
- package/dist/oracles/stream.d.ts +94 -0
- package/dist/oracles/stream.js +1268 -0
- package/dist/oracles/ui-states.d.ts +49 -0
- package/dist/oracles/ui-states.js +894 -0
- package/dist/oracles/video.d.ts +1 -1
- package/dist/oracles/video.js +232 -16
- package/dist/oracles/web.js +464 -73
- package/dist/plugins/builtins.d.ts +12 -0
- package/dist/plugins/builtins.js +1052 -0
- package/dist/plugins/registry.d.ts +86 -0
- package/dist/plugins/registry.js +554 -0
- package/dist/setup/index.js +145 -33
- package/package.json +56 -47
- package/skills/vibecode-anything/SKILL.md +75 -52
|
@@ -0,0 +1,1329 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zero-dependency, deterministic latency & payload-size budget oracle (`perf_budget`)
|
|
3
|
+
* supporting both HTTP endpoints and CLI commands.
|
|
4
|
+
*/
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import crypto from "node:crypto";
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import os from "node:os";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { performance } from "node:perf_hooks";
|
|
11
|
+
import { VibecodeError, errorMessage } from "../core/errors.js";
|
|
12
|
+
import { buildWindowsCmdSpawn, isWindowsCmdShim, killProcessTree, splitCommand } from "../core/exec.js";
|
|
13
|
+
import { DETERMINISTIC_CLI_ENV, resolveCommandForSandbox } from "../core/fs-snapshot.js";
|
|
14
|
+
import { HTTP_HEADER_NAME_RE, STRICT_CONTROL_CHARS_RE, clampInt, collectHeaderSecrets, collectJsonSecrets, collectSecretValue, collectUrlSecrets, defineOwnProp, isForbiddenObjectKey, isInsideVaultDirectory, isSensitiveHeaderName, isSensitiveKeyName, isSensitiveQueryParamName, redactDeepValue, redactSecretSpans, redactSensitiveText, resolveSafeTargetUrl, safeIsArray, safeLength, safePrimitiveToString, safeReadOwnDataProp, safeReadPlainObject, safeString } from "../core/security.js";
|
|
15
|
+
import { mergeRuntimeVars, redactRuntimeVars } from "../core/target-map.js";
|
|
16
|
+
import { filterRuntimeHeaders, mergeHeaders } from "../ingestors/trace.js";
|
|
17
|
+
export const DEFAULT_PERF_RUNS = 5;
|
|
18
|
+
export const MAX_PERF_RUNS = 30;
|
|
19
|
+
export const DEFAULT_PERF_WARMUP = 1;
|
|
20
|
+
export const MAX_PERF_WARMUP = 5;
|
|
21
|
+
export const DEFAULT_PERF_TIMEOUT_MS = 10_000;
|
|
22
|
+
export const MAX_PERF_TIMEOUT_MS = 60_000;
|
|
23
|
+
export const MAX_PERF_BODY_BYTES = 10 * 1024 * 1024;
|
|
24
|
+
const MIN_PERF_TIMEOUT_MS = 100;
|
|
25
|
+
const MAX_TRAVERSAL_DEPTH = 32;
|
|
26
|
+
const MAX_SAMPLE_ERRORS = 5;
|
|
27
|
+
const MAX_SAMPLE_SCAN = 1_000_000;
|
|
28
|
+
const MAX_ALLOWED_CODES = 128;
|
|
29
|
+
const HTTP_METHOD_RE = /^[A-Z!#$%&'*+\-.^_`|~0-9]+$/;
|
|
30
|
+
const VARS_TEMPLATE_RE = /\{\{\s*vars\.([^{}]+?)\s*\}\}/g;
|
|
31
|
+
const PRESERVE_HASH_KEYS = new Set(["candidateOutputHash"]);
|
|
32
|
+
function hasOwn(obj, key) {
|
|
33
|
+
try {
|
|
34
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function snapshotPlainRecord(raw, label, options = {}) {
|
|
41
|
+
if (raw === undefined || (options.allowNullish === true && raw === null)) {
|
|
42
|
+
return { ok: true, value: {} };
|
|
43
|
+
}
|
|
44
|
+
const res = safeReadPlainObject(raw, label, {
|
|
45
|
+
allowNullish: options.allowNullish,
|
|
46
|
+
forbiddenKeyPolicy: "skip"
|
|
47
|
+
});
|
|
48
|
+
if (!res.ok)
|
|
49
|
+
return { ok: false, error: res.error };
|
|
50
|
+
const value = {};
|
|
51
|
+
for (const [k, v] of res.entries)
|
|
52
|
+
defineOwnProp(value, k, v);
|
|
53
|
+
return { ok: true, value };
|
|
54
|
+
}
|
|
55
|
+
function round2(value) {
|
|
56
|
+
if (!Number.isFinite(value))
|
|
57
|
+
return 0;
|
|
58
|
+
if (Math.abs(value) >= 1e15)
|
|
59
|
+
return value;
|
|
60
|
+
const rounded = Math.round(value * 100) / 100;
|
|
61
|
+
return rounded === 0 ? 0 : rounded;
|
|
62
|
+
}
|
|
63
|
+
function round4(value) {
|
|
64
|
+
if (!Number.isFinite(value))
|
|
65
|
+
return 0;
|
|
66
|
+
if (Math.abs(value) >= 1e13)
|
|
67
|
+
return value;
|
|
68
|
+
const rounded = Math.round(value * 10_000) / 10_000;
|
|
69
|
+
return rounded === 0 ? 0 : rounded;
|
|
70
|
+
}
|
|
71
|
+
function nearestRankValue(sorted, percentile) {
|
|
72
|
+
const n = sorted.length;
|
|
73
|
+
// Exact integer ceiling of (percentile * n) / 100 avoids IEEE-754 boundary drift.
|
|
74
|
+
const rank = Math.floor((percentile * n + 99) / 100);
|
|
75
|
+
const idx = Math.min(n - 1, Math.max(0, rank - 1));
|
|
76
|
+
return sorted[idx];
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Compute exact nearest-rank latency percentiles from non-negative finite durations (ms),
|
|
80
|
+
* rounded to 2 decimal places. Returns all zeros for empty input.
|
|
81
|
+
*/
|
|
82
|
+
export function computeLatencyPercentiles(durationsMs) {
|
|
83
|
+
if (!safeIsArray(durationsMs)) {
|
|
84
|
+
return { count: 0, minMs: 0, meanMs: 0, p50Ms: 0, p95Ms: 0, p99Ms: 0, maxMs: 0 };
|
|
85
|
+
}
|
|
86
|
+
const len = safeLength(durationsMs, MAX_SAMPLE_SCAN);
|
|
87
|
+
if (len === 0) {
|
|
88
|
+
return { count: 0, minMs: 0, meanMs: 0, p50Ms: 0, p95Ms: 0, p99Ms: 0, maxMs: 0 };
|
|
89
|
+
}
|
|
90
|
+
const valid = [];
|
|
91
|
+
let sum = 0;
|
|
92
|
+
for (let i = 0; i < len; i++) {
|
|
93
|
+
let d;
|
|
94
|
+
try {
|
|
95
|
+
d = durationsMs[i];
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (typeof d === "number" && Number.isFinite(d) && d >= 0) {
|
|
101
|
+
const normalized = d === 0 ? 0 : d;
|
|
102
|
+
valid.push(normalized);
|
|
103
|
+
sum += normalized;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const count = valid.length;
|
|
107
|
+
if (count === 0) {
|
|
108
|
+
return { count: 0, minMs: 0, meanMs: 0, p50Ms: 0, p95Ms: 0, p99Ms: 0, maxMs: 0 };
|
|
109
|
+
}
|
|
110
|
+
let mean;
|
|
111
|
+
if (Number.isFinite(sum)) {
|
|
112
|
+
mean = sum / count;
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
// Overflow-safe incremental mean for extreme finite values near Number.MAX_VALUE.
|
|
116
|
+
mean = 0;
|
|
117
|
+
for (let i = 0; i < count; i++) {
|
|
118
|
+
mean += (valid[i] - mean) / (i + 1);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
// Native unboxed Float64Array sort stays O(N log N) and avoids JS comparator callback overhead.
|
|
122
|
+
const sorted = Float64Array.from(valid);
|
|
123
|
+
sorted.sort();
|
|
124
|
+
return {
|
|
125
|
+
count,
|
|
126
|
+
minMs: round2(sorted[0]),
|
|
127
|
+
meanMs: round2(mean),
|
|
128
|
+
p50Ms: round2(nearestRankValue(sorted, 50)),
|
|
129
|
+
p95Ms: round2(nearestRankValue(sorted, 95)),
|
|
130
|
+
p99Ms: round2(nearestRankValue(sorted, 99)),
|
|
131
|
+
maxMs: round2(sorted[count - 1])
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
function matchesAllowedNumber(actual, expected) {
|
|
135
|
+
if (safeIsArray(expected)) {
|
|
136
|
+
const len = safeLength(expected, MAX_ALLOWED_CODES);
|
|
137
|
+
for (let i = 0; i < len; i++) {
|
|
138
|
+
try {
|
|
139
|
+
const item = expected[i];
|
|
140
|
+
if (typeof item === "number" && Number.isFinite(item) && item === actual)
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
return typeof expected === "number" && Number.isFinite(expected) && expected === actual;
|
|
150
|
+
}
|
|
151
|
+
function isValidNonNegativeBudget(value) {
|
|
152
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Pure deterministic evaluator checking error rate, latency percentile/mean/max budgets,
|
|
156
|
+
* and payload size bounds over collected performance samples. Fails closed on empty samples
|
|
157
|
+
* or invalid budget thresholds.
|
|
158
|
+
*/
|
|
159
|
+
export function evaluatePerfBudget(samples, spec) {
|
|
160
|
+
const specSnap = snapshotPlainRecord(spec, "perf_budget spec", { allowNullish: true });
|
|
161
|
+
if (!specSnap.ok) {
|
|
162
|
+
return {
|
|
163
|
+
passed: false,
|
|
164
|
+
failures: [specSnap.error],
|
|
165
|
+
latency: computeLatencyPercentiles([]),
|
|
166
|
+
bytes: { minBytes: 0, meanBytes: 0, maxBytes: 0 },
|
|
167
|
+
errorCount: 0,
|
|
168
|
+
errorRate: 0,
|
|
169
|
+
sampleCount: 0
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
const safeSpec = specSnap.value;
|
|
173
|
+
const sampleCount = safeIsArray(samples) ? safeLength(samples, MAX_SAMPLE_SCAN) : 0;
|
|
174
|
+
if (sampleCount === 0) {
|
|
175
|
+
return {
|
|
176
|
+
passed: false,
|
|
177
|
+
failures: ["no performance samples collected"],
|
|
178
|
+
latency: computeLatencyPercentiles([]),
|
|
179
|
+
bytes: { minBytes: 0, meanBytes: 0, maxBytes: 0 },
|
|
180
|
+
errorCount: 0,
|
|
181
|
+
errorRate: 0,
|
|
182
|
+
sampleCount: 0
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
const durations = [];
|
|
186
|
+
let minBytes = Number.POSITIVE_INFINITY;
|
|
187
|
+
let maxBytes = 0;
|
|
188
|
+
let sumBytes = 0;
|
|
189
|
+
let validByteCount = 0;
|
|
190
|
+
let errorCount = 0;
|
|
191
|
+
for (let i = 0; i < sampleCount; i++) {
|
|
192
|
+
let rawSample;
|
|
193
|
+
try {
|
|
194
|
+
rawSample = samples[i];
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
errorCount++;
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const sampleSnap = snapshotPlainRecord(rawSample, `sample[${i}]`);
|
|
201
|
+
if (!sampleSnap.ok) {
|
|
202
|
+
errorCount++;
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
const sample = sampleSnap.value;
|
|
206
|
+
if (typeof sample.durationMs === "number") {
|
|
207
|
+
durations.push(sample.durationMs);
|
|
208
|
+
}
|
|
209
|
+
if (typeof sample.bytes === "number" && Number.isFinite(sample.bytes) && sample.bytes >= 0) {
|
|
210
|
+
if (sample.bytes < minBytes)
|
|
211
|
+
minBytes = sample.bytes;
|
|
212
|
+
if (sample.bytes > maxBytes)
|
|
213
|
+
maxBytes = sample.bytes;
|
|
214
|
+
sumBytes += sample.bytes;
|
|
215
|
+
validByteCount++;
|
|
216
|
+
}
|
|
217
|
+
const statusMismatch = safeSpec.status !== undefined &&
|
|
218
|
+
typeof sample.status === "number" &&
|
|
219
|
+
!matchesAllowedNumber(sample.status, safeSpec.status);
|
|
220
|
+
const exitCodeMismatch = safeSpec.exitCode !== undefined &&
|
|
221
|
+
typeof sample.exitCode === "number" &&
|
|
222
|
+
!matchesAllowedNumber(sample.exitCode, safeSpec.exitCode);
|
|
223
|
+
if (sample.ok !== true || statusMismatch || exitCodeMismatch) {
|
|
224
|
+
errorCount++;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const latency = computeLatencyPercentiles(durations);
|
|
228
|
+
const bytes = validByteCount > 0
|
|
229
|
+
? {
|
|
230
|
+
minBytes: round2(minBytes),
|
|
231
|
+
meanBytes: round2(sumBytes / validByteCount),
|
|
232
|
+
maxBytes: round2(maxBytes)
|
|
233
|
+
}
|
|
234
|
+
: { minBytes: 0, meanBytes: 0, maxBytes: 0 };
|
|
235
|
+
const rawErrorRate = errorCount / sampleCount;
|
|
236
|
+
const errorRate = round4(rawErrorRate);
|
|
237
|
+
const failures = [];
|
|
238
|
+
// Error rate budget (default 0)
|
|
239
|
+
if (safeSpec.maxErrorRate === undefined) {
|
|
240
|
+
if (rawErrorRate > 0) {
|
|
241
|
+
failures.push(`errorRate ${errorRate} (${errorCount}/${sampleCount}) > maxErrorRate 0`);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
else if (typeof safeSpec.maxErrorRate !== "number" ||
|
|
245
|
+
!Number.isFinite(safeSpec.maxErrorRate) ||
|
|
246
|
+
safeSpec.maxErrorRate < 0 ||
|
|
247
|
+
safeSpec.maxErrorRate > 1) {
|
|
248
|
+
failures.push(`invalid maxErrorRate budget: expected a finite number in [0, 1]`);
|
|
249
|
+
}
|
|
250
|
+
else if (rawErrorRate > safeSpec.maxErrorRate) {
|
|
251
|
+
failures.push(`errorRate ${errorRate} (${errorCount}/${sampleCount}) > maxErrorRate ${safeSpec.maxErrorRate}`);
|
|
252
|
+
}
|
|
253
|
+
// Latency budgets
|
|
254
|
+
const latencyChecks = [
|
|
255
|
+
{ key: "maxP50Ms", label: "p50", actual: latency.p50Ms },
|
|
256
|
+
{ key: "maxP95Ms", label: "p95", actual: latency.p95Ms },
|
|
257
|
+
{ key: "maxP99Ms", label: "p99", actual: latency.p99Ms },
|
|
258
|
+
{ key: "maxMeanMs", label: "mean", actual: latency.meanMs },
|
|
259
|
+
{ key: "maxDurationMs", label: "maxDuration", actual: latency.maxMs }
|
|
260
|
+
];
|
|
261
|
+
let requestedLatencyCheck = false;
|
|
262
|
+
for (const check of latencyChecks) {
|
|
263
|
+
const limit = safeSpec[check.key];
|
|
264
|
+
if (limit === undefined)
|
|
265
|
+
continue;
|
|
266
|
+
requestedLatencyCheck = true;
|
|
267
|
+
if (!isValidNonNegativeBudget(limit)) {
|
|
268
|
+
failures.push(`invalid ${check.key} budget: expected a finite non-negative number`);
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
if (latency.count > 0 && check.actual > limit) {
|
|
272
|
+
failures.push(`${check.label} latency ${check.actual}ms > ${check.key} ${limit}ms`);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
if (requestedLatencyCheck && latency.count === 0) {
|
|
276
|
+
failures.push("no finite latency samples available to verify latency budget");
|
|
277
|
+
}
|
|
278
|
+
// Payload byte budgets
|
|
279
|
+
const hasMaxBytes = safeSpec.maxBytes !== undefined;
|
|
280
|
+
const hasMinBytes = safeSpec.minBytes !== undefined;
|
|
281
|
+
const maxBytesValid = hasMaxBytes && isValidNonNegativeBudget(safeSpec.maxBytes);
|
|
282
|
+
const minBytesValid = hasMinBytes && isValidNonNegativeBudget(safeSpec.minBytes);
|
|
283
|
+
if (hasMaxBytes && !maxBytesValid) {
|
|
284
|
+
failures.push("invalid maxBytes budget: expected a finite non-negative number");
|
|
285
|
+
}
|
|
286
|
+
if (hasMinBytes && !minBytesValid) {
|
|
287
|
+
failures.push("invalid minBytes budget: expected a finite non-negative number");
|
|
288
|
+
}
|
|
289
|
+
if (minBytesValid && maxBytesValid && safeSpec.minBytes > safeSpec.maxBytes) {
|
|
290
|
+
failures.push(`invalid byte budget: minBytes ${safeSpec.minBytes} > maxBytes ${safeSpec.maxBytes}`);
|
|
291
|
+
}
|
|
292
|
+
if ((hasMaxBytes || hasMinBytes) && validByteCount === 0) {
|
|
293
|
+
failures.push("no finite byte samples available to verify payload size budget");
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
if (maxBytesValid && bytes.maxBytes > safeSpec.maxBytes) {
|
|
297
|
+
failures.push(`payload maxBytes ${bytes.maxBytes} > maxBytes ${safeSpec.maxBytes}`);
|
|
298
|
+
}
|
|
299
|
+
if (minBytesValid && bytes.minBytes < safeSpec.minBytes) {
|
|
300
|
+
failures.push(`payload minBytes ${bytes.minBytes} < minBytes ${safeSpec.minBytes}`);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return {
|
|
304
|
+
passed: failures.length === 0,
|
|
305
|
+
failures,
|
|
306
|
+
latency,
|
|
307
|
+
bytes,
|
|
308
|
+
errorCount,
|
|
309
|
+
errorRate,
|
|
310
|
+
sampleCount
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
function redactAll(text, runtimeVars, extraSecrets) {
|
|
314
|
+
const raw = typeof text === "string" ? text : safeString(text);
|
|
315
|
+
if (!raw)
|
|
316
|
+
return "";
|
|
317
|
+
const preScrub = redactSecretSpans(raw, extraSecrets);
|
|
318
|
+
const out = redactRuntimeVars(preScrub, runtimeVars);
|
|
319
|
+
if (!out)
|
|
320
|
+
return "";
|
|
321
|
+
return redactSensitiveText(redactSecretSpans(out, extraSecrets));
|
|
322
|
+
}
|
|
323
|
+
function redactDeep(value, runtimeVars, extraSecrets) {
|
|
324
|
+
return redactDeepValue(value, {
|
|
325
|
+
maxDepth: MAX_TRAVERSAL_DEPTH,
|
|
326
|
+
redactText: (s) => redactAll(s, runtimeVars, extraSecrets),
|
|
327
|
+
preserveKeys: PRESERVE_HASH_KEYS
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
function scrubOutcome(outcome, runtimeVars, extraSecrets) {
|
|
331
|
+
const out = { ...outcome };
|
|
332
|
+
if (outcome.failures !== undefined) {
|
|
333
|
+
out.failures = outcome.failures.map((f) => redactAll(f, runtimeVars, extraSecrets));
|
|
334
|
+
}
|
|
335
|
+
if (outcome.reason !== undefined) {
|
|
336
|
+
out.reason = redactAll(outcome.reason, runtimeVars, extraSecrets);
|
|
337
|
+
}
|
|
338
|
+
if (outcome.diff !== undefined) {
|
|
339
|
+
out.diff = redactDeep(outcome.diff, runtimeVars, extraSecrets);
|
|
340
|
+
}
|
|
341
|
+
if (outcome.metrics !== undefined) {
|
|
342
|
+
out.metrics = redactDeep(outcome.metrics, runtimeVars, extraSecrets);
|
|
343
|
+
}
|
|
344
|
+
if (outcome.diagnostic !== undefined) {
|
|
345
|
+
out.diagnostic = redactDeep(outcome.diagnostic, runtimeVars, extraSecrets);
|
|
346
|
+
}
|
|
347
|
+
return out;
|
|
348
|
+
}
|
|
349
|
+
function readSafeStringMapChecked(raw, label) {
|
|
350
|
+
const snap = snapshotPlainRecord(raw, label, { allowNullish: true });
|
|
351
|
+
if (!snap.ok)
|
|
352
|
+
return snap;
|
|
353
|
+
const out = {};
|
|
354
|
+
for (const [key, val] of Object.entries(snap.value)) {
|
|
355
|
+
if (typeof val === "string") {
|
|
356
|
+
defineOwnProp(out, key, val);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
return { ok: true, value: out };
|
|
360
|
+
}
|
|
361
|
+
function interpolateVarsString(raw, vars, unresolved, blocked) {
|
|
362
|
+
if (!raw.includes("{{"))
|
|
363
|
+
return raw;
|
|
364
|
+
return raw.replace(VARS_TEMPLATE_RE, (full, rawName) => {
|
|
365
|
+
const name = rawName.trim();
|
|
366
|
+
if (!name || isForbiddenObjectKey(name) || name.split(".").some((seg) => isForbiddenObjectKey(seg.trim()))) {
|
|
367
|
+
const expr = `vars.${name}`;
|
|
368
|
+
if (!blocked.includes(expr))
|
|
369
|
+
blocked.push(expr);
|
|
370
|
+
return full;
|
|
371
|
+
}
|
|
372
|
+
if (!hasOwn(vars, name)) {
|
|
373
|
+
const expr = `vars.${name}`;
|
|
374
|
+
if (!unresolved.includes(expr))
|
|
375
|
+
unresolved.push(expr);
|
|
376
|
+
return full;
|
|
377
|
+
}
|
|
378
|
+
return vars[name];
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
function interpolateVarsDeep(node, vars, unresolved, blocked, errors, depth = 0, ancestors = new WeakSet()) {
|
|
382
|
+
if (depth > MAX_TRAVERSAL_DEPTH)
|
|
383
|
+
return "[TRUNCATED]";
|
|
384
|
+
if (typeof node === "string")
|
|
385
|
+
return interpolateVarsString(node, vars, unresolved, blocked);
|
|
386
|
+
if (node === null || typeof node !== "object")
|
|
387
|
+
return node;
|
|
388
|
+
if (ancestors.has(node))
|
|
389
|
+
return "[CIRCULAR]";
|
|
390
|
+
ancestors.add(node);
|
|
391
|
+
try {
|
|
392
|
+
if (safeIsArray(node)) {
|
|
393
|
+
const len = safeLength(node, 10_000);
|
|
394
|
+
const arr = [];
|
|
395
|
+
for (let i = 0; i < len; i++) {
|
|
396
|
+
let item;
|
|
397
|
+
try {
|
|
398
|
+
item = node[i];
|
|
399
|
+
}
|
|
400
|
+
catch (err) {
|
|
401
|
+
errors.push(`input.body[${i}] could not be read safely: ${errorMessage(err)}`);
|
|
402
|
+
return null;
|
|
403
|
+
}
|
|
404
|
+
arr.push(interpolateVarsDeep(item, vars, unresolved, blocked, errors, depth + 1, ancestors));
|
|
405
|
+
}
|
|
406
|
+
return arr;
|
|
407
|
+
}
|
|
408
|
+
const snap = snapshotPlainRecord(node, "input.body");
|
|
409
|
+
if (!snap.ok) {
|
|
410
|
+
errors.push(snap.error);
|
|
411
|
+
return null;
|
|
412
|
+
}
|
|
413
|
+
const out = {};
|
|
414
|
+
for (const [k, v] of Object.entries(snap.value)) {
|
|
415
|
+
if (isForbiddenObjectKey(k))
|
|
416
|
+
continue;
|
|
417
|
+
defineOwnProp(out, k, interpolateVarsDeep(v, vars, unresolved, blocked, errors, depth + 1, ancestors));
|
|
418
|
+
}
|
|
419
|
+
return out;
|
|
420
|
+
}
|
|
421
|
+
finally {
|
|
422
|
+
ancestors.delete(node);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
function sanitizeHeaderRecordChecked(raw, label) {
|
|
426
|
+
const snap = snapshotPlainRecord(raw, label, { allowNullish: true });
|
|
427
|
+
if (!snap.ok)
|
|
428
|
+
return snap;
|
|
429
|
+
const out = {};
|
|
430
|
+
for (const [key, val] of Object.entries(snap.value)) {
|
|
431
|
+
if (val === undefined || val === null)
|
|
432
|
+
continue;
|
|
433
|
+
const strVal = safePrimitiveToString(val);
|
|
434
|
+
if (strVal === null) {
|
|
435
|
+
return { ok: false, error: `${label}[${JSON.stringify(key)}] must be a string or primitive value` };
|
|
436
|
+
}
|
|
437
|
+
defineOwnProp(out, key, strVal);
|
|
438
|
+
}
|
|
439
|
+
return { ok: true, value: out };
|
|
440
|
+
}
|
|
441
|
+
function validateHeaders(headers) {
|
|
442
|
+
if (!headers)
|
|
443
|
+
return null;
|
|
444
|
+
for (const [rawKey, rawVal] of Object.entries(headers)) {
|
|
445
|
+
const trimmed = rawKey.trim();
|
|
446
|
+
if (STRICT_CONTROL_CHARS_RE.test(rawKey) ||
|
|
447
|
+
rawKey !== trimmed ||
|
|
448
|
+
!trimmed ||
|
|
449
|
+
isForbiddenObjectKey(trimmed) ||
|
|
450
|
+
!HTTP_HEADER_NAME_RE.test(trimmed)) {
|
|
451
|
+
return `invalid HTTP header name ${JSON.stringify(rawKey)}`;
|
|
452
|
+
}
|
|
453
|
+
if (STRICT_CONTROL_CHARS_RE.test(rawVal)) {
|
|
454
|
+
return `invalid HTTP header value for ${JSON.stringify(trimmed)}: contains control characters`;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
return null;
|
|
458
|
+
}
|
|
459
|
+
function extractAllowedNumbers(raw, label) {
|
|
460
|
+
if (typeof raw === "number") {
|
|
461
|
+
if (!Number.isFinite(raw)) {
|
|
462
|
+
return { ok: false, error: `invalid ${label} budget: expected a finite number or array of finite numbers` };
|
|
463
|
+
}
|
|
464
|
+
return { ok: true, value: raw };
|
|
465
|
+
}
|
|
466
|
+
if (safeIsArray(raw)) {
|
|
467
|
+
const len = safeLength(raw, MAX_ALLOWED_CODES);
|
|
468
|
+
const out = [];
|
|
469
|
+
for (let i = 0; i < len; i++) {
|
|
470
|
+
let item;
|
|
471
|
+
try {
|
|
472
|
+
item = raw[i];
|
|
473
|
+
}
|
|
474
|
+
catch (err) {
|
|
475
|
+
return { ok: false, error: `${label}[${i}] could not be read safely: ${errorMessage(err)}` };
|
|
476
|
+
}
|
|
477
|
+
if (typeof item !== "number" || !Number.isFinite(item)) {
|
|
478
|
+
return { ok: false, error: `invalid ${label} budget: array elements must be finite numbers` };
|
|
479
|
+
}
|
|
480
|
+
out.push(item);
|
|
481
|
+
}
|
|
482
|
+
if (out.length === 0) {
|
|
483
|
+
return { ok: false, error: `invalid ${label} budget: expected at least one allowed number` };
|
|
484
|
+
}
|
|
485
|
+
return { ok: true, value: out };
|
|
486
|
+
}
|
|
487
|
+
return { ok: false, error: `invalid ${label} budget: expected a finite number or array of finite numbers` };
|
|
488
|
+
}
|
|
489
|
+
function extractBudgetSpec(rawExpected) {
|
|
490
|
+
const spec = {};
|
|
491
|
+
const numericKeys = [
|
|
492
|
+
"maxP50Ms",
|
|
493
|
+
"maxP95Ms",
|
|
494
|
+
"maxP99Ms",
|
|
495
|
+
"maxMeanMs",
|
|
496
|
+
"maxDurationMs",
|
|
497
|
+
"maxBytes",
|
|
498
|
+
"minBytes",
|
|
499
|
+
"maxErrorRate"
|
|
500
|
+
];
|
|
501
|
+
for (const key of numericKeys) {
|
|
502
|
+
if (hasOwn(rawExpected, key) && rawExpected[key] !== undefined) {
|
|
503
|
+
defineOwnProp(spec, key, rawExpected[key]);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
if (hasOwn(rawExpected, "status") && rawExpected.status !== undefined) {
|
|
507
|
+
const parsed = extractAllowedNumbers(rawExpected.status, "status");
|
|
508
|
+
if (!parsed.ok)
|
|
509
|
+
return parsed;
|
|
510
|
+
spec.status = parsed.value;
|
|
511
|
+
}
|
|
512
|
+
if (hasOwn(rawExpected, "exitCode") && rawExpected.exitCode !== undefined) {
|
|
513
|
+
const parsed = extractAllowedNumbers(rawExpected.exitCode, "exitCode");
|
|
514
|
+
if (!parsed.ok)
|
|
515
|
+
return parsed;
|
|
516
|
+
spec.exitCode = parsed.value;
|
|
517
|
+
}
|
|
518
|
+
return { ok: true, spec };
|
|
519
|
+
}
|
|
520
|
+
function summarizeBudget(spec) {
|
|
521
|
+
const out = {
|
|
522
|
+
maxErrorRate: spec.maxErrorRate ?? 0
|
|
523
|
+
};
|
|
524
|
+
for (const key of [
|
|
525
|
+
"maxP50Ms",
|
|
526
|
+
"maxP95Ms",
|
|
527
|
+
"maxP99Ms",
|
|
528
|
+
"maxMeanMs",
|
|
529
|
+
"maxDurationMs",
|
|
530
|
+
"maxBytes",
|
|
531
|
+
"minBytes",
|
|
532
|
+
"status",
|
|
533
|
+
"exitCode"
|
|
534
|
+
]) {
|
|
535
|
+
if (spec[key] !== undefined) {
|
|
536
|
+
defineOwnProp(out, key, spec[key]);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
return out;
|
|
540
|
+
}
|
|
541
|
+
function isExpectedHttpStatus(status, expected) {
|
|
542
|
+
if (expected !== undefined)
|
|
543
|
+
return matchesAllowedNumber(status, expected);
|
|
544
|
+
return status >= 200 && status <= 299;
|
|
545
|
+
}
|
|
546
|
+
async function measureHttpRun(url, options, fetchWithTimeout) {
|
|
547
|
+
if (fetchWithTimeout) {
|
|
548
|
+
const started = performance.now();
|
|
549
|
+
try {
|
|
550
|
+
const obs = await fetchWithTimeout(url, {
|
|
551
|
+
method: options.method,
|
|
552
|
+
headers: options.headers,
|
|
553
|
+
body: options.rawBody,
|
|
554
|
+
timeoutMs: options.timeoutMs
|
|
555
|
+
});
|
|
556
|
+
const durationMs = round2(Math.max(0, performance.now() - started));
|
|
557
|
+
const bodyStr = typeof obs?.text === "string" ? obs.text : "";
|
|
558
|
+
const rawBytes = Buffer.byteLength(bodyStr, "utf8");
|
|
559
|
+
const exceededCap = rawBytes > MAX_PERF_BODY_BYTES;
|
|
560
|
+
const bytes = exceededCap ? MAX_PERF_BODY_BYTES + 1 : rawBytes;
|
|
561
|
+
const statusOk = isExpectedHttpStatus(obs?.status, options.expectedStatus);
|
|
562
|
+
const errors = [];
|
|
563
|
+
if (exceededCap) {
|
|
564
|
+
errors.push(`response body exceeded MAX_PERF_BODY_BYTES (${MAX_PERF_BODY_BYTES} bytes)`);
|
|
565
|
+
}
|
|
566
|
+
if (!statusOk) {
|
|
567
|
+
const expLabel = options.expectedStatus !== undefined ? JSON.stringify(options.expectedStatus) : "200..299";
|
|
568
|
+
errors.push(`status expected ${expLabel}, got ${obs?.status}`);
|
|
569
|
+
}
|
|
570
|
+
const candidateOutputHash = options.captureHash && !exceededCap && rawBytes > 0
|
|
571
|
+
? crypto.createHash("sha256").update(bodyStr, "utf8").digest("hex")
|
|
572
|
+
: undefined;
|
|
573
|
+
return {
|
|
574
|
+
durationMs,
|
|
575
|
+
bytes,
|
|
576
|
+
ok: errors.length === 0,
|
|
577
|
+
status: obs?.status,
|
|
578
|
+
...(errors.length > 0 ? { error: errors.join("; ") } : {}),
|
|
579
|
+
...(candidateOutputHash ? { candidateOutputHash } : {})
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
catch (err) {
|
|
583
|
+
const durationMs = round2(Math.max(0, performance.now() - started));
|
|
584
|
+
return {
|
|
585
|
+
durationMs,
|
|
586
|
+
bytes: 0,
|
|
587
|
+
ok: false,
|
|
588
|
+
error: `request failed: ${errorMessage(err)}`
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
const ctrl = new AbortController();
|
|
593
|
+
let timedOut = false;
|
|
594
|
+
// Keep timer ref'd until finally clears it so hanging AbortSignal promises trigger timeout cleanly.
|
|
595
|
+
const timer = setTimeout(() => {
|
|
596
|
+
timedOut = true;
|
|
597
|
+
ctrl.abort();
|
|
598
|
+
}, options.timeoutMs);
|
|
599
|
+
let reader = null;
|
|
600
|
+
const started = performance.now();
|
|
601
|
+
try {
|
|
602
|
+
const res = await fetch(url, {
|
|
603
|
+
method: options.method,
|
|
604
|
+
headers: options.headers,
|
|
605
|
+
body: options.body,
|
|
606
|
+
signal: ctrl.signal
|
|
607
|
+
});
|
|
608
|
+
let bytes = 0;
|
|
609
|
+
let exceededCap = false;
|
|
610
|
+
const hasher = options.captureHash ? crypto.createHash("sha256") : null;
|
|
611
|
+
if (res.body) {
|
|
612
|
+
reader = res.body.getReader();
|
|
613
|
+
while (true) {
|
|
614
|
+
const chunk = await reader.read();
|
|
615
|
+
if (chunk.done)
|
|
616
|
+
break;
|
|
617
|
+
if (chunk.value) {
|
|
618
|
+
bytes += chunk.value.byteLength;
|
|
619
|
+
if (bytes > MAX_PERF_BODY_BYTES) {
|
|
620
|
+
exceededCap = true;
|
|
621
|
+
bytes = MAX_PERF_BODY_BYTES + 1;
|
|
622
|
+
// Abort the underlying HTTP socket immediately before cancelling the stream.
|
|
623
|
+
ctrl.abort();
|
|
624
|
+
await reader.cancel().catch(() => { });
|
|
625
|
+
break;
|
|
626
|
+
}
|
|
627
|
+
hasher?.update(chunk.value);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
const durationMs = round2(Math.max(0, performance.now() - started));
|
|
632
|
+
const statusOk = isExpectedHttpStatus(res.status, options.expectedStatus);
|
|
633
|
+
const errors = [];
|
|
634
|
+
if (exceededCap) {
|
|
635
|
+
errors.push(`response body exceeded MAX_PERF_BODY_BYTES (${MAX_PERF_BODY_BYTES} bytes)`);
|
|
636
|
+
}
|
|
637
|
+
if (!statusOk) {
|
|
638
|
+
const expLabel = options.expectedStatus !== undefined ? JSON.stringify(options.expectedStatus) : "200..299";
|
|
639
|
+
errors.push(`status expected ${expLabel}, got ${res.status}`);
|
|
640
|
+
}
|
|
641
|
+
const candidateOutputHash = hasher && !exceededCap && bytes > 0 ? hasher.digest("hex") : undefined;
|
|
642
|
+
return {
|
|
643
|
+
durationMs,
|
|
644
|
+
bytes,
|
|
645
|
+
ok: errors.length === 0,
|
|
646
|
+
status: res.status,
|
|
647
|
+
...(errors.length > 0 ? { error: errors.join("; ") } : {}),
|
|
648
|
+
...(candidateOutputHash ? { candidateOutputHash } : {})
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
catch (err) {
|
|
652
|
+
const durationMs = round2(Math.max(0, performance.now() - started));
|
|
653
|
+
const msg = timedOut
|
|
654
|
+
? `request timed out after ${options.timeoutMs}ms`
|
|
655
|
+
: `request failed: ${errorMessage(err)}`;
|
|
656
|
+
return {
|
|
657
|
+
durationMs,
|
|
658
|
+
bytes: 0,
|
|
659
|
+
ok: false,
|
|
660
|
+
error: msg
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
finally {
|
|
664
|
+
clearTimeout(timer);
|
|
665
|
+
if (reader) {
|
|
666
|
+
await reader.cancel().catch(() => { });
|
|
667
|
+
try {
|
|
668
|
+
reader.releaseLock();
|
|
669
|
+
}
|
|
670
|
+
catch {
|
|
671
|
+
// ignore already released lock
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* Streams stdout + stderr byte counts in O(1) memory without buffering payloads in RAM,
|
|
678
|
+
* immediately terminating the child process tree if output exceeds MAX_PERF_BODY_BYTES
|
|
679
|
+
* or execution exceeds timeoutMs.
|
|
680
|
+
*/
|
|
681
|
+
async function measureCliRun(target, args, options) {
|
|
682
|
+
const started = performance.now();
|
|
683
|
+
const strArgs = args.map(String);
|
|
684
|
+
const useShell = Boolean(options.shell);
|
|
685
|
+
const winCmd = !useShell && isWindowsCmdShim(target);
|
|
686
|
+
const env = { ...process.env, ...options.env };
|
|
687
|
+
let child;
|
|
688
|
+
try {
|
|
689
|
+
if (winCmd) {
|
|
690
|
+
const spec = buildWindowsCmdSpawn(target, strArgs);
|
|
691
|
+
child = spawn(spec.command, spec.args, {
|
|
692
|
+
cwd: options.cwd,
|
|
693
|
+
env,
|
|
694
|
+
shell: false,
|
|
695
|
+
windowsVerbatimArguments: true,
|
|
696
|
+
windowsHide: true,
|
|
697
|
+
detached: false,
|
|
698
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
699
|
+
});
|
|
700
|
+
}
|
|
701
|
+
else {
|
|
702
|
+
child = spawn(target, strArgs, {
|
|
703
|
+
cwd: options.cwd,
|
|
704
|
+
env,
|
|
705
|
+
shell: useShell,
|
|
706
|
+
windowsHide: true,
|
|
707
|
+
detached: process.platform !== "win32",
|
|
708
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
catch (err) {
|
|
713
|
+
const durationMs = round2(Math.max(0, performance.now() - started));
|
|
714
|
+
return {
|
|
715
|
+
durationMs,
|
|
716
|
+
bytes: 0,
|
|
717
|
+
ok: false,
|
|
718
|
+
error: `command failed: ${errorMessage(err)}`
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
return new Promise((resolve) => {
|
|
722
|
+
let totalBytes = 0;
|
|
723
|
+
let exceededCap = false;
|
|
724
|
+
let timedOut = false;
|
|
725
|
+
let settled = false;
|
|
726
|
+
let spawnErr = null;
|
|
727
|
+
let exitCode = null;
|
|
728
|
+
let timeoutTimer = null;
|
|
729
|
+
let postKillTimer = null;
|
|
730
|
+
const hasher = options.captureHash ? crypto.createHash("sha256") : null;
|
|
731
|
+
const finish = (code, err) => {
|
|
732
|
+
if (settled)
|
|
733
|
+
return;
|
|
734
|
+
settled = true;
|
|
735
|
+
if (timeoutTimer) {
|
|
736
|
+
clearTimeout(timeoutTimer);
|
|
737
|
+
timeoutTimer = null;
|
|
738
|
+
}
|
|
739
|
+
if (postKillTimer) {
|
|
740
|
+
clearTimeout(postKillTimer);
|
|
741
|
+
postKillTimer = null;
|
|
742
|
+
}
|
|
743
|
+
if (timedOut || exceededCap) {
|
|
744
|
+
child.stdin?.destroy();
|
|
745
|
+
child.stdout?.destroy();
|
|
746
|
+
child.stderr?.destroy();
|
|
747
|
+
}
|
|
748
|
+
const durationMs = round2(Math.max(0, performance.now() - started));
|
|
749
|
+
const bytes = exceededCap ? MAX_PERF_BODY_BYTES + 1 : totalBytes;
|
|
750
|
+
if (timedOut) {
|
|
751
|
+
resolve({
|
|
752
|
+
durationMs,
|
|
753
|
+
bytes,
|
|
754
|
+
ok: false,
|
|
755
|
+
error: `command timed out after ${options.timeoutMs}ms`
|
|
756
|
+
});
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
if (exceededCap) {
|
|
760
|
+
resolve({
|
|
761
|
+
durationMs,
|
|
762
|
+
bytes,
|
|
763
|
+
ok: false,
|
|
764
|
+
...(code !== null ? { exitCode: code } : {}),
|
|
765
|
+
error: `command output exceeded MAX_PERF_BODY_BYTES (${MAX_PERF_BODY_BYTES} bytes)`
|
|
766
|
+
});
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
if (err && code === null) {
|
|
770
|
+
resolve({
|
|
771
|
+
durationMs,
|
|
772
|
+
bytes,
|
|
773
|
+
ok: false,
|
|
774
|
+
error: `command failed: ${err.message}`
|
|
775
|
+
});
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
778
|
+
const errors = [];
|
|
779
|
+
if (code === null || !matchesAllowedNumber(code, options.expectedExitCode)) {
|
|
780
|
+
const expArr = Array.isArray(options.expectedExitCode)
|
|
781
|
+
? options.expectedExitCode
|
|
782
|
+
: [options.expectedExitCode];
|
|
783
|
+
errors.push(`exitCode expected ${JSON.stringify(expArr)}, got ${code}`);
|
|
784
|
+
}
|
|
785
|
+
const candidateOutputHash = hasher && bytes > 0 ? hasher.digest("hex") : undefined;
|
|
786
|
+
resolve({
|
|
787
|
+
durationMs,
|
|
788
|
+
bytes,
|
|
789
|
+
ok: errors.length === 0,
|
|
790
|
+
...(code !== null ? { exitCode: code } : {}),
|
|
791
|
+
...(errors.length > 0 ? { error: errors.join("; ") } : {}),
|
|
792
|
+
...(candidateOutputHash ? { candidateOutputHash } : {})
|
|
793
|
+
});
|
|
794
|
+
};
|
|
795
|
+
const onChunk = (chunk) => {
|
|
796
|
+
if (settled || exceededCap)
|
|
797
|
+
return;
|
|
798
|
+
const chunkBytes = Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(chunk, "utf8");
|
|
799
|
+
totalBytes += chunkBytes;
|
|
800
|
+
if (totalBytes > MAX_PERF_BODY_BYTES) {
|
|
801
|
+
exceededCap = true;
|
|
802
|
+
totalBytes = MAX_PERF_BODY_BYTES + 1;
|
|
803
|
+
child.stdin?.destroy();
|
|
804
|
+
child.stdout?.destroy();
|
|
805
|
+
child.stderr?.destroy();
|
|
806
|
+
killProcessTree(child);
|
|
807
|
+
if (postKillTimer)
|
|
808
|
+
clearTimeout(postKillTimer);
|
|
809
|
+
postKillTimer = setTimeout(() => {
|
|
810
|
+
finish(exitCode, spawnErr);
|
|
811
|
+
}, 500);
|
|
812
|
+
postKillTimer.unref?.();
|
|
813
|
+
return;
|
|
814
|
+
}
|
|
815
|
+
if (hasher) {
|
|
816
|
+
if (Buffer.isBuffer(chunk))
|
|
817
|
+
hasher.update(chunk);
|
|
818
|
+
else
|
|
819
|
+
hasher.update(chunk, "utf8");
|
|
820
|
+
}
|
|
821
|
+
};
|
|
822
|
+
child.stdout?.on("error", () => { });
|
|
823
|
+
child.stderr?.on("error", () => { });
|
|
824
|
+
child.stdout?.on("data", onChunk);
|
|
825
|
+
child.stderr?.on("data", onChunk);
|
|
826
|
+
child.stdin?.on("error", () => { });
|
|
827
|
+
if (options.stdin !== undefined && options.stdin !== null) {
|
|
828
|
+
child.stdin?.end(String(options.stdin));
|
|
829
|
+
}
|
|
830
|
+
else {
|
|
831
|
+
child.stdin?.end();
|
|
832
|
+
}
|
|
833
|
+
if (options.timeoutMs > 0) {
|
|
834
|
+
timeoutTimer = setTimeout(() => {
|
|
835
|
+
if (settled)
|
|
836
|
+
return;
|
|
837
|
+
timedOut = true;
|
|
838
|
+
killProcessTree(child);
|
|
839
|
+
if (postKillTimer)
|
|
840
|
+
clearTimeout(postKillTimer);
|
|
841
|
+
postKillTimer = setTimeout(() => {
|
|
842
|
+
finish(null, spawnErr);
|
|
843
|
+
}, 500);
|
|
844
|
+
postKillTimer.unref?.();
|
|
845
|
+
}, options.timeoutMs);
|
|
846
|
+
timeoutTimer.unref?.();
|
|
847
|
+
}
|
|
848
|
+
child.on("error", (err) => {
|
|
849
|
+
spawnErr = err;
|
|
850
|
+
finish(null, err);
|
|
851
|
+
});
|
|
852
|
+
child.on("exit", (code) => {
|
|
853
|
+
exitCode = code;
|
|
854
|
+
if ((timedOut || exceededCap) && !settled) {
|
|
855
|
+
if (postKillTimer)
|
|
856
|
+
clearTimeout(postKillTimer);
|
|
857
|
+
postKillTimer = setTimeout(() => {
|
|
858
|
+
finish(code, spawnErr);
|
|
859
|
+
}, 150);
|
|
860
|
+
postKillTimer.unref?.();
|
|
861
|
+
}
|
|
862
|
+
});
|
|
863
|
+
child.on("close", (code) => {
|
|
864
|
+
finish(code ?? exitCode, spawnErr);
|
|
865
|
+
});
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
function parseCommandTarget(rawTarget) {
|
|
869
|
+
const trimmed = rawTarget.trim();
|
|
870
|
+
if (!trimmed)
|
|
871
|
+
return [];
|
|
872
|
+
if (!trimmed.startsWith('"') && !trimmed.startsWith("'")) {
|
|
873
|
+
try {
|
|
874
|
+
if (fs.existsSync(trimmed) && fs.statSync(trimmed).isFile()) {
|
|
875
|
+
return [trimmed];
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
catch {
|
|
879
|
+
// Fall through to standard quote-aware tokenization.
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
return splitCommand(trimmed);
|
|
883
|
+
}
|
|
884
|
+
function inferPerfKind(domain, rawInput) {
|
|
885
|
+
if (rawInput.kind !== undefined) {
|
|
886
|
+
if (rawInput.kind === "http" || rawInput.kind === "command")
|
|
887
|
+
return rawInput.kind;
|
|
888
|
+
return null;
|
|
889
|
+
}
|
|
890
|
+
const hasPath = typeof rawInput.path === "string" && rawInput.path.trim().length > 0;
|
|
891
|
+
if (domain === "cli" || (rawInput.args !== undefined && !hasPath)) {
|
|
892
|
+
return "command";
|
|
893
|
+
}
|
|
894
|
+
return "http";
|
|
895
|
+
}
|
|
896
|
+
function collectSampleErrors(samples) {
|
|
897
|
+
const unique = [];
|
|
898
|
+
for (const s of samples) {
|
|
899
|
+
if (typeof s.error === "string" && s.error && !unique.includes(s.error)) {
|
|
900
|
+
unique.push(s.error);
|
|
901
|
+
if (unique.length >= MAX_SAMPLE_ERRORS)
|
|
902
|
+
break;
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
return unique;
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
* Verifies deterministic latency percentile & payload size budgets against an HTTP endpoint
|
|
909
|
+
* or CLI command target with strict protocol, memory, timer, and secret-redaction guards.
|
|
910
|
+
*/
|
|
911
|
+
export async function verifyPerfBudget(invariant, ctx, deps = {}) {
|
|
912
|
+
const extraSecrets = new Set();
|
|
913
|
+
const secretOpts = {};
|
|
914
|
+
const emptyFallbackMetrics = (kindVal = "http", runsVal = DEFAULT_PERF_RUNS, warmupVal = DEFAULT_PERF_WARMUP, extra = {}) => ({
|
|
915
|
+
kind: kindVal,
|
|
916
|
+
runs: runsVal,
|
|
917
|
+
warmupRuns: warmupVal,
|
|
918
|
+
latency: computeLatencyPercentiles([]),
|
|
919
|
+
bytes: { minBytes: 0, meanBytes: 0, maxBytes: 0 },
|
|
920
|
+
errorCount: 0,
|
|
921
|
+
errorRate: 0,
|
|
922
|
+
...extra
|
|
923
|
+
});
|
|
924
|
+
// Read top-level ctx/invariant/deps fields safely via descriptors so hostile Proxies/getters fail closed.
|
|
925
|
+
const ctxVarsProp = safeReadOwnDataProp(ctx, "vars", "ctx");
|
|
926
|
+
const ctxVarsSnap = ctxVarsProp.ok
|
|
927
|
+
? readSafeStringMapChecked(ctxVarsProp.value, "ctx.vars")
|
|
928
|
+
: { ok: false, error: ctxVarsProp.error };
|
|
929
|
+
const safeCtxVars = ctxVarsSnap.ok && Object.keys(ctxVarsSnap.value).length > 0 ? ctxVarsSnap.value : undefined;
|
|
930
|
+
const failEarly = (failures, metrics = emptyFallbackMetrics(), varsOverride = safeCtxVars) => scrubOutcome({ status: "fail", score: 0, failures: Array.isArray(failures) ? failures : [failures], metrics }, varsOverride, extraSecrets);
|
|
931
|
+
const invDomainProp = safeReadOwnDataProp(invariant, "domain", "invariant");
|
|
932
|
+
const invInputProp = safeReadOwnDataProp(invariant, "input", "invariant");
|
|
933
|
+
const invExpectedProp = safeReadOwnDataProp(invariant, "expected", "invariant");
|
|
934
|
+
const ctxTargetProp = safeReadOwnDataProp(ctx, "target", "ctx");
|
|
935
|
+
const ctxHeadersProp = safeReadOwnDataProp(ctx, "headers", "ctx");
|
|
936
|
+
const ctxCwdProp = safeReadOwnDataProp(ctx, "cwd", "ctx");
|
|
937
|
+
const depsFetchProp = safeReadOwnDataProp(deps, "fetchWithTimeout", "deps");
|
|
938
|
+
if (!invDomainProp.ok)
|
|
939
|
+
return failEarly(invDomainProp.error);
|
|
940
|
+
if (!invInputProp.ok)
|
|
941
|
+
return failEarly(invInputProp.error);
|
|
942
|
+
if (!invExpectedProp.ok)
|
|
943
|
+
return failEarly(invExpectedProp.error);
|
|
944
|
+
const inputSnap = snapshotPlainRecord(invInputProp.value, "perf_budget input", { allowNullish: true });
|
|
945
|
+
const expectedSnap = snapshotPlainRecord(invExpectedProp.value, "perf_budget expected", { allowNullish: true });
|
|
946
|
+
if (!inputSnap.ok)
|
|
947
|
+
return failEarly(inputSnap.error);
|
|
948
|
+
if (!expectedSnap.ok)
|
|
949
|
+
return failEarly(expectedSnap.error);
|
|
950
|
+
const rawInput = inputSnap.value;
|
|
951
|
+
const rawExpected = expectedSnap.value;
|
|
952
|
+
const kind = inferPerfKind(invDomainProp.value, rawInput);
|
|
953
|
+
const runs = clampInt(rawInput.runs, DEFAULT_PERF_RUNS, 1, MAX_PERF_RUNS);
|
|
954
|
+
const warmupRuns = clampInt(rawInput.warmupRuns, DEFAULT_PERF_WARMUP, 0, MAX_PERF_WARMUP);
|
|
955
|
+
const timeoutMs = clampInt(rawInput.timeoutMs, DEFAULT_PERF_TIMEOUT_MS, MIN_PERF_TIMEOUT_MS, MAX_PERF_TIMEOUT_MS);
|
|
956
|
+
const emptyMetrics = (extra = {}) => emptyFallbackMetrics(kind ?? "http", runs, warmupRuns, extra);
|
|
957
|
+
const fail = (failures, extra, varsOverride = safeCtxVars) => failEarly(failures, emptyMetrics(extra), varsOverride);
|
|
958
|
+
if (!ctxVarsSnap.ok)
|
|
959
|
+
return fail(ctxVarsSnap.error, undefined, undefined);
|
|
960
|
+
if (!ctxTargetProp.ok)
|
|
961
|
+
return fail(ctxTargetProp.error);
|
|
962
|
+
if (!ctxHeadersProp.ok)
|
|
963
|
+
return fail(ctxHeadersProp.error);
|
|
964
|
+
if (!ctxCwdProp.ok)
|
|
965
|
+
return fail(ctxCwdProp.error);
|
|
966
|
+
if (!depsFetchProp.ok)
|
|
967
|
+
return fail(depsFetchProp.error);
|
|
968
|
+
const inputVarsSnap = readSafeStringMapChecked(rawInput.vars, "perf_budget input.vars");
|
|
969
|
+
if (!inputVarsSnap.ok)
|
|
970
|
+
return fail(inputVarsSnap.error);
|
|
971
|
+
const inputVars = inputVarsSnap.value;
|
|
972
|
+
for (const [k, v] of Object.entries(inputVars)) {
|
|
973
|
+
if (isSensitiveKeyName(k) || isSensitiveHeaderName(k) || redactSensitiveText(v) !== v) {
|
|
974
|
+
collectSecretValue(extraSecrets, v, secretOpts);
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
const mergedVars = mergeRuntimeVars(inputVars, safeCtxVars);
|
|
978
|
+
if (!kind) {
|
|
979
|
+
return fail(`invalid perf_budget input.kind: ${JSON.stringify(rawInput.kind)} (expected "http" or "command")`);
|
|
980
|
+
}
|
|
981
|
+
const targetStr = ctxTargetProp.value;
|
|
982
|
+
if (typeof targetStr !== "string" || !targetStr.trim()) {
|
|
983
|
+
throw new VibecodeError("TARGET_MISSING", kind === "command"
|
|
984
|
+
? 'Missing --target "<command>" for CLI performance budget verification.'
|
|
985
|
+
: "Missing --target <base-url> for HTTP performance budget verification.");
|
|
986
|
+
}
|
|
987
|
+
const budgetSpecRes = extractBudgetSpec(rawExpected);
|
|
988
|
+
if (!budgetSpecRes.ok)
|
|
989
|
+
return fail(budgetSpecRes.error);
|
|
990
|
+
const budgetSpec = budgetSpecRes.spec;
|
|
991
|
+
const ctxCwd = typeof ctxCwdProp.value === "string" ? ctxCwdProp.value : undefined;
|
|
992
|
+
const fetchWithTimeout = typeof depsFetchProp.value === "function"
|
|
993
|
+
? depsFetchProp.value
|
|
994
|
+
: undefined;
|
|
995
|
+
const overallStarted = performance.now();
|
|
996
|
+
if (kind === "http") {
|
|
997
|
+
collectUrlSecrets(extraSecrets, targetStr, secretOpts);
|
|
998
|
+
const ctxHeadersSnap = sanitizeHeaderRecordChecked(ctxHeadersProp.value, "ctx.headers");
|
|
999
|
+
if (!ctxHeadersSnap.ok)
|
|
1000
|
+
return fail(ctxHeadersSnap.error);
|
|
1001
|
+
const sanitizedCtxHeaders = ctxHeadersSnap.value;
|
|
1002
|
+
collectHeaderSecrets(extraSecrets, sanitizedCtxHeaders, secretOpts);
|
|
1003
|
+
const unresolved = [];
|
|
1004
|
+
const blocked = [];
|
|
1005
|
+
if (rawInput.method !== undefined && typeof rawInput.method !== "string") {
|
|
1006
|
+
return fail("invalid HTTP method: expected a string");
|
|
1007
|
+
}
|
|
1008
|
+
const rawMethod = typeof rawInput.method === "string"
|
|
1009
|
+
? interpolateVarsString(rawInput.method, mergedVars, unresolved, blocked)
|
|
1010
|
+
: "GET";
|
|
1011
|
+
const methodHadControlChars = STRICT_CONTROL_CHARS_RE.test(rawMethod);
|
|
1012
|
+
const methodTrimmed = rawMethod.trim();
|
|
1013
|
+
const method = rawInput.method === undefined ? "GET" : methodTrimmed.toUpperCase();
|
|
1014
|
+
if (rawInput.path !== undefined && typeof rawInput.path !== "string") {
|
|
1015
|
+
return fail("perf_budget input.path must be a string", { method: method || "GET" });
|
|
1016
|
+
}
|
|
1017
|
+
const rawPath = typeof rawInput.path === "string"
|
|
1018
|
+
? interpolateVarsString(rawInput.path, mergedVars, unresolved, blocked)
|
|
1019
|
+
: "/";
|
|
1020
|
+
collectUrlSecrets(extraSecrets, rawPath, secretOpts);
|
|
1021
|
+
let interpolatedQuery;
|
|
1022
|
+
if (rawInput.query !== undefined) {
|
|
1023
|
+
const querySnap = snapshotPlainRecord(rawInput.query, "perf_budget input.query");
|
|
1024
|
+
if (!querySnap.ok)
|
|
1025
|
+
return fail(querySnap.error, { method });
|
|
1026
|
+
interpolatedQuery = {};
|
|
1027
|
+
for (const [k, v] of Object.entries(querySnap.value)) {
|
|
1028
|
+
if (isForbiddenObjectKey(k) || v === undefined || v === null)
|
|
1029
|
+
continue;
|
|
1030
|
+
let resolvedVal;
|
|
1031
|
+
if (typeof v === "string") {
|
|
1032
|
+
resolvedVal = interpolateVarsString(v, mergedVars, unresolved, blocked);
|
|
1033
|
+
}
|
|
1034
|
+
else if (typeof v === "number" || typeof v === "boolean") {
|
|
1035
|
+
resolvedVal = v;
|
|
1036
|
+
}
|
|
1037
|
+
else {
|
|
1038
|
+
return fail(`perf_budget input.query[${JSON.stringify(k)}] must be a string, number, or boolean`, { method });
|
|
1039
|
+
}
|
|
1040
|
+
if (isSensitiveQueryParamName(k) || isSensitiveKeyName(k)) {
|
|
1041
|
+
collectSecretValue(extraSecrets, String(resolvedVal), secretOpts);
|
|
1042
|
+
}
|
|
1043
|
+
defineOwnProp(interpolatedQuery, k, resolvedVal);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
let rawInputHeaders;
|
|
1047
|
+
if (rawInput.headers !== undefined) {
|
|
1048
|
+
const inputHeadersSnap = sanitizeHeaderRecordChecked(rawInput.headers, "perf_budget input.headers");
|
|
1049
|
+
if (!inputHeadersSnap.ok)
|
|
1050
|
+
return fail(inputHeadersSnap.error, { method });
|
|
1051
|
+
rawInputHeaders = {};
|
|
1052
|
+
for (const [k, v] of Object.entries(inputHeadersSnap.value)) {
|
|
1053
|
+
const resolvedVal = interpolateVarsString(v, mergedVars, unresolved, blocked);
|
|
1054
|
+
defineOwnProp(rawInputHeaders, k, resolvedVal);
|
|
1055
|
+
}
|
|
1056
|
+
collectHeaderSecrets(extraSecrets, rawInputHeaders, secretOpts);
|
|
1057
|
+
}
|
|
1058
|
+
let resolvedRawBody = undefined;
|
|
1059
|
+
if (rawInput.body !== undefined && rawInput.body !== null) {
|
|
1060
|
+
const bodyErrors = [];
|
|
1061
|
+
resolvedRawBody = interpolateVarsDeep(rawInput.body, mergedVars, unresolved, blocked, bodyErrors);
|
|
1062
|
+
if (bodyErrors.length > 0)
|
|
1063
|
+
return fail(bodyErrors, { method, url: rawPath });
|
|
1064
|
+
if (typeof resolvedRawBody === "string") {
|
|
1065
|
+
if (redactSensitiveText(resolvedRawBody) !== resolvedRawBody) {
|
|
1066
|
+
collectSecretValue(extraSecrets, resolvedRawBody, secretOpts);
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
else {
|
|
1070
|
+
collectJsonSecrets(extraSecrets, resolvedRawBody, { maxDepth: MAX_TRAVERSAL_DEPTH, ...secretOpts });
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
if (blocked.length > 0 || unresolved.length > 0) {
|
|
1074
|
+
return fail([
|
|
1075
|
+
...blocked.map((expr) => `blocked prototype key in template expression "${expr}"`),
|
|
1076
|
+
...unresolved.map((expr) => `unresolved template expression "${expr}"`)
|
|
1077
|
+
], { method, url: rawPath });
|
|
1078
|
+
}
|
|
1079
|
+
let parsedUrl;
|
|
1080
|
+
try {
|
|
1081
|
+
parsedUrl = resolveSafeTargetUrl(rawPath, targetStr, { query: interpolatedQuery });
|
|
1082
|
+
}
|
|
1083
|
+
catch (err) {
|
|
1084
|
+
return fail(`invalid HTTP URL: ${errorMessage(err)}`, { method, url: rawPath });
|
|
1085
|
+
}
|
|
1086
|
+
const url = parsedUrl.toString();
|
|
1087
|
+
collectUrlSecrets(extraSecrets, url, secretOpts);
|
|
1088
|
+
if (methodHadControlChars || !method || STRICT_CONTROL_CHARS_RE.test(method) || !HTTP_METHOD_RE.test(method)) {
|
|
1089
|
+
return fail(`invalid HTTP method: ${JSON.stringify(rawMethod)}`, { method, url });
|
|
1090
|
+
}
|
|
1091
|
+
// Validate raw header names/values BEFORE filterRuntimeHeaders trims or drops entries.
|
|
1092
|
+
const rawHeaderErr = validateHeaders(rawInputHeaders) ?? validateHeaders(sanitizedCtxHeaders);
|
|
1093
|
+
if (rawHeaderErr)
|
|
1094
|
+
return fail(rawHeaderErr, { method, url });
|
|
1095
|
+
const filteredInputHeaders = filterRuntimeHeaders(rawInputHeaders);
|
|
1096
|
+
const filteredCtxHeaders = filterRuntimeHeaders(sanitizedCtxHeaders);
|
|
1097
|
+
const headers = mergeHeaders(filteredInputHeaders, filteredCtxHeaders);
|
|
1098
|
+
let serializedBody;
|
|
1099
|
+
if (resolvedRawBody !== undefined && resolvedRawBody !== null) {
|
|
1100
|
+
if (typeof resolvedRawBody === "string") {
|
|
1101
|
+
serializedBody = resolvedRawBody;
|
|
1102
|
+
}
|
|
1103
|
+
else {
|
|
1104
|
+
try {
|
|
1105
|
+
serializedBody = JSON.stringify(resolvedRawBody);
|
|
1106
|
+
}
|
|
1107
|
+
catch (err) {
|
|
1108
|
+
return fail(`failed to serialize request body: ${errorMessage(err)}`, { method, url });
|
|
1109
|
+
}
|
|
1110
|
+
if (!Object.keys(headers).some((k) => k.toLowerCase() === "content-type")) {
|
|
1111
|
+
headers["Content-Type"] = "application/json";
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
const runOptions = {
|
|
1116
|
+
method,
|
|
1117
|
+
headers,
|
|
1118
|
+
body: serializedBody,
|
|
1119
|
+
rawBody: resolvedRawBody,
|
|
1120
|
+
timeoutMs,
|
|
1121
|
+
expectedStatus: budgetSpec.status
|
|
1122
|
+
};
|
|
1123
|
+
// Sequential warmup runs (discarded from statistics).
|
|
1124
|
+
for (let w = 0; w < warmupRuns; w++) {
|
|
1125
|
+
await measureHttpRun(url, runOptions, fetchWithTimeout);
|
|
1126
|
+
}
|
|
1127
|
+
// Sequential measured runs to avoid self-contention distortion.
|
|
1128
|
+
const samples = [];
|
|
1129
|
+
let lastOutputHash;
|
|
1130
|
+
for (let run = 1; run <= runs; run++) {
|
|
1131
|
+
const { candidateOutputHash, ...sample } = await measureHttpRun(url, run === runs ? { ...runOptions, captureHash: true } : runOptions, fetchWithTimeout);
|
|
1132
|
+
if (candidateOutputHash)
|
|
1133
|
+
lastOutputHash = candidateOutputHash;
|
|
1134
|
+
samples.push({ run, ...sample });
|
|
1135
|
+
}
|
|
1136
|
+
const evaluation = evaluatePerfBudget(samples, budgetSpec);
|
|
1137
|
+
const sampleErrors = collectSampleErrors(samples);
|
|
1138
|
+
const diff = {};
|
|
1139
|
+
if (!evaluation.passed) {
|
|
1140
|
+
diff.code = "PERFORMANCE_REGRESSION";
|
|
1141
|
+
diff.actual = {
|
|
1142
|
+
latency: evaluation.latency,
|
|
1143
|
+
bytes: evaluation.bytes,
|
|
1144
|
+
errorCount: evaluation.errorCount,
|
|
1145
|
+
errorRate: evaluation.errorRate,
|
|
1146
|
+
sampleCount: evaluation.sampleCount
|
|
1147
|
+
};
|
|
1148
|
+
diff.budget = summarizeBudget(budgetSpec);
|
|
1149
|
+
diff.violations = evaluation.failures;
|
|
1150
|
+
if (sampleErrors.length > 0)
|
|
1151
|
+
diff.sampleErrors = sampleErrors;
|
|
1152
|
+
}
|
|
1153
|
+
return scrubOutcome({
|
|
1154
|
+
status: evaluation.passed ? "pass" : "fail",
|
|
1155
|
+
score: evaluation.passed ? 1 : 0,
|
|
1156
|
+
failures: evaluation.failures,
|
|
1157
|
+
...(Object.keys(diff).length > 0 ? { diff } : {}),
|
|
1158
|
+
metrics: {
|
|
1159
|
+
kind: "http",
|
|
1160
|
+
method,
|
|
1161
|
+
url,
|
|
1162
|
+
runs,
|
|
1163
|
+
warmupRuns,
|
|
1164
|
+
latency: evaluation.latency,
|
|
1165
|
+
bytes: evaluation.bytes,
|
|
1166
|
+
errorCount: evaluation.errorCount,
|
|
1167
|
+
errorRate: evaluation.errorRate,
|
|
1168
|
+
sampleCount: evaluation.sampleCount,
|
|
1169
|
+
durationMs: round2(Math.max(0, performance.now() - overallStarted)),
|
|
1170
|
+
...(lastOutputHash ? { candidateOutputHash: lastOutputHash } : {})
|
|
1171
|
+
}
|
|
1172
|
+
}, safeCtxVars, extraSecrets);
|
|
1173
|
+
}
|
|
1174
|
+
// CLI mode (`kind === "command"`)
|
|
1175
|
+
collectUrlSecrets(extraSecrets, targetStr, secretOpts);
|
|
1176
|
+
const tokens = parseCommandTarget(targetStr);
|
|
1177
|
+
if (tokens.length === 0) {
|
|
1178
|
+
throw new VibecodeError("TARGET_MISSING", "Invalid --target command for CLI performance budget verification.");
|
|
1179
|
+
}
|
|
1180
|
+
if (rawInput.args !== undefined && !safeIsArray(rawInput.args)) {
|
|
1181
|
+
return fail("perf_budget input.args must be an array of strings");
|
|
1182
|
+
}
|
|
1183
|
+
const unresolved = [];
|
|
1184
|
+
const blocked = [];
|
|
1185
|
+
const interpolatedInputArgs = [];
|
|
1186
|
+
if (rawInput.args !== undefined && safeIsArray(rawInput.args)) {
|
|
1187
|
+
const argsLen = safeLength(rawInput.args, 1024);
|
|
1188
|
+
for (let i = 0; i < argsLen; i++) {
|
|
1189
|
+
let rawArg;
|
|
1190
|
+
try {
|
|
1191
|
+
rawArg = rawInput.args[i];
|
|
1192
|
+
}
|
|
1193
|
+
catch (err) {
|
|
1194
|
+
return fail(`perf_budget input.args[${i}] could not be read safely: ${errorMessage(err)}`);
|
|
1195
|
+
}
|
|
1196
|
+
const strArg = safePrimitiveToString(rawArg);
|
|
1197
|
+
if (strArg === null)
|
|
1198
|
+
return fail(`perf_budget input.args[${i}] must be a string or primitive value`);
|
|
1199
|
+
const resolvedArg = interpolateVarsString(strArg, mergedVars, unresolved, blocked);
|
|
1200
|
+
collectUrlSecrets(extraSecrets, resolvedArg, secretOpts);
|
|
1201
|
+
if (redactSensitiveText(resolvedArg) !== resolvedArg)
|
|
1202
|
+
collectSecretValue(extraSecrets, resolvedArg, secretOpts);
|
|
1203
|
+
interpolatedInputArgs.push(resolvedArg);
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
let stdin;
|
|
1207
|
+
if (rawInput.stdin !== undefined && rawInput.stdin !== null) {
|
|
1208
|
+
const stdinStr = safePrimitiveToString(rawInput.stdin);
|
|
1209
|
+
if (stdinStr === null)
|
|
1210
|
+
return fail("perf_budget input.stdin must be a string");
|
|
1211
|
+
stdin = interpolateVarsString(stdinStr, mergedVars, unresolved, blocked);
|
|
1212
|
+
if (redactSensitiveText(stdin) !== stdin)
|
|
1213
|
+
collectSecretValue(extraSecrets, stdin, secretOpts);
|
|
1214
|
+
}
|
|
1215
|
+
const env = { ...DETERMINISTIC_CLI_ENV };
|
|
1216
|
+
if (rawInput.env !== undefined) {
|
|
1217
|
+
const envSnap = snapshotPlainRecord(rawInput.env, "perf_budget input.env");
|
|
1218
|
+
if (!envSnap.ok)
|
|
1219
|
+
return fail(envSnap.error);
|
|
1220
|
+
for (const [k, v] of Object.entries(envSnap.value)) {
|
|
1221
|
+
if (isForbiddenObjectKey(k))
|
|
1222
|
+
continue;
|
|
1223
|
+
if (v === undefined) {
|
|
1224
|
+
defineOwnProp(env, k, undefined);
|
|
1225
|
+
}
|
|
1226
|
+
else {
|
|
1227
|
+
const valStr = safePrimitiveToString(v);
|
|
1228
|
+
if (valStr === null)
|
|
1229
|
+
return fail(`perf_budget input.env[${JSON.stringify(k)}] must be a string or primitive value`);
|
|
1230
|
+
const resolvedVal = interpolateVarsString(valStr, mergedVars, unresolved, blocked);
|
|
1231
|
+
if (isSensitiveKeyName(k) || isSensitiveHeaderName(k) || redactSensitiveText(resolvedVal) !== resolvedVal) {
|
|
1232
|
+
collectSecretValue(extraSecrets, resolvedVal, secretOpts);
|
|
1233
|
+
}
|
|
1234
|
+
defineOwnProp(env, k, resolvedVal);
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
if (rawInput.cwd !== undefined && typeof rawInput.cwd !== "string") {
|
|
1239
|
+
return fail("perf_budget input.cwd must be a string");
|
|
1240
|
+
}
|
|
1241
|
+
if (typeof rawInput.cwd === "string" && STRICT_CONTROL_CHARS_RE.test(rawInput.cwd)) {
|
|
1242
|
+
return fail("perf_budget input.cwd must not contain control characters");
|
|
1243
|
+
}
|
|
1244
|
+
if (blocked.length > 0 || unresolved.length > 0) {
|
|
1245
|
+
return fail([
|
|
1246
|
+
...blocked.map((expr) => `blocked prototype key in template expression "${expr}"`),
|
|
1247
|
+
...unresolved.map((expr) => `unresolved template expression "${expr}"`)
|
|
1248
|
+
]);
|
|
1249
|
+
}
|
|
1250
|
+
const resolvedAll = resolveCommandForSandbox([...tokens, ...interpolatedInputArgs], ctxCwd);
|
|
1251
|
+
const [targetCmd, ...finalArgs] = resolvedAll;
|
|
1252
|
+
const expectedExitCode = budgetSpec.exitCode ?? [0];
|
|
1253
|
+
const shell = rawInput.shell === true;
|
|
1254
|
+
const hasExplicitCwd = typeof rawInput.cwd === "string" && rawInput.cwd.trim().length > 0 && rawInput.cwd.trim() !== ".";
|
|
1255
|
+
let sandboxDir = null;
|
|
1256
|
+
let effectiveCwd;
|
|
1257
|
+
if (hasExplicitCwd) {
|
|
1258
|
+
effectiveCwd = path.resolve(ctxCwd || process.cwd(), String(rawInput.cwd));
|
|
1259
|
+
if (isInsideVaultDirectory(effectiveCwd)) {
|
|
1260
|
+
return fail("perf_budget input.cwd must not point inside a holdout vault directory");
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
else {
|
|
1264
|
+
sandboxDir = fs.mkdtempSync(path.join(os.tmpdir(), "vibecode-perf-cli-"));
|
|
1265
|
+
effectiveCwd = sandboxDir;
|
|
1266
|
+
}
|
|
1267
|
+
const samples = [];
|
|
1268
|
+
let lastOutputHash;
|
|
1269
|
+
try {
|
|
1270
|
+
const cliOptions = {
|
|
1271
|
+
stdin,
|
|
1272
|
+
env,
|
|
1273
|
+
cwd: effectiveCwd,
|
|
1274
|
+
timeoutMs,
|
|
1275
|
+
shell,
|
|
1276
|
+
expectedExitCode
|
|
1277
|
+
};
|
|
1278
|
+
for (let w = 0; w < warmupRuns; w++) {
|
|
1279
|
+
await measureCliRun(targetCmd, finalArgs, cliOptions);
|
|
1280
|
+
}
|
|
1281
|
+
for (let run = 1; run <= runs; run++) {
|
|
1282
|
+
const { candidateOutputHash, ...sample } = await measureCliRun(targetCmd, finalArgs, run === runs ? { ...cliOptions, captureHash: true } : cliOptions);
|
|
1283
|
+
if (candidateOutputHash)
|
|
1284
|
+
lastOutputHash = candidateOutputHash;
|
|
1285
|
+
samples.push({ run, ...sample });
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
finally {
|
|
1289
|
+
if (sandboxDir) {
|
|
1290
|
+
fs.rmSync(sandboxDir, { recursive: true, force: true, maxRetries: 15, retryDelay: 50 });
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
const evaluation = evaluatePerfBudget(samples, budgetSpec);
|
|
1294
|
+
const sampleErrors = collectSampleErrors(samples);
|
|
1295
|
+
const diff = {};
|
|
1296
|
+
if (!evaluation.passed) {
|
|
1297
|
+
diff.code = "PERFORMANCE_REGRESSION";
|
|
1298
|
+
diff.actual = {
|
|
1299
|
+
latency: evaluation.latency,
|
|
1300
|
+
bytes: evaluation.bytes,
|
|
1301
|
+
errorCount: evaluation.errorCount,
|
|
1302
|
+
errorRate: evaluation.errorRate,
|
|
1303
|
+
sampleCount: evaluation.sampleCount
|
|
1304
|
+
};
|
|
1305
|
+
diff.budget = summarizeBudget(budgetSpec);
|
|
1306
|
+
diff.violations = evaluation.failures;
|
|
1307
|
+
if (sampleErrors.length > 0)
|
|
1308
|
+
diff.sampleErrors = sampleErrors;
|
|
1309
|
+
}
|
|
1310
|
+
return scrubOutcome({
|
|
1311
|
+
status: evaluation.passed ? "pass" : "fail",
|
|
1312
|
+
score: evaluation.passed ? 1 : 0,
|
|
1313
|
+
failures: evaluation.failures,
|
|
1314
|
+
...(Object.keys(diff).length > 0 ? { diff } : {}),
|
|
1315
|
+
metrics: {
|
|
1316
|
+
kind: "command",
|
|
1317
|
+
runs,
|
|
1318
|
+
warmupRuns,
|
|
1319
|
+
latency: evaluation.latency,
|
|
1320
|
+
bytes: evaluation.bytes,
|
|
1321
|
+
errorCount: evaluation.errorCount,
|
|
1322
|
+
errorRate: evaluation.errorRate,
|
|
1323
|
+
sampleCount: evaluation.sampleCount,
|
|
1324
|
+
durationMs: round2(Math.max(0, performance.now() - overallStarted)),
|
|
1325
|
+
...(lastOutputHash ? { candidateOutputHash: lastOutputHash } : {})
|
|
1326
|
+
}
|
|
1327
|
+
}, safeCtxVars, extraSecrets);
|
|
1328
|
+
}
|
|
1329
|
+
export const verifyInvariant = verifyPerfBudget;
|