clinkx 0.3.0 → 1.1.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 (669) hide show
  1. package/CHANGELOG.md +119 -0
  2. package/LICENSE +10 -0
  3. package/README.md +154 -26
  4. package/clinkx-workflows/dist/allowed-roots.d.ts +1 -0
  5. package/clinkx-workflows/dist/allowed-roots.js +5 -0
  6. package/clinkx-workflows/dist/allowed-roots.js.map +1 -0
  7. package/clinkx-workflows/dist/artifacts.d.ts +20 -1
  8. package/clinkx-workflows/dist/artifacts.js +38 -9
  9. package/clinkx-workflows/dist/artifacts.js.map +1 -1
  10. package/clinkx-workflows/dist/backend.d.ts +4 -0
  11. package/clinkx-workflows/dist/chairman-knobs.d.ts +24 -0
  12. package/clinkx-workflows/dist/chairman-knobs.js +27 -0
  13. package/clinkx-workflows/dist/chairman-knobs.js.map +1 -0
  14. package/clinkx-workflows/dist/citation-check.d.ts +40 -0
  15. package/clinkx-workflows/dist/citation-check.js +348 -0
  16. package/clinkx-workflows/dist/citation-check.js.map +1 -0
  17. package/clinkx-workflows/dist/clink-client.d.ts +12 -1
  18. package/clinkx-workflows/dist/clink-client.js +56 -5
  19. package/clinkx-workflows/dist/clink-client.js.map +1 -1
  20. package/clinkx-workflows/dist/config.d.ts +173 -16
  21. package/clinkx-workflows/dist/config.js +417 -26
  22. package/clinkx-workflows/dist/config.js.map +1 -1
  23. package/clinkx-workflows/dist/contained-file.d.ts +172 -0
  24. package/clinkx-workflows/dist/contained-file.js +483 -0
  25. package/clinkx-workflows/dist/contained-file.js.map +1 -0
  26. package/clinkx-workflows/dist/context-builder-lifecycle-contract.d.ts +416 -0
  27. package/clinkx-workflows/dist/context-builder-lifecycle-contract.js +328 -0
  28. package/clinkx-workflows/dist/context-builder-lifecycle-contract.js.map +1 -0
  29. package/clinkx-workflows/dist/context-builder-lifecycle-router.d.ts +24 -0
  30. package/clinkx-workflows/dist/context-builder-lifecycle-router.js +39 -0
  31. package/clinkx-workflows/dist/context-builder-lifecycle-router.js.map +1 -0
  32. package/clinkx-workflows/dist/context-cache-key.d.ts +53 -0
  33. package/clinkx-workflows/dist/context-cache-key.js +91 -0
  34. package/clinkx-workflows/dist/context-cache-key.js.map +1 -0
  35. package/clinkx-workflows/dist/context-mode-resolver.d.ts +27 -0
  36. package/clinkx-workflows/dist/context-mode-resolver.js +126 -0
  37. package/clinkx-workflows/dist/context-mode-resolver.js.map +1 -0
  38. package/clinkx-workflows/dist/context-preflight.d.ts +189 -0
  39. package/clinkx-workflows/dist/context-preflight.js +91 -0
  40. package/clinkx-workflows/dist/context-preflight.js.map +1 -0
  41. package/clinkx-workflows/dist/council-execution-policy.d.ts +68 -0
  42. package/clinkx-workflows/dist/council-execution-policy.js +110 -0
  43. package/clinkx-workflows/dist/council-execution-policy.js.map +1 -0
  44. package/clinkx-workflows/dist/council-expander.d.ts +10 -9
  45. package/clinkx-workflows/dist/council-expander.js +20 -10
  46. package/clinkx-workflows/dist/council-expander.js.map +1 -1
  47. package/clinkx-workflows/dist/dashboard/activity-contract.d.ts +5718 -0
  48. package/clinkx-workflows/dist/dashboard/activity-contract.js +157 -0
  49. package/clinkx-workflows/dist/dashboard/activity-contract.js.map +1 -0
  50. package/clinkx-workflows/dist/dashboard/activity-lease.d.ts +25 -0
  51. package/clinkx-workflows/dist/dashboard/activity-lease.js +34 -0
  52. package/clinkx-workflows/dist/dashboard/activity-lease.js.map +1 -0
  53. package/clinkx-workflows/dist/dashboard/activity-reader.d.ts +90 -0
  54. package/clinkx-workflows/dist/dashboard/activity-reader.js +493 -0
  55. package/clinkx-workflows/dist/dashboard/activity-reader.js.map +1 -0
  56. package/clinkx-workflows/dist/dashboard/api-routes.d.ts +40 -0
  57. package/clinkx-workflows/dist/dashboard/api-routes.js +1155 -0
  58. package/clinkx-workflows/dist/dashboard/api-routes.js.map +1 -0
  59. package/clinkx-workflows/dist/dashboard/artifact-index.d.ts +37 -0
  60. package/clinkx-workflows/dist/dashboard/artifact-index.js +145 -0
  61. package/clinkx-workflows/dist/dashboard/artifact-index.js.map +1 -0
  62. package/clinkx-workflows/dist/dashboard/auth/challenge-store.d.ts +31 -0
  63. package/clinkx-workflows/dist/dashboard/auth/challenge-store.js +65 -0
  64. package/clinkx-workflows/dist/dashboard/auth/challenge-store.js.map +1 -0
  65. package/clinkx-workflows/dist/dashboard/auth/controller.d.ts +26 -0
  66. package/clinkx-workflows/dist/dashboard/auth/controller.js +596 -0
  67. package/clinkx-workflows/dist/dashboard/auth/controller.js.map +1 -0
  68. package/clinkx-workflows/dist/dashboard/auth/credential-store.d.ts +60 -0
  69. package/clinkx-workflows/dist/dashboard/auth/credential-store.js +776 -0
  70. package/clinkx-workflows/dist/dashboard/auth/credential-store.js.map +1 -0
  71. package/clinkx-workflows/dist/dashboard/auth/enrollment-gate.d.ts +9 -0
  72. package/clinkx-workflows/dist/dashboard/auth/enrollment-gate.js +44 -0
  73. package/clinkx-workflows/dist/dashboard/auth/enrollment-gate.js.map +1 -0
  74. package/clinkx-workflows/dist/dashboard/auth/session-store.d.ts +17 -0
  75. package/clinkx-workflows/dist/dashboard/auth/session-store.js +77 -0
  76. package/clinkx-workflows/dist/dashboard/auth/session-store.js.map +1 -0
  77. package/clinkx-workflows/dist/dashboard/auth/webauthn-service.d.ts +25 -0
  78. package/clinkx-workflows/dist/dashboard/auth/webauthn-service.js +71 -0
  79. package/clinkx-workflows/dist/dashboard/auth/webauthn-service.js.map +1 -0
  80. package/clinkx-workflows/dist/dashboard/context-builder-invocation-contract.d.ts +3865 -0
  81. package/clinkx-workflows/dist/dashboard/context-builder-invocation-contract.js +69 -0
  82. package/clinkx-workflows/dist/dashboard/context-builder-invocation-contract.js.map +1 -0
  83. package/clinkx-workflows/dist/dashboard/context-run-liveness.d.ts +37 -0
  84. package/clinkx-workflows/dist/dashboard/context-run-liveness.js +49 -0
  85. package/clinkx-workflows/dist/dashboard/context-run-liveness.js.map +1 -0
  86. package/clinkx-workflows/dist/dashboard/context-run-reader.d.ts +256 -0
  87. package/clinkx-workflows/dist/dashboard/context-run-reader.js +1301 -0
  88. package/clinkx-workflows/dist/dashboard/context-run-reader.js.map +1 -0
  89. package/clinkx-workflows/dist/dashboard/contracts.d.ts +28483 -0
  90. package/clinkx-workflows/dist/dashboard/contracts.js +1284 -0
  91. package/clinkx-workflows/dist/dashboard/contracts.js.map +1 -0
  92. package/clinkx-workflows/dist/dashboard/generation.d.ts +14 -0
  93. package/clinkx-workflows/dist/dashboard/generation.js +41 -0
  94. package/clinkx-workflows/dist/dashboard/generation.js.map +1 -0
  95. package/clinkx-workflows/dist/dashboard/index.d.ts +32 -0
  96. package/clinkx-workflows/dist/dashboard/index.js +20 -0
  97. package/clinkx-workflows/dist/dashboard/index.js.map +1 -0
  98. package/clinkx-workflows/dist/dashboard/invocation-contract.d.ts +786 -0
  99. package/clinkx-workflows/dist/dashboard/invocation-contract.js +201 -0
  100. package/clinkx-workflows/dist/dashboard/invocation-contract.js.map +1 -0
  101. package/clinkx-workflows/dist/dashboard/lazy-content.d.ts +114 -0
  102. package/clinkx-workflows/dist/dashboard/lazy-content.js +799 -0
  103. package/clinkx-workflows/dist/dashboard/lazy-content.js.map +1 -0
  104. package/clinkx-workflows/dist/dashboard/native-transcript/contract.d.ts +90 -0
  105. package/clinkx-workflows/dist/dashboard/native-transcript/contract.js +31 -0
  106. package/clinkx-workflows/dist/dashboard/native-transcript/contract.js.map +1 -0
  107. package/clinkx-workflows/dist/dashboard/native-transcript/projection.d.ts +12 -0
  108. package/clinkx-workflows/dist/dashboard/native-transcript/projection.js +286 -0
  109. package/clinkx-workflows/dist/dashboard/native-transcript/projection.js.map +1 -0
  110. package/clinkx-workflows/dist/dashboard/progress-report-contract.d.ts +446 -0
  111. package/clinkx-workflows/dist/dashboard/progress-report-contract.js +221 -0
  112. package/clinkx-workflows/dist/dashboard/progress-report-contract.js.map +1 -0
  113. package/clinkx-workflows/dist/dashboard/progress-report-reader.d.ts +50 -0
  114. package/clinkx-workflows/dist/dashboard/progress-report-reader.js +529 -0
  115. package/clinkx-workflows/dist/dashboard/progress-report-reader.js.map +1 -0
  116. package/clinkx-workflows/dist/dashboard/progress-report-status-overlay.d.ts +89 -0
  117. package/clinkx-workflows/dist/dashboard/progress-report-status-overlay.js +71 -0
  118. package/clinkx-workflows/dist/dashboard/progress-report-status-overlay.js.map +1 -0
  119. package/clinkx-workflows/dist/dashboard/progress-report-status-store.d.ts +29 -0
  120. package/clinkx-workflows/dist/dashboard/progress-report-status-store.js +111 -0
  121. package/clinkx-workflows/dist/dashboard/progress-report-status-store.js.map +1 -0
  122. package/clinkx-workflows/dist/dashboard/prompt-builder-library-contract.d.ts +194 -0
  123. package/clinkx-workflows/dist/dashboard/prompt-builder-library-contract.js +89 -0
  124. package/clinkx-workflows/dist/dashboard/prompt-builder-library-contract.js.map +1 -0
  125. package/clinkx-workflows/dist/dashboard/prompt-builder-library-store.d.ts +26 -0
  126. package/clinkx-workflows/dist/dashboard/prompt-builder-library-store.js +102 -0
  127. package/clinkx-workflows/dist/dashboard/prompt-builder-library-store.js.map +1 -0
  128. package/clinkx-workflows/dist/dashboard/read-model.d.ts +86 -0
  129. package/clinkx-workflows/dist/dashboard/read-model.js +440 -0
  130. package/clinkx-workflows/dist/dashboard/read-model.js.map +1 -0
  131. package/clinkx-workflows/dist/dashboard/request-admission.d.ts +31 -0
  132. package/clinkx-workflows/dist/dashboard/request-admission.js +130 -0
  133. package/clinkx-workflows/dist/dashboard/request-admission.js.map +1 -0
  134. package/clinkx-workflows/dist/dashboard/scanner.d.ts +78 -0
  135. package/clinkx-workflows/dist/dashboard/scanner.js +1154 -0
  136. package/clinkx-workflows/dist/dashboard/scanner.js.map +1 -0
  137. package/clinkx-workflows/dist/dashboard/server-factory.d.ts +63 -0
  138. package/clinkx-workflows/dist/dashboard/server-factory.js +483 -0
  139. package/clinkx-workflows/dist/dashboard/server-factory.js.map +1 -0
  140. package/clinkx-workflows/dist/dashboard/session-log-contract.d.ts +2778 -0
  141. package/clinkx-workflows/dist/dashboard/session-log-contract.js +506 -0
  142. package/clinkx-workflows/dist/dashboard/session-log-contract.js.map +1 -0
  143. package/clinkx-workflows/dist/dashboard/session-log-identity.d.ts +21 -0
  144. package/clinkx-workflows/dist/dashboard/session-log-identity.js +101 -0
  145. package/clinkx-workflows/dist/dashboard/session-log-identity.js.map +1 -0
  146. package/clinkx-workflows/dist/dashboard/session-log-journal.d.ts +43 -0
  147. package/clinkx-workflows/dist/dashboard/session-log-journal.js +529 -0
  148. package/clinkx-workflows/dist/dashboard/session-log-journal.js.map +1 -0
  149. package/clinkx-workflows/dist/dashboard/session-log-reader.d.ts +61 -0
  150. package/clinkx-workflows/dist/dashboard/session-log-reader.js +378 -0
  151. package/clinkx-workflows/dist/dashboard/session-log-reader.js.map +1 -0
  152. package/clinkx-workflows/dist/dashboard/session-log-redaction.d.ts +14 -0
  153. package/clinkx-workflows/dist/dashboard/session-log-redaction.js +1101 -0
  154. package/clinkx-workflows/dist/dashboard/session-log-redaction.js.map +1 -0
  155. package/clinkx-workflows/dist/dashboard/session-log-retention.d.ts +23 -0
  156. package/clinkx-workflows/dist/dashboard/session-log-retention.js +212 -0
  157. package/clinkx-workflows/dist/dashboard/session-log-retention.js.map +1 -0
  158. package/clinkx-workflows/dist/dashboard/static-responses.d.ts +10 -0
  159. package/clinkx-workflows/dist/dashboard/static-responses.js +94 -0
  160. package/clinkx-workflows/dist/dashboard/static-responses.js.map +1 -0
  161. package/clinkx-workflows/dist/dashboard/worker-lock-observer.d.ts +28 -0
  162. package/clinkx-workflows/dist/dashboard/worker-lock-observer.js +241 -0
  163. package/clinkx-workflows/dist/dashboard/worker-lock-observer.js.map +1 -0
  164. package/clinkx-workflows/dist/dashboard-ui/assets/ibm-plex-mono-latin-400-normal-CvHOgSBP.woff +0 -0
  165. package/clinkx-workflows/dist/dashboard-ui/assets/ibm-plex-mono-latin-400-normal-DMJ8VG8y.woff2 +0 -0
  166. package/clinkx-workflows/dist/dashboard-ui/assets/ibm-plex-mono-latin-500-normal-CB9ihrfo.woff +0 -0
  167. package/clinkx-workflows/dist/dashboard-ui/assets/ibm-plex-mono-latin-500-normal-DSY6xOcd.woff2 +0 -0
  168. package/clinkx-workflows/dist/dashboard-ui/assets/ibm-plex-sans-latin-400-normal-CDDApCn2.woff2 +0 -0
  169. package/clinkx-workflows/dist/dashboard-ui/assets/ibm-plex-sans-latin-400-normal-CYLoc0-x.woff +0 -0
  170. package/clinkx-workflows/dist/dashboard-ui/assets/ibm-plex-sans-latin-500-normal-6ng42L7E.woff2 +0 -0
  171. package/clinkx-workflows/dist/dashboard-ui/assets/ibm-plex-sans-latin-500-normal-BgVn5rGT.woff +0 -0
  172. package/clinkx-workflows/dist/dashboard-ui/assets/ibm-plex-sans-latin-600-normal-Cu4Hd6ag.woff +0 -0
  173. package/clinkx-workflows/dist/dashboard-ui/assets/ibm-plex-sans-latin-600-normal-CuJfVYMP.woff2 +0 -0
  174. package/clinkx-workflows/dist/dashboard-ui/assets/index-JPHQVtn9.js +106 -0
  175. package/clinkx-workflows/dist/dashboard-ui/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  176. package/clinkx-workflows/dist/dashboard-ui/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  177. package/clinkx-workflows/dist/dashboard-ui/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
  178. package/clinkx-workflows/dist/dashboard-ui/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
  179. package/clinkx-workflows/dist/dashboard-ui/assets/style-DOMHk-j6.css +1 -0
  180. package/clinkx-workflows/dist/dashboard-ui/contracts/council-plan-review-input-v1.json +158 -0
  181. package/clinkx-workflows/dist/dashboard-ui/index.html +15 -0
  182. package/clinkx-workflows/dist/dashboard-ui/licenses/IBM-Plex-Mono-OFL.txt +93 -0
  183. package/clinkx-workflows/dist/dashboard-ui/licenses/IBM-Plex-Sans-OFL.txt +93 -0
  184. package/clinkx-workflows/dist/dashboard-ui/licenses/JetBrains-Mono-OFL.txt +93 -0
  185. package/clinkx-workflows/dist/dashboard-ui/licenses/NOTICE.md +32 -0
  186. package/clinkx-workflows/dist/dashboard-ui/theme-init.js +8 -0
  187. package/clinkx-workflows/dist/definition-normalizer.d.ts +19 -0
  188. package/clinkx-workflows/dist/definition-normalizer.js.map +1 -1
  189. package/clinkx-workflows/dist/delegate-finalizer-policy.d.ts +26 -0
  190. package/clinkx-workflows/dist/delegate-finalizer-policy.js +72 -0
  191. package/clinkx-workflows/dist/delegate-finalizer-policy.js.map +1 -0
  192. package/clinkx-workflows/dist/delegate-signature.d.ts +14 -0
  193. package/clinkx-workflows/dist/delegate-signature.js +14 -0
  194. package/clinkx-workflows/dist/delegate-signature.js.map +1 -0
  195. package/clinkx-workflows/dist/delegate-validate.d.ts +108 -0
  196. package/clinkx-workflows/dist/delegate-validate.js +148 -0
  197. package/clinkx-workflows/dist/delegate-validate.js.map +1 -0
  198. package/clinkx-workflows/dist/engine.d.ts +251 -0
  199. package/clinkx-workflows/dist/engine.js +1342 -92
  200. package/clinkx-workflows/dist/engine.js.map +1 -1
  201. package/clinkx-workflows/dist/errors.d.ts +24 -2
  202. package/clinkx-workflows/dist/errors.js +30 -2
  203. package/clinkx-workflows/dist/errors.js.map +1 -1
  204. package/clinkx-workflows/dist/fidelity.d.ts +47 -1
  205. package/clinkx-workflows/dist/fidelity.js +54 -1
  206. package/clinkx-workflows/dist/fidelity.js.map +1 -1
  207. package/clinkx-workflows/dist/fingerprint.d.ts +25 -7
  208. package/clinkx-workflows/dist/fingerprint.js +33 -10
  209. package/clinkx-workflows/dist/fingerprint.js.map +1 -1
  210. package/clinkx-workflows/dist/index.d.ts +19 -0
  211. package/clinkx-workflows/dist/index.js +68 -1
  212. package/clinkx-workflows/dist/index.js.map +1 -1
  213. package/clinkx-workflows/dist/loader.d.ts +9 -3
  214. package/clinkx-workflows/dist/loader.js +92 -21
  215. package/clinkx-workflows/dist/loader.js.map +1 -1
  216. package/clinkx-workflows/dist/logger.d.ts +1 -1
  217. package/clinkx-workflows/dist/logger.js +17 -3
  218. package/clinkx-workflows/dist/logger.js.map +1 -1
  219. package/clinkx-workflows/dist/monotonic-clock.d.ts +19 -0
  220. package/clinkx-workflows/dist/monotonic-clock.js +22 -0
  221. package/clinkx-workflows/dist/monotonic-clock.js.map +1 -0
  222. package/clinkx-workflows/dist/plan-review/admission.d.ts +160 -0
  223. package/clinkx-workflows/dist/plan-review/admission.js +290 -0
  224. package/clinkx-workflows/dist/plan-review/admission.js.map +1 -0
  225. package/clinkx-workflows/dist/plan-review/context-policy.d.ts +55 -0
  226. package/clinkx-workflows/dist/plan-review/context-policy.js +146 -0
  227. package/clinkx-workflows/dist/plan-review/context-policy.js.map +1 -0
  228. package/clinkx-workflows/dist/plan-review/contract.d.ts +763 -0
  229. package/clinkx-workflows/dist/plan-review/contract.js +289 -0
  230. package/clinkx-workflows/dist/plan-review/contract.js.map +1 -0
  231. package/clinkx-workflows/dist/plan-review/digest.d.ts +68 -0
  232. package/clinkx-workflows/dist/plan-review/digest.js +241 -0
  233. package/clinkx-workflows/dist/plan-review/digest.js.map +1 -0
  234. package/clinkx-workflows/dist/plan-review/discovery.d.ts +45 -0
  235. package/clinkx-workflows/dist/plan-review/discovery.js +36 -0
  236. package/clinkx-workflows/dist/plan-review/discovery.js.map +1 -0
  237. package/clinkx-workflows/dist/plan-review/execution-contract.d.ts +298 -0
  238. package/clinkx-workflows/dist/plan-review/execution-contract.js +194 -0
  239. package/clinkx-workflows/dist/plan-review/execution-contract.js.map +1 -0
  240. package/clinkx-workflows/dist/plan-review/expander.d.ts +48 -0
  241. package/clinkx-workflows/dist/plan-review/expander.js +243 -0
  242. package/clinkx-workflows/dist/plan-review/expander.js.map +1 -0
  243. package/clinkx-workflows/dist/plan-review/projector.d.ts +126 -0
  244. package/clinkx-workflows/dist/plan-review/projector.js +437 -0
  245. package/clinkx-workflows/dist/plan-review/projector.js.map +1 -0
  246. package/clinkx-workflows/dist/plan-review/publication.d.ts +95 -0
  247. package/clinkx-workflows/dist/plan-review/publication.js +182 -0
  248. package/clinkx-workflows/dist/plan-review/publication.js.map +1 -0
  249. package/clinkx-workflows/dist/plan-review/ranking-reducer.d.ts +34 -0
  250. package/clinkx-workflows/dist/plan-review/ranking-reducer.js +139 -0
  251. package/clinkx-workflows/dist/plan-review/ranking-reducer.js.map +1 -0
  252. package/clinkx-workflows/dist/plan-review/resume.d.ts +38 -0
  253. package/clinkx-workflows/dist/plan-review/resume.js +122 -0
  254. package/clinkx-workflows/dist/plan-review/resume.js.map +1 -0
  255. package/clinkx-workflows/dist/plan-review/rubric.d.ts +7 -0
  256. package/clinkx-workflows/dist/plan-review/rubric.js +24 -0
  257. package/clinkx-workflows/dist/plan-review/rubric.js.map +1 -0
  258. package/clinkx-workflows/dist/plan-review/run-state.d.ts +398 -0
  259. package/clinkx-workflows/dist/plan-review/run-state.js +183 -0
  260. package/clinkx-workflows/dist/plan-review/run-state.js.map +1 -0
  261. package/clinkx-workflows/dist/plan-review/runtime-policy.d.ts +74 -0
  262. package/clinkx-workflows/dist/plan-review/runtime-policy.js +186 -0
  263. package/clinkx-workflows/dist/plan-review/runtime-policy.js.map +1 -0
  264. package/clinkx-workflows/dist/plan-review/snapshot.d.ts +81 -0
  265. package/clinkx-workflows/dist/plan-review/snapshot.js +170 -0
  266. package/clinkx-workflows/dist/plan-review/snapshot.js.map +1 -0
  267. package/clinkx-workflows/dist/plan-review/stage-error.d.ts +19 -0
  268. package/clinkx-workflows/dist/plan-review/stage-error.js +20 -0
  269. package/clinkx-workflows/dist/plan-review/stage-error.js.map +1 -0
  270. package/clinkx-workflows/dist/post-processors/index.d.ts +20 -0
  271. package/clinkx-workflows/dist/post-processors/index.js +21 -0
  272. package/clinkx-workflows/dist/post-processors/index.js.map +1 -0
  273. package/clinkx-workflows/dist/prompt-budget.d.ts +7 -0
  274. package/clinkx-workflows/dist/prompt-budget.js +7 -1
  275. package/clinkx-workflows/dist/prompt-budget.js.map +1 -1
  276. package/clinkx-workflows/dist/reducers/index.js +2 -0
  277. package/clinkx-workflows/dist/reducers/index.js.map +1 -1
  278. package/clinkx-workflows/dist/roster-contract.d.ts +889 -0
  279. package/clinkx-workflows/dist/roster-contract.js +180 -0
  280. package/clinkx-workflows/dist/roster-contract.js.map +1 -0
  281. package/clinkx-workflows/dist/rosters.d.ts +14 -0
  282. package/clinkx-workflows/dist/rosters.js +169 -0
  283. package/clinkx-workflows/dist/rosters.js.map +1 -0
  284. package/clinkx-workflows/dist/run-health.d.ts +7 -0
  285. package/clinkx-workflows/dist/run-health.js +25 -0
  286. package/clinkx-workflows/dist/run-health.js.map +1 -0
  287. package/clinkx-workflows/dist/run-lock-heartbeat.d.ts +2 -0
  288. package/clinkx-workflows/dist/run-lock-heartbeat.js +3 -0
  289. package/clinkx-workflows/dist/run-lock-heartbeat.js.map +1 -0
  290. package/clinkx-workflows/dist/run-summary/cards/council-plan-review.d.ts +34 -0
  291. package/clinkx-workflows/dist/run-summary/cards/council-plan-review.js +74 -0
  292. package/clinkx-workflows/dist/run-summary/cards/council-plan-review.js.map +1 -0
  293. package/clinkx-workflows/dist/run-summary/cards/index.js +5 -0
  294. package/clinkx-workflows/dist/run-summary/cards/index.js.map +1 -1
  295. package/clinkx-workflows/dist/run-summary.d.ts +13 -0
  296. package/clinkx-workflows/dist/run-summary.js +29 -1
  297. package/clinkx-workflows/dist/run-summary.js.map +1 -1
  298. package/clinkx-workflows/dist/schema.d.ts +140 -21
  299. package/clinkx-workflows/dist/schema.js +34 -1
  300. package/clinkx-workflows/dist/schema.js.map +1 -1
  301. package/clinkx-workflows/dist/seed-terms.d.ts +30 -0
  302. package/clinkx-workflows/dist/seed-terms.js +176 -0
  303. package/clinkx-workflows/dist/seed-terms.js.map +1 -0
  304. package/clinkx-workflows/dist/server.d.ts +5 -2
  305. package/clinkx-workflows/dist/server.js +84 -52
  306. package/clinkx-workflows/dist/server.js.map +1 -1
  307. package/clinkx-workflows/dist/shutdown.d.ts +29 -18
  308. package/clinkx-workflows/dist/shutdown.js +90 -64
  309. package/clinkx-workflows/dist/shutdown.js.map +1 -1
  310. package/clinkx-workflows/dist/state-schema.d.ts +61 -0
  311. package/clinkx-workflows/dist/state.d.ts +175 -3
  312. package/clinkx-workflows/dist/state.js +1398 -44
  313. package/clinkx-workflows/dist/state.js.map +1 -1
  314. package/clinkx-workflows/dist/stdio-watchdog.d.ts +52 -0
  315. package/clinkx-workflows/dist/stdio-watchdog.js +212 -0
  316. package/clinkx-workflows/dist/stdio-watchdog.js.map +1 -0
  317. package/clinkx-workflows/dist/transport.d.ts +15 -0
  318. package/clinkx-workflows/dist/transport.js +19 -10
  319. package/clinkx-workflows/dist/transport.js.map +1 -1
  320. package/clinkx-workflows/dist/types.d.ts +20 -2
  321. package/clinkx-workflows/dist/validators/council.d.ts +334 -101
  322. package/clinkx-workflows/dist/validators/council.js +52 -13
  323. package/clinkx-workflows/dist/validators/council.js.map +1 -1
  324. package/clinkx-workflows/dist/validators/index.d.ts +1 -0
  325. package/clinkx-workflows/dist/validators/index.js +3 -0
  326. package/clinkx-workflows/dist/validators/index.js.map +1 -1
  327. package/clinkx-workflows/dist/validators/plan-review.d.ts +398 -0
  328. package/clinkx-workflows/dist/validators/plan-review.js +316 -0
  329. package/clinkx-workflows/dist/validators/plan-review.js.map +1 -0
  330. package/clinkx-workflows/dist/workflow-receipt.js +188 -4
  331. package/clinkx-workflows/dist/workflow-receipt.js.map +1 -1
  332. package/clinkx-workflows/dist/workflow-tools.d.ts +118 -3
  333. package/clinkx-workflows/dist/workflow-tools.js +2110 -175
  334. package/clinkx-workflows/dist/workflow-tools.js.map +1 -1
  335. package/clinkx-workflows/dist/workspace-signature.d.ts +16 -0
  336. package/clinkx-workflows/dist/workspace-signature.js +388 -0
  337. package/clinkx-workflows/dist/workspace-signature.js.map +1 -0
  338. package/clinkx-workflows/templates/council/answer-chairman.txt +3 -0
  339. package/clinkx-workflows/templates/council/answer-cross-reviewer.txt +3 -0
  340. package/clinkx-workflows/templates/council/answer-specialist.txt +5 -1
  341. package/clinkx-workflows/templates/council/chairman.txt +3 -0
  342. package/clinkx-workflows/templates/council/code-review-chairman.txt +16 -0
  343. package/clinkx-workflows/templates/council/code-review-cross-reviewer.txt +7 -1
  344. package/clinkx-workflows/templates/council/code-review-reviewer.txt +22 -3
  345. package/clinkx-workflows/templates/council/debug-chairman.txt +3 -0
  346. package/clinkx-workflows/templates/council/debug-cross-reviewer.txt +3 -0
  347. package/clinkx-workflows/templates/council/debug-debugger.txt +5 -1
  348. package/clinkx-workflows/templates/council/discover-analyst.txt +5 -1
  349. package/clinkx-workflows/templates/council/discover-chairman.txt +3 -0
  350. package/clinkx-workflows/templates/council/discover-cross-reviewer.txt +3 -0
  351. package/clinkx-workflows/templates/council/member.txt +5 -1
  352. package/clinkx-workflows/templates/council/plan-review-chairman.txt +71 -0
  353. package/clinkx-workflows/templates/council/plan-review-cross-reviewer.txt +54 -0
  354. package/clinkx-workflows/templates/council/plan-review-reviewer.txt +63 -0
  355. package/clinkx-workflows/templates/council/reviewer.txt +3 -0
  356. package/clinkx-workflows/templates/plan-review/chairman.txt +48 -0
  357. package/clinkx-workflows/templates/plan-review/cross-review.txt +52 -0
  358. package/clinkx-workflows/templates/plan-review/ranking.txt +16 -0
  359. package/clinkx-workflows/templates/plan-review/reviewer.txt +57 -0
  360. package/clinkx-workflows/workflows/council-answer.yaml +100 -8
  361. package/clinkx-workflows/workflows/council-code-review.yaml +106 -8
  362. package/clinkx-workflows/workflows/council-debug.yaml +100 -8
  363. package/clinkx-workflows/workflows/council-default.yaml +104 -8
  364. package/clinkx-workflows/workflows/council-discover.yaml +100 -8
  365. package/clinkx-workflows/workflows/council-plan-review.yaml +253 -0
  366. package/clinkx-workflows/workflows/plan-review-receipts.yaml +230 -0
  367. package/conf/adapters/agy.json +56 -0
  368. package/conf/adapters/claude.json +12 -0
  369. package/conf/adapters/codex-app-server.json +44 -0
  370. package/conf/adapters/codex.json +14 -2
  371. package/conf/adapters/glm.json +24 -3
  372. package/conf/adapters/grok.json +67 -0
  373. package/conf/adapters/hapi/agy.json +59 -0
  374. package/conf/adapters/hapi/claude.json +12 -0
  375. package/conf/adapters/hapi/codex.json +14 -2
  376. package/conf/adapters/hapi/glm.json +25 -4
  377. package/conf/rosters/default-council.json +21 -0
  378. package/dist/activity-journal.d.ts +56 -0
  379. package/dist/activity-journal.js +706 -0
  380. package/dist/activity-journal.js.map +1 -0
  381. package/dist/allowed-roots.d.ts +41 -0
  382. package/dist/allowed-roots.js +125 -3
  383. package/dist/allowed-roots.js.map +1 -1
  384. package/dist/codex/activity-session-log.d.ts +14 -0
  385. package/dist/codex/activity-session-log.js +206 -0
  386. package/dist/codex/activity-session-log.js.map +1 -0
  387. package/dist/codex/agent-tools.d.ts +23 -0
  388. package/dist/codex/agent-tools.js +1306 -0
  389. package/dist/codex/agent-tools.js.map +1 -0
  390. package/dist/codex/app-server-client.d.ts +79 -0
  391. package/dist/codex/app-server-client.js +593 -0
  392. package/dist/codex/app-server-client.js.map +1 -0
  393. package/dist/codex/app-server-registry.d.ts +407 -0
  394. package/dist/codex/app-server-registry.js +1493 -0
  395. package/dist/codex/app-server-registry.js.map +1 -0
  396. package/dist/codex/client-types.d.ts +115 -0
  397. package/dist/codex/client-types.js +2 -0
  398. package/dist/codex/client-types.js.map +1 -0
  399. package/dist/codex/protocol.d.ts +5375 -0
  400. package/dist/codex/protocol.js +614 -0
  401. package/dist/codex/protocol.js.map +1 -0
  402. package/dist/codex/session.d.ts +263 -0
  403. package/dist/codex/session.js +466 -0
  404. package/dist/codex/session.js.map +1 -0
  405. package/dist/config.d.ts +386 -23
  406. package/dist/config.js +184 -15
  407. package/dist/config.js.map +1 -1
  408. package/dist/context-builder/anchors.d.ts +1 -0
  409. package/dist/context-builder/anchors.js +3 -0
  410. package/dist/context-builder/anchors.js.map +1 -1
  411. package/dist/context-builder/bundle.d.ts +48 -2
  412. package/dist/context-builder/bundle.js +388 -2417
  413. package/dist/context-builder/bundle.js.map +1 -1
  414. package/dist/context-builder/codemap.d.ts +5 -0
  415. package/dist/context-builder/codemap.js +387 -13
  416. package/dist/context-builder/codemap.js.map +1 -1
  417. package/dist/context-builder/config.d.ts +1 -0
  418. package/dist/context-builder/config.js +12 -0
  419. package/dist/context-builder/config.js.map +1 -1
  420. package/dist/context-builder/context-run-catalog.d.ts +17 -0
  421. package/dist/context-builder/context-run-catalog.js +99 -0
  422. package/dist/context-builder/context-run-catalog.js.map +1 -0
  423. package/dist/context-builder/delegate-finalizer-effective.d.ts +33 -0
  424. package/dist/context-builder/delegate-finalizer-effective.js +82 -0
  425. package/dist/context-builder/delegate-finalizer-effective.js.map +1 -0
  426. package/dist/context-builder/delegate-packet.d.ts +55 -0
  427. package/dist/context-builder/delegate-packet.js +430 -74
  428. package/dist/context-builder/delegate-packet.js.map +1 -1
  429. package/dist/context-builder/delegate-reconstruction.d.ts +29 -0
  430. package/dist/context-builder/delegate-reconstruction.js +110 -41
  431. package/dist/context-builder/delegate-reconstruction.js.map +1 -1
  432. package/dist/context-builder/delegate-validation.d.ts +41 -1
  433. package/dist/context-builder/delegate-validation.js +237 -48
  434. package/dist/context-builder/delegate-validation.js.map +1 -1
  435. package/dist/context-builder/delegate.d.ts +11 -0
  436. package/dist/context-builder/delegate.js +210 -58
  437. package/dist/context-builder/delegate.js.map +1 -1
  438. package/dist/context-builder/diagnostics.d.ts +11 -2
  439. package/dist/context-builder/diagnostics.js +39 -6
  440. package/dist/context-builder/diagnostics.js.map +1 -1
  441. package/dist/context-builder/discovery-progress.d.ts +25 -0
  442. package/dist/context-builder/discovery-progress.js +64 -0
  443. package/dist/context-builder/discovery-progress.js.map +1 -0
  444. package/dist/context-builder/discovery-watchdog.d.ts +15 -0
  445. package/dist/context-builder/discovery-watchdog.js +39 -0
  446. package/dist/context-builder/discovery-watchdog.js.map +1 -0
  447. package/dist/context-builder/discovery.d.ts +36 -1
  448. package/dist/context-builder/discovery.js +584 -172
  449. package/dist/context-builder/discovery.js.map +1 -1
  450. package/dist/context-builder/external-gaps.d.ts +73 -0
  451. package/dist/context-builder/external-gaps.js +248 -0
  452. package/dist/context-builder/external-gaps.js.map +1 -0
  453. package/dist/context-builder/globs.d.ts +1 -0
  454. package/dist/context-builder/globs.js +25 -10
  455. package/dist/context-builder/globs.js.map +1 -1
  456. package/dist/context-builder/handler.d.ts +67 -2
  457. package/dist/context-builder/handler.js +1810 -2440
  458. package/dist/context-builder/handler.js.map +1 -1
  459. package/dist/context-builder/invocation-sidecar.d.ts +41 -0
  460. package/dist/context-builder/invocation-sidecar.js +189 -0
  461. package/dist/context-builder/invocation-sidecar.js.map +1 -0
  462. package/dist/context-builder/lifecycle-contract.d.ts +424 -0
  463. package/dist/context-builder/lifecycle-contract.js +523 -0
  464. package/dist/context-builder/lifecycle-contract.js.map +1 -0
  465. package/dist/context-builder/lifecycle-journal.d.ts +62 -0
  466. package/dist/context-builder/lifecycle-journal.js +88 -0
  467. package/dist/context-builder/lifecycle-journal.js.map +1 -0
  468. package/dist/context-builder/lifecycle-observer.d.ts +102 -0
  469. package/dist/context-builder/lifecycle-observer.js +258 -0
  470. package/dist/context-builder/lifecycle-observer.js.map +1 -0
  471. package/dist/context-builder/lifecycle-reconcile.d.ts +32 -0
  472. package/dist/context-builder/lifecycle-reconcile.js +191 -0
  473. package/dist/context-builder/lifecycle-reconcile.js.map +1 -0
  474. package/dist/context-builder/lifecycle-recovery.d.ts +2 -0
  475. package/dist/context-builder/lifecycle-recovery.js +14 -0
  476. package/dist/context-builder/lifecycle-recovery.js.map +1 -0
  477. package/dist/context-builder/mutation-lock.d.ts +32 -0
  478. package/dist/context-builder/mutation-lock.js +321 -0
  479. package/dist/context-builder/mutation-lock.js.map +1 -0
  480. package/dist/context-builder/path-signals.js +9 -5
  481. package/dist/context-builder/path-signals.js.map +1 -1
  482. package/dist/context-builder/progress.d.ts +3 -1
  483. package/dist/context-builder/progress.js +23 -0
  484. package/dist/context-builder/progress.js.map +1 -1
  485. package/dist/context-builder/receipt.d.ts +6 -4
  486. package/dist/context-builder/receipt.js +12 -1
  487. package/dist/context-builder/receipt.js.map +1 -1
  488. package/dist/context-builder/refine-handler.d.ts +14 -0
  489. package/dist/context-builder/refine-handler.js +790 -0
  490. package/dist/context-builder/refine-handler.js.map +1 -0
  491. package/dist/context-builder/review-coverage.d.ts +116 -0
  492. package/dist/context-builder/review-coverage.js +544 -0
  493. package/dist/context-builder/review-coverage.js.map +1 -0
  494. package/dist/context-builder/schema.d.ts +315 -2
  495. package/dist/context-builder/schema.js +133 -7
  496. package/dist/context-builder/schema.js.map +1 -1
  497. package/dist/context-builder/secrets.d.ts +59 -0
  498. package/dist/context-builder/secrets.js +2255 -44
  499. package/dist/context-builder/secrets.js.map +1 -1
  500. package/dist/context-builder/selection.d.ts +7 -3
  501. package/dist/context-builder/selection.js +200 -738
  502. package/dist/context-builder/selection.js.map +1 -1
  503. package/dist/context-builder/session-log-identity.d.ts +1 -0
  504. package/dist/context-builder/session-log-identity.js +66 -0
  505. package/dist/context-builder/session-log-identity.js.map +1 -0
  506. package/dist/context-builder/slice-range-math.d.ts +16 -0
  507. package/dist/context-builder/slice-range-math.js +137 -0
  508. package/dist/context-builder/slice-range-math.js.map +1 -0
  509. package/dist/context-builder/status.d.ts +23 -2
  510. package/dist/context-builder/status.js +60 -4
  511. package/dist/context-builder/status.js.map +1 -1
  512. package/dist/context-builder/storage.d.ts +59 -2
  513. package/dist/context-builder/storage.js +500 -168
  514. package/dist/context-builder/storage.js.map +1 -1
  515. package/dist/context-builder/token-estimate.d.ts +13 -2
  516. package/dist/context-builder/token-estimate.js +77 -4
  517. package/dist/context-builder/token-estimate.js.map +1 -1
  518. package/dist/context-builder/versions.d.ts +44 -0
  519. package/dist/context-builder/versions.js +45 -0
  520. package/dist/context-builder/versions.js.map +1 -0
  521. package/dist/context-builder/workflow-runner.d.ts +75 -0
  522. package/dist/context-builder/workflow-runner.js +1241 -0
  523. package/dist/context-builder/workflow-runner.js.map +1 -0
  524. package/dist/context-builder/write-watchdog.d.ts +14 -0
  525. package/dist/context-builder/write-watchdog.js +38 -0
  526. package/dist/context-builder/write-watchdog.js.map +1 -0
  527. package/dist/dashboard-adapter-catalog.d.ts +9 -0
  528. package/dist/dashboard-adapter-catalog.js +53 -0
  529. package/dist/dashboard-adapter-catalog.js.map +1 -0
  530. package/dist/dashboard-cli.d.ts +81 -0
  531. package/dist/dashboard-cli.js +623 -0
  532. package/dist/dashboard-cli.js.map +1 -0
  533. package/dist/dashboard-companion/client.d.ts +37 -0
  534. package/dist/dashboard-companion/client.js +229 -0
  535. package/dist/dashboard-companion/client.js.map +1 -0
  536. package/dist/dashboard-companion/config.d.ts +8 -0
  537. package/dist/dashboard-companion/config.js +52 -0
  538. package/dist/dashboard-companion/config.js.map +1 -0
  539. package/dist/dashboard-companion/http-proxy.d.ts +10 -0
  540. package/dist/dashboard-companion/http-proxy.js +234 -0
  541. package/dist/dashboard-companion/http-proxy.js.map +1 -0
  542. package/dist/dashboard-companion/protocol.d.ts +80 -0
  543. package/dist/dashboard-companion/protocol.js +458 -0
  544. package/dist/dashboard-companion/protocol.js.map +1 -0
  545. package/dist/dashboard-companion/standalone-assets.d.ts +12 -0
  546. package/dist/dashboard-companion/standalone-assets.js +72 -0
  547. package/dist/dashboard-companion/standalone-assets.js.map +1 -0
  548. package/dist/dashboard-companion/standalone-entry.d.ts +1 -0
  549. package/dist/dashboard-companion/standalone-entry.js +17 -0
  550. package/dist/dashboard-companion/standalone-entry.js.map +1 -0
  551. package/dist/dashboard-gateway/config.d.ts +9 -0
  552. package/dist/dashboard-gateway/config.js +44 -0
  553. package/dist/dashboard-gateway/config.js.map +1 -0
  554. package/dist/dashboard-gateway/index.d.ts +12 -0
  555. package/dist/dashboard-gateway/index.js +786 -0
  556. package/dist/dashboard-gateway/index.js.map +1 -0
  557. package/dist/dashboard-gateway/main.d.ts +1 -0
  558. package/dist/dashboard-gateway/main.js +25 -0
  559. package/dist/dashboard-gateway/main.js.map +1 -0
  560. package/dist/dashboard-pairing-token.d.ts +1 -0
  561. package/dist/dashboard-pairing-token.js +5 -0
  562. package/dist/dashboard-pairing-token.js.map +1 -0
  563. package/dist/elaris/client.d.ts +73 -0
  564. package/dist/elaris/client.js +825 -0
  565. package/dist/elaris/client.js.map +1 -0
  566. package/dist/elaris/config.d.ts +18 -0
  567. package/dist/elaris/config.js +75 -0
  568. package/dist/elaris/config.js.map +1 -0
  569. package/dist/elaris/errors.d.ts +41 -0
  570. package/dist/elaris/errors.js +205 -0
  571. package/dist/elaris/errors.js.map +1 -0
  572. package/dist/elaris/github-repo.d.ts +18 -0
  573. package/dist/elaris/github-repo.js +89 -0
  574. package/dist/elaris/github-repo.js.map +1 -0
  575. package/dist/elaris/index.d.ts +10 -0
  576. package/dist/elaris/index.js +11 -0
  577. package/dist/elaris/index.js.map +1 -0
  578. package/dist/elaris/redact.d.ts +89 -0
  579. package/dist/elaris/redact.js +423 -0
  580. package/dist/elaris/redact.js.map +1 -0
  581. package/dist/elaris/run-id.d.ts +5 -0
  582. package/dist/elaris/run-id.js +20 -0
  583. package/dist/elaris/run-id.js.map +1 -0
  584. package/dist/elaris/status.d.ts +45 -0
  585. package/dist/elaris/status.js +122 -0
  586. package/dist/elaris/status.js.map +1 -0
  587. package/dist/elaris/tool-schemas.d.ts +314 -0
  588. package/dist/elaris/tool-schemas.js +208 -0
  589. package/dist/elaris/tool-schemas.js.map +1 -0
  590. package/dist/elaris/tools.d.ts +73 -0
  591. package/dist/elaris/tools.js +1065 -0
  592. package/dist/elaris/tools.js.map +1 -0
  593. package/dist/elaris/types.d.ts +1541 -0
  594. package/dist/elaris/types.js +252 -0
  595. package/dist/elaris/types.js.map +1 -0
  596. package/dist/errors.d.ts +16 -0
  597. package/dist/errors.js +19 -0
  598. package/dist/errors.js.map +1 -1
  599. package/dist/handler.d.ts +4 -0
  600. package/dist/handler.js +15 -2
  601. package/dist/handler.js.map +1 -1
  602. package/dist/index.d.ts +20 -2
  603. package/dist/index.js +154 -6
  604. package/dist/index.js.map +1 -1
  605. package/dist/local-clink-backend.d.ts +3 -0
  606. package/dist/local-clink-backend.js +4 -0
  607. package/dist/local-clink-backend.js.map +1 -1
  608. package/dist/logger.d.ts +1 -1
  609. package/dist/logger.js +18 -3
  610. package/dist/logger.js.map +1 -1
  611. package/dist/package-info.d.ts +2 -0
  612. package/dist/package-info.js +18 -0
  613. package/dist/package-info.js.map +1 -0
  614. package/dist/parsers/agy-stream-json.d.ts +14 -0
  615. package/dist/parsers/agy-stream-json.js +172 -0
  616. package/dist/parsers/agy-stream-json.js.map +1 -0
  617. package/dist/parsers/codex-jsonl.js +48 -3
  618. package/dist/parsers/codex-jsonl.js.map +1 -1
  619. package/dist/parsers/extract.d.ts +10 -1
  620. package/dist/parsers/extract.js +16 -4
  621. package/dist/parsers/extract.js.map +1 -1
  622. package/dist/parsers/observed-invocation.d.ts +20 -0
  623. package/dist/parsers/observed-invocation.js +42 -0
  624. package/dist/parsers/observed-invocation.js.map +1 -0
  625. package/dist/pipeline.d.ts +17 -0
  626. package/dist/pipeline.js +181 -10
  627. package/dist/pipeline.js.map +1 -1
  628. package/dist/progress-report/lock.d.ts +74 -0
  629. package/dist/progress-report/lock.js +343 -0
  630. package/dist/progress-report/lock.js.map +1 -0
  631. package/dist/progress-report/schema.d.ts +808 -0
  632. package/dist/progress-report/schema.js +119 -0
  633. package/dist/progress-report/schema.js.map +1 -0
  634. package/dist/progress-report/store.d.ts +66 -0
  635. package/dist/progress-report/store.js +766 -0
  636. package/dist/progress-report/store.js.map +1 -0
  637. package/dist/progress-report/tools.d.ts +20 -0
  638. package/dist/progress-report/tools.js +141 -0
  639. package/dist/progress-report/tools.js.map +1 -0
  640. package/dist/prompt-mode.d.ts +1 -1
  641. package/dist/prompt-mode.js +7 -2
  642. package/dist/prompt-mode.js.map +1 -1
  643. package/dist/run-dir.d.ts +24 -0
  644. package/dist/run-dir.js +201 -2
  645. package/dist/run-dir.js.map +1 -1
  646. package/dist/runner.d.ts +20 -0
  647. package/dist/runner.js +192 -16
  648. package/dist/runner.js.map +1 -1
  649. package/dist/safety.d.ts +54 -4
  650. package/dist/safety.js +186 -5
  651. package/dist/safety.js.map +1 -1
  652. package/dist/schema.d.ts +15 -7
  653. package/dist/schema.js +20 -0
  654. package/dist/schema.js.map +1 -1
  655. package/dist/server.d.ts +7 -1
  656. package/dist/server.js +451 -23
  657. package/dist/server.js.map +1 -1
  658. package/dist/session-log-stream.d.ts +18 -0
  659. package/dist/session-log-stream.js +566 -0
  660. package/dist/session-log-stream.js.map +1 -0
  661. package/dist/stdio-activity.d.ts +28 -0
  662. package/dist/stdio-activity.js +72 -0
  663. package/dist/stdio-activity.js.map +1 -0
  664. package/package.json +47 -5
  665. package/conf/adapters/gemini.json +0 -44
  666. package/conf/adapters/hapi/gemini.json +0 -47
  667. package/dist/parsers/gemini-json.d.ts +0 -2
  668. package/dist/parsers/gemini-json.js +0 -72
  669. package/dist/parsers/gemini-json.js.map +0 -1
