milieu-cli 0.3.2 → 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 (330) hide show
  1. package/README.md +177 -76
  2. package/dist/bridges/context/agents-json.d.ts +0 -1
  3. package/dist/bridges/context/agents-json.js +21 -12
  4. package/dist/bridges/context/auth-clarity.d.ts +0 -1
  5. package/dist/bridges/context/auth-clarity.js +11 -9
  6. package/dist/bridges/context/auth-legibility.d.ts +2 -2
  7. package/dist/bridges/context/auth-legibility.js +67 -60
  8. package/dist/bridges/context/index.d.ts +1 -2
  9. package/dist/bridges/context/index.js +19 -40
  10. package/dist/bridges/context/oauth-metadata.d.ts +14 -0
  11. package/dist/bridges/context/oauth-metadata.js +127 -0
  12. package/dist/bridges/context/probe.d.ts +33 -0
  13. package/dist/bridges/context/probe.js +157 -0
  14. package/dist/bridges/context/rate-limits.d.ts +5 -2
  15. package/dist/bridges/context/rate-limits.js +27 -51
  16. package/dist/bridges/context/tos-contact.d.ts +13 -4
  17. package/dist/bridges/context/tos-contact.js +108 -46
  18. package/dist/bridges/context/versioning.d.ts +1 -2
  19. package/dist/bridges/context/versioning.js +42 -7
  20. package/dist/bridges/index.d.ts +0 -1
  21. package/dist/bridges/index.js +0 -1
  22. package/dist/bridges/reachability/crawler-policy.d.ts +30 -10
  23. package/dist/bridges/reachability/crawler-policy.js +41 -56
  24. package/dist/bridges/reachability/http-status.d.ts +3 -2
  25. package/dist/bridges/reachability/http-status.js +18 -3
  26. package/dist/bridges/reachability/https-check.d.ts +2 -2
  27. package/dist/bridges/reachability/https-check.js +6 -3
  28. package/dist/bridges/reachability/index.d.ts +1 -2
  29. package/dist/bridges/reachability/index.js +34 -43
  30. package/dist/bridges/reachability/meta-robots.d.ts +0 -13
  31. package/dist/bridges/reachability/meta-robots.js +89 -101
  32. package/dist/bridges/reachability/robots-parser.d.ts +7 -7
  33. package/dist/bridges/reachability/robots-parser.js +65 -15
  34. package/dist/bridges/reachability/robots-txt.d.ts +4 -2
  35. package/dist/bridges/reachability/robots-txt.js +33 -60
  36. package/dist/bridges/schema/descriptions.d.ts +2 -2
  37. package/dist/bridges/schema/descriptions.js +79 -44
  38. package/dist/bridges/schema/error-schemas.d.ts +2 -2
  39. package/dist/bridges/schema/error-schemas.js +31 -18
  40. package/dist/bridges/schema/index.d.ts +2 -2
  41. package/dist/bridges/schema/index.js +48 -30
  42. package/dist/bridges/schema/oas-types.d.ts +65 -26
  43. package/dist/bridges/schema/oas-types.js +37 -7
  44. package/dist/bridges/schema/operation-ids.d.ts +2 -2
  45. package/dist/bridges/schema/operation-ids.js +2 -3
  46. package/dist/bridges/schema/required-fields.d.ts +2 -2
  47. package/dist/bridges/schema/required-fields.js +12 -10
  48. package/dist/bridges/schema/schema-sources.d.ts +19 -0
  49. package/dist/bridges/schema/schema-sources.js +182 -0
  50. package/dist/bridges/schema/schema-types.d.ts +2 -2
  51. package/dist/bridges/schema/schema-types.js +20 -21
  52. package/dist/bridges/separation/api-presence.d.ts +3 -15
  53. package/dist/bridges/separation/api-presence.js +34 -85
  54. package/dist/bridges/separation/developer-docs.d.ts +6 -18
  55. package/dist/bridges/separation/developer-docs.js +100 -99
  56. package/dist/bridges/separation/docs-discovery.d.ts +28 -0
  57. package/dist/bridges/separation/docs-discovery.js +95 -0
  58. package/dist/bridges/separation/evidence-summary.d.ts +2 -0
  59. package/dist/bridges/separation/evidence-summary.js +67 -0
  60. package/dist/bridges/separation/index.d.ts +2 -19
  61. package/dist/bridges/separation/index.js +35 -39
  62. package/dist/bridges/separation/published-routes.d.ts +69 -0
  63. package/dist/bridges/separation/published-routes.js +271 -0
  64. package/dist/bridges/separation/sdk-references.d.ts +8 -3
  65. package/dist/bridges/separation/sdk-references.js +86 -61
  66. package/dist/bridges/separation/webhook-support.d.ts +3 -23
  67. package/dist/bridges/separation/webhook-support.js +61 -162
  68. package/dist/bridges/standards/a2a-agent-card.d.ts +0 -1
  69. package/dist/bridges/standards/a2a-agent-card.js +24 -9
  70. package/dist/bridges/standards/graphql.d.ts +3 -4
  71. package/dist/bridges/standards/graphql.js +70 -66
  72. package/dist/bridges/standards/index.d.ts +1 -2
  73. package/dist/bridges/standards/index.js +57 -47
  74. package/dist/bridges/standards/json-ld.d.ts +25 -11
  75. package/dist/bridges/standards/json-ld.js +114 -56
  76. package/dist/bridges/standards/llms-txt.d.ts +4 -2
  77. package/dist/bridges/standards/llms-txt.js +46 -32
  78. package/dist/bridges/standards/markdown-negotiation.d.ts +4 -1
  79. package/dist/bridges/standards/markdown-negotiation.js +16 -11
  80. package/dist/bridges/standards/mcp.d.ts +3 -12
  81. package/dist/bridges/standards/mcp.js +89 -132
  82. package/dist/bridges/standards/openapi.d.ts +7 -15
  83. package/dist/bridges/standards/openapi.js +657 -207
  84. package/dist/bridges/standards/probe-evidence.d.ts +30 -0
  85. package/dist/bridges/standards/probe-evidence.js +90 -0
  86. package/dist/bridges/standards/schema-org.d.ts +15 -9
  87. package/dist/bridges/standards/schema-org.js +38 -64
  88. package/dist/bridges/standards/sitemap.d.ts +2 -3
  89. package/dist/bridges/standards/sitemap.js +161 -169
  90. package/dist/bridges/standards/well-known.d.ts +3 -7
  91. package/dist/bridges/standards/well-known.js +28 -12
  92. package/dist/cli/index.d.ts +1 -1
  93. package/dist/cli/index.js +107 -22
  94. package/dist/cli/journey-commands.d.ts +3 -0
  95. package/dist/cli/journey-commands.js +35 -0
  96. package/dist/cli/read-report.d.ts +2 -0
  97. package/dist/cli/read-report.js +11 -0
  98. package/dist/core/bridge-output.d.ts +11 -0
  99. package/dist/core/bridge-output.js +86 -0
  100. package/dist/core/bridge-session.d.ts +28 -0
  101. package/dist/core/bridge-session.js +58 -0
  102. package/dist/core/bridge-worker.d.ts +1 -0
  103. package/dist/core/bridge-worker.js +66 -0
  104. package/dist/core/diff.d.ts +79 -0
  105. package/dist/core/diff.js +499 -0
  106. package/dist/core/explanations.d.ts +1 -3
  107. package/dist/core/explanations.js +36 -59
  108. package/dist/core/index.d.ts +4 -2
  109. package/dist/core/index.js +2 -3
  110. package/dist/core/scan-options.d.ts +0 -1
  111. package/dist/core/scan-options.js +14 -6
  112. package/dist/core/scan.d.ts +0 -1
  113. package/dist/core/scan.js +91 -41
  114. package/dist/core/scoring.d.ts +6 -0
  115. package/dist/core/scoring.js +27 -0
  116. package/dist/core/types.d.ts +97 -61
  117. package/dist/core/types.js +9 -3
  118. package/dist/core/validate-report.d.ts +5 -0
  119. package/dist/core/validate-report.js +95 -0
  120. package/dist/core/version.d.ts +0 -1
  121. package/dist/core/version.js +0 -1
  122. package/dist/index.d.ts +0 -1
  123. package/dist/index.js +0 -1
  124. package/dist/journey/body-worker.d.ts +27 -0
  125. package/dist/journey/body-worker.js +140 -0
  126. package/dist/journey/case.d.ts +74 -0
  127. package/dist/journey/case.js +187 -0
  128. package/dist/journey/cli.d.ts +14 -0
  129. package/dist/journey/cli.js +226 -0
  130. package/dist/journey/compare.d.ts +43 -0
  131. package/dist/journey/compare.js +83 -0
  132. package/dist/journey/contracts.d.ts +143 -0
  133. package/dist/journey/contracts.js +37 -0
  134. package/dist/journey/decision.d.ts +72 -0
  135. package/dist/journey/decision.js +121 -0
  136. package/dist/journey/demo.d.ts +36 -0
  137. package/dist/journey/demo.js +137 -0
  138. package/dist/journey/document.d.ts +8 -0
  139. package/dist/journey/document.js +113 -0
  140. package/dist/journey/excerpt.d.ts +6 -0
  141. package/dist/journey/excerpt.js +54 -0
  142. package/dist/journey/name-guidance.d.ts +2 -0
  143. package/dist/journey/name-guidance.js +41 -0
  144. package/dist/journey/providers.d.ts +34 -0
  145. package/dist/journey/providers.js +197 -0
  146. package/dist/journey/report-validation.d.ts +3 -0
  147. package/dist/journey/report-validation.js +457 -0
  148. package/dist/journey/runner.d.ts +12 -0
  149. package/dist/journey/runner.js +321 -0
  150. package/dist/journey/scope.d.ts +8 -0
  151. package/dist/journey/scope.js +50 -0
  152. package/dist/journey/transport.d.ts +3 -0
  153. package/dist/journey/transport.js +45 -0
  154. package/dist/journey/verify.d.ts +21 -0
  155. package/dist/journey/verify.js +213 -0
  156. package/dist/render/colors.d.ts +6 -7
  157. package/dist/render/colors.js +16 -25
  158. package/dist/render/discovery-guidance.d.ts +3 -0
  159. package/dist/render/discovery-guidance.js +66 -0
  160. package/dist/render/format-bridge.d.ts +1 -2
  161. package/dist/render/format-bridge.js +22 -17
  162. package/dist/render/format-diff.d.ts +2 -0
  163. package/dist/render/format-diff.js +169 -0
  164. package/dist/render/format-scan.d.ts +0 -1
  165. package/dist/render/format-scan.js +6 -4
  166. package/dist/render/format-verbose.d.ts +0 -1
  167. package/dist/render/format-verbose.js +7 -4
  168. package/dist/render/index.d.ts +0 -1
  169. package/dist/render/index.js +1 -2
  170. package/dist/render/oauth-observations.d.ts +4 -0
  171. package/dist/render/oauth-observations.js +27 -0
  172. package/dist/render/progress-bar.d.ts +1 -2
  173. package/dist/render/progress-bar.js +8 -6
  174. package/dist/render/robots-inventory.d.ts +3 -0
  175. package/dist/render/robots-inventory.js +38 -0
  176. package/dist/render/symbols.d.ts +4 -10
  177. package/dist/render/symbols.js +15 -17
  178. package/dist/render/terminal-text.d.ts +1 -3
  179. package/dist/render/terminal-text.js +1 -5
  180. package/dist/utils/analysis-worker-entry.d.ts +3 -0
  181. package/dist/utils/analysis-worker-entry.js +12 -0
  182. package/dist/utils/analysis-worker.d.ts +12 -0
  183. package/dist/utils/analysis-worker.js +54 -0
  184. package/dist/utils/html.d.ts +39 -0
  185. package/dist/utils/html.js +261 -0
  186. package/dist/utils/http-client.d.ts +24 -17
  187. package/dist/utils/http-client.js +166 -200
  188. package/dist/utils/http-types.d.ts +43 -0
  189. package/dist/utils/http-types.js +11 -0
  190. package/dist/utils/index.d.ts +0 -1
  191. package/dist/utils/index.js +0 -1
  192. package/dist/utils/package-registry.d.ts +11 -0
  193. package/dist/utils/package-registry.js +69 -0
  194. package/dist/utils/read-json-file.d.ts +3 -0
  195. package/dist/utils/read-json-file.js +41 -0
  196. package/dist/utils/record.d.ts +1 -0
  197. package/dist/utils/record.js +3 -0
  198. package/dist/utils/response-body.d.ts +7 -0
  199. package/dist/utils/response-body.js +71 -0
  200. package/dist/utils/ssrf.d.ts +11 -15
  201. package/dist/utils/ssrf.js +80 -44
  202. package/dist/utils/terminal-text.d.ts +2 -0
  203. package/dist/utils/terminal-text.js +4 -0
  204. package/dist/utils/url.d.ts +29 -1
  205. package/dist/utils/url.js +147 -17
  206. package/docs/examples/onboarding/account-claim.json +25 -0
  207. package/docs/examples/onboarding/pages/account-claim.html +3 -0
  208. package/docs/examples/onboarding/pages/production-activation.html +3 -0
  209. package/docs/examples/onboarding/pages/test-credential.html +3 -0
  210. package/docs/examples/onboarding/production-activation.json +25 -0
  211. package/docs/examples/onboarding/test-credential.json +25 -0
  212. package/docs/journey-qualification.md +46 -0
  213. package/docs/journeys.md +83 -0
  214. package/package.json +28 -8
  215. package/dist/bridges/context/agents-json.d.ts.map +0 -1
  216. package/dist/bridges/context/agents-json.js.map +0 -1
  217. package/dist/bridges/context/auth-clarity.d.ts.map +0 -1
  218. package/dist/bridges/context/auth-clarity.js.map +0 -1
  219. package/dist/bridges/context/auth-legibility.d.ts.map +0 -1
  220. package/dist/bridges/context/auth-legibility.js.map +0 -1
  221. package/dist/bridges/context/index.d.ts.map +0 -1
  222. package/dist/bridges/context/index.js.map +0 -1
  223. package/dist/bridges/context/rate-limits.d.ts.map +0 -1
  224. package/dist/bridges/context/rate-limits.js.map +0 -1
  225. package/dist/bridges/context/tos-contact.d.ts.map +0 -1
  226. package/dist/bridges/context/tos-contact.js.map +0 -1
  227. package/dist/bridges/context/versioning.d.ts.map +0 -1
  228. package/dist/bridges/context/versioning.js.map +0 -1
  229. package/dist/bridges/index.d.ts.map +0 -1
  230. package/dist/bridges/index.js.map +0 -1
  231. package/dist/bridges/reachability/crawler-policy.d.ts.map +0 -1
  232. package/dist/bridges/reachability/crawler-policy.js.map +0 -1
  233. package/dist/bridges/reachability/http-status.d.ts.map +0 -1
  234. package/dist/bridges/reachability/http-status.js.map +0 -1
  235. package/dist/bridges/reachability/https-check.d.ts.map +0 -1
  236. package/dist/bridges/reachability/https-check.js.map +0 -1
  237. package/dist/bridges/reachability/index.d.ts.map +0 -1
  238. package/dist/bridges/reachability/index.js.map +0 -1
  239. package/dist/bridges/reachability/meta-robots.d.ts.map +0 -1
  240. package/dist/bridges/reachability/meta-robots.js.map +0 -1
  241. package/dist/bridges/reachability/robots-parser.d.ts.map +0 -1
  242. package/dist/bridges/reachability/robots-parser.js.map +0 -1
  243. package/dist/bridges/reachability/robots-txt.d.ts.map +0 -1
  244. package/dist/bridges/reachability/robots-txt.js.map +0 -1
  245. package/dist/bridges/schema/descriptions.d.ts.map +0 -1
  246. package/dist/bridges/schema/descriptions.js.map +0 -1
  247. package/dist/bridges/schema/error-schemas.d.ts.map +0 -1
  248. package/dist/bridges/schema/error-schemas.js.map +0 -1
  249. package/dist/bridges/schema/index.d.ts.map +0 -1
  250. package/dist/bridges/schema/index.js.map +0 -1
  251. package/dist/bridges/schema/oas-types.d.ts.map +0 -1
  252. package/dist/bridges/schema/oas-types.js.map +0 -1
  253. package/dist/bridges/schema/operation-ids.d.ts.map +0 -1
  254. package/dist/bridges/schema/operation-ids.js.map +0 -1
  255. package/dist/bridges/schema/required-fields.d.ts.map +0 -1
  256. package/dist/bridges/schema/required-fields.js.map +0 -1
  257. package/dist/bridges/schema/schema-types.d.ts.map +0 -1
  258. package/dist/bridges/schema/schema-types.js.map +0 -1
  259. package/dist/bridges/separation/api-presence.d.ts.map +0 -1
  260. package/dist/bridges/separation/api-presence.js.map +0 -1
  261. package/dist/bridges/separation/developer-docs.d.ts.map +0 -1
  262. package/dist/bridges/separation/developer-docs.js.map +0 -1
  263. package/dist/bridges/separation/index.d.ts.map +0 -1
  264. package/dist/bridges/separation/index.js.map +0 -1
  265. package/dist/bridges/separation/sdk-references.d.ts.map +0 -1
  266. package/dist/bridges/separation/sdk-references.js.map +0 -1
  267. package/dist/bridges/separation/webhook-support.d.ts.map +0 -1
  268. package/dist/bridges/separation/webhook-support.js.map +0 -1
  269. package/dist/bridges/standards/a2a-agent-card.d.ts.map +0 -1
  270. package/dist/bridges/standards/a2a-agent-card.js.map +0 -1
  271. package/dist/bridges/standards/graphql.d.ts.map +0 -1
  272. package/dist/bridges/standards/graphql.js.map +0 -1
  273. package/dist/bridges/standards/index.d.ts.map +0 -1
  274. package/dist/bridges/standards/index.js.map +0 -1
  275. package/dist/bridges/standards/json-ld.d.ts.map +0 -1
  276. package/dist/bridges/standards/json-ld.js.map +0 -1
  277. package/dist/bridges/standards/llms-txt.d.ts.map +0 -1
  278. package/dist/bridges/standards/llms-txt.js.map +0 -1
  279. package/dist/bridges/standards/markdown-negotiation.d.ts.map +0 -1
  280. package/dist/bridges/standards/markdown-negotiation.js.map +0 -1
  281. package/dist/bridges/standards/mcp.d.ts.map +0 -1
  282. package/dist/bridges/standards/mcp.js.map +0 -1
  283. package/dist/bridges/standards/openapi.d.ts.map +0 -1
  284. package/dist/bridges/standards/openapi.js.map +0 -1
  285. package/dist/bridges/standards/schema-org.d.ts.map +0 -1
  286. package/dist/bridges/standards/schema-org.js.map +0 -1
  287. package/dist/bridges/standards/sitemap.d.ts.map +0 -1
  288. package/dist/bridges/standards/sitemap.js.map +0 -1
  289. package/dist/bridges/standards/well-known.d.ts.map +0 -1
  290. package/dist/bridges/standards/well-known.js.map +0 -1
  291. package/dist/cli/index.d.ts.map +0 -1
  292. package/dist/cli/index.js.map +0 -1
  293. package/dist/core/explanations.d.ts.map +0 -1
  294. package/dist/core/explanations.js.map +0 -1
  295. package/dist/core/index.d.ts.map +0 -1
  296. package/dist/core/index.js.map +0 -1
  297. package/dist/core/scan-options.d.ts.map +0 -1
  298. package/dist/core/scan-options.js.map +0 -1
  299. package/dist/core/scan.d.ts.map +0 -1
  300. package/dist/core/scan.js.map +0 -1
  301. package/dist/core/types.d.ts.map +0 -1
  302. package/dist/core/types.js.map +0 -1
  303. package/dist/core/version.d.ts.map +0 -1
  304. package/dist/core/version.js.map +0 -1
  305. package/dist/index.d.ts.map +0 -1
  306. package/dist/index.js.map +0 -1
  307. package/dist/render/colors.d.ts.map +0 -1
  308. package/dist/render/colors.js.map +0 -1
  309. package/dist/render/format-bridge.d.ts.map +0 -1
  310. package/dist/render/format-bridge.js.map +0 -1
  311. package/dist/render/format-scan.d.ts.map +0 -1
  312. package/dist/render/format-scan.js.map +0 -1
  313. package/dist/render/format-verbose.d.ts.map +0 -1
  314. package/dist/render/format-verbose.js.map +0 -1
  315. package/dist/render/index.d.ts.map +0 -1
  316. package/dist/render/index.js.map +0 -1
  317. package/dist/render/progress-bar.d.ts.map +0 -1
  318. package/dist/render/progress-bar.js.map +0 -1
  319. package/dist/render/symbols.d.ts.map +0 -1
  320. package/dist/render/symbols.js.map +0 -1
  321. package/dist/render/terminal-text.d.ts.map +0 -1
  322. package/dist/render/terminal-text.js.map +0 -1
  323. package/dist/utils/http-client.d.ts.map +0 -1
  324. package/dist/utils/http-client.js.map +0 -1
  325. package/dist/utils/index.d.ts.map +0 -1
  326. package/dist/utils/index.js.map +0 -1
  327. package/dist/utils/ssrf.d.ts.map +0 -1
  328. package/dist/utils/ssrf.js.map +0 -1
  329. package/dist/utils/url.d.ts.map +0 -1
  330. package/dist/utils/url.js.map +0 -1
