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,1190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zero-dependency, bounded, holdout-opaque verification trend & hotspot ledger
|
|
3
|
+
* persisted at `.vibecode/trends.ndjson`.
|
|
4
|
+
*/
|
|
5
|
+
import crypto from "node:crypto";
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { VibecodeError, errorCode } from "../core/errors.js";
|
|
9
|
+
import { STRICT_CONTROL_CHARS_RE, clampInt, isForbiddenObjectKey, isInsideVaultDirectory, isPathWithinDir, isRecordSafe, redactSensitiveText, safeIsArray, safeLength, safeString, sanitizeSingleLine } from "../core/security.js";
|
|
10
|
+
import { readContract, readHoldouts } from "../core/store.js";
|
|
11
|
+
export const TRENDS_FILE = ".vibecode/trends.ndjson";
|
|
12
|
+
export const MAX_TREND_ENTRIES = 200;
|
|
13
|
+
export const MAX_TRENDS_FILE_BYTES = 4 * 1024 * 1024;
|
|
14
|
+
export const DEFAULT_TREND_WINDOW = 20;
|
|
15
|
+
export const DEFAULT_MAX_TREND_BRIEF_CHARS = 1500;
|
|
16
|
+
const SPARK_BLOCKS = "▁▂▃▄▅▆▇█";
|
|
17
|
+
const FLAT_NONZERO_SPARK_INDEX = 4;
|
|
18
|
+
const DEFAULT_MAX_HOTSPOTS = 10;
|
|
19
|
+
const MAX_HOTSPOTS_CAP = 200;
|
|
20
|
+
const MAX_SLOWEST_INVARIANTS = 5;
|
|
21
|
+
const MAX_PRETTY_HOTSPOTS = 20;
|
|
22
|
+
const MAX_BRIEF_CHARS_CAP = 1_000_000;
|
|
23
|
+
const MAX_ID_CHARS = 160;
|
|
24
|
+
const MAX_META_CHARS = 64;
|
|
25
|
+
const MAX_VISIBLE_SAMPLES_PER_ENTRY = 2000;
|
|
26
|
+
const MAX_TREND_ARRAY_SCAN = 100_000;
|
|
27
|
+
const MAX_INVARIANT_ARRAY_SCAN = 20_000;
|
|
28
|
+
const MAX_ID_SANITIZE_CACHE = 4096;
|
|
29
|
+
const READ_CHUNK_BYTES = 64 * 1024;
|
|
30
|
+
const LATENCY_DRIFT_RATIO_THRESHOLD = 1.5;
|
|
31
|
+
const LATENCY_DRIFT_DELTA_MS_THRESHOLD = 25;
|
|
32
|
+
const INVARIANT_DRIFT_MIN_RATIO = 1.2;
|
|
33
|
+
const TREND_DIRECTION_DELTA_THRESHOLD = 0.02;
|
|
34
|
+
const VALID_GATE_STATUSES = new Set([
|
|
35
|
+
"pass",
|
|
36
|
+
"pass_with_warnings",
|
|
37
|
+
"fail",
|
|
38
|
+
"incomplete"
|
|
39
|
+
]);
|
|
40
|
+
const VALID_INVARIANT_STATUSES = new Set([
|
|
41
|
+
"pass",
|
|
42
|
+
"fail",
|
|
43
|
+
"skipped",
|
|
44
|
+
"warn",
|
|
45
|
+
"error"
|
|
46
|
+
]);
|
|
47
|
+
const ANSI = {
|
|
48
|
+
reset: "\x1b[0m",
|
|
49
|
+
bold: "\x1b[1m",
|
|
50
|
+
dim: "\x1b[2m",
|
|
51
|
+
red: "\x1b[31m",
|
|
52
|
+
green: "\x1b[32m",
|
|
53
|
+
yellow: "\x1b[33m",
|
|
54
|
+
cyan: "\x1b[36m"
|
|
55
|
+
};
|
|
56
|
+
const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
57
|
+
const isRecord = isRecordSafe;
|
|
58
|
+
function own(obj, key) {
|
|
59
|
+
if (!isRecord(obj) || isForbiddenObjectKey(key))
|
|
60
|
+
return undefined;
|
|
61
|
+
try {
|
|
62
|
+
return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function roundNum(value, decimals = 6) {
|
|
69
|
+
if (!Number.isFinite(value))
|
|
70
|
+
return 0;
|
|
71
|
+
const factor = 10 ** decimals;
|
|
72
|
+
const rounded = Math.round(value * factor) / factor;
|
|
73
|
+
return rounded === 0 ? 0 : rounded;
|
|
74
|
+
}
|
|
75
|
+
function clamp01(value) {
|
|
76
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
77
|
+
return 0;
|
|
78
|
+
return Math.max(0, Math.min(1, value));
|
|
79
|
+
}
|
|
80
|
+
function finiteNonNeg(value, fallback = 0) {
|
|
81
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
82
|
+
return fallback;
|
|
83
|
+
return value < 0 ? 0 : value;
|
|
84
|
+
}
|
|
85
|
+
function finiteNonNegInt(value, fallback = 0) {
|
|
86
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
87
|
+
return fallback;
|
|
88
|
+
return value <= 0 ? 0 : Math.floor(value);
|
|
89
|
+
}
|
|
90
|
+
function toGateStatus(value, fallback = "fail") {
|
|
91
|
+
return typeof value === "string" && VALID_GATE_STATUSES.has(value)
|
|
92
|
+
? value
|
|
93
|
+
: fallback;
|
|
94
|
+
}
|
|
95
|
+
function toInvariantStatus(value, fallback = "fail") {
|
|
96
|
+
return typeof value === "string" && VALID_INVARIANT_STATUSES.has(value)
|
|
97
|
+
? value
|
|
98
|
+
: fallback;
|
|
99
|
+
}
|
|
100
|
+
function isPassingGate(status) {
|
|
101
|
+
return status === "pass" || status === "pass_with_warnings";
|
|
102
|
+
}
|
|
103
|
+
function isFailureInvariantStatus(status) {
|
|
104
|
+
return status === "fail" || status === "error";
|
|
105
|
+
}
|
|
106
|
+
function isHoldoutResult(result) {
|
|
107
|
+
if (!isRecord(result))
|
|
108
|
+
return false;
|
|
109
|
+
const metrics = own(result, "metrics");
|
|
110
|
+
return (own(metrics, "redacted") === true ||
|
|
111
|
+
own(metrics, "holdout") === true ||
|
|
112
|
+
typeof own(metrics, "holdoutHint") === "string" ||
|
|
113
|
+
own(result, "redacted") === true ||
|
|
114
|
+
own(result, "holdout") === true ||
|
|
115
|
+
typeof own(result, "holdoutHint") === "string");
|
|
116
|
+
}
|
|
117
|
+
function formatPct(ratio) {
|
|
118
|
+
return `${(clamp01(ratio) * 100).toFixed(1)}%`;
|
|
119
|
+
}
|
|
120
|
+
function formatSignedPct(delta) {
|
|
121
|
+
const safe = Number.isFinite(delta) ? delta : 0;
|
|
122
|
+
const pct = safe * 100;
|
|
123
|
+
if (Math.abs(pct) < 0.05)
|
|
124
|
+
return "+0.0%";
|
|
125
|
+
return `${pct > 0 ? "+" : ""}${pct.toFixed(1)}%`;
|
|
126
|
+
}
|
|
127
|
+
function formatMs(ms) {
|
|
128
|
+
const safe = finiteNonNeg(ms, 0);
|
|
129
|
+
return `${roundNum(safe, 1)}ms`;
|
|
130
|
+
}
|
|
131
|
+
function formatSignedMs(delta) {
|
|
132
|
+
const safe = Number.isFinite(delta) ? roundNum(delta, 1) : 0;
|
|
133
|
+
if (safe === 0)
|
|
134
|
+
return "+0ms";
|
|
135
|
+
return `${safe > 0 ? "+" : ""}${safe}ms`;
|
|
136
|
+
}
|
|
137
|
+
function style(text, codes, useColor) {
|
|
138
|
+
return useColor ? `${codes}${text}${ANSI.reset}` : text;
|
|
139
|
+
}
|
|
140
|
+
function computeMedian(values) {
|
|
141
|
+
const finite = [];
|
|
142
|
+
for (const v of values) {
|
|
143
|
+
if (typeof v === "number" && Number.isFinite(v)) {
|
|
144
|
+
finite.push(v < 0 ? 0 : v);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (finite.length === 0)
|
|
148
|
+
return 0;
|
|
149
|
+
finite.sort((a, b) => a - b);
|
|
150
|
+
const mid = Math.floor(finite.length / 2);
|
|
151
|
+
const med = finite.length % 2 === 1 ? finite[mid] : (finite[mid - 1] + finite[mid]) / 2;
|
|
152
|
+
return roundNum(med, 3);
|
|
153
|
+
}
|
|
154
|
+
function computeLatencyRatio(baselineMs, recentMs) {
|
|
155
|
+
if (baselineMs > 0)
|
|
156
|
+
return roundNum(recentMs / baselineMs, 4);
|
|
157
|
+
if (recentMs <= 0)
|
|
158
|
+
return 1;
|
|
159
|
+
return roundNum(recentMs, 4);
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Maps finite numeric values deterministically to 8-level Unicode sparkline blocks (`▁▂▃▄▅▆▇█`).
|
|
163
|
+
*/
|
|
164
|
+
export function renderSparkline(values, options) {
|
|
165
|
+
if (!safeIsArray(values))
|
|
166
|
+
return "";
|
|
167
|
+
const finite = [];
|
|
168
|
+
const len = safeLength(values, MAX_TREND_ARRAY_SCAN);
|
|
169
|
+
for (let i = 0; i < len; i++) {
|
|
170
|
+
let v;
|
|
171
|
+
try {
|
|
172
|
+
v = values[i];
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
if (typeof v === "number" && Number.isFinite(v)) {
|
|
178
|
+
finite.push(v);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (finite.length === 0)
|
|
182
|
+
return "";
|
|
183
|
+
let dataMin = finite[0];
|
|
184
|
+
let dataMax = finite[0];
|
|
185
|
+
for (let i = 1; i < finite.length; i++) {
|
|
186
|
+
if (finite[i] < dataMin)
|
|
187
|
+
dataMin = finite[i];
|
|
188
|
+
if (finite[i] > dataMax)
|
|
189
|
+
dataMax = finite[i];
|
|
190
|
+
}
|
|
191
|
+
const rawMin = own(options, "min");
|
|
192
|
+
const rawMax = own(options, "max");
|
|
193
|
+
const lo = typeof rawMin === "number" && Number.isFinite(rawMin) ? rawMin : dataMin;
|
|
194
|
+
const hi = typeof rawMax === "number" && Number.isFinite(rawMax) ? rawMax : dataMax;
|
|
195
|
+
const span = hi - lo;
|
|
196
|
+
let out = "";
|
|
197
|
+
const maxIndex = SPARK_BLOCKS.length - 1;
|
|
198
|
+
if (span <= 0) {
|
|
199
|
+
for (let i = 0; i < finite.length; i++) {
|
|
200
|
+
const idx = finite[i] === 0 ? 0 : FLAT_NONZERO_SPARK_INDEX;
|
|
201
|
+
out += SPARK_BLOCKS[idx];
|
|
202
|
+
}
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
205
|
+
for (let i = 0; i < finite.length; i++) {
|
|
206
|
+
const clamped = Math.max(lo, Math.min(hi, finite[i]));
|
|
207
|
+
const norm = (clamped - lo) / span;
|
|
208
|
+
const idx = Math.max(0, Math.min(maxIndex, Math.round(norm * maxIndex)));
|
|
209
|
+
out += SPARK_BLOCKS[idx];
|
|
210
|
+
}
|
|
211
|
+
return out;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Extracts a compact, sanitized, holdout-opaque `TrendEntry` from a `ParityReport`.
|
|
215
|
+
*/
|
|
216
|
+
export function buildTrendEntry(report, options) {
|
|
217
|
+
const safeReport = isRecord(report) ? report : {};
|
|
218
|
+
const rawResults = own(safeReport, "results");
|
|
219
|
+
const results = safeIsArray(rawResults) ? rawResults : [];
|
|
220
|
+
let holdoutCount = 0;
|
|
221
|
+
let summedDurationMs = 0;
|
|
222
|
+
let inferredHardPassed = 0;
|
|
223
|
+
let inferredHardTotal = 0;
|
|
224
|
+
let inferredSoftPassed = 0;
|
|
225
|
+
let inferredSoftTotal = 0;
|
|
226
|
+
const visibleInvariants = [];
|
|
227
|
+
const resultsLen = safeLength(results, MAX_INVARIANT_ARRAY_SCAN);
|
|
228
|
+
for (let i = 0; i < resultsLen; i++) {
|
|
229
|
+
let item;
|
|
230
|
+
try {
|
|
231
|
+
item = results[i];
|
|
232
|
+
}
|
|
233
|
+
catch {
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (!isRecord(item))
|
|
237
|
+
continue;
|
|
238
|
+
const status = toInvariantStatus(own(item, "status"), "fail");
|
|
239
|
+
const durationMs = roundNum(finiteNonNeg(own(item, "durationMs"), 0), 3);
|
|
240
|
+
summedDurationMs += durationMs;
|
|
241
|
+
const severity = own(item, "severity");
|
|
242
|
+
if (severity === "hard") {
|
|
243
|
+
inferredHardTotal++;
|
|
244
|
+
if (status === "pass")
|
|
245
|
+
inferredHardPassed++;
|
|
246
|
+
}
|
|
247
|
+
else if (severity === "soft") {
|
|
248
|
+
inferredSoftTotal++;
|
|
249
|
+
if (status === "pass")
|
|
250
|
+
inferredSoftPassed++;
|
|
251
|
+
}
|
|
252
|
+
if (isHoldoutResult(item)) {
|
|
253
|
+
holdoutCount++;
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
if (visibleInvariants.length < MAX_VISIBLE_SAMPLES_PER_ENTRY) {
|
|
257
|
+
const cleanId = sanitizeSingleLine(safeString(own(item, "id")), MAX_ID_CHARS);
|
|
258
|
+
if (cleanId) {
|
|
259
|
+
visibleInvariants.push({ id: cleanId, status, durationMs });
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
const rawTimestamp = sanitizeSingleLine(safeString(own(safeReport, "timestamp")), MAX_META_CHARS);
|
|
264
|
+
const timestamp = rawTimestamp || new Date().toISOString();
|
|
265
|
+
const gateObj = own(safeReport, "gate");
|
|
266
|
+
const gateFallback = own(gateObj, "passed") === true ? "pass" : "fail";
|
|
267
|
+
const gateStatus = toGateStatus(own(gateObj, "status"), gateFallback);
|
|
268
|
+
const hardObj = own(safeReport, "hard");
|
|
269
|
+
const hardPassed = finiteNonNegInt(own(hardObj, "passed"), inferredHardPassed);
|
|
270
|
+
const hardTotal = finiteNonNegInt(own(hardObj, "total"), inferredHardTotal);
|
|
271
|
+
const rawHardParity = own(hardObj, "parity");
|
|
272
|
+
const hardParity = roundNum(typeof rawHardParity === "number" && Number.isFinite(rawHardParity)
|
|
273
|
+
? clamp01(rawHardParity)
|
|
274
|
+
: hardTotal > 0
|
|
275
|
+
? clamp01(hardPassed / hardTotal)
|
|
276
|
+
: 1, 6);
|
|
277
|
+
const softObj = own(safeReport, "soft");
|
|
278
|
+
const softPassed = finiteNonNegInt(own(softObj, "passed"), inferredSoftPassed);
|
|
279
|
+
const softTotal = finiteNonNegInt(own(softObj, "total"), inferredSoftTotal);
|
|
280
|
+
const compositeScore = roundNum(clamp01(own(safeReport, "compositeScore")), 6);
|
|
281
|
+
const optTotalDuration = own(options, "totalDurationMs");
|
|
282
|
+
const totalDurationMs = roundNum(typeof optTotalDuration === "number" && Number.isFinite(optTotalDuration) && optTotalDuration >= 0
|
|
283
|
+
? optTotalDuration
|
|
284
|
+
: summedDurationMs, 3);
|
|
285
|
+
const gitSha = sanitizeSingleLine(safeString(own(options, "gitSha")), MAX_META_CHARS);
|
|
286
|
+
const mode = sanitizeSingleLine(safeString(own(options, "mode")), MAX_META_CHARS);
|
|
287
|
+
const optAffected = own(options, "affected");
|
|
288
|
+
return {
|
|
289
|
+
timestamp,
|
|
290
|
+
...(gitSha ? { gitSha } : {}),
|
|
291
|
+
gateStatus,
|
|
292
|
+
compositeScore,
|
|
293
|
+
hardPassed,
|
|
294
|
+
hardTotal,
|
|
295
|
+
hardParity,
|
|
296
|
+
softPassed,
|
|
297
|
+
softTotal,
|
|
298
|
+
totalDurationMs,
|
|
299
|
+
holdoutCount,
|
|
300
|
+
...(mode ? { mode } : {}),
|
|
301
|
+
...(typeof optAffected === "boolean" ? { affected: optAffected } : {}),
|
|
302
|
+
visibleInvariants
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
function resolveRealOrAncestor(absPath, hopsLeft = 16, visited = new Set()) {
|
|
306
|
+
const normKey = process.platform === "win32" ? absPath.toLowerCase() : absPath;
|
|
307
|
+
if (visited.has(normKey)) {
|
|
308
|
+
throw configInvalid("Trends ledger symlink cycle detected.");
|
|
309
|
+
}
|
|
310
|
+
if (hopsLeft < 0) {
|
|
311
|
+
throw configInvalid("Trends ledger symlink chain exceeded maximum resolution depth.");
|
|
312
|
+
}
|
|
313
|
+
visited.add(normKey);
|
|
314
|
+
let probe = absPath;
|
|
315
|
+
const trailing = [];
|
|
316
|
+
for (let steps = 0; steps < 64; steps++) {
|
|
317
|
+
let lstat;
|
|
318
|
+
try {
|
|
319
|
+
lstat = fs.lstatSync(probe);
|
|
320
|
+
}
|
|
321
|
+
catch (err) {
|
|
322
|
+
const code = errorCode(err);
|
|
323
|
+
if (code === "ENOENT" || code === "ENOTDIR") {
|
|
324
|
+
const parent = path.dirname(probe);
|
|
325
|
+
if (parent === probe)
|
|
326
|
+
break;
|
|
327
|
+
trailing.push(path.basename(probe));
|
|
328
|
+
probe = parent;
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
throw configInvalid(`Trends ledger path could not be verified safely (${code ?? "FS_ERROR"}).`);
|
|
332
|
+
}
|
|
333
|
+
if (lstat.isSymbolicLink()) {
|
|
334
|
+
let linkTarget;
|
|
335
|
+
try {
|
|
336
|
+
linkTarget = fs.readlinkSync(probe);
|
|
337
|
+
}
|
|
338
|
+
catch {
|
|
339
|
+
throw configInvalid("Trends ledger symlink could not be resolved safely.");
|
|
340
|
+
}
|
|
341
|
+
const nextBase = path.resolve(path.dirname(probe), linkTarget);
|
|
342
|
+
const nextFull = trailing.length > 0 ? path.join(nextBase, ...trailing.reverse()) : nextBase;
|
|
343
|
+
return resolveRealOrAncestor(nextFull, hopsLeft - 1, visited);
|
|
344
|
+
}
|
|
345
|
+
try {
|
|
346
|
+
const realAncestor = fs.realpathSync(probe);
|
|
347
|
+
return trailing.length > 0 ? path.join(realAncestor, ...trailing.reverse()) : realAncestor;
|
|
348
|
+
}
|
|
349
|
+
catch (err) {
|
|
350
|
+
const code = errorCode(err);
|
|
351
|
+
throw configInvalid(`Trends ledger path could not be resolved safely (${code ?? "FS_ERROR"}).`);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return absPath;
|
|
355
|
+
}
|
|
356
|
+
function configInvalid(message) {
|
|
357
|
+
return new VibecodeError("CONFIG_INVALID", message);
|
|
358
|
+
}
|
|
359
|
+
function checkSymlinkConfinement(targetPath, realCwd, label) {
|
|
360
|
+
let lstat;
|
|
361
|
+
try {
|
|
362
|
+
lstat = fs.lstatSync(targetPath);
|
|
363
|
+
}
|
|
364
|
+
catch (err) {
|
|
365
|
+
const code = errorCode(err);
|
|
366
|
+
if (code === "ENOENT" || code === "ENOTDIR")
|
|
367
|
+
return null;
|
|
368
|
+
throw configInvalid(`Unable to inspect ${label}: ${code ?? "FS_ERROR"}`);
|
|
369
|
+
}
|
|
370
|
+
if (isInsideVaultDirectory(targetPath)) {
|
|
371
|
+
throw configInvalid(`${label} must not be inside a holdout vault directory.`);
|
|
372
|
+
}
|
|
373
|
+
if (lstat.isSymbolicLink()) {
|
|
374
|
+
const visited = new Set();
|
|
375
|
+
let cursor = targetPath;
|
|
376
|
+
for (let hop = 0; hop < 16; hop++) {
|
|
377
|
+
const cursorKey = process.platform === "win32" ? cursor.toLowerCase() : cursor;
|
|
378
|
+
if (visited.has(cursorKey)) {
|
|
379
|
+
throw configInvalid(`${label} symlink cycle detected.`);
|
|
380
|
+
}
|
|
381
|
+
visited.add(cursorKey);
|
|
382
|
+
let curStat;
|
|
383
|
+
try {
|
|
384
|
+
curStat = fs.lstatSync(cursor);
|
|
385
|
+
}
|
|
386
|
+
catch (err) {
|
|
387
|
+
const code = errorCode(err);
|
|
388
|
+
if (code === "ENOENT" || code === "ENOTDIR")
|
|
389
|
+
break;
|
|
390
|
+
throw configInvalid(`${label} symlink could not be verified safely.`);
|
|
391
|
+
}
|
|
392
|
+
if (!curStat.isSymbolicLink())
|
|
393
|
+
break;
|
|
394
|
+
let linkTarget;
|
|
395
|
+
try {
|
|
396
|
+
linkTarget = fs.readlinkSync(cursor);
|
|
397
|
+
}
|
|
398
|
+
catch {
|
|
399
|
+
throw configInvalid(`${label} symlink could not be resolved safely.`);
|
|
400
|
+
}
|
|
401
|
+
const resolvedLink = path.resolve(path.dirname(cursor), linkTarget);
|
|
402
|
+
const realLink = resolveRealOrAncestor(resolvedLink);
|
|
403
|
+
if (isInsideVaultDirectory(resolvedLink) || isInsideVaultDirectory(realLink)) {
|
|
404
|
+
throw configInvalid(`${label} symlink must not point inside a holdout vault directory.`);
|
|
405
|
+
}
|
|
406
|
+
if (!isPathWithinDir(realLink, realCwd, { allowEqual: false }) ||
|
|
407
|
+
!isPathWithinDir(resolveRealOrAncestor(cursor), realCwd, { allowEqual: false })) {
|
|
408
|
+
throw configInvalid(`${label} symlink escapes the workspace root.`);
|
|
409
|
+
}
|
|
410
|
+
cursor = resolvedLink;
|
|
411
|
+
if (hop === 15) {
|
|
412
|
+
throw configInvalid(`${label} symlink chain exceeded maximum resolution depth.`);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
try {
|
|
416
|
+
const realTarget = fs.realpathSync(targetPath);
|
|
417
|
+
if (isInsideVaultDirectory(realTarget)) {
|
|
418
|
+
throw configInvalid(`${label} symlink resolves inside a holdout vault directory.`);
|
|
419
|
+
}
|
|
420
|
+
if (!isPathWithinDir(realTarget, realCwd, { allowEqual: false })) {
|
|
421
|
+
throw configInvalid(`${label} symlink escapes the workspace root.`);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
catch (err) {
|
|
425
|
+
if (err instanceof VibecodeError)
|
|
426
|
+
throw err;
|
|
427
|
+
const code = errorCode(err);
|
|
428
|
+
if (code === "ENOENT") {
|
|
429
|
+
throw configInvalid(`${label} must not be a dangling symlink.`);
|
|
430
|
+
}
|
|
431
|
+
throw configInvalid(`${label} symlink could not be verified safely.`);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
else {
|
|
435
|
+
try {
|
|
436
|
+
const realTarget = fs.realpathSync(targetPath);
|
|
437
|
+
if (isInsideVaultDirectory(realTarget)) {
|
|
438
|
+
throw configInvalid(`${label} resolves inside a holdout vault directory.`);
|
|
439
|
+
}
|
|
440
|
+
if (!isPathWithinDir(realTarget, realCwd, { allowEqual: false })) {
|
|
441
|
+
throw configInvalid(`${label} escapes the workspace root.`);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
catch (err) {
|
|
445
|
+
if (err instanceof VibecodeError)
|
|
446
|
+
throw err;
|
|
447
|
+
throw configInvalid(`Unable to resolve ${label} inside workspace.`);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
return lstat;
|
|
451
|
+
}
|
|
452
|
+
function resolveConfinedTrendsPaths(cwd) {
|
|
453
|
+
if (typeof cwd !== "string" || !cwd.trim() || STRICT_CONTROL_CHARS_RE.test(cwd)) {
|
|
454
|
+
throw configInvalid("Workspace directory for trends ledger must be a valid path string.");
|
|
455
|
+
}
|
|
456
|
+
const resolvedCwd = path.resolve(cwd);
|
|
457
|
+
const realCwd = resolveRealOrAncestor(resolvedCwd);
|
|
458
|
+
if (isInsideVaultDirectory(resolvedCwd) || isInsideVaultDirectory(realCwd)) {
|
|
459
|
+
throw configInvalid("Trends ledger workspace must not be inside a holdout vault directory.");
|
|
460
|
+
}
|
|
461
|
+
const parts = TRENDS_FILE.split("/");
|
|
462
|
+
const vibecodeDir = path.join(resolvedCwd, parts[0]);
|
|
463
|
+
const trendsPath = path.join(resolvedCwd, ...parts);
|
|
464
|
+
if (!isPathWithinDir(vibecodeDir, resolvedCwd, { allowEqual: false }) ||
|
|
465
|
+
!isPathWithinDir(trendsPath, resolvedCwd, { allowEqual: false })) {
|
|
466
|
+
throw configInvalid("Trends ledger path escapes the workspace root.");
|
|
467
|
+
}
|
|
468
|
+
if (isInsideVaultDirectory(vibecodeDir) || isInsideVaultDirectory(trendsPath)) {
|
|
469
|
+
throw configInvalid("Trends ledger path must not be inside a holdout vault directory.");
|
|
470
|
+
}
|
|
471
|
+
const dirLstat = checkSymlinkConfinement(vibecodeDir, realCwd, ".vibecode directory");
|
|
472
|
+
if (dirLstat) {
|
|
473
|
+
try {
|
|
474
|
+
const dirStat = fs.statSync(vibecodeDir);
|
|
475
|
+
if (!dirStat.isDirectory()) {
|
|
476
|
+
throw configInvalid(".vibecode path exists and is not a directory.");
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
catch (err) {
|
|
480
|
+
if (err instanceof VibecodeError)
|
|
481
|
+
throw err;
|
|
482
|
+
if (errorCode(err) !== "ENOENT") {
|
|
483
|
+
throw configInvalid(".vibecode directory is inaccessible.");
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
const fileLstat = checkSymlinkConfinement(trendsPath, realCwd, TRENDS_FILE);
|
|
488
|
+
if (fileLstat) {
|
|
489
|
+
try {
|
|
490
|
+
const fileStat = fs.statSync(trendsPath);
|
|
491
|
+
if (!fileStat.isFile()) {
|
|
492
|
+
throw configInvalid(`${TRENDS_FILE} must be a regular file.`);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
catch (err) {
|
|
496
|
+
if (err instanceof VibecodeError)
|
|
497
|
+
throw err;
|
|
498
|
+
if (errorCode(err) !== "ENOENT") {
|
|
499
|
+
throw configInvalid(`${TRENDS_FILE} is inaccessible.`);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
return { resolvedCwd, realCwd, vibecodeDir, trendsPath, fileLstat };
|
|
504
|
+
}
|
|
505
|
+
function parseJsonSafely(line) {
|
|
506
|
+
return JSON.parse(line, (key, value) => (isForbiddenObjectKey(key) ? undefined : value));
|
|
507
|
+
}
|
|
508
|
+
function sanitizeCachedId(rawId, cache) {
|
|
509
|
+
if (cache) {
|
|
510
|
+
const hit = cache.get(rawId);
|
|
511
|
+
if (hit !== undefined)
|
|
512
|
+
return hit;
|
|
513
|
+
}
|
|
514
|
+
const clean = sanitizeSingleLine(rawId, MAX_ID_CHARS);
|
|
515
|
+
if (cache && cache.size < MAX_ID_SANITIZE_CACHE) {
|
|
516
|
+
cache.set(rawId, clean);
|
|
517
|
+
}
|
|
518
|
+
return clean;
|
|
519
|
+
}
|
|
520
|
+
function normalizeTrendEntry(raw, idCache) {
|
|
521
|
+
if (!isRecord(raw))
|
|
522
|
+
return null;
|
|
523
|
+
const rawTs = own(raw, "timestamp");
|
|
524
|
+
const rawGate = own(raw, "gateStatus");
|
|
525
|
+
const rawScore = own(raw, "compositeScore");
|
|
526
|
+
if (typeof rawTs !== "string" ||
|
|
527
|
+
typeof rawGate !== "string" ||
|
|
528
|
+
!VALID_GATE_STATUSES.has(rawGate) ||
|
|
529
|
+
typeof rawScore !== "number" ||
|
|
530
|
+
!Number.isFinite(rawScore)) {
|
|
531
|
+
return null;
|
|
532
|
+
}
|
|
533
|
+
const timestamp = sanitizeSingleLine(rawTs, MAX_META_CHARS);
|
|
534
|
+
if (!timestamp)
|
|
535
|
+
return null;
|
|
536
|
+
const hardPassed = finiteNonNegInt(own(raw, "hardPassed"), 0);
|
|
537
|
+
const hardTotal = finiteNonNegInt(own(raw, "hardTotal"), 0);
|
|
538
|
+
const rawHardParity = own(raw, "hardParity");
|
|
539
|
+
const hardParity = roundNum(typeof rawHardParity === "number" && Number.isFinite(rawHardParity)
|
|
540
|
+
? clamp01(rawHardParity)
|
|
541
|
+
: hardTotal > 0
|
|
542
|
+
? clamp01(hardPassed / hardTotal)
|
|
543
|
+
: 1, 6);
|
|
544
|
+
const softPassed = finiteNonNegInt(own(raw, "softPassed"), 0);
|
|
545
|
+
const softTotal = finiteNonNegInt(own(raw, "softTotal"), 0);
|
|
546
|
+
const totalDurationMs = roundNum(finiteNonNeg(own(raw, "totalDurationMs"), 0), 3);
|
|
547
|
+
const holdoutCount = finiteNonNegInt(own(raw, "holdoutCount"), 0);
|
|
548
|
+
const gitSha = sanitizeSingleLine(safeString(own(raw, "gitSha")), MAX_META_CHARS);
|
|
549
|
+
const mode = sanitizeSingleLine(safeString(own(raw, "mode")), MAX_META_CHARS);
|
|
550
|
+
const rawAffected = own(raw, "affected");
|
|
551
|
+
const visibleInvariants = [];
|
|
552
|
+
const rawVisible = own(raw, "visibleInvariants");
|
|
553
|
+
if (safeIsArray(rawVisible)) {
|
|
554
|
+
const rawVisibleLen = safeLength(rawVisible, MAX_INVARIANT_ARRAY_SCAN);
|
|
555
|
+
for (let i = 0; i < rawVisibleLen && visibleInvariants.length < MAX_VISIBLE_SAMPLES_PER_ENTRY; i++) {
|
|
556
|
+
let sample;
|
|
557
|
+
try {
|
|
558
|
+
sample = rawVisible[i];
|
|
559
|
+
}
|
|
560
|
+
catch {
|
|
561
|
+
continue;
|
|
562
|
+
}
|
|
563
|
+
if (!isRecord(sample))
|
|
564
|
+
continue;
|
|
565
|
+
if (isHoldoutResult(sample))
|
|
566
|
+
continue;
|
|
567
|
+
const rawId = own(sample, "id");
|
|
568
|
+
const rawStatus = own(sample, "status");
|
|
569
|
+
if (typeof rawId !== "string" || typeof rawStatus !== "string")
|
|
570
|
+
continue;
|
|
571
|
+
if (!VALID_INVARIANT_STATUSES.has(rawStatus))
|
|
572
|
+
continue;
|
|
573
|
+
const id = sanitizeCachedId(rawId, idCache);
|
|
574
|
+
if (!id)
|
|
575
|
+
continue;
|
|
576
|
+
const durationMs = roundNum(finiteNonNeg(own(sample, "durationMs"), 0), 3);
|
|
577
|
+
visibleInvariants.push({ id, status: rawStatus, durationMs });
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
return {
|
|
581
|
+
timestamp,
|
|
582
|
+
...(gitSha ? { gitSha } : {}),
|
|
583
|
+
gateStatus: rawGate,
|
|
584
|
+
compositeScore: roundNum(clamp01(rawScore), 6),
|
|
585
|
+
hardPassed,
|
|
586
|
+
hardTotal,
|
|
587
|
+
hardParity,
|
|
588
|
+
softPassed,
|
|
589
|
+
softTotal,
|
|
590
|
+
totalDurationMs,
|
|
591
|
+
holdoutCount,
|
|
592
|
+
...(mode ? { mode } : {}),
|
|
593
|
+
...(typeof rawAffected === "boolean" ? { affected: rawAffected } : {}),
|
|
594
|
+
visibleInvariants
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
function readBoundedFileUtf8(fd, maxBytes) {
|
|
598
|
+
const chunks = [];
|
|
599
|
+
let totalBytes = 0;
|
|
600
|
+
const scratch = Buffer.allocUnsafe(READ_CHUNK_BYTES);
|
|
601
|
+
while (true) {
|
|
602
|
+
const remaining = maxBytes - totalBytes + 1;
|
|
603
|
+
const toRead = Math.min(scratch.length, remaining);
|
|
604
|
+
const n = fs.readSync(fd, scratch, 0, toRead, null);
|
|
605
|
+
if (n <= 0)
|
|
606
|
+
break;
|
|
607
|
+
totalBytes += n;
|
|
608
|
+
if (totalBytes > maxBytes) {
|
|
609
|
+
throw configInvalid(`${TRENDS_FILE} exceeds maximum allowed size of ${maxBytes} bytes.`);
|
|
610
|
+
}
|
|
611
|
+
chunks.push(Buffer.from(scratch.subarray(0, n)));
|
|
612
|
+
}
|
|
613
|
+
return chunks.length === 0 ? "" : Buffer.concat(chunks, totalBytes).toString("utf8");
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Reads chronological trend entries from `.vibecode/trends.ndjson`.
|
|
617
|
+
* Rejects symlink escapes, vault paths, and oversized files (> 4 MiB) with `VibecodeError("CONFIG_INVALID")`.
|
|
618
|
+
*/
|
|
619
|
+
export function readTrendEntries(cwd, options) {
|
|
620
|
+
const { trendsPath, fileLstat } = resolveConfinedTrendsPaths(cwd);
|
|
621
|
+
const noFollowFlag = typeof fs.constants.O_NOFOLLOW === "number" && (!fileLstat || !fileLstat.isSymbolicLink())
|
|
622
|
+
? fs.constants.O_NOFOLLOW
|
|
623
|
+
: 0;
|
|
624
|
+
let fd;
|
|
625
|
+
try {
|
|
626
|
+
fd = fs.openSync(trendsPath, fs.constants.O_RDONLY | noFollowFlag);
|
|
627
|
+
}
|
|
628
|
+
catch (err) {
|
|
629
|
+
const code = errorCode(err);
|
|
630
|
+
if (code === "ENOENT" || code === "ENOTDIR")
|
|
631
|
+
return [];
|
|
632
|
+
throw configInvalid(`Unable to read ${TRENDS_FILE}: ${code ?? "FS_ERROR"}`);
|
|
633
|
+
}
|
|
634
|
+
let content;
|
|
635
|
+
try {
|
|
636
|
+
const stat = fs.fstatSync(fd);
|
|
637
|
+
if (!stat.isFile()) {
|
|
638
|
+
throw configInvalid(`${TRENDS_FILE} must be a regular file.`);
|
|
639
|
+
}
|
|
640
|
+
if (stat.size > MAX_TRENDS_FILE_BYTES) {
|
|
641
|
+
throw configInvalid(`${TRENDS_FILE} exceeds maximum allowed size of ${MAX_TRENDS_FILE_BYTES} bytes.`);
|
|
642
|
+
}
|
|
643
|
+
content = readBoundedFileUtf8(fd, MAX_TRENDS_FILE_BYTES);
|
|
644
|
+
}
|
|
645
|
+
finally {
|
|
646
|
+
fs.closeSync(fd);
|
|
647
|
+
}
|
|
648
|
+
const entries = [];
|
|
649
|
+
const idCache = new Map();
|
|
650
|
+
const lines = content.split(/\r?\n/);
|
|
651
|
+
for (const rawLine of lines) {
|
|
652
|
+
const line = rawLine.trim();
|
|
653
|
+
if (!line)
|
|
654
|
+
continue;
|
|
655
|
+
let parsed;
|
|
656
|
+
try {
|
|
657
|
+
parsed = parseJsonSafely(line);
|
|
658
|
+
}
|
|
659
|
+
catch {
|
|
660
|
+
continue;
|
|
661
|
+
}
|
|
662
|
+
const normalized = normalizeTrendEntry(parsed, idCache);
|
|
663
|
+
if (normalized)
|
|
664
|
+
entries.push(normalized);
|
|
665
|
+
}
|
|
666
|
+
const rawLimit = own(options, "limit");
|
|
667
|
+
if (typeof rawLimit === "number" && Number.isFinite(rawLimit)) {
|
|
668
|
+
const limit = Math.floor(rawLimit);
|
|
669
|
+
if (limit <= 0)
|
|
670
|
+
return [];
|
|
671
|
+
return entries.slice(-limit);
|
|
672
|
+
}
|
|
673
|
+
return entries;
|
|
674
|
+
}
|
|
675
|
+
function serializeBoundedNdjson(entries) {
|
|
676
|
+
const serialized = entries.map((e) => JSON.stringify(e));
|
|
677
|
+
let start = 0;
|
|
678
|
+
let totalBytes = serialized.reduce((sum, line) => sum + Buffer.byteLength(line, "utf8") + 1, 0);
|
|
679
|
+
while (totalBytes > MAX_TRENDS_FILE_BYTES && start < serialized.length - 1) {
|
|
680
|
+
totalBytes -= Buffer.byteLength(serialized[start], "utf8") + 1;
|
|
681
|
+
start++;
|
|
682
|
+
}
|
|
683
|
+
const keptEntries = start > 0 ? entries.slice(start) : entries;
|
|
684
|
+
const keptLines = start > 0 ? serialized.slice(start) : serialized;
|
|
685
|
+
if (totalBytes > MAX_TRENDS_FILE_BYTES && keptEntries.length === 1) {
|
|
686
|
+
const compact = { ...keptEntries[0], visibleInvariants: [] };
|
|
687
|
+
const compactLine = JSON.stringify(compact);
|
|
688
|
+
return { entries: [compact], payload: `${compactLine}\n` };
|
|
689
|
+
}
|
|
690
|
+
return { entries: keptEntries, payload: `${keptLines.join("\n")}\n` };
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* Appends a sanitized, holdout-opaque trend entry to `.vibecode/trends.ndjson`
|
|
694
|
+
* with bounded rotation and atomic `.tmp` + `renameSync` persistence.
|
|
695
|
+
*/
|
|
696
|
+
export function appendTrendEntry(cwd, report, options) {
|
|
697
|
+
const { resolvedCwd, realCwd, vibecodeDir, trendsPath } = resolveConfinedTrendsPaths(cwd);
|
|
698
|
+
const existing = readTrendEntries(cwd);
|
|
699
|
+
let safeReport = report;
|
|
700
|
+
try {
|
|
701
|
+
const knownHoldouts = new Set();
|
|
702
|
+
for (const h of readHoldouts(resolvedCwd)) {
|
|
703
|
+
knownHoldouts.add(h.id);
|
|
704
|
+
}
|
|
705
|
+
const contractFile = path.join(resolvedCwd, ".vibecode", "contract.json");
|
|
706
|
+
if (fs.existsSync(contractFile)) {
|
|
707
|
+
const c = readContract(resolvedCwd);
|
|
708
|
+
for (const inv of c.invariants) {
|
|
709
|
+
if (inv.holdout === true)
|
|
710
|
+
knownHoldouts.add(inv.id);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
if (knownHoldouts.size > 0 && isRecord(report) && safeIsArray(own(report, "results"))) {
|
|
714
|
+
const rawResults = own(report, "results");
|
|
715
|
+
safeReport = {
|
|
716
|
+
...report,
|
|
717
|
+
results: rawResults.map((item) => {
|
|
718
|
+
if (!isRecord(item))
|
|
719
|
+
return item;
|
|
720
|
+
const id = own(item, "id");
|
|
721
|
+
if (typeof id === "string" && knownHoldouts.has(id) && !isHoldoutResult(item)) {
|
|
722
|
+
const metrics = own(item, "metrics");
|
|
723
|
+
return {
|
|
724
|
+
...item,
|
|
725
|
+
metrics: {
|
|
726
|
+
...(isRecord(metrics) ? metrics : {}),
|
|
727
|
+
holdout: true,
|
|
728
|
+
redacted: true
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
}
|
|
732
|
+
return item;
|
|
733
|
+
})
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
catch {
|
|
738
|
+
// Best-effort defense-in-depth: missing/invalid vault or contract never blocks trend persistence.
|
|
739
|
+
}
|
|
740
|
+
const entry = buildTrendEntry(safeReport, options);
|
|
741
|
+
const maxEntries = clampInt(own(options, "maxEntries"), MAX_TREND_ENTRIES, 1, MAX_TREND_ENTRIES);
|
|
742
|
+
const combined = [...existing, entry];
|
|
743
|
+
const trimmed = combined.length > maxEntries ? combined.slice(-maxEntries) : combined;
|
|
744
|
+
const { entries: finalEntries, payload } = serializeBoundedNdjson(trimmed);
|
|
745
|
+
fs.mkdirSync(vibecodeDir, { recursive: true });
|
|
746
|
+
checkSymlinkConfinement(vibecodeDir, realCwd, ".vibecode directory");
|
|
747
|
+
const tmpPath = `${trendsPath}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`;
|
|
748
|
+
let wroteTmp = false;
|
|
749
|
+
try {
|
|
750
|
+
fs.writeFileSync(tmpPath, payload, { encoding: "utf8", flag: "wx" });
|
|
751
|
+
wroteTmp = true;
|
|
752
|
+
// Re-verify confinement right before atomic swap to narrow TOCTOU windows.
|
|
753
|
+
checkSymlinkConfinement(vibecodeDir, realCwd, ".vibecode directory");
|
|
754
|
+
checkSymlinkConfinement(trendsPath, realCwd, TRENDS_FILE);
|
|
755
|
+
fs.renameSync(tmpPath, trendsPath);
|
|
756
|
+
}
|
|
757
|
+
catch (err) {
|
|
758
|
+
if (wroteTmp) {
|
|
759
|
+
try {
|
|
760
|
+
fs.rmSync(tmpPath, { force: true });
|
|
761
|
+
}
|
|
762
|
+
catch {
|
|
763
|
+
// ignore temp file cleanup error
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
throw err;
|
|
767
|
+
}
|
|
768
|
+
return {
|
|
769
|
+
path: trendsPath,
|
|
770
|
+
entry: finalEntries[finalEntries.length - 1],
|
|
771
|
+
totalEntries: finalEntries.length
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
function buildLatencyDrift(windowed) {
|
|
775
|
+
if (windowed.length < 4) {
|
|
776
|
+
const med = computeMedian(windowed.map((e) => e.totalDurationMs));
|
|
777
|
+
return {
|
|
778
|
+
regressed: false,
|
|
779
|
+
baselineMedianMs: med,
|
|
780
|
+
recentMedianMs: med,
|
|
781
|
+
ratio: 1,
|
|
782
|
+
deltaMs: 0,
|
|
783
|
+
slowestInvariants: []
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
const splitIdx = Math.floor(windowed.length / 2);
|
|
787
|
+
const baselineEntries = windowed.slice(0, splitIdx);
|
|
788
|
+
const recentEntries = windowed.slice(splitIdx);
|
|
789
|
+
const baselineMedianMs = computeMedian(baselineEntries.map((e) => e.totalDurationMs));
|
|
790
|
+
const recentMedianMs = computeMedian(recentEntries.map((e) => e.totalDurationMs));
|
|
791
|
+
const deltaMs = roundNum(recentMedianMs - baselineMedianMs, 3);
|
|
792
|
+
const ratio = computeLatencyRatio(baselineMedianMs, recentMedianMs);
|
|
793
|
+
const regressed = recentMedianMs >= roundNum(baselineMedianMs * LATENCY_DRIFT_RATIO_THRESHOLD, 6) &&
|
|
794
|
+
deltaMs >= LATENCY_DRIFT_DELTA_MS_THRESHOLD;
|
|
795
|
+
const baselineById = new Map();
|
|
796
|
+
for (const entry of baselineEntries) {
|
|
797
|
+
for (const sample of entry.visibleInvariants) {
|
|
798
|
+
let arr = baselineById.get(sample.id);
|
|
799
|
+
if (!arr) {
|
|
800
|
+
arr = [];
|
|
801
|
+
baselineById.set(sample.id, arr);
|
|
802
|
+
}
|
|
803
|
+
arr.push(sample.durationMs);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
const recentById = new Map();
|
|
807
|
+
for (const entry of recentEntries) {
|
|
808
|
+
for (const sample of entry.visibleInvariants) {
|
|
809
|
+
let arr = recentById.get(sample.id);
|
|
810
|
+
if (!arr) {
|
|
811
|
+
arr = [];
|
|
812
|
+
recentById.set(sample.id, arr);
|
|
813
|
+
}
|
|
814
|
+
arr.push(sample.durationMs);
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
const slowestInvariants = [];
|
|
818
|
+
for (const [id, recentDurs] of recentById.entries()) {
|
|
819
|
+
const baseDurs = baselineById.get(id);
|
|
820
|
+
if (!baseDurs || baseDurs.length === 0)
|
|
821
|
+
continue;
|
|
822
|
+
const invBase = computeMedian(baseDurs);
|
|
823
|
+
const invRecent = computeMedian(recentDurs);
|
|
824
|
+
if (invRecent <= invBase)
|
|
825
|
+
continue;
|
|
826
|
+
const invRatio = computeLatencyRatio(invBase, invRecent);
|
|
827
|
+
if (invRatio < INVARIANT_DRIFT_MIN_RATIO)
|
|
828
|
+
continue;
|
|
829
|
+
slowestInvariants.push({
|
|
830
|
+
id,
|
|
831
|
+
baselineMedianMs: invBase,
|
|
832
|
+
recentMedianMs: invRecent,
|
|
833
|
+
ratio: invRatio
|
|
834
|
+
});
|
|
835
|
+
}
|
|
836
|
+
slowestInvariants.sort((a, b) => b.ratio - a.ratio || cmp(a.id, b.id));
|
|
837
|
+
return {
|
|
838
|
+
regressed,
|
|
839
|
+
baselineMedianMs,
|
|
840
|
+
recentMedianMs,
|
|
841
|
+
ratio,
|
|
842
|
+
deltaMs,
|
|
843
|
+
slowestInvariants: slowestInvariants.slice(0, MAX_SLOWEST_INVARIANTS)
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
function buildHotspots(windowed, maxHotspots) {
|
|
847
|
+
if (maxHotspots <= 0 || windowed.length === 0)
|
|
848
|
+
return [];
|
|
849
|
+
const agg = new Map();
|
|
850
|
+
for (const entry of windowed) {
|
|
851
|
+
for (const sample of entry.visibleInvariants) {
|
|
852
|
+
const existing = agg.get(sample.id);
|
|
853
|
+
const isFail = isFailureInvariantStatus(sample.status);
|
|
854
|
+
if (!existing) {
|
|
855
|
+
agg.set(sample.id, {
|
|
856
|
+
runs: 1,
|
|
857
|
+
failures: isFail ? 1 : 0,
|
|
858
|
+
flips: 0,
|
|
859
|
+
lastStatus: sample.status,
|
|
860
|
+
totalDurationMs: sample.durationMs
|
|
861
|
+
});
|
|
862
|
+
}
|
|
863
|
+
else {
|
|
864
|
+
const prevPassed = existing.lastStatus === "pass";
|
|
865
|
+
const currPassed = sample.status === "pass";
|
|
866
|
+
if (prevPassed !== currPassed)
|
|
867
|
+
existing.flips++;
|
|
868
|
+
existing.runs++;
|
|
869
|
+
if (isFail)
|
|
870
|
+
existing.failures++;
|
|
871
|
+
existing.lastStatus = sample.status;
|
|
872
|
+
existing.totalDurationMs += sample.durationMs;
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
const hotspots = [];
|
|
877
|
+
for (const [id, state] of agg.entries()) {
|
|
878
|
+
if (state.failures === 0 && state.flips === 0)
|
|
879
|
+
continue;
|
|
880
|
+
hotspots.push({
|
|
881
|
+
id,
|
|
882
|
+
runs: state.runs,
|
|
883
|
+
failures: state.failures,
|
|
884
|
+
failRate: roundNum(state.runs > 0 ? state.failures / state.runs : 0, 6),
|
|
885
|
+
flips: state.flips,
|
|
886
|
+
lastStatus: state.lastStatus,
|
|
887
|
+
avgDurationMs: roundNum(state.runs > 0 ? state.totalDurationMs / state.runs : 0, 3)
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
hotspots.sort((a, b) => b.flips - a.flips ||
|
|
891
|
+
b.failures - a.failures ||
|
|
892
|
+
b.failRate - a.failRate ||
|
|
893
|
+
cmp(a.id, b.id));
|
|
894
|
+
return hotspots.slice(0, maxHotspots);
|
|
895
|
+
}
|
|
896
|
+
function buildSummaryBrief(report, maxBriefChars) {
|
|
897
|
+
const lines = [];
|
|
898
|
+
if (report.windowSize === 0 || !report.latest) {
|
|
899
|
+
lines.push("Verification trends: 0 runs (insufficient_data). Run verification to start recording parity trends and hotspots.");
|
|
900
|
+
}
|
|
901
|
+
else {
|
|
902
|
+
const streakLabel = report.streak.status === "none" ? "none" : `${report.streak.count} ${report.streak.status}`;
|
|
903
|
+
const totalLabel = report.runCount > report.windowSize ? `/${report.runCount} total` : "";
|
|
904
|
+
lines.push(`Verification trends: ${report.windowSize}${totalLabel} run(s), direction=${report.direction}, passRate=${formatPct(report.passRate)}, streak=${streakLabel}`);
|
|
905
|
+
const latest = report.latest;
|
|
906
|
+
const latestExtras = [];
|
|
907
|
+
if (latest.gitSha)
|
|
908
|
+
latestExtras.push(`sha=${latest.gitSha}`);
|
|
909
|
+
if (latest.mode)
|
|
910
|
+
latestExtras.push(`mode=${latest.mode}`);
|
|
911
|
+
if (latest.holdoutCount > 0)
|
|
912
|
+
latestExtras.push(`holdouts=${latest.holdoutCount}`);
|
|
913
|
+
lines.push(`Latest: gate=${latest.gateStatus}, score=${formatPct(latest.compositeScore)} (last ${formatSignedPct(report.scoreDeltaLast)}, window ${formatSignedPct(report.scoreDeltaWindow)}), hard=${latest.hardPassed}/${latest.hardTotal}, duration=${formatMs(latest.totalDurationMs)}${latestExtras.length > 0 ? `, ${latestExtras.join(", ")}` : ""}`);
|
|
914
|
+
lines.push(`Sparklines: score=${report.scoreSparkline} | latency=${report.durationSparkline}`);
|
|
915
|
+
const drift = report.latencyDrift;
|
|
916
|
+
if (drift.regressed) {
|
|
917
|
+
lines.push(`Latency drift ALERT: median ${formatMs(drift.baselineMedianMs)} -> ${formatMs(drift.recentMedianMs)} (${drift.ratio.toFixed(2)}x, ${formatSignedMs(drift.deltaMs)})`);
|
|
918
|
+
}
|
|
919
|
+
if (drift.slowestInvariants.length > 0) {
|
|
920
|
+
const slow = drift.slowestInvariants
|
|
921
|
+
.map((s) => `${s.id} (${formatMs(s.baselineMedianMs)}->${formatMs(s.recentMedianMs)}, ${s.ratio.toFixed(2)}x)`)
|
|
922
|
+
.join(", ");
|
|
923
|
+
lines.push(`Drifting invariants: ${slow}`);
|
|
924
|
+
}
|
|
925
|
+
if (report.hotspots.length > 0) {
|
|
926
|
+
lines.push(`Hotspots (${report.hotspots.length}):`);
|
|
927
|
+
for (const h of report.hotspots) {
|
|
928
|
+
lines.push(`- ${h.id}: fail=${h.failures}/${h.runs} (${formatPct(h.failRate)}), flips=${h.flips}, last=${h.lastStatus}, avg=${formatMs(h.avgDurationMs)}`);
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
const scrubbed = redactSensitiveText(lines.join("\n")).trim();
|
|
933
|
+
if (scrubbed.length <= maxBriefChars)
|
|
934
|
+
return scrubbed;
|
|
935
|
+
if (maxBriefChars <= 3)
|
|
936
|
+
return scrubbed.slice(0, maxBriefChars);
|
|
937
|
+
return `${scrubbed.slice(0, maxBriefChars - 3).trimEnd()}...`;
|
|
938
|
+
}
|
|
939
|
+
/**
|
|
940
|
+
* Analyzes chronological verification trend entries over a bounded sliding window.
|
|
941
|
+
*/
|
|
942
|
+
export function analyzeTrends(entries, options) {
|
|
943
|
+
const validEntries = [];
|
|
944
|
+
const idCache = new Map();
|
|
945
|
+
if (safeIsArray(entries)) {
|
|
946
|
+
const entriesLen = safeLength(entries, MAX_TREND_ARRAY_SCAN);
|
|
947
|
+
for (let i = 0; i < entriesLen; i++) {
|
|
948
|
+
let raw;
|
|
949
|
+
try {
|
|
950
|
+
raw = entries[i];
|
|
951
|
+
}
|
|
952
|
+
catch {
|
|
953
|
+
continue;
|
|
954
|
+
}
|
|
955
|
+
const normalized = normalizeTrendEntry(raw, idCache);
|
|
956
|
+
if (normalized)
|
|
957
|
+
validEntries.push(normalized);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
const requestedWindow = clampInt(own(options, "window"), DEFAULT_TREND_WINDOW, 1, MAX_TREND_ENTRIES);
|
|
961
|
+
const rawMaxHotspots = own(options, "maxHotspots");
|
|
962
|
+
const maxHotspots = typeof rawMaxHotspots === "number" && Number.isFinite(rawMaxHotspots) && rawMaxHotspots >= 0
|
|
963
|
+
? Math.min(MAX_HOTSPOTS_CAP, Math.floor(rawMaxHotspots))
|
|
964
|
+
: DEFAULT_MAX_HOTSPOTS;
|
|
965
|
+
const rawMaxBrief = own(options, "maxBriefChars");
|
|
966
|
+
const maxBriefChars = typeof rawMaxBrief === "number" && Number.isFinite(rawMaxBrief) && rawMaxBrief > 0
|
|
967
|
+
? Math.min(MAX_BRIEF_CHARS_CAP, Math.floor(rawMaxBrief))
|
|
968
|
+
: DEFAULT_MAX_TREND_BRIEF_CHARS;
|
|
969
|
+
const windowed = validEntries.slice(-requestedWindow);
|
|
970
|
+
const runCount = validEntries.length;
|
|
971
|
+
const windowSize = windowed.length;
|
|
972
|
+
const latest = windowSize > 0 ? windowed[windowSize - 1] : undefined;
|
|
973
|
+
let passedCount = 0;
|
|
974
|
+
for (const e of windowed) {
|
|
975
|
+
if (isPassingGate(e.gateStatus))
|
|
976
|
+
passedCount++;
|
|
977
|
+
}
|
|
978
|
+
const passRate = windowSize > 0 ? roundNum(passedCount / windowSize, 6) : 0;
|
|
979
|
+
let streak = { status: "none", count: 0 };
|
|
980
|
+
if (latest) {
|
|
981
|
+
if (isPassingGate(latest.gateStatus)) {
|
|
982
|
+
let count = 0;
|
|
983
|
+
for (let i = windowSize - 1; i >= 0; i--) {
|
|
984
|
+
if (isPassingGate(windowed[i].gateStatus))
|
|
985
|
+
count++;
|
|
986
|
+
else
|
|
987
|
+
break;
|
|
988
|
+
}
|
|
989
|
+
streak = { status: "pass", count };
|
|
990
|
+
}
|
|
991
|
+
else if (latest.gateStatus === "fail") {
|
|
992
|
+
let count = 0;
|
|
993
|
+
for (let i = windowSize - 1; i >= 0; i--) {
|
|
994
|
+
if (windowed[i].gateStatus === "fail")
|
|
995
|
+
count++;
|
|
996
|
+
else
|
|
997
|
+
break;
|
|
998
|
+
}
|
|
999
|
+
streak = { status: "fail", count };
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
const scoreDeltaLast = windowSize >= 2
|
|
1003
|
+
? roundNum(windowed[windowSize - 1].compositeScore - windowed[windowSize - 2].compositeScore, 6)
|
|
1004
|
+
: 0;
|
|
1005
|
+
const scoreDeltaWindow = windowSize >= 2
|
|
1006
|
+
? roundNum(windowed[windowSize - 1].compositeScore - windowed[0].compositeScore, 6)
|
|
1007
|
+
: 0;
|
|
1008
|
+
let direction;
|
|
1009
|
+
if (windowSize < 2) {
|
|
1010
|
+
direction = "insufficient_data";
|
|
1011
|
+
}
|
|
1012
|
+
else if (scoreDeltaWindow >= TREND_DIRECTION_DELTA_THRESHOLD) {
|
|
1013
|
+
direction = "improving";
|
|
1014
|
+
}
|
|
1015
|
+
else if (scoreDeltaWindow <= -TREND_DIRECTION_DELTA_THRESHOLD) {
|
|
1016
|
+
direction = "regressing";
|
|
1017
|
+
}
|
|
1018
|
+
else {
|
|
1019
|
+
direction = "stable";
|
|
1020
|
+
}
|
|
1021
|
+
const scoreSparkline = renderSparkline(windowed.map((e) => e.compositeScore), { min: 0, max: 1 });
|
|
1022
|
+
const durationSparkline = renderSparkline(windowed.map((e) => e.totalDurationMs));
|
|
1023
|
+
const latencyDrift = buildLatencyDrift(windowed);
|
|
1024
|
+
const hotspots = buildHotspots(windowed, maxHotspots);
|
|
1025
|
+
const base = {
|
|
1026
|
+
runCount,
|
|
1027
|
+
windowSize,
|
|
1028
|
+
direction,
|
|
1029
|
+
passRate,
|
|
1030
|
+
streak,
|
|
1031
|
+
...(latest ? { latest } : {}),
|
|
1032
|
+
scoreDeltaLast,
|
|
1033
|
+
scoreDeltaWindow,
|
|
1034
|
+
scoreSparkline,
|
|
1035
|
+
durationSparkline,
|
|
1036
|
+
latencyDrift,
|
|
1037
|
+
hotspots
|
|
1038
|
+
};
|
|
1039
|
+
return {
|
|
1040
|
+
...base,
|
|
1041
|
+
summaryBrief: buildSummaryBrief(base, maxBriefChars)
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
function directionColor(direction) {
|
|
1045
|
+
if (direction === "improving")
|
|
1046
|
+
return `${ANSI.bold}${ANSI.green}`;
|
|
1047
|
+
if (direction === "regressing")
|
|
1048
|
+
return `${ANSI.bold}${ANSI.red}`;
|
|
1049
|
+
if (direction === "stable")
|
|
1050
|
+
return `${ANSI.bold}${ANSI.cyan}`;
|
|
1051
|
+
return ANSI.dim;
|
|
1052
|
+
}
|
|
1053
|
+
/**
|
|
1054
|
+
* Formats a `TrendReport` as a clean terminal dashboard with optional ANSI coloring.
|
|
1055
|
+
*/
|
|
1056
|
+
export function formatPrettyTrends(report, options) {
|
|
1057
|
+
const useColor = own(options, "color") === true;
|
|
1058
|
+
const safeReport = isRecord(report) ? report : {};
|
|
1059
|
+
const runCount = finiteNonNegInt(own(safeReport, "runCount"), 0);
|
|
1060
|
+
const windowSize = finiteNonNegInt(own(safeReport, "windowSize"), 0);
|
|
1061
|
+
const rawDirection = sanitizeSingleLine(safeString(own(safeReport, "direction")) || "insufficient_data", 32);
|
|
1062
|
+
const passRate = clamp01(own(safeReport, "passRate"));
|
|
1063
|
+
const badge = style("[TRENDS]", `${ANSI.bold}${ANSI.cyan}`, useColor);
|
|
1064
|
+
const dirText = style(rawDirection.toUpperCase(), directionColor(rawDirection), useColor);
|
|
1065
|
+
const countScope = runCount > windowSize ? `${windowSize} window / ${runCount} total` : `${windowSize} run${windowSize === 1 ? "" : "s"}`;
|
|
1066
|
+
const lines = [`${badge} ${countScope} | direction: ${dirText}`];
|
|
1067
|
+
if (windowSize === 0) {
|
|
1068
|
+
lines.push("No verification runs recorded yet.");
|
|
1069
|
+
return lines.join("\n");
|
|
1070
|
+
}
|
|
1071
|
+
const streakObj = own(safeReport, "streak");
|
|
1072
|
+
const streakStatus = sanitizeSingleLine(safeString(own(streakObj, "status")) || "none", 16);
|
|
1073
|
+
const streakCount = finiteNonNegInt(own(streakObj, "count"), 0);
|
|
1074
|
+
const streakRaw = streakStatus === "none" || streakCount === 0 ? "none" : `${streakCount} ${streakStatus}`;
|
|
1075
|
+
const streakTone = streakStatus === "pass" ? ANSI.green : streakStatus === "fail" ? ANSI.red : ANSI.dim;
|
|
1076
|
+
lines.push(`Pass rate: ${style(formatPct(passRate), passRate >= 0.9 ? ANSI.green : passRate >= 0.7 ? ANSI.yellow : ANSI.red, useColor)} | Streak: ${style(streakRaw, streakTone, useColor)}`);
|
|
1077
|
+
const latest = own(safeReport, "latest");
|
|
1078
|
+
const rawScoreDeltaLast = own(safeReport, "scoreDeltaLast");
|
|
1079
|
+
const scoreDeltaLast = typeof rawScoreDeltaLast === "number" && Number.isFinite(rawScoreDeltaLast)
|
|
1080
|
+
? rawScoreDeltaLast
|
|
1081
|
+
: 0;
|
|
1082
|
+
const rawScoreDeltaWindow = own(safeReport, "scoreDeltaWindow");
|
|
1083
|
+
const scoreDeltaWindow = typeof rawScoreDeltaWindow === "number" && Number.isFinite(rawScoreDeltaWindow)
|
|
1084
|
+
? rawScoreDeltaWindow
|
|
1085
|
+
: 0;
|
|
1086
|
+
if (isRecord(latest)) {
|
|
1087
|
+
const gate = sanitizeSingleLine(safeString(own(latest, "gateStatus")) || "unknown", 32);
|
|
1088
|
+
const gateTone = gate === "pass"
|
|
1089
|
+
? ANSI.green
|
|
1090
|
+
: gate === "pass_with_warnings"
|
|
1091
|
+
? ANSI.yellow
|
|
1092
|
+
: ANSI.red;
|
|
1093
|
+
const score = clamp01(own(latest, "compositeScore"));
|
|
1094
|
+
const hardPassed = finiteNonNegInt(own(latest, "hardPassed"), 0);
|
|
1095
|
+
const hardTotal = finiteNonNegInt(own(latest, "hardTotal"), 0);
|
|
1096
|
+
const totalDurationMs = finiteNonNeg(own(latest, "totalDurationMs"), 0);
|
|
1097
|
+
const holdoutCount = finiteNonNegInt(own(latest, "holdoutCount"), 0);
|
|
1098
|
+
const gitSha = sanitizeSingleLine(safeString(own(latest, "gitSha")), MAX_META_CHARS);
|
|
1099
|
+
const mode = sanitizeSingleLine(safeString(own(latest, "mode")), MAX_META_CHARS);
|
|
1100
|
+
const metaParts = [`hard ${hardPassed}/${hardTotal}`, formatMs(totalDurationMs)];
|
|
1101
|
+
if (holdoutCount > 0)
|
|
1102
|
+
metaParts.push(`holdouts ${holdoutCount}`);
|
|
1103
|
+
if (gitSha)
|
|
1104
|
+
metaParts.push(`sha ${gitSha}`);
|
|
1105
|
+
if (mode)
|
|
1106
|
+
metaParts.push(`mode ${mode}`);
|
|
1107
|
+
lines.push(`Latest: ${style(gate.toUpperCase(), `${ANSI.bold}${gateTone}`, useColor)} | Score: ${formatPct(score)} (last ${formatSignedPct(scoreDeltaLast)}, window ${formatSignedPct(scoreDeltaWindow)}) | ${metaParts.join(", ")}`);
|
|
1108
|
+
}
|
|
1109
|
+
const scoreSpark = sanitizeSingleLine(safeString(own(safeReport, "scoreSparkline")), MAX_TREND_ENTRIES);
|
|
1110
|
+
const durSpark = sanitizeSingleLine(safeString(own(safeReport, "durationSparkline")), MAX_TREND_ENTRIES);
|
|
1111
|
+
lines.push(`Score sparkline: ${scoreSpark || "(none)"}`);
|
|
1112
|
+
lines.push(`Latency sparkline: ${durSpark || "(none)"}`);
|
|
1113
|
+
const driftObj = own(safeReport, "latencyDrift");
|
|
1114
|
+
const driftRegressed = own(driftObj, "regressed") === true;
|
|
1115
|
+
const baseMed = finiteNonNeg(own(driftObj, "baselineMedianMs"), 0);
|
|
1116
|
+
const recentMed = finiteNonNeg(own(driftObj, "recentMedianMs"), 0);
|
|
1117
|
+
const driftRatioRaw = own(driftObj, "ratio");
|
|
1118
|
+
const driftRatio = typeof driftRatioRaw === "number" && Number.isFinite(driftRatioRaw) ? driftRatioRaw : 1;
|
|
1119
|
+
const driftDeltaRaw = own(driftObj, "deltaMs");
|
|
1120
|
+
const driftDelta = typeof driftDeltaRaw === "number" && Number.isFinite(driftDeltaRaw) ? driftDeltaRaw : 0;
|
|
1121
|
+
const driftLabel = driftRegressed
|
|
1122
|
+
? style("REGRESSED", `${ANSI.bold}${ANSI.red}`, useColor)
|
|
1123
|
+
: style("OK", ANSI.green, useColor);
|
|
1124
|
+
lines.push(`Latency drift: ${driftLabel} (${formatMs(baseMed)} -> ${formatMs(recentMed)}, ${driftRatio.toFixed(2)}x, ${formatSignedMs(driftDelta)})`);
|
|
1125
|
+
const rawSlowest = own(driftObj, "slowestInvariants");
|
|
1126
|
+
const rawSlowestLen = safeIsArray(rawSlowest) ? safeLength(rawSlowest, MAX_INVARIANT_ARRAY_SCAN) : 0;
|
|
1127
|
+
if (safeIsArray(rawSlowest) && rawSlowestLen > 0) {
|
|
1128
|
+
const slowestLines = [];
|
|
1129
|
+
for (let i = 0; i < rawSlowestLen && slowestLines.length < MAX_SLOWEST_INVARIANTS; i++) {
|
|
1130
|
+
let item;
|
|
1131
|
+
try {
|
|
1132
|
+
item = rawSlowest[i];
|
|
1133
|
+
}
|
|
1134
|
+
catch {
|
|
1135
|
+
continue;
|
|
1136
|
+
}
|
|
1137
|
+
if (!isRecord(item) || isHoldoutResult(item))
|
|
1138
|
+
continue;
|
|
1139
|
+
const id = sanitizeSingleLine(safeString(own(item, "id")), MAX_ID_CHARS);
|
|
1140
|
+
if (!id)
|
|
1141
|
+
continue;
|
|
1142
|
+
const b = finiteNonNeg(own(item, "baselineMedianMs"), 0);
|
|
1143
|
+
const r = finiteNonNeg(own(item, "recentMedianMs"), 0);
|
|
1144
|
+
const ratRaw = own(item, "ratio");
|
|
1145
|
+
const rat = typeof ratRaw === "number" && Number.isFinite(ratRaw) ? ratRaw : 1;
|
|
1146
|
+
slowestLines.push(` - ${id}: ${formatMs(b)} -> ${formatMs(r)} (${rat.toFixed(2)}x)`);
|
|
1147
|
+
}
|
|
1148
|
+
if (slowestLines.length > 0) {
|
|
1149
|
+
lines.push("Slowest drifting invariants:");
|
|
1150
|
+
lines.push(...slowestLines);
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
const rawHotspots = own(safeReport, "hotspots");
|
|
1154
|
+
const hotspotLines = [];
|
|
1155
|
+
if (safeIsArray(rawHotspots)) {
|
|
1156
|
+
const rawHotspotsLen = safeLength(rawHotspots, MAX_INVARIANT_ARRAY_SCAN);
|
|
1157
|
+
for (let i = 0; i < rawHotspotsLen && hotspotLines.length < MAX_PRETTY_HOTSPOTS; i++) {
|
|
1158
|
+
let item;
|
|
1159
|
+
try {
|
|
1160
|
+
item = rawHotspots[i];
|
|
1161
|
+
}
|
|
1162
|
+
catch {
|
|
1163
|
+
continue;
|
|
1164
|
+
}
|
|
1165
|
+
if (!isRecord(item) || isHoldoutResult(item))
|
|
1166
|
+
continue;
|
|
1167
|
+
const id = sanitizeSingleLine(safeString(own(item, "id")), MAX_ID_CHARS);
|
|
1168
|
+
if (!id)
|
|
1169
|
+
continue;
|
|
1170
|
+
const runs = finiteNonNegInt(own(item, "runs"), 0);
|
|
1171
|
+
const failures = finiteNonNegInt(own(item, "failures"), 0);
|
|
1172
|
+
const failRate = clamp01(own(item, "failRate"));
|
|
1173
|
+
const flips = finiteNonNegInt(own(item, "flips"), 0);
|
|
1174
|
+
const lastStatus = sanitizeSingleLine(safeString(own(item, "lastStatus")) || "unknown", 16);
|
|
1175
|
+
const avgDurationMs = finiteNonNeg(own(item, "avgDurationMs"), 0);
|
|
1176
|
+
const tag = flips > 0
|
|
1177
|
+
? style("FLAKY", `${ANSI.bold}${ANSI.yellow}`, useColor)
|
|
1178
|
+
: style("CHRONIC", `${ANSI.bold}${ANSI.red}`, useColor);
|
|
1179
|
+
hotspotLines.push(` - [${tag}] ${id}: fail ${failures}/${runs} (${formatPct(failRate)}), flips ${flips}, last ${lastStatus}, avg ${formatMs(avgDurationMs)}`);
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
if (hotspotLines.length === 0) {
|
|
1183
|
+
lines.push("Hotspots: none (all visible invariants stable)");
|
|
1184
|
+
}
|
|
1185
|
+
else {
|
|
1186
|
+
lines.push(`Hotspots (${hotspotLines.length}):`);
|
|
1187
|
+
lines.push(...hotspotLines);
|
|
1188
|
+
}
|
|
1189
|
+
return lines.join("\n");
|
|
1190
|
+
}
|