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,321 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { getVersion } from "../core/version.js";
3
+ import { AnalysisLimitError, runAnalysisWorker } from "../utils/analysis-worker.js";
4
+ import { terminalText } from "../utils/terminal-text.js";
5
+ import { caseFingerprint, selectTarget, stringDigest } from "./case.js";
6
+ import { budgets, redactLiteral, JourneyFault, } from "./contracts.js";
7
+ import { actorInstructions, apiNavigationInstructions, decisionRepair, parseDecision } from "./decision.js";
8
+ import { nameFormatHint, requestedNameType } from "./name-guidance.js";
9
+ import { normalize } from "./document.js";
10
+ import { isCanonicalPath, isDocsPath } from "./scope.js";
11
+ import { boundAssertion, operational, verifyApi, verifyFinish } from "./verify.js";
12
+ const elapsed = (start) => Math.max(0, Math.floor(performance.now() - start));
13
+ const faultCode = (err) => err instanceof JourneyFault && /^[A-Z_]{1,64}$/.test(err.code) ? err.code : "INTERNAL_ERROR";
14
+ async function limited(parent, ms, timeoutCode, op) {
15
+ if (parent.aborted)
16
+ throw new JourneyFault("CANCELLED");
17
+ if (ms <= 0)
18
+ throw new JourneyFault("BUDGET_EXHAUSTED");
19
+ const timeout = new AbortController();
20
+ const signal = AbortSignal.any([parent, timeout.signal]);
21
+ const timer = setTimeout(() => timeout.abort(), ms);
22
+ const fail = () => new JourneyFault(parent.aborted ? "CANCELLED" : timeoutCode);
23
+ let cancel = () => { };
24
+ try {
25
+ const interrupted = new Promise((_, reject) => {
26
+ cancel = () => reject(fail());
27
+ signal.addEventListener("abort", cancel, { once: true });
28
+ });
29
+ const result = await Promise.race([op(signal), interrupted]);
30
+ if (signal.aborted)
31
+ throw fail();
32
+ return result;
33
+ }
34
+ finally {
35
+ clearTimeout(timer);
36
+ signal.removeEventListener("abort", cancel);
37
+ }
38
+ }
39
+ function documentationLinkHint(rejected, links) {
40
+ if (!rejected || typeof rejected !== "object" ||
41
+ !("action" in rejected) || rejected.action !== "get_api" || !("path" in rejected))
42
+ return "";
43
+ for (const [linkId, path] of links) {
44
+ if (path === rejected.path) {
45
+ return (" Your get_api path matches a documentation link already shown on the page. " +
46
+ `To read that selected page, use open_link with linkId "${linkId}", path null, and evidenceIds []. ` +
47
+ "Use get_api for an endpoint documented by the product.");
48
+ }
49
+ }
50
+ return "";
51
+ }
52
+ class Execution {
53
+ prefix;
54
+ c;
55
+ target;
56
+ transport;
57
+ signal;
58
+ clean;
59
+ credential;
60
+ role;
61
+ events = [];
62
+ observations = [];
63
+ links = new Map();
64
+ start = performance.now();
65
+ gets = 0;
66
+ constructor(prefix, c, target, transport, signal, clean, credential, role = "actor") {
67
+ this.prefix = prefix;
68
+ this.c = c;
69
+ this.target = target;
70
+ this.transport = transport;
71
+ this.signal = signal;
72
+ this.clean = clean;
73
+ this.credential = credential;
74
+ this.role = role;
75
+ }
76
+ event(detail) {
77
+ const event = {
78
+ ...detail,
79
+ id: this.prefix + "-e" + (this.events.length + 1),
80
+ atMs: elapsed(this.start),
81
+ };
82
+ this.events.push(event);
83
+ return event;
84
+ }
85
+ async response(url) {
86
+ if (this.clean(url.href) !== url.href)
87
+ throw new JourneyFault("SCOPE_DENIED");
88
+ if (++this.gets > (this.role === "control" ? 1 : budgets.productGets))
89
+ throw new JourneyFault("BUDGET_EXHAUSTED");
90
+ const remaining = budgets.attemptMs - elapsed(this.start);
91
+ return limited(this.signal, Math.min(budgets.productMs, remaining), remaining <= budgets.productMs ? "BUDGET_EXHAUSTED" : "TARGET_TIMEOUT", (s) => this.transport(url, s));
92
+ }
93
+ async read(kind, path) {
94
+ const c = this.c;
95
+ if (!isCanonicalPath(path) ||
96
+ (kind === "page"
97
+ ? !isDocsPath(path, c.scope.docsPathPrefixes)
98
+ : c.kind !== "api_read" || !c.scope.apiPaths.includes(path)) ||
99
+ this.clean(path) !== path) {
100
+ return this.event({ kind: "denied", code: "SCOPE_DENIED" });
101
+ }
102
+ const url = new URL(path, kind === "page" ? this.target.docsOrigin : this.target.apiOrigin);
103
+ const event = this.event({ kind, path });
104
+ const obs = { event };
105
+ this.observations.push(obs);
106
+ try {
107
+ const r = await this.response(url);
108
+ if (r.status !== null)
109
+ event.status = r.status;
110
+ if (r.code)
111
+ throw new JourneyFault(r.code);
112
+ if (r.status === null)
113
+ throw new JourneyFault("TARGET_UNAVAILABLE");
114
+ if (r.status >= 300 && r.status < 400)
115
+ throw new JourneyFault("REDIRECT_BLOCKED");
116
+ if (r.status === 429)
117
+ throw new JourneyFault("TARGET_RATE_LIMIT");
118
+ if (r.status < 200 || r.status >= 300)
119
+ return event;
120
+ if (r.body.byteLength > budgets.responseBytes)
121
+ throw new JourneyFault("INCOMPLETE_BODY");
122
+ const input = {
123
+ body: r.body, mediaType: r.mediaType, event, url: url.href, c, role: this.role,
124
+ prefix: this.prefix, linkCount: this.links.size, credential: this.credential,
125
+ };
126
+ const result = await limited(this.signal, budgets.attemptMs - elapsed(this.start), "BUDGET_EXHAUSTED", (signal) => runAnalysisWorker(new URL("./body-worker.js", import.meta.url), input, { signal, timeoutMs: 5_000 }));
127
+ if ("fault" in result)
128
+ throw new JourneyFault(result.fault);
129
+ Object.assign(event, result.event);
130
+ Object.assign(obs, result.observation);
131
+ for (const { linkId, path } of result.links ?? [])
132
+ this.links.set(linkId, path);
133
+ const feedback = { ...event, ...result.feedback };
134
+ const required = c.kind === "api_read" ? c.expect.requiredDocsPath : c.expect.sourcePath;
135
+ if (kind === "page" && required)
136
+ event.requiredLink = obs.offeredPath ? "offered" : obs.hiddenPath ? "hidden" : "absent";
137
+ return feedback;
138
+ }
139
+ catch (err) {
140
+ event.code = err instanceof AnalysisLimitError ? (kind === "api" ? "JSON_LIMIT" : "DOCUMENT_LIMIT") : faultCode(err);
141
+ if (this.signal.aborted || (this.role === "actor" && event.code === "BUDGET_EXHAUSTED"))
142
+ throw err;
143
+ return event;
144
+ }
145
+ }
146
+ }
147
+ async function attempt(c, ordinal, io, backend, signal, clean) {
148
+ const result = {
149
+ ordinal,
150
+ events: io.events,
151
+ verdict: "inconclusive",
152
+ assertions: [],
153
+ durationMs: 0,
154
+ disposition: null,
155
+ answer: null,
156
+ };
157
+ let corrected = false;
158
+ try {
159
+ const task = clean(c.prompt);
160
+ const type = c.kind === "grounded_answer" ? requestedNameType(task) : undefined;
161
+ const instructions = c.kind === "api_read" ? actorInstructions + "\n" + apiNavigationInstructions : actorInstructions;
162
+ const messages = [
163
+ { role: "system", content: instructions },
164
+ { role: "user", content: task },
165
+ ];
166
+ let feedback = await io.read("page", c.startPath);
167
+ for (let i = 0; i < budgets.modelCalls; i++) {
168
+ if (type && "kind" in feedback && feedback.kind === "page") {
169
+ const hint = "text" in feedback && typeof feedback.text === "string" ? nameFormatHint(type, feedback.text) : "";
170
+ messages[0] = { role: "system", content: hint ? instructions + "\n" + hint : instructions };
171
+ }
172
+ messages.push({ role: "user", content: JSON.stringify(feedback) });
173
+ if (Buffer.byteLength(JSON.stringify(messages)) > budgets.historyBytes)
174
+ throw new JourneyFault("HISTORY_LIMIT");
175
+ const rest = budgets.attemptMs - elapsed(io.start);
176
+ const raw = await limited(signal, Math.min(budgets.modelMs, rest), rest <= budgets.modelMs ? "BUDGET_EXHAUSTED" : "MODEL_TIMEOUT", (s) => backend.decide(messages, s));
177
+ const d = parseDecision(raw);
178
+ if (typeof d === "string") {
179
+ const event = io.event({ kind: "error", code: "INVALID_DECISION", preview: d });
180
+ if (corrected) {
181
+ Object.assign(result, operational("INVALID_DECISION", event.id));
182
+ return result;
183
+ }
184
+ corrected = true;
185
+ feedback = {
186
+ kind: "decision_correction",
187
+ instruction: "The previous decision was invalid. " +
188
+ decisionRepair[d] +
189
+ " Submit one corrected decision using the observations already provided." +
190
+ (d === "NAVIGATION_EVIDENCE_IDS" ? documentationLinkHint(raw, io.links) : ""),
191
+ };
192
+ continue;
193
+ }
194
+ if (d.action === "finish") {
195
+ result.disposition = d.disposition;
196
+ result.answer = d.answer === null ? null : normalize(clean(d.answer));
197
+ const finish = io.event({ kind: "finish" });
198
+ Object.assign(result, verifyFinish(c, d, io.observations, finish.id, result.answer));
199
+ return result;
200
+ }
201
+ // Scope is checked before constructing any request from the model decision.
202
+ if (d.action === "get_api")
203
+ feedback = await io.read("api", d.path);
204
+ else {
205
+ const path = io.links.get(d.linkId);
206
+ feedback = path ? await io.read("page", path) : io.event({ kind: "denied", code: "SCOPE_DENIED" });
207
+ }
208
+ messages.push({
209
+ role: "assistant",
210
+ content: JSON.stringify(d, (_key, v) => (typeof v === "string" ? clean(v) : v)),
211
+ });
212
+ }
213
+ throw new JourneyFault("BUDGET_EXHAUSTED");
214
+ }
215
+ catch (err) {
216
+ const code = signal.aborted ? "CANCELLED" : faultCode(err);
217
+ const event = io.event({ kind: signal.aborted ? "interruption" : "error", code });
218
+ Object.assign(result, operational(code, event.id));
219
+ return result;
220
+ }
221
+ finally {
222
+ result.durationMs = elapsed(io.start);
223
+ }
224
+ }
225
+ export async function runJourney(c, options) {
226
+ const { mode, repeat, backend } = options;
227
+ if (!Number.isInteger(repeat) || repeat < 1 || repeat > 10)
228
+ throw new JourneyFault("INVALID_REPEAT");
229
+ const target = selectTarget(c, options.target);
230
+ const signal = options.signal ?? new AbortController().signal;
231
+ const credential = backend.credentialForRedaction?.();
232
+ const clean = (s) => terminalText(redactLiteral(s, credential));
233
+ // A case containing a configured credential cannot be safely used as a target
234
+ // or rendered with faithful case identifiers. Reject it before any product GET.
235
+ if (credential) {
236
+ JSON.stringify(c, (key, value) => {
237
+ if (key.includes(credential) || (typeof value === "string" && value.includes(credential)))
238
+ throw new JourneyFault("CASE_CONTAINS_CREDENTIAL");
239
+ return value;
240
+ });
241
+ }
242
+ const start = performance.now();
243
+ const report = {
244
+ schemaVersion: c.kind === "grounded_answer" ? 3 : c.expect.requiredDocsExcerpt ? 2 : 1,
245
+ kind: "journey_run",
246
+ mode,
247
+ runId: randomUUID(),
248
+ startedAt: new Date().toISOString(),
249
+ status: "completed",
250
+ durationMs: 0,
251
+ caseId: c.id,
252
+ caseKind: c.kind,
253
+ caseFingerprint: caseFingerprint(c),
254
+ requirements: c.kind === "api_read"
255
+ ? {
256
+ apiPath: c.expect.apiPath,
257
+ requiredDocsPath: c.expect.requiredDocsPath ?? null,
258
+ ...(c.expect.requiredDocsExcerpt && {
259
+ requiredDocsExcerptDigest: stringDigest(normalize(c.expect.requiredDocsExcerpt)),
260
+ }),
261
+ assertionIds: c.expect.assertions.map((a) => a.id),
262
+ }
263
+ : {
264
+ sourcePath: c.expect.sourcePath,
265
+ disposition: c.expect.disposition,
266
+ excerptDigest: stringDigest(normalize(c.expect.excerpt)),
267
+ ...(c.expect.disposition === "answer" && { answerDigest: stringDigest(normalize(c.expect.value)) }),
268
+ },
269
+ target: { ...target, name: options.target },
270
+ runner: { version: getVersion(), policyVersion: "journeys-8", budgets },
271
+ model: backend.identity,
272
+ attempts: [],
273
+ counts: { planned: repeat, pass: 0, fail: 0, inconclusive: 0, notStarted: repeat },
274
+ control: null,
275
+ };
276
+ for (let n = 1; n <= repeat && !signal.aborted; n++) {
277
+ const io = new Execution("a" + n, c, target, options.transport(budgets.productGets), signal, clean, credential);
278
+ report.attempts.push(await attempt(c, n, io, backend, signal, clean));
279
+ }
280
+ if (!signal.aborted && backend.finalize) {
281
+ try {
282
+ await limited(signal, budgets.modelMs, "MODEL_TIMEOUT", (s) => backend.finalize(s));
283
+ }
284
+ catch (err) {
285
+ if (!signal.aborted) {
286
+ const code = faultCode(err);
287
+ report.model = { ...backend.identity, resolved: [] };
288
+ for (const a of report.attempts) {
289
+ const id = "a" + a.ordinal + "-e" + (a.events.length + 1);
290
+ a.events.push({ id, atMs: a.durationMs, kind: "error", code });
291
+ Object.assign(a, operational(code, id));
292
+ }
293
+ }
294
+ }
295
+ }
296
+ if (c.kind === "api_read" && !signal.aborted) {
297
+ const io = new Execution("control", c, target, options.transport(1), signal, clean, credential, "control");
298
+ try {
299
+ await io.read("api", c.expect.apiPath);
300
+ if (!signal.aborted) {
301
+ const control = { ...verifyApi(c, io.observations[0]), events: io.events };
302
+ report.control = control;
303
+ }
304
+ }
305
+ catch (err) {
306
+ if (!signal.aborted)
307
+ throw err;
308
+ }
309
+ }
310
+ for (const a of report.attempts)
311
+ report.counts[a.verdict]++;
312
+ report.counts.notStarted = repeat - report.attempts.length;
313
+ report.status = signal.aborted ? "cancelled" : "completed";
314
+ report.durationMs = elapsed(start);
315
+ for (const assessment of [...report.attempts, ...(report.control ? [report.control] : [])]) {
316
+ for (const assertion of assessment.assertions)
317
+ boundAssertion(assertion, clean);
318
+ }
319
+ // Preserve opaque identity strings exactly. Human-readable renderers sanitize them on output.
320
+ return structuredClone(report);
321
+ }
@@ -0,0 +1,8 @@
1
+ export declare function isCanonicalPath(value: unknown): value is string;
2
+ export declare function isDocsPath(path: string, prefixes: readonly string[]): boolean;
3
+ /** Parse only an authority, so URL normalization cannot erase a supplied path. */
4
+ export declare function canonicalOrigin(value: unknown): string;
5
+ /** Fragments have no effect on a static GET. Resolve relative references against
6
+ * the actual response URL, never an HTML base element or a model-supplied URL.
7
+ */
8
+ export declare function resolveDocsLink(href: string, pageUrl: string, docsOrigin: string, prefixes: readonly string[]): string | null;
@@ -0,0 +1,50 @@
1
+ import { isNonPublicIp } from '../utils/ssrf.js';
2
+ import { parseHttpUrl } from '../utils/url.js';
3
+ export function isCanonicalPath(value) {
4
+ return typeof value === 'string' && value.startsWith('/') &&
5
+ !value.includes('//') && !/[^A-Za-z0-9._~/-]/u.test(value) &&
6
+ !value.split('/').some(segment => segment === '.' || segment === '..');
7
+ }
8
+ export function isDocsPath(path, prefixes) {
9
+ return isCanonicalPath(path) && prefixes.some(prefix => path.startsWith(prefix));
10
+ }
11
+ /** Parse only an authority, so URL normalization cannot erase a supplied path. */
12
+ export function canonicalOrigin(value) {
13
+ if (typeof value !== 'string' || !/^https:\/\/[^/?#@%\\\s]+\/?$/iu.test(value) ||
14
+ /[\p{Cc}\p{Bidi_Control}]/u.test(value)) {
15
+ throw new Error('expected a public HTTPS origin without credentials, path, query or fragment');
16
+ }
17
+ let url;
18
+ try {
19
+ url = parseHttpUrl(value);
20
+ }
21
+ catch {
22
+ throw new Error('invalid HTTPS origin');
23
+ }
24
+ const host = url.hostname.replace(/^\[|\]$/gu, '').replace(/\.$/u, '');
25
+ if (url.port || host === 'localhost' || host.endsWith('.localhost') || isNonPublicIp(host)) {
26
+ throw new Error('expected a public HTTPS origin on the default port');
27
+ }
28
+ return url.origin;
29
+ }
30
+ /** Fragments have no effect on a static GET. Resolve relative references against
31
+ * the actual response URL, never an HTML base element or a model-supplied URL.
32
+ */
33
+ export function resolveDocsLink(href, pageUrl, docsOrigin, prefixes) {
34
+ const reference = href.split('#', 1)[0];
35
+ if (/[?%\\\s\p{Cc}]/u.test(reference))
36
+ return null;
37
+ // The URL constructor intentionally tolerates empty credentials, malformed
38
+ // schemes and extra leading slashes. Treat those as unusable references.
39
+ if (/^[a-z][a-z\d+.-]*:/iu.test(reference) && !/^https:\/\//iu.test(reference))
40
+ return null;
41
+ if (/^(?:https:)?\/\/(?:\/|[^/]*@)/iu.test(reference))
42
+ return null;
43
+ try {
44
+ const url = parseHttpUrl(reference, pageUrl);
45
+ return url.origin === docsOrigin && isDocsPath(url.pathname, prefixes) ? url.pathname : null;
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ }
@@ -0,0 +1,3 @@
1
+ import { type ProductTransport } from "./contracts.js";
2
+ /** One transport per attempt or independent control. Only receives executor-approved URLs. */
3
+ export declare function createProductTransport(maxRequests?: number): ProductTransport;
@@ -0,0 +1,45 @@
1
+ import { httpGetBytes, RequestCoordinator } from "../utils/http-client.js";
2
+ import { budgets } from "./contracts.js";
3
+ import { isCanonicalPath } from "./scope.js";
4
+ const emptyBody = new Uint8Array();
5
+ /** One transport per attempt or independent control. Only receives executor-approved URLs. */
6
+ export function createProductTransport(maxRequests = budgets.productGets) {
7
+ const coordinator = new RequestCoordinator(1, maxRequests);
8
+ const dnsCache = new Map();
9
+ return async (url, signal) => {
10
+ const empty = { mediaType: "", body: emptyBody };
11
+ if (url.protocol !== "https:" || url.username || url.password || url.port ||
12
+ !isCanonicalPath(url.pathname) || url.href !== url.origin + url.pathname) {
13
+ return { ...empty, status: null, code: "SCOPE_DENIED" };
14
+ }
15
+ const result = await httpGetBytes(url.href, {
16
+ coordinator, dnsCache, signal, timeout: budgets.productMs, maxBodyBytes: budgets.responseBytes,
17
+ maxRedirects: 0, retry: false, publicProductRead: true,
18
+ });
19
+ if (result.ok) {
20
+ return { status: result.status, mediaType: result.headers["content-type"] ?? "", body: result.body };
21
+ }
22
+ const { kind, statusCode } = result.error;
23
+ const status = statusCode ?? null;
24
+ let code;
25
+ if (signal.aborted)
26
+ code = signal.reason?.name === "TimeoutError" ? "TARGET_TIMEOUT" : "CANCELLED";
27
+ else if (kind === "timeout")
28
+ code = "TARGET_TIMEOUT";
29
+ else if (status !== null && status >= 300 && status < 400)
30
+ code = "REDIRECT_BLOCKED";
31
+ else if (status === 429)
32
+ code = "TARGET_RATE_LIMIT";
33
+ else if (kind === "bot_protected")
34
+ code = "BOT_BLOCKED";
35
+ else if (kind === "ssrf_blocked")
36
+ code = "SCOPE_DENIED";
37
+ else if (kind === "request_budget_exhausted")
38
+ code = "BUDGET_EXHAUSTED";
39
+ else if (status !== null && status >= 200 && status < 300)
40
+ code = "INCOMPLETE_BODY";
41
+ else if (kind !== "http_error" || status === null)
42
+ code = "TARGET_UNAVAILABLE";
43
+ return { ...empty, status, ...(code && { code }) };
44
+ };
45
+ }
@@ -0,0 +1,21 @@
1
+ import { type ApiCase, type JourneyCase } from "./case.js";
2
+ import { type Assessment, type Assertion, type EvidenceEvent } from "./contracts.js";
3
+ import type { ExcerptRead } from "./excerpt.js";
4
+ import type { FinishDecision } from "./decision.js";
5
+ /** Private observation. Only the event and selected assertion summaries enter a report. */
6
+ export interface Observation {
7
+ event: EvidenceEvent;
8
+ text?: string;
9
+ excerpt?: ExcerptRead;
10
+ clipped?: boolean;
11
+ hiddenPath?: string;
12
+ offeredPath?: string;
13
+ json?: unknown;
14
+ originalJson?: unknown;
15
+ jsonCode?: string;
16
+ apiAssessment?: Assessment;
17
+ }
18
+ export declare function operational(code: string, id: string): Assessment;
19
+ export declare function boundAssertion(assertion: Assertion, clean: (value: string) => string): void;
20
+ export declare function verifyApi(c: ApiCase, obs: Observation): Assessment;
21
+ export declare function verifyFinish(c: JourneyCase, d: FinishDecision, all: Observation[], finishId: string, safeAnswer: string | null): Assessment;
@@ -0,0 +1,213 @@
1
+ import { stringDigest } from "./case.js";
2
+ import { decisiveAssertion, isObservedPage } from "./contracts.js";
3
+ import { clip, normalize } from "./document.js";
4
+ const missing = { missing: true };
5
+ const check = (id, verdict, expected, observed, evidenceIds, code) => ({ id, verdict, expected, observed, evidenceIds, ...(code && { code }) });
6
+ function assess(assertions) {
7
+ const issue = decisiveAssertion(assertions);
8
+ return { verdict: issue?.verdict ?? "pass", ...(issue && { code: issue.code }), assertions };
9
+ }
10
+ export function operational(code, id) {
11
+ return assess([check("runtime.completion", "inconclusive", "completed", code, [id], code)]);
12
+ }
13
+ function matches(id, expected, observed, ids, code) {
14
+ return check(id, expected === observed ? "pass" : "fail", expected, observed, ids, expected === observed ? undefined : code);
15
+ }
16
+ function atPointer(value, pointer) {
17
+ if (!pointer)
18
+ return value;
19
+ for (const raw of pointer.slice(1).split("/")) {
20
+ const key = raw.replace(/~1/g, "/").replace(/~0/g, "~");
21
+ if (value === null || typeof value !== "object" || !Object.hasOwn(value, key))
22
+ return undefined;
23
+ if (Array.isArray(value) && !/^(0|[1-9][0-9]*)$/.test(key))
24
+ return undefined;
25
+ value = value[key];
26
+ }
27
+ return value;
28
+ }
29
+ function typeOf(value) {
30
+ return value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
31
+ }
32
+ function summarize(value) {
33
+ if (value === undefined)
34
+ return missing;
35
+ if (typeof value === "object" && value !== null)
36
+ return { type: Array.isArray(value) ? "array" : "object" };
37
+ return value;
38
+ }
39
+ export function boundAssertion(assertion, clean) {
40
+ function bounded(value) {
41
+ if (typeof value !== "string")
42
+ return value;
43
+ const safe = clean(value);
44
+ if (safe === value && Buffer.byteLength(value) <= 256)
45
+ return value;
46
+ return { preview: clip(safe, 256), sha256: stringDigest(value) };
47
+ }
48
+ assertion.expected = bounded(assertion.expected);
49
+ assertion.observed = bounded(assertion.observed);
50
+ }
51
+ export function verifyApi(c, obs) {
52
+ if (obs.apiAssessment)
53
+ return obs.apiAssessment;
54
+ const { id, status, code } = obs.event;
55
+ const ids = [id];
56
+ if (code)
57
+ return assess([check("api.status", "inconclusive", c.expect.status, status ?? missing, ids, code)]);
58
+ const statusCheck = matches("api.status", c.expect.status, status ?? missing, ids, "STATUS_MISMATCH");
59
+ const assertions = [statusCheck];
60
+ if (statusCheck.verdict !== "pass")
61
+ return assess(assertions);
62
+ assertions.push(check("api.json", obs.jsonCode ? "fail" : "pass", "JSON", obs.jsonCode ?? "JSON", ids, obs.jsonCode));
63
+ if (obs.jsonCode)
64
+ return assess(assertions);
65
+ for (const a of c.expect.assertions) {
66
+ const value = atPointer(obs.json, a.pointer);
67
+ const expected = a.op === "exists" ? true : a.op === "type" ? a.type : a.value;
68
+ const evaluate = (v) => v !== undefined && (a.op === "exists" || (a.op === "type" ? typeOf(v) === a.type : v === a.value));
69
+ if (value === undefined && obs.clipped) {
70
+ assertions.push(check(a.id, "inconclusive", expected, "omitted from observation", ids, "INCOMPLETE_BODY"));
71
+ continue;
72
+ }
73
+ const ok = evaluate(value);
74
+ if (Object.hasOwn(obs, "originalJson") && ok !== evaluate(atPointer(obs.originalJson, a.pointer))) {
75
+ assertions.push(check(a.id, "inconclusive", expected, "sanitized observation", ids, "REDACTED_EVIDENCE"));
76
+ continue;
77
+ }
78
+ let observed = missing;
79
+ if (value !== undefined) {
80
+ if (a.op === "exists")
81
+ observed = true;
82
+ else if (a.op === "type")
83
+ observed = typeOf(value);
84
+ else
85
+ observed = summarize(value);
86
+ }
87
+ assertions.push(check(a.id, ok ? "pass" : "fail", expected, observed, ids, ok ? undefined : "POINTER_MISMATCH"));
88
+ }
89
+ return assess(assertions);
90
+ }
91
+ function unavailable(observations, kind, path) {
92
+ const reads = observations.filter((o) => o.event.kind === kind && o.event.path === path);
93
+ // A recovered read supplies a real opportunity to cite the evidence.
94
+ if (reads.some((o) => !o.event.code))
95
+ return undefined;
96
+ const failed = reads.find((o) => o.event.code);
97
+ if (failed)
98
+ return failed;
99
+ // With no successful starting document there are no link IDs to follow.
100
+ const start = observations[0];
101
+ return start?.event.kind === "page" &&
102
+ start.event.code &&
103
+ !observations.some((o) => o.event.kind === "page" && o.text !== undefined)
104
+ ? start
105
+ : undefined;
106
+ }
107
+ function hiddenNavigation(observations, path) {
108
+ if (observations.some(o => o.offeredPath === path || o.event.path === path))
109
+ return;
110
+ return observations.find(o => o.hiddenPath === path);
111
+ }
112
+ function missingSource(id, path, observations, finishId, requiredDocsPath) {
113
+ const kind = id === "api.evidence" ? "api" : "page";
114
+ // An observed API response could have been cited regardless of how its path was discovered.
115
+ const hidden = requiredDocsPath && !observations.some(o => o.event.kind === kind && o.event.path === path) ?
116
+ hiddenNavigation(observations, requiredDocsPath) : undefined;
117
+ const blocked = hidden ?? unavailable(observations, kind, path);
118
+ return assess([
119
+ check(id, blocked ? "inconclusive" : "fail", path, missing, [blocked?.event.id ?? finishId], hidden ? "LINK_LIMIT" : (blocked?.event.code ?? "MISSING_EVIDENCE")),
120
+ ]);
121
+ }
122
+ function verifyGrounded(c, d, cited, all, finishId, safeAnswer) {
123
+ const sources = cited.filter((o) => o.event.kind === "page" && o.event.path === c.expect.sourcePath && isObservedPage(o.event));
124
+ if (!sources.length)
125
+ return missingSource("docs.passage", c.expect.sourcePath, all, finishId, c.expect.sourcePath);
126
+ const excerpt = normalize(c.expect.excerpt);
127
+ const source = sources.find((o) => o.text.includes(excerpt)) ?? sources.find((o) => o.clipped) ?? sources[0];
128
+ const found = source.text.includes(excerpt);
129
+ const verdict = found ? "pass" : source.clipped ? "inconclusive" : "fail";
130
+ const passage = check("docs.passage", verdict, excerpt, found ? excerpt : clip(source.text, 256), [source.event.id], verdict === "fail" ? "PASSAGE_MISMATCH" : verdict === "inconclusive" ? "INCOMPLETE_BODY" : undefined);
131
+ if (verdict === "inconclusive")
132
+ return assess([passage]);
133
+ const assertions = [
134
+ passage,
135
+ matches("docs.disposition", c.expect.disposition, d.disposition, [finishId], "DISPOSITION_MISMATCH"),
136
+ ];
137
+ if (c.expect.disposition === "answer") {
138
+ const expected = normalize(c.expect.value);
139
+ const original = d.answer === null ? missing : normalize(d.answer);
140
+ const observed = safeAnswer ?? missing;
141
+ const agrees = (expected === original) === (expected === observed);
142
+ assertions.push(agrees
143
+ ? matches("docs.value", expected, observed, [finishId], "VALUE_MISMATCH")
144
+ : check("docs.value", "inconclusive", expected, observed, [finishId], "REDACTED_EVIDENCE"));
145
+ }
146
+ return assess(assertions);
147
+ }
148
+ function verifyDocsExcerpt(c, earlier, apiId) {
149
+ const expected = normalize(c.expect.requiredDocsExcerpt);
150
+ const reads = earlier.filter((o) => o.event.kind === "page" && o.event.path === c.expect.requiredDocsPath);
151
+ const match = reads.find((o) => o.excerpt?.matched !== undefined);
152
+ if (match?.excerpt) {
153
+ return {
154
+ ...check("api.docs_excerpt", "pass", expected, match.excerpt.matched, [match.event.id, apiId]),
155
+ coverage: match.excerpt.coverage,
156
+ };
157
+ }
158
+ // A complete miss cannot establish absence across a different unknown read.
159
+ const unknown = reads.find((o) => !o.excerpt || o.excerpt.coverage !== "complete");
160
+ const source = unknown ?? reads[0];
161
+ const coverage = source ? (source.excerpt?.coverage ?? "unavailable") : "not-read";
162
+ const reason = {
163
+ complete: "DOCS_EXCERPT_MISSING",
164
+ clipped: "INCOMPLETE_BODY",
165
+ redacted: "REDACTED_EVIDENCE",
166
+ unavailable: source?.event.code ?? "DOCUMENT_UNAVAILABLE",
167
+ "not-read": "DOCS_NOT_OBSERVED",
168
+ }[coverage];
169
+ return {
170
+ ...check("api.docs_excerpt", coverage === "complete" ? "fail" : "inconclusive", expected, missing, source ? [source.event.id, apiId] : [apiId], reason),
171
+ coverage,
172
+ };
173
+ }
174
+ export function verifyFinish(c, d, all, finishId, safeAnswer) {
175
+ const cited = [];
176
+ for (const id of d.evidenceIds) {
177
+ const obs = all.find((o) => o.event.id === id);
178
+ if (!obs)
179
+ return assess([
180
+ check("evidence.references", "fail", "observed actor evidence", missing, [finishId], "MISSING_EVIDENCE"),
181
+ ]);
182
+ cited.push(obs);
183
+ }
184
+ if (c.kind === "grounded_answer")
185
+ return verifyGrounded(c, d, cited, all, finishId, safeAnswer);
186
+ const apis = cited.filter((o) => o.event.kind === "api" && o.event.path === c.expect.apiPath);
187
+ if (!apis.length)
188
+ return missingSource("api.evidence", c.expect.apiPath, all, finishId, c.expect.requiredDocsPath);
189
+ const results = apis.map((api) => {
190
+ const checks = [];
191
+ const earlier = all.slice(0, all.indexOf(api));
192
+ if (c.expect.requiredDocsPath) {
193
+ const pages = earlier.filter((o) => o.event.kind === "page" && o.event.path === c.expect.requiredDocsPath);
194
+ const docs = pages.find((o) => isObservedPage(o.event));
195
+ const hidden = hiddenNavigation(earlier, c.expect.requiredDocsPath);
196
+ const blocked = docs
197
+ ? undefined
198
+ : (hidden ?? unavailable(earlier, "page", c.expect.requiredDocsPath) ??
199
+ (c.expect.requiredDocsExcerpt ? pages[0] : undefined));
200
+ checks.push(check("api.docs", docs ? "pass" : blocked ? "inconclusive" : "fail", c.expect.requiredDocsPath, docs?.event.path ?? missing, docs ? [docs.event.id, api.event.id] : [api.event.id, ...(blocked ? [blocked.event.id] : [])], docs ? undefined : hidden ? "LINK_LIMIT" : (blocked?.event.code ?? (blocked ? "DOCUMENT_UNAVAILABLE" : "DOCS_ORDER"))));
201
+ }
202
+ if (c.expect.requiredDocsExcerpt) {
203
+ checks.push(verifyDocsExcerpt(c, earlier, api.event.id));
204
+ }
205
+ checks.push(...verifyApi(c, api).assertions);
206
+ if (!checks.some((a) => a.verdict === "inconclusive"))
207
+ checks.push(matches("api.disposition", "answer", d.disposition, [finishId], "DISPOSITION_MISMATCH"));
208
+ return assess(checks);
209
+ });
210
+ return (results.find((r) => r.verdict === "pass") ??
211
+ results.find((r) => r.verdict === "inconclusive") ??
212
+ results[0]);
213
+ }