@@ -0,0 +1,187 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readJsonFile } from '../utils/read-json-file.js';
3
+ export { readJsonFile } from '../utils/read-json-file.js';
4
+ import { terminalText } from '../utils/terminal-text.js';
5
+ import { containsRoute } from './excerpt.js';
6
+ import { normalize } from './document.js';
7
+ import { budgets } from './contracts.js';
8
+ import { canonicalOrigin, isCanonicalPath, isDocsPath } from './scope.js';
9
+ export function record(value, field) {
10
+ if (!value || typeof value !== 'object' || Array.isArray(value))
11
+ throw new Error(field + ' must be an object');
12
+ const prototype = Object.getPrototypeOf(value);
13
+ if (prototype !== null && prototype !== Object.prototype)
14
+ throw new Error(field + ' must be a JSON object');
15
+ return value;
16
+ }
17
+ export function fields(obj, field, required, optional = []) {
18
+ if (!required.every(key => Object.hasOwn(obj, key)))
19
+ throw new Error(field + ' is missing a required field');
20
+ const allowed = new Set([...required, ...optional]);
21
+ if (!Object.keys(obj).every(key => allowed.has(key)))
22
+ throw new Error(field + ' contains an unknown field');
23
+ }
24
+ export function isIdentifier(value) {
25
+ return typeof value === 'string' && value.length > 0 && !/[^a-z0-9-]/u.test(value);
26
+ }
27
+ function id(value, field) {
28
+ if (!isIdentifier(value))
29
+ throw new Error(field + ' must use lowercase letters, digits and hyphens');
30
+ return value;
31
+ }
32
+ export function nonempty(value, field) {
33
+ if (typeof value !== 'string' || !value.trim())
34
+ throw new Error(field + ' must be a nonempty string');
35
+ return value;
36
+ }
37
+ // Validate the usable text while preserving the author's original string for
38
+ // matching and fingerprinting. Removing controls can otherwise create an
39
+ // empty substring that matches every page.
40
+ function caseText(value, field, maxChars) {
41
+ const text = nonempty(value, field);
42
+ const visible = normalize(terminalText(text));
43
+ if (!/[^\s\p{Default_Ignorable_Code_Point}]/u.test(visible)) {
44
+ throw new Error(field + ' must contain visible text after normalization');
45
+ }
46
+ if (maxChars !== undefined && ([...text].length > maxChars || [...visible].length > maxChars)) {
47
+ throw new Error(field + ' exceeds ' + maxChars + ' characters');
48
+ }
49
+ return text;
50
+ }
51
+ export function isScalar(value) {
52
+ return value === null || typeof value === 'string' || typeof value === 'boolean' ||
53
+ (typeof value === 'number' && Number.isFinite(value));
54
+ }
55
+ function observableExcerpt(value, field) {
56
+ const text = caseText(value, field);
57
+ if (Buffer.byteLength(normalize(text)) > budgets.observationBytes) {
58
+ throw new Error(field + ' exceeds the document observation budget');
59
+ }
60
+ return text;
61
+ }
62
+ function pathList(value, docs) {
63
+ if (!Array.isArray(value) || !value.length || !value.every(isCanonicalPath) ||
64
+ (docs && !value.every(path => path.endsWith('/'))) || new Set(value).size !== value.length) {
65
+ throw new Error(docs ? 'docsPathPrefixes must list unique canonical prefixes ending in /' : 'apiPaths must list unique canonical paths');
66
+ }
67
+ return value;
68
+ }
69
+ function docsPath(value, prefixes, field) {
70
+ if (typeof value !== 'string' || !isDocsPath(value, prefixes))
71
+ throw new Error(field + ' must be a canonical path in documentation scope');
72
+ return value;
73
+ }
74
+ function target(value, api) {
75
+ const obj = record(value, 'target');
76
+ fields(obj, 'target', ['docsOrigin', 'releaseId', 'fixtureId', ...(api ? ['apiOrigin'] : [])]);
77
+ return {
78
+ docsOrigin: canonicalOrigin(obj.docsOrigin),
79
+ ...(api ? { apiOrigin: canonicalOrigin(obj.apiOrigin) } : {}),
80
+ releaseId: nonempty(obj.releaseId, 'releaseId'), fixtureId: nonempty(obj.fixtureId, 'fixtureId'),
81
+ };
82
+ }
83
+ const jsonTypes = ['null', 'boolean', 'number', 'string', 'array', 'object'];
84
+ function apiAssertion(value) {
85
+ const obj = record(value, 'assertion');
86
+ const assertionId = id(obj.id, 'assertion.id');
87
+ if (typeof obj.pointer !== 'string' || (obj.pointer && !obj.pointer.startsWith('/')) || /~(?![01])/u.test(obj.pointer)) {
88
+ throw new Error('assertion.pointer must be a valid JSON pointer');
89
+ }
90
+ const base = { id: assertionId, pointer: obj.pointer };
91
+ switch (obj.op) {
92
+ case 'exists':
93
+ fields(obj, 'exists assertion', ['id', 'pointer', 'op']);
94
+ return { ...base, op: 'exists' };
95
+ case 'equals':
96
+ fields(obj, 'equals assertion', ['id', 'pointer', 'op', 'value']);
97
+ if (!isScalar(obj.value))
98
+ throw new Error('equals requires a JSON scalar value');
99
+ return { ...base, op: 'equals', value: obj.value };
100
+ case 'type':
101
+ fields(obj, 'type assertion', ['id', 'pointer', 'op', 'type']);
102
+ if (!jsonTypes.some(t => t === obj.type))
103
+ throw new Error('type requires a JSON type name');
104
+ return { ...base, op: 'type', type: obj.type };
105
+ default:
106
+ throw new Error('unsupported assertion operator');
107
+ }
108
+ }
109
+ export function parseCase(value) {
110
+ const obj = record(value, 'case');
111
+ fields(obj, 'case', ['schemaVersion', 'id', 'kind', 'prompt', 'startPath', 'scope', 'targets', 'expect']);
112
+ if (obj.schemaVersion !== 1 || (obj.kind !== 'grounded_answer' && obj.kind !== 'api_read'))
113
+ throw new Error('unsupported case version or kind');
114
+ const api = obj.kind === 'api_read';
115
+ const scope = record(obj.scope, 'scope');
116
+ fields(scope, 'scope', api ? ['docsPathPrefixes', 'apiPaths'] : ['docsPathPrefixes']);
117
+ const docsPathPrefixes = pathList(scope.docsPathPrefixes, true);
118
+ const prompt = caseText(obj.prompt, 'prompt', 4000);
119
+ const targets = Object.create(null);
120
+ for (const [name, entry] of Object.entries(record(obj.targets, 'targets'))) {
121
+ targets[id(name, 'target name')] = target(entry, api);
122
+ }
123
+ if (!Object.keys(targets).length)
124
+ throw new Error('at least one target is required');
125
+ const common = { schemaVersion: 1, id: id(obj.id, 'case.id'), prompt, targets,
126
+ startPath: docsPath(obj.startPath, docsPathPrefixes, 'startPath') };
127
+ const expect = record(obj.expect, 'expect');
128
+ if (!api) {
129
+ const disposition = expect.disposition;
130
+ if (disposition !== 'answer' && disposition !== 'clarify' && disposition !== 'stop')
131
+ throw new Error('invalid expected disposition');
132
+ fields(expect, 'grounded expectation', ['disposition', 'sourcePath', 'excerpt', ...(disposition === 'answer' ? ['value'] : [])]);
133
+ const passage = { sourcePath: docsPath(expect.sourcePath, docsPathPrefixes, 'sourcePath'), excerpt: observableExcerpt(expect.excerpt, 'excerpt') };
134
+ return { ...common, kind: 'grounded_answer', scope: { docsPathPrefixes }, expect: disposition === 'answer' ?
135
+ { ...passage, disposition, value: caseText(expect.value, 'answer value') } : { ...passage, disposition } };
136
+ }
137
+ fields(expect, 'API expectation', ['apiPath', 'status', 'assertions'], ['requiredDocsPath', 'requiredDocsExcerpt']);
138
+ const apiPaths = pathList(scope.apiPaths, false);
139
+ if (typeof expect.apiPath !== 'string' || !apiPaths.includes(expect.apiPath))
140
+ throw new Error('expected apiPath is outside the exact API path list');
141
+ if (typeof expect.status !== 'number' || !Number.isInteger(expect.status) || expect.status < 200 || expect.status >= 300)
142
+ throw new Error('expected status must be a 2xx integer');
143
+ if (!Array.isArray(expect.assertions) || expect.assertions.length < 1 || expect.assertions.length > 10)
144
+ throw new Error('expected 1 to 10 API assertions');
145
+ const assertions = expect.assertions.map(apiAssertion);
146
+ const conditions = assertions.map(({ id: _id, ...condition }) => JSON.stringify(condition));
147
+ if (new Set(assertions.map(a => a.id)).size !== assertions.length || new Set(conditions).size !== assertions.length)
148
+ throw new Error('duplicate API assertion or id');
149
+ const requiredDocsPath = Object.hasOwn(expect, 'requiredDocsPath')
150
+ ? docsPath(expect.requiredDocsPath, docsPathPrefixes, 'requiredDocsPath') : undefined;
151
+ let requiredDocsExcerpt;
152
+ if (Object.hasOwn(expect, 'requiredDocsExcerpt')) {
153
+ requiredDocsExcerpt = observableExcerpt(expect.requiredDocsExcerpt, 'requiredDocsExcerpt');
154
+ if (!requiredDocsPath || !containsRoute(normalize(requiredDocsExcerpt), expect.apiPath)) {
155
+ throw new Error('requiredDocsExcerpt requires requiredDocsPath and must contain the complete expected API path');
156
+ }
157
+ }
158
+ return { ...common, kind: 'api_read', scope: { docsPathPrefixes, apiPaths },
159
+ expect: { apiPath: expect.apiPath, status: expect.status, assertions, ...(requiredDocsPath && { requiredDocsPath }), ...(requiredDocsExcerpt && { requiredDocsExcerpt }) } };
160
+ }
161
+ export function selectTarget(c, name) {
162
+ if (!Object.hasOwn(c.targets, name))
163
+ throw new Error('unknown target name');
164
+ return c.targets[name];
165
+ }
166
+ /** Emit sorted object keys directly, including integer-like keys that JSON.stringify
167
+ * would otherwise enumerate in numeric order. Array order stays significant. */
168
+ export function canonicalJson(value) {
169
+ if (Array.isArray(value))
170
+ return '[' + value.map(canonicalJson).join(',') + ']';
171
+ if (value && typeof value === 'object') {
172
+ const obj = value;
173
+ return '{' + Object.keys(obj).sort().map(key => JSON.stringify(key) + ':' + canonicalJson(obj[key])).join(',') + '}';
174
+ }
175
+ return JSON.stringify(value);
176
+ }
177
+ /** SHA-256 over the UTF-8 bytes of JSON.stringify(s), including its quotes and escapes. */
178
+ export function stringDigest(s) {
179
+ return createHash('sha256').update(JSON.stringify(s), 'utf8').digest('hex');
180
+ }
181
+ export function caseFingerprint(c) {
182
+ const { targets: _targets, ...semantics } = c;
183
+ return createHash('sha256').update(canonicalJson(semantics), 'utf8').digest('hex');
184
+ }
185
+ export async function readCase(path) {
186
+ return parseCase(await readJsonFile(path, 128 * 1024));
187
+ }
@@ -0,0 +1,14 @@
1
+ interface Options {
2
+ json?: boolean;
3
+ kind?: string;
4
+ provider?: string;
5
+ model?: string;
6
+ probe?: boolean;
7
+ repeat?: string;
8
+ target?: string;
9
+ gate?: boolean;
10
+ verbose?: boolean;
11
+ }
12
+ export declare function writeJourneyError(code: string, message: string, jsonMode: boolean, exit?: number): void;
13
+ export declare function executeJourney(name: string, args: string[], opts: Options): Promise<void>;
14
+ export {};
@@ -0,0 +1,226 @@
1
+ import { writeFile } from "node:fs/promises";
2
+ import { terminalText } from "../utils/terminal-text.js";
3
+ import { caseFingerprint, readCase, selectTarget } from "./case.js";
4
+ import { compareValidatedRuns } from "./compare.js";
5
+ import { JourneyFault } from "./contracts.js";
6
+ import { decisionRepair } from "./decision.js";
7
+ import { caseTemplate, runDemo } from "./demo.js";
8
+ import { createProvider, doctor, redactCredential } from "./providers.js";
9
+ import { readRunReport } from "./report-validation.js";
10
+ import { runJourney } from "./runner.js";
11
+ import { createProductTransport } from "./transport.js";
12
+ function safe(text) {
13
+ return terminalText(redactCredential(text));
14
+ }
15
+ function json(value) {
16
+ // Preserve opaque report identities. Escaping the remaining terminal-control
17
+ // code points keeps the JSON transport safe without changing decoded values.
18
+ return JSON.stringify(value, (_key, item) => typeof item === "string" ? redactCredential(item) : item)
19
+ .replace(/[\u007f-\u009f\p{Bidi_Control}\u2028\u2029]/gu, char => "\\u" + char.charCodeAt(0).toString(16).padStart(4, "0"));
20
+ }
21
+ function emit(report, human, jsonMode) {
22
+ process.stdout.write((jsonMode ? json(report) : human) + "\n");
23
+ }
24
+ export function writeJourneyError(code, message, jsonMode, exit = 2) {
25
+ const diagnostic = safe(message);
26
+ if (jsonMode)
27
+ emit({ schemaVersion: 1, kind: "journey_error", code, message: diagnostic }, "", true);
28
+ process.stderr.write(safe(code) + ": " + diagnostic + "\n");
29
+ process.exitCode = exit;
30
+ }
31
+ function eventLine(event) {
32
+ // Old reports can carry a generic invalid decision without a recorded reason.
33
+ const preview = event.code === "INVALID_DECISION" && !Object.hasOwn(decisionRepair, event.preview ?? "")
34
+ ? "" : event.preview;
35
+ return [event.id, event.kind, event.path, event.status, event.code, preview, event.linksTruncated ? "Links truncated" : undefined]
36
+ .filter(value => value !== undefined && value !== "").map(value => safe(String(value))).join(" ");
37
+ }
38
+ function assessmentLines(result, events, verbose) {
39
+ const selected = verbose ? result.assertions
40
+ : result.assertions.filter(check => check.verdict !== "pass" && check.verdict === result.verdict).slice(0, 1);
41
+ const lines = [];
42
+ for (const check of selected) {
43
+ const reason = check.code ? ` (${safe(check.code)})` : "";
44
+ lines.push(` ${safe(check.id)} ${check.verdict}${reason}: expected ${json(check.expected)}, observed ${json(check.observed)}`);
45
+ if ("coverage" in check)
46
+ lines.push(" Coverage: " + safe(String(check.coverage)));
47
+ if (verbose && check.evidenceIds.length)
48
+ lines.push(" Events: " + check.evidenceIds.map(safe).join(", "));
49
+ if (!verbose) {
50
+ for (const event of events.filter(e => check.evidenceIds.includes(e.id)))
51
+ lines.push(" " + eventLine(event));
52
+ }
53
+ if (verbose && check.verdict !== "pass" && check.id === "api.docs_excerpt")
54
+ lines.push(" Verify that the cited quickstart visibly names the exact API route before the request.");
55
+ }
56
+ if (verbose) {
57
+ lines.push(" Event trace");
58
+ for (const event of events) {
59
+ lines.push(" " + eventLine(event));
60
+ if (event.code === "INVALID_DECISION" && event.preview && Object.hasOwn(decisionRepair, event.preview)) {
61
+ lines.push(" " + decisionRepair[event.preview]);
62
+ }
63
+ }
64
+ }
65
+ return lines;
66
+ }
67
+ function renderRun(run, verbose = false, inspecting = false) {
68
+ const { pass, fail, inconclusive, notStarted } = run.counts;
69
+ const counts = `${pass} pass, ${fail} fail, ${inconclusive} inconclusive, ${notStarted} not started`;
70
+ const title = `${safe(run.caseId)} / ${safe(run.target.name)}: ${counts} (${run.status})`;
71
+ const lines = [run.mode === "scripted" ? "Scripted fixture | " + title : title];
72
+ for (const attempt of run.attempts) {
73
+ const interrupted = attempt.events.some(event => event.kind === "interruption") ? " (interrupted)" : "";
74
+ lines.push(` Attempt ${attempt.ordinal}: ${attempt.verdict}${interrupted}`, ...assessmentLines(attempt, attempt.events, verbose));
75
+ if (!verbose && attempt.verdict !== "pass" && run.control?.verdict === "pass") {
76
+ const last = attempt.events.filter(e => e.kind !== "finish").at(-1);
77
+ if (last)
78
+ lines.push(` Last observed step: ${safe(last.id)} ${last.kind} ${safe(last.path ?? "")}`.trimEnd());
79
+ }
80
+ }
81
+ if (run.control)
82
+ lines.push(` Direct API control: ${run.control.verdict}`, ...assessmentLines(run.control, run.control.events, verbose));
83
+ else if (inspecting)
84
+ lines.push(run.caseKind === "api_read" ? " Direct API control: unstarted" : " Direct API control: not applicable");
85
+ return lines.join("\n");
86
+ }
87
+ function filenameArgument(path) {
88
+ const value = safe(path);
89
+ if (/^[a-zA-Z0-9_./-]+$/.test(value))
90
+ return value;
91
+ return "'" + value.replaceAll("'", process.platform === "win32" ? "''" : "'\\''") + "'";
92
+ }
93
+ async function live(path, opts) {
94
+ const repeat = opts.repeat ?? "1";
95
+ if (!/^(?:[1-9]|10)$/.test(repeat))
96
+ throw new Error("--repeat must be an integer from 1 through 10");
97
+ const c = await readCase(path).catch(error => {
98
+ writeJourneyError("INVALID_CASE", error instanceof Error ? error.message : "Invalid case", !!opts.json);
99
+ return null;
100
+ });
101
+ if (!c)
102
+ return;
103
+ const target = opts.target;
104
+ selectTarget(c, target);
105
+ const cancel = new AbortController();
106
+ let interruption = 130;
107
+ const interrupt = (signal) => {
108
+ interruption = signal === "SIGTERM" ? 143 : 130;
109
+ if (cancel.signal.aborted)
110
+ process.exit(interruption);
111
+ cancel.abort();
112
+ };
113
+ process.on("SIGINT", interrupt);
114
+ process.on("SIGTERM", interrupt);
115
+ try {
116
+ const backend = await createProvider(opts.provider, opts.model, cancel.signal);
117
+ const run = await runJourney(c, {
118
+ target, repeat: Number(repeat), mode: "live", backend, transport: createProductTransport, signal: cancel.signal
119
+ });
120
+ emit(run, renderRun(run), opts.json);
121
+ if (run.status === "cancelled")
122
+ process.exitCode = interruption;
123
+ else if (!(run.counts.pass + run.counts.fail) && (!run.control || run.control.verdict === "inconclusive"))
124
+ process.exitCode = 2;
125
+ }
126
+ catch (error) {
127
+ if (!cancel.signal.aborted)
128
+ throw error;
129
+ writeJourneyError("CANCELLED", "Interrupted during setup", !!opts.json, interruption);
130
+ }
131
+ finally {
132
+ process.removeListener("SIGINT", interrupt);
133
+ process.removeListener("SIGTERM", interrupt);
134
+ }
135
+ }
136
+ export async function executeJourney(name, args, opts) {
137
+ let code = "INVALID_ARGUMENT";
138
+ try {
139
+ switch (name) {
140
+ case "demo": {
141
+ const demo = await runDemo();
142
+ emit(demo, demo.runs.map(run => renderRun(run)).join("\n\n"), opts.json);
143
+ if (!demo.ok)
144
+ process.exitCode = 2;
145
+ break;
146
+ }
147
+ case "init": {
148
+ if (opts.kind !== "api_read" && opts.kind !== "grounded_answer")
149
+ throw new Error("--kind must be grounded_answer or api_read");
150
+ const template = caseTemplate(opts.kind);
151
+ code = "CREATE_CASE";
152
+ await writeFile(args[0], JSON.stringify(template, null, 2) + "\n", { flag: "wx" });
153
+ emit({ schemaVersion: 1, kind: "journey_init", path: args[0], caseKind: opts.kind }, `Created ${safe(args[0])}. Edit its targets, then run milieu journey validate ${args[0].startsWith("-") ? "-- " : ""}${filenameArgument(args[0])}`, opts.json);
154
+ break;
155
+ }
156
+ case "validate": {
157
+ code = "INVALID_CASE";
158
+ const c = await readCase(args[0]);
159
+ const targets = Object.keys(c.targets);
160
+ emit({ schemaVersion: 1, kind: "journey_validation", caseId: c.id, caseKind: c.kind, caseFingerprint: caseFingerprint(c), targets }, `Valid ${safe(c.kind)} case ${safe(c.id)}. Targets: ${targets.map(safe).join(", ")}`, opts.json);
161
+ break;
162
+ }
163
+ case "doctor": {
164
+ code = "PROVIDER_SETUP";
165
+ const result = await doctor(opts);
166
+ emit(result, "Journey provider setup\n" + Object.entries(result).filter(([k]) => !["schemaVersion", "kind"].includes(k))
167
+ .map(([k, v]) => " " + safe(k) + ": " + (typeof v === "string" ? safe(v) : json(v))).join("\n"), opts.json);
168
+ break;
169
+ }
170
+ case "run":
171
+ await live(args[0], opts);
172
+ break;
173
+ case "inspect": {
174
+ code = "INVALID_REPORT";
175
+ const run = await readRunReport(args[0]);
176
+ emit(run, renderRun(run, !!opts.verbose, true), opts.json);
177
+ break;
178
+ }
179
+ case "compare": {
180
+ code = "INVALID_REPORT";
181
+ const [before, after] = await Promise.all(args.map(async (path, index) => {
182
+ try {
183
+ return await readRunReport(path);
184
+ }
185
+ catch (error) {
186
+ const role = index === 0 ? "baseline" : "candidate";
187
+ throw new Error(role + " report: " + (error instanceof Error ? error.message : "read failed"));
188
+ }
189
+ }));
190
+ const { report, exitCode } = compareValidatedRuns(before, after, opts.gate);
191
+ const actor = (run) => `${run.counts.pass}/${run.counts.planned} passed, ${run.counts.inconclusive} inconclusive`;
192
+ const lines = [`Actor: ${actor(before)} -> ${actor(after)}`];
193
+ if (report.passRateDeltaPercentagePoints !== null) {
194
+ const delta = report.passRateDeltaPercentagePoints;
195
+ lines.push(`Actor pass rate change: ${delta > 0 ? "+" : ""}${delta} percentage points`);
196
+ }
197
+ if (!report.compatible)
198
+ lines.push("Incompatible: " + report.mismatches.map(safe).join(", "));
199
+ const matchedFailures = report.controlChange === "unchanged" && after.control?.verdict === "fail";
200
+ lines.push(`Direct API control: ${before.control?.verdict ?? "unavailable"} -> ${after.control?.verdict ?? "unavailable"} (${report.controlChange}${matchedFailures ? ", no new regression" : ""})`);
201
+ const gate = exitCode === 2 ? "ineligible" : exitCode === 1 ? "regression" : "no new regression";
202
+ if (opts.gate)
203
+ lines.push("Gate: " + gate);
204
+ emit(opts.gate ? { ...report, gate } : report, [lines.join("\n"), renderRun(before), renderRun(after)].join("\n\n"), opts.json);
205
+ if (exitCode)
206
+ process.exitCode = exitCode;
207
+ break;
208
+ }
209
+ }
210
+ }
211
+ catch (error) {
212
+ const hints = {
213
+ MODEL_AUTH: "Set OPENAI_API_KEY in the invoking environment and check project access.",
214
+ MODEL_NOT_INSTALLED: "Run ollama list and pass an installed model name to --model.",
215
+ MODEL_UNAVAILABLE: "Check the selected provider is reachable, then run journey doctor with --provider and --model.",
216
+ INVALID_PROVIDER: "Choose ollama or openai for --provider.",
217
+ PROVIDER_REQUIRED: "Supply --provider ollama or --provider openai.",
218
+ MODEL_REQUIRED: "Supply --model with --probe.",
219
+ INVALID_MODEL: "Provide the provider's model identifier.",
220
+ PROBE_FAILED: "The model did not return the requested structured decision."
221
+ };
222
+ const message = error instanceof JourneyFault ? hints[error.code] ?? error.code :
223
+ error instanceof Error ? error.message : "Journey command failed";
224
+ writeJourneyError(error instanceof JourneyFault ? error.code : code, message, !!opts.json);
225
+ }
226
+ }
@@ -0,0 +1,43 @@
1
+ import type { Control, RunReport } from './contracts.js';
2
+ type ControlChange = 'regression' | 'recovery' | 'unchanged' | 'changed-failure' | 'unavailable';
3
+ declare function side(run: RunReport): {
4
+ runId: string;
5
+ status: "cancelled" | "completed";
6
+ counts: {
7
+ planned: number;
8
+ pass: number;
9
+ fail: number;
10
+ inconclusive: number;
11
+ notStarted: number;
12
+ };
13
+ target: import("./case.js").JourneyTarget & {
14
+ name: string;
15
+ };
16
+ attempts: {
17
+ assertions: import("./contracts.js").Assertion[];
18
+ events: import("./contracts.js").EvidenceEvent[];
19
+ code?: string | undefined;
20
+ ordinal: number;
21
+ verdict: import("./contracts.js").Verdict;
22
+ }[];
23
+ control: Control | null;
24
+ };
25
+ export interface JourneyComparison {
26
+ schemaVersion: 1;
27
+ kind: 'journey_comparison';
28
+ compatible: boolean;
29
+ mismatches: string[];
30
+ baseline: ReturnType<typeof side>;
31
+ candidate: ReturnType<typeof side>;
32
+ controlChange: ControlChange;
33
+ passRateDeltaPercentagePoints: number | null;
34
+ }
35
+ export declare function compareRuns(before: unknown, after: unknown, gate?: boolean): {
36
+ report: JourneyComparison;
37
+ exitCode: 0 | 1 | 2;
38
+ };
39
+ export declare function compareValidatedRuns(a: RunReport, b: RunReport, gate?: boolean): {
40
+ report: JourneyComparison;
41
+ exitCode: 0 | 1 | 2;
42
+ };
43
+ export {};
@@ -0,0 +1,83 @@
1
+ import { canonicalJson } from './case.js';
2
+ import { validateRunReport } from './report-validation.js';
3
+ function stableModel(model) {
4
+ return model.resolved.length === 1 && (model.provider !== 'ollama' || model.digest !== null);
5
+ }
6
+ /** A status or JSON failure short-circuits later checks. Verify the observed
7
+ * part of the control contract, including author check IDs, values and order. */
8
+ function matchedControls(left, right) {
9
+ if (left.events[0].path !== right.events[0].path)
10
+ return false;
11
+ const overlap = Math.min(left.assertions.length, right.assertions.length);
12
+ for (let i = 0; i < overlap; i++) {
13
+ const before = left.assertions[i];
14
+ const after = right.assertions[i];
15
+ if (before.id !== after.id || canonicalJson(before.expected) !== canonicalJson(after.expected))
16
+ return false;
17
+ }
18
+ return true;
19
+ }
20
+ function compatibility(a, b) {
21
+ const differences = [];
22
+ if (a.schemaVersion !== b.schemaVersion)
23
+ differences.push('run schema version');
24
+ if (a.status !== 'completed' || b.status !== 'completed')
25
+ differences.push('cancelled run');
26
+ if (a.mode !== b.mode)
27
+ differences.push('mode');
28
+ if (a.caseKind !== b.caseKind || a.caseId !== b.caseId || a.caseFingerprint !== b.caseFingerprint)
29
+ differences.push('case identity or fingerprint');
30
+ if (canonicalJson(a.requirements) !== canonicalJson(b.requirements))
31
+ differences.push('required evidence paths or assertions');
32
+ if (a.target.fixtureId !== b.target.fixtureId)
33
+ differences.push('fixture ID');
34
+ if (a.runner.version !== b.runner.version)
35
+ differences.push('CLI version');
36
+ if (a.runner.policyVersion !== b.runner.policyVersion)
37
+ differences.push('policy version');
38
+ if (canonicalJson(a.runner.budgets) !== canonicalJson(b.runner.budgets))
39
+ differences.push('effective budgets');
40
+ if (!stableModel(a.model) || !stableModel(b.model))
41
+ differences.push('unresolved or changing model identity');
42
+ else if (canonicalJson(a.model) !== canonicalJson(b.model))
43
+ differences.push('model identity');
44
+ if (a.control && b.control && !matchedControls(a.control, b.control))
45
+ differences.push('direct control path or assertions');
46
+ return differences;
47
+ }
48
+ function controlChange(before, after) {
49
+ if (!before || !after || before.verdict === 'inconclusive' || after.verdict === 'inconclusive')
50
+ return 'unavailable';
51
+ if (before.verdict === 'fail' && after.verdict === 'fail') {
52
+ const prior = new Map(before.assertions.map(a => [a.id, a.verdict]));
53
+ const failures = after.assertions.filter(a => a.verdict === 'fail');
54
+ if (failures.some(a => prior.get(a.id) === 'pass'))
55
+ return 'regression';
56
+ const failureIds = (control) => control.assertions.filter(a => a.verdict === 'fail').map(a => [a.id, a.code]);
57
+ if (canonicalJson(failureIds(before)) !== canonicalJson(failureIds(after)))
58
+ return 'changed-failure';
59
+ }
60
+ if (before.verdict === after.verdict)
61
+ return 'unchanged';
62
+ return before.verdict === 'pass' ? 'regression' : 'recovery';
63
+ }
64
+ function side(run) {
65
+ return { runId: run.runId, status: run.status, counts: run.counts, target: run.target,
66
+ attempts: run.attempts.map(({ ordinal, verdict, assertions, events, code }) => ({ ordinal, verdict, ...(code && { code }), assertions, events })), control: run.control };
67
+ }
68
+ export function compareRuns(before, after, gate = false) {
69
+ return compareValidatedRuns(validateRunReport(before), validateRunReport(after), gate);
70
+ }
71
+ export function compareValidatedRuns(a, b, gate = false) {
72
+ const mismatches = compatibility(a, b);
73
+ const compatible = !mismatches.length;
74
+ const change = compatible ? controlChange(a.control, b.control) : 'unavailable';
75
+ const report = {
76
+ schemaVersion: 1, kind: 'journey_comparison', compatible, mismatches,
77
+ baseline: side(a), candidate: side(b), controlChange: change,
78
+ passRateDeltaPercentagePoints: compatible && a.counts.planned === b.counts.planned ?
79
+ Number(((b.counts.pass - a.counts.pass) * 100 / a.counts.planned).toFixed(2)) : null,
80
+ };
81
+ const exitCode = !compatible || (gate && change === 'unavailable') ? 2 : (gate && change === 'regression') ? 1 : 0;
82
+ return { report, exitCode };
83
+ }