@@ -0,0 +1,1241 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { realpathSync, statSync } from "node:fs";
3
+ import { copyFile, link, lstat, mkdir, open, readFile, realpath, rename, rm, utimes, } from "node:fs/promises";
4
+ import { isAbsolute, join, relative, resolve } from "node:path";
5
+ // ---------------------------------------------------------------------------
6
+ // Deep `clinkx-workflows/dist` imports (one-way dependency, build-order coupled)
7
+ //
8
+ // The next four imports pull cache-key, preflight-contract, config, and
9
+ // workspace-signature helpers from the COMPILED output of the sibling
10
+ // `clinkx-workflows` package rather than from a published entry point. This is
11
+ // deliberate and safe:
12
+ //
13
+ // - The dependency arrow points one way: root -> clinkx-workflows. The
14
+ // workflows package defines only the `ContextBuilderRunner` callback
15
+ // interface and never statically imports the root `context-builder/`
16
+ // modules, so there is no import cycle. See docs/architecture.md, "Module
17
+ // boundary (no dependency cycle)".
18
+ // - `clinkx-workflows` is a separate tsc project with no package `exports`
19
+ // map; its public runtime surface is its `dist/*.js` files. Importing its
20
+ // source `.ts` would violate the NodeNext + `.js`-extension ESM contract.
21
+ //
22
+ // BUILD ORDER: `clinkx-workflows/dist` MUST be built before the root package is
23
+ // built or run. `npm run build:all` enforces this (clinkx-workflows first, then
24
+ // root). A bare `npm run build` assumes dist already exists; a missing dist
25
+ // surfaces as ERR_MODULE_NOT_FOUND at import time, not a compile error.
26
+ // ---------------------------------------------------------------------------
27
+ import { computeCacheKey, computeInputsHash, deriveWfctxId, } from "../../clinkx-workflows/dist/context-cache-key.js";
28
+ import { resolveWorkspaceRoot as resolveWorkflowWorkspaceRoot } from "../../clinkx-workflows/dist/config.js";
29
+ import { createSessionLogGeneration, readSessionLogGeneration, } from "../../clinkx-workflows/dist/dashboard/session-log-identity.js";
30
+ import { getSignatureCoveredPaths, workspaceSignature as computeWorkspaceSignature, } from "../../clinkx-workflows/dist/workspace-signature.js";
31
+ import { isArtifactOnlyAllowedRootEntry, isPathWithinAllowedRoots, } from "../allowed-roots.js";
32
+ import { CancellationError, ExecutionError, InvalidParamsError } from "../errors.js";
33
+ import { logger } from "../logger.js";
34
+ import { getCurrentAllowedRoots } from "../paths.js";
35
+ import { CONTEXT_BUILDER_RENDERER_VERSION } from "./bundle.js";
36
+ import { CONTEXT_DELEGATE_PROMPT_VERSION, CONTEXT_DISCOVERY_ALGORITHM_VERSION, } from "./versions.js";
37
+ import { getSharedContextBuilderSemaphore, resolveContextBuilderRunsDir, } from "./config.js";
38
+ import { handleContextBuilder } from "./handler.js";
39
+ import { CONTEXT_BUILDER_INVOCATION_AUDIT_FILENAME, isContextBuilderInvocationAuditSidecarProvenInvalid, readContextBuilderInvocationAuditSidecar, } from "./invocation-sidecar.js";
40
+ import { CONTEXT_BUILDER_INTENT_PROFILE_DEFAULTS, CONTEXT_BUILDER_INTENT_PROFILES, resolveContextBuilderAdapterBudgetInput, } from "./schema.js";
41
+ import { assertNoHighConfidenceSecretsInTask, resolveAllowSecrets, } from "./secrets.js";
42
+ import { CONTEXT_BUILDER_DELEGATE_SCHEMA_VERSION, CONTEXT_BUILDER_NO_DELEGATE_SCHEMA_VERSION, createContextBuilderReceipt, } from "./receipt.js";
43
+ import { notEvaluatedCoverageReport, } from "./review-coverage.js";
44
+ import { ContextBuilderActiveRunClaimConflictError, ContextBuilderAncillaryPromotionError, ContextBuilderCommittedRunChangedError, ContextBuilderRunClaimConflictError, evictWorkflowContextRuns, isContextBuilderRunCommitted, resolveContextBuilderRunPaths, withCommittedContextBuilderRunMutationLease, withPromotedContextBuilderRun, } from "./storage.js";
45
+ import { ContextBuilderLifecycleController, ContextBuilderLifecycleObserverError, } from "./lifecycle-observer.js";
46
+ export function createWorkflowContextBuilderRunner(options = {}) {
47
+ const cb = options.handleContextBuilder ?? handleContextBuilder;
48
+ // Default to the SHARED process-wide context_builder gate so workflow
49
+ // preflight, standalone context_builder, and refine_context_run all contend
50
+ // for one CLINKX_CONTEXT_BUILDER_MAX_CONCURRENT permit pool. Tests may inject
51
+ // their own semaphore for isolation.
52
+ const semaphore = options.semaphore ?? getSharedContextBuilderSemaphore();
53
+ const runIdFactory = options.runIdFactory ?? generateWorkflowPreflightRunId;
54
+ const workspaceRootResolver = options.resolveWorkspaceRoot ?? resolveWorkflowWorkspaceRoot;
55
+ const workspaceSignature = options.workspaceSignature ?? computeWorkspaceSignature;
56
+ const signatureCoveredPaths = options.getSignatureCoveredPaths ?? getSignatureCoveredPaths;
57
+ const rendererVersion = options.rendererVersion ?? CONTEXT_BUILDER_RENDERER_VERSION;
58
+ const discoveryAlgorithmVersion = options.discoveryAlgorithmVersion ?? CONTEXT_DISCOVERY_ALGORITHM_VERSION;
59
+ const delegatePromptVersion = options.delegatePromptVersion ?? CONTEXT_DELEGATE_PROMPT_VERSION;
60
+ const registry = options.registry;
61
+ const syncInvocationSnapshotDirectory = options.syncInvocationSnapshotDirectory ?? syncDirectoryEntry;
62
+ return {
63
+ assertRootsAllowed(roots) {
64
+ assertExplicitRootsWithinAllowed(roots);
65
+ },
66
+ assertTaskSecretsAllowed(variables) {
67
+ const rawFlag = variables["cb_allow_secrets"];
68
+ const explicit = typeof rawFlag === "boolean" ? rawFlag : undefined;
69
+ if (resolveAllowSecrets(explicit)) {
70
+ return;
71
+ }
72
+ for (const key of ["cb_task", "user_request"]) {
73
+ const value = variables[key];
74
+ if (typeof value === "string" && value.length > 0) {
75
+ assertNoHighConfidenceSecretsInTask(value);
76
+ }
77
+ }
78
+ },
79
+ async runOrReuse(input, opts) {
80
+ let lifecycle;
81
+ try {
82
+ throwIfAborted(opts.signal);
83
+ const mappedInput = await mapPreflightContextInput(input, {
84
+ resolveWorkspaceRoot: workspaceRootResolver,
85
+ });
86
+ const mapped = input.context_budget_adapter == null ||
87
+ input.context_budget_adapter.trim() === ""
88
+ ? mappedInput
89
+ : {
90
+ ...mappedInput,
91
+ budget: resolveContextBuilderAdapterBudgetInput({
92
+ adapterDefaults: resolveAdapterBudgetDefaults(registry, input.context_budget_adapter),
93
+ profile: mappedInput.profile,
94
+ explicit: mappedInput.budget,
95
+ }),
96
+ };
97
+ const lifecycleInjection = options.lifecycleFactory?.(input);
98
+ lifecycle = lifecycleInjection == null
99
+ ? undefined
100
+ : new ContextBuilderLifecycleController({
101
+ operationKind: "workflow_preflight",
102
+ execution: workflowLifecycleExecutionConfig(mapped),
103
+ observer: lifecycleInjection.observer,
104
+ ...(lifecycleInjection.origin == null
105
+ ? {}
106
+ : { origin: lifecycleInjection.origin }),
107
+ ...(options.lifecycleNow == null
108
+ ? {}
109
+ : { now: options.lifecycleNow }),
110
+ });
111
+ await lifecycle?.transition("resolving");
112
+ // The controller has now minted the preflight operation id
113
+ // (lifecycle.contextRunId). Pair it with a generation sidecar created under
114
+ // the workflow run dir so the dashboard can later locate the preflight's
115
+ // session-log subtree. Only the injected-lifecycle (workflow) path builds
116
+ // this; the standalone path derives its own identity from its journal.
117
+ const preflightSessionLogContext = lifecycle == null
118
+ ? undefined
119
+ : await resolvePreflightSessionLogContext(input.runDir, lifecycle.contextRunId);
120
+ const cacheInput = {
121
+ ...mapped,
122
+ roots: await normalizeCacheRoots(mapped.roots),
123
+ };
124
+ const includeSelectedContext = input.includeSelectedContext === true;
125
+ const effectiveSchemaVersion = mapped.delegate.enabled === true
126
+ ? CONTEXT_BUILDER_DELEGATE_SCHEMA_VERSION
127
+ : CONTEXT_BUILDER_NO_DELEGATE_SCHEMA_VERSION;
128
+ const cacheSchemaVersion = options.cbSchemaVersion ?? effectiveSchemaVersion;
129
+ const runsDir = await resolveContextBuilderRunsDir(options.runsDir);
130
+ let preSig = await workspaceSignature(mapped.roots);
131
+ throwIfAborted(opts.signal);
132
+ let cache = deriveCacheCoordinates(cacheInput, preSig, runsDir, {
133
+ rendererVersion,
134
+ cbSchemaVersion: cacheSchemaVersion,
135
+ discoveryAlgorithmVersion,
136
+ delegatePromptVersion,
137
+ });
138
+ let cacheReason = "cache_miss";
139
+ if (await isContextBuilderRunCommitted(cache.targetStorage.runDir)) {
140
+ const postSig = await workspaceSignature(mapped.roots);
141
+ throwIfAborted(opts.signal);
142
+ if (postSig === preSig) {
143
+ let hit;
144
+ try {
145
+ hit = await withCommittedContextBuilderRunMutationLease(cache.targetStorage, async () => {
146
+ // Refresh directory mtime so LRU eviction treats this as recently used.
147
+ try {
148
+ const now = new Date();
149
+ await utimes(cache.targetStorage.runDir, now, now);
150
+ }
151
+ catch {
152
+ // best-effort — a hit must not fail because utimes failed
153
+ }
154
+ return await synthesizePreflightResultFromCommittedRun({
155
+ storage: cache.targetStorage,
156
+ runDir: input.runDir,
157
+ keyPrefix: cache.keyPrefix,
158
+ schemaVersion: effectiveSchemaVersion,
159
+ budgetCaps: mapped.budget,
160
+ includeSelectedContext,
161
+ syncInvocationSnapshotDirectory,
162
+ ...(lifecycle == null ? {} : { lifecycle }),
163
+ });
164
+ });
165
+ }
166
+ catch (error) {
167
+ if (!(error instanceof ContextBuilderCommittedRunChangedError)) {
168
+ throw error;
169
+ }
170
+ }
171
+ if (hit !== undefined) {
172
+ await lifecycle?.complete(workflowLifecycleTerminalStatus(hit), {
173
+ artifactRunId: hit.source_run_id,
174
+ ...workflowResultLifecyclePatch(hit, lifecycle, true),
175
+ });
176
+ return hit;
177
+ }
178
+ cacheReason = "cache_stale";
179
+ }
180
+ else {
181
+ cacheReason = "cache_stale";
182
+ preSig = postSig;
183
+ cache = deriveCacheCoordinates(cacheInput, preSig, runsDir, {
184
+ rendererVersion,
185
+ cbSchemaVersion: cacheSchemaVersion,
186
+ discoveryAlgorithmVersion,
187
+ delegatePromptVersion,
188
+ });
189
+ }
190
+ }
191
+ await lifecycle?.transition("cache_lookup", {
192
+ cache: {
193
+ lookup: "miss",
194
+ write: "not_attempted",
195
+ reason_code: cacheReason,
196
+ },
197
+ reasonCodes: [cacheReason],
198
+ });
199
+ const tempId = runIdFactory();
200
+ const tempInput = { ...mapped, run_id: tempId };
201
+ const tempStorage = resolveContextBuilderRunPaths(runsDir, tempId);
202
+ // The id of the run this call will return as its live source. Eviction in
203
+ // the finally must protect it so small/zero retention bounds cannot delete
204
+ // the run whose source_artifact_dir we are about to hand back.
205
+ let liveSourceRunId = tempId;
206
+ const consumeCommittedRun = async (response, storageOps) => {
207
+ throwIfAborted(opts.signal);
208
+ const receipt = parseReceiptResponse(response);
209
+ return await withCommittedContextBuilderRunMutationLease(tempStorage, async (sourceOps) => {
210
+ const tempManifest = await readManifest(tempStorage.manifestJson, sourceOps);
211
+ // Degraded fallback selections (delegate failure_policy:"fallback") must
212
+ // NEVER enter the shared wfctx cache: a cached fallback would be replayed
213
+ // for a later fail-closed failure_policy:"fail" request (silently
214
+ // succeeding instead of failing) and would mask genuine delegated
215
+ // successes. Not caching also lets a later identical request retry
216
+ // delegation rather than reusing a stale degraded bundle. The same
217
+ // holds for a delegated selection that proceeded with external
218
+ // evidence gaps (isDelegateDegradedForCache). The manifest is the
219
+ // authoritative persisted source; fall back to the receipt.
220
+ const delegateDegraded = isDelegateDegradedForCache(tempManifest.delegate) ||
221
+ isDelegateDegradedForCache(receipt.delegate);
222
+ const selectedPaths = await resolveSelectedContextPaths(tempManifest, mapped.roots);
223
+ const gate = await evaluatePostCbPromotionGate({
224
+ roots: mapped.roots,
225
+ selectedPaths,
226
+ workspaceSignature,
227
+ signatureCoveredPaths,
228
+ });
229
+ throwIfAborted(opts.signal);
230
+ if (!delegateDegraded
231
+ && gate?.selectedFilesCovered === true
232
+ && gate.postSig === preSig) {
233
+ try {
234
+ await lifecycle?.transition("materializing");
235
+ return await withPromotedContextBuilderRun(tempStorage.runDir, cache.wfctxId, async (promoted, targetOps) => {
236
+ // Promotion completed under source→target locks. Keep the target
237
+ // lease through this authoritative manifest read and final copy.
238
+ liveSourceRunId = cache.wfctxId;
239
+ const promotedManifest = await readManifest(promoted.manifestJson, targetOps);
240
+ const resultBeforeMaterialization = buildPreflightResult({
241
+ receipt: createReceiptFromManifest(promotedManifest, promoted),
242
+ sourceRunId: cache.wfctxId,
243
+ sourceArtifactDir: promoted.runDir,
244
+ cache: {
245
+ hit: false,
246
+ write: true,
247
+ target_id: cache.wfctxId,
248
+ key_prefix: cache.keyPrefix,
249
+ },
250
+ copiedPaths: [],
251
+ schemaVersion: effectiveSchemaVersion,
252
+ observability: preflightObservabilityFromManifest(tempManifest, mapped.budget),
253
+ coverage: coverageFromManifest(tempManifest),
254
+ });
255
+ const copiedPaths = await materializeWorkflowContext({
256
+ artifacts: promotedManifest.artifacts,
257
+ sourceRunDir: promoted.runDir,
258
+ workflowRunDir: input.runDir,
259
+ includeSelectedContext,
260
+ syncInvocationSnapshotDirectory,
261
+ ...(lifecycle == null
262
+ ? {}
263
+ : { contextRunId: lifecycle.contextRunId }),
264
+ ...(lifecycle == null
265
+ ? {}
266
+ : {
267
+ beforeManifestCommit: async () => {
268
+ await lifecycle?.transition("committing", {
269
+ artifactRunId: resultBeforeMaterialization.source_run_id,
270
+ cache: {
271
+ lookup: "miss",
272
+ write: "written",
273
+ reason_code: cacheReason,
274
+ },
275
+ ...workflowResultLifecyclePatch(resultBeforeMaterialization, lifecycle),
276
+ });
277
+ },
278
+ }),
279
+ });
280
+ const result = {
281
+ ...resultBeforeMaterialization,
282
+ copied_paths: copiedPaths,
283
+ };
284
+ await lifecycle?.complete(workflowLifecycleTerminalStatus(result), {
285
+ artifactRunId: result.source_run_id,
286
+ ...workflowResultLifecyclePatch(result, lifecycle),
287
+ });
288
+ return result;
289
+ }, sourceOps);
290
+ }
291
+ catch (error) {
292
+ if (error instanceof ContextBuilderAncillaryPromotionError) {
293
+ logger.warn({
294
+ reason_code: error.reasonCode,
295
+ source_run_id: tempId,
296
+ }, "workflow context_builder cache promotion skipped because invocation audit ancillary promotion failed");
297
+ }
298
+ else if (!isPromoteClaimConflict(error)) {
299
+ throw error;
300
+ }
301
+ }
302
+ }
303
+ // Non-promote (or promote-claim-conflict) path: copy from the surviving
304
+ // temp run, which is the authoritative source for the returned id.
305
+ await lifecycle?.transition("materializing");
306
+ const resultBeforeMaterialization = buildPreflightResult({
307
+ receipt: createReceiptFromManifest(tempManifest, tempStorage),
308
+ sourceRunId: tempId,
309
+ sourceArtifactDir: tempStorage.runDir,
310
+ cache: {
311
+ hit: false,
312
+ write: false,
313
+ target_id: null,
314
+ key_prefix: cache.keyPrefix,
315
+ },
316
+ copiedPaths: [],
317
+ schemaVersion: effectiveSchemaVersion,
318
+ observability: preflightObservabilityFromManifest(tempManifest, mapped.budget),
319
+ coverage: coverageFromManifest(tempManifest),
320
+ });
321
+ const copiedPaths = await materializeWorkflowContext({
322
+ artifacts: tempManifest.artifacts,
323
+ sourceRunDir: tempStorage.runDir,
324
+ workflowRunDir: input.runDir,
325
+ includeSelectedContext,
326
+ syncInvocationSnapshotDirectory,
327
+ ...(lifecycle == null
328
+ ? {}
329
+ : { contextRunId: lifecycle.contextRunId }),
330
+ ...(lifecycle == null
331
+ ? {}
332
+ : {
333
+ beforeManifestCommit: async () => {
334
+ await lifecycle?.transition("committing", {
335
+ artifactRunId: resultBeforeMaterialization.source_run_id,
336
+ cache: {
337
+ lookup: "miss",
338
+ write: "skipped",
339
+ reason_code: cacheReason,
340
+ },
341
+ ...workflowResultLifecyclePatch(resultBeforeMaterialization, lifecycle),
342
+ });
343
+ },
344
+ }),
345
+ });
346
+ const result = {
347
+ ...resultBeforeMaterialization,
348
+ copied_paths: copiedPaths,
349
+ };
350
+ await lifecycle?.complete(workflowLifecycleTerminalStatus(result), {
351
+ artifactRunId: result.source_run_id,
352
+ ...workflowResultLifecyclePatch(result, lifecycle),
353
+ });
354
+ return result;
355
+ }, storageOps);
356
+ };
357
+ let retainedResult;
358
+ try {
359
+ const response = await cb(tempInput, {
360
+ runsDir,
361
+ semaphore,
362
+ ...(registry == null ? {} : { registry }),
363
+ ...(input.allowRootWideDiscovery == null
364
+ ? {}
365
+ : { allowRootWideDiscovery: input.allowRootWideDiscovery }),
366
+ ...(opts.signal == null ? {} : { signal: opts.signal }),
367
+ ...(lifecycle == null ? {} : { lifecycleController: lifecycle }),
368
+ ...(preflightSessionLogContext == null
369
+ ? {}
370
+ : { sessionLogContext: preflightSessionLogContext }),
371
+ retainCommittedRun: async (committedResponse, committedStorage, leasedOps) => {
372
+ if (committedStorage.runId !== tempStorage.runId
373
+ || committedStorage.runDir !== tempStorage.runDir) {
374
+ throw new ExecutionError("context_builder retained an unexpected workflow temp run");
375
+ }
376
+ retainedResult = await consumeCommittedRun(committedResponse, leasedOps);
377
+ },
378
+ });
379
+ if (retainedResult !== undefined) {
380
+ return retainedResult;
381
+ }
382
+ return await consumeCommittedRun(response);
383
+ }
384
+ finally {
385
+ // Best-effort, prefix-scoped/TTL-guarded eviction on every completed
386
+ // MISS path (promote and non-promote). The active source run of this
387
+ // call is protected so zero/small retention bounds cannot self-delete
388
+ // the run whose source_artifact_dir we just returned.
389
+ await evictWorkflowContextRuns(runsDir, {
390
+ protectedRunIds: [liveSourceRunId],
391
+ })
392
+ .then((eviction) => {
393
+ if (eviction.failed > 0) {
394
+ logger.warn({ runsDir, eviction }, "workflow context_builder cache eviction had delete failures");
395
+ }
396
+ })
397
+ .catch((err) => {
398
+ logger.warn({ err, runsDir }, "workflow context_builder cache eviction failed");
399
+ });
400
+ }
401
+ }
402
+ catch (error) {
403
+ if (lifecycle != null && !(error instanceof ContextBuilderLifecycleObserverError)) {
404
+ const cancelled = error instanceof CancellationError || opts.signal?.aborted === true;
405
+ const delegateFailed = workflowDelegateExecutionActive(lifecycle);
406
+ await lifecycle.fail(cancelled ? "cancelled" : "failed", {
407
+ ...workflowTerminalExecutionPatch(lifecycle, cancelled),
408
+ reasonCodes: [
409
+ cancelled
410
+ ? "operation_cancelled"
411
+ : delegateFailed
412
+ ? "delegate_failed"
413
+ : "internal_failure",
414
+ ],
415
+ ...(!cancelled && delegateFailed
416
+ ? {
417
+ fallback: {
418
+ status: "failed",
419
+ reason_code: "delegate_failed",
420
+ },
421
+ }
422
+ : {}),
423
+ });
424
+ }
425
+ // Rethrow the ORIGINAL error object, never a wrapper: markers set by
426
+ // the handler (e.g. ExecutionError.failureClass:"transient" on a
427
+ // delegate timeout) must reach the workflow engine's failure
428
+ // classifier intact.
429
+ throw error;
430
+ }
431
+ },
432
+ };
433
+ }
434
+ /**
435
+ * Subdirectory of the workflow run dir holding operation-scoped preflight
436
+ * metadata: the session-log generation and immutable invocation snapshots.
437
+ */
438
+ const PREFLIGHT_SESSION_LOG_DIR = ".context-preflight";
439
+ async function materializeWorkflowContext(input) {
440
+ const copiedPaths = await copyBundleArtifactsIntoRun(input.artifacts, input.workflowRunDir, {
441
+ includeSelectedContext: input.includeSelectedContext,
442
+ ...(input.beforeManifestCommit == null
443
+ ? {}
444
+ : { beforeManifestCommit: input.beforeManifestCommit }),
445
+ });
446
+ if (input.contextRunId !== undefined) {
447
+ await snapshotWorkflowInvocationAudit({
448
+ sourceRunDir: input.sourceRunDir,
449
+ workflowRunDir: input.workflowRunDir,
450
+ contextRunId: input.contextRunId,
451
+ syncInvocationSnapshotDirectory: input.syncInvocationSnapshotDirectory,
452
+ });
453
+ }
454
+ return copiedPaths;
455
+ }
456
+ async function snapshotWorkflowInvocationAudit(input) {
457
+ let source;
458
+ try {
459
+ source = await readContextBuilderInvocationAuditSidecar(input.sourceRunDir);
460
+ }
461
+ catch (error) {
462
+ logger.warn({ err: error, source_artifact_dir: input.sourceRunDir }, "workflow context_builder invocation audit snapshot source rejected");
463
+ return;
464
+ }
465
+ if (source === undefined)
466
+ return;
467
+ const workflowRunRoot = await realpath(input.workflowRunDir);
468
+ const preflightDir = await admitExactWorkflowDirectory(workflowRunRoot, PREFLIGHT_SESSION_LOG_DIR, "workflow context_builder invocation audit snapshot directory");
469
+ const admittedSnapshotDir = await admitExactWorkflowDirectory(preflightDir, input.contextRunId, "workflow context_builder invocation audit snapshot directory");
470
+ assertContainedPath(workflowRunRoot, admittedSnapshotDir, "workflow context_builder invocation audit snapshot escaped the workflow run");
471
+ const target = join(admittedSnapshotDir, CONTEXT_BUILDER_INVOCATION_AUDIT_FILENAME);
472
+ const temp = join(admittedSnapshotDir, `.${CONTEXT_BUILDER_INVOCATION_AUDIT_FILENAME}.${process.pid}.${randomUUID()}.tmp`);
473
+ let ownsTemp = false;
474
+ let publicationAccepted = false;
475
+ try {
476
+ let handle;
477
+ try {
478
+ handle = await open(temp, "wx", 0o600);
479
+ ownsTemp = true;
480
+ await handle.writeFile(source.serialized, "utf8");
481
+ await handle.chmod(0o600);
482
+ await handle.sync();
483
+ }
484
+ finally {
485
+ await handle?.close();
486
+ }
487
+ try {
488
+ await link(temp, target);
489
+ }
490
+ catch (error) {
491
+ if (!isNodeError(error) || error.code !== "EEXIST")
492
+ throw error;
493
+ let incumbent;
494
+ try {
495
+ incumbent = await readContextBuilderInvocationAuditSidecar(admittedSnapshotDir);
496
+ }
497
+ catch (error) {
498
+ if (!isContextBuilderInvocationAuditSidecarProvenInvalid(error)) {
499
+ throw error;
500
+ }
501
+ logger.warn({ err: error, incumbent_path: target }, "workflow context_builder invocation audit snapshot incumbent rejected; preserving existing entry");
502
+ return;
503
+ }
504
+ if (incumbent?.serialized !== source.serialized) {
505
+ throw new ExecutionError("workflow context_builder invocation audit snapshot conflicts with existing bytes");
506
+ }
507
+ }
508
+ publicationAccepted = true;
509
+ }
510
+ finally {
511
+ if (ownsTemp) {
512
+ try {
513
+ await rm(temp, { force: true });
514
+ }
515
+ catch (error) {
516
+ logger.warn({ err: error, temporary_path: temp }, "workflow context_builder invocation audit snapshot temp cleanup failed");
517
+ }
518
+ }
519
+ if (publicationAccepted) {
520
+ await syncSnapshotDirectoriesBestEffort([admittedSnapshotDir, preflightDir, workflowRunRoot], input.syncInvocationSnapshotDirectory);
521
+ }
522
+ }
523
+ }
524
+ async function syncDirectoryEntry(path) {
525
+ const handle = await open(path, "r");
526
+ try {
527
+ await handle.sync();
528
+ }
529
+ finally {
530
+ await handle.close();
531
+ }
532
+ }
533
+ async function syncSnapshotDirectoriesBestEffort(directories, syncDirectory) {
534
+ for (const directory of directories) {
535
+ try {
536
+ await syncDirectory(directory);
537
+ }
538
+ catch (error) {
539
+ logger.warn({ err: error, directory }, "workflow context_builder invocation audit snapshot directory sync failed");
540
+ }
541
+ }
542
+ }
543
+ async function admitExactWorkflowDirectory(parent, name, label) {
544
+ const path = join(parent, name);
545
+ try {
546
+ await mkdir(path, { mode: 0o700 });
547
+ }
548
+ catch (error) {
549
+ if (!isNodeError(error) || error.code !== "EEXIST")
550
+ throw error;
551
+ }
552
+ try {
553
+ const [stats, canonicalPath] = await Promise.all([
554
+ lstat(path),
555
+ realpath(path),
556
+ ]);
557
+ if (stats.isSymbolicLink() ||
558
+ !stats.isDirectory() ||
559
+ canonicalPath !== path) {
560
+ throw new ExecutionError(`${label} is unsafe`);
561
+ }
562
+ return path;
563
+ }
564
+ catch (error) {
565
+ if (error instanceof ExecutionError)
566
+ throw error;
567
+ throw new ExecutionError(`${label} is unsafe`);
568
+ }
569
+ }
570
+ /**
571
+ * Create-or-read the preflight session-log generation sidecar under the workflow
572
+ * run dir, then pair it with the controller-minted operation id. Create-or-read
573
+ * (rather than exclusive-create) keeps the generation stable across retries of
574
+ * the same run. Best-effort: any failure resolves to undefined, and the preflight
575
+ * renders without a `[ log ]` affordance (the prior telemetry-only contract).
576
+ */
577
+ async function resolvePreflightSessionLogContext(runDir, contextRunId) {
578
+ try {
579
+ const workflowRunRoot = await realpath(runDir);
580
+ const sidecarDir = await admitExactWorkflowDirectory(workflowRunRoot, PREFLIGHT_SESSION_LOG_DIR, "workflow context_builder preflight metadata directory");
581
+ const existing = await readSessionLogGeneration(sidecarDir);
582
+ const contextGeneration = existing.kind === "available"
583
+ ? existing.sessionLogGeneration
584
+ : await createSessionLogGeneration(sidecarDir);
585
+ return { contextRunId, contextGeneration };
586
+ }
587
+ catch {
588
+ return undefined;
589
+ }
590
+ }
591
+ function workflowLifecycleExecutionConfig(input) {
592
+ if (input.delegate.enabled !== true) {
593
+ return {
594
+ curator: { configured: false, enabled: false },
595
+ finalizer: { configured: false, enabled: false },
596
+ };
597
+ }
598
+ const finalizerEnabled = input.delegate.finalizer.enabled ??
599
+ (input.profile == null
600
+ ? true
601
+ : CONTEXT_BUILDER_INTENT_PROFILE_DEFAULTS[input.profile].finalizer_enabled);
602
+ return {
603
+ curator: { configured: true, enabled: true },
604
+ finalizer: { configured: true, enabled: finalizerEnabled },
605
+ };
606
+ }
607
+ /**
608
+ * A delegate bundle that is degraded — a deterministic fallback, or a
609
+ * delegated selection that proceeded with known external evidence gaps
610
+ * (status "partial", fallback_used false, external_gap_policy "degrade") — is
611
+ * never promoted into or served from the wfctx cache. The gap policy is not
612
+ * in the cache key, so a cached degraded bundle could otherwise satisfy a later
613
+ * fail-closed request.
614
+ */
615
+ function isDelegateDegradedForCache(delegate) {
616
+ return delegate?.fallback_used === true || delegate?.status === "partial";
617
+ }
618
+ function workflowLifecycleTerminalStatus(result) {
619
+ return result.delegate?.fallback_used === true || result.status === "partial"
620
+ ? "partial"
621
+ : "succeeded";
622
+ }
623
+ function workflowResultLifecyclePatch(result, lifecycle, cacheHit = false) {
624
+ const coverage = result.coverage ?? notEvaluatedCoverageReport();
625
+ const required = coverage.required_when_available.length;
626
+ const missing = coverage.missing_required.length;
627
+ const snapshot = lifecycle?.snapshot;
628
+ const executionPatch = cacheHit
629
+ ? {
630
+ ...(snapshot?.curator.effective_enabled === true
631
+ ? { curatorStatus: "skipped" }
632
+ : {}),
633
+ ...(snapshot?.finalizer.effective_enabled === true
634
+ ? { finalizerStatus: "skipped" }
635
+ : {}),
636
+ }
637
+ : result.delegate?.fallback_used === true
638
+ ? {
639
+ ...(snapshot?.curator.effective_enabled === true
640
+ ? { curatorStatus: "failed" }
641
+ : {}),
642
+ ...(snapshot?.finalizer.effective_enabled === true
643
+ ? { finalizerStatus: "skipped" }
644
+ : {}),
645
+ fallback: {
646
+ status: "used",
647
+ reason_code: "delegate_fallback",
648
+ },
649
+ reasonCodes: ["delegate_fallback"],
650
+ }
651
+ : {
652
+ ...(snapshot?.curator.effective_enabled === true &&
653
+ snapshot.curator.execution_status === "pending"
654
+ ? { curatorStatus: "succeeded" }
655
+ : {}),
656
+ ...(snapshot?.finalizer.effective_enabled === true &&
657
+ snapshot.finalizer.execution_status === "pending"
658
+ ? { finalizerStatus: "succeeded" }
659
+ : {}),
660
+ };
661
+ return {
662
+ ...executionPatch,
663
+ counts: {
664
+ files_seen: cacheHit ? 0 : result.metrics.files_seen,
665
+ files_considered: cacheHit ? 0 : result.metrics.files_considered,
666
+ files_selected: result.metrics.files_selected,
667
+ files_omitted: cacheHit ? 0 : result.metrics.files_omitted,
668
+ search_results: cacheHit ? 0 : snapshot?.counts.search_results ?? 0,
669
+ bytes_read: cacheHit ? 0 : result.metrics.bytes_read,
670
+ bytes_written: result.metrics.bytes_written,
671
+ },
672
+ coverage: {
673
+ policy: coverage.policy_id,
674
+ status: coverage.status,
675
+ required,
676
+ selected: Math.max(0, required - missing),
677
+ missing,
678
+ },
679
+ ...(coverage.status === "degraded"
680
+ ? { reasonCodes: [...(executionPatch.reasonCodes ?? []), "coverage_degraded"] }
681
+ : {}),
682
+ };
683
+ }
684
+ function workflowTerminalExecutionPatch(lifecycle, cancelled) {
685
+ const snapshot = lifecycle.snapshot;
686
+ if (snapshot == null)
687
+ return {};
688
+ const terminalStatus = cancelled ? "cancelled" : "failed";
689
+ return {
690
+ ...(snapshot.curator.execution_status === "running"
691
+ ? { curatorStatus: terminalStatus }
692
+ : snapshot.curator.execution_status === "pending"
693
+ ? { curatorStatus: "skipped" }
694
+ : {}),
695
+ ...(snapshot.finalizer.execution_status === "running"
696
+ ? { finalizerStatus: terminalStatus }
697
+ : snapshot.finalizer.execution_status === "pending"
698
+ ? { finalizerStatus: "skipped" }
699
+ : {}),
700
+ };
701
+ }
702
+ function workflowDelegateExecutionActive(lifecycle) {
703
+ const snapshot = lifecycle.snapshot;
704
+ return snapshot?.curator.execution_status === "running" ||
705
+ snapshot?.finalizer.execution_status === "running";
706
+ }
707
+ export async function copyBundleIntoRun(receipt, runDir, options = {}) {
708
+ return copyBundleArtifactsIntoRun(receipt.artifacts, runDir, options);
709
+ }
710
+ export async function copyBundleArtifactsIntoRun(artifacts, runDir, options = {}) {
711
+ const runRoot = await realpath(runDir);
712
+ const contextDir = join(runRoot, "artifacts", "context");
713
+ await mkdir(contextDir, { recursive: true });
714
+ const realContextDir = await realpath(contextDir);
715
+ const bundleDest = await copyArtifactIntoContextDir(await resolveArtifactPath(artifacts, "bundle_md", "bundle.md"), realContextDir, "bundle.md");
716
+ const selectedContextDest = options.includeSelectedContext === true
717
+ ? await copyArtifactIntoContextDir(await resolveArtifactPath(artifacts, "selected_context_jsonl", "selected-context.jsonl"), realContextDir, "selected-context.jsonl")
718
+ : undefined;
719
+ const manifestSource = await resolveArtifactPath(artifacts, "manifest_json", "manifest.json");
720
+ await options.beforeManifestCommit?.();
721
+ const manifestDest = await copyArtifactIntoContextDir(manifestSource, realContextDir, "manifest.json");
722
+ return selectedContextDest == null
723
+ ? [bundleDest, manifestDest]
724
+ : [bundleDest, selectedContextDest, manifestDest];
725
+ }
726
+ export async function mapPreflightContextInput(input, options) {
727
+ assertExplicitRootsWithinAllowed(input.roots);
728
+ const task = input.cb_task.trim() === "" ? input.user_request : input.cb_task;
729
+ const roots = input.roots.length > 0
730
+ ? [...input.roots]
731
+ : [await resolveFallbackRoot(options.resolveWorkspaceRoot)];
732
+ const profile = validateProfile(input.profile);
733
+ return {
734
+ task,
735
+ roots,
736
+ focus_paths: [...input.focus_paths],
737
+ include_globs: [...input.include_globs],
738
+ exclude_globs: [...input.exclude_globs],
739
+ search_terms: [...input.search_terms],
740
+ allow_secrets: resolveAllowSecrets(input.allow_secrets),
741
+ budget: input.budget ?? {},
742
+ delegate: input.delegate ?? { enabled: false },
743
+ ...(options.run_id == null ? {} : { run_id: options.run_id }),
744
+ ...(profile == null ? {} : { profile }),
745
+ };
746
+ }
747
+ // cb_budget_adapter is intentionally backend-agnostic: this only reads numeric
748
+ // context_builder.budget_defaults and NEVER executes the adapter, so app_server
749
+ // adapters are permitted here even though they are rejected for execution.
750
+ function resolveAdapterBudgetDefaults(registry, name) {
751
+ const trimmed = name?.trim();
752
+ if (trimmed == null || trimmed === "") {
753
+ return {};
754
+ }
755
+ if (registry == null) {
756
+ throw new InvalidParamsError(`cb_budget_adapter "${trimmed}" set but no adapter registry is available`);
757
+ }
758
+ const budgetDefaults = registry.resolveAdapter(trimmed).context_builder?.budget_defaults ?? {};
759
+ return {
760
+ ...(budgetDefaults.max_estimated_tokens == null
761
+ ? {}
762
+ : { max_estimated_tokens: budgetDefaults.max_estimated_tokens }),
763
+ ...(budgetDefaults.max_files == null
764
+ ? {}
765
+ : { max_files: budgetDefaults.max_files }),
766
+ ...(budgetDefaults.max_scan_files == null
767
+ ? {}
768
+ : { max_scan_files: budgetDefaults.max_scan_files }),
769
+ ...(budgetDefaults.max_bytes_per_file == null
770
+ ? {}
771
+ : { max_bytes_per_file: budgetDefaults.max_bytes_per_file }),
772
+ ...(budgetDefaults.max_total_bytes == null
773
+ ? {}
774
+ : { max_total_bytes: budgetDefaults.max_total_bytes }),
775
+ ...(budgetDefaults.max_search_results == null
776
+ ? {}
777
+ : { max_search_results: budgetDefaults.max_search_results }),
778
+ };
779
+ }
780
+ function deriveCacheCoordinates(mappedInput, workspaceSig, runsDir, versions) {
781
+ const inputsHash = computeInputsHash(mappedInput);
782
+ const cacheKey = computeCacheKey({
783
+ inputsHash,
784
+ workspaceSig,
785
+ rendererVersion: versions.rendererVersion,
786
+ cbSchemaVersion: versions.cbSchemaVersion,
787
+ discoveryAlgorithmVersion: versions.discoveryAlgorithmVersion,
788
+ delegatePromptVersion: versions.delegatePromptVersion,
789
+ });
790
+ const wfctxId = deriveWfctxId(cacheKey);
791
+ return {
792
+ workspaceSig,
793
+ cacheKey,
794
+ wfctxId,
795
+ keyPrefix: cacheKey.slice(0, 16),
796
+ targetStorage: resolveContextBuilderRunPaths(runsDir, wfctxId),
797
+ };
798
+ }
799
+ async function synthesizePreflightResultFromCommittedRun(input) {
800
+ try {
801
+ const manifest = await readManifest(input.storage.manifestJson);
802
+ // A committed fallback bundle is degraded (delegate failure_policy:"fallback")
803
+ // and must NEVER be served, especially to a fail-closed failure_policy:"fail"
804
+ // request (failure_policy is intentionally not in the cache key). A poisoned
805
+ // wfctx entry can exist from a mixed-version/older writer, an external/manual
806
+ // artifact, or a future code path. Treat it as a cache MISS (return undefined,
807
+ // the same value the ENOENT/not-usable case returns) so runOrReuse falls
808
+ // through and re-runs the builder; a real "fail" policy then fails closed.
809
+ // A degraded external-gap bundle (status "partial" without fallback) is
810
+ // refused the same way.
811
+ if (isDelegateDegradedForCache(manifest.delegate)) {
812
+ return undefined;
813
+ }
814
+ const receipt = createReceiptFromManifest(manifest, input.storage);
815
+ const resultBeforeMaterialization = buildPreflightResult({
816
+ receipt,
817
+ sourceRunId: input.storage.runId,
818
+ sourceArtifactDir: input.storage.runDir,
819
+ cache: {
820
+ hit: true,
821
+ write: false,
822
+ target_id: input.storage.runId,
823
+ key_prefix: input.keyPrefix,
824
+ },
825
+ copiedPaths: [],
826
+ schemaVersion: input.schemaVersion,
827
+ observability: preflightObservabilityFromManifest(manifest, input.budgetCaps),
828
+ coverage: coverageFromManifest(manifest),
829
+ });
830
+ await input.lifecycle?.transition("cache_lookup", {
831
+ artifactRunId: resultBeforeMaterialization.source_run_id,
832
+ cache: { lookup: "hit", write: "skipped" },
833
+ ...workflowResultLifecyclePatch(resultBeforeMaterialization, input.lifecycle, true),
834
+ });
835
+ await input.lifecycle?.transition("materializing");
836
+ const copiedPaths = await materializeWorkflowContext({
837
+ artifacts: manifest.artifacts,
838
+ sourceRunDir: input.storage.runDir,
839
+ workflowRunDir: input.runDir,
840
+ includeSelectedContext: input.includeSelectedContext,
841
+ syncInvocationSnapshotDirectory: input.syncInvocationSnapshotDirectory,
842
+ ...(input.lifecycle == null
843
+ ? {}
844
+ : { contextRunId: input.lifecycle.contextRunId }),
845
+ ...(input.lifecycle == null
846
+ ? {}
847
+ : {
848
+ beforeManifestCommit: async () => {
849
+ await input.lifecycle?.transition("committing");
850
+ },
851
+ }),
852
+ });
853
+ return buildPreflightResult({
854
+ receipt,
855
+ sourceRunId: input.storage.runId,
856
+ sourceArtifactDir: input.storage.runDir,
857
+ cache: {
858
+ hit: true,
859
+ write: false,
860
+ target_id: input.storage.runId,
861
+ key_prefix: input.keyPrefix,
862
+ },
863
+ copiedPaths,
864
+ schemaVersion: input.schemaVersion,
865
+ observability: preflightObservabilityFromManifest(manifest, input.budgetCaps),
866
+ coverage: coverageFromManifest(manifest),
867
+ });
868
+ }
869
+ catch (error) {
870
+ if (isNodeError(error)
871
+ && error.code === "ENOENT"
872
+ && input.lifecycle?.snapshot?.cache.lookup !== "hit") {
873
+ return undefined;
874
+ }
875
+ throw error;
876
+ }
877
+ }
878
+ function createReceiptFromManifest(manifest, storage) {
879
+ return createContextBuilderReceipt({
880
+ run_id: storage.runId,
881
+ status: manifest.status,
882
+ artifact_dir: storage.artifactDir,
883
+ artifacts: { ...manifest.artifacts },
884
+ metrics: manifest.metrics,
885
+ warnings: [...manifest.warnings],
886
+ omissions: [...manifest.omissions],
887
+ ...(manifest.delegate == null ? {} : { delegate: manifest.delegate }),
888
+ });
889
+ }
890
+ function buildPreflightResult(input) {
891
+ // The request-derived effective schema (input.schemaVersion) must match the
892
+ // receipt's own schema. A divergence means a handler-contract violation (e.g.
893
+ // a delegate-enabled request whose handler returned a no-delegate v1 receipt),
894
+ // which would otherwise emit schema_version:2 with no delegate metadata. Fail
895
+ // loudly rather than emit a contradictory result.
896
+ if (input.schemaVersion !== input.receipt.schema_version) {
897
+ throw new ExecutionError("context_builder schema mismatch: request-derived schema_version " +
898
+ `${input.schemaVersion} does not match receipt schema_version ` +
899
+ `${input.receipt.schema_version}`);
900
+ }
901
+ // A delegate schema_version that carries no delegate metadata is contradictory
902
+ // (a delegated build that lost its delegate provenance). Fail loudly rather
903
+ // than silently emitting delegate: undefined, which would erase fallback_used.
904
+ if (input.receipt.schema_version === CONTEXT_BUILDER_DELEGATE_SCHEMA_VERSION
905
+ && input.receipt.delegate == null) {
906
+ throw new ExecutionError("context_builder receipt has delegate schema_version but no delegate metadata");
907
+ }
908
+ const delegate = input.receipt.schema_version === CONTEXT_BUILDER_DELEGATE_SCHEMA_VERSION
909
+ && input.receipt.delegate != null
910
+ ? {
911
+ enabled: true,
912
+ status: input.receipt.delegate.status,
913
+ fallback_used: input.receipt.delegate.fallback_used,
914
+ }
915
+ : undefined;
916
+ return {
917
+ receipt: input.receipt,
918
+ source_run_id: input.sourceRunId,
919
+ source_artifact_dir: input.sourceArtifactDir,
920
+ cache: input.cache,
921
+ schema_version: input.schemaVersion,
922
+ status: input.receipt.status,
923
+ copied_paths: input.copiedPaths,
924
+ coverage: input.coverage,
925
+ metrics: input.receipt.metrics,
926
+ warning_count: input.receipt.warnings.length,
927
+ omission_count: input.receipt.omissions.length,
928
+ ...(delegate == null ? {} : { delegate }),
929
+ ...(input.observability == null
930
+ ? {}
931
+ : { observability: input.observability }),
932
+ };
933
+ }
934
+ function preflightObservabilityFromManifest(manifest, budgetCaps) {
935
+ const raw = manifest["observability"];
936
+ const record = raw !== null && typeof raw === "object"
937
+ ? raw
938
+ : {};
939
+ return {
940
+ curator_ms: nullableNonNegativeNumber(record["curator_ms"]),
941
+ finalizer_ms: nullableNonNegativeNumber(record["finalizer_ms"]),
942
+ candidate_pool_size: nonNegativeInteger(record["candidate_pool_size"]),
943
+ delegate_packet_size: nonNegativeInteger(record["delegate_packet_size"]),
944
+ budget_caps: budgetCapsFromManifest(manifest["budget"], budgetCaps),
945
+ };
946
+ }
947
+ function coverageFromManifest(manifest) {
948
+ const value = manifest["coverage"];
949
+ if (value === null || typeof value !== "object") {
950
+ return notEvaluatedCoverageReport();
951
+ }
952
+ const coverage = value;
953
+ if (!isCoveragePolicyId(coverage["policy_id"])
954
+ || !isCoverageStatus(coverage["status"])
955
+ || !isEvidenceClassArray(coverage["required_when_available"])
956
+ || !isEvidenceClassArray(coverage["available"])
957
+ || !isEvidenceClassArray(coverage["selected"])
958
+ || !isEvidenceClassArray(coverage["missing_required"])
959
+ || !isEvidenceClassArray(coverage["advisory_missing"])
960
+ || !isEvidenceClassArray(coverage["unclassifiable"])) {
961
+ return notEvaluatedCoverageReport();
962
+ }
963
+ if (!isSemanticallyConsistentCoverage(coverage)) {
964
+ return notEvaluatedCoverageReport();
965
+ }
966
+ return {
967
+ policy_id: coverage["policy_id"],
968
+ status: coverage["status"],
969
+ required_when_available: [...coverage["required_when_available"]],
970
+ available: [...coverage["available"]],
971
+ selected: [...coverage["selected"]],
972
+ missing_required: [...coverage["missing_required"]],
973
+ advisory_missing: [...coverage["advisory_missing"]],
974
+ unclassifiable: [...coverage["unclassifiable"]],
975
+ };
976
+ }
977
+ function isSemanticallyConsistentCoverage(coverage) {
978
+ const policyId = coverage["policy_id"];
979
+ const status = coverage["status"];
980
+ const available = new Set(coverage["available"]);
981
+ const selected = coverage["selected"];
982
+ const missing = coverage["missing_required"];
983
+ if (policyId === null) {
984
+ return (status === "not_evaluated" &&
985
+ available.size === 0 &&
986
+ selected.length === 0 &&
987
+ missing.length === 0);
988
+ }
989
+ if (status === "not_evaluated") {
990
+ return false;
991
+ }
992
+ if (selected.some((evidenceClass) => !available.has(evidenceClass))) {
993
+ return false;
994
+ }
995
+ if (status === "satisfied") {
996
+ return missing.length === 0 && available.has("review_target");
997
+ }
998
+ return missing.length > 0;
999
+ }
1000
+ function isCoveragePolicyId(value) {
1001
+ return value === null || value === "review_deep_v1";
1002
+ }
1003
+ function isCoverageStatus(value) {
1004
+ return value === "satisfied" || value === "degraded" || value === "not_evaluated";
1005
+ }
1006
+ function isEvidenceClassArray(value) {
1007
+ return Array.isArray(value) && value.every(isEvidenceClass);
1008
+ }
1009
+ function isEvidenceClass(value) {
1010
+ return value === "review_target"
1011
+ || value === "public_entrypoint"
1012
+ || value === "reverse_consumer"
1013
+ || value === "configuration"
1014
+ || value === "dependency"
1015
+ || value === "regression_test";
1016
+ }
1017
+ function budgetCapsFromManifest(value, fallback) {
1018
+ if (value === null || typeof value !== "object") {
1019
+ return { ...fallback };
1020
+ }
1021
+ const record = value;
1022
+ return {
1023
+ ...optionalPositiveIntegerCap(record, "max_estimated_tokens"),
1024
+ ...optionalPositiveIntegerCap(record, "max_files"),
1025
+ ...optionalPositiveIntegerCap(record, "max_scan_files"),
1026
+ ...optionalPositiveIntegerCap(record, "max_bytes_per_file"),
1027
+ ...optionalPositiveIntegerCap(record, "max_total_bytes"),
1028
+ ...optionalPositiveIntegerCap(record, "max_search_results"),
1029
+ };
1030
+ }
1031
+ function optionalPositiveIntegerCap(record, key) {
1032
+ const value = record[key];
1033
+ return typeof value === "number" && Number.isInteger(value) && value > 0
1034
+ ? { [key]: value }
1035
+ : {};
1036
+ }
1037
+ function nullableNonNegativeNumber(value) {
1038
+ return typeof value === "number" && Number.isFinite(value) && value >= 0
1039
+ ? value
1040
+ : null;
1041
+ }
1042
+ function nonNegativeInteger(value) {
1043
+ return typeof value === "number" && Number.isInteger(value) && value >= 0
1044
+ ? value
1045
+ : 0;
1046
+ }
1047
+ async function readManifest(manifestPath, ops) {
1048
+ return JSON.parse(await (ops?.readFile ?? readFile)(manifestPath, "utf8"));
1049
+ }
1050
+ async function resolveSelectedContextPaths(manifest, roots) {
1051
+ const selected = Array.isArray(manifest["selected_context"])
1052
+ ? manifest["selected_context"]
1053
+ : [];
1054
+ const absolutePaths = [];
1055
+ for (const entry of selected) {
1056
+ if (entry === null || typeof entry !== "object") {
1057
+ throw new ExecutionError("context_builder manifest selected_context entry is invalid");
1058
+ }
1059
+ const rootIndex = entry.root_index;
1060
+ const selectedPath = entry.path;
1061
+ if (typeof rootIndex !== "number"
1062
+ || !Number.isInteger(rootIndex)
1063
+ || rootIndex < 0
1064
+ || rootIndex >= roots.length
1065
+ || typeof selectedPath !== "string"
1066
+ || selectedPath.trim() === "") {
1067
+ throw new ExecutionError("context_builder manifest selected_context entry is invalid");
1068
+ }
1069
+ const logicalPath = resolve(roots[rootIndex], selectedPath);
1070
+ const realPath = await normalizeExistingPath(logicalPath);
1071
+ absolutePaths.push({
1072
+ logicalPath,
1073
+ realPath,
1074
+ traversedSymlink: realPath !== logicalPath,
1075
+ });
1076
+ }
1077
+ return absolutePaths;
1078
+ }
1079
+ async function evaluatePostCbPromotionGate(input) {
1080
+ try {
1081
+ const coveredPaths = await input.signatureCoveredPaths(input.roots);
1082
+ const selectedFilesCovered =
1083
+ // Empty selections carry no realized-file evidence, so they are not promotable.
1084
+ input.selectedPaths.length > 0 &&
1085
+ input.selectedPaths.every((path) => !path.traversedSymlink && coveredPaths.has(path.realPath));
1086
+ const postSig = await input.workspaceSignature(input.roots);
1087
+ return { selectedFilesCovered, postSig };
1088
+ }
1089
+ catch {
1090
+ return undefined;
1091
+ }
1092
+ }
1093
+ async function normalizeCacheRoots(roots) {
1094
+ const normalized = [];
1095
+ for (const root of roots.length === 0 ? [process.cwd()] : roots) {
1096
+ const absolute = resolve(root);
1097
+ normalized.push(await normalizeExistingPath(absolute));
1098
+ }
1099
+ return Array.from(new Set(normalized)).sort();
1100
+ }
1101
+ async function normalizeExistingPath(path) {
1102
+ const absolute = resolve(path);
1103
+ try {
1104
+ return await realpath(absolute);
1105
+ }
1106
+ catch {
1107
+ return absolute;
1108
+ }
1109
+ }
1110
+ function isPromoteClaimConflict(error) {
1111
+ return error instanceof ContextBuilderRunClaimConflictError
1112
+ || error instanceof ContextBuilderActiveRunClaimConflictError;
1113
+ }
1114
+ function throwIfAborted(signal) {
1115
+ if (signal?.aborted === true) {
1116
+ throw new CancellationError();
1117
+ }
1118
+ }
1119
+ function isNodeError(error) {
1120
+ return error instanceof Error && "code" in error;
1121
+ }
1122
+ function generateWorkflowPreflightRunId() {
1123
+ return `wfpre-${randomUUID()}`;
1124
+ }
1125
+ async function resolveFallbackRoot(resolveWorkspaceRoot) {
1126
+ const workspaceRoot = resolveWorkspaceRoot?.() ?? resolveWorkflowWorkspaceRoot();
1127
+ const resolvedWorkspaceRoot = await realpath(workspaceRoot).catch(() => resolve(workspaceRoot));
1128
+ const sourceAllowedRoots = getContextBuilderSourceAllowedRoots();
1129
+ if (!isPathWithinAllowedRoots(resolvedWorkspaceRoot, sourceAllowedRoots)) {
1130
+ throw new InvalidParamsError(`context_builder fallback root is outside source allowed roots: ${resolvedWorkspaceRoot}. ` +
1131
+ `Allowed: ${sourceAllowedRoots.join(", ")}`);
1132
+ }
1133
+ return resolvedWorkspaceRoot;
1134
+ }
1135
+ function assertExplicitRootsWithinAllowed(roots) {
1136
+ if (roots.length === 0)
1137
+ return;
1138
+ const allowed = getContextBuilderSourceAllowedRoots();
1139
+ for (const root of roots) {
1140
+ const resolved = realpathSyncBestEffort(resolve(process.cwd(), root));
1141
+ if (!isPathWithinAllowedRoots(resolved, allowed)) {
1142
+ throw new InvalidParamsError(`context_builder root is outside allowed roots: ${root}`);
1143
+ }
1144
+ let stat;
1145
+ try {
1146
+ stat = statSync(resolved);
1147
+ }
1148
+ catch {
1149
+ throw new InvalidParamsError(`context_builder root does not exist: ${root}`);
1150
+ }
1151
+ if (!stat.isDirectory()) {
1152
+ throw new InvalidParamsError(`context_builder root is not a directory: ${root}`);
1153
+ }
1154
+ }
1155
+ }
1156
+ function getContextBuilderSourceAllowedRoots() {
1157
+ const raw = process.env["CLINKX_ALLOWED_ROOTS"];
1158
+ if (raw == null || raw.trim() === "") {
1159
+ return getCurrentAllowedRoots();
1160
+ }
1161
+ const cwd = resolve(process.cwd());
1162
+ const roots = [];
1163
+ const seen = new Set();
1164
+ for (const entry of raw
1165
+ .split(",")
1166
+ .map((root) => root.trim())
1167
+ .filter((root) => root.length > 0)) {
1168
+ if (isArtifactOnlyAllowedRootEntry(entry)) {
1169
+ continue;
1170
+ }
1171
+ const resolved = resolve(cwd, entry);
1172
+ const canonical = realpathSyncBestEffort(resolved);
1173
+ if (!seen.has(canonical)) {
1174
+ seen.add(canonical);
1175
+ roots.push(canonical);
1176
+ }
1177
+ }
1178
+ return roots;
1179
+ }
1180
+ function realpathSyncBestEffort(path) {
1181
+ try {
1182
+ return realpathSync(path);
1183
+ }
1184
+ catch {
1185
+ return path;
1186
+ }
1187
+ }
1188
+ function validateProfile(profile) {
1189
+ if (profile == null || profile.trim() === "") {
1190
+ return undefined;
1191
+ }
1192
+ if (isContextBuilderProfile(profile)) {
1193
+ return profile;
1194
+ }
1195
+ throw new InvalidParamsError(`Unknown context_builder profile "${profile}". ` +
1196
+ `Allowed: ${CONTEXT_BUILDER_INTENT_PROFILES.join(", ")}`);
1197
+ }
1198
+ function isContextBuilderProfile(profile) {
1199
+ return CONTEXT_BUILDER_INTENT_PROFILES.includes(profile);
1200
+ }
1201
+ async function resolveArtifactPath(artifacts, key, label) {
1202
+ const artifactPath = artifacts[key];
1203
+ if (typeof artifactPath !== "string" || artifactPath.trim() === "") {
1204
+ throw new ExecutionError(`context_builder receipt is missing ${label}`);
1205
+ }
1206
+ return realpath(artifactPath);
1207
+ }
1208
+ async function copyArtifactIntoContextDir(source, contextDir, fileName) {
1209
+ const target = resolve(contextDir, fileName);
1210
+ assertContainedPath(contextDir, target, `context_builder copy target escaped: ${target}`);
1211
+ const tempTarget = resolve(contextDir, `.${fileName}.${process.pid}.${randomUUID()}.tmp`);
1212
+ assertContainedPath(contextDir, tempTarget, `context_builder temp copy target escaped: ${tempTarget}`);
1213
+ try {
1214
+ await copyFile(source, tempTarget);
1215
+ await rename(tempTarget, target);
1216
+ }
1217
+ catch (error) {
1218
+ await rm(tempTarget, { force: true }).catch(() => { });
1219
+ throw error;
1220
+ }
1221
+ const realTarget = await realpath(target);
1222
+ assertContainedPath(contextDir, realTarget, `context_builder copied artifact escaped context directory: ${realTarget}`);
1223
+ return realTarget;
1224
+ }
1225
+ function assertContainedPath(parent, child, message) {
1226
+ if (!isAbsolute(child)) {
1227
+ throw new ExecutionError(message);
1228
+ }
1229
+ const rel = relative(parent, child);
1230
+ if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) {
1231
+ throw new ExecutionError(message);
1232
+ }
1233
+ }
1234
+ function parseReceiptResponse(response) {
1235
+ const receiptText = response.content[0]?.text;
1236
+ if (typeof receiptText !== "string") {
1237
+ throw new ExecutionError("context_builder returned no receipt text");
1238
+ }
1239
+ return JSON.parse(receiptText);
1240
+ }
1241
+ //# sourceMappingURL=workflow-runner.js.map