vibecode-anything 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +239 -67
  2. package/dist/cli.js +2140 -73
  3. package/dist/core/adapters.d.ts +26 -3
  4. package/dist/core/adapters.js +411 -25
  5. package/dist/core/agent-adapter.d.ts +67 -0
  6. package/dist/core/agent-adapter.js +312 -0
  7. package/dist/core/anti-cheat.d.ts +6 -0
  8. package/dist/core/anti-cheat.js +372 -0
  9. package/dist/core/badge.d.ts +18 -0
  10. package/dist/core/badge.js +360 -0
  11. package/dist/core/cache.d.ts +47 -0
  12. package/dist/core/cache.js +403 -0
  13. package/dist/core/ci-export.d.ts +35 -0
  14. package/dist/core/ci-export.js +796 -0
  15. package/dist/core/ci-formats.d.ts +21 -0
  16. package/dist/core/ci-formats.js +388 -0
  17. package/dist/core/client-codegen.d.ts +36 -0
  18. package/dist/core/client-codegen.js +2538 -0
  19. package/dist/core/compose.d.ts +71 -0
  20. package/dist/core/compose.js +1088 -0
  21. package/dist/core/docs-export.d.ts +37 -0
  22. package/dist/core/docs-export.js +2706 -0
  23. package/dist/core/doctor.d.ts +21 -1
  24. package/dist/core/doctor.js +234 -21
  25. package/dist/core/exec.d.ts +26 -2
  26. package/dist/core/exec.js +235 -8
  27. package/dist/core/fixtures.d.ts +153 -0
  28. package/dist/core/fixtures.js +2245 -0
  29. package/dist/core/format.d.ts +77 -0
  30. package/dist/core/format.js +632 -0
  31. package/dist/core/fs-snapshot.d.ts +37 -0
  32. package/dist/core/fs-snapshot.js +216 -0
  33. package/dist/core/graphql-export.d.ts +34 -0
  34. package/dist/core/graphql-export.js +2482 -0
  35. package/dist/core/har-export.d.ts +29 -0
  36. package/dist/core/har-export.js +988 -0
  37. package/dist/core/html-report.d.ts +27 -0
  38. package/dist/core/html-report.js +1535 -0
  39. package/dist/core/http-export.d.ts +31 -0
  40. package/dist/core/http-export.js +726 -0
  41. package/dist/core/impact.d.ts +80 -0
  42. package/dist/core/impact.js +1412 -0
  43. package/dist/core/lint.d.ts +38 -0
  44. package/dist/core/lint.js +1111 -0
  45. package/dist/core/load-export.d.ts +37 -0
  46. package/dist/core/load-export.js +1813 -0
  47. package/dist/core/mcp-export.d.ts +35 -0
  48. package/dist/core/mcp-export.js +1736 -0
  49. package/dist/core/mock-server.d.ts +47 -0
  50. package/dist/core/mock-server.js +1722 -0
  51. package/dist/core/openapi-export.d.ts +44 -0
  52. package/dist/core/openapi-export.js +1074 -0
  53. package/dist/core/parity.d.ts +6 -1
  54. package/dist/core/parity.js +36 -1
  55. package/dist/core/playwright-exporter.d.ts +23 -0
  56. package/dist/core/playwright-exporter.js +1343 -0
  57. package/dist/core/png.js +45 -9
  58. package/dist/core/regression.d.ts +54 -0
  59. package/dist/core/regression.js +529 -0
  60. package/dist/core/responsive.d.ts +86 -0
  61. package/dist/core/responsive.js +606 -0
  62. package/dist/core/run.d.ts +74 -0
  63. package/dist/core/run.js +696 -0
  64. package/dist/core/scheduler.d.ts +24 -0
  65. package/dist/core/scheduler.js +162 -0
  66. package/dist/core/schema-export.d.ts +29 -0
  67. package/dist/core/schema-export.js +2215 -0
  68. package/dist/core/schema.d.ts +3 -2
  69. package/dist/core/schema.js +460 -17
  70. package/dist/core/security.d.ts +233 -0
  71. package/dist/core/security.js +1839 -0
  72. package/dist/core/server-export.d.ts +38 -0
  73. package/dist/core/server-export.js +3198 -0
  74. package/dist/core/spec-writer.d.ts +9 -0
  75. package/dist/core/spec-writer.js +1202 -0
  76. package/dist/core/store.d.ts +11 -2
  77. package/dist/core/store.js +128 -8
  78. package/dist/core/target-map.d.ts +34 -0
  79. package/dist/core/target-map.js +262 -0
  80. package/dist/core/test-exporter.d.ts +25 -0
  81. package/dist/core/test-exporter.js +1918 -0
  82. package/dist/core/types.d.ts +182 -14
  83. package/dist/core/visual-semantic.d.ts +67 -0
  84. package/dist/core/visual-semantic.js +673 -0
  85. package/dist/core/visual.js +65 -16
  86. package/dist/core/watch.d.ts +28 -3
  87. package/dist/core/watch.js +222 -12
  88. package/dist/core/yaml.d.ts +5 -0
  89. package/dist/core/yaml.js +1009 -0
  90. package/dist/diagnostics/diagnose.d.ts +53 -0
  91. package/dist/diagnostics/diagnose.js +1083 -0
  92. package/dist/diagnostics/flake.d.ts +71 -0
  93. package/dist/diagnostics/flake.js +608 -0
  94. package/dist/diagnostics/mutation-audit.d.ts +69 -0
  95. package/dist/diagnostics/mutation-audit.js +769 -0
  96. package/dist/diagnostics/spatial.d.ts +42 -0
  97. package/dist/diagnostics/spatial.js +346 -0
  98. package/dist/diagnostics/trends.d.ts +122 -0
  99. package/dist/diagnostics/trends.js +1190 -0
  100. package/dist/discovery/discover.d.ts +111 -0
  101. package/dist/discovery/discover.js +2017 -0
  102. package/dist/discovery/lock.d.ts +116 -0
  103. package/dist/discovery/lock.js +1505 -0
  104. package/dist/discovery/routes.d.ts +36 -0
  105. package/dist/discovery/routes.js +1494 -0
  106. package/dist/discovery/test-importer.d.ts +92 -0
  107. package/dist/discovery/test-importer.js +4952 -0
  108. package/dist/index.d.ts +123 -0
  109. package/dist/index.js +99 -0
  110. package/dist/ingestors/api-collections.d.ts +28 -0
  111. package/dist/ingestors/api-collections.js +2335 -0
  112. package/dist/ingestors/api-repo.d.ts +2 -1
  113. package/dist/ingestors/api-repo.js +483 -85
  114. package/dist/ingestors/asyncapi.d.ts +26 -0
  115. package/dist/ingestors/asyncapi.js +2105 -0
  116. package/dist/ingestors/bridges.d.ts +2 -0
  117. package/dist/ingestors/bridges.js +702 -0
  118. package/dist/ingestors/cli.d.ts +2 -1
  119. package/dist/ingestors/cli.js +234 -46
  120. package/dist/ingestors/curl.d.ts +14 -0
  121. package/dist/ingestors/curl.js +1024 -0
  122. package/dist/ingestors/graphql.d.ts +56 -0
  123. package/dist/ingestors/graphql.js +1852 -0
  124. package/dist/ingestors/http-file.d.ts +20 -0
  125. package/dist/ingestors/http-file.js +923 -0
  126. package/dist/ingestors/index.js +486 -6
  127. package/dist/ingestors/openrpc.d.ts +29 -0
  128. package/dist/ingestors/openrpc.js +1807 -0
  129. package/dist/ingestors/proto.d.ts +47 -0
  130. package/dist/ingestors/proto.js +2690 -0
  131. package/dist/ingestors/trace.d.ts +10 -0
  132. package/dist/ingestors/trace.js +599 -0
  133. package/dist/ingestors/video.d.ts +4 -1
  134. package/dist/ingestors/video.js +86 -36
  135. package/dist/ingestors/web.d.ts +16 -1
  136. package/dist/ingestors/web.js +474 -32
  137. package/dist/mcp/server.js +3532 -67
  138. package/dist/oracles/api-repo.js +102 -30
  139. package/dist/oracles/cli.js +65 -17
  140. package/dist/oracles/http-workflow.d.ts +68 -0
  141. package/dist/oracles/http-workflow.js +828 -0
  142. package/dist/oracles/image.js +178 -28
  143. package/dist/oracles/index.d.ts +3 -1
  144. package/dist/oracles/index.js +243 -14
  145. package/dist/oracles/perf-budget.d.ts +90 -0
  146. package/dist/oracles/perf-budget.js +1329 -0
  147. package/dist/oracles/stream.d.ts +94 -0
  148. package/dist/oracles/stream.js +1268 -0
  149. package/dist/oracles/ui-states.d.ts +49 -0
  150. package/dist/oracles/ui-states.js +894 -0
  151. package/dist/oracles/video.d.ts +1 -1
  152. package/dist/oracles/video.js +232 -16
  153. package/dist/oracles/web.js +464 -73
  154. package/dist/plugins/builtins.d.ts +12 -0
  155. package/dist/plugins/builtins.js +1052 -0
  156. package/dist/plugins/registry.d.ts +86 -0
  157. package/dist/plugins/registry.js +554 -0
  158. package/dist/setup/index.js +145 -33
  159. package/package.json +56 -47
  160. package/skills/vibecode-anything/SKILL.md +75 -52
@@ -0,0 +1,769 @@
1
+ /**
2
+ * Zero-dependency contract oracle strength & mutation self-auditor for vibecode-anything.
3
+ *
4
+ * Statically scores how strongly each invariant in a `.vibecode/contract.json` resists
5
+ * regressions, constant stubs and AI reward-hacking (0..100, grade A..F), synthesizes the
6
+ * concrete stub-bypass mutant each weakness admits, and emits a bounded, redacted
7
+ * `hardeningBrief` for agents. Pure function of its input: never throws, never does I/O.
8
+ */
9
+ import { isForbiddenObjectKey, isRecordSafe, redactSensitiveText, safeIsArray, safeOwnProp, safeString, sanitizeSingleLine } from "../core/security.js";
10
+ import { inferDomainForInvariant } from "../core/target-map.js";
11
+ export const DEFAULT_MAX_HARDENING_BRIEF_CHARS = 2000;
12
+ export const DEFAULT_MIN_STRENGTH_SCORE = 60;
13
+ const MAX_TOP_RISKS = 10;
14
+ const MAX_CONTRACT_PENALTY = 60;
15
+ const MAX_ID_CHARS = 120;
16
+ const MAX_BRIEF_CHARS_CAP = 1_000_000;
17
+ const SEVERITY_RANK = { critical: 4, high: 3, medium: 2, low: 1 };
18
+ const KNOWN_INVARIANT_TYPES = new Set([
19
+ "command",
20
+ "http",
21
+ "http_workflow",
22
+ "http_stream",
23
+ "ws_protocol",
24
+ "perf_budget",
25
+ "web_route",
26
+ "web_flow",
27
+ "web_network",
28
+ "web_ui_states",
29
+ "image_layout",
30
+ "image_perceptual",
31
+ "video_timeline",
32
+ "repo_exports",
33
+ "plugin_svg_a11y",
34
+ "plugin_state_file"
35
+ ]);
36
+ const RISKS = {
37
+ EMPTY_CONTRACT: {
38
+ severity: "critical", deduction: 100,
39
+ message: "Contract has no visible invariants; nothing is verified.",
40
+ mutantScenario: "Any implementation, including an empty file, passes an empty contract.",
41
+ recommendation: "Ingest the reference (vibecode-anything ingest) or add at least one hard invariant per feature."
42
+ },
43
+ NO_HARD_GATE: {
44
+ severity: "critical", deduction: 30,
45
+ message: "Contract has no hard invariants; soft-only failures exit 0 without --strict.",
46
+ mutantScenario: "A broken build that fails every soft invariant still exits 0 and ships.",
47
+ recommendation: "Promote the core behaviors to severity \"hard\" so regressions fail the gate."
48
+ },
49
+ ZERO_HOLDOUTS: {
50
+ severity: "high", deduction: 10,
51
+ message: "No holdout invariants; every probe is visible to the agent.",
52
+ mutantScenario: "An agent overfits the visible probes (hard-coded outputs per input) and passes 100%.",
53
+ recommendation: "Move 10-20% of invariants into the holdout vault so overfitting is caught."
54
+ },
55
+ SINGLE_PROBE_SURFACE: {
56
+ severity: "medium", deduction: 10,
57
+ message: "Contract has a single invariant; the probe surface is trivial.",
58
+ mutantScenario: "A constant stub that replays the one expected answer passes.",
59
+ recommendation: "Add invariants covering distinct inputs, error paths and edge cases."
60
+ },
61
+ CLI_NO_ERROR_PATH: {
62
+ severity: "low", deduction: 5,
63
+ message: "No command invariant covers an error path (non-zero exit or stderr).",
64
+ mutantScenario: "A CLI that never validates input and always exits 0 passes.",
65
+ recommendation: "Add a command invariant with invalid input expecting a non-zero exitCode and stderrContains."
66
+ },
67
+ MALFORMED_INVARIANT: {
68
+ severity: "high", deduction: 100,
69
+ message: "Invariant is malformed and cannot be evaluated.",
70
+ mutantScenario: "A malformed invariant verifies nothing, so any implementation passes it.",
71
+ recommendation: "Fix the invariant so it is an object with id, type, severity, input and expected."
72
+ },
73
+ NO_ASSERTIONS: {
74
+ severity: "high", deduction: 45,
75
+ message: "Invariant declares no expected assertions.",
76
+ mutantScenario: "Any response from a no-op stub satisfies an empty expectation.",
77
+ recommendation: "Add concrete expected assertions (schema, exact text, subset) for this invariant."
78
+ },
79
+ CLI_EXIT_ONLY: {
80
+ severity: "high", deduction: 45,
81
+ message: "Command checks only the exit code.",
82
+ mutantScenario: "A no-op `exit 0` stub passes without producing any output.",
83
+ recommendation: "Assert stdoutExact/goldenStdout, jsonSchema or stdoutContains with distinctive text."
84
+ },
85
+ CLI_WEAK_MATCH: {
86
+ severity: "medium", deduction: 20,
87
+ message: "Command output matching is too weak (tiny stdoutContains needles).",
88
+ mutantScenario: "A stub printing a short common token (e.g. \"ok\") satisfies the match.",
89
+ recommendation: "Use stdoutExact, goldenStdout, jsonSchema or needles of 4+ distinctive characters."
90
+ },
91
+ CLI_UNCHECKED_SIDE_EFFECT: {
92
+ severity: "low", deduction: 10,
93
+ message: "Command writes files but no fsEffects are asserted.",
94
+ mutantScenario: "A stub prints the expected output but never writes the output file.",
95
+ recommendation: "Add expected.fsEffects (path, status, sha256) or enable input.fsDiff."
96
+ },
97
+ HTTP_STATUS_ONLY: {
98
+ severity: "high", deduction: 45,
99
+ message: "HTTP invariant checks only the status code.",
100
+ mutantScenario: "An empty `{}` 200 OK handler false-passes.",
101
+ recommendation: "Add expected.jsonSchema plus jsonSubset/jsonPaths or bodyContains for the payload."
102
+ },
103
+ HTTP_NO_SCHEMA: {
104
+ severity: "medium", deduction: 15,
105
+ message: "HTTP body is matched without a jsonSchema.",
106
+ mutantScenario: "Drifted field types or missing required fields slip through.",
107
+ recommendation: "Add expected.jsonSchema with required fields and types."
108
+ },
109
+ HTTP_NO_CONTENT_TYPE: {
110
+ severity: "low", deduction: 10,
111
+ message: "JSON response is asserted without a content-type header check.",
112
+ mutantScenario: "A handler returning JSON-looking text/html passes and breaks real clients.",
113
+ recommendation: "Assert expected.headers[\"content-type\"] (e.g. application/json)."
114
+ },
115
+ WORKFLOW_SINGLE_STEP: {
116
+ severity: "medium", deduction: 20,
117
+ message: "Workflow has fewer than two steps; no state transition is verified.",
118
+ mutantScenario: "A stateless stub that never persists anything passes a one-shot workflow.",
119
+ recommendation: "Chain create -> read-back -> update/delete steps using extract and {{vars}}."
120
+ },
121
+ WORKFLOW_NO_CLEANUP: {
122
+ severity: "high", deduction: 25,
123
+ message: "Workflow mutates state without finallySteps cleanup.",
124
+ mutantScenario: "Dirty state leaks across runs and flakes subsequent verifications.",
125
+ recommendation: "Add input.finallySteps that delete or reset the created resources."
126
+ },
127
+ WORKFLOW_WEAK_STEPS: {
128
+ severity: "medium", deduction: 20,
129
+ message: "Most workflow steps assert only the status code.",
130
+ mutantScenario: "Handlers returning fixed status codes with empty bodies pass every step.",
131
+ recommendation: "Give steps expected.jsonSchema/jsonSubset/jsonPaths or extract values and read them back."
132
+ },
133
+ STREAM_NO_ASSERTIONS: {
134
+ severity: "high", deduction: 45,
135
+ message: "Stream/socket invariant asserts no events or messages.",
136
+ mutantScenario: "An endpoint that opens and immediately closes the stream passes.",
137
+ recommendation: "Set expected.minEvents, orderedEvents/terminalEvent, or ws expect steps with jsonSchema."
138
+ },
139
+ WEB_STATUS_ONLY: {
140
+ severity: "high", deduction: 45,
141
+ message: "Web route checks only the HTTP status.",
142
+ mutantScenario: "A blank 200 page passes.",
143
+ recommendation: "Assert titleContains, landmarks, visibleText or domAssertions."
144
+ },
145
+ WEB_NO_RESPONSIVE: {
146
+ severity: "low", deduction: 10,
147
+ message: "Web route has no responsiveViewports.",
148
+ mutantScenario: "A layout that collapses on mobile widths passes.",
149
+ recommendation: "Add expected.responsiveViewports (e.g. mobile 375x812, desktop 1280x800)."
150
+ },
151
+ WEB_FLOW_NO_ASSERTIONS: {
152
+ severity: "high", deduction: 40,
153
+ message: "Web flow performs actions without post-action assertions.",
154
+ mutantScenario: "Buttons wired to nothing pass because no outcome is checked.",
155
+ recommendation: "Assert finalUrlIncludes, visibleText, domAssertions or networkCalls after the actions."
156
+ },
157
+ UI_STATES_EMPTY: {
158
+ severity: "critical", deduction: 80,
159
+ message: "web_ui_states invariant has no checks.",
160
+ mutantScenario: "Any page passes because zero UI states are exercised.",
161
+ recommendation: "Add input.checks for focus/keyboard_tab, hover, disabled, empty_state and error_state."
162
+ },
163
+ UI_STATES_NO_A11Y_FOCUS: {
164
+ severity: "medium", deduction: 15,
165
+ message: "UI states lack keyboard/focus coverage.",
166
+ mutantScenario: "A UI with broken tab order or invisible focus rings passes.",
167
+ recommendation: "Add a keyboard_tab check with expectedFocusOrder or a focus check."
168
+ },
169
+ UI_STATES_NO_EDGE_STATE: {
170
+ severity: "low", deduction: 10,
171
+ message: "UI states lack a negative/edge state.",
172
+ mutantScenario: "A UI that only renders the happy path passes.",
173
+ recommendation: "Add error_state, empty_state or disabled checks."
174
+ },
175
+ VISUAL_PERMISSIVE_THRESHOLD: {
176
+ severity: "high", deduction: 35,
177
+ message: "Visual tolerance thresholds are overly permissive.",
178
+ mutantScenario: "A visibly different or half-rendered image passes the similarity gate.",
179
+ recommendation: "Tighten tolerance: minSSIM >= 0.7, min IoU >= 0.6, max diff ratio <= 0.25."
180
+ },
181
+ VIDEO_WEAK_TIMELINE: {
182
+ severity: "medium", deduction: 25,
183
+ message: "Video timeline has too few states or a permissive similarity floor.",
184
+ mutantScenario: "A static frame or wrong scene order passes the timeline check.",
185
+ recommendation: "Assert 2+ keyframe states with transitions and a similarity floor >= 0.7."
186
+ },
187
+ REPO_EMPTY_EXPORTS: {
188
+ severity: "high", deduction: 45,
189
+ message: "repo_exports invariant expects no exports and no files.",
190
+ mutantScenario: "An empty module passes.",
191
+ recommendation: "List expected.exports (name, kind) and expected.filesPresent."
192
+ },
193
+ STATE_WILDCARD_MASK: {
194
+ severity: "critical", deduction: 60,
195
+ message: "State-file ignorePaths masks the entire document.",
196
+ mutantScenario: "Any JSON (or an empty object) passes because everything is ignored.",
197
+ recommendation: "Ignore only volatile leaf paths (e.g. $.updatedAt), never \"$\", \"*\" or \"\"."
198
+ },
199
+ STATE_NO_ASSERTIONS: {
200
+ severity: "high", deduction: 45,
201
+ message: "State-file invariant has no JSON assertions.",
202
+ mutantScenario: "Writing `{}` to the state file passes.",
203
+ recommendation: "Add expected.jsonSchema plus jsonSubset or jsonPaths for the persisted state."
204
+ },
205
+ SVG_WEAK_GUARD: {
206
+ severity: "medium", deduction: 25,
207
+ message: "SVG security/accessibility guards are disabled.",
208
+ mutantScenario: "An SVG with inline <script> or no accessible name passes.",
209
+ recommendation: "Remove allowScripts and keep requireAccessibleName enabled."
210
+ },
211
+ PERF_NO_BUDGET: {
212
+ severity: "high", deduction: 45,
213
+ message: "Performance budget invariant declares neither a latency nor a payload byte budget.",
214
+ mutantScenario: "A slow or bloated regression passes because no latency percentile or byte ceiling is enforced.",
215
+ recommendation: "Set latency budgets (maxP95Ms, maxP50Ms, maxMeanMs, maxDurationMs) and/or payload bounds (maxBytes, minBytes)."
216
+ },
217
+ PERF_SINGLE_RUN: {
218
+ severity: "low", deduction: 10,
219
+ message: "Performance budget executes only a single measured run (runs: 1).",
220
+ mutantScenario: "A single noisy sample hides tail-latency regressions or produces unstable p95/p99 measurements.",
221
+ recommendation: "Set input.runs >= 3 (default 5) with warmupRuns >= 1 for stable latency percentiles."
222
+ },
223
+ FIXTURE_UNBALANCED_LIFECYCLE: {
224
+ severity: "low", deduction: 5,
225
+ message: "Contract fixtures declare setup hooks without matching teardown hooks.",
226
+ mutantScenario: "Stateful mutations from fixture setup leak across verification runs and cause order-dependent false passes or flakes.",
227
+ recommendation: "Pair fixtures.httpSetup with fixtures.httpTeardown and fixtures.commandSetup with fixtures.commandTeardown so runs stay idempotent."
228
+ }
229
+ };
230
+ const isObj = isRecordSafe;
231
+ const own = safeOwnProp;
232
+ function has(o, key) {
233
+ const v = own(o, key);
234
+ if (v === undefined || v === null)
235
+ return false;
236
+ if (safeIsArray(v)) {
237
+ try {
238
+ return v.length > 0;
239
+ }
240
+ catch {
241
+ return false;
242
+ }
243
+ }
244
+ if (typeof v === "string")
245
+ return v.length > 0;
246
+ return true;
247
+ }
248
+ function hasAny(o, keys) {
249
+ return keys.some((k) => has(o, k));
250
+ }
251
+ function arr(v) {
252
+ return safeIsArray(v) ? v : [];
253
+ }
254
+ function num(v) {
255
+ return typeof v === "number" && Number.isFinite(v) ? v : undefined;
256
+ }
257
+ function clamp(n) {
258
+ return Math.max(0, Math.min(100, n));
259
+ }
260
+ export function scoreToGrade(score) {
261
+ const s = typeof score === "number" && Number.isFinite(score) ? score : 0;
262
+ if (s >= 90)
263
+ return "A";
264
+ if (s >= 75)
265
+ return "B";
266
+ if (s >= 60)
267
+ return "C";
268
+ if (s >= 45)
269
+ return "D";
270
+ return "F";
271
+ }
272
+ function makeRisk(code, invariantId, domain) {
273
+ const t = RISKS[code];
274
+ const risk = {
275
+ code,
276
+ severity: t.severity,
277
+ message: invariantId ? `${invariantId}: ${t.message}` : t.message,
278
+ mutantScenario: t.mutantScenario,
279
+ recommendation: t.recommendation,
280
+ deduction: t.deduction
281
+ };
282
+ if (invariantId !== undefined)
283
+ risk.invariantId = invariantId;
284
+ if (domain !== undefined)
285
+ risk.domain = domain;
286
+ return risk;
287
+ }
288
+ const CLI_OUTPUT_KEYS = [
289
+ "stdoutExact", "stdoutContains", "stdoutNotContains", "stdoutRegex", "stderrExact", "stderrContains",
290
+ "goldenStdout", "jsonSchema", "jsonSubset", "jsonPaths", "jsonPath", "fsEffects"
291
+ ];
292
+ const CLI_STRONG_KEYS = ["stdoutExact", "goldenStdout", "stdoutRegex", "jsonSchema", "jsonSubset", "jsonPaths", "jsonPath"];
293
+ const HTTP_BODY_KEYS = ["jsonSchema", "jsonSubset", "bodyContains", "bodyExact", "jsonPaths", "jsonPath", "headers"];
294
+ const JSON_KEYS = ["jsonSchema", "jsonSubset", "jsonPaths", "jsonPath"];
295
+ const STEP_ASSERT_KEYS = ["jsonSchema", "jsonSubset", "jsonPaths", "jsonPath", "bodyContains", "bodyExact", "headers", "textExact", "textContains"];
296
+ const WEB_CONTENT_KEYS = [
297
+ "titleContains", "title", "landmarks", "textContains", "visibleText", "hiddenText", "domAssertions",
298
+ "interactiveLandmarks", "boundingBoxes", "responsiveViewports"
299
+ ];
300
+ const WEB_FLOW_ASSERT_KEYS = [
301
+ "finalUrlIncludes", "visibleText", "hiddenText", "textContains", "domAssertions", "networkCalls",
302
+ "titleContains", "landmarks", "boundingBoxes", "assertions"
303
+ ];
304
+ const MUTATING_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
305
+ const WRITE_ARG_RE = /^(?:--out(?:put)?(?:=.*)?|-o|write|--write(?:=.*)?)$/i;
306
+ const WILDCARD_IGNORE = new Set(["*", "$", "", "$.*", "$[*]", "$..*"]);
307
+ function auditCommand(expected, input, codes) {
308
+ if (!hasAny(expected, CLI_OUTPUT_KEYS)) {
309
+ codes.add("CLI_EXIT_ONLY");
310
+ }
311
+ else if (!hasAny(expected, CLI_STRONG_KEYS) && !has(expected, "fsEffects")) {
312
+ const needles = arr(own(expected, "stdoutContains")).filter((n) => typeof n === "string");
313
+ if (needles.length > 0 && needles.every((n) => n.trim().length < 4))
314
+ codes.add("CLI_WEAK_MATCH");
315
+ }
316
+ const args = arr(own(input, "args")).filter((a) => typeof a === "string");
317
+ if (args.some((a) => WRITE_ARG_RE.test(a)) && !has(expected, "fsEffects") && own(input, "fsDiff") !== true) {
318
+ codes.add("CLI_UNCHECKED_SIDE_EFFECT");
319
+ }
320
+ }
321
+ function headerKeys(o) {
322
+ const h = own(o, "headers");
323
+ if (!isObj(h))
324
+ return [];
325
+ try {
326
+ return Object.keys(h).map((k) => k.toLowerCase());
327
+ }
328
+ catch {
329
+ return [];
330
+ }
331
+ }
332
+ function auditHttp(expected, codes) {
333
+ if (!hasAny(expected, HTTP_BODY_KEYS)) {
334
+ codes.add("HTTP_STATUS_ONLY");
335
+ return;
336
+ }
337
+ if (hasAny(expected, ["jsonSubset", "bodyContains", "jsonPaths", "jsonPath"]) && !has(expected, "jsonSchema")) {
338
+ codes.add("HTTP_NO_SCHEMA");
339
+ }
340
+ if (hasAny(expected, JSON_KEYS) && !headerKeys(expected).includes("content-type")) {
341
+ codes.add("HTTP_NO_CONTENT_TYPE");
342
+ }
343
+ }
344
+ function auditWorkflow(input, codes) {
345
+ const steps = arr(own(input, "steps"));
346
+ if (steps.length <= 1)
347
+ codes.add("WORKFLOW_SINGLE_STEP");
348
+ const mutating = steps.some((s) => {
349
+ const m = own(s, "method");
350
+ return typeof m === "string" && MUTATING_METHODS.has(m.trim().toUpperCase());
351
+ });
352
+ if (mutating && arr(own(input, "finallySteps")).length === 0)
353
+ codes.add("WORKFLOW_NO_CLEANUP");
354
+ let weak = 0;
355
+ for (const s of steps) {
356
+ const exp = own(s, "expected") ?? own(s, "expect");
357
+ if (!hasAny(exp, STEP_ASSERT_KEYS) && !has(s, "extract"))
358
+ weak++;
359
+ }
360
+ if (steps.length === 0 || weak * 2 > steps.length)
361
+ codes.add("WORKFLOW_WEAK_STEPS");
362
+ }
363
+ function auditStream(type, expected, input, codes) {
364
+ const minEvents = num(own(expected, "minEvents")) ?? 0;
365
+ let asserted = minEvents > 0 ||
366
+ hasAny(expected, ["expectEvents", "expectMessages", "expectFrames", "orderedEvents", "terminalEvent"]);
367
+ if (!asserted && type === "ws_protocol") {
368
+ asserted = arr(own(input, "steps")).some((s) => own(s, "action") === "expect");
369
+ }
370
+ if (!asserted)
371
+ codes.add("STREAM_NO_ASSERTIONS");
372
+ }
373
+ function auditWebRoute(expected, codes) {
374
+ if (!hasAny(expected, WEB_CONTENT_KEYS))
375
+ codes.add("WEB_STATUS_ONLY");
376
+ if (!has(expected, "responsiveViewports"))
377
+ codes.add("WEB_NO_RESPONSIVE");
378
+ }
379
+ function auditWebFlow(expected, input, codes) {
380
+ const steps = arr(own(input, "steps"));
381
+ const stepAsserts = steps.some((s) => {
382
+ const action = own(s, "action");
383
+ return typeof action === "string" && /^(?:expect|assert)/i.test(action);
384
+ });
385
+ if (!hasAny(expected, WEB_FLOW_ASSERT_KEYS) && !stepAsserts)
386
+ codes.add("WEB_FLOW_NO_ASSERTIONS");
387
+ }
388
+ function auditUiStates(expected, input, codes) {
389
+ const checks = arr(own(input, "checks")).length > 0 ? arr(own(input, "checks")) : arr(own(expected, "checks"));
390
+ if (checks.length === 0) {
391
+ codes.add("UI_STATES_EMPTY");
392
+ return;
393
+ }
394
+ const kinds = new Set(checks.map((c) => own(c, "kind")).filter((k) => typeof k === "string"));
395
+ if (!kinds.has("keyboard_tab") && !kinds.has("focus"))
396
+ codes.add("UI_STATES_NO_A11Y_FOCUS");
397
+ if (!kinds.has("error_state") && !kinds.has("empty_state") && !kinds.has("disabled"))
398
+ codes.add("UI_STATES_NO_EDGE_STATE");
399
+ }
400
+ function firstNum(sources, keys) {
401
+ const out = [];
402
+ for (const src of sources)
403
+ for (const k of keys) {
404
+ const n = num(own(src, k));
405
+ if (n !== undefined)
406
+ out.push(n);
407
+ }
408
+ return out;
409
+ }
410
+ function auditVisual(expected, tolerance, codes) {
411
+ const src = [tolerance, expected];
412
+ const permissive = firstNum(src, ["minSSIM"]).some((n) => n < 0.7) ||
413
+ firstNum(src, ["minRegionIoU", "minLayoutIoU"]).some((n) => n < 0.6) ||
414
+ firstNum(src, ["maxDiffRatio", "maxPixelDiffRatio"]).some((n) => n > 0.25);
415
+ if (permissive)
416
+ codes.add("VISUAL_PERMISSIVE_THRESHOLD");
417
+ }
418
+ function auditVideo(expected, tolerance, codes) {
419
+ const states = arr(own(expected, "states"));
420
+ const permissive = firstNum([tolerance, expected], ["minSimilarity", "stateMatchFloor", "minKeyframeSSIM"]).some((n) => n < 0.7);
421
+ if (states.length < 2 || permissive)
422
+ codes.add("VIDEO_WEAK_TIMELINE");
423
+ }
424
+ function auditStateFile(expected, input, codes) {
425
+ const ignore = [...arr(own(input, "ignorePaths")), ...arr(own(expected, "ignorePaths"))];
426
+ if (ignore.some((p) => typeof p === "string" && WILDCARD_IGNORE.has(p.trim())))
427
+ codes.add("STATE_WILDCARD_MASK");
428
+ if (!hasAny(expected, ["jsonSchema", "jsonSubset", "expectedJson", "jsonPaths", "jsonPath"]))
429
+ codes.add("STATE_NO_ASSERTIONS");
430
+ }
431
+ const PERF_BUDGET_KEYS = [
432
+ "maxP50Ms", "maxP95Ms", "maxP99Ms", "maxMeanMs", "maxDurationMs", "maxBytes", "minBytes"
433
+ ];
434
+ function auditPerfBudget(expected, input, codes) {
435
+ const hasBudget = PERF_BUDGET_KEYS.some((k) => {
436
+ const v = num(own(expected, k));
437
+ return v !== undefined && v >= 0;
438
+ });
439
+ if (!hasBudget)
440
+ codes.add("PERF_NO_BUDGET");
441
+ if (num(own(input, "runs")) === 1)
442
+ codes.add("PERF_SINGLE_RUN");
443
+ }
444
+ function auditSvg(expected, input, codes) {
445
+ if (own(expected, "allowScripts") === true || own(input, "allowScripts") === true || own(expected, "requireAccessibleName") === false) {
446
+ codes.add("SVG_WEAK_GUARD");
447
+ }
448
+ }
449
+ function auditInvariant(raw, index) {
450
+ const fallbackId = `invariant-${index + 1}`;
451
+ if (!isObj(raw)) {
452
+ const risks = [makeRisk("MALFORMED_INVARIANT", fallbackId, "cli")];
453
+ return { id: fallbackId, type: "unknown", domain: "cli", severity: "hard", score: 0, grade: "F", risks };
454
+ }
455
+ const rawId = own(raw, "id");
456
+ const scrubbedId = typeof rawId === "string" || typeof rawId === "number" ? sanitizeSingleLine(String(rawId), MAX_ID_CHARS) : "";
457
+ const id = scrubbedId || fallbackId;
458
+ const rawType = own(raw, "type");
459
+ const trimmedType = typeof rawType === "string" ? rawType.trim() : "";
460
+ const type = trimmedType
461
+ ? KNOWN_INVARIANT_TYPES.has(trimmedType)
462
+ ? trimmedType
463
+ : sanitizeSingleLine(trimmedType, 64) || "unknown"
464
+ : "unknown";
465
+ const rawDomain = own(raw, "domain");
466
+ const domain = inferDomainForInvariant({
467
+ ...(typeof rawDomain === "string" ? { domain: rawDomain } : {}),
468
+ ...(trimmedType ? { type: trimmedType } : {})
469
+ });
470
+ const severity = own(raw, "severity") === "soft" ? "soft" : "hard";
471
+ const codes = new Set();
472
+ try {
473
+ const expected = own(raw, "expected");
474
+ const input = own(raw, "input");
475
+ const tolerance = own(raw, "tolerance");
476
+ const t = trimmedType;
477
+ if (t === "command")
478
+ auditCommand(expected, input, codes);
479
+ else if (t === "http")
480
+ auditHttp(expected, codes);
481
+ else if (t === "http_workflow")
482
+ auditWorkflow(input, codes);
483
+ else if (t === "http_stream" || t === "ws_protocol")
484
+ auditStream(t, expected, input, codes);
485
+ else if (t === "perf_budget")
486
+ auditPerfBudget(expected, input, codes);
487
+ else if (t === "web_route")
488
+ auditWebRoute(expected, codes);
489
+ else if (t === "web_flow")
490
+ auditWebFlow(expected, input, codes);
491
+ else if (t === "web_ui_states")
492
+ auditUiStates(expected, input, codes);
493
+ else if (t === "image_layout" || t === "image_perceptual")
494
+ auditVisual(expected, tolerance, codes);
495
+ else if (t === "video_timeline")
496
+ auditVideo(expected, tolerance, codes);
497
+ else if (t === "repo_exports") {
498
+ if (!hasAny(expected, ["exports", "files", "filesPresent"]))
499
+ codes.add("REPO_EMPTY_EXPORTS");
500
+ }
501
+ else if (t === "plugin_state_file")
502
+ auditStateFile(expected, input, codes);
503
+ else if (t === "plugin_svg_a11y")
504
+ auditSvg(expected, input, codes);
505
+ else if (!t)
506
+ codes.add("MALFORMED_INVARIANT");
507
+ else if (!isObj(expected) || Object.keys(expected).filter((k) => !isForbiddenObjectKey(k)).length === 0) {
508
+ codes.add("NO_ASSERTIONS");
509
+ }
510
+ }
511
+ catch {
512
+ codes.clear();
513
+ codes.add("MALFORMED_INVARIANT");
514
+ }
515
+ const risks = [...codes].map((c) => makeRisk(c, id, domain));
516
+ const score = Math.round(clamp(100 - risks.reduce((sum, r) => sum + r.deduction, 0)));
517
+ return { id, type, domain, severity, score, grade: scoreToGrade(score), risks };
518
+ }
519
+ function compareRisks(a, b) {
520
+ const sev = SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity];
521
+ if (sev !== 0)
522
+ return sev;
523
+ if (b.deduction !== a.deduction)
524
+ return b.deduction - a.deduction;
525
+ const ai = a.invariantId ?? "";
526
+ const bi = b.invariantId ?? "";
527
+ if (ai !== bi)
528
+ return ai < bi ? -1 : 1;
529
+ return a.code < b.code ? -1 : a.code > b.code ? 1 : 0;
530
+ }
531
+ /** Strict O(N) top-K selection preserving compareRisks order without sorting all N risks. */
532
+ function selectTopRisks(all, limit) {
533
+ const top = [];
534
+ for (const r of all) {
535
+ if (top.length < limit) {
536
+ top.push(r);
537
+ let idx = top.length - 1;
538
+ while (idx > 0 && compareRisks(top[idx], top[idx - 1]) < 0) {
539
+ const tmp = top[idx - 1];
540
+ top[idx - 1] = top[idx];
541
+ top[idx] = tmp;
542
+ idx--;
543
+ }
544
+ }
545
+ else if (compareRisks(r, top[limit - 1]) < 0) {
546
+ let idx = limit - 1;
547
+ top[idx] = r;
548
+ while (idx > 0 && compareRisks(top[idx], top[idx - 1]) < 0) {
549
+ const tmp = top[idx - 1];
550
+ top[idx - 1] = top[idx];
551
+ top[idx] = tmp;
552
+ idx--;
553
+ }
554
+ }
555
+ }
556
+ return top;
557
+ }
558
+ function positiveInt(v, fallback) {
559
+ return typeof v === "number" && Number.isFinite(v) && v >= 1 ? Math.min(MAX_BRIEF_CHARS_CAP, Math.floor(v)) : fallback;
560
+ }
561
+ function buildBrief(report, maxChars) {
562
+ const s = report.summary;
563
+ const lines = [
564
+ `Oracle strength: ${report.grade} (${report.score}/100) ${report.ok ? "PASS" : "FAIL"}${report.strict ? " [strict]" : ""}; ` +
565
+ `${s.invariants} invariants (${s.hard} hard, ${s.soft} soft), ${s.holdouts} holdouts; ` +
566
+ `risks: ${s.critical} critical, ${s.high} high, ${s.medium} medium, ${s.low} low.`
567
+ ];
568
+ if (report.topRisks.length > 0) {
569
+ lines.push("Hardening fixes:");
570
+ report.topRisks.forEach((r, i) => {
571
+ lines.push(`${i + 1}. [${r.severity}] ${r.code}${r.invariantId ? ` @${r.invariantId}` : ""}: ${r.recommendation}`);
572
+ });
573
+ }
574
+ else {
575
+ lines.push("No mutation risks found; keep holdouts rotating.");
576
+ }
577
+ let out = "";
578
+ for (const line of lines.map((l) => sanitizeSingleLine(l))) {
579
+ const next = out ? `${out}\n${line}` : line;
580
+ if (next.length > maxChars) {
581
+ if (!out)
582
+ out = line.slice(0, maxChars);
583
+ break;
584
+ }
585
+ out = next;
586
+ }
587
+ // Redaction may change lengths; re-scrub and hard-cap so the bound is unconditional.
588
+ return redactSensitiveText(out).slice(0, maxChars);
589
+ }
590
+ function failClosedReport(strict, maxChars) {
591
+ const risk = makeRisk("EMPTY_CONTRACT");
592
+ const base = {
593
+ ok: false, strict, exitCode: 1, score: 0, grade: "F",
594
+ summary: { invariants: 0, hard: 0, soft: 0, holdouts: 0, critical: 1, high: 0, medium: 0, low: 0 },
595
+ byDomain: {}, invariants: [], contractRisks: [risk], topRisks: [risk]
596
+ };
597
+ return { ...base, hardeningBrief: buildBrief(base, maxChars) };
598
+ }
599
+ export function auditContractStrength(contract, options = {}) {
600
+ const opts = options;
601
+ const strict = own(opts, "strict") === true;
602
+ const minScoreRaw = num(own(opts, "minScore"));
603
+ const minScore = minScoreRaw === undefined ? DEFAULT_MIN_STRENGTH_SCORE : clamp(minScoreRaw);
604
+ const maxChars = positiveInt(own(opts, "maxBriefChars"), DEFAULT_MAX_HARDENING_BRIEF_CHARS);
605
+ const holdoutOpt = num(own(opts, "holdoutCount"));
606
+ const hasValidHoldoutOpt = holdoutOpt !== undefined && holdoutOpt >= 0;
607
+ const rawInvariants = own(contract, "invariants");
608
+ if (!isObj(contract) || !safeIsArray(rawInvariants))
609
+ return failClosedReport(strict, maxChars);
610
+ try {
611
+ const visible = [];
612
+ let flaggedHoldouts = 0;
613
+ for (const inv of rawInvariants) {
614
+ if (own(inv, "holdout") === true)
615
+ flaggedHoldouts++;
616
+ else
617
+ visible.push(inv);
618
+ }
619
+ const holdouts = hasValidHoldoutOpt
620
+ ? Math.max(flaggedHoldouts, Math.min(1_000_000, Math.floor(holdoutOpt)))
621
+ : flaggedHoldouts;
622
+ const invariants = visible.map((inv, i) => auditInvariant(inv, i));
623
+ const hard = invariants.filter((i) => i.severity === "hard").length;
624
+ const soft = invariants.length - hard;
625
+ const contractRisks = [];
626
+ if (invariants.length === 0)
627
+ contractRisks.push(makeRisk("EMPTY_CONTRACT"));
628
+ else if (hard === 0)
629
+ contractRisks.push(makeRisk("NO_HARD_GATE"));
630
+ if (holdouts === 0 && (hasValidHoldoutOpt || invariants.length >= 2))
631
+ contractRisks.push(makeRisk("ZERO_HOLDOUTS"));
632
+ if (invariants.length === 1)
633
+ contractRisks.push(makeRisk("SINGLE_PROBE_SURFACE"));
634
+ const commands = visible.filter((inv) => own(inv, "type") === "command");
635
+ if (commands.length >= 3) {
636
+ const errorPath = commands.some((inv) => {
637
+ const exp = own(inv, "expected");
638
+ const codesRaw = own(exp, "exitCode");
639
+ const exits = safeIsArray(codesRaw) ? codesRaw : [codesRaw];
640
+ try {
641
+ return exits.some((c) => typeof c === "number" && c !== 0) || hasAny(exp, ["stderrContains", "stderrExact"]);
642
+ }
643
+ catch {
644
+ return false;
645
+ }
646
+ });
647
+ if (!errorPath)
648
+ contractRisks.push(makeRisk("CLI_NO_ERROR_PATH"));
649
+ }
650
+ const rawFixtures = own(contract, "fixtures");
651
+ if (isObj(rawFixtures)) {
652
+ const hasHttpSetup = arr(own(rawFixtures, "httpSetup")).length > 0;
653
+ const hasHttpTeardown = arr(own(rawFixtures, "httpTeardown")).length > 0;
654
+ const hasCmdSetup = arr(own(rawFixtures, "commandSetup")).length > 0;
655
+ const hasCmdTeardown = arr(own(rawFixtures, "commandTeardown")).length > 0;
656
+ if ((hasHttpSetup && !hasHttpTeardown) || (hasCmdSetup && !hasCmdTeardown)) {
657
+ contractRisks.push(makeRisk("FIXTURE_UNBALANCED_LIFECYCLE"));
658
+ }
659
+ }
660
+ let score = 0;
661
+ if (invariants.length > 0) {
662
+ const avg = invariants.reduce((sum, i) => sum + i.score, 0) / invariants.length;
663
+ const penalty = Math.min(MAX_CONTRACT_PENALTY, contractRisks.reduce((sum, r) => sum + r.deduction, 0));
664
+ score = Math.round(clamp(avg - penalty));
665
+ }
666
+ const allRisks = [];
667
+ for (const r of contractRisks)
668
+ allRisks.push(r);
669
+ for (const inv of invariants) {
670
+ for (const r of inv.risks)
671
+ allRisks.push(r);
672
+ }
673
+ const counts = { critical: 0, high: 0, medium: 0, low: 0 };
674
+ for (const r of allRisks)
675
+ counts[r.severity]++;
676
+ const domainAgg = new Map();
677
+ for (const inv of invariants) {
678
+ const agg = domainAgg.get(inv.domain) ?? { count: 0, total: 0 };
679
+ agg.count++;
680
+ agg.total += inv.score;
681
+ domainAgg.set(inv.domain, agg);
682
+ }
683
+ const byDomain = {};
684
+ for (const domain of [...domainAgg.keys()].sort()) {
685
+ const agg = domainAgg.get(domain);
686
+ const avgScore = Math.round(agg.total / agg.count);
687
+ byDomain[domain] = { count: agg.count, avgScore, grade: scoreToGrade(avgScore) };
688
+ }
689
+ const critical = counts.critical > 0;
690
+ const ok = strict ? !critical && score >= minScore : !critical;
691
+ const base = {
692
+ ok, strict, exitCode: ok ? 0 : 1, score, grade: scoreToGrade(score),
693
+ summary: { invariants: invariants.length, hard, soft, holdouts, ...counts },
694
+ byDomain, invariants, contractRisks,
695
+ topRisks: selectTopRisks(allRisks, MAX_TOP_RISKS)
696
+ };
697
+ return { ...base, hardeningBrief: buildBrief(base, maxChars) };
698
+ }
699
+ catch {
700
+ return failClosedReport(strict, maxChars);
701
+ }
702
+ }
703
+ const ANSI = { reset: "\x1b[0m", bold: "\x1b[1m", red: "\x1b[31m", green: "\x1b[32m", yellow: "\x1b[33m" };
704
+ export function formatPrettyMutationAudit(report, options = {}) {
705
+ const color = own(options, "color") === true;
706
+ const paint = (code, text) => (color ? `${code}${text}${ANSI.reset}` : text);
707
+ const clean = (v, max = 240) => sanitizeSingleLine(safeString(v), max);
708
+ const gradeColor = (g) => (g === "A" || g === "B" ? ANSI.green : g === "C" ? ANSI.yellow : ANSI.red);
709
+ const r = isObj(report) ? report : {};
710
+ const rawSummary = own(r, "summary");
711
+ const s = isObj(rawSummary) ? rawSummary : { invariants: 0, hard: 0, soft: 0, holdouts: 0, critical: 0, high: 0, medium: 0, low: 0 };
712
+ const grade = clean(own(r, "grade") ?? "F", 1) || "F";
713
+ const score = num(own(r, "score")) ?? 0;
714
+ const status = own(r, "ok") === true ? paint(ANSI.green, "PASS") : paint(ANSI.red, "FAIL");
715
+ const isStrict = own(r, "strict") === true;
716
+ const lines = [
717
+ `${paint(ANSI.bold, "Oracle strength audit")}: grade ${paint(gradeColor(grade), grade)} (${score}/100) ${status}${isStrict ? " [strict]" : ""}`,
718
+ `Invariants: ${num(own(s, "invariants")) ?? 0} (hard ${num(own(s, "hard")) ?? 0}, soft ${num(own(s, "soft")) ?? 0}), holdouts ${num(own(s, "holdouts")) ?? 0}`,
719
+ `Risks: critical ${num(own(s, "critical")) ?? 0}, high ${num(own(s, "high")) ?? 0}, medium ${num(own(s, "medium")) ?? 0}, low ${num(own(s, "low")) ?? 0}`
720
+ ];
721
+ const rawByDomain = own(r, "byDomain");
722
+ let domains = [];
723
+ if (isObj(rawByDomain)) {
724
+ try {
725
+ domains = Object.keys(rawByDomain).filter((k) => !isForbiddenObjectKey(k)).sort();
726
+ }
727
+ catch {
728
+ domains = [];
729
+ }
730
+ }
731
+ if (domains.length > 0) {
732
+ lines.push("", "By domain:", ` ${"domain".padEnd(8)}${"count".padStart(6)}${"avg".padStart(6)} grade`);
733
+ for (const d of domains) {
734
+ const row = own(rawByDomain, d);
735
+ const g = clean(own(row, "grade") ?? "F", 1) || "F";
736
+ lines.push(` ${clean(d, 8).padEnd(8)}${String(num(own(row, "count")) ?? 0).padStart(6)}${String(num(own(row, "avgScore")) ?? 0).padStart(6)} ${paint(gradeColor(g), g)}`);
737
+ }
738
+ }
739
+ const rawTop = own(r, "topRisks");
740
+ const top = [];
741
+ if (safeIsArray(rawTop)) {
742
+ try {
743
+ for (const item of rawTop) {
744
+ if (top.length >= MAX_TOP_RISKS)
745
+ break;
746
+ top.push(item);
747
+ }
748
+ }
749
+ catch {
750
+ // Ignore hostile topRisks array traps.
751
+ }
752
+ }
753
+ lines.push("");
754
+ if (top.length === 0) {
755
+ lines.push("No stub-bypass mutation risks detected.");
756
+ }
757
+ else {
758
+ lines.push("Top stub-bypass mutation risks:");
759
+ top.forEach((risk, i) => {
760
+ const sev = clean(own(risk, "severity"), 16).toUpperCase();
761
+ const sevPaint = sev === "CRITICAL" || sev === "HIGH" ? ANSI.red : sev === "MEDIUM" ? ANSI.yellow : ANSI.reset;
762
+ const inv = own(risk, "invariantId");
763
+ lines.push(` ${i + 1}. [${paint(sevPaint, sev)}] ${clean(own(risk, "code"), 64)}${inv !== undefined ? ` (${clean(inv, MAX_ID_CHARS)})` : ""}`);
764
+ lines.push(` mutant: ${clean(own(risk, "mutantScenario"))}`);
765
+ lines.push(` fix: ${clean(own(risk, "recommendation"))}`);
766
+ });
767
+ }
768
+ return `${lines.join("\n")}\n`;
769
+ }