@ebrindley/build 0.0.0-stage → 1.42.1-rc28

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 (878) hide show
  1. package/.build-project/providers/catalog.json +13951 -0
  2. package/.build-project/providers/pricing.json +1978 -0
  3. package/.build-project/providers/registry.json +4103 -0
  4. package/.github/SECURITY.md +75 -0
  5. package/.nvmrc +1 -0
  6. package/CHANGELOG.md +661 -0
  7. package/CODE_OF_CONDUCT.md +44 -0
  8. package/CONTRIBUTING.md +24 -0
  9. package/INSTALL.md +623 -0
  10. package/LICENSE +21 -0
  11. package/README.md +118 -2
  12. package/THIRD_PARTY_NOTICES.txt +26 -0
  13. package/dist/ai-judge-UE5UOYOO.js +191 -0
  14. package/dist/allowlist-grounding-KPLN6NC5.js +16 -0
  15. package/dist/allowlist-utils-MZZKKXRD.js +31 -0
  16. package/dist/apply-completion-mode-EM37UZHB.js +110 -0
  17. package/dist/artifact-migrator-WPACNSEP.js +276 -0
  18. package/dist/ask-2OZ4JFQR.js +176 -0
  19. package/dist/auth-6UKBTJUQ.js +185 -0
  20. package/dist/auth-H5KJL6HL.js +165 -0
  21. package/dist/auth-LVJRJDMU.js +12 -0
  22. package/dist/auth-NHZOCNRR.js +94 -0
  23. package/dist/auth-PBXHWXGW.js +95 -0
  24. package/dist/auth-T7Y5DCAH.js +91 -0
  25. package/dist/auth-TVVKCHQW.js +13 -0
  26. package/dist/auth-UHB2UCSS.js +97 -0
  27. package/dist/auth-VACA3VUL.js +98 -0
  28. package/dist/auth-VVLC77S3.js +44 -0
  29. package/dist/auth-liveness-XO4AGDDD.js +53 -0
  30. package/dist/autoloop-cleanup-SI3VGAAR.js +106 -0
  31. package/dist/autoloop-evidence-gates-J5GG5YQB.js +39 -0
  32. package/dist/autoloop-gate-policy-SUNAEP6Q.js +169 -0
  33. package/dist/autoloop-helpers-VQGQNTT6.js +52 -0
  34. package/dist/autoloop-ledger-P6TIDP7C.js +96 -0
  35. package/dist/autoloop-ledger-subscriber-HFAGOZXH.js +161 -0
  36. package/dist/autoloop-run-defaults-GWGZBNT7.js +27 -0
  37. package/dist/autoloop-run-lock-GBWRM5A2.js +197 -0
  38. package/dist/autoloop-success-C32QVWOP.js +93 -0
  39. package/dist/autoloop-termination-summary-GI6IBQWD.js +58 -0
  40. package/dist/autoloop-trajectory-AMKSQISD.js +70 -0
  41. package/dist/autoloop-wall-clock-T7ZVIQOC.js +12 -0
  42. package/dist/automatic-branch-cleanup-R62X2C5O.js +49 -0
  43. package/dist/autonomous-loop-controller-2WL363LW.js +4386 -0
  44. package/dist/backend-YUTFDZXZ.js +30 -0
  45. package/dist/background-executor-Z3ODTMD7.js +260 -0
  46. package/dist/backlog-75QPEAMW.js +403 -0
  47. package/dist/backlog-execution-intent-GWUV5TUK.js +19 -0
  48. package/dist/backup-active-store-XHWLN34M.js +16 -0
  49. package/dist/backup-machine-stores-UI4LTJOY.js +251 -0
  50. package/dist/backup-telemetry-db-Z4ICYCNW.js +26 -0
  51. package/dist/branch-archive-manager-FMSQ7YJF.js +18 -0
  52. package/dist/branch-cleanup-manager-ST6FJGND.js +35 -0
  53. package/dist/build-gate-7NKWPY62.js +68 -0
  54. package/dist/build-root-S7DINODY.js +18 -0
  55. package/dist/change-summary-R6CB6VXJ.js +50 -0
  56. package/dist/chunk-24MNKKOM.js +173 -0
  57. package/dist/chunk-2H6VZFIO.js +235 -0
  58. package/dist/chunk-2JIX3EKV.js +39 -0
  59. package/dist/chunk-2KO7HVZM.js +106 -0
  60. package/dist/chunk-2L36U25O.js +100 -0
  61. package/dist/chunk-2NMNFUQA.js +475 -0
  62. package/dist/chunk-2OUAEH67.js +83 -0
  63. package/dist/chunk-2VLJUXJU.js +115 -0
  64. package/dist/chunk-2VUEDIUM.js +77 -0
  65. package/dist/chunk-2Y2IIHPI.js +430 -0
  66. package/dist/chunk-2YRG3LHZ.js +220 -0
  67. package/dist/chunk-2Z5Q3SUY.js +65 -0
  68. package/dist/chunk-32IYXIE5.js +873 -0
  69. package/dist/chunk-33IGPPUI.js +292 -0
  70. package/dist/chunk-352PCJLK.js +283 -0
  71. package/dist/chunk-35J4NE6S.js +226 -0
  72. package/dist/chunk-3C7WBIVK.js +1016 -0
  73. package/dist/chunk-3H3EY6U7.js +1225 -0
  74. package/dist/chunk-3H4MWYIC.js +198 -0
  75. package/dist/chunk-3HHWQR3N.js +2479 -0
  76. package/dist/chunk-3JKNRYEE.js +14 -0
  77. package/dist/chunk-3LECCYZY.js +128 -0
  78. package/dist/chunk-3LOY6YZI.js +852 -0
  79. package/dist/chunk-3M57DADF.js +44 -0
  80. package/dist/chunk-3NOTLVLG.js +3803 -0
  81. package/dist/chunk-3OPP2OZB.js +1480 -0
  82. package/dist/chunk-3P5IN5E7.js +9 -0
  83. package/dist/chunk-3PL22IYZ.js +20 -0
  84. package/dist/chunk-3REDAJUJ.js +14 -0
  85. package/dist/chunk-3S2R4XJI.js +203 -0
  86. package/dist/chunk-3UBZI5DW.js +61 -0
  87. package/dist/chunk-3VV5OBGG.js +308 -0
  88. package/dist/chunk-3WY5TU2O.js +823 -0
  89. package/dist/chunk-43OKHTW4.js +82 -0
  90. package/dist/chunk-45KUJBDI.js +112 -0
  91. package/dist/chunk-47X5LM7B.js +224 -0
  92. package/dist/chunk-4B6FQJ77.js +268 -0
  93. package/dist/chunk-4BTDUT2S.js +42 -0
  94. package/dist/chunk-4DJL2VXA.js +24 -0
  95. package/dist/chunk-4EBSXZ73.js +48 -0
  96. package/dist/chunk-4QKP6I4C.js +294 -0
  97. package/dist/chunk-4U6XK2DG.js +300 -0
  98. package/dist/chunk-4UMRUFBD.js +132 -0
  99. package/dist/chunk-4US4SYJ4.js +569 -0
  100. package/dist/chunk-4ZPLWEZO.js +154 -0
  101. package/dist/chunk-56WPYDJH.js +624 -0
  102. package/dist/chunk-57WRCJJW.js +50 -0
  103. package/dist/chunk-5AW4RMNG.js +24 -0
  104. package/dist/chunk-5EQN56OZ.js +155 -0
  105. package/dist/chunk-5F43TUIN.js +38 -0
  106. package/dist/chunk-5FKHIKTS.js +115 -0
  107. package/dist/chunk-5HDP7XZG.js +91 -0
  108. package/dist/chunk-5KQETTNS.js +152 -0
  109. package/dist/chunk-5PDVN2KO.js +498 -0
  110. package/dist/chunk-5UBIFVRD.js +509 -0
  111. package/dist/chunk-5YDE3Q62.js +46 -0
  112. package/dist/chunk-626AJVMU.js +302 -0
  113. package/dist/chunk-633XZ7UF.js +3583 -0
  114. package/dist/chunk-63DHNHGA.js +236 -0
  115. package/dist/chunk-666656AR.js +568 -0
  116. package/dist/chunk-67YRJPJO.js +19 -0
  117. package/dist/chunk-6CAU7VBA.js +20 -0
  118. package/dist/chunk-6CB3KJRY.js +21 -0
  119. package/dist/chunk-6DBMALXL.js +29 -0
  120. package/dist/chunk-6E25C4IA.js +269 -0
  121. package/dist/chunk-6FIBNIQU.js +73 -0
  122. package/dist/chunk-6G57FYBV.js +189 -0
  123. package/dist/chunk-6KZKRTG3.js +4885 -0
  124. package/dist/chunk-6LAH2UV2.js +525 -0
  125. package/dist/chunk-6PZY2TTU.js +921 -0
  126. package/dist/chunk-6T6NHXK4.js +230 -0
  127. package/dist/chunk-6TBEX4R4.js +432 -0
  128. package/dist/chunk-6TRD7TEE.js +911 -0
  129. package/dist/chunk-6XCP2RAI.js +47 -0
  130. package/dist/chunk-726G6WDL.js +351 -0
  131. package/dist/chunk-75EMT7BF.js +616 -0
  132. package/dist/chunk-762ACDZJ.js +4696 -0
  133. package/dist/chunk-77I6G4CO.js +1 -0
  134. package/dist/chunk-7DJ6SQH3.js +510 -0
  135. package/dist/chunk-7HPCIOMA.js +1383 -0
  136. package/dist/chunk-7HYBSRPZ.js +17503 -0
  137. package/dist/chunk-7KBEOPVB.js +73 -0
  138. package/dist/chunk-7LHJDJB3.js +2222 -0
  139. package/dist/chunk-7NVJMH52.js +306 -0
  140. package/dist/chunk-7RMARDVH.js +33 -0
  141. package/dist/chunk-7SEWU4QG.js +36 -0
  142. package/dist/chunk-7TUTZTI2.js +911 -0
  143. package/dist/chunk-7VBDFPUM.js +340 -0
  144. package/dist/chunk-7VRJHTGZ.js +6406 -0
  145. package/dist/chunk-7YAOUUKK.js +493 -0
  146. package/dist/chunk-AAAODV76.js +860 -0
  147. package/dist/chunk-AB4HUJVQ.js +339 -0
  148. package/dist/chunk-AEQWV746.js +611 -0
  149. package/dist/chunk-AHU3FKPA.js +11639 -0
  150. package/dist/chunk-AISTV5XU.js +226 -0
  151. package/dist/chunk-AJBTKGJZ.js +48 -0
  152. package/dist/chunk-AJJNW7XT.js +248 -0
  153. package/dist/chunk-AJN5Y5YZ.js +160 -0
  154. package/dist/chunk-ALDTFNZ3.js +150 -0
  155. package/dist/chunk-ARARVIZK.js +281 -0
  156. package/dist/chunk-ATBM6AW5.js +53 -0
  157. package/dist/chunk-ATKEKM3E.js +206 -0
  158. package/dist/chunk-AUJLW6JZ.js +92 -0
  159. package/dist/chunk-AY3MHEFM.js +24 -0
  160. package/dist/chunk-B7PYTV72.js +236 -0
  161. package/dist/chunk-B7YRSULE.js +1423 -0
  162. package/dist/chunk-BAWJNMWF.js +339 -0
  163. package/dist/chunk-BBPIILO2.js +88 -0
  164. package/dist/chunk-BD3PGW6A.js +957 -0
  165. package/dist/chunk-BDPYFAB4.js +44 -0
  166. package/dist/chunk-BIUV23HH.js +729 -0
  167. package/dist/chunk-BQ3VAGXH.js +243 -0
  168. package/dist/chunk-BQJOGAWT.js +31 -0
  169. package/dist/chunk-BT7EG7CO.js +68 -0
  170. package/dist/chunk-BV3XQQLU.js +27 -0
  171. package/dist/chunk-BY6ODHNZ.js +78 -0
  172. package/dist/chunk-BZRLSZNV.js +79 -0
  173. package/dist/chunk-C3DH3NCY.js +2773 -0
  174. package/dist/chunk-C3KCMAJP.js +756 -0
  175. package/dist/chunk-C7AGUJ5K.js +267 -0
  176. package/dist/chunk-CBSWKQCX.js +342 -0
  177. package/dist/chunk-CE5OZBYY.js +21 -0
  178. package/dist/chunk-CFCVYHSW.js +373 -0
  179. package/dist/chunk-CHA2HDE5.js +126 -0
  180. package/dist/chunk-CIHWPGS5.js +146 -0
  181. package/dist/chunk-CJBSZX3F.js +127 -0
  182. package/dist/chunk-CLA6QIJM.js +43 -0
  183. package/dist/chunk-CPSVQR2I.js +365 -0
  184. package/dist/chunk-CRPRVNQ4.js +254 -0
  185. package/dist/chunk-CSIE4Y7C.js +1093 -0
  186. package/dist/chunk-CSOPSYDY.js +142 -0
  187. package/dist/chunk-CSXLLEGB.js +205 -0
  188. package/dist/chunk-CTDLERWU.js +293 -0
  189. package/dist/chunk-CULBXMSK.js +110 -0
  190. package/dist/chunk-D2M2Y5ID.js +21 -0
  191. package/dist/chunk-D37WY7SH.js +1060 -0
  192. package/dist/chunk-D4VJFCGZ.js +89 -0
  193. package/dist/chunk-D6WTZMZB.js +48 -0
  194. package/dist/chunk-DBHOWDUH.js +976 -0
  195. package/dist/chunk-DCACX7BV.js +19364 -0
  196. package/dist/chunk-DFHX4XYA.js +128 -0
  197. package/dist/chunk-DIKBRRKE.js +176 -0
  198. package/dist/chunk-DJG5RIOR.js +9 -0
  199. package/dist/chunk-DNIOIISW.js +616 -0
  200. package/dist/chunk-DOA5G7IA.js +315 -0
  201. package/dist/chunk-DP7FKP6W.js +855 -0
  202. package/dist/chunk-DS2JZ677.js +79 -0
  203. package/dist/chunk-DSRLVYBS.js +82 -0
  204. package/dist/chunk-EAEVKNJA.js +209 -0
  205. package/dist/chunk-EEUESN3T.js +575 -0
  206. package/dist/chunk-EJ4LUU5Y.js +73 -0
  207. package/dist/chunk-EJIWTPSZ.js +1063 -0
  208. package/dist/chunk-EJVCDTAN.js +116 -0
  209. package/dist/chunk-EKLUBDBQ.js +627 -0
  210. package/dist/chunk-EN62WLFD.js +849 -0
  211. package/dist/chunk-ENYRCL43.js +26 -0
  212. package/dist/chunk-EP22ZMFO.js +273 -0
  213. package/dist/chunk-EP4SVAVI.js +87 -0
  214. package/dist/chunk-EPAMVGI3.js +1562 -0
  215. package/dist/chunk-EPRMH6HO.js +24 -0
  216. package/dist/chunk-ES6NWJ36.js +4057 -0
  217. package/dist/chunk-ETA2K4KI.js +30 -0
  218. package/dist/chunk-ETAD4NKD.js +31 -0
  219. package/dist/chunk-EUWIIDQ7.js +93 -0
  220. package/dist/chunk-EVE3OD2W.js +141 -0
  221. package/dist/chunk-EXA26FFC.js +459 -0
  222. package/dist/chunk-EXSPAA35.js +244 -0
  223. package/dist/chunk-F55YABKV.js +258 -0
  224. package/dist/chunk-F5DNGU5W.js +27 -0
  225. package/dist/chunk-F622MJYV.js +103 -0
  226. package/dist/chunk-F6NIQD74.js +5111 -0
  227. package/dist/chunk-FAWJTC34.js +43 -0
  228. package/dist/chunk-FAZBRHGG.js +47 -0
  229. package/dist/chunk-FIEUSGNJ.js +39 -0
  230. package/dist/chunk-FKCG7K6H.js +1146 -0
  231. package/dist/chunk-FOVVXV45.js +229 -0
  232. package/dist/chunk-FRBPKBFE.js +30 -0
  233. package/dist/chunk-FSA5BPFI.js +268 -0
  234. package/dist/chunk-FSJ5TTZ3.js +29 -0
  235. package/dist/chunk-FT7SGLXT.js +193 -0
  236. package/dist/chunk-FUUVZZUB.js +62 -0
  237. package/dist/chunk-FYMRVUNZ.js +1697 -0
  238. package/dist/chunk-FYTAA5FG.js +162 -0
  239. package/dist/chunk-G3VB2UCZ.js +3892 -0
  240. package/dist/chunk-G6OIMVXH.js +405 -0
  241. package/dist/chunk-G7PQCXVH.js +228 -0
  242. package/dist/chunk-GAB6UW52.js +1087 -0
  243. package/dist/chunk-GAFJEYLK.js +29 -0
  244. package/dist/chunk-GC4CRMTS.js +642 -0
  245. package/dist/chunk-GFHSIWHL.js +5297 -0
  246. package/dist/chunk-GI5M67YA.js +735 -0
  247. package/dist/chunk-GIJWHUWF.js +191 -0
  248. package/dist/chunk-GO6DRECI.js +1 -0
  249. package/dist/chunk-GOFVBTMN.js +314 -0
  250. package/dist/chunk-GQIP72ZJ.js +13 -0
  251. package/dist/chunk-GQXLXRFA.js +28 -0
  252. package/dist/chunk-GT6HFKJB.js +48 -0
  253. package/dist/chunk-GVJGSSKM.js +174 -0
  254. package/dist/chunk-GWHGTG37.js +36 -0
  255. package/dist/chunk-GZAJHLKO.js +18 -0
  256. package/dist/chunk-GZK62I3N.js +314 -0
  257. package/dist/chunk-H3HGMISG.js +483 -0
  258. package/dist/chunk-H3ISZJMJ.js +403 -0
  259. package/dist/chunk-H4HXVWEC.js +9 -0
  260. package/dist/chunk-H6MJGKAW.js +120 -0
  261. package/dist/chunk-HBTTGVR5.js +353 -0
  262. package/dist/chunk-HBZ322WZ.js +35 -0
  263. package/dist/chunk-HEP3ILP4.js +34 -0
  264. package/dist/chunk-HGFXODKO.js +106 -0
  265. package/dist/chunk-HHWDTB6S.js +59 -0
  266. package/dist/chunk-HKO45NLZ.js +286 -0
  267. package/dist/chunk-HLVTEA6A.js +89 -0
  268. package/dist/chunk-HS3SY6HN.js +160 -0
  269. package/dist/chunk-HT5OCGKN.js +899 -0
  270. package/dist/chunk-HXIIEMGF.js +78 -0
  271. package/dist/chunk-I56TH7VM.js +46 -0
  272. package/dist/chunk-I6FN3R5D.js +352 -0
  273. package/dist/chunk-I7SCBHJN.js +655 -0
  274. package/dist/chunk-IJM4GKAT.js +529 -0
  275. package/dist/chunk-IMEYU36R.js +344 -0
  276. package/dist/chunk-INJ3SS6A.js +936 -0
  277. package/dist/chunk-IUKOPCCE.js +441 -0
  278. package/dist/chunk-IVEPZQJO.js +33 -0
  279. package/dist/chunk-IVZEONFC.js +43 -0
  280. package/dist/chunk-IWBHRSG7.js +936 -0
  281. package/dist/chunk-IYY3HQAD.js +484 -0
  282. package/dist/chunk-J2ICMYDA.js +48 -0
  283. package/dist/chunk-J2QCFLUN.js +505 -0
  284. package/dist/chunk-J5HM6V5P.js +1039 -0
  285. package/dist/chunk-J6NZX6QH.js +398 -0
  286. package/dist/chunk-JBBB2Y47.js +432 -0
  287. package/dist/chunk-JDCZQZU7.js +42 -0
  288. package/dist/chunk-JEDNXGSS.js +169 -0
  289. package/dist/chunk-JHP7OT6K.js +89 -0
  290. package/dist/chunk-JLS65NUQ.js +14 -0
  291. package/dist/chunk-JNMWYMC6.js +38 -0
  292. package/dist/chunk-JNSTWNNW.js +25 -0
  293. package/dist/chunk-JOSK6GEU.js +9564 -0
  294. package/dist/chunk-JQUMSIGC.js +100 -0
  295. package/dist/chunk-JVHGMURQ.js +1106 -0
  296. package/dist/chunk-JYXS47FQ.js +951 -0
  297. package/dist/chunk-K2ZMW2Z5.js +2147 -0
  298. package/dist/chunk-K7FAFORM.js +14 -0
  299. package/dist/chunk-KBJXX3ON.js +333 -0
  300. package/dist/chunk-KHFKVQWY.js +486 -0
  301. package/dist/chunk-KHMEI3DQ.js +173 -0
  302. package/dist/chunk-KHW3UD7B.js +69 -0
  303. package/dist/chunk-KKQKWAMF.js +365 -0
  304. package/dist/chunk-KOKXJV2U.js +455 -0
  305. package/dist/chunk-KQ4NGOJI.js +14 -0
  306. package/dist/chunk-KQYQOXMS.js +342 -0
  307. package/dist/chunk-KTMW65UX.js +14 -0
  308. package/dist/chunk-KUEWV2JH.js +593 -0
  309. package/dist/chunk-KXYDV3HP.js +1523 -0
  310. package/dist/chunk-KZ4JMGZ5.js +96 -0
  311. package/dist/chunk-KZWGBUIO.js +2659 -0
  312. package/dist/chunk-L2CBG5IX.js +1892 -0
  313. package/dist/chunk-L2S235CU.js +314 -0
  314. package/dist/chunk-L32WD57F.js +98 -0
  315. package/dist/chunk-LDJCKAJP.js +123 -0
  316. package/dist/chunk-LDWNBEN7.js +541 -0
  317. package/dist/chunk-LJVH57G2.js +241 -0
  318. package/dist/chunk-LPQ7NZEN.js +209 -0
  319. package/dist/chunk-LRGH3CCV.js +148 -0
  320. package/dist/chunk-LULOGMMM.js +1133 -0
  321. package/dist/chunk-LWGKN2GY.js +8284 -0
  322. package/dist/chunk-LX4F24ZH.js +157 -0
  323. package/dist/chunk-M4BUEXXF.js +839 -0
  324. package/dist/chunk-M6UHOC4I.js +553 -0
  325. package/dist/chunk-MCBNWZNO.js +657 -0
  326. package/dist/chunk-MEMSY6VY.js +223 -0
  327. package/dist/chunk-MHLEZQQI.js +145 -0
  328. package/dist/chunk-MJ6WNSIX.js +192 -0
  329. package/dist/chunk-MKASIKWZ.js +442 -0
  330. package/dist/chunk-MNOVBYFU.js +60 -0
  331. package/dist/chunk-MO2BYAAF.js +2896 -0
  332. package/dist/chunk-MP6P7Y2A.js +180 -0
  333. package/dist/chunk-MQ4TFJAG.js +3365 -0
  334. package/dist/chunk-MT2WAIR3.js +131 -0
  335. package/dist/chunk-MTU7VTNN.js +1122 -0
  336. package/dist/chunk-MULMXX4V.js +150 -0
  337. package/dist/chunk-MW2DWWVA.js +147 -0
  338. package/dist/chunk-MY3ZPUN4.js +151 -0
  339. package/dist/chunk-MYLH2S4G.js +64 -0
  340. package/dist/chunk-MZ5WYKNA.js +28 -0
  341. package/dist/chunk-N3Q2JNPV.js +249 -0
  342. package/dist/chunk-N5DX4JAK.js +12 -0
  343. package/dist/chunk-NAINGKHF.js +35 -0
  344. package/dist/chunk-NEQUQHOX.js +223 -0
  345. package/dist/chunk-NHNPEZS4.js +1408 -0
  346. package/dist/chunk-NHTIXJCR.js +17 -0
  347. package/dist/chunk-NKLPMBNV.js +1154 -0
  348. package/dist/chunk-NMVZ5YES.js +199 -0
  349. package/dist/chunk-NRFRY3GE.js +256 -0
  350. package/dist/chunk-NTD6CSI6.js +1266 -0
  351. package/dist/chunk-NUO7B3SH.js +318 -0
  352. package/dist/chunk-NVOHIJKG.js +1319 -0
  353. package/dist/chunk-NXH3RX7O.js +523 -0
  354. package/dist/chunk-NXZ3DURF.js +257 -0
  355. package/dist/chunk-O26L6F7F.js +209 -0
  356. package/dist/chunk-O5RRIUEP.js +124 -0
  357. package/dist/chunk-O5X6BKAO.js +10 -0
  358. package/dist/chunk-O6ZQUVTR.js +31 -0
  359. package/dist/chunk-O7FE75QZ.js +306 -0
  360. package/dist/chunk-OC7Z6AJQ.js +81 -0
  361. package/dist/chunk-OH7IEZ63.js +307 -0
  362. package/dist/chunk-OI734GRS.js +115 -0
  363. package/dist/chunk-OJBH62DK.js +684 -0
  364. package/dist/chunk-OKJLVSTJ.js +247 -0
  365. package/dist/chunk-OMX5VL43.js +79 -0
  366. package/dist/chunk-ONHAMBN6.js +12 -0
  367. package/dist/chunk-ONYPLIVE.js +753 -0
  368. package/dist/chunk-OSK7QWPD.js +637 -0
  369. package/dist/chunk-OTXLMJKP.js +438 -0
  370. package/dist/chunk-OV5PKQMA.js +213 -0
  371. package/dist/chunk-OXK5HA4B.js +31 -0
  372. package/dist/chunk-OYDWFQA4.js +272 -0
  373. package/dist/chunk-OZAUKWHB.js +22 -0
  374. package/dist/chunk-P5P2EKGH.js +94 -0
  375. package/dist/chunk-P6SSWAKY.js +29 -0
  376. package/dist/chunk-P7CQGPLS.js +30 -0
  377. package/dist/chunk-P7RVCHQV.js +197 -0
  378. package/dist/chunk-PEBWDYIW.js +726 -0
  379. package/dist/chunk-PFCXFO7A.js +9193 -0
  380. package/dist/chunk-PFLDWMX6.js +168 -0
  381. package/dist/chunk-PHZGLQSK.js +15883 -0
  382. package/dist/chunk-PNFTPNSR.js +20 -0
  383. package/dist/chunk-PPHXX4W7.js +175 -0
  384. package/dist/chunk-PPZESPJT.js +262 -0
  385. package/dist/chunk-PRDHI2L5.js +296 -0
  386. package/dist/chunk-PSTKWHHN.js +32 -0
  387. package/dist/chunk-PV53ODOT.js +555 -0
  388. package/dist/chunk-PVJBTI7P.js +24 -0
  389. package/dist/chunk-PXKERBKX.js +100 -0
  390. package/dist/chunk-PZ5AY32C.js +10 -0
  391. package/dist/chunk-Q3DHEZA5.js +85 -0
  392. package/dist/chunk-Q5RZDVQK.js +204 -0
  393. package/dist/chunk-Q64IR2Z2.js +4933 -0
  394. package/dist/chunk-Q6Z5UGPL.js +398 -0
  395. package/dist/chunk-QAMAV4DT.js +627 -0
  396. package/dist/chunk-QBWF4444.js +112 -0
  397. package/dist/chunk-QDKYT4CI.js +22805 -0
  398. package/dist/chunk-QFLBRWCJ.js +126 -0
  399. package/dist/chunk-QILAQACE.js +107 -0
  400. package/dist/chunk-QJ6OEH4K.js +3683 -0
  401. package/dist/chunk-QK3NLYTV.js +320 -0
  402. package/dist/chunk-QOFLUS24.js +535 -0
  403. package/dist/chunk-QOIASNEJ.js +98 -0
  404. package/dist/chunk-QP4UTSOV.js +3587 -0
  405. package/dist/chunk-QP5ST7RI.js +904 -0
  406. package/dist/chunk-QS5AGRZN.js +167 -0
  407. package/dist/chunk-QTAOU53N.js +107 -0
  408. package/dist/chunk-QTCLJHLZ.js +351 -0
  409. package/dist/chunk-QTOLTG4L.js +119 -0
  410. package/dist/chunk-QWDV4OSL.js +142 -0
  411. package/dist/chunk-QWMQ74KD.js +508 -0
  412. package/dist/chunk-QX6LOMMH.js +158 -0
  413. package/dist/chunk-QXBKIHY7.js +238 -0
  414. package/dist/chunk-QXBKTJT6.js +270 -0
  415. package/dist/chunk-QYQOVOLR.js +196 -0
  416. package/dist/chunk-R2CKS6WT.js +73 -0
  417. package/dist/chunk-R2TIYG7U.js +68 -0
  418. package/dist/chunk-R2W3LESH.js +465 -0
  419. package/dist/chunk-R5EXHMUN.js +100 -0
  420. package/dist/chunk-RBBTBCHX.js +289 -0
  421. package/dist/chunk-RBKLOUXA.js +121 -0
  422. package/dist/chunk-RCP2Y6DQ.js +86 -0
  423. package/dist/chunk-RCYEJSD5.js +260 -0
  424. package/dist/chunk-RFDVSI4N.js +134 -0
  425. package/dist/chunk-RGJU63FV.js +1717 -0
  426. package/dist/chunk-RI4EX2QE.js +18 -0
  427. package/dist/chunk-RIMARPCF.js +152 -0
  428. package/dist/chunk-RJ6RSNT6.js +42 -0
  429. package/dist/chunk-RNI2GUIF.js +131 -0
  430. package/dist/chunk-RPHUWJ3K.js +264 -0
  431. package/dist/chunk-RPIMAMV7.js +361 -0
  432. package/dist/chunk-RQFX6YRN.js +49 -0
  433. package/dist/chunk-RRC5BL7B.js +285 -0
  434. package/dist/chunk-RSYTSBOO.js +79 -0
  435. package/dist/chunk-RWQQIKIC.js +35 -0
  436. package/dist/chunk-RZUBOZH2.js +373 -0
  437. package/dist/chunk-S2E632FQ.js +380 -0
  438. package/dist/chunk-S2VQCZO4.js +22 -0
  439. package/dist/chunk-S2XIMQJQ.js +681 -0
  440. package/dist/chunk-S47ISY27.js +183 -0
  441. package/dist/chunk-S6I4KISU.js +142 -0
  442. package/dist/chunk-S6TAFQI5.js +2403 -0
  443. package/dist/chunk-SBBNT5ZJ.js +27 -0
  444. package/dist/chunk-SDJV2DTQ.js +491 -0
  445. package/dist/chunk-SDPIFNLD.js +33 -0
  446. package/dist/chunk-SF6YK3JI.js +835 -0
  447. package/dist/chunk-SK3ZFONO.js +976 -0
  448. package/dist/chunk-SKTFRFQ7.js +1775 -0
  449. package/dist/chunk-SNGM452K.js +2002 -0
  450. package/dist/chunk-STW7OFOA.js +581 -0
  451. package/dist/chunk-SU6UFUQY.js +1351 -0
  452. package/dist/chunk-SVJM3LJA.js +27 -0
  453. package/dist/chunk-SVUNZOPG.js +129 -0
  454. package/dist/chunk-T5XLUYV3.js +34 -0
  455. package/dist/chunk-T7E5JS6N.js +57 -0
  456. package/dist/chunk-TA3N5MMO.js +450 -0
  457. package/dist/chunk-TAJPCXSB.js +13 -0
  458. package/dist/chunk-TDEMDRN2.js +1639 -0
  459. package/dist/chunk-TDSEX5CF.js +24 -0
  460. package/dist/chunk-TGCVL74Y.js +28 -0
  461. package/dist/chunk-TGXXYDL4.js +1012 -0
  462. package/dist/chunk-TIKTYUJO.js +296 -0
  463. package/dist/chunk-TIZAJD4M.js +6029 -0
  464. package/dist/chunk-TLSEZZCG.js +5549 -0
  465. package/dist/chunk-TMBDRHAX.js +19 -0
  466. package/dist/chunk-TRURQUBP.js +1217 -0
  467. package/dist/chunk-TSQ256N5.js +152 -0
  468. package/dist/chunk-TUQMMFEQ.js +2244 -0
  469. package/dist/chunk-U424MJLC.js +81 -0
  470. package/dist/chunk-U4DRS6ZW.js +11 -0
  471. package/dist/chunk-U5KS22IN.js +204 -0
  472. package/dist/chunk-UAPHFJPN.js +673 -0
  473. package/dist/chunk-UB7LQITD.js +1040 -0
  474. package/dist/chunk-UBVRHGAZ.js +237 -0
  475. package/dist/chunk-UDNNAQN5.js +98 -0
  476. package/dist/chunk-UJP3XM54.js +342 -0
  477. package/dist/chunk-UJYDH2MW.js +305 -0
  478. package/dist/chunk-UKMPASIC.js +399 -0
  479. package/dist/chunk-UKUL3EHK.js +763 -0
  480. package/dist/chunk-UPHU64NB.js +1327 -0
  481. package/dist/chunk-URMSZXAD.js +43 -0
  482. package/dist/chunk-US3RT6CY.js +525 -0
  483. package/dist/chunk-UTDEOPKV.js +30 -0
  484. package/dist/chunk-UUUDKV7N.js +13 -0
  485. package/dist/chunk-UVKWU3SM.js +39 -0
  486. package/dist/chunk-V2TVPO3X.js +521 -0
  487. package/dist/chunk-V3KLVK7B.js +398 -0
  488. package/dist/chunk-V3YFFHDR.js +17 -0
  489. package/dist/chunk-VAG6GUBR.js +1162 -0
  490. package/dist/chunk-VBENAHDA.js +1814 -0
  491. package/dist/chunk-VBNCKCCI.js +16 -0
  492. package/dist/chunk-VCGSWN5M.js +1300 -0
  493. package/dist/chunk-VE2O2I7M.js +115 -0
  494. package/dist/chunk-VIFHYTI5.js +31 -0
  495. package/dist/chunk-VJER3FUS.js +5080 -0
  496. package/dist/chunk-VLMDM56Q.js +268 -0
  497. package/dist/chunk-VMFZEVVX.js +99 -0
  498. package/dist/chunk-VNDPQVUZ.js +1853 -0
  499. package/dist/chunk-VSPJRLGA.js +4783 -0
  500. package/dist/chunk-VSWC5ZXI.js +103 -0
  501. package/dist/chunk-VYI4DSZP.js +2017 -0
  502. package/dist/chunk-W4BAIQ6L.js +1212 -0
  503. package/dist/chunk-W7VQAL2K.js +2203 -0
  504. package/dist/chunk-WEI3ZDZH.js +33 -0
  505. package/dist/chunk-WEIUS5NT.js +26 -0
  506. package/dist/chunk-WEW7UFWE.js +546 -0
  507. package/dist/chunk-WGQAXLNA.js +384 -0
  508. package/dist/chunk-WJAL4JL3.js +206 -0
  509. package/dist/chunk-WKFOJ5ZG.js +141 -0
  510. package/dist/chunk-WMWQEFLN.js +2177 -0
  511. package/dist/chunk-WNECKKO2.js +154 -0
  512. package/dist/chunk-WPKLYOAM.js +195 -0
  513. package/dist/chunk-WSH37YQN.js +243 -0
  514. package/dist/chunk-WV3KQDPE.js +84 -0
  515. package/dist/chunk-WZFC4V4U.js +389 -0
  516. package/dist/chunk-XCOIBNET.js +13 -0
  517. package/dist/chunk-XDM65LBX.js +53 -0
  518. package/dist/chunk-XGU6PBO5.js +645 -0
  519. package/dist/chunk-XHOI4V62.js +43 -0
  520. package/dist/chunk-XIBVFMLQ.js +6858 -0
  521. package/dist/chunk-XJ2E7YEJ.js +117 -0
  522. package/dist/chunk-XON4ZCYX.js +69 -0
  523. package/dist/chunk-XQPEWJPI.js +127 -0
  524. package/dist/chunk-XSJTIFUY.js +31 -0
  525. package/dist/chunk-XT7OVWM3.js +64 -0
  526. package/dist/chunk-XTXYIISX.js +1104 -0
  527. package/dist/chunk-XV7NZL4B.js +57 -0
  528. package/dist/chunk-XWIZ6B5S.js +109 -0
  529. package/dist/chunk-XWLIKOBX.js +240 -0
  530. package/dist/chunk-XZOXEIN4.js +156 -0
  531. package/dist/chunk-XZRS7I7W.js +3673 -0
  532. package/dist/chunk-Y4ZDDHB6.js +44 -0
  533. package/dist/chunk-Y733RB7T.js +194 -0
  534. package/dist/chunk-YBHUB4XR.js +14931 -0
  535. package/dist/chunk-YKC75XK4.js +147 -0
  536. package/dist/chunk-YKMXFVK7.js +27 -0
  537. package/dist/chunk-YO5BAJ55.js +225 -0
  538. package/dist/chunk-YPDCLXNZ.js +568 -0
  539. package/dist/chunk-YSQPGVFK.js +116 -0
  540. package/dist/chunk-YTVVTIWJ.js +716 -0
  541. package/dist/chunk-YVCMDVBB.js +698 -0
  542. package/dist/chunk-YYTOA6DP.js +114 -0
  543. package/dist/chunk-Z5WGNULV.js +88 -0
  544. package/dist/chunk-Z6NGVVXG.js +66 -0
  545. package/dist/chunk-Z7CDQNH3.js +20 -0
  546. package/dist/chunk-ZH4G3FU5.js +187 -0
  547. package/dist/chunk-ZJB6SQPA.js +257 -0
  548. package/dist/chunk-ZL6E4HMY.js +42 -0
  549. package/dist/chunk-ZMLOC3DW.js +62 -0
  550. package/dist/chunk-ZORW64QH.js +101 -0
  551. package/dist/chunk-ZVVD2XGV.js +1369 -0
  552. package/dist/cli-utils-ER33ODC5.js +31 -0
  553. package/dist/cli-validation-6CHPTANV.js +146 -0
  554. package/dist/commit-utils-3STAY7C7.js +49 -0
  555. package/dist/compatibility-notice-IHNXR2JR.js +21 -0
  556. package/dist/compete-config-resolver-V3GDNJMM.js +125 -0
  557. package/dist/compete-results-XUM3PJHS.js +318 -0
  558. package/dist/competition-outcome-tracker-NWSMVUPG.js +62 -0
  559. package/dist/config-4HHE4OIK.js +238 -0
  560. package/dist/config-D6YAZASH.js +10 -0
  561. package/dist/config-MIPRDYYV.js +46 -0
  562. package/dist/config-audit-GA5DCUAI.js +371 -0
  563. package/dist/config-explain-4LMO556H.js +71 -0
  564. package/dist/config-loader-RGP634PC.js +51 -0
  565. package/dist/config-manager-J2UTO635.js +114 -0
  566. package/dist/config-merger-TVUJBZTS.js +14 -0
  567. package/dist/config-validator-H4ZVIE56.js +122 -0
  568. package/dist/cost-HSIV5U2Y.js +85 -0
  569. package/dist/data-migration-state-OAUL2WPQ.js +35 -0
  570. package/dist/db-migrator-NUOW5NKR.js +34 -0
  571. package/dist/default-paths-UILB62BN.js +49 -0
  572. package/dist/discovery-V6GYUJUC.js +53 -0
  573. package/dist/doctor-BBSMCDWE.js +271 -0
  574. package/dist/doctor-context-blocks-LPY75VZA.js +231 -0
  575. package/dist/doctor-instructions-import-JXHDDOE5.js +70 -0
  576. package/dist/doctor-purpose-6YJOXPBE.js +30 -0
  577. package/dist/domain-analyzer-S35ABUNA.js +48 -0
  578. package/dist/ensure-initialized-Q6PEU55O.js +78 -0
  579. package/dist/entry.js +922 -0
  580. package/dist/error-parser-core-MZFMFANN.js +70 -0
  581. package/dist/evaluation-context-GQBYDAEV.js +63 -0
  582. package/dist/evidence-plan-resolver-5FUAP3SA.js +111 -0
  583. package/dist/execution-data-writer-YCG5UH37.js +72 -0
  584. package/dist/execution-policy-applier-PWZM5LNA.js +63 -0
  585. package/dist/execution-preflight-DASJWWQF.js +223 -0
  586. package/dist/execution-roles-KNSNNB2D.js +112 -0
  587. package/dist/exit-code-error-QIY5DOKF.js +18 -0
  588. package/dist/external-temp-cleanup-CAW7LQ6R.js +360 -0
  589. package/dist/factory-YCYCB7AE.js +209 -0
  590. package/dist/file-utils-ZQYNBQBW.js +45 -0
  591. package/dist/flywheel-allowlist-revert-H22HA6JE.js +21 -0
  592. package/dist/flywheel-autoloop-executor-PDOASJEZ.js +316 -0
  593. package/dist/flywheel-autoloop-unverified-TOKYFCDC.js +36 -0
  594. package/dist/flywheel-competition-executor-YJUMMEJO.js +320 -0
  595. package/dist/flywheel-executor-JWU43KAY.js +437 -0
  596. package/dist/flywheel-git-isolation-FQ2TRWMB.js +56 -0
  597. package/dist/flywheel-manifest-HDPNMWWF.js +114 -0
  598. package/dist/flywheel-model-defaults-UHAKTZT3.js +110 -0
  599. package/dist/flywheel-preflight-III2C7TH.js +163 -0
  600. package/dist/flywheel-resume-2O45MS7Y.js +31 -0
  601. package/dist/flywheel-resume-execution-lease-P2BK257J.js +59 -0
  602. package/dist/flywheel-safety-AVAVFXIJ.js +19 -0
  603. package/dist/flywheel-scope-decision-ALJUUNGG.js +14 -0
  604. package/dist/get-telemetry-logger-MPDVO2JA.js +155 -0
  605. package/dist/git-message-style-KCXGMTDT.js +104 -0
  606. package/dist/guidance-profile-config-G3K5YQOO.js +113 -0
  607. package/dist/guidance-profile-renderer-TX4TNDFL.js +23 -0
  608. package/dist/identity-XLQJ4YJF.js +25 -0
  609. package/dist/index-query-6NUY4FKX.js +37 -0
  610. package/dist/index.js +85588 -0
  611. package/dist/indexer-DL54CM3K.js +44 -0
  612. package/dist/init-OUZ72344.js +245 -0
  613. package/dist/instructions-import-offer-NSYXSITC.js +363 -0
  614. package/dist/instructions-run-NBII7W36.js +114 -0
  615. package/dist/interrupted-work-E4TLKJLE.js +43 -0
  616. package/dist/invoke-provider-auth-NEWEIHCI.js +38 -0
  617. package/dist/judge-scoring.json +64 -0
  618. package/dist/lab-mode-YXQ2Y3NG.js +44 -0
  619. package/dist/lab-utils-5QAMDJR5.js +29 -0
  620. package/dist/linux-host-class-YDWQX65O.js +31 -0
  621. package/dist/llm-judge-executor-OJSNCTFJ.js +179 -0
  622. package/dist/local-ci-config-VZ4WWDT5.js +48 -0
  623. package/dist/local-executor-DCMDDRX2.js +280 -0
  624. package/dist/logger-5KNKS3O4.js +154 -0
  625. package/dist/matrix-prompt-builder-4ZBOGZSB.js +527 -0
  626. package/dist/matrix-result-parser-EZJM4YXP.js +14 -0
  627. package/dist/merge-batch-RTEEMVDB.js +313 -0
  628. package/dist/merge-batch-members-VIWGVRHP.js +24 -0
  629. package/dist/merge-queue-TIIUSOY6.js +126 -0
  630. package/dist/merge-queue-trust-DUNZ4J65.js +21 -0
  631. package/dist/metadata-UKSMWM6J.js +29 -0
  632. package/dist/model-catalog-readiness-R5KJBP5M.js +202 -0
  633. package/dist/model-invocations-db-XTUPPQ34.js +70 -0
  634. package/dist/model-resolver-JFZ2MHOJ.js +39 -0
  635. package/dist/model-resolver-SCQ57KAQ.js +217 -0
  636. package/dist/model-roles-D3OR4NAH.js +110 -0
  637. package/dist/monitor-F4SIU5G2.js +96 -0
  638. package/dist/nested-worktrees-2WUWQ75N.js +23 -0
  639. package/dist/next-S3IRLVER.js +96 -0
  640. package/dist/next-UKPFRXOO.js +148 -0
  641. package/dist/opportunistic-TL4S26VX.js +86 -0
  642. package/dist/optimization-config-resolver-NAEIYU6A.js +148 -0
  643. package/dist/package-HJR4QJT4.js +10 -0
  644. package/dist/parse-git-status-7PIYFPS2.js +21 -0
  645. package/dist/path-security-5WJSY56G.js +41 -0
  646. package/dist/paths-JUI7C4KU.js +45 -0
  647. package/dist/plan-backlog-list-fast-SSTQL5XP.js +89 -0
  648. package/dist/plan-backlog-show-fast-PFRAQ3JB.js +114 -0
  649. package/dist/plan-sprint-list-fast-HD2KBZSY.js +110 -0
  650. package/dist/plan-sprint-status-fast-YFYH7WQF.js +116 -0
  651. package/dist/plan-task-status-fast-JU5PNLUU.js +114 -0
  652. package/dist/plan-to-flywheel-PY5MSY2H.js +529 -0
  653. package/dist/preflight-PJHGTJNZ.js +12 -0
  654. package/dist/process-registry-B4ZUCN7T.js +28 -0
  655. package/dist/process-scanner-TU3QHWVB.js +23 -0
  656. package/dist/processes-6FHVGT72.js +28 -0
  657. package/dist/processes-json-fast-YWTMUWXB.js +72 -0
  658. package/dist/profile-HWTC56SG.js +209 -0
  659. package/dist/project-runtime-paths-2UQNG5Y4.js +41 -0
  660. package/dist/protected-branches-N36LDBFY.js +71 -0
  661. package/dist/provider-aware-resource-manager-YTFAHNGJ.js +40 -0
  662. package/dist/provider-matrix-2KO2V5OM.js +214 -0
  663. package/dist/provider-matrix-renderer-MEC3PER7.js +139 -0
  664. package/dist/provider-output-forwarding-2AHL7YMA.js +26 -0
  665. package/dist/provider-registry-WCZ65QHC.js +136 -0
  666. package/dist/provider-temp-cleanup-IUNPJCZF.js +14 -0
  667. package/dist/prune-engine-EOQVWEP6.js +448 -0
  668. package/dist/publication-turn-S42RZTQF.js +44 -0
  669. package/dist/quality-gate-JQMVCKOO.js +72 -0
  670. package/dist/quickstart-3O6FRCFB.js +105 -0
  671. package/dist/readiness-GW6ABRHB.js +139 -0
  672. package/dist/readiness-KFZCXDTT.js +215 -0
  673. package/dist/registry-7XG376SY.js +217 -0
  674. package/dist/repair-helpers-TTV5FEF4.js +117 -0
  675. package/dist/repo-root-YG6MQZDW.js +28 -0
  676. package/dist/resolution-engine-FFEK7HQ2.js +187 -0
  677. package/dist/resolve-provider-cli-ZEXVZKET.js +44 -0
  678. package/dist/restore-telemetry-db-E7BR5PO7.js +459 -0
  679. package/dist/routing-events-AW6SRZ6G.js +13 -0
  680. package/dist/routing-history-store-FMDDQL6W.js +39 -0
  681. package/dist/routing-planner-C6OHO3EY.js +221 -0
  682. package/dist/runner-KHDNQ5KU.js +1194 -0
  683. package/dist/runner-PIS2BW7Y.js +1801 -0
  684. package/dist/safety-E3JJVSFL.js +67 -0
  685. package/dist/safety-stanza-HE6GXP4G.js +49 -0
  686. package/dist/sandbox-7LBZC5PE.js +72 -0
  687. package/dist/sandbox-ASWCDYZL.js +80 -0
  688. package/dist/schema-extensions.sql +234 -0
  689. package/dist/security-JI22TBEB.js +17 -0
  690. package/dist/setup-bb-plugin-FQXLA76Y.js +531 -0
  691. package/dist/setup-claude-code-NF4ZSHVE.js +197 -0
  692. package/dist/setup-temp-cleanup-2APZ4HMA.js +29 -0
  693. package/dist/shared-utils-34HJZ6JX.js +40 -0
  694. package/dist/simple-artifact-goal-MQLDDMMX.js +29 -0
  695. package/dist/sprint-N7JFTEGL.js +403 -0
  696. package/dist/sprint-bridge-KJXIBNRJ.js +117 -0
  697. package/dist/sprint-completion-dependents-34SR7JVL.js +43 -0
  698. package/dist/sprint-execution-service-A6JPUBWY.js +376 -0
  699. package/dist/sprint-manager-MU2ZUWN2.js +140 -0
  700. package/dist/sqlite-timeout-config-U2CT4LKU.js +13 -0
  701. package/dist/sqlite-wrapper-FSGJ2QEW.js +19 -0
  702. package/dist/stale-cleanup-orchestrator-4X6324VF.js +71 -0
  703. package/dist/storage-access-I3V5LER7.js +31 -0
  704. package/dist/store-XVG64ZR2.js +25 -0
  705. package/dist/task-classifier-MN2DYE5R.js +558 -0
  706. package/dist/task-list-fast-7AT6LTTA.js +112 -0
  707. package/dist/task-manager-LHPBBRRE.js +136 -0
  708. package/dist/task-report-OLPAWBTK.js +64 -0
  709. package/dist/task-type-detector-6RG3YNZF.js +27 -0
  710. package/dist/task-type-resolver-EQHOUIHT.js +64 -0
  711. package/dist/telemetry-5VYSK772.js +212 -0
  712. package/dist/telemetry-health-tracker-4GFW2EMP.js +12 -0
  713. package/dist/telemetry-path-resolver-H3NFHHQY.js +34 -0
  714. package/dist/telemetry-reliability-URJDTNPZ.js +76 -0
  715. package/dist/transports-NREZQTJK.js +106 -0
  716. package/dist/unified-cost-tracker-5MTBJ2CL.js +59 -0
  717. package/dist/unified-state-cleanup-GGAXLHXF.js +292 -0
  718. package/dist/universal-cost-calculator-JTFEJVWK.js +70 -0
  719. package/dist/user-agents-QLIGPLP2.js +30 -0
  720. package/dist/variant-execution-I4ZZUAWY.js +319 -0
  721. package/dist/variant-opt-parser-JHCXKY2K.js +251 -0
  722. package/dist/variant-request-input-PL37N3AN.js +11 -0
  723. package/dist/variant-state-cleanup-KHMXRBZN.js +287 -0
  724. package/dist/variant-worker-COB5YTJX.js +4517 -0
  725. package/dist/variant-worker.js +26 -0
  726. package/dist/variants-XGDSXYG3.js +267 -0
  727. package/dist/verification-command-YSPU4VBH.js +66 -0
  728. package/dist/verify-command-timeout-DQUYH33Z.js +11 -0
  729. package/dist/verify-commands-LOHMOFKC.js +65 -0
  730. package/dist/warning-JSKSFKBT.js +13 -0
  731. package/dist/work-edge-K65NHVWY.js +50 -0
  732. package/dist/work-item-writer-KY5ZWZWW.js +30 -0
  733. package/dist/worker-JNXXEIT6.js +1504 -0
  734. package/dist/worker.js +21 -0
  735. package/dist/workspace-tree-identity-JO5PSKTW.js +52 -0
  736. package/dist/worktree-environment-WTVABAQW.js +64 -0
  737. package/dist/worktree-metrics-VZRQI26T.js +66 -0
  738. package/dist/writeback-TQFQBJNU.js +50 -0
  739. package/docs/CLI_REFERENCE.md +8287 -0
  740. package/docs/PROVIDER_SETUP.md +1737 -0
  741. package/docs/README.md +96 -0
  742. package/docs/TROUBLESHOOTING.md +2209 -0
  743. package/docs/getting-started/QUICK_START.md +260 -0
  744. package/docs/getting-started/README.md +198 -0
  745. package/docs/getting-started/SETUP.md +25 -0
  746. package/docs/reference/AGENT_CONTEXT.md +84 -0
  747. package/docs/reference/DELIVERY_ONBOARDING.md +198 -0
  748. package/docs/reference/PROVIDER_RELEASE_TIERS.md +34 -0
  749. package/docs/reference/SECURITY.md +291 -0
  750. package/docs/reference/TELEMETRY_PRIVACY.md +259 -0
  751. package/integrations/bb-plugin-build/README.md +391 -0
  752. package/integrations/bb-plugin-build/app.css +431 -0
  753. package/integrations/bb-plugin-build/app.tsx +6210 -0
  754. package/integrations/bb-plugin-build/package.json +45 -0
  755. package/integrations/bb-plugin-build/server.ts +488 -0
  756. package/integrations/bb-plugin-build/src/adapter.ts +3672 -0
  757. package/integrations/bb-plugin-build/src/backlog-authoring-model.ts +150 -0
  758. package/integrations/bb-plugin-build/src/backlog-authoring-schema.ts +458 -0
  759. package/integrations/bb-plugin-build/src/backlog-authoring-service.ts +467 -0
  760. package/integrations/bb-plugin-build/src/backlog-authoring-view.ts +1025 -0
  761. package/integrations/bb-plugin-build/src/command-evidence-schema.ts +13 -0
  762. package/integrations/bb-plugin-build/src/competition-defaults-schema.ts +122 -0
  763. package/integrations/bb-plugin-build/src/competition-defaults-service.ts +105 -0
  764. package/integrations/bb-plugin-build/src/competition-defaults-view.ts +138 -0
  765. package/integrations/bb-plugin-build/src/contract.ts +718 -0
  766. package/integrations/bb-plugin-build/src/execution-activity-view.ts +98 -0
  767. package/integrations/bb-plugin-build/src/finalize-model.ts +205 -0
  768. package/integrations/bb-plugin-build/src/finalize-schema.ts +150 -0
  769. package/integrations/bb-plugin-build/src/finalize-service.ts +330 -0
  770. package/integrations/bb-plugin-build/src/finalize-view.ts +159 -0
  771. package/integrations/bb-plugin-build/src/judge-operations-readback.ts +303 -0
  772. package/integrations/bb-plugin-build/src/judge-operations-schema.ts +33 -0
  773. package/integrations/bb-plugin-build/src/judge-operations-view.ts +459 -0
  774. package/integrations/bb-plugin-build/src/model.ts +1318 -0
  775. package/integrations/bb-plugin-build/src/monitor-service.ts +233 -0
  776. package/integrations/bb-plugin-build/src/panel-read-ux.ts +97 -0
  777. package/integrations/bb-plugin-build/src/patch-preview-schema.ts +166 -0
  778. package/integrations/bb-plugin-build/src/patch-preview-service.ts +480 -0
  779. package/integrations/bb-plugin-build/src/patch-preview-view.ts +109 -0
  780. package/integrations/bb-plugin-build/src/planning-readback.ts +228 -0
  781. package/integrations/bb-plugin-build/src/planning-service.ts +647 -0
  782. package/integrations/bb-plugin-build/src/planning-sync-evidence.ts +37 -0
  783. package/integrations/bb-plugin-build/src/planning-workspace-readback.ts +33 -0
  784. package/integrations/bb-plugin-build/src/planning-workspace-schema.ts +131 -0
  785. package/integrations/bb-plugin-build/src/planning-workspace.ts +333 -0
  786. package/integrations/bb-plugin-build/src/poll-handoff.ts +136 -0
  787. package/integrations/bb-plugin-build/src/project-target-server.ts +21 -0
  788. package/integrations/bb-plugin-build/src/project-target.ts +45 -0
  789. package/integrations/bb-plugin-build/src/reference-index.ts +218 -0
  790. package/integrations/bb-plugin-build/src/repository-identity.ts +17 -0
  791. package/integrations/bb-plugin-build/src/repository-schema.ts +30 -0
  792. package/integrations/bb-plugin-build/src/result-explorer-view.ts +597 -0
  793. package/integrations/bb-plugin-build/src/result-readback-model.ts +163 -0
  794. package/integrations/bb-plugin-build/src/result-readback-schema.ts +319 -0
  795. package/integrations/bb-plugin-build/src/result-readback-service.ts +333 -0
  796. package/integrations/bb-plugin-build/src/run-page-view.ts +332 -0
  797. package/integrations/bb-plugin-build/src/setup-config-schema.ts +293 -0
  798. package/integrations/bb-plugin-build/src/setup-config-service.ts +620 -0
  799. package/integrations/bb-plugin-build/src/setup-config-view.ts +388 -0
  800. package/integrations/bb-plugin-build/src/sprint-close-model.ts +150 -0
  801. package/integrations/bb-plugin-build/src/sprint-close-schema.ts +128 -0
  802. package/integrations/bb-plugin-build/src/sprint-close-service.ts +293 -0
  803. package/integrations/bb-plugin-build/src/sprint-close-view.ts +116 -0
  804. package/integrations/bb-plugin-build/src/sprint-composition-model.ts +709 -0
  805. package/integrations/bb-plugin-build/src/sprint-composition-readback.ts +231 -0
  806. package/integrations/bb-plugin-build/src/sprint-composition-schema.ts +597 -0
  807. package/integrations/bb-plugin-build/src/sprint-composition-service.ts +773 -0
  808. package/integrations/bb-plugin-build/src/sprint-composition-view.ts +1221 -0
  809. package/integrations/bb-plugin-build/src/sprint-execution-schema.ts +188 -0
  810. package/integrations/bb-plugin-build/src/sprint-execution-service.ts +289 -0
  811. package/integrations/bb-plugin-build/src/sprint-execution-view.ts +54 -0
  812. package/integrations/bb-plugin-build/src/task-authoring-model.ts +563 -0
  813. package/integrations/bb-plugin-build/src/task-authoring-schema.ts +629 -0
  814. package/integrations/bb-plugin-build/src/task-authoring-service.ts +842 -0
  815. package/integrations/bb-plugin-build/src/task-authoring-view.ts +1227 -0
  816. package/integrations/bb-plugin-build/src/task-catalog-schema.ts +46 -0
  817. package/integrations/bb-plugin-build/src/task-catalog-service.ts +44 -0
  818. package/integrations/bb-plugin-build/src/task-detail-readback.ts +56 -0
  819. package/integrations/bb-plugin-build/src/task-detail-schema.ts +171 -0
  820. package/integrations/bb-plugin-build/src/task-navigation.ts +446 -0
  821. package/integrations/bb-plugin-build/src/workbench-route.ts +74 -0
  822. package/package.json +306 -4
  823. package/schemas/README.md +80 -0
  824. package/schemas/build.config.schema.json +2110 -0
  825. package/schemas/config-v1.schema.json +136 -0
  826. package/schemas/execution-config.schema.json +47 -0
  827. package/schemas/judge-scoring.schema.json +257 -0
  828. package/schemas/provider-config.schema.json +179 -0
  829. package/schemas/telemetry-config.schema.json +79 -0
  830. package/schemas/user-preferences.schema.json +141 -0
  831. package/scripts/assert-node-runtime.mjs +146 -0
  832. package/scripts/preflight-native.mjs +49 -0
  833. package/scripts/setup-git-hooks.mjs +39 -0
  834. package/scripts/sync.sh +2871 -0
  835. package/scripts/write-node-launcher.sh +138 -0
  836. package/src/resources/gemini/slash-packs/default/plan.toml +15 -0
  837. package/src/resources/gemini/slash-packs/default/summary.toml +16 -0
  838. package/src/resources/gemini/slash-packs/default/tests.toml +16 -0
  839. package/templates/.build-project/README.md +41 -0
  840. package/templates/.build-project/agents/README.md +50 -0
  841. package/templates/.build-project/agents/architect.md +10 -0
  842. package/templates/.build-project/agents/code-reviewer.md +10 -0
  843. package/templates/.build-project/agents/debugger.md +10 -0
  844. package/templates/.build-project/agents/documenter.md +10 -0
  845. package/templates/.build-project/agents/test-automator.md +10 -0
  846. package/templates/.build-project/config/build.config.jsonc +64 -0
  847. package/templates/.build-project/config/project-context.template.json +6 -0
  848. package/templates/.build-project/config/task-type-aliases.presets/kanban.yaml +14 -0
  849. package/templates/.build-project/config/task-type-aliases.presets/scrum.yaml +17 -0
  850. package/templates/.build-project/config/task-type-aliases.presets/xp.yaml +12 -0
  851. package/templates/.build-project/config/task-type-aliases.yaml +29 -0
  852. package/templates/.build-project/gitignore.template +70 -0
  853. package/templates/.build-project/task-types/analysis.yaml +38 -0
  854. package/templates/.build-project/task-types/architecture.yaml +35 -0
  855. package/templates/.build-project/task-types/doc.yaml +34 -0
  856. package/templates/.build-project/task-types/feature.yaml +22 -0
  857. package/templates/.build-project/task-types/general.yaml +4 -0
  858. package/templates/.build-project/task-types/security.yaml +38 -0
  859. package/templates/AGENTS.template.md +85 -0
  860. package/templates/CLAUDE.template.md +1 -0
  861. package/templates/GEMINI.template.md +1 -0
  862. package/templates/builtin-workflows/code-review.yaml +73 -0
  863. package/templates/builtin-workflows/skills/code-review/SKILL.md +61 -0
  864. package/templates/builtin-workflows/skills/execution-contract-analysis/SKILL.md +24 -0
  865. package/templates/builtin-workflows/skills/execution-contract-code/SKILL.md +19 -0
  866. package/templates/builtin-workflows/skills/execution-contract-structured/SKILL.md +17 -0
  867. package/templates/ci/incident-intake.mjs +787 -0
  868. package/templates/ci/incidents.yml.template +103 -0
  869. package/templates/ci/node.yml.template +17 -0
  870. package/templates/ci/python.yml.template +17 -0
  871. package/templates/guard-kit/GUARD_SETUP.md.template +258 -0
  872. package/templates/guard-kit/build-guard.yml.template +189 -0
  873. package/templates/guard-kit/check.mjs.template +932 -0
  874. package/templates/guard-kit/config.json.template +7 -0
  875. package/templates/guard-kit/policy.json.template +1 -0
  876. package/templates/profiles/README.md +57 -0
  877. package/templates/profiles/frontier-claude.json +23 -0
  878. package/templates/profiles/frontier-codex.json +23 -0
@@ -0,0 +1,4696 @@
1
+ import {
2
+ buildWinnerReconciliationForResults,
3
+ formatAnalysisSynthesisArtifactPath,
4
+ formatInterruptedCompetitionNotice,
5
+ getDisplayVerificationVerdict,
6
+ getLatestWinnerFlipForTask,
7
+ hasUsableFusionRecommendation,
8
+ normalizeRequiredGatePolicy,
9
+ renderAnalysisSynthesisMarkdown,
10
+ renderFusionDeliverableMarkdown,
11
+ scoreForVariant,
12
+ variantHandlesMatchForResults
13
+ } from "./chunk-LWGKN2GY.js";
14
+ import {
15
+ reconcileRunNestedOptions
16
+ } from "./chunk-QWDV4OSL.js";
17
+ import {
18
+ resolveSynthesisDeliveryProjection,
19
+ undeliveredLineFromTelemetry,
20
+ undeliveredLineLookup
21
+ } from "./chunk-NTD6CSI6.js";
22
+ import {
23
+ deriveSynthesisValueFromArtifactOrSummary,
24
+ formatSynthesisValueRunSummaryLine
25
+ } from "./chunk-I6FN3R5D.js";
26
+ import {
27
+ readRunTaskState
28
+ } from "./chunk-DFHX4XYA.js";
29
+ import {
30
+ findLabRunStateForTask,
31
+ listLabRunDirs
32
+ } from "./chunk-FT7SGLXT.js";
33
+ import {
34
+ extractTitleFromPrompt,
35
+ formatExecutionModeLabel,
36
+ formatTaskLabel
37
+ } from "./chunk-2L36U25O.js";
38
+ import {
39
+ formatJudgeCoverageSummary,
40
+ isSemanticNoWinnerReason
41
+ } from "./chunk-DCACX7BV.js";
42
+ import {
43
+ getCompetitionOperationalReadbackV1,
44
+ toFusionOperationalReadbackV1
45
+ } from "./chunk-HBTTGVR5.js";
46
+ import {
47
+ getMostRecentCompetitionId,
48
+ getRunSnapshotV1,
49
+ normaliseInputSpecWarning,
50
+ readCompetitionState,
51
+ resolveCliStateRoots
52
+ } from "./chunk-AAAODV76.js";
53
+ import {
54
+ TaskIdSchema
55
+ } from "./chunk-AISTV5XU.js";
56
+ import {
57
+ TelemetryLogger,
58
+ judgeModelLabel
59
+ } from "./chunk-PFCXFO7A.js";
60
+ import {
61
+ repairDuplicatedProviderSegment
62
+ } from "./chunk-GZK62I3N.js";
63
+ import {
64
+ resolveProgressNarrationConfig
65
+ } from "./chunk-C3DH3NCY.js";
66
+ import {
67
+ validateCommandOptions
68
+ } from "./chunk-I7SCBHJN.js";
69
+ import {
70
+ normalizeForReconciliation
71
+ } from "./chunk-TGXXYDL4.js";
72
+ import {
73
+ parseJsonWithContext,
74
+ parseJsonWithFallback
75
+ } from "./chunk-P6SSWAKY.js";
76
+ import {
77
+ formatApplicationVerificationLine
78
+ } from "./chunk-SKTFRFQ7.js";
79
+ import {
80
+ readVariantVerification
81
+ } from "./chunk-3OPP2OZB.js";
82
+ import {
83
+ LabPathResolver
84
+ } from "./chunk-C3KCMAJP.js";
85
+ import {
86
+ readDirsForStateRoot,
87
+ resolveCheckoutRoot,
88
+ resolveLabsRoot
89
+ } from "./chunk-AJN5Y5YZ.js";
90
+ import {
91
+ getProviderConfig
92
+ } from "./chunk-QJ6OEH4K.js";
93
+
94
+ // src/cli/commands/compete-results.ts
95
+ import fs from "fs";
96
+ import path2 from "path";
97
+ import chalk6 from "chalk";
98
+ import { Command } from "commander";
99
+ import { z } from "zod";
100
+
101
+ // src/core/progress/judge-operations-projection.ts
102
+ var JUDGE_OPERATIONS_PROJECTION_VERSION = "1.0.0";
103
+ var NO_JUDGE_BY_DESIGN = "No judge by design";
104
+ var NON_JUDGING_RUN_KINDS = /* @__PURE__ */ new Set(["fusion"]);
105
+ var UNAVAILABLE_NOT_RECORDED = { state: "unavailable", reason: "not_recorded" };
106
+ function evidence(value, reason = "not_recorded") {
107
+ return value === void 0 || value === null ? { state: "unavailable", reason } : { state: "available", value };
108
+ }
109
+ function stringEvidence(value, reason = "not_recorded") {
110
+ const trimmed = typeof value === "string" ? value.trim() : "";
111
+ return trimmed.length > 0 ? { state: "available", value: trimmed } : { state: "unavailable", reason };
112
+ }
113
+ function stringList(values) {
114
+ if (!Array.isArray(values)) return [];
115
+ return values.filter((value) => typeof value === "string").map((value) => value.trim()).filter((value) => value.length > 0);
116
+ }
117
+ function unavailableEvidence(reason) {
118
+ return { state: "unavailable", reason };
119
+ }
120
+ function hasNoJudgeEvidence(facts) {
121
+ return facts.judge === void 0 && facts.matrix === void 0 && facts.decision === void 0 && facts.judgesExecuted === void 0 && facts.winner === void 0 && facts.confidence === void 0 && facts.criteria === void 0 && (facts.judgeFailures === void 0 || facts.judgeFailures.length === 0);
122
+ }
123
+ function recordDegraded(facts) {
124
+ return facts.health?.state === "degraded" || facts.health?.state === "unavailable";
125
+ }
126
+ function matrixState(matrix) {
127
+ if (matrix === void 0) return "unavailable";
128
+ if (matrix.autoRun === true) return "escalated";
129
+ if (matrix.autoRun === false) return "not_escalated";
130
+ return "unavailable";
131
+ }
132
+ function matrixProfileDecision(matrix) {
133
+ if (matrix === void 0) return "unknown";
134
+ if (matrix.profileDecision === "unanimous" || matrix.profileDecision === "split" || matrix.profileDecision === "inconclusive") {
135
+ return matrix.profileDecision;
136
+ }
137
+ if (matrix.winnerStatus === "inconclusive") return "inconclusive";
138
+ if (typeof matrix.profilesDisagree === "boolean") {
139
+ return matrix.profilesDisagree ? "split" : "unanimous";
140
+ }
141
+ return "unknown";
142
+ }
143
+ function judgePhase(facts, escalated) {
144
+ const status = facts.judge?.status;
145
+ if (status === "disabled" || status === "skipped") return "not_requested";
146
+ if (status === "requested") return escalated ? "escalated" : "judging";
147
+ if (status === "completed" || status === "failed") return "complete";
148
+ if (escalated) return "escalated";
149
+ return "unavailable";
150
+ }
151
+ function judgeStatus(facts, phase, winner) {
152
+ const status = facts.judge?.status;
153
+ if (status === "disabled" || status === "skipped") return "not_run";
154
+ if (status === "failed") return "degraded";
155
+ if (phase === "judging" || phase === "escalated") {
156
+ return status === "completed" ? judgedOutcome(facts, winner) : "in_flight";
157
+ }
158
+ if (status === "completed") return judgedOutcome(facts, winner);
159
+ return "unavailable";
160
+ }
161
+ function judgedOutcome(facts, winner) {
162
+ if ((facts.judgeFailures ?? []).length > 0) return "degraded";
163
+ if (winner.state === "no_winner") return "inconclusive";
164
+ if (winner.state === "unavailable") return "unavailable";
165
+ if (facts.matrix?.winnerStatus === "inconclusive") return "inconclusive";
166
+ return "decisive";
167
+ }
168
+ function winnerProjection(facts) {
169
+ if (facts.winner === null) return { state: "no_winner" };
170
+ const recorded = facts.winner;
171
+ const selectedVariant = facts.decision?.selectedVariant;
172
+ if (recorded === void 0) {
173
+ if (stringEvidence(selectedVariant).state === "unavailable") {
174
+ const status = facts.judge?.status;
175
+ if (status === "disabled" || status === "skipped") {
176
+ return { state: "unavailable", reason: "not_run" };
177
+ }
178
+ if (status === "requested") return { state: "unavailable", reason: "in_flight" };
179
+ return { state: "unavailable", reason: "not_recorded" };
180
+ }
181
+ return {
182
+ state: "selected",
183
+ identity: {
184
+ variant: stringEvidence(selectedVariant),
185
+ provider: UNAVAILABLE_NOT_RECORDED,
186
+ model: UNAVAILABLE_NOT_RECORDED,
187
+ strategy: UNAVAILABLE_NOT_RECORDED,
188
+ selectionSource: UNAVAILABLE_NOT_RECORDED,
189
+ selectionReason: UNAVAILABLE_NOT_RECORDED
190
+ }
191
+ };
192
+ }
193
+ return {
194
+ state: "selected",
195
+ identity: {
196
+ variant: stringEvidence(recorded.variant ?? selectedVariant),
197
+ provider: stringEvidence(recorded.provider),
198
+ // `resolvedModel` is the model the run actually used when recorded.
199
+ model: stringEvidence(recorded.resolvedModel ?? recorded.model),
200
+ strategy: stringEvidence(recorded.strategy),
201
+ selectionSource: stringEvidence(recorded.winnerSelectionSource),
202
+ selectionReason: stringEvidence(recorded.winnerSelectionReason)
203
+ }
204
+ };
205
+ }
206
+ function artifactProjection(facts) {
207
+ const synthesis = facts.synthesis;
208
+ const application = facts.application;
209
+ return {
210
+ synthesis: synthesis === void 0 ? unavailableEvidence("not_recorded") : {
211
+ state: "available",
212
+ value: {
213
+ status: stringEvidence(synthesis.status),
214
+ expected: evidence(synthesis.expected),
215
+ artifactPath: stringEvidence(synthesis.artifactPath),
216
+ jsonPath: stringEvidence(synthesis.jsonPath),
217
+ contributorCount: evidence(synthesis.contributorCount)
218
+ }
219
+ },
220
+ delivery: application === void 0 ? unavailableEvidence("not_recorded") : {
221
+ state: "available",
222
+ value: {
223
+ status: stringEvidence(application.status),
224
+ variantId: stringEvidence(application.variantId),
225
+ branch: stringEvidence(application.targetBranch),
226
+ commit: stringEvidence(application.targetPostApplyHeadSha)
227
+ }
228
+ }
229
+ };
230
+ }
231
+ function criteriaProjection(facts) {
232
+ const criteria = facts.criteria;
233
+ if (criteria === void 0) return unavailableEvidence("not_recorded");
234
+ const mapped = criteria.filter(
235
+ (entry) => typeof entry?.criterion === "string" && entry.criterion.trim().length > 0 && typeof entry.assessment === "string" && entry.assessment.trim().length > 0
236
+ ).map((entry) => ({
237
+ criterion: entry.criterion.trim(),
238
+ assessment: entry.assessment.trim(),
239
+ evidence: stringList(entry.evidence),
240
+ provenance: stringEvidence(entry.provenance)
241
+ }));
242
+ return mapped.length > 0 ? { state: "available", value: mapped } : unavailableEvidence("not_recorded");
243
+ }
244
+ function stackProjection(facts) {
245
+ const executed = stringList(facts.judgesExecuted);
246
+ const primaryJudge = stringEvidence(facts.decision?.primaryJudge);
247
+ const executedEvidence = facts.judgesExecuted === void 0 ? (
248
+ // A recorded primary judge is itself evidence that one judge executed.
249
+ primaryJudge.state === "available" ? { state: "available", value: [primaryJudge.value] } : unavailableEvidence("not_recorded")
250
+ ) : { state: "available", value: executed };
251
+ return {
252
+ requested: stringEvidence(facts.judge?.requested),
253
+ executed: executedEvidence,
254
+ failures: (facts.judgeFailures ?? []).map((failure) => ({
255
+ judgeType: typeof failure?.judgeType === "string" ? failure.judgeType.trim() : "",
256
+ reason: typeof failure?.reason === "string" ? failure.reason.trim() : ""
257
+ })).filter((failure) => failure.judgeType.length > 0 || failure.reason.length > 0)
258
+ };
259
+ }
260
+ function verdictProjection(facts) {
261
+ const confidence = facts.confidence;
262
+ return {
263
+ primaryJudge: stringEvidence(facts.decision?.primaryJudge),
264
+ outcome: stringEvidence(facts.decision?.decisionOutcome ?? facts.decision?.outcome),
265
+ reason: stringEvidence(facts.decision?.reason ?? facts.judge?.reason),
266
+ confidence: typeof confidence === "number" && Number.isFinite(confidence) ? { state: "available", value: confidence } : unavailableEvidence("not_recorded")
267
+ };
268
+ }
269
+ function matrixProjection(facts) {
270
+ const matrix = facts.matrix;
271
+ const state = matrixState(matrix);
272
+ return {
273
+ state,
274
+ evaluatorType: stringEvidence(matrix?.evaluatorType),
275
+ profiles: evidence(matrix?.profiles),
276
+ winnerStatus: stringEvidence(matrix?.winnerStatus),
277
+ escalationReasons: stringList(matrix?.escalationReasons),
278
+ profileDecision: matrixProfileDecision(matrix),
279
+ caveats: stringList(matrix?.winnerCaveats),
280
+ blockingHumanChecks: matrix?.blockingHumanChecks === void 0 ? unavailableEvidence("not_recorded") : { state: "available", value: stringList(matrix.blockingHumanChecks) },
281
+ advisoryHumanChecks: matrix?.advisoryHumanChecks === void 0 ? unavailableEvidence("not_recorded") : { state: "available", value: stringList(matrix.advisoryHumanChecks) }
282
+ };
283
+ }
284
+ function recordCaveats(facts) {
285
+ const health = facts.health;
286
+ if (health === void 0) return [];
287
+ const caveats = [];
288
+ if (health.state !== "healthy") caveats.push(`health ${health.state}`);
289
+ for (const issue of stringList(health.issues)) caveats.push(`issue ${issue}`);
290
+ return caveats;
291
+ }
292
+ function notApplicableProjection(facts) {
293
+ return {
294
+ version: JUDGE_OPERATIONS_PROJECTION_VERSION,
295
+ runId: facts.id,
296
+ kind: facts.kind,
297
+ applicability: "not_applicable",
298
+ notApplicableReason: NO_JUDGE_BY_DESIGN,
299
+ phase: "not_applicable",
300
+ status: "not_applicable",
301
+ stack: {
302
+ requested: unavailableEvidence("not_applicable"),
303
+ executed: unavailableEvidence("not_applicable"),
304
+ failures: []
305
+ },
306
+ verdict: {
307
+ primaryJudge: unavailableEvidence("not_applicable"),
308
+ outcome: unavailableEvidence("not_applicable"),
309
+ reason: unavailableEvidence("not_applicable"),
310
+ confidence: unavailableEvidence("not_applicable")
311
+ },
312
+ matrix: {
313
+ state: "unavailable",
314
+ evaluatorType: unavailableEvidence("not_applicable"),
315
+ profiles: unavailableEvidence("not_applicable"),
316
+ winnerStatus: unavailableEvidence("not_applicable"),
317
+ escalationReasons: [],
318
+ profileDecision: "unknown",
319
+ caveats: [],
320
+ blockingHumanChecks: unavailableEvidence("not_applicable"),
321
+ advisoryHumanChecks: unavailableEvidence("not_applicable")
322
+ },
323
+ criteria: unavailableEvidence("not_applicable"),
324
+ winner: { state: "unavailable", reason: "not_applicable" },
325
+ // Fusion still synthesizes and delivers, so artifact evidence is reported.
326
+ artifacts: artifactProjection(facts),
327
+ caveats: recordCaveats(facts)
328
+ };
329
+ }
330
+ function projectJudgeOperations(facts) {
331
+ if (NON_JUDGING_RUN_KINDS.has(facts.kind)) return notApplicableProjection(facts);
332
+ const winner = winnerProjection(facts);
333
+ const matrix = matrixProjection(facts);
334
+ const historical = hasNoJudgeEvidence(facts);
335
+ const phase = historical ? "unavailable" : judgePhase(facts, matrix.state === "escalated");
336
+ const status = historical ? "unavailable" : judgeStatus(facts, phase, winner);
337
+ return {
338
+ version: JUDGE_OPERATIONS_PROJECTION_VERSION,
339
+ runId: facts.id,
340
+ kind: facts.kind,
341
+ applicability: "applicable",
342
+ phase,
343
+ status: (
344
+ // A degraded canonical record cannot support a decisive claim.
345
+ status === "decisive" && recordDegraded(facts) ? "degraded" : status
346
+ ),
347
+ stack: stackProjection(facts),
348
+ verdict: verdictProjection(facts),
349
+ matrix,
350
+ criteria: criteriaProjection(facts),
351
+ winner,
352
+ artifacts: artifactProjection(facts),
353
+ caveats: recordCaveats(facts)
354
+ };
355
+ }
356
+
357
+ // src/core/progress/run-progress-projection.ts
358
+ var RUN_PROGRESS_VARIANT_LIMIT = 20;
359
+ var RUN_PROGRESS_MAX_LINE_CHARS = 160;
360
+ var DEFAULT_OBSERVED_ACTIVITY_MAX_AGE_MS = 6e4;
361
+ var TERMINAL_STATUSES = /* @__PURE__ */ new Set([
362
+ "succeeded",
363
+ "failed",
364
+ "cancelled"
365
+ ]);
366
+ var OBSERVED_ACTIVITY_LABELS = {
367
+ tool: {
368
+ apply_patch: "applying edits",
369
+ bash: "running command",
370
+ build: "building",
371
+ edit: "editing files",
372
+ edit_file: "editing files",
373
+ glob: "inspecting files",
374
+ grep: "searching files",
375
+ lint: "linting",
376
+ read: "reading files",
377
+ read_file: "reading files",
378
+ search: "searching files",
379
+ shell: "running command",
380
+ test: "running tests",
381
+ verify: "verifying",
382
+ write: "writing files",
383
+ write_file: "writing files"
384
+ },
385
+ step: {
386
+ active: "working",
387
+ building: "building",
388
+ editing: "editing",
389
+ inspecting: "inspecting",
390
+ linting: "linting",
391
+ planning: "planning",
392
+ searching: "searching",
393
+ testing: "testing",
394
+ verifying: "verifying"
395
+ }
396
+ };
397
+ function observedActivityLabel(signal) {
398
+ const key = signal.name.trim().toLowerCase();
399
+ if (!/^[a-z][a-z0-9_-]*$/.test(key)) return void 0;
400
+ return OBSERVED_ACTIVITY_LABELS[signal.kind][key];
401
+ }
402
+ function truncateLine(text) {
403
+ const normalized = text.replace(/\s+/g, " ").trim();
404
+ if (normalized.length <= RUN_PROGRESS_MAX_LINE_CHARS) return normalized;
405
+ return `${normalized.slice(0, RUN_PROGRESS_MAX_LINE_CHARS - 3)}...`;
406
+ }
407
+ function boundedVariantLimit(value) {
408
+ if (value === void 0 || !Number.isFinite(value)) return RUN_PROGRESS_VARIANT_LIMIT;
409
+ return Math.min(RUN_PROGRESS_VARIANT_LIMIT, Math.max(0, Math.floor(value)));
410
+ }
411
+ function isStale(facts) {
412
+ return facts.freshness.state === "stale" || facts.health.issues.includes("stale");
413
+ }
414
+ function hasStartedWork(facts) {
415
+ if (facts.progress.completedVariants > 0) return true;
416
+ if (facts.variants.some((variant) => variant.status !== "running")) return true;
417
+ if (facts.variants.some((variant) => (variant.changedFiles ?? 0) > 0)) return true;
418
+ const { createdAt, lastActivityAt } = facts.timestamps;
419
+ if (!lastActivityAt) return false;
420
+ if (!createdAt) return true;
421
+ return Date.parse(lastActivityAt) > Date.parse(createdAt);
422
+ }
423
+ function deriveRunProgressPhase(facts) {
424
+ if (TERMINAL_STATUSES.has(facts.status)) return "completed";
425
+ if (isStale(facts)) return "stale";
426
+ if (facts.status === "unknown") return "unknown";
427
+ switch (facts.phase) {
428
+ case "judge":
429
+ return "judging";
430
+ case "synthesis":
431
+ return "synthesizing";
432
+ case "delivery":
433
+ return "finalizing";
434
+ case "execution":
435
+ return hasStartedWork(facts) ? "active" : "queued";
436
+ default:
437
+ return "unknown";
438
+ }
439
+ }
440
+ function variantPhase(variant) {
441
+ if (variant.status === "succeeded" || variant.status === "failed" || variant.status === "cancelled") {
442
+ return "completed";
443
+ }
444
+ if (variant.status === "unknown") return "unknown";
445
+ switch (variant.phase) {
446
+ case "judge":
447
+ return "judging";
448
+ case "synthesis":
449
+ return "synthesizing";
450
+ case "delivery":
451
+ return "finalizing";
452
+ case "execution":
453
+ return (variant.changedFiles ?? 0) > 0 ? "active" : "queued";
454
+ default:
455
+ return "unknown";
456
+ }
457
+ }
458
+ function coarseVariantDetail(variant, phase) {
459
+ switch (phase) {
460
+ case "completed": {
461
+ const gates = [
462
+ variant.verification?.buildStatus ? `build ${variant.verification.buildStatus}` : void 0,
463
+ variant.verification?.testStatus ? `tests ${variant.verification.testStatus}` : void 0
464
+ ].filter((value) => value !== void 0);
465
+ const outcome = variant.status === "succeeded" ? "succeeded" : variant.status;
466
+ return gates.length > 0 ? `${outcome}, ${gates.join(", ")}` : outcome;
467
+ }
468
+ case "queued":
469
+ return variant.status === "detached" ? "detached, no local activity observed" : "queued";
470
+ case "active": {
471
+ const changed = variant.changedFiles ?? 0;
472
+ return changed > 0 ? `working, ${changed} file(s) changed` : "working";
473
+ }
474
+ case "verifying":
475
+ return "verifying";
476
+ case "finalizing":
477
+ return "finalizing";
478
+ case "judging":
479
+ return "judging";
480
+ case "synthesizing":
481
+ return "synthesizing";
482
+ case "stale":
483
+ return "no recent activity observed";
484
+ default:
485
+ return "state unavailable";
486
+ }
487
+ }
488
+ function resolveObservedDetail(runId, variant, phase, options, now) {
489
+ const coarse = { text: coarseVariantDetail(variant, phase), observed: false };
490
+ const signal = options.observedActivity?.[runId]?.[variant.id];
491
+ if (signal === void 0) return coarse;
492
+ if (phase !== "active" && phase !== "verifying") return coarse;
493
+ const maxAgeMs = options.observedActivityMaxAgeMs ?? DEFAULT_OBSERVED_ACTIVITY_MAX_AGE_MS;
494
+ const age = now - signal.observedAt;
495
+ if (!Number.isFinite(age) || age < 0 || age > maxAgeMs) return coarse;
496
+ const label = observedActivityLabel(signal);
497
+ if (label === void 0) return coarse;
498
+ return {
499
+ text: label,
500
+ observed: true
501
+ };
502
+ }
503
+ function variantLine(runId, variant, options, now) {
504
+ const phase = variantPhase(variant);
505
+ const detail = resolveObservedDetail(runId, variant, phase, options, now);
506
+ const label = variant.model ? `${variant.provider} ${variant.model}` : variant.provider;
507
+ return {
508
+ variantId: variant.id,
509
+ provider: variant.provider,
510
+ status: variant.status,
511
+ phase,
512
+ observed: detail.observed,
513
+ detail: truncateLine(`${phase}: ${detail.text}`),
514
+ text: truncateLine(`${label} ${phase}: ${detail.text}`)
515
+ };
516
+ }
517
+ function snapshotCaveats(facts) {
518
+ const caveats = [];
519
+ if (facts.health.state !== "healthy") caveats.push(`health ${facts.health.state}`);
520
+ for (const issue of facts.health.issues) caveats.push(`issue ${issue}`);
521
+ if (facts.freshness.state === "stale" || facts.freshness.state === "unknown") {
522
+ caveats.push(`freshness ${facts.freshness.state}`);
523
+ }
524
+ return caveats;
525
+ }
526
+ function aggregateDetail(facts, phase, caveats) {
527
+ const { completedVariants, totalVariants } = facts.progress;
528
+ const counts = totalVariants > 0 ? `${completedVariants}/${totalVariants} variants complete` : "";
529
+ const parts = [];
530
+ if (phase === "completed") parts.push(facts.status);
531
+ if (phase === "stale") parts.push("no recent activity observed");
532
+ if (phase === "unknown") parts.push("run state unavailable");
533
+ if (counts) parts.push(counts);
534
+ if (caveats.length > 0) parts.push(caveats.join(", "));
535
+ return parts.join(" | ");
536
+ }
537
+ function activityStatus(status) {
538
+ if (status === "running") return "running";
539
+ if (status === "succeeded") return "succeeded";
540
+ if (status === "failed") return "failed";
541
+ if (status === "cancelled") return "cancelled";
542
+ return "unknown";
543
+ }
544
+ function activityLabel(phase) {
545
+ if (phase === "judging") return "Judge";
546
+ if (phase === "synthesizing") return "Synthesis";
547
+ if (phase === "finalizing") return "Delivery";
548
+ if (phase === "completed") return "Outcome";
549
+ return "Execution";
550
+ }
551
+ function projectActivity(facts, phase, text, variants) {
552
+ const terminal = TERMINAL_STATUSES.has(facts.status);
553
+ const status = terminal ? facts.status === "succeeded" ? "succeeded" : facts.status === "failed" ? "failed" : facts.status === "cancelled" ? "cancelled" : "unknown" : phase === "stale" || phase === "unknown" ? "unknown" : "running";
554
+ return {
555
+ schemaVersion: "1.0.0",
556
+ position: facts.progress.totalVariants > 0 ? `${facts.progress.completedVariants} of ${facts.progress.totalVariants} variants complete` : null,
557
+ milestones: [
558
+ {
559
+ id: phase,
560
+ label: activityLabel(phase),
561
+ status,
562
+ detail: text,
563
+ items: variants.map((variant) => ({
564
+ id: variant.variantId,
565
+ label: variant.provider,
566
+ status: activityStatus(variant.status),
567
+ detail: variant.detail
568
+ }))
569
+ }
570
+ ]
571
+ };
572
+ }
573
+ function progressSignature(facts, phase, variants, caveats) {
574
+ const variantPart = variants.map((variant) => `${variant.variantId}=${variant.phase}:${variant.text}`).join(";");
575
+ return [
576
+ facts.id,
577
+ facts.status,
578
+ phase,
579
+ `${facts.progress.completedVariants}/${facts.progress.totalVariants}`,
580
+ caveats.join(","),
581
+ variantPart
582
+ ].join("|");
583
+ }
584
+ function snapshotTimestamp(facts) {
585
+ const timestamps = [
586
+ facts.timestamps.createdAt,
587
+ facts.timestamps.updatedAt,
588
+ facts.timestamps.completedAt,
589
+ facts.timestamps.lastActivityAt
590
+ ].map((value) => value === void 0 ? void 0 : Date.parse(value)).filter((value) => value !== void 0 && Number.isFinite(value));
591
+ const latest = timestamps.length > 0 ? Math.max(...timestamps) : 0;
592
+ return new Date(latest).toISOString();
593
+ }
594
+ function projectRunProgress(facts, options = {}) {
595
+ const now = options.now !== void 0 && Number.isFinite(options.now) ? options.now : Date.now();
596
+ const phase = deriveRunProgressPhase(facts);
597
+ const caveats = snapshotCaveats(facts);
598
+ const limit = boundedVariantLimit(options.variantLimit);
599
+ const variants = limit === 0 ? [] : [...facts.variants].sort((left, right) => left.id.localeCompare(right.id)).slice(0, limit).map((variant) => variantLine(facts.id, variant, options, now));
600
+ const detail = aggregateDetail(facts, phase, caveats);
601
+ const text = truncateLine(
602
+ detail ? `${facts.kind} ${phase}: ${detail}` : `${facts.kind} ${phase}`
603
+ );
604
+ return {
605
+ runId: facts.id,
606
+ phase,
607
+ text,
608
+ progress: { ...facts.progress },
609
+ terminal: TERMINAL_STATUSES.has(facts.status),
610
+ caveats,
611
+ variants,
612
+ activityV1: projectActivity(facts, phase, text, variants),
613
+ signature: progressSignature(facts, phase, variants, caveats),
614
+ snapshotAt: snapshotTimestamp(facts),
615
+ observedAt: new Date(now).toISOString()
616
+ };
617
+ }
618
+
619
+ // src/core/progress/run-narration-request.ts
620
+ var RUN_NARRATION_REQUEST_VERSION = "1.0.0";
621
+ var RUN_NARRATION_DEFAULT_MIN_INTERVAL_MS = 15e3;
622
+ var RUN_NARRATION_DEFAULT_MAX_AGE_MS = 6e4;
623
+ var RUN_NARRATION_DEFAULT_TIMEOUT_MS = 1e4;
624
+ var RUN_NARRATION_DEFAULT_MAX_FAILURES = 3;
625
+ function nonEmpty(value) {
626
+ const trimmed = value?.trim();
627
+ return trimmed ? trimmed : void 0;
628
+ }
629
+ function boundedInteger(value, fallback, maximum) {
630
+ if (value === void 0 || !Number.isFinite(value)) return fallback;
631
+ const integer = Math.floor(value);
632
+ if (integer <= 0) return fallback;
633
+ return Math.min(integer, maximum);
634
+ }
635
+ function normalizeProgressNarrationConfig(input) {
636
+ const provider = nonEmpty(input?.provider);
637
+ const model = nonEmpty(input?.model);
638
+ const enabled = input?.enabled === true && provider !== void 0;
639
+ return {
640
+ enabled,
641
+ ...enabled ? { provider } : {},
642
+ ...enabled && model ? { model } : {},
643
+ minIntervalMs: boundedInteger(
644
+ input?.minIntervalMs,
645
+ RUN_NARRATION_DEFAULT_MIN_INTERVAL_MS,
646
+ 6e5
647
+ ),
648
+ maxAgeMs: boundedInteger(input?.maxAgeMs, RUN_NARRATION_DEFAULT_MAX_AGE_MS, 6e5),
649
+ maxChars: boundedInteger(
650
+ input?.maxChars,
651
+ RUN_PROGRESS_MAX_LINE_CHARS,
652
+ RUN_PROGRESS_MAX_LINE_CHARS
653
+ ),
654
+ timeoutMs: boundedInteger(input?.timeoutMs, RUN_NARRATION_DEFAULT_TIMEOUT_MS, 12e4),
655
+ maxConsecutiveFailures: boundedInteger(
656
+ input?.maxConsecutiveFailures,
657
+ RUN_NARRATION_DEFAULT_MAX_FAILURES,
658
+ 20
659
+ )
660
+ };
661
+ }
662
+ function boundedFactText(value, maximum) {
663
+ const withoutControlCharacters = [...value].map((character) => {
664
+ const codePoint = character.codePointAt(0) ?? 0;
665
+ return codePoint <= 31 || codePoint === 127 ? " " : character;
666
+ }).join("");
667
+ const normalized = withoutControlCharacters.replace(/\s+/g, " ").trim();
668
+ if (normalized.length <= maximum) return normalized;
669
+ return `${normalized.slice(0, Math.max(1, maximum - 3))}...`;
670
+ }
671
+ function buildRunNarrationRequestV1(projection, configInput, advisoryInput) {
672
+ const config = normalizeProgressNarrationConfig(configInput);
673
+ return {
674
+ schemaVersion: RUN_NARRATION_REQUEST_VERSION,
675
+ enabled: config.enabled,
676
+ provider: config.provider ?? null,
677
+ model: config.model ?? null,
678
+ minIntervalMs: config.minIntervalMs,
679
+ maxAgeMs: config.maxAgeMs,
680
+ maxChars: config.maxChars,
681
+ timeoutMs: config.timeoutMs,
682
+ maxConsecutiveFailures: config.maxConsecutiveFailures,
683
+ signature: projection.signature,
684
+ advisory: {
685
+ configurationError: advisoryInput?.configurationError ? boundedFactText(advisoryInput.configurationError, 200) : null
686
+ },
687
+ facts: {
688
+ runId: boundedFactText(projection.runId, 160),
689
+ phase: projection.phase,
690
+ terminal: projection.terminal,
691
+ progress: { ...projection.progress },
692
+ caveats: projection.caveats.slice(0, 10).map((value) => boundedFactText(value, 80)),
693
+ variants: projection.variants.slice(0, RUN_PROGRESS_VARIANT_LIMIT).map((variant) => ({
694
+ variantId: boundedFactText(variant.variantId, 160),
695
+ provider: boundedFactText(variant.provider, 80),
696
+ phase: variant.phase,
697
+ detail: boundedFactText(variant.text, RUN_PROGRESS_MAX_LINE_CHARS)
698
+ }))
699
+ }
700
+ };
701
+ }
702
+
703
+ // src/cli/formatters/warning-formatter.ts
704
+ import chalk from "chalk";
705
+ var WarningFormatter = class {
706
+ verbosity;
707
+ /**
708
+ * Create a new warning formatter.
709
+ *
710
+ * @param verbosity - Output verbosity level (defaults to 'normal')
711
+ */
712
+ constructor(verbosity = "normal") {
713
+ this.verbosity = verbosity;
714
+ }
715
+ /**
716
+ * Format warnings for CLI display.
717
+ *
718
+ * Groups warnings by severity and formats according to verbosity level.
719
+ *
720
+ * @param warnings - Array of structured warnings to format
721
+ * @returns Formatted warning output string
722
+ */
723
+ formatWarnings(warnings) {
724
+ if (this.verbosity === "silent" || warnings.length === 0) {
725
+ return "";
726
+ }
727
+ const lines = [];
728
+ const errors = warnings.filter((w) => w.severity === "ERROR");
729
+ const warns = warnings.filter((w) => w.severity === "WARN");
730
+ const infos = warnings.filter((w) => w.severity === "INFO");
731
+ if (this.verbosity === "minimal") {
732
+ const parts = [];
733
+ if (errors.length > 0) {
734
+ parts.push(chalk.red(`${errors.length} error(s)`));
735
+ }
736
+ if (warns.length > 0) {
737
+ parts.push(chalk.yellow(`${warns.length} warning(s)`));
738
+ }
739
+ return parts.join(", ");
740
+ }
741
+ if (errors.length > 0) {
742
+ lines.push(chalk.red.bold("\nErrors:"));
743
+ for (const warning of errors) {
744
+ lines.push(this.formatWarning(warning));
745
+ }
746
+ }
747
+ if (warns.length > 0) {
748
+ lines.push(chalk.yellow.bold("\nWarnings:"));
749
+ for (const warning of warns) {
750
+ lines.push(this.formatWarning(warning));
751
+ }
752
+ }
753
+ if (this.verbosity === "verbose" && infos.length > 0) {
754
+ lines.push(chalk.blue.bold("\nInfo:"));
755
+ for (const warning of infos) {
756
+ lines.push(this.formatWarning(warning));
757
+ }
758
+ }
759
+ return lines.join("\n");
760
+ }
761
+ /**
762
+ * Format a single warning.
763
+ *
764
+ * @param warning - The warning to format
765
+ * @returns Formatted warning string
766
+ */
767
+ formatWarning(warning) {
768
+ const lines = [];
769
+ const label = this.getLabelForSeverity(warning.severity);
770
+ const color = this.getColorForSeverity(warning.severity);
771
+ lines.push(color(` ${label} [${warning.code}] ${warning.message}`));
772
+ if (this.verbosity === "verbose") {
773
+ if (warning.context.provider) {
774
+ lines.push(chalk.dim(` Provider: ${warning.context.provider}`));
775
+ }
776
+ if (warning.context.executionPhase) {
777
+ lines.push(chalk.dim(` Phase: ${warning.context.executionPhase}`));
778
+ }
779
+ if (warning.recovered) {
780
+ lines.push(chalk.green(` OK Recovered: ${warning.recoveryMechanism || "automatic"}`));
781
+ }
782
+ if (warning.metadata && Object.keys(warning.metadata).length > 0) {
783
+ lines.push(chalk.dim(` Metadata: ${JSON.stringify(warning.metadata)}`));
784
+ }
785
+ }
786
+ return lines.join("\n");
787
+ }
788
+ /**
789
+ * Format warning summary.
790
+ *
791
+ * Provides a concise summary of warnings by severity.
792
+ *
793
+ * @param warnings - Array of warnings to summarize
794
+ * @returns Formatted summary string
795
+ */
796
+ formatSummary(warnings) {
797
+ if (this.verbosity === "silent" || warnings.length === 0) {
798
+ return "";
799
+ }
800
+ const errors = warnings.filter((w) => w.severity === "ERROR").length;
801
+ const warns = warnings.filter((w) => w.severity === "WARN").length;
802
+ const infos = warnings.filter((w) => w.severity === "INFO").length;
803
+ const recovered = warnings.filter((w) => w.recovered).length;
804
+ const parts = [];
805
+ if (errors > 0) parts.push(chalk.red(`${errors} error(s)`));
806
+ if (warns > 0) parts.push(chalk.yellow(`${warns} warning(s)`));
807
+ if (infos > 0) parts.push(chalk.blue(`${infos} info`));
808
+ if (recovered > 0) parts.push(chalk.green(`${recovered} recovered`));
809
+ return parts.join(", ");
810
+ }
811
+ /**
812
+ * Format a validation result for CLI display.
813
+ *
814
+ * Intended for human-readable summaries of structured validation output.
815
+ */
816
+ formatValidationResult(result) {
817
+ if (this.verbosity === "silent") return "";
818
+ const statusLine = result.valid ? "Validation passed" : "Validation failed";
819
+ if (this.verbosity === "minimal") {
820
+ return statusLine;
821
+ }
822
+ const meta = result.metadata ?? {};
823
+ const icon = (ok) => ok ? "OK" : "Error";
824
+ const testsIcon = meta.testsRun === false ? "Error" : icon(meta.testsPass);
825
+ const lines = [statusLine];
826
+ lines.push(`Tests: ${testsIcon}`);
827
+ lines.push(`Lint: ${icon(meta.lintPass)}`);
828
+ lines.push(`Build: ${icon(meta.buildSuccess)}`);
829
+ lines.push(`Completeness: ${Math.round(meta.completeness ?? 0)}%`);
830
+ if (this.verbosity === "verbose") {
831
+ lines.push(`Git clean: ${icon(meta.gitClean)}`);
832
+ lines.push(`Warnings: ${result.warnings?.length ?? 0}`);
833
+ lines.push(`Errors: ${result.errors?.length ?? 0}`);
834
+ }
835
+ return lines.join("\n");
836
+ }
837
+ /**
838
+ * Update verbosity level.
839
+ *
840
+ * @param verbosity - New verbosity level
841
+ */
842
+ setVerbosity(verbosity) {
843
+ this.verbosity = verbosity;
844
+ }
845
+ /**
846
+ * Get current verbosity level.
847
+ *
848
+ * @returns Current verbosity level
849
+ */
850
+ getVerbosity() {
851
+ return this.verbosity;
852
+ }
853
+ /**
854
+ * Get plain label for warning severity.
855
+ *
856
+ * @param severity - Warning severity level
857
+ * @returns Label text
858
+ */
859
+ getLabelForSeverity(severity) {
860
+ switch (severity) {
861
+ case "ERROR":
862
+ return "Error:";
863
+ case "WARN":
864
+ return "Warning:";
865
+ case "INFO":
866
+ return "Info:";
867
+ default:
868
+ return "Info:";
869
+ }
870
+ }
871
+ /**
872
+ * Get chalk color function for warning severity.
873
+ *
874
+ * @param severity - Warning severity level
875
+ * @returns Chalk color function
876
+ */
877
+ getColorForSeverity(severity) {
878
+ switch (severity) {
879
+ case "ERROR":
880
+ return chalk.red;
881
+ case "WARN":
882
+ return chalk.yellow;
883
+ case "INFO":
884
+ return chalk.blue;
885
+ default:
886
+ return chalk.white;
887
+ }
888
+ }
889
+ };
890
+
891
+ // src/cli/handlers/compete/competition-status-projection.ts
892
+ var SYNTHESIS_FAILURE_STATUSES = /* @__PURE__ */ new Set([
893
+ "failed",
894
+ "gate_failed",
895
+ "generation_failed",
896
+ "timed_out",
897
+ "editable_workspace_unavailable"
898
+ ]);
899
+ var SYNTHESIS_DEGRADED_STATUSES = /* @__PURE__ */ new Set([...SYNTHESIS_FAILURE_STATUSES, "degraded", "partial"]);
900
+ function resolveExecutionHealthFromCompetitionState(state) {
901
+ if (state.status === "running") {
902
+ const variants = [
903
+ ...state.variants ?? [],
904
+ ...getRawCompetitionCandidatesFromCompetitionState(state)
905
+ ];
906
+ return variants.some((variant) => variant.success === false) ? "degraded" : "clean";
907
+ }
908
+ const synthesis = resolveProjectionSynthesis(state);
909
+ if (synthesis?.expected === true && (isSynthesisDegradedStatus(synthesis.status) || state.runMetadata?.runSemantics === "fusion" && !synthesis.status)) {
910
+ if (state.runMetadata?.runSemantics === "fusion" && (isSynthesisFailureStatus(synthesis.status) || !synthesis.status)) {
911
+ return "failed";
912
+ }
913
+ return "degraded";
914
+ }
915
+ if (state.runMetadata?.runSemantics === "fusion" && synthesis?.expected === true && synthesis.status === "succeeded") {
916
+ return "clean";
917
+ }
918
+ if (isJudgeOffComparisonState(state)) {
919
+ return state.variants?.some((variant) => variant.success === false) ? "degraded" : "clean";
920
+ }
921
+ if (state.outcome !== "winner_selected" || !state.winner) {
922
+ return "failed";
923
+ }
924
+ return hasIncompleteWinnerSelectedVariant(state) ? "degraded" : "clean";
925
+ }
926
+ function resolveCompetitionResultFromCompetitionState(state) {
927
+ if (state.status === "running") return "incomplete";
928
+ const synthesis = resolveProjectionSynthesis(state);
929
+ if (synthesis?.expected === true) {
930
+ if (state.runMetadata?.runSemantics === "fusion" && (isSynthesisFailureStatus(synthesis.status) || !synthesis.status)) {
931
+ return "failed";
932
+ }
933
+ if (state.runMetadata?.runSemantics === "fusion" && synthesis.status === "succeeded") {
934
+ return "success";
935
+ }
936
+ if (isSynthesisDegradedStatus(synthesis.status)) {
937
+ return "degraded";
938
+ }
939
+ }
940
+ if (state.outcome === "winner_selected") {
941
+ return hasIncompleteWinnerSelectedVariant(state) ? "degraded" : "success";
942
+ }
943
+ if (isJudgeOffComparisonState(state)) return "incomplete";
944
+ return "failed";
945
+ }
946
+ function resolveCompetitionStatusFromCompetitionState(state) {
947
+ return {
948
+ competitionResult: resolveCompetitionResultFromCompetitionState(state),
949
+ executionHealth: resolveExecutionHealthFromCompetitionState(state)
950
+ };
951
+ }
952
+ function competitionStatusStateFromBasicResult(result) {
953
+ const variants = result.variants ?? [];
954
+ const synthesisStatus = resolveLiveSynthesisProjectionStatus(result.synthesisResult);
955
+ return {
956
+ outcome: result.winner ? "winner_selected" : "no_winner",
957
+ winner: result.winner ? result.winner : null,
958
+ winnerVerification: result.winnerVerification ?? null,
959
+ variants,
960
+ rawHandle: {
961
+ variants
962
+ },
963
+ runMetadata: {
964
+ runSemantics: "competition",
965
+ ...synthesisStatus ? {
966
+ synthesis: {
967
+ expected: true,
968
+ status: synthesisStatus
969
+ }
970
+ } : {}
971
+ }
972
+ };
973
+ }
974
+ function resolveProjectionSynthesis(state) {
975
+ const metadata = state.runMetadata?.synthesis;
976
+ const durableStatus = resolveLiveSynthesisProjectionStatus(getDurableSynthesisResult(state));
977
+ return {
978
+ expected: metadata?.expected === true || durableStatus !== void 0 ? true : metadata?.expected,
979
+ status: durableStatus ?? metadata?.status
980
+ };
981
+ }
982
+ function getDurableSynthesisResult(state) {
983
+ if (state.synthesis && typeof state.synthesis === "object") {
984
+ return state.synthesis;
985
+ }
986
+ const rawHandle = state.rawHandle && typeof state.rawHandle === "object" ? state.rawHandle : null;
987
+ const fromRaw = rawHandle?.synthesis;
988
+ if (fromRaw && typeof fromRaw === "object" && !Array.isArray(fromRaw)) {
989
+ return fromRaw;
990
+ }
991
+ return void 0;
992
+ }
993
+ function resolveLiveSynthesisProjectionStatus(synthesisResult) {
994
+ if (!synthesisResult) return void 0;
995
+ if (synthesisResult.synthesisApplied === true) return "succeeded";
996
+ if (synthesisResult.success === false || synthesisResult.synthesisOutcomeStatus === "gate_failed" || synthesisResult.synthesisOutcomeStatus === "generation_failed" || synthesisResult.synthesisOutcomeStatus === "timed_out" || synthesisResult.synthesisOutcomeStatus === "editable_workspace_unavailable") {
997
+ return "failed";
998
+ }
999
+ if (synthesisResult.winnerFallback === true || synthesisResult.synthesisOutcomeStatus === "winner_carry_forward" || synthesisResult.synthesisOutcomeStatus === "no_pick") {
1000
+ return "no_pick";
1001
+ }
1002
+ return synthesisResult.success === true ? "succeeded" : void 0;
1003
+ }
1004
+ function isJudgeOffComparisonState(state) {
1005
+ return state.outcome === "no_winner" && state.winner == null && (state.runMetadata?.judge?.status === "disabled" || state.runMetadata?.judge?.requested === "off" || state.decision?.reason === "judge_off");
1006
+ }
1007
+ function isSynthesisFailureStatus(status) {
1008
+ return typeof status === "string" && SYNTHESIS_FAILURE_STATUSES.has(status);
1009
+ }
1010
+ function isSynthesisDegradedStatus(status) {
1011
+ return typeof status === "string" && SYNTHESIS_DEGRADED_STATUSES.has(status);
1012
+ }
1013
+ function hasIncompleteWinnerSelectedVariant(state) {
1014
+ if (hasUnverifiedWinnerEvidence(state)) {
1015
+ return true;
1016
+ }
1017
+ const candidates = getRawCompetitionCandidatesFromCompetitionState(
1018
+ state
1019
+ );
1020
+ if (candidates.some(
1021
+ (variant) => Object.hasOwn(variant, "success") ? variant.success !== true : hasTerminalIncompleteSignal(variant)
1022
+ )) {
1023
+ return true;
1024
+ }
1025
+ const winner = state.winner;
1026
+ return winner != null && Object.hasOwn(winner, "success") && winner.success !== true;
1027
+ }
1028
+ function hasUnverifiedWinnerEvidence(state) {
1029
+ const original = state.winnerVerification?.original;
1030
+ const originalStatus = normalizeStatusToken(original?.status);
1031
+ if (original?.failed === true || originalStatus === "failed") return true;
1032
+ if (originalStatus === "passed" || originalStatus === "baseline-clean") return false;
1033
+ if (originalStatus === "not-run" || originalStatus === "no-data") {
1034
+ return !isAnalysisIntentState(state);
1035
+ }
1036
+ const winnerCandidate = findWinnerCandidate(state);
1037
+ if (!winnerCandidate || !hasExplicitVerificationEvidence(winnerCandidate)) {
1038
+ return false;
1039
+ }
1040
+ return getDisplayVerificationVerdict({ ...winnerCandidate }, {
1041
+ requiredGatePolicy: "build-only"
1042
+ }).failed;
1043
+ }
1044
+ function findWinnerCandidate(state) {
1045
+ const candidates = getRawCompetitionCandidatesFromCompetitionState(state);
1046
+ if (candidates.length === 0) return null;
1047
+ const winner = state.winner;
1048
+ if (!winner) return candidates.length === 1 ? candidates[0] ?? null : null;
1049
+ const byVariant = findUniqueCandidateByAlias(candidates, normalizeVariantToken(winner.variant), [
1050
+ (candidate) => normalizeVariantToken(candidate.variant)
1051
+ ]);
1052
+ if (byVariant) return byVariant;
1053
+ const byReconciledVariant = findUniqueCandidateByAlias(
1054
+ candidates,
1055
+ winner.variant ? normalizeForReconciliation(winner.variant) : null,
1056
+ [
1057
+ (candidate) => typeof candidate.variant === "string" ? normalizeForReconciliation(candidate.variant) : null
1058
+ ]
1059
+ );
1060
+ if (byReconciledVariant) return byReconciledVariant;
1061
+ const byProviderModelStrategy = findUniqueCandidateByAlias(
1062
+ candidates,
1063
+ buildVariantToken(winner.provider, winner.model ?? winner.resolvedModel, winner.strategy),
1064
+ [
1065
+ (candidate) => buildVariantToken(candidate.provider, candidate.model, candidate.strategy),
1066
+ (candidate) => buildVariantToken(candidate.provider, candidate.resolvedModel, candidate.strategy)
1067
+ ]
1068
+ );
1069
+ if (byProviderModelStrategy) return byProviderModelStrategy;
1070
+ const byProviderStrategy = findUniqueCandidateByAlias(
1071
+ candidates,
1072
+ buildVariantToken(winner.provider, winner.strategy),
1073
+ [(candidate) => buildVariantToken(candidate.provider, candidate.strategy)]
1074
+ );
1075
+ return byProviderStrategy ?? (candidates.length === 1 ? candidates[0] ?? null : null);
1076
+ }
1077
+ function findUniqueCandidateByAlias(candidates, winnerAlias, candidateAliases) {
1078
+ if (!winnerAlias) return null;
1079
+ const matches = candidates.filter(
1080
+ (candidate) => candidateAliases.some((alias) => alias(candidate) === winnerAlias)
1081
+ );
1082
+ return matches.length === 1 ? matches[0] ?? null : null;
1083
+ }
1084
+ function hasExplicitVerificationEvidence(candidate) {
1085
+ const outcome = candidate.outcome && typeof candidate.outcome === "object" && !Array.isArray(candidate.outcome) ? candidate.outcome : null;
1086
+ const verification = outcome?.verification && typeof outcome.verification === "object" && !Array.isArray(outcome.verification) ? outcome.verification : null;
1087
+ return [
1088
+ verification?.status,
1089
+ verification?.outcome,
1090
+ verification?.buildStatus,
1091
+ verification?.testStatus,
1092
+ verification?.deterministicGatesPassed,
1093
+ candidate.buildStatus,
1094
+ candidate.testStatus
1095
+ ].some((value) => value !== void 0 && value !== null);
1096
+ }
1097
+ function isAnalysisIntentState(state) {
1098
+ if (normalizeStatusToken(state.runMetadata?.replay?.executionIntent) === "analysis") {
1099
+ return true;
1100
+ }
1101
+ const winnerCandidate = findWinnerCandidate(state);
1102
+ if (!winnerCandidate) return false;
1103
+ if (normalizeStatusToken(winnerCandidate.executionIntent) === "analysis") return true;
1104
+ const testsExecuted = winnerCandidate.testsExecuted && typeof winnerCandidate.testsExecuted === "object" && !Array.isArray(winnerCandidate.testsExecuted) ? winnerCandidate.testsExecuted : null;
1105
+ return normalizeStatusToken(testsExecuted?.skipReason) === "analysis-intent";
1106
+ }
1107
+ function normalizeStatusToken(value) {
1108
+ return typeof value === "string" && value.trim().length > 0 ? value.trim().replace(/_/g, "-") : null;
1109
+ }
1110
+ function normalizeVariantToken(value) {
1111
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
1112
+ }
1113
+ function buildVariantToken(...parts) {
1114
+ if (!normalizeVariantToken(parts[0])) return null;
1115
+ const tokens = parts.map(normalizeVariantToken).filter((token) => Boolean(token));
1116
+ return tokens.join(":");
1117
+ }
1118
+ function getRawCompetitionCandidatesFromCompetitionState(state) {
1119
+ const rawHandle = state.rawHandle && typeof state.rawHandle === "object" ? state.rawHandle : null;
1120
+ return Array.isArray(rawHandle?.candidates) ? rawHandle.candidates : Array.isArray(rawHandle?.variants) ? rawHandle.variants : [];
1121
+ }
1122
+ function hasTerminalIncompleteSignal(variant) {
1123
+ if (variant.timedOut === true) return true;
1124
+ if (typeof variant.errorMessage === "string" && variant.errorMessage.trim().length > 0) {
1125
+ return true;
1126
+ }
1127
+ if (typeof variant.terminationReason === "string" && variant.terminationReason.trim().length > 0) {
1128
+ return true;
1129
+ }
1130
+ const verification = variant.outcome?.verification;
1131
+ if (verification?.status === "failed" || verification?.buildStatus === "failed" || verification?.testStatus === "failed") {
1132
+ return true;
1133
+ }
1134
+ if (typeof variant.completeness === "number" && Number.isFinite(variant.completeness)) {
1135
+ return variant.completeness <= 0;
1136
+ }
1137
+ return false;
1138
+ }
1139
+
1140
+ // src/cli/utils/default-competition-id.ts
1141
+ import path from "path";
1142
+ import chalk2 from "chalk";
1143
+ async function resolveDefaultCompetitionId(buildDir) {
1144
+ const stateDir = LabPathResolver.getInstance().getStateDir(buildDir);
1145
+ return getMostRecentCompetitionId({
1146
+ stateDirs: readDirsForStateRoot(buildDir, stateDir).map(
1147
+ (dir) => path.join(dir, "competitions")
1148
+ ),
1149
+ checkoutRoot: resolveCheckoutRoot(buildDir)
1150
+ });
1151
+ }
1152
+ async function resolveDefaultCompetitionIdOrReport(buildDir) {
1153
+ const recent = await resolveDefaultCompetitionId(buildDir);
1154
+ if (!recent) {
1155
+ console.error(
1156
+ chalk2.red(
1157
+ "\nError: No competition state found. Run a competition first, or pass a task ID.\n"
1158
+ )
1159
+ );
1160
+ process.exitCode = 1;
1161
+ return null;
1162
+ }
1163
+ console.error(chalk2.gray(`Using most recent competition: ${recent}`));
1164
+ return recent;
1165
+ }
1166
+
1167
+ // src/cli/utils/judge-operations-read.ts
1168
+ function recordedWinner(state) {
1169
+ if (state.winner === null || state.outcome === "no_winner") return null;
1170
+ return state.winner;
1171
+ }
1172
+ function judgeOperationsFactsForState(run, state) {
1173
+ return {
1174
+ id: run.id,
1175
+ kind: run.kind,
1176
+ judge: state.runMetadata?.judge,
1177
+ matrix: state.runMetadata?.matrix,
1178
+ synthesis: state.runMetadata?.synthesis,
1179
+ decision: state.decision,
1180
+ judgeFailures: state.judgeFailures,
1181
+ winner: recordedWinner(state),
1182
+ application: state.application,
1183
+ health: run.health
1184
+ };
1185
+ }
1186
+ function projectJudgeOperationsFromState(run, state) {
1187
+ return projectJudgeOperations(judgeOperationsFactsForState(run, state));
1188
+ }
1189
+
1190
+ // src/cli/utils/multi-judge-display.ts
1191
+ import chalk3 from "chalk";
1192
+ function logJsonParseFallback(context) {
1193
+ return {
1194
+ onError: (error) => console.warn(`Failed to parse ${context}: ${error}`)
1195
+ };
1196
+ }
1197
+ function printLine(message) {
1198
+ console.log(message);
1199
+ }
1200
+ function hasWinnerInResults(row) {
1201
+ return Object.values(parseResultsJson(row)).some(
1202
+ (entry) => typeof entry?.winner === "string" && entry.winner.trim().length > 0
1203
+ );
1204
+ }
1205
+ function hasPrimaryWinner(row) {
1206
+ const winner = row.primary_winner ?? row.primaryWinner;
1207
+ return typeof winner === "string" && winner.trim().length > 0;
1208
+ }
1209
+ function primaryDeclaredNoWinner(row) {
1210
+ if (hasPrimaryWinner(row)) return false;
1211
+ const primary = row.primary_judge ?? row.primaryJudge;
1212
+ if (!primary) return false;
1213
+ const reason = parseResultsJson(row)[primary]?.noWinnerReason;
1214
+ return isSemanticNoWinnerReason(reason);
1215
+ }
1216
+ function normalizeMultiJudgeRunRow(row) {
1217
+ if (!row.no_winner_reason) return row;
1218
+ if (!hasPrimaryWinner(row) && !hasWinnerInResults(row)) return row;
1219
+ if (primaryDeclaredNoWinner(row)) return row;
1220
+ return { ...row, no_winner_reason: null };
1221
+ }
1222
+ function parseJudgesExecuted(row) {
1223
+ if (Array.isArray(row.judgesExecuted)) return row.judgesExecuted;
1224
+ const raw = row.judges_executed ?? row.judgesExecuted;
1225
+ if (typeof raw !== "string" || raw.trim().length === 0) return [];
1226
+ try {
1227
+ const parsed = JSON.parse(raw);
1228
+ if (Array.isArray(parsed)) return parsed.filter((judge) => typeof judge === "string");
1229
+ } catch {
1230
+ }
1231
+ return raw.split(",").map((judge) => judge.trim()).filter(Boolean);
1232
+ }
1233
+ function parseResultsJson(row) {
1234
+ if (row.resultsJson && typeof row.resultsJson === "object" && !Array.isArray(row.resultsJson)) {
1235
+ return row.resultsJson;
1236
+ }
1237
+ const raw = row.results_json ?? row.resultsJson;
1238
+ if (typeof raw !== "string") return {};
1239
+ const parsed = parseJsonWithFallback(
1240
+ raw,
1241
+ "multi_judge_runs.results_json",
1242
+ {},
1243
+ logJsonParseFallback("multi_judge_runs.results_json")
1244
+ );
1245
+ if (parsed.truncated === true && parsed.summary && typeof parsed.summary === "object" && !Array.isArray(parsed.summary)) {
1246
+ return parsed.summary;
1247
+ }
1248
+ return parsed;
1249
+ }
1250
+ function secondaryJudgePicks(row) {
1251
+ if (!primaryDeclaredNoWinner(row)) return [];
1252
+ const primary = row.primary_judge ?? row.primaryJudge ?? null;
1253
+ return Object.entries(parseResultsJson(row)).filter(([judge]) => judge !== primary).flatMap(
1254
+ ([judge, entry]) => typeof entry?.winner === "string" && entry.winner.trim().length > 0 ? [{ judge, winner: entry.winner.trim() }] : []
1255
+ );
1256
+ }
1257
+ function normalizeReasonLabel(value) {
1258
+ return value.replace(/_/g, "-").replace(/\s+/g, " ").trim();
1259
+ }
1260
+ function readString(value) {
1261
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
1262
+ }
1263
+ function readJudgeAudit(entry) {
1264
+ return entry.metadata?.audit ?? {};
1265
+ }
1266
+ function getJudgeInvalidCause(entry) {
1267
+ const audit = readJudgeAudit(entry);
1268
+ const rationale = readString(entry.rationale);
1269
+ const rationaleCause = rationale?.match(/\bcause:\s*([a-z_]+)/i)?.[1] ?? null;
1270
+ return readString(entry.judgeInvalidCause) ?? readString(audit.judgeInvalidCause) ?? readString(audit.judgeInvalidReason) ?? readString(entry.judgeInvalidReason) ?? readString(rationaleCause) ?? null;
1271
+ }
1272
+ function classifyJudgeDisplayStatus(entry) {
1273
+ if (entry.status === "skipped") {
1274
+ return { kind: "skipped", reason: readString(entry.skippedReason) ?? "unspecified" };
1275
+ }
1276
+ if (typeof entry.winner === "string" && entry.winner.trim().length > 0) {
1277
+ return { kind: "winner", winner: entry.winner.trim() };
1278
+ }
1279
+ const audit = readJudgeAudit(entry);
1280
+ const invalidCause = getJudgeInvalidCause(entry);
1281
+ const rationale = readString(entry.rationale);
1282
+ const normalizedRationale = rationale?.toLowerCase().trim();
1283
+ const noWinnerReason = readString(entry.noWinnerReason);
1284
+ const judgeStatus2 = readString(entry.judgeStatus) ?? readString(audit.judgeStatus);
1285
+ const error = readString(entry.error);
1286
+ const rationaleIndicatesNonTechnical = normalizedRationale === "non-technical task" || normalizedRationale === "non_technical_task" || normalizedRationale === "judge_invalid: multi-lens skipped for non-technical task";
1287
+ if (invalidCause === "non_technical_task" || !invalidCause && rationaleIndicatesNonTechnical) {
1288
+ return { kind: "not-applicable", reason: "non-technical task" };
1289
+ }
1290
+ if (error) return { kind: "failed", reason: error };
1291
+ if (judgeStatus2 === "judge_invalid") {
1292
+ return {
1293
+ kind: "failed",
1294
+ reason: normalizeReasonLabel(invalidCause ?? "judge invalid")
1295
+ };
1296
+ }
1297
+ if (normalizedRationale?.startsWith("judge_invalid:")) {
1298
+ return {
1299
+ kind: "failed",
1300
+ reason: normalizeReasonLabel(invalidCause ?? "judge invalid")
1301
+ };
1302
+ }
1303
+ if (noWinnerReason === "judge-error") {
1304
+ return { kind: "failed", reason: normalizeReasonLabel(noWinnerReason) };
1305
+ }
1306
+ return { kind: "none" };
1307
+ }
1308
+ function buildAgreementSummary(row, results, judgesExecuted) {
1309
+ const entries = Object.entries(results);
1310
+ const totalCount = judgesExecuted.length > 0 ? judgesExecuted.length : entries.length;
1311
+ const winners = entries.map(([, entry]) => ({ entry, status: classifyJudgeDisplayStatus(entry) })).filter(
1312
+ (item) => item.status.kind === "winner"
1313
+ );
1314
+ const distinctWinners = new Set(winners.map(({ status }) => status.winner));
1315
+ const normalizedModels = winners.map(({ entry }) => {
1316
+ const audit = readJudgeAudit(entry);
1317
+ const provider = readString(entry.provider) ?? readString(audit.llmProvider) ?? readString(audit.orchestrationProvider);
1318
+ const model = entry.model?.trim().toLowerCase() ?? "";
1319
+ return model ? `${provider?.toLowerCase() ?? "unknown"}:${model}` : "";
1320
+ });
1321
+ const correlated = normalizedModels.length >= 2 && normalizedModels.every((model) => model.length > 0 && model === normalizedModels[0]);
1322
+ if (winners.length >= 2) {
1323
+ return {
1324
+ status: distinctWinners.size === 1 ? "agree" : "disagree",
1325
+ applicableCount: winners.length,
1326
+ totalCount,
1327
+ correlated
1328
+ };
1329
+ }
1330
+ if (entries.length === 0 && row.all_match !== null) {
1331
+ return {
1332
+ status: row.all_match === 1 ? "agree" : "disagree",
1333
+ applicableCount: row.all_match === 1 ? totalCount : 0,
1334
+ totalCount,
1335
+ correlated: false
1336
+ };
1337
+ }
1338
+ return { status: "n/a", applicableCount: winners.length, totalCount, correlated: false };
1339
+ }
1340
+ function formatAgreementLabel(summary) {
1341
+ const label = summary.status === "agree" ? chalk3.green("agree") : summary.status === "disagree" ? chalk3.yellow("disagree") : chalk3.gray("n/a");
1342
+ const suffix = summary.totalCount > 0 && summary.applicableCount !== summary.totalCount ? ` (${summary.applicableCount} of ${summary.totalCount} applicable)` : "";
1343
+ const correlationSuffix = summary.correlated ? " (correlated: same model)" : "";
1344
+ return `${label}${suffix}${correlationSuffix}`;
1345
+ }
1346
+ function formatJudgeDisplayLine(entry) {
1347
+ const status = classifyJudgeDisplayStatus(entry);
1348
+ const usageSuffix = formatJudgeUsageSuffix(entry);
1349
+ const deferredSuffix = formatDeferredShadowStatus(entry);
1350
+ if (status.kind === "winner") {
1351
+ const suffix = entry.error ? chalk3.red(` (${entry.error})`) : "";
1352
+ return `${status.winner}${suffix}${usageSuffix}${deferredSuffix}`;
1353
+ }
1354
+ if (status.kind === "not-applicable") {
1355
+ return `not applicable (${status.reason})${usageSuffix}${deferredSuffix}`;
1356
+ }
1357
+ if (status.kind === "failed") {
1358
+ return chalk3.red(`failed (${status.reason})${usageSuffix}${deferredSuffix}`);
1359
+ }
1360
+ if (status.kind === "skipped") {
1361
+ return chalk3.yellow(`skipped (${status.reason})${usageSuffix}${deferredSuffix}`);
1362
+ }
1363
+ return `none${usageSuffix}${deferredSuffix}`;
1364
+ }
1365
+ function formatDeferredShadowStatus(entry) {
1366
+ if (entry.deferredShadowStatus === "pending") {
1367
+ return chalk3.yellow(" [shadow pending]");
1368
+ }
1369
+ if (entry.deferredShadowStatus === "reconciled") {
1370
+ return chalk3.green(" [shadow reconciled]");
1371
+ }
1372
+ return "";
1373
+ }
1374
+ function formatTokens(tokensUsed) {
1375
+ if (typeof tokensUsed !== "number" || !Number.isFinite(tokensUsed) || tokensUsed <= 0)
1376
+ return null;
1377
+ return tokensUsed >= 1e3 ? `${(tokensUsed / 1e3).toFixed(1)}k tok` : `${Math.round(tokensUsed)} tok`;
1378
+ }
1379
+ function formatCost(costUsd) {
1380
+ if (typeof costUsd !== "number" || !Number.isFinite(costUsd) || costUsd < 0) return null;
1381
+ return `$${costUsd.toFixed(4)}`;
1382
+ }
1383
+ function formatJudgeUsageSuffix(entry) {
1384
+ const parts = [];
1385
+ if (typeof entry.evaluationTimeMs === "number" && Number.isFinite(entry.evaluationTimeMs)) {
1386
+ parts.push(`${Math.round(entry.evaluationTimeMs)}ms`);
1387
+ }
1388
+ const tokenLabel = formatTokens(entry.tokensUsed);
1389
+ if (tokenLabel) parts.push(tokenLabel);
1390
+ const costLabel = formatCost(entry.costUsd);
1391
+ if (costLabel) parts.push(costLabel);
1392
+ if (typeof entry.model === "string" && entry.model.trim()) {
1393
+ parts.push(entry.model.trim());
1394
+ }
1395
+ if (typeof entry.sandboxProvenance === "string" && entry.sandboxProvenance.trim()) {
1396
+ parts.push(`sb:${entry.sandboxProvenance}`);
1397
+ }
1398
+ const modeLabel = formatJudgeModeSuffix(entry);
1399
+ if (modeLabel) parts.push(modeLabel);
1400
+ return parts.length > 0 ? ` [${parts.join(", ")}]` : "";
1401
+ }
1402
+ function formatJudgeModeSuffix(entry) {
1403
+ if (entry.executionMode !== "lightweight" && entry.executionMode !== "host-owned") {
1404
+ return null;
1405
+ }
1406
+ const reason = typeof entry.routingReason === "string" && entry.routingReason.trim() ? ` (${entry.routingReason.trim()})` : "";
1407
+ const pieces = [`mode=${entry.executionMode}${reason}`];
1408
+ if (typeof entry.workerPacketCount === "number" && Number.isFinite(entry.workerPacketCount)) {
1409
+ pieces.push(`workers=${entry.workerPacketCount}`);
1410
+ }
1411
+ return pieces.join(" ");
1412
+ }
1413
+ function renderAgenticSummary(summary, compact) {
1414
+ const severity = summary.severityCounts;
1415
+ const verification = summary.verificationCounts;
1416
+ const headline = compact ? "agentic" : "Agentic Findings";
1417
+ const prefix = compact ? " " : " ";
1418
+ const riskTag = summary.hasCriticalOrHigh ? "critical/high present" : "no critical/high";
1419
+ const toolsLabel = summary.topTools.length > 0 ? ` topTools=${summary.topTools.join(", ")}` : "";
1420
+ console.log(
1421
+ chalk3.gray(
1422
+ `${prefix}${headline}: findings=${summary.totalFindings} (critical=${severity.critical}, high=${severity.high}, medium=${severity.medium}, low=${severity.low}, info=${severity.info}) verify=${verification.passed}/${verification.failed}/${verification.skipped}/${verification.error} deepDive=${summary.deepDiveVariants} variantsWithFindings=${summary.variantsWithFindings} tools=${summary.toolsUsedCount} ${riskTag}${toolsLabel}`
1423
+ )
1424
+ );
1425
+ }
1426
+ function getLatestMultiJudgeRunForTask(telemetry, taskId) {
1427
+ try {
1428
+ const db = telemetry.databaseModule.getVariantsDb();
1429
+ if (!db) return null;
1430
+ const scope = telemetry.getTelemetryScope({ includeLabs: true });
1431
+ const row = db.prepare(
1432
+ `
1433
+ SELECT
1434
+ timestamp,
1435
+ judges_executed,
1436
+ primary_judge,
1437
+ primary_winner,
1438
+ primary_winner_score,
1439
+ primary_winner_confidence,
1440
+ all_match,
1441
+ results_json,
1442
+ no_winner_reason,
1443
+ total_variants,
1444
+ evaluation_time_ms
1445
+ FROM multi_judge_runs
1446
+ WHERE ${scope.where} AND task_id = ?
1447
+ ORDER BY timestamp DESC
1448
+ LIMIT 1
1449
+ `
1450
+ ).get(...scope.params, taskId);
1451
+ if (row) return normalizeMultiJudgeRunRow(row);
1452
+ const fallbackRow = db.prepare(
1453
+ `
1454
+ SELECT
1455
+ timestamp,
1456
+ judges_executed,
1457
+ primary_judge,
1458
+ primary_winner,
1459
+ primary_winner_score,
1460
+ primary_winner_confidence,
1461
+ all_match,
1462
+ results_json,
1463
+ no_winner_reason,
1464
+ total_variants,
1465
+ evaluation_time_ms
1466
+ FROM multi_judge_runs
1467
+ WHERE task_id = ?
1468
+ ORDER BY timestamp DESC
1469
+ LIMIT 1
1470
+ `
1471
+ ).get(taskId);
1472
+ return fallbackRow ? normalizeMultiJudgeRunRow(fallbackRow) : null;
1473
+ } catch {
1474
+ return null;
1475
+ }
1476
+ }
1477
+ function renderMultiJudgeRun(row, options = {}) {
1478
+ row = normalizeMultiJudgeRunRow(row);
1479
+ if (options.compact) {
1480
+ const judgesExecuted2 = parseJudgesExecuted(row);
1481
+ const primaryJudge2 = row.primary_judge ?? row.primaryJudge ?? null;
1482
+ const results2 = parseResultsJson(row);
1483
+ const agreement2 = buildAgreementSummary(row, results2, judgesExecuted2);
1484
+ console.log(
1485
+ chalk3.gray(
1486
+ ` Judges: [${judgesExecuted2.join(", ")}] primary=${primaryJudge2} agreement=${formatAgreementLabel(agreement2)}`
1487
+ )
1488
+ );
1489
+ const shouldShowJudgeDetails = agreement2.status !== "agree" || agreement2.applicableCount !== agreement2.totalCount;
1490
+ if (shouldShowJudgeDetails) {
1491
+ try {
1492
+ const dedupWarnings = /* @__PURE__ */ new Set();
1493
+ let agenticSummary;
1494
+ for (const [judge, result] of Object.entries(results2)) {
1495
+ if (!agenticSummary && result.agenticFindings) {
1496
+ agenticSummary = result.agenticFindings;
1497
+ }
1498
+ for (const warning of result.warnings ?? []) {
1499
+ dedupWarnings.add(warning);
1500
+ }
1501
+ console.log(chalk3.gray(` ${judge}: ${formatJudgeDisplayLine(result)}`));
1502
+ }
1503
+ if (agenticSummary) {
1504
+ renderAgenticSummary(agenticSummary, true);
1505
+ }
1506
+ for (const warning of dedupWarnings) {
1507
+ console.log(chalk3.yellow(` [WARN] ${warning}`));
1508
+ }
1509
+ } catch {
1510
+ }
1511
+ }
1512
+ if (!shouldShowJudgeDetails) {
1513
+ try {
1514
+ const dedupWarnings = /* @__PURE__ */ new Set();
1515
+ const agenticSummary = Object.values(results2).find(
1516
+ (result) => result.agenticFindings
1517
+ )?.agenticFindings;
1518
+ for (const [judge, result] of Object.entries(results2)) {
1519
+ const modeSuffix = formatJudgeModeSuffix(result);
1520
+ const deferredSuffix = formatDeferredShadowStatus(result).trim();
1521
+ const suffixes = [modeSuffix, deferredSuffix].filter(Boolean);
1522
+ if (suffixes.length > 0) {
1523
+ console.log(chalk3.gray(` ${judge}: ${suffixes.join(" ")}`));
1524
+ }
1525
+ }
1526
+ if (agenticSummary) {
1527
+ renderAgenticSummary(agenticSummary, true);
1528
+ }
1529
+ for (const result of Object.values(results2)) {
1530
+ for (const warning of result.warnings ?? []) {
1531
+ dedupWarnings.add(warning);
1532
+ }
1533
+ }
1534
+ for (const warning of dedupWarnings) {
1535
+ console.log(chalk3.yellow(` [WARN] ${warning}`));
1536
+ }
1537
+ } catch {
1538
+ }
1539
+ }
1540
+ return;
1541
+ }
1542
+ console.log(chalk3.cyan.bold("\nMulti-Judge Run:\n"));
1543
+ console.log(chalk3.gray(` Timestamp: ${row.timestamp}`));
1544
+ const judgesExecuted = parseJudgesExecuted(row);
1545
+ console.log(chalk3.white(` Judges: ${judgesExecuted.join(", ")}`));
1546
+ const primaryJudge = row.primary_judge ?? row.primaryJudge ?? null;
1547
+ const primaryWinner = row.primary_winner ?? row.primaryWinner ?? null;
1548
+ if (primaryJudge) console.log(chalk3.white(` Primary: ${primaryJudge}`));
1549
+ if (primaryWinner) console.log(chalk3.white(` Primary Winner: ${primaryWinner}`));
1550
+ const results = parseResultsJson(row);
1551
+ const agreement = buildAgreementSummary(row, results, judgesExecuted);
1552
+ printLine(chalk3.white(` Agreement: ${formatAgreementLabel(agreement)}`));
1553
+ if (agreement.totalCount > 0) {
1554
+ printLine(chalk3.white(` Applicable: ${agreement.applicableCount} of ${agreement.totalCount}`));
1555
+ }
1556
+ if (row.total_variants !== null) {
1557
+ console.log(chalk3.white(` Variants: ${row.total_variants}`));
1558
+ }
1559
+ if (row.evaluation_time_ms !== null) {
1560
+ console.log(chalk3.white(` Evaluation Time: ${row.evaluation_time_ms.toFixed(0)}ms`));
1561
+ }
1562
+ if (row.no_winner_reason) {
1563
+ console.log(chalk3.yellow(` No Winner Reason: ${row.no_winner_reason}`));
1564
+ }
1565
+ try {
1566
+ const dedupWarnings = /* @__PURE__ */ new Set();
1567
+ console.log(chalk3.white("\n Results:"));
1568
+ for (const [judge, result] of Object.entries(results)) {
1569
+ for (const warning of result.warnings ?? []) {
1570
+ dedupWarnings.add(warning);
1571
+ }
1572
+ console.log(chalk3.gray(` ${judge}: ${formatJudgeDisplayLine(result)}`));
1573
+ if (result.executionMode === "lightweight" || result.executionMode === "host-owned") {
1574
+ const reason = typeof result.routingReason === "string" && result.routingReason.trim().length > 0 ? ` (${result.routingReason.trim()})` : "";
1575
+ console.log(chalk3.gray(` mode: ${result.executionMode}${reason}`));
1576
+ if (typeof result.workerPacketCount === "number" && Number.isFinite(result.workerPacketCount)) {
1577
+ console.log(chalk3.gray(` workerPackets: ${result.workerPacketCount}`));
1578
+ }
1579
+ }
1580
+ if (result.agenticFindings) {
1581
+ renderAgenticSummary(result.agenticFindings, false);
1582
+ }
1583
+ }
1584
+ for (const warning of dedupWarnings) {
1585
+ console.log(chalk3.yellow(` [WARN] ${warning}`));
1586
+ }
1587
+ } catch {
1588
+ }
1589
+ console.log();
1590
+ }
1591
+
1592
+ // src/cli/utils/results-intent-tokens.ts
1593
+ function formatFusionFallbackContribution(success) {
1594
+ if (success === true) return "completed";
1595
+ if (success === false) return "not_completed";
1596
+ return "unknown";
1597
+ }
1598
+ function isAnalysisIntentToken(value) {
1599
+ return typeof value === "string" && value.trim().replace(/_/g, "-") === "analysis";
1600
+ }
1601
+ function isAnalysisIntentSkipReason(value) {
1602
+ return typeof value === "string" && value.trim().replace(/_/g, "-") === "analysis-intent";
1603
+ }
1604
+
1605
+ // src/cli/commands/compete-results-ignored-artifacts.ts
1606
+ import chalk4 from "chalk";
1607
+ function normaliseIgnoredPathEvidence(value) {
1608
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
1609
+ const record = value;
1610
+ const paths = Array.isArray(record.paths) ? record.paths.filter((path3) => typeof path3 === "string" && path3.length > 0) : [];
1611
+ if (paths.length === 0) return null;
1612
+ return {
1613
+ paths,
1614
+ ...typeof record.reason === "string" ? { reason: record.reason } : {},
1615
+ ...typeof record.source === "string" ? { source: record.source } : {}
1616
+ };
1617
+ }
1618
+ function extractIgnoredArtifactPaths(candidateRecord) {
1619
+ const evidence2 = normaliseIgnoredPathEvidence(candidateRecord.ignoredPathEvidence);
1620
+ const paths = Array.isArray(evidence2?.paths) ? evidence2.paths : [];
1621
+ return paths.filter((path3) => typeof path3 === "string" && path3.length > 0);
1622
+ }
1623
+ function formatIgnoredArtifactLine(paths) {
1624
+ if (paths.length === 0) return null;
1625
+ const preview = paths.slice(0, 5);
1626
+ const suffix = paths.length > preview.length ? ` (+${paths.length - preview.length} more)` : "";
1627
+ return `Ignored artifacts: ${preview.join(", ")}${suffix}`;
1628
+ }
1629
+ function printCandidateEvidenceLines(record) {
1630
+ const alsoOnBase = record?.alsoFailingOnBase;
1631
+ if (Array.isArray(alsoOnBase) && alsoOnBase.length > 0) {
1632
+ console.log(chalk4.gray(` Also failing on base: ${alsoOnBase.join(", ")}`));
1633
+ }
1634
+ const line = record ? formatIgnoredArtifactLine(extractIgnoredArtifactPaths(record)) : null;
1635
+ if (line) console.log(chalk4.gray(` ${line}`));
1636
+ }
1637
+
1638
+ // src/cli/commands/compete-results-not-found.ts
1639
+ import chalk5 from "chalk";
1640
+ function buildNoEvaluationFoundHints(surface, taskId) {
1641
+ let runTask = null;
1642
+ try {
1643
+ runTask = readRunTaskState(taskId);
1644
+ } catch {
1645
+ runTask = null;
1646
+ }
1647
+ if (runTask?.artifact && runTask.providerOutputArtifactRelativePath) {
1648
+ return [
1649
+ `${taskId} is a single-pass build run task (status: ${runTask.status}); single-pass tasks have no ${surface === "fusion" ? "fusion" : "competition"} results.`,
1650
+ `Inspect it with: build monitor ${taskId}`,
1651
+ `Provider output artifact: ${runTask.providerOutputArtifactRelativePath}`
1652
+ ];
1653
+ }
1654
+ const competitionsDir = `${resolveCliStateRoots().competitionsDir}/`;
1655
+ const stateLocations = surface === "fusion" ? `.build-project/analysis-synthesis/ or ${competitionsDir}` : competitionsDir;
1656
+ return [
1657
+ `Run build monitor ${taskId} to see whether this id belongs to a single-pass task or another run kind.`,
1658
+ `Check that the task id matches a file under ${stateLocations}.`
1659
+ ];
1660
+ }
1661
+ function renderNoEvaluationFoundError(surface, taskId) {
1662
+ console.error(chalk5.red(`
1663
+ Error: No evaluation found for task ID: ${taskId}`));
1664
+ for (const hint of buildNoEvaluationFoundHints(surface, taskId)) {
1665
+ console.error(chalk5.gray(`Hint: ${hint}`));
1666
+ }
1667
+ console.error();
1668
+ }
1669
+
1670
+ // src/cli/commands/compete-results.ts
1671
+ var SCORE_CALIBRATION_DISPLAY_DELTA_THRESHOLD = 0.1;
1672
+ function hasCompetitionStateData(state) {
1673
+ return state.sources.competitionHandle.exists || state.sources.backgroundHandle.exists;
1674
+ }
1675
+ var resolveExecutionHealthFromState = resolveExecutionHealthFromCompetitionState;
1676
+ var resolveCompetitionResultFromState = resolveCompetitionResultFromCompetitionState;
1677
+ var getRawCompetitionCandidates = getRawCompetitionCandidatesFromCompetitionState;
1678
+ function getFusionRunReadModel(runId, options) {
1679
+ const runSnapshotV1 = getRunSnapshotV1(runId, options);
1680
+ const runProgressV1 = runSnapshotV1 === null ? null : projectRunProgress(runSnapshotV1);
1681
+ const operationalReadbackV1 = runSnapshotV1 === null ? null : toFusionOperationalReadbackV1(runSnapshotV1);
1682
+ let narrationConfig;
1683
+ let narrationConfigurationError;
1684
+ try {
1685
+ narrationConfig = resolveProgressNarrationConfig(options?.cwd ?? process.cwd());
1686
+ } catch {
1687
+ narrationConfig = void 0;
1688
+ narrationConfigurationError = "Progress narration configuration could not be resolved.";
1689
+ }
1690
+ return {
1691
+ runSnapshotV1,
1692
+ runProgressV1,
1693
+ operationalReadbackV1,
1694
+ runNarrationRequestV1: runProgressV1 === null ? null : buildRunNarrationRequestV1(runProgressV1, narrationConfig?.value, {
1695
+ configurationError: narrationConfigurationError
1696
+ })
1697
+ };
1698
+ }
1699
+ function getCompetitionRunReadModel(runId, options) {
1700
+ const operationalReadbackV1 = getCompetitionOperationalReadbackV1(runId, options);
1701
+ const snapshot = operationalReadbackV1?.competition ?? null;
1702
+ return {
1703
+ operationalReadbackV1,
1704
+ // The same provider-neutral progress projection Fusion already publishes.
1705
+ // BB renders it; it never reconstructs variant state from competition prose.
1706
+ runProgressV1: snapshot === null ? null : projectRunProgress(snapshot)
1707
+ };
1708
+ }
1709
+ function hasAnalysisIntentEvidence(state, candidates) {
1710
+ if (isAnalysisIntentToken(state?.runMetadata?.replay?.executionIntent)) return true;
1711
+ return candidates.some((candidate) => {
1712
+ if (isAnalysisIntentToken(candidate.executionIntent)) return true;
1713
+ const testsExecuted = candidate.testsExecuted && typeof candidate.testsExecuted === "object" ? candidate.testsExecuted : null;
1714
+ return isAnalysisIntentSkipReason(testsExecuted?.skipReason);
1715
+ });
1716
+ }
1717
+ function sanitizeFusionContributorOutcome(outcome) {
1718
+ if (!outcome || typeof outcome !== "object" || Array.isArray(outcome)) return outcome ?? null;
1719
+ const record = outcome;
1720
+ const delivery = record.delivery && typeof record.delivery === "object" && !Array.isArray(record.delivery) ? { ...record.delivery } : void 0;
1721
+ if (delivery) {
1722
+ delete delivery.score;
1723
+ }
1724
+ return {
1725
+ ...record,
1726
+ ...delivery ? { delivery } : {}
1727
+ };
1728
+ }
1729
+ function buildCompetitionHandleVariantJson(c, options = {}) {
1730
+ const isFusion = options.runSemantics === "fusion";
1731
+ const inputSpecWarning = normaliseInputSpecWarning(c.inputSpecWarning);
1732
+ const ignoredPathEvidence = normaliseIgnoredPathEvidence(c.ignoredPathEvidence);
1733
+ return {
1734
+ provider: c.provider ?? null,
1735
+ requestedProvider: c.requestedProvider ?? null,
1736
+ model: c.model ?? null,
1737
+ requestedModel: c.requestedModel ?? null,
1738
+ resolvedModel: c.resolvedModel ?? null,
1739
+ modelResolutionSource: c.modelResolutionSource ?? null,
1740
+ failoverFromProvider: c.failoverFromProvider ?? null,
1741
+ failoverReason: c.failoverReason ?? null,
1742
+ strategy: c.strategy ?? null,
1743
+ variant: c.variant ?? null,
1744
+ workspaceMode: c.workspaceMode ?? null,
1745
+ workspaceModeRequested: c.workspaceModeRequested ?? null,
1746
+ reasoningEffort: c.reasoningEffort ?? null,
1747
+ cursorPromptProfile: c.cursorPromptProfile ?? null,
1748
+ outcome: isFusion ? sanitizeFusionContributorOutcome(c.outcome) : c.outcome ?? null,
1749
+ success: c.success ?? null,
1750
+ ...isFusion ? { contribution: formatFusionFallbackContribution(c.success) } : { completeness: c.completeness ?? null },
1751
+ duration: c.duration ?? null,
1752
+ terminationReason: c.terminationReason ?? null,
1753
+ timedOut: c.timedOut ?? null,
1754
+ errorMessage: c.errorMessage ?? null,
1755
+ ...typeof c.warningCount === "number" ? { warningCount: c.warningCount } : {},
1756
+ ...Array.isArray(c.warnings) ? { warnings: c.warnings } : {},
1757
+ cloudTaskId: c.cloudTaskId ?? null,
1758
+ submittedOnly: c.submittedOnly ?? null,
1759
+ prNumber: c.prNumber ?? null,
1760
+ prUrl: c.prUrl ?? null,
1761
+ ...inputSpecWarning ? { inputSpecWarning } : {},
1762
+ ...ignoredPathEvidence ? { ignoredPathEvidence } : {}
1763
+ };
1764
+ }
1765
+ function stringField(record, key) {
1766
+ const value = record[key];
1767
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
1768
+ }
1769
+ function resultVariantRowMatchesFinalWinner(row, finalWinnerVariant) {
1770
+ const provider = stringField(row, "provider");
1771
+ const strategy = stringField(row, "strategy");
1772
+ const model = stringField(row, "model");
1773
+ const resolvedModel = stringField(row, "resolvedModel");
1774
+ const executionMode = stringField(row, "executionMode");
1775
+ const aliases = [
1776
+ stringField(row, "variant"),
1777
+ provider && model ? `${provider}:${model}` : null,
1778
+ provider && resolvedModel ? `${provider}:${resolvedModel}` : null,
1779
+ // Persisted rows written before the strategy axis was removed reconstruct
1780
+ // their variant key from the historical grammar.
1781
+ provider && strategy ? `${provider}:${strategy}` : null,
1782
+ provider && model && strategy ? `${provider}:${model}:${strategy}` : null,
1783
+ provider && resolvedModel && strategy ? `${provider}:${resolvedModel}:${strategy}` : null,
1784
+ provider && strategy && executionMode ? `${provider}:${strategy}:${executionMode}` : null,
1785
+ provider && model && strategy && executionMode ? `${provider}:${model}:${strategy}:${executionMode}` : null,
1786
+ provider && resolvedModel && strategy && executionMode ? `${provider}:${resolvedModel}:${strategy}:${executionMode}` : null
1787
+ ];
1788
+ return aliases.some((alias) => variantHandlesMatchForResults(alias, finalWinnerVariant));
1789
+ }
1790
+ function findDecisionCandidateForResults(candidates, selectedVariant, winnerVariant) {
1791
+ const candidateVariant = typeof selectedVariant === "string" && selectedVariant.trim().length > 0 ? selectedVariant : typeof winnerVariant === "string" && winnerVariant.trim().length > 0 ? winnerVariant : null;
1792
+ if (!candidateVariant) {
1793
+ return null;
1794
+ }
1795
+ return candidates.find(
1796
+ (candidate) => resultVariantRowMatchesFinalWinner(candidate, candidateVariant)
1797
+ ) ?? null;
1798
+ }
1799
+ function buildFallbackJudgeSummary(state) {
1800
+ const runJudge = state.runMetadata?.judge;
1801
+ const decision = state.decision;
1802
+ if (!runJudge && !decision) return null;
1803
+ const status = runJudge?.status ?? (decision?.reason === "judge_off" ? "disabled" : decision?.decisionStatus ? "completed" : null);
1804
+ return {
1805
+ requested: runJudge?.requested ?? decision?.primaryJudge ?? null,
1806
+ status,
1807
+ ...decision?.reason ? { reason: decision.reason } : {},
1808
+ ...decision?.decisionStatus ? { decisionStatus: decision.decisionStatus } : {},
1809
+ ...decision?.decisionOutcome ? { decisionOutcome: decision.decisionOutcome } : {},
1810
+ ...decision?.selectedVariant ? { selectedVariant: decision.selectedVariant } : {},
1811
+ ...decision?.primaryJudge ? { primaryJudge: decision.primaryJudge } : {}
1812
+ };
1813
+ }
1814
+ function buildFallbackDecisionSummary(state) {
1815
+ const decision = state.decision;
1816
+ if (!decision) return null;
1817
+ return {
1818
+ outcome: decision.outcome ?? null,
1819
+ reason: decision.reason ?? null,
1820
+ decisionStatus: decision.decisionStatus ?? null,
1821
+ decisionOutcome: decision.decisionOutcome ?? null,
1822
+ selectedVariant: decision.selectedVariant ?? null,
1823
+ primaryJudge: decision.primaryJudge ?? null
1824
+ };
1825
+ }
1826
+ function hasEvaluationVariantScores(evaluation) {
1827
+ return Boolean(evaluation?.variantScores && Object.keys(evaluation.variantScores).length > 0);
1828
+ }
1829
+ function getStoredEvaluationTaskId(evaluation) {
1830
+ const taskId = evaluation?.taskId;
1831
+ return typeof taskId === "string" && taskId.trim().length > 0 ? taskId : null;
1832
+ }
1833
+ var AmbiguousLabTaskIdError = class extends Error {
1834
+ constructor(requestedTaskId, matches, matchType) {
1835
+ super(
1836
+ `Ambiguous lab task ID prefix "${requestedTaskId}" matched ${matches.length} state files. Use a longer task ID. Matches: ${matches.map((match) => `${match.taskId} (${path2.relative(process.cwd(), match.runRoot)})`).join(", ")}`
1837
+ );
1838
+ this.requestedTaskId = requestedTaskId;
1839
+ this.matches = matches;
1840
+ this.matchType = matchType;
1841
+ this.name = "AmbiguousLabTaskIdError";
1842
+ }
1843
+ requestedTaskId;
1844
+ matches;
1845
+ matchType;
1846
+ toJson() {
1847
+ return {
1848
+ error: this.message,
1849
+ code: "ambiguous_lab_task_id",
1850
+ taskId: this.requestedTaskId,
1851
+ matchType: this.matchType,
1852
+ matches: this.matches.map((match) => ({
1853
+ taskId: match.taskId,
1854
+ runRoot: match.runRoot
1855
+ }))
1856
+ };
1857
+ }
1858
+ };
1859
+ function findLabRunStateForTask2(buildDir, taskId) {
1860
+ const exact = findLabRunStateForTask(taskId, buildDir);
1861
+ if (exact) {
1862
+ return { runRoot: exact.runPath, taskId: exact.taskId };
1863
+ }
1864
+ const prefixMatches = /* @__PURE__ */ new Map();
1865
+ for (const { runPath: runRoot } of listLabRunDirs(buildDir)) {
1866
+ for (const subdir of ["competitions", "background"]) {
1867
+ const stateDir = path2.join(runRoot, "state", subdir);
1868
+ if (!fs.existsSync(stateDir)) {
1869
+ continue;
1870
+ }
1871
+ for (const entry of fs.readdirSync(stateDir)) {
1872
+ if (!entry.endsWith(".json") || !entry.startsWith(`${taskId}-`)) {
1873
+ continue;
1874
+ }
1875
+ const resolvedTaskId = entry.slice(0, -".json".length);
1876
+ prefixMatches.set(`${runRoot}\0${resolvedTaskId}`, {
1877
+ runRoot,
1878
+ taskId: resolvedTaskId
1879
+ });
1880
+ }
1881
+ }
1882
+ }
1883
+ const matches = [...prefixMatches.values()];
1884
+ if (matches.length > 1) {
1885
+ throw new AmbiguousLabTaskIdError(taskId, matches, "prefix");
1886
+ }
1887
+ return matches[0] ?? null;
1888
+ }
1889
+ function buildLabStateReaderOptions(runRoot) {
1890
+ const stateRoot = path2.join(runRoot, "state");
1891
+ return {
1892
+ stateDir: path2.join(stateRoot, "competitions"),
1893
+ backgroundDir: path2.join(stateRoot, "background"),
1894
+ unifiedStateDir: stateRoot
1895
+ };
1896
+ }
1897
+ function resolveCompetitionResultsTaskId(options) {
1898
+ const candidates = [];
1899
+ const seen = /* @__PURE__ */ new Set();
1900
+ const pushCandidate = (taskId) => {
1901
+ if (typeof taskId !== "string") return;
1902
+ const trimmed = taskId.trim();
1903
+ if (trimmed.length === 0 || seen.has(trimmed)) return;
1904
+ seen.add(trimmed);
1905
+ candidates.push(trimmed);
1906
+ };
1907
+ pushCandidate(options.requestedTaskId);
1908
+ pushCandidate(options.evaluationTaskId);
1909
+ for (const taskId of options.judgeEvaluationTaskIds ?? []) {
1910
+ pushCandidate(taskId);
1911
+ }
1912
+ if (!/-st\d+$/.test(options.requestedTaskId)) {
1913
+ pushCandidate(`${options.requestedTaskId}-st1`);
1914
+ }
1915
+ for (const candidate of candidates) {
1916
+ if (options.hasCompetitionState(candidate)) {
1917
+ return candidate;
1918
+ }
1919
+ }
1920
+ const storedEvaluationTaskId = [
1921
+ options.evaluationTaskId,
1922
+ ...options.judgeEvaluationTaskIds ?? []
1923
+ ].map((taskId) => typeof taskId === "string" ? taskId.trim() : "").find((taskId) => taskId.length > 0);
1924
+ return storedEvaluationTaskId ?? options.requestedTaskId;
1925
+ }
1926
+ function getPrimaryWinnerScoreForCalibration(report, multiJudgeRun) {
1927
+ return typeof multiJudgeRun?.primary_winner_score === "number" && Number.isFinite(multiJudgeRun.primary_winner_score) ? multiJudgeRun.primary_winner_score : report.judgeSelectedTopPick.score;
1928
+ }
1929
+ function renderInterruptedCompetitionNotice(state) {
1930
+ const line = formatInterruptedCompetitionNotice(state);
1931
+ if (!line) return;
1932
+ console.log(chalk6.yellow(line));
1933
+ console.log();
1934
+ }
1935
+ function formatWinnerReconciliationHuman(report, multiJudgeRun) {
1936
+ if (!report.hasTelemetry) return;
1937
+ const j = report.judgeSelectedTopPick.variant;
1938
+ const r = report.finalRetainedWinner.variant;
1939
+ const jScore = typeof report.judgeSelectedTopPick.score === "number" ? ` (${report.judgeSelectedTopPick.score.toFixed(1)})` : "";
1940
+ const rScore = typeof report.finalRetainedWinner.score === "number" ? ` (${report.finalRetainedWinner.score.toFixed(1)})` : "";
1941
+ console.log(chalk6.cyan.bold("Winner reconciliation"));
1942
+ if (report.competitionOutcome) {
1943
+ console.log(chalk6.gray(` Competition outcome: ${report.competitionOutcome}`));
1944
+ }
1945
+ if (!j) {
1946
+ console.log(chalk6.gray(" Judge-selected top pick: (none)"));
1947
+ } else {
1948
+ console.log(chalk6.white(` Judge-selected top pick: ${j}${jScore}`));
1949
+ }
1950
+ if (!r) {
1951
+ console.log(
1952
+ chalk6.gray(" Final retained winner: (none \u2014 competition outcome did not retain a winner)")
1953
+ );
1954
+ } else {
1955
+ console.log(chalk6.white(` Final retained winner: ${r}${rScore}`));
1956
+ }
1957
+ if (report.requiredGatePolicy) {
1958
+ console.log(chalk6.white(` Required gate policy: ${report.requiredGatePolicy}`));
1959
+ }
1960
+ if (report.detectedTaskType) {
1961
+ console.log(chalk6.white(` Detected task type: ${report.detectedTaskType}`));
1962
+ }
1963
+ if (report.multiJudgePrimaryWinner) {
1964
+ const aligned = report.multiJudgePrimaryAlignedWithFinal === null ? "" : report.multiJudgePrimaryAlignedWithFinal ? chalk6.green(" (matches final retained)") : chalk6.yellow(" (differs from final retained)");
1965
+ console.log(
1966
+ chalk6.white(` Multi-judge primary winner: ${report.multiJudgePrimaryWinner}${aligned}`)
1967
+ );
1968
+ }
1969
+ const primaryWinnerScore = getPrimaryWinnerScoreForCalibration(report, multiJudgeRun);
1970
+ const scoreDelta = typeof primaryWinnerScore === "number" && typeof report.finalRetainedWinner.score === "number" ? primaryWinnerScore - report.finalRetainedWinner.score : null;
1971
+ if (scoreDelta != null && Math.abs(scoreDelta) >= SCORE_CALIBRATION_DISPLAY_DELTA_THRESHOLD) {
1972
+ console.log(chalk6.white(` Primary-vs-final score delta: ${scoreDelta.toFixed(1)}`));
1973
+ }
1974
+ if (report.multiLensWinnerFlip) {
1975
+ const f = report.multiLensWinnerFlip;
1976
+ console.log(
1977
+ chalk6.gray(
1978
+ ` Multi-lens winner flip: ${f.rawWinner} \u2192 ${f.finalWinner}${f.reason ? ` \u2014 ${f.reason}` : ""}`
1979
+ )
1980
+ );
1981
+ }
1982
+ if (report.judgedWinnerNotRetainedReason) {
1983
+ console.log(
1984
+ chalk6.yellow(` Judged winner not retained: ${report.judgedWinnerNotRetainedReason}`)
1985
+ );
1986
+ } else if (j && r && report.reconciliationStatus === "aligned") {
1987
+ console.log(chalk6.green(" Judge pick matches final retained winner."));
1988
+ } else if (!j && !r) {
1989
+ console.log(chalk6.gray(" No judge pick or retained winner recorded for reconciliation."));
1990
+ }
1991
+ console.log();
1992
+ }
1993
+ function normalizeMatrixProfileDecision(input) {
1994
+ if (input.profileDecision === "unanimous" || input.profileDecision === "split" || input.profileDecision === "inconclusive") {
1995
+ return input.profileDecision;
1996
+ }
1997
+ if (input.winnerStatus === "inconclusive") return "inconclusive";
1998
+ if (typeof input.profilesDisagree === "boolean") {
1999
+ return input.profilesDisagree ? "split" : "unanimous";
2000
+ }
2001
+ return "unknown";
2002
+ }
2003
+ function matrixSummaryFromStateMetadata(matrix) {
2004
+ if (!matrix || matrix.autoRun !== true) return null;
2005
+ return {
2006
+ matrixAutoRun: true,
2007
+ matrixEvaluatorType: matrix.evaluatorType,
2008
+ matrixProfiles: matrix.profiles,
2009
+ matrixWinnerStatus: matrix.winnerStatus,
2010
+ matrixProfilesDisagree: matrix.profilesDisagree,
2011
+ matrixProfileDecision: normalizeMatrixProfileDecision({
2012
+ profileDecision: matrix.profileDecision,
2013
+ winnerStatus: matrix.winnerStatus,
2014
+ profilesDisagree: matrix.profilesDisagree
2015
+ }),
2016
+ blockingHumanChecks: [],
2017
+ advisoryHumanChecks: [
2018
+ ...matrix.escalationReasons?.length ? [`Escalation reasons: ${matrix.escalationReasons.join(", ")}`] : [],
2019
+ ...matrix.winnerCaveats ?? []
2020
+ ]
2021
+ };
2022
+ }
2023
+ function getSelectedEvaluationKind(evaluation) {
2024
+ if (!evaluation) return "unknown";
2025
+ const rationale = evaluation.winnerRationale;
2026
+ if (rationale && typeof rationale === "object" && rationale.mode === "profile-matrix") {
2027
+ return "profile-matrix";
2028
+ }
2029
+ const evaluationId = evaluation.evaluationId;
2030
+ if (typeof evaluationId === "string" && evaluationId.includes("profile-matrix")) {
2031
+ return "profile-matrix";
2032
+ }
2033
+ const judgeType = evaluation.judgeType;
2034
+ return typeof judgeType === "string" ? judgeType : "unknown";
2035
+ }
2036
+ function formatJudgeEvaluationModelLine(evaluation) {
2037
+ const label = judgeModelLabel(evaluation.model, evaluation.reportedModel);
2038
+ return label ? ` Model: ${label}` : void 0;
2039
+ }
2040
+ function isFiniteNumber(value) {
2041
+ return typeof value === "number" && Number.isFinite(value);
2042
+ }
2043
+ function uniqueEvaluationsForWinnerEvidence(selectedEvaluation, judgeEvaluations) {
2044
+ const seen = /* @__PURE__ */ new Set();
2045
+ const result = [];
2046
+ for (const evaluation of [selectedEvaluation, ...judgeEvaluations]) {
2047
+ const stored = evaluation;
2048
+ const key = typeof stored.evaluationId === "string" ? `id:${stored.evaluationId}` : `content:${stored.judgeType ?? "unknown"}:${stored.model ?? ""}:${stored.winnerVariant ?? ""}:${stored.winnerScore ?? ""}:${stored.winnerConfidence ?? ""}:${Object.keys(
2049
+ stored.variantScores ?? {}
2050
+ ).sort().join("|")}`;
2051
+ if (seen.has(key)) continue;
2052
+ seen.add(key);
2053
+ result.push(evaluation);
2054
+ }
2055
+ return result;
2056
+ }
2057
+ function evaluationWinnerMatchesFinal(evaluation, finalWinnerVariant) {
2058
+ return Boolean(
2059
+ finalWinnerVariant && evaluation?.winnerVariant && variantHandlesMatchForResults(evaluation.winnerVariant, finalWinnerVariant)
2060
+ );
2061
+ }
2062
+ function resolveWinnerEvidenceForResults(options) {
2063
+ const {
2064
+ finalWinnerVariant,
2065
+ selectedEvaluation,
2066
+ judgeEvaluations,
2067
+ multiJudgeRun,
2068
+ winnerReconciliation
2069
+ } = options;
2070
+ const selectedKind = getSelectedEvaluationKind(selectedEvaluation);
2071
+ const primaryJudge = multiJudgeRun?.primary_judge?.trim() || null;
2072
+ const evaluations = uniqueEvaluationsForWinnerEvidence(selectedEvaluation, judgeEvaluations);
2073
+ const matchingEvaluations = evaluations.filter(
2074
+ (entry) => getSelectedEvaluationKind(entry) !== "profile-matrix" && evaluationWinnerMatchesFinal(entry, finalWinnerVariant)
2075
+ );
2076
+ const primaryEvaluation = primaryJudge != null ? matchingEvaluations.find(
2077
+ (entry) => entry.judgeType === primaryJudge
2078
+ ) : void 0;
2079
+ const selectedMatchesFinal = getSelectedEvaluationKind(selectedEvaluation) !== "profile-matrix" && evaluationWinnerMatchesFinal(selectedEvaluation, finalWinnerVariant);
2080
+ const selectedWinnerEvaluation = selectedMatchesFinal ? selectedEvaluation : void 0;
2081
+ const winnerEvaluation = primaryEvaluation ?? selectedWinnerEvaluation ?? matchingEvaluations.at(0) ?? null;
2082
+ if (winnerEvaluation) {
2083
+ const score = scoreForVariant(winnerEvaluation, finalWinnerVariant) ?? (isFiniteNumber(winnerEvaluation.winnerScore) ? winnerEvaluation.winnerScore : null);
2084
+ const source = winnerEvaluation === primaryEvaluation ? "primary_judge" : winnerEvaluation === selectedWinnerEvaluation ? "selected_evaluation" : "judge_row";
2085
+ return {
2086
+ score,
2087
+ decisionScore: score,
2088
+ confidence: isFiniteNumber(winnerEvaluation.winnerConfidence) ? winnerEvaluation.winnerConfidence : null,
2089
+ rationale: winnerEvaluation.winnerRationale ?? null,
2090
+ scoreSource: source,
2091
+ provenance: source === "primary_judge" ? "competition_handle; primary judge evaluation aligned" : "competition_handle; judge evaluation aligned"
2092
+ };
2093
+ }
2094
+ if (winnerReconciliation.multiJudgePrimaryAlignedWithFinal === true) {
2095
+ const score = (isFiniteNumber(multiJudgeRun?.primary_winner_score) ? multiJudgeRun.primary_winner_score : null) ?? winnerReconciliation.judgeSelectedTopPick.score;
2096
+ return {
2097
+ score,
2098
+ decisionScore: score,
2099
+ confidence: isFiniteNumber(multiJudgeRun?.primary_winner_confidence) ? multiJudgeRun.primary_winner_confidence : null,
2100
+ rationale: null,
2101
+ scoreSource: "primary_judge",
2102
+ provenance: "competition_handle; primary judge telemetry aligned"
2103
+ };
2104
+ }
2105
+ if (winnerReconciliation.finalRetainedWinner.score != null) {
2106
+ return {
2107
+ score: winnerReconciliation.finalRetainedWinner.score,
2108
+ decisionScore: winnerReconciliation.finalRetainedWinner.score,
2109
+ confidence: null,
2110
+ rationale: null,
2111
+ scoreSource: "reconciliation",
2112
+ provenance: "competition_handle; score recovered from reconciliation"
2113
+ };
2114
+ }
2115
+ const scoreSource = winnerReconciliation.reconciliationStatus === "handle_differs_from_judge_row" ? "handle_drift" : selectedKind === "profile-matrix" ? "matrix_advisory" : "unavailable";
2116
+ return {
2117
+ score: null,
2118
+ decisionScore: null,
2119
+ confidence: null,
2120
+ rationale: null,
2121
+ scoreSource,
2122
+ provenance: scoreSource === "handle_drift" ? "competition_handle; final retained winner differs from judge row handle" : selectedKind === "profile-matrix" ? "competition_handle; selected evaluation is advisory matrix" : "competition_handle; judge evaluation winner unavailable"
2123
+ };
2124
+ }
2125
+ function isRecord(value) {
2126
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
2127
+ }
2128
+ function readLatestProfileMatrixSummary(options) {
2129
+ const matrixEvaluation = options.evaluations.filter((entry) => {
2130
+ const rationale2 = entry.winnerRationale;
2131
+ return entry.evaluationId.includes("-profile-matrix-") || isRecord(rationale2) && rationale2.mode === "profile-matrix";
2132
+ }).sort(
2133
+ (left, right) => String(right.createdAt ?? "").localeCompare(String(left.createdAt ?? ""))
2134
+ ).at(0);
2135
+ const rationale = matrixEvaluation?.winnerRationale;
2136
+ if (!matrixEvaluation || !isRecord(rationale) || typeof rationale.artifactPath !== "string") {
2137
+ return null;
2138
+ }
2139
+ for (const telemetryDir of options.telemetryDirs) {
2140
+ const artifactPath = path2.join(telemetryDir, rationale.artifactPath);
2141
+ if (!fs.existsSync(artifactPath)) continue;
2142
+ let raw;
2143
+ try {
2144
+ raw = parseJsonWithContext(
2145
+ fs.readFileSync(artifactPath, "utf8"),
2146
+ `Profile matrix artifact at ${artifactPath}`
2147
+ );
2148
+ } catch {
2149
+ continue;
2150
+ }
2151
+ const payload = isRecord(raw) ? raw : {};
2152
+ const result = isRecord(payload.result) ? payload.result : payload;
2153
+ const disagreements = isRecord(result.disagreements) ? result.disagreements : {};
2154
+ const diagnostics = isRecord(result.diagnostics) ? result.diagnostics : {};
2155
+ const winnerByProfile = isRecord(disagreements.winnerByProfile) ? Object.fromEntries(
2156
+ Object.entries(disagreements.winnerByProfile).filter(
2157
+ (entry) => typeof entry[1] === "string"
2158
+ )
2159
+ ) : void 0;
2160
+ const blockingHumanChecks = Array.isArray(diagnostics.blockingHumanChecks) ? diagnostics.blockingHumanChecks.filter(
2161
+ (entry) => typeof entry === "string"
2162
+ ) : [];
2163
+ const advisoryHumanChecks = Array.isArray(diagnostics.advisoryHumanChecks) ? diagnostics.advisoryHumanChecks.filter(
2164
+ (entry) => typeof entry === "string"
2165
+ ) : [];
2166
+ return {
2167
+ matrixAutoRun: true,
2168
+ matrixEvaluatorType: typeof result.matrixEvaluatorType === "string" ? result.matrixEvaluatorType : void 0,
2169
+ matrixProfiles: winnerByProfile,
2170
+ matrixWinnerStatus: typeof result.winnerStatus === "string" ? result.winnerStatus : void 0,
2171
+ matrixProfilesDisagree: typeof disagreements.profilesDisagree === "boolean" ? disagreements.profilesDisagree : void 0,
2172
+ matrixProfileDecision: normalizeMatrixProfileDecision({
2173
+ winnerStatus: result.winnerStatus,
2174
+ profilesDisagree: disagreements.profilesDisagree
2175
+ }),
2176
+ blockingHumanChecks,
2177
+ advisoryHumanChecks: [
2178
+ ...Array.isArray(result.winnerCaveats) ? result.winnerCaveats.filter((entry) => typeof entry === "string") : [],
2179
+ ...advisoryHumanChecks
2180
+ ]
2181
+ };
2182
+ }
2183
+ return null;
2184
+ }
2185
+ function formatMatrixProfilesForResults(profiles) {
2186
+ if (!profiles || Object.keys(profiles).length === 0) return "n/a";
2187
+ return Object.entries(profiles).map(([profile, winner]) => `${profile}=${winner}`).join(", ");
2188
+ }
2189
+ function renderMatrixResultsSummary(summary) {
2190
+ if (!summary) return;
2191
+ console.log(chalk6.cyan.bold("Matrix Escalation:"));
2192
+ console.log(chalk6.white(" matrixAutoRun: true"));
2193
+ if (summary.matrixEvaluatorType) {
2194
+ console.log(chalk6.white(` matrixEvaluatorType: ${summary.matrixEvaluatorType}`));
2195
+ }
2196
+ console.log(
2197
+ chalk6.white(` matrixProfiles: ${formatMatrixProfilesForResults(summary.matrixProfiles)}`)
2198
+ );
2199
+ if (summary.matrixWinnerStatus) {
2200
+ console.log(chalk6.white(` matrixWinnerStatus: ${summary.matrixWinnerStatus}`));
2201
+ }
2202
+ if (typeof summary.matrixProfilesDisagree === "boolean") {
2203
+ console.log(chalk6.white(` matrixProfilesDisagree: ${summary.matrixProfilesDisagree}`));
2204
+ console.log(chalk6.white(` matrixProfileDecision: ${summary.matrixProfileDecision}`));
2205
+ }
2206
+ if (summary.blockingHumanChecks.length > 0) {
2207
+ console.log(chalk6.white(" Conditional checks:"));
2208
+ for (const check of summary.blockingHumanChecks) {
2209
+ console.log(chalk6.gray(` - ${check}`));
2210
+ }
2211
+ }
2212
+ if (summary.advisoryHumanChecks.length > 0) {
2213
+ console.log(chalk6.white(" Advisory checks:"));
2214
+ for (const check of summary.advisoryHumanChecks) {
2215
+ console.log(chalk6.gray(` - ${check}`));
2216
+ }
2217
+ }
2218
+ console.log();
2219
+ }
2220
+ function buildScoreCalibrationSummary(options) {
2221
+ const primaryWinner = options.report.multiJudgePrimaryWinner;
2222
+ const finalWinner = options.report.finalRetainedWinner.variant;
2223
+ const primaryWinnerScore = getPrimaryWinnerScoreForCalibration(
2224
+ options.report,
2225
+ options.multiJudgeRun
2226
+ );
2227
+ const finalWinnerScore = options.report.finalRetainedWinner.score;
2228
+ const primaryAlignedWithFinal = primaryWinner && finalWinner ? variantHandlesMatchForResults(primaryWinner, finalWinner) : options.report.multiJudgePrimaryAlignedWithFinal;
2229
+ const scoreDeltaPrimaryMinusFinal = typeof primaryWinnerScore === "number" && typeof finalWinnerScore === "number" ? primaryWinnerScore - finalWinnerScore : null;
2230
+ return {
2231
+ primaryJudge: options.multiJudgeRun?.primary_judge ?? null,
2232
+ primaryWinner,
2233
+ primaryWinnerScore,
2234
+ finalWinner,
2235
+ finalWinnerScore,
2236
+ primaryAlignedWithFinal,
2237
+ scoreDeltaPrimaryMinusFinal
2238
+ };
2239
+ }
2240
+ function formatConfidencePercent(value) {
2241
+ const percent = value <= 1 ? value * 100 : value;
2242
+ return `${percent.toFixed(2)}%`;
2243
+ }
2244
+ var WARNING_VERBOSITY_VALUES = ["silent", "minimal", "normal", "verbose"];
2245
+ function resolveWarningVerbosity(input, source) {
2246
+ if (typeof input !== "string") {
2247
+ throw new Error(`Invalid warning verbosity from ${source}`);
2248
+ }
2249
+ if (WARNING_VERBOSITY_VALUES.includes(input)) {
2250
+ return input;
2251
+ }
2252
+ throw new Error(
2253
+ `Invalid warning verbosity "${input}" from ${source}. Expected one of: ${WARNING_VERBOSITY_VALUES.join(", ")}`
2254
+ );
2255
+ }
2256
+ function getDisplayableSelfConfidence(entry) {
2257
+ if (entry.confidenceSource === "decision_fallback") {
2258
+ return void 0;
2259
+ }
2260
+ return typeof entry.confidence === "number" && Number.isFinite(entry.confidence) ? entry.confidence : void 0;
2261
+ }
2262
+ function resolveProviderDisplayLabel(providerId) {
2263
+ const normalized = providerId.trim();
2264
+ if (normalized.length === 0) {
2265
+ return "Provider";
2266
+ }
2267
+ try {
2268
+ const config = getProviderConfig(normalized);
2269
+ const displayName = typeof config.display_name === "string" && config.display_name.trim().length > 0 ? config.display_name.trim() : typeof config.name === "string" && config.name.trim().length > 0 ? config.name.trim() : "";
2270
+ if (displayName.length > 0) {
2271
+ return displayName;
2272
+ }
2273
+ } catch {
2274
+ }
2275
+ return normalized.charAt(0).toUpperCase() + normalized.slice(1);
2276
+ }
2277
+ function formatProviderExecutionPathLine(variant, resultRecord) {
2278
+ const executionPath = typeof resultRecord?.executionPath === "string" ? resultRecord.executionPath.trim() : "";
2279
+ if (executionPath.length === 0) {
2280
+ return null;
2281
+ }
2282
+ const providerId = variant.split(":")[0] ?? "";
2283
+ const providerLabel = resolveProviderDisplayLabel(providerId);
2284
+ const fallbackReason = typeof resultRecord?.fallbackReason === "string" ? resultRecord.fallbackReason.trim() : "";
2285
+ return fallbackReason.length > 0 ? `${providerLabel} Execution: ${executionPath} (${fallbackReason})` : `${providerLabel} Execution: ${executionPath}`;
2286
+ }
2287
+ function toSafeNumber(value) {
2288
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
2289
+ }
2290
+ function candidateHasFailingVerificationForDisplay(candidateRecord, requiredGatePolicy) {
2291
+ return getDisplayVerificationVerdict(candidateRecord, { requiredGatePolicy }).failed;
2292
+ }
2293
+ function shouldRenderUnretainedJudgeTopPick(input) {
2294
+ return !input.hasFinalWinner && Boolean(input.evaluationWinnerVariant) && input.decisionReason !== "judge_off";
2295
+ }
2296
+ function extractPartialEditStats(candidateRecord) {
2297
+ const filesChangedDirect = toSafeNumber(candidateRecord.filesChanged);
2298
+ const linesAddedDirect = toSafeNumber(candidateRecord.linesAdded);
2299
+ const linesRemovedDirect = toSafeNumber(candidateRecord.linesRemoved);
2300
+ const gitMetrics = typeof candidateRecord.gitMetrics === "object" && candidateRecord.gitMetrics !== null ? candidateRecord.gitMetrics : null;
2301
+ const worktreeSummary = typeof candidateRecord.worktreeSummary === "object" && candidateRecord.worktreeSummary !== null ? candidateRecord.worktreeSummary : null;
2302
+ const filesChanged = filesChangedDirect ?? toSafeNumber(gitMetrics?.filesChanged) ?? toSafeNumber(worktreeSummary?.filesChanged) ?? 0;
2303
+ const linesAdded = linesAddedDirect ?? toSafeNumber(gitMetrics?.linesAdded) ?? toSafeNumber(worktreeSummary?.insertions) ?? 0;
2304
+ const linesRemoved = linesRemovedDirect ?? toSafeNumber(gitMetrics?.linesDeleted) ?? toSafeNumber(worktreeSummary?.deletions) ?? 0;
2305
+ if (filesChanged <= 0 && linesAdded <= 0 && linesRemoved <= 0) {
2306
+ return null;
2307
+ }
2308
+ return { filesChanged, linesAdded, linesRemoved };
2309
+ }
2310
+ function formatVariantTestVerificationLine(candidateRecord) {
2311
+ const record = candidateRecord;
2312
+ const signals = [
2313
+ record.outcome?.verification?.testStatus,
2314
+ record.testStatus,
2315
+ record.testsExecuted?.exitCode,
2316
+ record.testMetrics?.failedTests
2317
+ ];
2318
+ if (signals.every((signal) => signal == null)) return null;
2319
+ const gate = readVariantVerification(candidateRecord).gates.test;
2320
+ const reason = gate.unavailableReason ? ` (${gate.unavailableReason})` : "";
2321
+ return `Tests: ${gate.status}${reason}`;
2322
+ }
2323
+ function compareVariantLabels(a, b) {
2324
+ const vLabelA = a.match(/^v(\d+)$/i);
2325
+ const vLabelB = b.match(/^v(\d+)$/i);
2326
+ if (vLabelA && vLabelB) {
2327
+ return Number(vLabelA[1]) - Number(vLabelB[1]);
2328
+ }
2329
+ if (vLabelA) return -1;
2330
+ if (vLabelB) return 1;
2331
+ const variantLabelA = a.match(/^variant-(\d+)$/i);
2332
+ const variantLabelB = b.match(/^variant-(\d+)$/i);
2333
+ if (variantLabelA && variantLabelB) {
2334
+ return Number(variantLabelA[1]) - Number(variantLabelB[1]);
2335
+ }
2336
+ if (variantLabelA) return -1;
2337
+ if (variantLabelB) return 1;
2338
+ return a.localeCompare(b);
2339
+ }
2340
+ function variantIdentityCandidates(variant) {
2341
+ const provider = variant.provider;
2342
+ const executionMode = variant.executionMode;
2343
+ const model = variant.model;
2344
+ const resolvedModel = variant.resolvedModel;
2345
+ const models = resolvedModel && resolvedModel !== model ? [resolvedModel, model] : [model];
2346
+ const strategy = variant.strategy;
2347
+ return [
2348
+ variant.variant ?? null,
2349
+ provider,
2350
+ ...models.flatMap(
2351
+ (m) => m ? [`${provider}:${m}`, executionMode ? `${provider}:${m}:${executionMode}` : null] : []
2352
+ ),
2353
+ `${provider}:${strategy}`,
2354
+ executionMode ? `${provider}:${strategy}:${executionMode}` : null,
2355
+ ...models.flatMap(
2356
+ (m) => m ? [
2357
+ `${provider}:${m}:${strategy}`,
2358
+ executionMode ? `${provider}:${m}:${strategy}:${executionMode}` : null
2359
+ ] : []
2360
+ )
2361
+ ].filter((value) => Boolean(value));
2362
+ }
2363
+ function findVariantInputSpecWarning(variantIds, variants) {
2364
+ const normalizedIds = new Set(
2365
+ variantIds.filter((value) => typeof value === "string").map((value) => value.trim()).filter(Boolean)
2366
+ );
2367
+ if (normalizedIds.size === 0) return null;
2368
+ for (const variant of variants) {
2369
+ if (!variant.inputSpecWarning) continue;
2370
+ if (variantIdentityCandidates(variant).some((identity) => normalizedIds.has(identity))) {
2371
+ return variant.inputSpecWarning;
2372
+ }
2373
+ }
2374
+ return null;
2375
+ }
2376
+ function extractVariantLabelMapping(evaluation) {
2377
+ const mapping = {};
2378
+ const directMapping = typeof evaluation.variantLabelMapping === "object" && evaluation.variantLabelMapping !== null ? evaluation.variantLabelMapping : null;
2379
+ if (directMapping) {
2380
+ for (const [label, variant] of Object.entries(directMapping)) {
2381
+ if (typeof variant !== "string") continue;
2382
+ const trimmedLabel = label.trim();
2383
+ const trimmedVariant = variant.trim();
2384
+ if (trimmedLabel.length === 0 || trimmedVariant.length === 0) continue;
2385
+ mapping[trimmedLabel] = trimmedVariant;
2386
+ }
2387
+ }
2388
+ const variantScores = typeof evaluation.variantScores === "object" && evaluation.variantScores !== null ? evaluation.variantScores : null;
2389
+ const pointerMapping = typeof variantScores?.variantLabelMapping === "object" && variantScores.variantLabelMapping !== null ? variantScores.variantLabelMapping : null;
2390
+ if (pointerMapping) {
2391
+ for (const [label, variant] of Object.entries(pointerMapping)) {
2392
+ if (typeof variant !== "string") continue;
2393
+ const trimmedLabel = label.trim();
2394
+ const trimmedVariant = variant.trim();
2395
+ if (trimmedLabel.length === 0 || trimmedVariant.length === 0) continue;
2396
+ mapping[trimmedLabel] = trimmedVariant;
2397
+ }
2398
+ }
2399
+ if (variantScores) {
2400
+ for (const [variant, data] of Object.entries(variantScores)) {
2401
+ const payload = data;
2402
+ if (!payload || typeof payload !== "object") continue;
2403
+ if (typeof payload.label !== "string") continue;
2404
+ const trimmedLabel = payload.label.trim();
2405
+ if (trimmedLabel.length === 0) continue;
2406
+ mapping[trimmedLabel] = variant;
2407
+ }
2408
+ }
2409
+ return Object.entries(mapping).map(([label, variant]) => ({ label, variant })).sort((a, b) => compareVariantLabels(a.label, b.label));
2410
+ }
2411
+ function formatStoredJudgeType(judgeType) {
2412
+ switch (judgeType) {
2413
+ case "ai":
2414
+ return "AI";
2415
+ case "multi-agent":
2416
+ return "Multi-Agent";
2417
+ case "multi-lens":
2418
+ return "Multi-Lens";
2419
+ case "canonical":
2420
+ return "Canonical";
2421
+ case "consolidated":
2422
+ return "Consolidated";
2423
+ case "unknown":
2424
+ return "Unknown";
2425
+ }
2426
+ }
2427
+ function judgeTypeDisplayPriority(judgeType) {
2428
+ switch (judgeType) {
2429
+ case "ai":
2430
+ return 0;
2431
+ case "multi-agent":
2432
+ return 1;
2433
+ case "multi-lens":
2434
+ return 2;
2435
+ case "canonical":
2436
+ return 3;
2437
+ case "consolidated":
2438
+ return 4;
2439
+ case "unknown":
2440
+ return 5;
2441
+ }
2442
+ }
2443
+ function normalizeDisplayJudgeEvaluations(entries) {
2444
+ const preferred = entries.filter(
2445
+ (entry) => entry.judgeType === "ai" || entry.judgeType === "multi-agent" || entry.judgeType === "multi-lens"
2446
+ );
2447
+ const source = preferred.length > 0 ? preferred : entries;
2448
+ return [...source].sort((a, b) => {
2449
+ const priorityDelta = judgeTypeDisplayPriority(a.judgeType) - judgeTypeDisplayPriority(b.judgeType);
2450
+ if (priorityDelta !== 0) return priorityDelta;
2451
+ return a.evaluationId.localeCompare(b.evaluationId);
2452
+ });
2453
+ }
2454
+ function getVariantOverallScore(entry) {
2455
+ if (!entry || typeof entry !== "object") return null;
2456
+ if (typeof entry.rankingScore === "number" && Number.isFinite(entry.rankingScore)) {
2457
+ return entry.rankingScore;
2458
+ }
2459
+ if (typeof entry.compositeScore === "number" && Number.isFinite(entry.compositeScore)) {
2460
+ return entry.compositeScore;
2461
+ }
2462
+ if (typeof entry.overallScore === "number" && Number.isFinite(entry.overallScore)) {
2463
+ return entry.overallScore;
2464
+ }
2465
+ return null;
2466
+ }
2467
+ function buildPerJudgeVariantMatrix(entries) {
2468
+ const matrix = /* @__PURE__ */ new Map();
2469
+ for (const entry of entries) {
2470
+ const judgeLabel = formatStoredJudgeType(entry.judgeType);
2471
+ for (const [variant, payload] of Object.entries(entry.variantScores ?? {})) {
2472
+ if (!payload || typeof payload !== "object" || !("scores" in payload)) {
2473
+ continue;
2474
+ }
2475
+ const variantEntry = matrix.get(variant) ?? {
2476
+ labels: /* @__PURE__ */ new Set(),
2477
+ scoresByJudge: {}
2478
+ };
2479
+ if (typeof payload?.label === "string" && payload.label.trim().length > 0) {
2480
+ variantEntry.labels.add(payload.label.trim());
2481
+ }
2482
+ variantEntry.scoresByJudge[judgeLabel] = getVariantOverallScore(payload);
2483
+ matrix.set(variant, variantEntry);
2484
+ }
2485
+ }
2486
+ return [...matrix.entries()].map(([variant, value]) => ({
2487
+ variant,
2488
+ labels: [...value.labels].sort(compareVariantLabels),
2489
+ scoresByJudge: value.scoresByJudge
2490
+ })).sort((a, b) => a.variant.localeCompare(b.variant));
2491
+ }
2492
+ function renderPerJudgeVariantScores(entries) {
2493
+ const displayEntries = normalizeDisplayJudgeEvaluations(entries);
2494
+ if (displayEntries.length < 2) return;
2495
+ const judgeLabels = displayEntries.map((entry) => formatStoredJudgeType(entry.judgeType));
2496
+ const matrix = buildPerJudgeVariantMatrix(displayEntries);
2497
+ if (matrix.length === 0) return;
2498
+ console.log(chalk6.cyan.bold("Per-Judge Variant Scores:\n"));
2499
+ for (const entry of displayEntries) {
2500
+ const winnerBits = [formatStoredJudgeType(entry.judgeType)];
2501
+ if (entry.winnerVariant) {
2502
+ const scoreSuffix = typeof entry.winnerScore === "number" ? ` (${entry.winnerScore.toFixed(1)})` : "";
2503
+ winnerBits.push(`winner=${entry.winnerVariant}${scoreSuffix}`);
2504
+ }
2505
+ if (entry.workerPacketArtifactPath) {
2506
+ winnerBits.push(`workerPackets=${entry.workerPacketArtifactPath}`);
2507
+ }
2508
+ console.log(chalk6.gray(` ${winnerBits.join(" \u2022 ")}`));
2509
+ }
2510
+ console.log();
2511
+ for (const row of matrix) {
2512
+ const labelText = row.labels.length > 0 ? ` [${row.labels.join(", ")}]` : "";
2513
+ console.log(chalk6.white(` ${row.variant}${labelText}`));
2514
+ for (const judgeLabel of judgeLabels) {
2515
+ const score = row.scoresByJudge[judgeLabel];
2516
+ const scoreText = typeof score === "number" ? score.toFixed(1) : "n/a";
2517
+ console.log(chalk6.gray(` ${judgeLabel}: ${scoreText}`));
2518
+ }
2519
+ }
2520
+ console.log();
2521
+ }
2522
+ function formatDonorDecisionDiagnostics(decisions) {
2523
+ if (!Array.isArray(decisions)) return [];
2524
+ return decisions.map((entry) => {
2525
+ if (typeof entry !== "object" || entry === null) return null;
2526
+ const decision = entry;
2527
+ if (typeof decision.variant !== "string") return null;
2528
+ const variant = decision.variant;
2529
+ if (decision.winner) {
2530
+ const scorePart = typeof decision.selectedJudgeScore === "number" ? `, score ${decision.selectedJudgeScore}` : "";
2531
+ return `+ ${variant} (winner${scorePart})`;
2532
+ }
2533
+ if (decision.selected) {
2534
+ const parts = ["donor"];
2535
+ if (typeof decision.selectedJudgeRank === "number") {
2536
+ parts.push(`rank ${decision.selectedJudgeRank}`);
2537
+ }
2538
+ if (typeof decision.selectedJudgeScore === "number") {
2539
+ parts.push(`score ${decision.selectedJudgeScore}`);
2540
+ }
2541
+ const reasons2 = Array.isArray(decision.reasons) ? decision.reasons.filter((r) => typeof r === "string") : [];
2542
+ const selectionReason = reasons2.find(
2543
+ (r) => r.startsWith("selected") || r.includes("semantic donor")
2544
+ );
2545
+ if (selectionReason) {
2546
+ parts.push(
2547
+ selectionReason.includes("semantic donor rejected") ? selectionReason.replace("semantic donor rejected:", "semantic profile note:") : selectionReason
2548
+ );
2549
+ }
2550
+ return `+ ${variant} (${parts.join(", ")})`;
2551
+ }
2552
+ const reasons = Array.isArray(decision.reasons) ? decision.reasons.filter((r) => typeof r === "string") : [];
2553
+ const primaryReason = reasons.find((r) => !r.startsWith("not selected")) ?? reasons[0] ?? "not selected";
2554
+ return `- ${variant} (${primaryReason})`;
2555
+ }).filter((line) => line !== null);
2556
+ }
2557
+ function summarizeDonorSelectionDecisions(decisions) {
2558
+ if (!Array.isArray(decisions)) return [];
2559
+ return decisions.map((entry) => {
2560
+ if (typeof entry !== "object" || entry === null) return null;
2561
+ const decision = entry;
2562
+ if (typeof decision.variant !== "string") return null;
2563
+ const reasons = Array.isArray(decision.reasons) ? decision.reasons.filter((reason) => typeof reason === "string") : [];
2564
+ const status = decision.winner ? "declared winner" : decision.selected ? "selected" : "not selected";
2565
+ const shown = decision.selected ? reasons.map(
2566
+ (reason) => reason.replace("semantic donor rejected:", "semantic profile note:")
2567
+ ) : reasons;
2568
+ const details = shown.length > 0 ? `: ${shown.join("; ")}` : "";
2569
+ return `${decision.variant} (${status})${details}`;
2570
+ }).filter((line) => line !== null && line.length > 0);
2571
+ }
2572
+ function summarizeSynthesisArtifact(artifact) {
2573
+ if (!artifact) return null;
2574
+ const synthesisApplied = typeof artifact.synthesisApplied === "boolean" ? artifact.synthesisApplied : null;
2575
+ const winnerFallback = typeof artifact.winnerFallback === "boolean" ? artifact.winnerFallback : null;
2576
+ const synthesisOutcomeStatus = typeof artifact.synthesisOutcomeStatus === "string" ? artifact.synthesisOutcomeStatus : null;
2577
+ const mergedVariants = Array.isArray(artifact.mergedVariants) ? artifact.mergedVariants.filter((value) => typeof value === "string").map(normalizeDisplayedVariantId) : [];
2578
+ const contributingVariants = Array.isArray(artifact.contributingVariants) ? artifact.contributingVariants.filter((value) => typeof value === "string").map(normalizeDisplayedVariantId) : [];
2579
+ const donorSelectionDecisions = Array.isArray(artifact.donorSelectionDecisions) ? artifact.donorSelectionDecisions : null;
2580
+ const synthesisGateResults = readSynthesisGateResultSnapshot(artifact);
2581
+ const harvestSummary = readHarvestManifestSummary(artifact.harvestManifest);
2582
+ const normalizedWinnerOnlyAttribution = normalizeWinnerOnlyAttribution({
2583
+ synthesisApplied,
2584
+ winnerFallback,
2585
+ mergedVariants,
2586
+ contributingVariants,
2587
+ donorSelectionDecisions,
2588
+ declaredWinner: typeof artifact.declaredWinner === "object" && artifact.declaredWinner !== null ? artifact.declaredWinner : null
2589
+ });
2590
+ return {
2591
+ strategy: typeof artifact.synthesisStrategy === "string" ? artifact.synthesisStrategy : null,
2592
+ provider: typeof artifact.synthesisProvider === "string" ? artifact.synthesisProvider : null,
2593
+ model: typeof artifact.synthesisModel === "string" ? artifact.synthesisModel : null,
2594
+ reasoningEffort: typeof artifact.synthesisReasoningEffort === "string" ? artifact.synthesisReasoningEffort : null,
2595
+ providerDurationMs: typeof artifact.synthesisProviderDurationMs === "number" ? artifact.synthesisProviderDurationMs : null,
2596
+ gateDurationMs: typeof artifact.synthesisGateDurationMs === "number" ? artifact.synthesisGateDurationMs : null,
2597
+ success: resolveSynthesisDeliveryProjection(artifact).success ? true : typeof artifact.success === "boolean" ? artifact.success : null,
2598
+ resultStatus: resolveSynthesisDeliveryProjection(artifact).resultStatus,
2599
+ deliverySucceeded: typeof artifact.deliverySucceeded === "boolean" ? artifact.deliverySucceeded : null,
2600
+ synthesisApplied,
2601
+ synthesisOutcomeStatus,
2602
+ winnerFallback,
2603
+ fallbackReason: typeof artifact.fallbackReason === "string" ? artifact.fallbackReason : null,
2604
+ patchApplyValidated: typeof artifact.patchApplyValidated === "boolean" ? artifact.patchApplyValidated : null,
2605
+ gatesPassed: typeof artifact.gatesPassed === "boolean" ? artifact.gatesPassed : null,
2606
+ gateFailureDetails: typeof artifact.gateFailureDetails === "object" && artifact.gateFailureDetails !== null ? artifact.gateFailureDetails : null,
2607
+ winnerClone: typeof artifact.winnerClone === "boolean" ? artifact.winnerClone : null,
2608
+ noveltyScore: typeof artifact.noveltyScore === "number" ? artifact.noveltyScore : null,
2609
+ mergedVariants: normalizedWinnerOnlyAttribution.mergedVariants,
2610
+ contributingVariants: normalizedWinnerOnlyAttribution.contributingVariants,
2611
+ donorSelectionDecisions,
2612
+ reasoning: typeof artifact.reasoning === "string" ? artifact.reasoning : null,
2613
+ error: typeof artifact.error === "string" ? artifact.error : null,
2614
+ intentFilteredHunkCount: typeof artifact.intentFilteredHunkCount === "number" ? artifact.intentFilteredHunkCount : null,
2615
+ excludedHunkCount: typeof artifact.excludedHunkCount === "number" ? artifact.excludedHunkCount : null,
2616
+ unknownIncludedHunkCount: typeof artifact.unknownIncludedHunkCount === "number" ? artifact.unknownIncludedHunkCount : null,
2617
+ unknownExcludedHunkCount: typeof artifact.unknownExcludedHunkCount === "number" ? artifact.unknownExcludedHunkCount : null,
2618
+ overlapRejectedHunkCount: typeof artifact.overlapRejectedHunkCount === "number" ? artifact.overlapRejectedHunkCount : null,
2619
+ complementaryPatchApplied: typeof artifact.complementaryPatchApplied === "boolean" ? artifact.complementaryPatchApplied : null,
2620
+ applyMode: typeof artifact.applyMode === "string" ? artifact.applyMode : null,
2621
+ aiGuidedFallbackAttempted: typeof artifact.aiGuidedFallbackAttempted === "boolean" ? artifact.aiGuidedFallbackAttempted : null,
2622
+ aiGuidedFallbackOutcome: normalizeAiGuidedFallbackOutcome({
2623
+ synthesisApplied,
2624
+ winnerFallback,
2625
+ outcome: typeof artifact.aiGuidedFallbackOutcome === "string" ? artifact.aiGuidedFallbackOutcome : null
2626
+ }),
2627
+ synthesisGateResults,
2628
+ donorHunksAccepted: harvestSummary?.acceptedHunkCount ?? null,
2629
+ donorHunksRejected: harvestSummary?.rejectedHunkCount ?? null,
2630
+ donorHunksConsidered: harvestSummary?.consideredHunkCount ?? null
2631
+ };
2632
+ }
2633
+ function readHarvestManifestSummary(value) {
2634
+ if (!value || typeof value !== "object") return null;
2635
+ const summary = value.summary;
2636
+ if (!summary || typeof summary !== "object") return null;
2637
+ const record = summary;
2638
+ if (typeof record.acceptedHunkCount !== "number" || typeof record.rejectedHunkCount !== "number" || typeof record.consideredHunkCount !== "number") {
2639
+ return null;
2640
+ }
2641
+ return {
2642
+ acceptedHunkCount: record.acceptedHunkCount,
2643
+ rejectedHunkCount: record.rejectedHunkCount,
2644
+ consideredHunkCount: record.consideredHunkCount
2645
+ };
2646
+ }
2647
+ function readSynthesisGateResultSnapshot(artifact) {
2648
+ const raw = isRecord(artifact.synthesisGateResults) ? artifact.synthesisGateResults : isRecord(artifact.gateResults) ? artifact.gateResults : null;
2649
+ if (!raw) return null;
2650
+ return isSynthesisGateResultSnapshot(raw) ? raw : null;
2651
+ }
2652
+ function isSynthesisGateResultSnapshot(value) {
2653
+ return typeof value.isEligible === "boolean" && typeof value.buildPassed === "boolean" && typeof value.lintPassed === "boolean" && typeof value.formatPassed === "boolean" && typeof value.buildStatus === "string" && typeof value.lintStatus === "string" && typeof value.testStatus === "string" && typeof value.formatStatus === "string";
2654
+ }
2655
+ function normalizeAiGuidedFallbackOutcome(params) {
2656
+ if (params.synthesisApplied === false && params.winnerFallback === true && params.outcome === "donor_augmented") {
2657
+ return "winner_equivalent";
2658
+ }
2659
+ return params.outcome;
2660
+ }
2661
+ function normalizeWinnerOnlyAttribution(params) {
2662
+ const { synthesisApplied, winnerFallback } = params;
2663
+ if (!(synthesisApplied === false && winnerFallback === true)) {
2664
+ return {
2665
+ mergedVariants: params.mergedVariants,
2666
+ contributingVariants: params.contributingVariants
2667
+ };
2668
+ }
2669
+ const winnerFromDecisions = params.donorSelectionDecisions?.map((entry) => {
2670
+ if (typeof entry !== "object" || entry === null) return null;
2671
+ const decision = entry;
2672
+ if (decision.winner !== true || typeof decision.variant !== "string") return null;
2673
+ return normalizeDisplayedVariantId(decision.variant.trim());
2674
+ }).find((value) => Boolean(value));
2675
+ const declaredWinnerProvider = typeof params.declaredWinner?.provider === "string" ? params.declaredWinner.provider.trim() : "";
2676
+ const declaredWinnerVariant = typeof params.declaredWinner?.variant === "string" ? params.declaredWinner.variant.trim() : "";
2677
+ const winnerFromDeclaredWinner = declaredWinnerProvider && declaredWinnerVariant ? normalizeDisplayedVariantId(
2678
+ declaredWinnerVariant.startsWith(`${declaredWinnerProvider}:`) ? declaredWinnerVariant : `${declaredWinnerProvider}:${declaredWinnerVariant}`
2679
+ ) : null;
2680
+ const normalizedWinner = winnerFromDecisions ?? winnerFromDeclaredWinner ?? params.contributingVariants[0] ?? params.mergedVariants[0] ?? null;
2681
+ if (!normalizedWinner) {
2682
+ return {
2683
+ mergedVariants: params.mergedVariants,
2684
+ contributingVariants: params.contributingVariants
2685
+ };
2686
+ }
2687
+ return {
2688
+ mergedVariants: [normalizedWinner],
2689
+ contributingVariants: [normalizedWinner]
2690
+ };
2691
+ }
2692
+ function normalizeDisplayedVariantId(variantId) {
2693
+ return repairDuplicatedProviderSegment(variantId);
2694
+ }
2695
+ function formatAiGuidedFallbackOutcomeLabel(attempted, outcome) {
2696
+ if (attempted !== true) return null;
2697
+ switch (outcome) {
2698
+ case "donor_augmented":
2699
+ return "agentic fallback donor-augmented (applied)";
2700
+ case "winner_equivalent":
2701
+ return "agentic fallback winner-equivalent (not applied)";
2702
+ case "candidate_rejected":
2703
+ return "agentic fallback candidate rejected by apply/gates (not applied)";
2704
+ case "generation_failed":
2705
+ return "agentic fallback generation failed (winner retained)";
2706
+ default:
2707
+ return "agentic fallback attempted";
2708
+ }
2709
+ }
2710
+ function formatSynthesisTelemetrySummaryLines(synthesisArtifact, rawArtifact) {
2711
+ const lines = [];
2712
+ if (synthesisArtifact.strategy) {
2713
+ lines.push(` Strategy: ${synthesisArtifact.strategy}`);
2714
+ }
2715
+ if (synthesisArtifact.provider) {
2716
+ lines.push(` Provider: ${synthesisArtifact.provider}`);
2717
+ }
2718
+ if (synthesisArtifact.model) {
2719
+ lines.push(` Model: ${synthesisArtifact.model}`);
2720
+ }
2721
+ if (synthesisArtifact.reasoningEffort) {
2722
+ lines.push(` Reasoning Effort: ${synthesisArtifact.reasoningEffort}`);
2723
+ }
2724
+ if (typeof synthesisArtifact.providerDurationMs === "number") {
2725
+ lines.push(` Provider Duration: ${formatDurationMs(synthesisArtifact.providerDurationMs)}`);
2726
+ }
2727
+ if (typeof synthesisArtifact.gateDurationMs === "number") {
2728
+ lines.push(` Gate Duration: ${formatDurationMs(synthesisArtifact.gateDurationMs)}`);
2729
+ }
2730
+ const delivery = resolveSynthesisDeliveryProjection(synthesisArtifact);
2731
+ if (delivery.success) {
2732
+ lines.push(" Success: yes");
2733
+ } else if (typeof synthesisArtifact.success === "boolean") {
2734
+ lines.push(` Success: ${synthesisArtifact.success ? "yes" : "no"}`);
2735
+ }
2736
+ if (delivery.resultStatus) {
2737
+ lines.push(` Result Status: ${delivery.resultStatus}`);
2738
+ }
2739
+ if (typeof synthesisArtifact.deliverySucceeded === "boolean") {
2740
+ lines.push(` Delivery Succeeded: ${synthesisArtifact.deliverySucceeded ? "yes" : "no"}`);
2741
+ }
2742
+ if (typeof synthesisArtifact.synthesisApplied === "boolean") {
2743
+ lines.push(` Synthesis Applied: ${synthesisArtifact.synthesisApplied ? "yes" : "no"}`);
2744
+ }
2745
+ if (synthesisArtifact.synthesisOutcomeStatus) {
2746
+ lines.push(` Synthesis Outcome: ${synthesisArtifact.synthesisOutcomeStatus}`);
2747
+ }
2748
+ if (typeof synthesisArtifact.winnerFallback === "boolean") {
2749
+ lines.push(` Winner Fallback: ${synthesisArtifact.winnerFallback ? "yes" : "no"}`);
2750
+ }
2751
+ if (typeof synthesisArtifact.patchApplyValidated === "boolean") {
2752
+ lines.push(` Patch Apply Validated: ${synthesisArtifact.patchApplyValidated ? "yes" : "no"}`);
2753
+ }
2754
+ if (typeof synthesisArtifact.gatesPassed === "boolean") {
2755
+ lines.push(` Gates Passed: ${synthesisArtifact.gatesPassed ? "yes" : "no"}`);
2756
+ }
2757
+ for (const line of formatSynthesisGateResultsSummaryLines(synthesisArtifact)) {
2758
+ lines.push(line);
2759
+ }
2760
+ const gateFailureSummary = formatGateFailureDetailsSummary(synthesisArtifact.gateFailureDetails);
2761
+ if (gateFailureSummary) {
2762
+ lines.push(` Gate Failure: ${gateFailureSummary}`);
2763
+ }
2764
+ if (synthesisArtifact.fallbackReason) {
2765
+ lines.push(` Fallback Reason: ${synthesisArtifact.fallbackReason}`);
2766
+ }
2767
+ if (typeof synthesisArtifact.winnerClone === "boolean") {
2768
+ lines.push(` Winner Clone: ${synthesisArtifact.winnerClone ? "yes" : "no"}`);
2769
+ }
2770
+ const aiFallbackLine = formatAiGuidedFallbackOutcomeLabel(
2771
+ synthesisArtifact.aiGuidedFallbackAttempted,
2772
+ synthesisArtifact.aiGuidedFallbackOutcome
2773
+ );
2774
+ if (aiFallbackLine) {
2775
+ lines.push(` AI Fallback: ${aiFallbackLine}`);
2776
+ }
2777
+ const donorMaterialLine = formatDonorMaterialSummaryLine(synthesisArtifact);
2778
+ if (donorMaterialLine) {
2779
+ lines.push(` Donor Material: ${donorMaterialLine}`);
2780
+ }
2781
+ const synthesisValue = deriveSynthesisValueFromArtifactOrSummary(rawArtifact, synthesisArtifact);
2782
+ if (synthesisValue) {
2783
+ lines.push(` Synthesis Value: ${formatSynthesisValueRunSummaryLine(synthesisValue)}`);
2784
+ }
2785
+ if (synthesisArtifact.applyMode) {
2786
+ lines.push(` Apply Mode: ${synthesisArtifact.applyMode}`);
2787
+ }
2788
+ const donorDiagnosticLines = formatDonorDecisionDiagnostics(
2789
+ synthesisArtifact.donorSelectionDecisions
2790
+ );
2791
+ if (donorDiagnosticLines.length > 0) {
2792
+ lines.push(" Donor Selection:");
2793
+ for (const line of donorDiagnosticLines) {
2794
+ lines.push(` ${line}`);
2795
+ }
2796
+ }
2797
+ return lines;
2798
+ }
2799
+ function formatCoverageLabel(status) {
2800
+ switch (status) {
2801
+ case "verified":
2802
+ return "verified";
2803
+ case "partially_verified":
2804
+ return "partial";
2805
+ case "skipped_no_command":
2806
+ return "not configured";
2807
+ case "skipped_tool_unavailable":
2808
+ return "unavailable";
2809
+ case "skipped_not_relevant":
2810
+ return "not relevant";
2811
+ case "unverified":
2812
+ return "unverified";
2813
+ default:
2814
+ return "unknown";
2815
+ }
2816
+ }
2817
+ function formatGateSummaryPart(input) {
2818
+ const reason = input.reason?.trim().replace(/\s+/g, " ");
2819
+ const suffix = reason ? `, ${reason}` : "";
2820
+ return `${input.label}=${input.status ?? "not_run"} (${formatCoverageLabel(
2821
+ input.coverageStatus
2822
+ )}${suffix})`;
2823
+ }
2824
+ function formatSynthesisGateResultsSummaryLines(synthesisArtifact) {
2825
+ if (synthesisArtifact.winnerFallback === true || synthesisArtifact.synthesisOutcomeStatus === "winner_carry_forward") {
2826
+ return [" Gate Source: carried-forward winner gates"];
2827
+ }
2828
+ const snapshot = synthesisArtifact.synthesisGateResults;
2829
+ if (!snapshot) {
2830
+ const status = synthesisArtifact.synthesisOutcomeStatus ?? "not_attempted";
2831
+ return [` Gate Results: not run (${status})`];
2832
+ }
2833
+ return [
2834
+ " Gate Source: synthesis worktree",
2835
+ ` Gate Results: ${[
2836
+ formatGateSummaryPart({
2837
+ label: "build/typecheck",
2838
+ status: snapshot.buildStatus,
2839
+ coverageStatus: snapshot.buildCoverage?.status,
2840
+ reason: snapshot.buildCoverage?.reason
2841
+ }),
2842
+ formatGateSummaryPart({
2843
+ label: "lint",
2844
+ status: snapshot.lintStatus,
2845
+ coverageStatus: snapshot.lintCoverage?.status,
2846
+ reason: snapshot.lintCoverage?.reason
2847
+ }),
2848
+ formatGateSummaryPart({
2849
+ label: "test",
2850
+ status: snapshot.testStatus,
2851
+ coverageStatus: snapshot.testCoverage?.status,
2852
+ reason: snapshot.testCoverage?.reason
2853
+ }),
2854
+ formatGateSummaryPart({
2855
+ label: "format",
2856
+ status: snapshot.formatPassed ? "passed" : snapshot.formatStatus === "verified" ? "failed" : "not_run",
2857
+ coverageStatus: snapshot.formatCoverage?.status ?? snapshot.formatStatus,
2858
+ reason: snapshot.formatCoverage?.reason
2859
+ })
2860
+ ].join("; ")}`
2861
+ ];
2862
+ }
2863
+ function formatDurationMs(durationMs) {
2864
+ if (!Number.isFinite(durationMs) || durationMs < 0) return "unknown";
2865
+ if (durationMs < 1e3) return `${Math.round(durationMs)}ms`;
2866
+ if (durationMs < 6e4) return `${(durationMs / 1e3).toFixed(1)}s`;
2867
+ return `${(durationMs / 6e4).toFixed(1)}m`;
2868
+ }
2869
+ function formatDonorMaterialSummaryLine(artifact) {
2870
+ const matched = artifact.intentFilteredHunkCount;
2871
+ const excluded = artifact.excludedHunkCount;
2872
+ const unknown = artifact.unknownIncludedHunkCount;
2873
+ const unknownExcluded = artifact.unknownExcludedHunkCount;
2874
+ const overlapRejected = artifact.overlapRejectedHunkCount;
2875
+ const applied = artifact.complementaryPatchApplied;
2876
+ const synthesisApplied = artifact.synthesisApplied;
2877
+ const hasFallbackSignal = artifact.winnerFallback === true || typeof artifact.fallbackReason === "string" || typeof artifact.applyMode === "string" || synthesisApplied === false;
2878
+ const hasAnyCount = typeof matched === "number" || typeof excluded === "number" || typeof unknown === "number" || typeof unknownExcluded === "number" || typeof overlapRejected === "number";
2879
+ if (!hasAnyCount) {
2880
+ const thresholdMissCount = countSemanticThresholdMissDonors(
2881
+ artifact.donorSelectionDecisions ?? null
2882
+ );
2883
+ if (thresholdMissCount > 0) {
2884
+ return `semantic threshold miss (${thresholdMissCount} donor${thresholdMissCount === 1 ? "" : "s"} below threshold)`;
2885
+ }
2886
+ const aiFallbackLabel = formatAiGuidedFallbackOutcomeLabel(
2887
+ artifact.aiGuidedFallbackAttempted ?? null,
2888
+ artifact.aiGuidedFallbackOutcome ?? null
2889
+ );
2890
+ if (aiFallbackLabel) return aiFallbackLabel;
2891
+ return null;
2892
+ }
2893
+ const matchedCount = matched ?? 0;
2894
+ const excludedCount = excluded ?? 0;
2895
+ if (matchedCount === 0 && excludedCount === 0) {
2896
+ return "none (no donor material found)";
2897
+ }
2898
+ if (matchedCount === 0 && excludedCount > 0) {
2899
+ return `rejected by intent filtering (${excludedCount} hunk${excludedCount === 1 ? "" : "s"} excluded)`;
2900
+ }
2901
+ const parts = [`${matchedCount} matched hunk${matchedCount === 1 ? "" : "s"}`];
2902
+ if (excludedCount > 0) {
2903
+ parts.push(`${excludedCount} excluded`);
2904
+ }
2905
+ if (typeof overlapRejected === "number" && overlapRejected > 0) {
2906
+ parts.push(`${overlapRejected} overlap-rejected`);
2907
+ }
2908
+ if (typeof unknown === "number" && unknown > 0) {
2909
+ parts.push(`${unknown} unknown-included`);
2910
+ }
2911
+ if (typeof unknownExcluded === "number" && unknownExcluded > 0) {
2912
+ parts.push(`${unknownExcluded} unknown-excluded`);
2913
+ }
2914
+ const statusSuffix = typeof applied === "boolean" ? applied ? ", applied" : ", not applied" : synthesisApplied === true ? ", applied" : hasFallbackSignal ? ", attempted" : "";
2915
+ return `${parts.join(", ")}${statusSuffix}`;
2916
+ }
2917
+ function countSemanticThresholdMissDonors(decisions) {
2918
+ if (!Array.isArray(decisions)) return 0;
2919
+ return decisions.filter((entry) => {
2920
+ if (typeof entry !== "object" || entry === null) return false;
2921
+ const decision = entry;
2922
+ if (decision.winner || decision.selected) return false;
2923
+ const reasons = Array.isArray(decision.reasons) ? decision.reasons.filter((reason) => typeof reason === "string") : [];
2924
+ return reasons.some((reason) => isSemanticThresholdMissReason(reason));
2925
+ }).length;
2926
+ }
2927
+ function isSemanticThresholdMissReason(reason) {
2928
+ const normalized = reason.toLowerCase();
2929
+ return normalized.includes("semantic donor rejected") && normalized.includes("threshold");
2930
+ }
2931
+ function formatGateFailureDetailsSummary(details) {
2932
+ if (!details || typeof details !== "object" || Array.isArray(details)) return null;
2933
+ const record = details;
2934
+ const gate = typeof record.gate === "string" ? record.gate : "unknown gate";
2935
+ const status = typeof record.status === "string" ? record.status : "failed";
2936
+ const reason = typeof record.reason === "string" ? record.reason : null;
2937
+ const deliveryPreserved = typeof record.deliveryPreserved === "boolean" ? record.deliveryPreserved ? "winner preserved" : "winner not preserved" : null;
2938
+ return [gate, status, deliveryPreserved, reason].filter(Boolean).join("; ");
2939
+ }
2940
+ function renderSynthesisTelemetryHuman(synthesisArtifact, rawArtifact) {
2941
+ console.log(chalk6.blue.bold("Synthesis Telemetry:\n"));
2942
+ for (const line of formatSynthesisTelemetrySummaryLines(synthesisArtifact, rawArtifact)) {
2943
+ console.log(chalk6.gray(line));
2944
+ }
2945
+ if (typeof synthesisArtifact.noveltyScore === "number") {
2946
+ console.log(chalk6.gray(` Novelty Score: ${synthesisArtifact.noveltyScore}`));
2947
+ }
2948
+ if (synthesisArtifact.mergedVariants.length > 0) {
2949
+ console.log(chalk6.gray(` Merged Variants: ${synthesisArtifact.mergedVariants.join(", ")}`));
2950
+ }
2951
+ if (synthesisArtifact.contributingVariants.length > 0) {
2952
+ console.log(
2953
+ chalk6.gray(` Contributing Variants: ${synthesisArtifact.contributingVariants.join(", ")}`)
2954
+ );
2955
+ }
2956
+ if (synthesisArtifact.reasoning) {
2957
+ console.log(chalk6.gray(` Reasoning: ${synthesisArtifact.reasoning}`));
2958
+ }
2959
+ const donorDecisionLines = summarizeDonorSelectionDecisions(
2960
+ synthesisArtifact.donorSelectionDecisions
2961
+ );
2962
+ if (donorDecisionLines.length > 0) {
2963
+ console.log(chalk6.gray(" Donor Decisions:"));
2964
+ for (const line of donorDecisionLines) {
2965
+ console.log(chalk6.gray(` - ${line}`));
2966
+ }
2967
+ }
2968
+ if (synthesisArtifact.error) {
2969
+ console.log(chalk6.red(` Error: ${synthesisArtifact.error}`));
2970
+ }
2971
+ console.log();
2972
+ }
2973
+ function buildSynthesisResultsJson(params) {
2974
+ const generated = params.synthesisGenerated === true;
2975
+ const aliases = {
2976
+ attempted: Boolean(params.artifact) || Boolean(params.artifactParseWarning) || generated,
2977
+ applied: params.artifact?.synthesisApplied ?? null,
2978
+ artifactParseWarning: params.artifactParseWarning ?? null,
2979
+ error: params.artifact?.error ?? null,
2980
+ fallbackReason: params.artifact?.fallbackReason ?? null,
2981
+ winnerFallback: params.artifact?.winnerFallback ?? null,
2982
+ deliverySucceeded: params.artifact?.deliverySucceeded ?? null,
2983
+ patchApplyValidated: params.artifact?.patchApplyValidated ?? null,
2984
+ gatesPassed: params.artifact?.gatesPassed ?? null,
2985
+ gateFailureDetails: params.artifact?.gateFailureDetails ?? null,
2986
+ synthesisValue: deriveSynthesisValueFromArtifactOrSummary(params.rawArtifact, params.artifact)
2987
+ };
2988
+ return generated ? {
2989
+ generated: true,
2990
+ code: params.synthesisCode ?? null,
2991
+ artifact: params.artifact,
2992
+ ...aliases
2993
+ } : {
2994
+ generated: false,
2995
+ code: null,
2996
+ artifact: params.artifact,
2997
+ ...aliases
2998
+ };
2999
+ }
3000
+ function buildFusionSynthesisResultsJson(params) {
3001
+ const analysisArtifact = params.analysisSynthesis ? {
3002
+ kind: "analysis-synthesis",
3003
+ status: params.analysisSynthesis.status ?? null,
3004
+ markdownPath: params.analysisSynthesis.artifactPath ?? null,
3005
+ jsonPath: params.analysisSynthesis.jsonPath ?? null,
3006
+ contributorCount: params.analysisSynthesis.contributorCount ?? null
3007
+ } : null;
3008
+ const generated = params.synthesisGenerated === true || params.analysisSynthesis?.status === "succeeded";
3009
+ const artifact = params.artifact ?? analysisArtifact;
3010
+ return {
3011
+ generated,
3012
+ attempted: params.analysisSynthesis?.expected === true || Boolean(artifact) || Boolean(params.artifactParseWarning) || generated,
3013
+ code: generated ? params.synthesisCode ?? null : null,
3014
+ artifact,
3015
+ artifactParseWarning: params.artifactParseWarning ?? null,
3016
+ error: params.artifact?.error ?? (params.analysisSynthesis?.status === "failed" ? "Fusion synthesis failed" : null),
3017
+ deliverySucceeded: params.artifact?.deliverySucceeded ?? (params.analysisSynthesis?.status === "succeeded" ? true : null)
3018
+ };
3019
+ }
3020
+ function readSynthesisArtifact(taskId, telemetryDir) {
3021
+ const artifactPath = path2.join(telemetryDir, "synthesis", `${taskId}.json`);
3022
+ if (!fs.existsSync(artifactPath)) {
3023
+ return { artifact: null, parseWarning: null };
3024
+ }
3025
+ try {
3026
+ return {
3027
+ artifact: parseJsonWithContext(
3028
+ fs.readFileSync(artifactPath, "utf-8"),
3029
+ `Synthesis artifact (${taskId})`
3030
+ ),
3031
+ parseWarning: null
3032
+ };
3033
+ } catch (error) {
3034
+ const message = error instanceof Error ? error.message : String(error);
3035
+ return {
3036
+ artifact: null,
3037
+ parseWarning: `${artifactPath}: ${message}`
3038
+ };
3039
+ }
3040
+ }
3041
+ function readFusionAnalysisSynthesisArtifact(taskId, buildDir) {
3042
+ const readFromArtifactDir = (artifactDir) => {
3043
+ const manifestPath = path2.join(artifactDir, `${taskId}.manifest.json`);
3044
+ const legacyJsonPath = path2.join(artifactDir, `${taskId}.json`);
3045
+ const jsonPath = fs.existsSync(manifestPath) ? manifestPath : legacyJsonPath;
3046
+ const markdownPath = path2.join(artifactDir, `${taskId}.md`);
3047
+ const hasJson = fs.existsSync(jsonPath);
3048
+ const hasMarkdown = fs.existsSync(markdownPath);
3049
+ if (!hasJson && !hasMarkdown) {
3050
+ return null;
3051
+ }
3052
+ if (!hasJson) {
3053
+ return {
3054
+ jsonPath: null,
3055
+ markdownPath: hasMarkdown ? markdownPath : null,
3056
+ artifact: null,
3057
+ parseWarning: null
3058
+ };
3059
+ }
3060
+ try {
3061
+ return {
3062
+ jsonPath,
3063
+ markdownPath: hasMarkdown ? markdownPath : null,
3064
+ artifact: parseJsonWithContext(
3065
+ fs.readFileSync(jsonPath, "utf-8"),
3066
+ `Fusion analysis synthesis artifact (${taskId})`
3067
+ ),
3068
+ parseWarning: null
3069
+ };
3070
+ } catch (error) {
3071
+ const message = error instanceof Error ? error.message : String(error);
3072
+ return {
3073
+ jsonPath,
3074
+ markdownPath: hasMarkdown ? markdownPath : null,
3075
+ artifact: null,
3076
+ parseWarning: `${jsonPath}: ${message}`
3077
+ };
3078
+ }
3079
+ };
3080
+ const rootArtifact = readFromArtifactDir(path2.join(buildDir, "analysis-synthesis"));
3081
+ if (rootArtifact) {
3082
+ return rootArtifact;
3083
+ }
3084
+ const labsDir = resolveLabsRoot(buildDir);
3085
+ if (!fs.existsSync(labsDir)) {
3086
+ return null;
3087
+ }
3088
+ for (const labId of fs.readdirSync(labsDir).sort()) {
3089
+ const runsDir = path2.join(labsDir, labId, "runs");
3090
+ if (!fs.existsSync(runsDir)) {
3091
+ continue;
3092
+ }
3093
+ for (const runId of fs.readdirSync(runsDir).sort()) {
3094
+ const artifact = readFromArtifactDir(path2.join(runsDir, runId, "analysis-synthesis"));
3095
+ if (artifact) {
3096
+ return artifact;
3097
+ }
3098
+ }
3099
+ }
3100
+ return null;
3101
+ }
3102
+ function getRecord(value) {
3103
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
3104
+ }
3105
+ function getArray(value) {
3106
+ return Array.isArray(value) ? value : [];
3107
+ }
3108
+ function extractIntegratedContributorIdsFromTrust(artifact) {
3109
+ if (artifact.kind === "fusion-synthesis-manifest" && Array.isArray(artifact.contributors)) {
3110
+ return artifact.contributors.flatMap((entry) => {
3111
+ const contributor = getRecord(entry);
3112
+ const variantId = contributor?.variantId;
3113
+ return contributor?.status === "included" && typeof variantId === "string" ? [normalizeDisplayedVariantId(variantId)] : [];
3114
+ });
3115
+ }
3116
+ const trust = getRecord(artifact.trust);
3117
+ const trustContributors = getRecord(trust?.contributors);
3118
+ if (trustContributors) {
3119
+ const statuses = trustContributors.statuses;
3120
+ if (statuses && typeof statuses === "object" && !Array.isArray(statuses)) {
3121
+ const ordered = [];
3122
+ const seen = /* @__PURE__ */ new Set();
3123
+ for (const [rawId, status] of Object.entries(statuses)) {
3124
+ if (status !== "included") continue;
3125
+ if (typeof rawId !== "string" || rawId.trim().length === 0) continue;
3126
+ const id = normalizeDisplayedVariantId(rawId);
3127
+ if (!id || seen.has(id)) continue;
3128
+ seen.add(id);
3129
+ ordered.push(id);
3130
+ }
3131
+ return ordered;
3132
+ }
3133
+ return [];
3134
+ }
3135
+ const inputs = getRecord(artifact.inputs);
3136
+ const contributorHealth = inputs?.contributorHealth;
3137
+ if (Array.isArray(contributorHealth)) {
3138
+ const ordered = [];
3139
+ const seen = /* @__PURE__ */ new Set();
3140
+ for (const entry of contributorHealth) {
3141
+ const record = getRecord(entry);
3142
+ if (!record || record.status !== "included") continue;
3143
+ const rawId = record.variantId;
3144
+ if (typeof rawId !== "string" || rawId.trim().length === 0) continue;
3145
+ const id = normalizeDisplayedVariantId(rawId);
3146
+ if (!id || seen.has(id)) continue;
3147
+ seen.add(id);
3148
+ ordered.push(id);
3149
+ }
3150
+ return ordered;
3151
+ }
3152
+ return null;
3153
+ }
3154
+ function extractFusionContributorIdsFromAttributions(artifact) {
3155
+ const contributors = /* @__PURE__ */ new Set();
3156
+ const crossVariant = getRecord(artifact.crossVariant);
3157
+ const sections = [
3158
+ ...getArray(crossVariant?.consensus),
3159
+ ...getArray(crossVariant?.contradictions),
3160
+ ...getArray(crossVariant?.partialCoverage),
3161
+ ...getArray(crossVariant?.uniqueInsights),
3162
+ ...getArray(crossVariant?.blindSpots)
3163
+ ];
3164
+ for (const section of sections) {
3165
+ const sectionRecord = getRecord(section);
3166
+ for (const attribution of getArray(sectionRecord?.attributions)) {
3167
+ const attributionRecord = getRecord(attribution);
3168
+ const variantId = attributionRecord?.variantId;
3169
+ if (typeof variantId === "string" && variantId.trim().length > 0) {
3170
+ contributors.add(normalizeDisplayedVariantId(variantId));
3171
+ }
3172
+ }
3173
+ }
3174
+ return [...contributors];
3175
+ }
3176
+ function extractFusionContributorIds(artifact) {
3177
+ if (!artifact) return [];
3178
+ const fromTrust = extractIntegratedContributorIdsFromTrust(artifact);
3179
+ if (fromTrust !== null) {
3180
+ return fromTrust;
3181
+ }
3182
+ return extractFusionContributorIdsFromAttributions(artifact);
3183
+ }
3184
+ function buildFusionAnalysisSynthesisJson(params) {
3185
+ const artifact = params.read.artifact;
3186
+ const isV2Manifest = artifact?.kind === "fusion-synthesis-manifest";
3187
+ const crossVariant = getRecord(artifact?.crossVariant);
3188
+ const persistedAnswer = isV2Manifest && params.read.markdownPath && fs.existsSync(params.read.markdownPath) ? fs.readFileSync(params.read.markdownPath, "utf8").replace(/\n$/, "") : null;
3189
+ const finalRecommendation = isV2Manifest ? persistedAnswer ? {
3190
+ summary: persistedAnswer.split(/\r?\n/).map((line) => line.replace(/^#+\s*/, "").trim()).find((line) => line.length > 0) ?? "Fusion synthesis completed.",
3191
+ recommendation: persistedAnswer,
3192
+ rationale: [],
3193
+ risks: [],
3194
+ nextSteps: []
3195
+ } : null : getRecord(artifact?.finalRecommendation);
3196
+ const status = typeof artifact?.status === "string" ? artifact.status : null;
3197
+ const contributors = extractFusionContributorIds(artifact);
3198
+ const markdownPath = params.read.markdownPath ? formatAnalysisSynthesisArtifactPath(params.read.markdownPath) : null;
3199
+ const jsonPath = params.read.jsonPath ? formatAnalysisSynthesisArtifactPath(params.read.jsonPath) : null;
3200
+ const artifactParseWarning = params.read.parseWarning && params.read.jsonPath ? params.read.parseWarning.replace(params.read.jsonPath, jsonPath ?? params.read.jsonPath) : params.read.parseWarning;
3201
+ return {
3202
+ taskId: params.taskId,
3203
+ requestedTaskId: params.requestedTaskId,
3204
+ resolvedTaskId: params.taskId,
3205
+ runSemantics: "fusion",
3206
+ result: status === "succeeded" ? "success" : status,
3207
+ executionHealth: status === "succeeded" ? "clean" : status === "failed" ? "failed" : "degraded",
3208
+ synthesis: {
3209
+ status,
3210
+ markdownPath,
3211
+ jsonPath,
3212
+ artifactParseWarning,
3213
+ consensusCount: getArray(crossVariant?.consensus).length,
3214
+ contradictionCount: getArray(crossVariant?.contradictions).length,
3215
+ partialCoverageCount: getArray(crossVariant?.partialCoverage).length,
3216
+ uniqueInsightCount: getArray(crossVariant?.uniqueInsights).length,
3217
+ blindSpotCount: getArray(crossVariant?.blindSpots).length,
3218
+ contributorCount: contributors.length,
3219
+ contributors,
3220
+ finalRecommendation: finalRecommendation && Object.keys(finalRecommendation).length > 0 ? finalRecommendation : null
3221
+ },
3222
+ ...isV2Manifest ? {
3223
+ analysisSynthesis: artifact,
3224
+ fusionAnswer: persistedAnswer
3225
+ } : artifact ? { analysisSynthesis: artifact } : {}
3226
+ };
3227
+ }
3228
+ function buildFusionArtifactJsonFields(read) {
3229
+ if (!read?.artifact) return {};
3230
+ if (!isFusionManifestV2(read.artifact)) {
3231
+ return { analysisSynthesis: read.artifact };
3232
+ }
3233
+ const fusionAnswer = read.markdownPath && fs.existsSync(read.markdownPath) ? fs.readFileSync(read.markdownPath, "utf8").replace(/\n$/, "") : null;
3234
+ return {
3235
+ // Retain the established manifest field and expose the primary answer separately.
3236
+ analysisSynthesis: read.artifact,
3237
+ fusionAnswer
3238
+ };
3239
+ }
3240
+ function isAnalysisSynthesisResultShape(value) {
3241
+ if (!isRecord(value)) return false;
3242
+ if (typeof value.status !== "string") return false;
3243
+ if (!isRecord(value.finalRecommendation)) return false;
3244
+ if (typeof value.finalRecommendation.recommendation !== "string") return false;
3245
+ if (typeof value.finalRecommendation.summary !== "string") return false;
3246
+ if (!Array.isArray(value.finalRecommendation.rationale)) return false;
3247
+ if (!Array.isArray(value.finalRecommendation.risks)) return false;
3248
+ if (!Array.isArray(value.finalRecommendation.nextSteps)) return false;
3249
+ if (!isRecord(value.crossVariant)) return false;
3250
+ for (const key of [
3251
+ "consensus",
3252
+ "contradictions",
3253
+ "partialCoverage",
3254
+ "uniqueInsights",
3255
+ "blindSpots"
3256
+ ]) {
3257
+ if (!Array.isArray(value.crossVariant[key])) return false;
3258
+ }
3259
+ if (!isRecord(value.inputs)) return false;
3260
+ if (!Array.isArray(value.inputs.variants)) return false;
3261
+ if (typeof value.inputs.selectedTopN !== "number") return false;
3262
+ if (!isRecord(value.provenance)) return false;
3263
+ return true;
3264
+ }
3265
+ function printFusionMarkdown(markdown) {
3266
+ console.log(markdown.endsWith("\n") ? markdown.slice(0, -1) : markdown);
3267
+ }
3268
+ function isFusionManifestV2(value) {
3269
+ return isRecord(value) && value.kind === "fusion-synthesis-manifest" && value.schemaVersion === 2 && typeof value.status === "string";
3270
+ }
3271
+ function formatFusionInputTruncationNotice(inputTruncation) {
3272
+ if (!inputTruncation) return void 0;
3273
+ const contributorDetails = getArray(inputTruncation.contributors).map((value) => getRecord(value)).filter((value) => value !== void 0).flatMap((value) => {
3274
+ const variantId = typeof value.variantId === "string" ? value.variantId : void 0;
3275
+ const originalChars = typeof value.originalChars === "number" ? value.originalChars : void 0;
3276
+ const consumedChars = typeof value.consumedChars === "number" ? value.consumedChars : void 0;
3277
+ return variantId && originalChars !== void 0 && consumedChars !== void 0 ? [`${variantId} ${originalChars}->${consumedChars} chars`] : [];
3278
+ });
3279
+ if (contributorDetails.length > 0) {
3280
+ return `Host input truncation: ${contributorDetails.join("; ")}`;
3281
+ }
3282
+ const contributors = getArray(inputTruncation.affectedContributors).filter(
3283
+ (value) => typeof value === "string"
3284
+ );
3285
+ if (contributors.length === 0) return void 0;
3286
+ const limit = typeof inputTruncation.perContributorChars === "number" ? ` at ${inputTruncation.perContributorChars} chars each` : "";
3287
+ return `Truncated contributor inputs${limit}: ${contributors.join(", ")}`;
3288
+ }
3289
+ function renderFusionManifestDetails(artifact) {
3290
+ if (!isFusionManifestV2(artifact)) return false;
3291
+ const provenance = getRecord(artifact.provenance);
3292
+ const completion = getRecord(artifact.completion);
3293
+ const answer = getRecord(artifact.answer);
3294
+ const persistence = getRecord(artifact.persistence);
3295
+ const reconciliation = getRecord(artifact.reconciliation);
3296
+ const degradedReasons = getArray(artifact.degradedReasons).filter(
3297
+ (reason) => typeof reason === "string"
3298
+ );
3299
+ const inputTruncation = getRecord(artifact.inputTruncation);
3300
+ console.log(chalk6.blue(" Manifest: v2 (host-owned)"));
3301
+ if (typeof provenance?.provider === "string") {
3302
+ const model = typeof provenance.model === "string" ? ` / ${provenance.model}` : "";
3303
+ console.log(chalk6.blue(` Synthesizer: ${provenance.provider}${model}`));
3304
+ }
3305
+ if (completion) {
3306
+ console.log(
3307
+ chalk6.blue(
3308
+ ` Completion: provider=${completion.providerCompleted === true ? "yes" : "no"}, terminal-output=${completion.terminalOutputPresent === true ? "yes" : "no"}, marker=${completion.completionMarkerObserved === true ? "yes" : "no"}, response-bound-exceeded=${completion.responseBoundExceeded === true ? "yes" : "no"}`
3309
+ )
3310
+ );
3311
+ }
3312
+ if (answer) {
3313
+ const redaction = answer.secretRedactionApplied === true ? "applied" : "not applied";
3314
+ const hash = typeof answer.sha256 === "string" ? `, sha256=${answer.sha256}` : "";
3315
+ console.log(chalk6.blue(` Answer integrity: secret redaction ${redaction}${hash}`));
3316
+ }
3317
+ if (typeof persistence?.status === "string") {
3318
+ console.log(chalk6.blue(` Persistence: ${persistence.status}`));
3319
+ }
3320
+ if (degradedReasons.length > 0) {
3321
+ console.log(chalk6.yellow(` Degraded reasons: ${degradedReasons.join(", ")}`));
3322
+ }
3323
+ const inputTruncationNotice = formatFusionInputTruncationNotice(inputTruncation);
3324
+ if (inputTruncationNotice) {
3325
+ console.log(chalk6.yellow(` ${inputTruncationNotice}`));
3326
+ }
3327
+ if (typeof reconciliation?.jsonPath === "string") {
3328
+ console.log(chalk6.blue(` Reconciliation: ${reconciliation.jsonPath}`));
3329
+ }
3330
+ return true;
3331
+ }
3332
+ function tryRenderFusionReadHuman(read, options = {}) {
3333
+ if (!read) return false;
3334
+ if (!isFusionManifestV2(read.artifact)) {
3335
+ return tryRenderFusionArtifactHuman(read.artifact, options);
3336
+ }
3337
+ if (options.inspect === true) return false;
3338
+ if (read.artifact.status !== "succeeded" && read.artifact.status !== "degraded") return false;
3339
+ if (!read.markdownPath || !fs.existsSync(read.markdownPath)) return false;
3340
+ if (read.artifact.status === "degraded") {
3341
+ const reasons = getArray(read.artifact.degradedReasons).filter(
3342
+ (reason) => typeof reason === "string"
3343
+ );
3344
+ console.log(
3345
+ `Warning: Fusion answer is degraded${reasons.length > 0 ? ` (${reasons.join(", ")})` : ""}.`
3346
+ );
3347
+ }
3348
+ const inputTruncationNotice = formatFusionInputTruncationNotice(
3349
+ getRecord(read.artifact.inputTruncation)
3350
+ );
3351
+ if (inputTruncationNotice) {
3352
+ console.log(`Warning: ${inputTruncationNotice}.`);
3353
+ }
3354
+ printFusionMarkdown(fs.readFileSync(read.markdownPath, "utf8"));
3355
+ return true;
3356
+ }
3357
+ function tryRenderFusionArtifactHuman(artifact, options = {}) {
3358
+ if (!artifact) return false;
3359
+ const inspect = options.inspect === true;
3360
+ try {
3361
+ if (isAnalysisSynthesisResultShape(artifact)) {
3362
+ printFusionMarkdown(
3363
+ renderAnalysisSynthesisMarkdown(artifact, {
3364
+ runSemantics: "fusion",
3365
+ inspect
3366
+ })
3367
+ );
3368
+ return true;
3369
+ }
3370
+ if (!inspect && hasUsableFusionRecommendation(artifact)) {
3371
+ const finalRecommendation = getRecord(artifact.finalRecommendation);
3372
+ const recommendation = finalRecommendation?.recommendation;
3373
+ if (typeof recommendation === "string" && recommendation.trim().length > 0) {
3374
+ printFusionMarkdown(renderFusionDeliverableMarkdown(recommendation));
3375
+ return true;
3376
+ }
3377
+ }
3378
+ } catch {
3379
+ return false;
3380
+ }
3381
+ return false;
3382
+ }
3383
+ function renderFusionAnalysisSynthesisInspectHuman(params) {
3384
+ const artifact = params.read.artifact;
3385
+ if (tryRenderFusionArtifactHuman(artifact, { inspect: true })) {
3386
+ if (params.read.parseWarning) {
3387
+ console.log(chalk6.yellow(`Warning: ${params.read.parseWarning}`));
3388
+ }
3389
+ return;
3390
+ }
3391
+ const json = buildFusionAnalysisSynthesisJson(params);
3392
+ const synthesis = json.synthesis;
3393
+ console.log(chalk6.blue.bold("\nFusion Results:\n"));
3394
+ console.log(chalk6.gray(` Task ID: ${params.taskId}`));
3395
+ if (params.requestedTaskId !== params.taskId) {
3396
+ console.log(chalk6.gray(` Requested ID: ${params.requestedTaskId}`));
3397
+ }
3398
+ if (synthesis.status) {
3399
+ console.log(chalk6.gray(` Status: ${synthesis.status}`));
3400
+ }
3401
+ if (synthesis.markdownPath) {
3402
+ console.log(chalk6.gray(` Synthesis: ${synthesis.markdownPath}`));
3403
+ }
3404
+ if (synthesis.jsonPath) {
3405
+ console.log(chalk6.gray(` Synthesis JSON: ${synthesis.jsonPath}`));
3406
+ }
3407
+ console.log(chalk6.gray(` Contributors: ${synthesis.contributorCount}`));
3408
+ if (synthesis.contributors.length > 0) {
3409
+ console.log(chalk6.gray(` ${synthesis.contributors.join(", ")}`));
3410
+ }
3411
+ const renderedManifest = artifact ? renderFusionManifestDetails(artifact) : false;
3412
+ if (!renderedManifest) {
3413
+ console.log(chalk6.gray(` Consensus Items: ${synthesis.consensusCount}`));
3414
+ console.log(chalk6.gray(` Contradictions: ${synthesis.contradictionCount}`));
3415
+ }
3416
+ const recommendation = synthesis.finalRecommendation;
3417
+ const summary = recommendation?.summary;
3418
+ const action = recommendation?.recommendation;
3419
+ if (typeof summary === "string" && summary.trim().length > 0) {
3420
+ console.log(chalk6.gray(` Summary: ${summary.trim()}`));
3421
+ }
3422
+ if (typeof action === "string" && action.trim().length > 0) {
3423
+ console.log(chalk6.gray(` Recommendation: ${action.trim()}`));
3424
+ }
3425
+ if (synthesis.artifactParseWarning) {
3426
+ console.log(chalk6.yellow(` Warning: ${synthesis.artifactParseWarning}`));
3427
+ }
3428
+ if (isFusionManifestV2(artifact)) {
3429
+ const reconciliation = getRecord(artifact.reconciliation);
3430
+ const reconciliationJsonPath = reconciliation?.jsonPath;
3431
+ if (typeof reconciliationJsonPath === "string" && reconciliationJsonPath.length > 0) {
3432
+ console.log(chalk6.gray(` Reconciliation: ${reconciliationJsonPath}`));
3433
+ const resolvedPath = path2.resolve(process.cwd(), reconciliationJsonPath);
3434
+ if (fs.existsSync(resolvedPath)) {
3435
+ try {
3436
+ const reconciliationArtifact = parseJsonWithContext(
3437
+ fs.readFileSync(resolvedPath, "utf8"),
3438
+ `Fusion reconciliation artifact (${params.taskId})`
3439
+ );
3440
+ tryRenderFusionArtifactHuman(reconciliationArtifact, { inspect: true });
3441
+ } catch (error) {
3442
+ const message = error instanceof Error ? error.message : String(error);
3443
+ console.log(chalk6.yellow(` Warning: ${message}`));
3444
+ }
3445
+ }
3446
+ }
3447
+ }
3448
+ console.log();
3449
+ }
3450
+ function renderFusionAnalysisSynthesisHuman(params) {
3451
+ if (tryRenderFusionReadHuman(params.read, { inspect: params.inspect })) {
3452
+ if (params.read.parseWarning && params.inspect) {
3453
+ console.log(chalk6.yellow(`Warning: ${params.read.parseWarning}`));
3454
+ }
3455
+ return;
3456
+ }
3457
+ renderFusionAnalysisSynthesisInspectHuman(params);
3458
+ }
3459
+ function renderFusionAnalysisSynthesisDetails(params) {
3460
+ if (!params.read) return;
3461
+ const json = buildFusionAnalysisSynthesisJson({
3462
+ taskId: params.taskId,
3463
+ requestedTaskId: params.requestedTaskId,
3464
+ read: params.read
3465
+ });
3466
+ const synthesis = json.synthesis;
3467
+ if (synthesis.markdownPath) {
3468
+ console.log(chalk6.blue(` Synthesis file: ${synthesis.markdownPath}`));
3469
+ }
3470
+ if (synthesis.jsonPath) {
3471
+ console.log(chalk6.blue(` Synthesis JSON: ${synthesis.jsonPath}`));
3472
+ }
3473
+ if (params.read.artifact && renderFusionManifestDetails(params.read.artifact)) {
3474
+ const recommendation2 = synthesis.finalRecommendation;
3475
+ const summary2 = recommendation2?.summary;
3476
+ if (typeof summary2 === "string" && summary2.trim().length > 0) {
3477
+ console.log(chalk6.blue(` Summary: ${summary2.trim()}`));
3478
+ }
3479
+ if (synthesis.artifactParseWarning) {
3480
+ console.log(chalk6.yellow(` Warning: ${synthesis.artifactParseWarning}`));
3481
+ }
3482
+ return;
3483
+ }
3484
+ console.log(chalk6.blue(` Consensus Items: ${synthesis.consensusCount}`));
3485
+ console.log(chalk6.blue(` Contradictions: ${synthesis.contradictionCount}`));
3486
+ console.log(chalk6.blue(` Partial Coverage: ${synthesis.partialCoverageCount}`));
3487
+ console.log(chalk6.blue(` Unique Insights: ${synthesis.uniqueInsightCount}`));
3488
+ console.log(chalk6.blue(` Blind Spots: ${synthesis.blindSpotCount}`));
3489
+ const recommendation = synthesis.finalRecommendation;
3490
+ const summary = recommendation?.summary;
3491
+ const action = recommendation?.recommendation;
3492
+ if (typeof summary === "string" && summary.trim().length > 0) {
3493
+ console.log(chalk6.blue(` Summary: ${summary.trim()}`));
3494
+ }
3495
+ if (typeof action === "string" && action.trim().length > 0) {
3496
+ console.log(chalk6.blue(` Recommendation: ${action.trim()}`));
3497
+ }
3498
+ if (synthesis.artifactParseWarning) {
3499
+ console.log(chalk6.yellow(` Warning: ${synthesis.artifactParseWarning}`));
3500
+ }
3501
+ }
3502
+ function createCompeteResultsCommand(options = {}) {
3503
+ const surface = options.surface ?? "compete";
3504
+ const isFusion = surface === "fusion";
3505
+ const cmd = new Command("results");
3506
+ cmd.description(
3507
+ isFusion ? "View recorded Fusion synthesis results and execution health" : "View recorded competition results, winner details, and execution health"
3508
+ ).argument(
3509
+ isFusion ? "<task-id>" : "[task-id]",
3510
+ isFusion ? "Fusion task ID" : "Competition task ID (defaults to the most recent competition)"
3511
+ ).option("--warnings <level>", "Warning verbosity: silent|minimal|normal|verbose", "normal").option("--no-warnings", "Suppress all warnings (equivalent to --warnings silent)").option("--json", "Output results as JSON");
3512
+ if (isFusion) {
3513
+ cmd.option(
3514
+ "--inspect",
3515
+ "Show detailed Fusion reconciliation, trust, and provenance instead of the deliverable alone"
3516
+ );
3517
+ cmd.option(
3518
+ "--verbose",
3519
+ "Alias for --inspect: show detailed Fusion reconciliation, trust, and provenance"
3520
+ );
3521
+ }
3522
+ cmd.addHelpText(
3523
+ "after",
3524
+ isFusion ? `
3525
+ Default human output prints the Fusion recommendation deliverable alone when present.
3526
+ Use --inspect or --verbose for the full reconciliation/provenance view. --json includes
3527
+ fusionAnswer plus analysisSynthesis when available and preserves synthesis summary fields.
3528
+ ` : `
3529
+ JSON output includes:
3530
+ - competitionResult: recorded run outcome
3531
+ - executionHealth: clean, degraded, or failed execution state
3532
+ - variants: provider outcomes and warning/input-spec metadata
3533
+ - synthesis.artifactParseWarning: advisory parse warning when present
3534
+ `
3535
+ ).action(async (taskId, options2, command) => {
3536
+ options2 = reconcileRunNestedOptions(command, options2);
3537
+ const inspectRequested = options2.inspect === true || options2.verbose === true;
3538
+ const baseTelemetry = TelemetryLogger.getInstance();
3539
+ let resolved;
3540
+ try {
3541
+ const requestedTaskId = taskId ?? await resolveDefaultCompetitionIdOrReport(resolveCliStateRoots().buildDir);
3542
+ if (requestedTaskId === null) return;
3543
+ const validatedTaskId = validateCommandOptions(TaskIdSchema, requestedTaskId);
3544
+ let warningVerbosity = "normal";
3545
+ if (options2.warnings === false) {
3546
+ warningVerbosity = "silent";
3547
+ } else if (typeof options2.warnings === "string") {
3548
+ warningVerbosity = resolveWarningVerbosity(options2.warnings, "--warnings");
3549
+ } else if (process.env.BUILD_WARNINGS) {
3550
+ warningVerbosity = resolveWarningVerbosity(process.env.BUILD_WARNINGS, "BUILD_WARNINGS");
3551
+ }
3552
+ const warningFormatter = new WarningFormatter(warningVerbosity);
3553
+ resolved = baseTelemetry.resolveLoggerForTaskWithLabFallback(validatedTaskId);
3554
+ const telemetry = resolved.telemetry;
3555
+ const evaluation = telemetry.variantsModule.getJudgeEvaluationDetails(validatedTaskId);
3556
+ const judgeEvaluations = telemetry.variantsModule.listJudgeEvaluationDetails(validatedTaskId);
3557
+ const roots = resolveCliStateRoots();
3558
+ const buildDir = roots.buildDir;
3559
+ const labResolver = LabPathResolver.getInstance();
3560
+ const labBaseStateDir = resolved.usedLabFallback ? labResolver.getStateDir(buildDir) : void 0;
3561
+ const telemetryDir = resolved.usedLabFallback ? labResolver.getTelemetryDir(buildDir) : telemetry.getTelemetryDir();
3562
+ const stateReaderOpts = labBaseStateDir ? {
3563
+ stateDir: path2.join(labBaseStateDir, "competitions"),
3564
+ backgroundDir: path2.join(labBaseStateDir, "background"),
3565
+ unifiedStateDir: labBaseStateDir
3566
+ } : void 0;
3567
+ const competitionStateCache = /* @__PURE__ */ new Map();
3568
+ const labResolvedTaskIdByLookup = /* @__PURE__ */ new Map();
3569
+ const labTelemetryDirByTaskId = /* @__PURE__ */ new Map();
3570
+ const labAmbiguityByLookup = /* @__PURE__ */ new Map();
3571
+ const getCompetitionState = (taskId2) => {
3572
+ const cached = competitionStateCache.get(taskId2);
3573
+ if (cached) return cached;
3574
+ let state = readCompetitionState(taskId2, stateReaderOpts);
3575
+ if (!hasCompetitionStateData(state)) {
3576
+ let labMatch = null;
3577
+ try {
3578
+ labMatch = findLabRunStateForTask2(buildDir, taskId2);
3579
+ } catch (error) {
3580
+ if (error instanceof AmbiguousLabTaskIdError) {
3581
+ labAmbiguityByLookup.set(taskId2, error);
3582
+ } else {
3583
+ throw error;
3584
+ }
3585
+ }
3586
+ if (labMatch) {
3587
+ state = readCompetitionState(
3588
+ labMatch.taskId,
3589
+ buildLabStateReaderOptions(labMatch.runRoot)
3590
+ );
3591
+ labResolvedTaskIdByLookup.set(taskId2, labMatch.taskId);
3592
+ labTelemetryDirByTaskId.set(taskId2, path2.join(labMatch.runRoot, "telemetry"));
3593
+ labTelemetryDirByTaskId.set(
3594
+ labMatch.taskId,
3595
+ path2.join(labMatch.runRoot, "telemetry")
3596
+ );
3597
+ competitionStateCache.set(labMatch.taskId, state);
3598
+ }
3599
+ }
3600
+ competitionStateCache.set(taskId2, state);
3601
+ return state;
3602
+ };
3603
+ let resolvedTaskId = resolveCompetitionResultsTaskId({
3604
+ requestedTaskId: validatedTaskId,
3605
+ evaluationTaskId: getStoredEvaluationTaskId(evaluation),
3606
+ judgeEvaluationTaskIds: judgeEvaluations.map((entry) => getStoredEvaluationTaskId(entry)),
3607
+ hasCompetitionState: (taskId2) => hasCompetitionStateData(getCompetitionState(taskId2))
3608
+ });
3609
+ resolvedTaskId = labResolvedTaskIdByLookup.get(resolvedTaskId) ?? resolvedTaskId;
3610
+ const selectedLabAmbiguity = labAmbiguityByLookup.get(resolvedTaskId);
3611
+ if (selectedLabAmbiguity) {
3612
+ throw selectedLabAmbiguity;
3613
+ }
3614
+ const bypassedRequestedAmbiguity = resolvedTaskId !== validatedTaskId ? labAmbiguityByLookup.get(validatedTaskId) : void 0;
3615
+ const compState = getCompetitionState(resolvedTaskId);
3616
+ const resolvedTelemetryDir = labTelemetryDirByTaskId.get(resolvedTaskId) ?? telemetryDir;
3617
+ const multiJudgeRun = getLatestMultiJudgeRunForTask(telemetry, resolvedTaskId);
3618
+ const winnerFlipRow = getLatestWinnerFlipForTask(telemetry, resolvedTaskId);
3619
+ const defaultTelemetryDir = roots.telemetryDir;
3620
+ let synthesisArtifactRead = readSynthesisArtifact(resolvedTaskId, resolvedTelemetryDir);
3621
+ if (synthesisArtifactRead.artifact === null && resolvedTelemetryDir !== defaultTelemetryDir) {
3622
+ synthesisArtifactRead = readSynthesisArtifact(resolvedTaskId, defaultTelemetryDir);
3623
+ }
3624
+ const synthesisArtifact = summarizeSynthesisArtifact(
3625
+ synthesisArtifactRead.artifact ?? compState.synthesis ?? null
3626
+ );
3627
+ const matrixSummary = readLatestProfileMatrixSummary({
3628
+ evaluations: judgeEvaluations,
3629
+ telemetryDirs: [
3630
+ .../* @__PURE__ */ new Set([telemetry.getTelemetryDir(), resolvedTelemetryDir, defaultTelemetryDir])
3631
+ ]
3632
+ }) ?? matrixSummaryFromStateMetadata(compState.runMetadata?.matrix);
3633
+ const isFusionResult = isFusion || compState.runMetadata?.runSemantics === "fusion";
3634
+ const fusionAnalysisRead = isFusionResult ? readFusionAnalysisSynthesisArtifact(resolvedTaskId, buildDir) : null;
3635
+ if (isFusionResult && !options2.json && fusionAnalysisRead?.artifact) {
3636
+ if (!inspectRequested) {
3637
+ renderFusionAnalysisSynthesisHuman({
3638
+ taskId: resolvedTaskId,
3639
+ requestedTaskId: validatedTaskId,
3640
+ read: fusionAnalysisRead,
3641
+ inspect: false
3642
+ });
3643
+ return;
3644
+ }
3645
+ if (evaluation) {
3646
+ if (hasCompetitionStateData(compState)) {
3647
+ const rawHandle = compState.rawHandle;
3648
+ const rawCandidates = Array.isArray(rawHandle?.candidates) ? rawHandle.candidates : Array.isArray(rawHandle?.variants) ? rawHandle.variants : [];
3649
+ const winnerReconciliation2 = buildWinnerReconciliationForResults({
3650
+ evaluation: void 0,
3651
+ compState,
3652
+ winnerFlipRow,
3653
+ multiJudgeRun
3654
+ });
3655
+ renderFallbackResults(
3656
+ resolvedTaskId,
3657
+ rawCandidates,
3658
+ null,
3659
+ null,
3660
+ compState,
3661
+ fusionAnalysisRead,
3662
+ winnerReconciliation2.requiredGatePolicy,
3663
+ {
3664
+ inspect: true,
3665
+ undeliveredLineFor: undeliveredLineLookup(
3666
+ telemetry.variantsModule,
3667
+ resolvedTaskId
3668
+ )
3669
+ }
3670
+ );
3671
+ return;
3672
+ }
3673
+ renderFusionAnalysisSynthesisHuman({
3674
+ taskId: resolvedTaskId,
3675
+ requestedTaskId: validatedTaskId,
3676
+ read: fusionAnalysisRead,
3677
+ inspect: true
3678
+ });
3679
+ return;
3680
+ }
3681
+ }
3682
+ if (!evaluation) {
3683
+ const fallbackState = compState;
3684
+ if (!hasCompetitionStateData(fallbackState)) {
3685
+ if (fusionAnalysisRead) {
3686
+ if (options2.json) {
3687
+ console.log(
3688
+ JSON.stringify(
3689
+ buildFusionAnalysisSynthesisJson({
3690
+ taskId: resolvedTaskId,
3691
+ requestedTaskId: validatedTaskId,
3692
+ read: fusionAnalysisRead
3693
+ }),
3694
+ null,
3695
+ 2
3696
+ )
3697
+ );
3698
+ } else {
3699
+ renderFusionAnalysisSynthesisHuman({
3700
+ taskId: resolvedTaskId,
3701
+ requestedTaskId: validatedTaskId,
3702
+ read: fusionAnalysisRead,
3703
+ inspect: inspectRequested
3704
+ });
3705
+ }
3706
+ return;
3707
+ }
3708
+ if (options2.json) {
3709
+ console.log(
3710
+ JSON.stringify(
3711
+ {
3712
+ error: "No evaluation found",
3713
+ taskId: resolvedTaskId,
3714
+ hints: buildNoEvaluationFoundHints(surface, resolvedTaskId)
3715
+ },
3716
+ null,
3717
+ 2
3718
+ )
3719
+ );
3720
+ } else {
3721
+ renderNoEvaluationFoundError(surface, resolvedTaskId);
3722
+ }
3723
+ process.exitCode = 1;
3724
+ return;
3725
+ }
3726
+ if (options2.json) {
3727
+ const rawCandidates2 = getRawCompetitionCandidates(fallbackState);
3728
+ const isFusionFallback2 = surface === "fusion" || fallbackState.runMetadata?.runSemantics === "fusion";
3729
+ const runMetadata = fallbackState.runMetadata ? {
3730
+ ...fallbackState.runMetadata,
3731
+ ...isFusionFallback2 ? { judge: void 0, replay: void 0 } : {}
3732
+ } : null;
3733
+ const outcome = isFusionFallback2 ? null : fallbackState.outcome ?? null;
3734
+ const winnerReconciliation3 = buildWinnerReconciliationForResults({
3735
+ evaluation: void 0,
3736
+ compState: fallbackState,
3737
+ winnerFlipRow,
3738
+ multiJudgeRun
3739
+ });
3740
+ console.log(
3741
+ JSON.stringify(
3742
+ {
3743
+ taskId: resolvedTaskId,
3744
+ requestedTaskId: validatedTaskId,
3745
+ resolvedTaskId,
3746
+ executionMode: fallbackState.executionMode ?? null,
3747
+ initiatedBy: fallbackState.initiatedBy ?? null,
3748
+ outcome,
3749
+ ...isFusionFallback2 ? {
3750
+ fusionResult: resolveCompetitionResultFromState(fallbackState),
3751
+ ...getFusionRunReadModel(resolvedTaskId, stateReaderOpts)
3752
+ } : {
3753
+ competitionResult: resolveCompetitionResultFromState(fallbackState),
3754
+ judgeOperationsV1: projectJudgeOperationsFromState(
3755
+ { id: resolvedTaskId, kind: "compete" },
3756
+ fallbackState
3757
+ ),
3758
+ ...getCompetitionRunReadModel(resolvedTaskId, stateReaderOpts)
3759
+ },
3760
+ executionHealth: resolveExecutionHealthFromState(fallbackState),
3761
+ runMetadata,
3762
+ lab: fallbackState.labId || fallbackState.labRunId ? {
3763
+ labId: fallbackState.labId ?? null,
3764
+ runId: fallbackState.labRunId ?? null
3765
+ } : null,
3766
+ ...!isFusionFallback2 ? { judge: buildFallbackJudgeSummary(fallbackState) } : {},
3767
+ decision: buildFallbackDecisionSummary(fallbackState),
3768
+ ...!isFusionFallback2 ? {
3769
+ winner: fallbackState.outcome === "winner_selected" && fallbackState.winner ? {
3770
+ provider: fallbackState.winner.provider ?? null,
3771
+ model: fallbackState.winner.resolvedModel ?? fallbackState.winner.model ?? null,
3772
+ variant: fallbackState.winner.variant ?? null,
3773
+ provenance: fallbackState.decision?.decisionStatus === "declared" ? "competition_handle; persisted judge decision" : "competition_handle; judge evaluation telemetry unavailable"
3774
+ } : null,
3775
+ ungradedIdentity: fallbackState.decision?.reason === "judge_off" && fallbackState.winner ? {
3776
+ provider: fallbackState.winner.provider ?? null,
3777
+ model: fallbackState.winner.resolvedModel ?? fallbackState.winner.model ?? null,
3778
+ variant: fallbackState.winner.variant ?? null
3779
+ } : null
3780
+ } : {},
3781
+ candidates: rawCandidates2.map(
3782
+ (candidate) => buildCompetitionHandleVariantJson(candidate, {
3783
+ runSemantics: fallbackState.runMetadata?.runSemantics ?? null
3784
+ })
3785
+ ),
3786
+ variants: rawCandidates2.map(
3787
+ (candidate) => buildCompetitionHandleVariantJson(candidate, {
3788
+ runSemantics: fallbackState.runMetadata?.runSemantics ?? null
3789
+ })
3790
+ ),
3791
+ synthesis: isFusionFallback2 ? buildFusionSynthesisResultsJson({
3792
+ synthesisGenerated: false,
3793
+ artifact: synthesisArtifact,
3794
+ artifactParseWarning: synthesisArtifactRead.parseWarning,
3795
+ analysisSynthesis: fallbackState.runMetadata?.synthesis
3796
+ }) : buildSynthesisResultsJson({
3797
+ synthesisGenerated: false,
3798
+ artifact: synthesisArtifact,
3799
+ artifactParseWarning: synthesisArtifactRead.parseWarning,
3800
+ rawArtifact: synthesisArtifactRead.artifact
3801
+ }),
3802
+ ...isFusionFallback2 ? buildFusionArtifactJsonFields(fusionAnalysisRead) : {},
3803
+ ...!isFusionFallback2 ? {
3804
+ multiJudge: multiJudgeRun ?? null,
3805
+ matrix: matrixSummary,
3806
+ judgeEvaluations
3807
+ } : {},
3808
+ ...!isFusionFallback2 && winnerReconciliation3.hasTelemetry ? { winnerReconciliation: winnerReconciliation3 } : {}
3809
+ },
3810
+ null,
3811
+ 2
3812
+ )
3813
+ );
3814
+ return;
3815
+ }
3816
+ if (resolved?.resolvedDbPath) {
3817
+ const relativeDbPath = path2.relative(process.cwd(), resolved.resolvedDbPath);
3818
+ const resolvedLabel = relativeDbPath.length > 0 && !relativeDbPath.startsWith("..") ? relativeDbPath : resolved.resolvedDbPath;
3819
+ const suffix = resolved.usedLabFallback ? " (lab fallback)" : "";
3820
+ console.log(chalk6.gray(`
3821
+ Telemetry DB: ${resolvedLabel}${suffix}
3822
+ `));
3823
+ }
3824
+ const rawHandle = fallbackState.rawHandle;
3825
+ const rawCandidates = Array.isArray(rawHandle?.candidates) ? rawHandle?.candidates : Array.isArray(rawHandle?.variants) ? rawHandle?.variants : [];
3826
+ const isFusionFallback = surface === "fusion" || fallbackState.runMetadata?.runSemantics === "fusion";
3827
+ if (isFusionFallback && !inspectRequested && tryRenderFusionReadHuman(fusionAnalysisRead, {
3828
+ inspect: false
3829
+ })) {
3830
+ return;
3831
+ }
3832
+ const winnerReconciliation2 = buildWinnerReconciliationForResults({
3833
+ evaluation: void 0,
3834
+ compState: fallbackState,
3835
+ winnerFlipRow,
3836
+ multiJudgeRun
3837
+ });
3838
+ renderFallbackResults(
3839
+ resolvedTaskId,
3840
+ rawCandidates,
3841
+ fallbackState.outcome === "winner_selected" || fallbackState.decision?.reason === "judge_off" ? fallbackState.winner ?? null : null,
3842
+ fallbackState.decision?.reason ?? null,
3843
+ fallbackState,
3844
+ fusionAnalysisRead,
3845
+ winnerReconciliation2.requiredGatePolicy,
3846
+ {
3847
+ inspect: inspectRequested,
3848
+ undeliveredLineFor: undeliveredLineLookup(telemetry.variantsModule, resolvedTaskId)
3849
+ }
3850
+ );
3851
+ if (synthesisArtifact) {
3852
+ renderSynthesisTelemetryHuman(synthesisArtifact, synthesisArtifactRead.artifact);
3853
+ }
3854
+ if (synthesisArtifactRead.parseWarning) {
3855
+ console.log(
3856
+ chalk6.yellow(
3857
+ `Warning: Synthesis artifact unreadable: ${synthesisArtifactRead.parseWarning}`
3858
+ )
3859
+ );
3860
+ console.log();
3861
+ }
3862
+ renderInterruptedCompetitionNotice(fallbackState);
3863
+ formatWinnerReconciliationHuman(winnerReconciliation2, multiJudgeRun);
3864
+ if (multiJudgeRun) {
3865
+ renderMultiJudgeRun(multiJudgeRun);
3866
+ }
3867
+ renderMatrixResultsSummary(matrixSummary);
3868
+ return;
3869
+ }
3870
+ if (options2.json) {
3871
+ const winnerReconciliation2 = buildWinnerReconciliationForResults({
3872
+ evaluation,
3873
+ compState,
3874
+ winnerFlipRow,
3875
+ multiJudgeRun
3876
+ });
3877
+ const hasFinalWinner2 = compState.outcome === "winner_selected";
3878
+ const rawCandidates = getRawCompetitionCandidates(compState);
3879
+ const finalWinnerForRows = hasFinalWinner2 && winnerReconciliation2.finalRetainedWinner.variant ? winnerReconciliation2.finalRetainedWinner.variant : hasFinalWinner2 && compState.winner?.variant ? compState.winner.variant : null;
3880
+ const isFusionRun = compState.runMetadata?.runSemantics === "fusion";
3881
+ const variantsJsonBase = isFusionRun ? rawCandidates.map(
3882
+ (candidate) => buildCompetitionHandleVariantJson(candidate, {
3883
+ runSemantics: compState.runMetadata?.runSemantics ?? null
3884
+ })
3885
+ ) : hasEvaluationVariantScores(evaluation) ? Object.entries(evaluation.variantScores ?? {}).map(([variantId, data]) => {
3886
+ const variantData = data && typeof data === "object" ? data : null;
3887
+ const inputSpecWarning = findVariantInputSpecWarning(
3888
+ [variantId, variantData?.label],
3889
+ compState.variants
3890
+ );
3891
+ return {
3892
+ variant: variantId,
3893
+ ...!isFusionRun ? {
3894
+ isWinner: hasFinalWinner2 && finalWinnerForRows != null && variantHandlesMatchForResults(variantId, finalWinnerForRows)
3895
+ } : {},
3896
+ label: variantData?.label ?? null,
3897
+ overallScore: typeof variantData?.overallScore === "number" && Number.isFinite(variantData.overallScore) ? variantData.overallScore : null,
3898
+ rankingScore: typeof variantData?.rankingScore === "number" && Number.isFinite(variantData.rankingScore) ? variantData.rankingScore : null,
3899
+ compositeScore: typeof variantData?.compositeScore === "number" && Number.isFinite(variantData.compositeScore) ? variantData.compositeScore : null,
3900
+ qualityScore: typeof variantData?.qualityScore === "number" && Number.isFinite(variantData.qualityScore) ? variantData.qualityScore : null,
3901
+ scoreSource: typeof variantData?.scoreSource === "string" ? variantData.scoreSource : null,
3902
+ ...inputSpecWarning ? { inputSpecWarning } : {},
3903
+ scores: variantData?.scores ?? null,
3904
+ confidence: getDisplayableSelfConfidence(variantData ?? {}),
3905
+ rationale: variantData?.rationale ?? null
3906
+ };
3907
+ }) : rawCandidates.map(
3908
+ (candidate) => buildCompetitionHandleVariantJson(candidate, {
3909
+ runSemantics: compState.runMetadata?.runSemantics ?? null
3910
+ })
3911
+ );
3912
+ const variantsJson = !isFusionRun && hasFinalWinner2 && finalWinnerForRows != null && !variantsJsonBase.some(
3913
+ (row) => resultVariantRowMatchesFinalWinner(row, finalWinnerForRows)
3914
+ ) ? [
3915
+ ...variantsJsonBase.map((row) => ({
3916
+ ...row,
3917
+ isWinner: false
3918
+ })),
3919
+ {
3920
+ variant: finalWinnerForRows,
3921
+ isWinner: true,
3922
+ label: null,
3923
+ overallScore: null,
3924
+ rankingScore: null,
3925
+ compositeScore: null,
3926
+ qualityScore: null,
3927
+ scoreSource: "competition_handle",
3928
+ scores: null,
3929
+ confidence: null,
3930
+ rationale: null
3931
+ }
3932
+ ] : variantsJsonBase;
3933
+ const outcome = isFusionRun ? null : compState.outcome ?? null;
3934
+ const finalWinnerVariant = isFusionRun ? null : finalWinnerForRows;
3935
+ const winnerEvidence2 = finalWinnerVariant ? resolveWinnerEvidenceForResults({
3936
+ finalWinnerVariant,
3937
+ selectedEvaluation: evaluation,
3938
+ judgeEvaluations,
3939
+ multiJudgeRun,
3940
+ winnerReconciliation: winnerReconciliation2
3941
+ }) : null;
3942
+ const winnerJson = finalWinnerVariant && winnerEvidence2 ? {
3943
+ variant: finalWinnerVariant,
3944
+ score: winnerEvidence2.score,
3945
+ decisionScore: winnerEvidence2.decisionScore,
3946
+ confidence: winnerEvidence2.confidence,
3947
+ rationale: winnerEvidence2.rationale,
3948
+ scoreSource: winnerEvidence2.scoreSource,
3949
+ provenance: winnerEvidence2.provenance
3950
+ } : null;
3951
+ const scoreCalibration = buildScoreCalibrationSummary({
3952
+ report: winnerReconciliation2,
3953
+ multiJudgeRun
3954
+ });
3955
+ if (winnerEvidence2 && scoreCalibration.primaryAlignedWithFinal === true && typeof winnerEvidence2.score === "number") {
3956
+ scoreCalibration.finalWinnerScore = winnerEvidence2.score;
3957
+ scoreCalibration.scoreDeltaPrimaryMinusFinal = typeof scoreCalibration.primaryWinnerScore === "number" ? scoreCalibration.primaryWinnerScore - winnerEvidence2.score : null;
3958
+ }
3959
+ console.log(
3960
+ JSON.stringify(
3961
+ {
3962
+ taskId: resolvedTaskId,
3963
+ requestedTaskId: validatedTaskId,
3964
+ resolvedTaskId,
3965
+ executionMode: compState.executionMode ?? null,
3966
+ initiatedBy: compState.initiatedBy ?? null,
3967
+ outcome,
3968
+ ...isFusionRun ? {
3969
+ fusionResult: resolveCompetitionResultFromState(compState),
3970
+ ...getFusionRunReadModel(resolvedTaskId, stateReaderOpts)
3971
+ } : {
3972
+ competitionResult: resolveCompetitionResultFromState(compState),
3973
+ judgeOperationsV1: projectJudgeOperationsFromState(
3974
+ { id: resolvedTaskId, kind: "compete" },
3975
+ compState
3976
+ ),
3977
+ ...getCompetitionRunReadModel(resolvedTaskId, stateReaderOpts)
3978
+ },
3979
+ executionHealth: resolveExecutionHealthFromState(compState),
3980
+ runMetadata: compState.runMetadata ? {
3981
+ ...compState.runMetadata,
3982
+ ...isFusionRun ? { judge: void 0, replay: void 0 } : {}
3983
+ } : null,
3984
+ lab: compState.labId || compState.labRunId ? {
3985
+ labId: compState.labId ?? null,
3986
+ runId: compState.labRunId ?? null
3987
+ } : null,
3988
+ ...!isFusionRun ? {
3989
+ judge: compState.runMetadata?.judge ?? (compState.decision ? {
3990
+ requested: compState.decision.primaryJudge ?? null,
3991
+ status: compState.decision.reason === "judge_off" ? "disabled" : null,
3992
+ reason: compState.decision.reason ?? null
3993
+ } : null),
3994
+ winner: winnerJson
3995
+ } : {},
3996
+ variants: variantsJson,
3997
+ ...!isFusionRun ? {
3998
+ metadata: {
3999
+ model: evaluation.model ?? null,
4000
+ totalVariants: evaluation.totalVariants ?? null,
4001
+ evaluationTimeMs: evaluation.evaluationTimeMs ?? null,
4002
+ evaluationDurationMs: evaluation.evaluationDurationMs ?? null,
4003
+ tokensUsed: evaluation.tokensUsed ?? null,
4004
+ costUsd: evaluation.costUsd ?? null
4005
+ },
4006
+ selectedEvaluation: {
4007
+ kind: getSelectedEvaluationKind(evaluation),
4008
+ winner: evaluation.winnerVariant ?? null,
4009
+ score: evaluation.winnerScore ?? null,
4010
+ confidence: evaluation.winnerConfidence ?? null,
4011
+ rationale: evaluation.winnerRationale ?? null
4012
+ },
4013
+ configuration: {
4014
+ criteriaWeights: evaluation.criteriaWeights ?? null,
4015
+ minAcceptableScore: evaluation.minAcceptableScore ?? null,
4016
+ confidenceThreshold: evaluation.confidenceThreshold ?? null
4017
+ }
4018
+ } : {},
4019
+ synthesis: isFusionRun ? buildFusionSynthesisResultsJson({
4020
+ synthesisGenerated: evaluation.synthesisGenerated,
4021
+ synthesisCode: evaluation.synthesisCode,
4022
+ artifact: synthesisArtifact,
4023
+ artifactParseWarning: synthesisArtifactRead.parseWarning,
4024
+ analysisSynthesis: compState.runMetadata?.synthesis
4025
+ }) : buildSynthesisResultsJson({
4026
+ synthesisGenerated: evaluation.synthesisGenerated,
4027
+ synthesisCode: evaluation.synthesisCode,
4028
+ artifact: synthesisArtifact,
4029
+ artifactParseWarning: synthesisArtifactRead.parseWarning,
4030
+ rawArtifact: synthesisArtifactRead.artifact
4031
+ }),
4032
+ ...isFusionRun ? buildFusionArtifactJsonFields(fusionAnalysisRead) : {},
4033
+ ...!isFusionRun ? {
4034
+ multiJudge: multiJudgeRun ?? null,
4035
+ matrix: matrixSummary,
4036
+ judgeEvaluations,
4037
+ scoreCalibration,
4038
+ ...winnerReconciliation2.hasTelemetry ? { winnerReconciliation: winnerReconciliation2 } : {}
4039
+ } : {},
4040
+ ...bypassedRequestedAmbiguity ? {
4041
+ warnings: [
4042
+ {
4043
+ code: "requested_lab_task_id_ambiguous",
4044
+ message: bypassedRequestedAmbiguity.message,
4045
+ taskId: bypassedRequestedAmbiguity.requestedTaskId,
4046
+ matchType: bypassedRequestedAmbiguity.matchType,
4047
+ matches: bypassedRequestedAmbiguity.matches.map((match) => ({
4048
+ taskId: match.taskId,
4049
+ runRoot: match.runRoot
4050
+ })),
4051
+ resolvedTaskId
4052
+ }
4053
+ ]
4054
+ } : {}
4055
+ },
4056
+ null,
4057
+ 2
4058
+ )
4059
+ );
4060
+ return;
4061
+ }
4062
+ if (bypassedRequestedAmbiguity) {
4063
+ console.error(
4064
+ chalk6.yellow(
4065
+ `Warning: ${bypassedRequestedAmbiguity.message} Resolved via stored evaluation taskId ${resolvedTaskId}.`
4066
+ )
4067
+ );
4068
+ }
4069
+ const resultsTitle = extractTitleFromPrompt(compState.prompt);
4070
+ console.log(
4071
+ chalk6.blue.bold(
4072
+ `
4073
+ Competition Results: ${formatTaskLabel({ title: resultsTitle, id: validatedTaskId })}
4074
+ `
4075
+ )
4076
+ );
4077
+ const hasFinalWinner = compState.outcome === "winner_selected";
4078
+ if (compState.executionMode) {
4079
+ console.log(chalk6.cyan(`Mode: ${formatExecutionModeLabel(compState.executionMode)}`));
4080
+ console.log();
4081
+ }
4082
+ const winnerReconciliation = buildWinnerReconciliationForResults({
4083
+ evaluation,
4084
+ compState,
4085
+ winnerFlipRow,
4086
+ multiJudgeRun
4087
+ });
4088
+ renderInterruptedCompetitionNotice(compState);
4089
+ formatWinnerReconciliationHuman(winnerReconciliation, multiJudgeRun);
4090
+ console.log(chalk6.white.bold("Evaluation Metadata:"));
4091
+ if (resolved?.resolvedDbPath) {
4092
+ const relativeDbPath = path2.relative(process.cwd(), resolved.resolvedDbPath);
4093
+ const resolvedLabel = relativeDbPath.length > 0 && !relativeDbPath.startsWith("..") ? relativeDbPath : resolved.resolvedDbPath;
4094
+ const suffix = resolved.usedLabFallback ? " (lab fallback)" : "";
4095
+ console.log(chalk6.white(` Telemetry DB: ${resolvedLabel}${suffix}`));
4096
+ }
4097
+ const judgeModelLine = formatJudgeEvaluationModelLine(evaluation);
4098
+ if (judgeModelLine) {
4099
+ console.log(chalk6.white(judgeModelLine));
4100
+ }
4101
+ console.log(chalk6.white(` Total Variants: ${evaluation.totalVariants}`));
4102
+ if (typeof evaluation.evaluationTimeMs === "number") {
4103
+ console.log(
4104
+ chalk6.white(` Evaluation Time: ${evaluation.evaluationTimeMs.toFixed(0)}ms`)
4105
+ );
4106
+ }
4107
+ if (typeof evaluation.evaluationDurationMs === "number") {
4108
+ console.log(chalk6.white(` Duration: ${evaluation.evaluationDurationMs.toFixed(0)}ms`));
4109
+ }
4110
+ if (evaluation.tokensUsed) {
4111
+ console.log(chalk6.white(` Tokens Used: ${evaluation.tokensUsed.toLocaleString()}`));
4112
+ }
4113
+ if (typeof evaluation.costUsd === "number") {
4114
+ console.log(chalk6.white(` Cost: $${evaluation.costUsd.toFixed(4)}`));
4115
+ }
4116
+ console.log();
4117
+ if (evaluation.criteriaWeights || evaluation.minAcceptableScore || evaluation.confidenceThreshold) {
4118
+ console.log(chalk6.white.bold("Configuration:"));
4119
+ if (evaluation.criteriaWeights) {
4120
+ console.log(chalk6.white(" Criteria Weights:"));
4121
+ for (const [criterion, weight] of Object.entries(evaluation.criteriaWeights)) {
4122
+ console.log(chalk6.gray(` ${criterion}: ${weight}`));
4123
+ }
4124
+ }
4125
+ if (evaluation.minAcceptableScore !== void 0) {
4126
+ console.log(chalk6.white(` Minimum Score: ${evaluation.minAcceptableScore}`));
4127
+ }
4128
+ if (evaluation.confidenceThreshold !== void 0) {
4129
+ console.log(chalk6.white(` Confidence Threshold: ${evaluation.confidenceThreshold}`));
4130
+ }
4131
+ console.log();
4132
+ }
4133
+ const decisionStatus = evaluation.winnerRationale?.decisionStatus;
4134
+ const decisionOutcome = evaluation.winnerRationale?.decisionOutcome;
4135
+ const escalation = evaluation.winnerRationale?.escalation;
4136
+ const coverageSummary = formatJudgeCoverageSummary(evaluation.winnerRationale?.coverage);
4137
+ const margin = evaluation.winnerRationale?.margin;
4138
+ const top2 = evaluation.winnerRationale?.top2;
4139
+ const variantLabelMapping = extractVariantLabelMapping(
4140
+ evaluation
4141
+ );
4142
+ const statusText = typeof decisionStatus === "string" ? decisionStatus : null;
4143
+ const outcomeText = typeof decisionOutcome === "string" ? decisionOutcome : null;
4144
+ const marginText = typeof margin === "number" && Number.isFinite(margin) ? margin : null;
4145
+ const top2List = Array.isArray(top2) ? top2 : null;
4146
+ const winnerVariant = compState.winner?.variant != null ? String(compState.winner.variant).trim() : null;
4147
+ const winnerEvidence = hasFinalWinner && winnerVariant ? resolveWinnerEvidenceForResults({
4148
+ finalWinnerVariant: winnerVariant,
4149
+ selectedEvaluation: evaluation,
4150
+ judgeEvaluations,
4151
+ multiJudgeRun,
4152
+ winnerReconciliation
4153
+ }) : null;
4154
+ if (shouldRenderUnretainedJudgeTopPick({
4155
+ hasFinalWinner,
4156
+ evaluationWinnerVariant: evaluation.winnerVariant,
4157
+ decisionReason: compState.decision?.reason
4158
+ })) {
4159
+ console.log(chalk6.yellow.bold("No Final Winner"));
4160
+ const top = winnerReconciliation.judgeSelectedTopPick.variant ?? evaluation.winnerVariant;
4161
+ const outcomeLabel = compState.outcome ?? "no_winner";
4162
+ const suffix = "judge-selected top pick was not retained";
4163
+ console.log(
4164
+ chalk6.yellow(
4165
+ ` Final outcome: ${outcomeLabel} \u2014 ${suffix} (${top}; see Winner reconciliation above).`
4166
+ )
4167
+ );
4168
+ console.log();
4169
+ }
4170
+ if (hasFinalWinner && winnerVariant) {
4171
+ console.log(chalk6.green.bold("Winner:"));
4172
+ console.log(chalk6.green(` Variant: ${winnerVariant}`));
4173
+ const applicationLine = formatApplicationVerificationLine(compState.application);
4174
+ if (applicationLine) console.log(chalk6.green(` ${applicationLine}`));
4175
+ if (typeof winnerEvidence?.decisionScore === "number") {
4176
+ console.log(
4177
+ chalk6.green(` Decision Score: ${winnerEvidence.decisionScore.toFixed(2)}%`)
4178
+ );
4179
+ }
4180
+ if (typeof winnerEvidence?.confidence === "number") {
4181
+ console.log(
4182
+ chalk6.green(
4183
+ ` Decision Confidence: ${formatConfidencePercent(winnerEvidence.confidence)}`
4184
+ )
4185
+ );
4186
+ }
4187
+ const winnerSelfConfidence = winnerVariant && evaluation.variantScores ? getDisplayableSelfConfidence(
4188
+ evaluation.variantScores[winnerVariant] ?? Object.entries(evaluation.variantScores).find(
4189
+ ([variant]) => variantHandlesMatchForResults(variant, winnerVariant)
4190
+ )?.[1] ?? {}
4191
+ ) : void 0;
4192
+ if (winnerSelfConfidence !== void 0) {
4193
+ console.log(
4194
+ chalk6.green(` Self-Confidence: ${formatConfidencePercent(winnerSelfConfidence)}`)
4195
+ );
4196
+ }
4197
+ if (statusText || outcomeText) {
4198
+ const parts = [];
4199
+ if (statusText) parts.push(`status=${statusText}`);
4200
+ if (outcomeText) parts.push(`outcome=${outcomeText}`);
4201
+ if (marginText !== null) parts.push(`margin=${marginText.toFixed(1)}`);
4202
+ if (top2List && top2List.length >= 2) {
4203
+ const first = top2List[0];
4204
+ const second = top2List[1];
4205
+ const firstLabel = typeof first?.variant === "string" ? `${first.variant}` : "unknown";
4206
+ const firstScore = typeof first?.score === "number" && Number.isFinite(first.score) ? `(${first.score.toFixed(1)})` : "";
4207
+ const secondLabel = typeof second?.variant === "string" ? `${second.variant}` : "unknown";
4208
+ const secondScore = typeof second?.score === "number" && Number.isFinite(second.score) ? `(${second.score.toFixed(1)})` : "";
4209
+ parts.push(`top2=${firstLabel}${firstScore} vs ${secondLabel}${secondScore}`);
4210
+ }
4211
+ console.log(chalk6.yellow(` Decision: ${parts.join(" \u2022 ")}`));
4212
+ }
4213
+ if (escalation && typeof escalation.recommended === "string" && escalation.recommended !== "none") {
4214
+ const reasons = Array.isArray(escalation.reasons) ? escalation.reasons.filter((reason) => typeof reason === "string") : [];
4215
+ console.log(
4216
+ chalk6.yellow(
4217
+ ` Escalation: ${escalation.recommended}${reasons.length > 0 ? ` [${reasons.join(", ")}]` : ""}`
4218
+ )
4219
+ );
4220
+ }
4221
+ if (coverageSummary) {
4222
+ console.log(chalk6.yellow(` Coverage: ${coverageSummary}`));
4223
+ }
4224
+ const winnerRationale = winnerEvidence?.rationale ?? null;
4225
+ if (winnerRationale) {
4226
+ console.log(chalk6.green("\n Rationale:"));
4227
+ console.log(
4228
+ chalk6.yellow.dim(
4229
+ " Warning: AI analysis may contain unverified claims. Verify critical findings with linter/tests."
4230
+ )
4231
+ );
4232
+ if (winnerRationale.reasoning) {
4233
+ console.log(chalk6.gray(` ${winnerRationale.reasoning}`));
4234
+ }
4235
+ if (winnerRationale.strengths && Array.isArray(winnerRationale.strengths)) {
4236
+ console.log(chalk6.gray("\n Strengths:"));
4237
+ for (const strength of winnerRationale.strengths) {
4238
+ console.log(chalk6.gray(` - ${strength}`));
4239
+ }
4240
+ }
4241
+ if (winnerRationale.weaknesses && Array.isArray(winnerRationale.weaknesses)) {
4242
+ console.log(chalk6.gray("\n Weaknesses:"));
4243
+ for (const weakness of winnerRationale.weaknesses) {
4244
+ console.log(chalk6.gray(` - ${weakness}`));
4245
+ }
4246
+ }
4247
+ if (variantLabelMapping.length > 0) {
4248
+ console.log(chalk6.gray("\n Label Mapping:"));
4249
+ for (const entry of variantLabelMapping) {
4250
+ console.log(chalk6.gray(` ${entry.label} -> ${entry.variant}`));
4251
+ }
4252
+ }
4253
+ }
4254
+ console.log();
4255
+ }
4256
+ if (evaluation.variantScores && Object.keys(evaluation.variantScores).length > 0) {
4257
+ console.log(chalk6.blue.bold("Variant Scores:\n"));
4258
+ for (const [variant, data] of Object.entries(evaluation.variantScores)) {
4259
+ if (!data || typeof data !== "object" || !("scores" in data)) {
4260
+ continue;
4261
+ }
4262
+ const isWinner = hasFinalWinner && winnerVariant != null && variantHandlesMatchForResults(variant, winnerVariant);
4263
+ const variantColor = isWinner ? chalk6.green : chalk6.white;
4264
+ const variantExecution = telemetry.getVariantExecution(validatedTaskId, variant);
4265
+ const terminationReason = variantExecution?.termination_reason;
4266
+ const terminationLabel = terminationReason ? ` (${terminationReason})` : "";
4267
+ let variantResultRecord = null;
4268
+ try {
4269
+ variantResultRecord = telemetry.variantsModule.getVariantResultRecord(
4270
+ validatedTaskId,
4271
+ variantExecution?.variant ?? variant
4272
+ );
4273
+ } catch {
4274
+ variantResultRecord = null;
4275
+ }
4276
+ console.log(
4277
+ variantColor.bold(` ${variant}${isWinner ? " (winner)" : ""}${terminationLabel}:`)
4278
+ );
4279
+ if (typeof data === "object" && data !== null) {
4280
+ const variantData = data;
4281
+ const variantLabel = typeof variantData.label === "string" ? variantData.label.trim() : "";
4282
+ if (variantLabel.length > 0) {
4283
+ console.log(chalk6.gray(` Label: ${variantLabel}`));
4284
+ }
4285
+ const providerExecutionPathLine = formatProviderExecutionPathLine(
4286
+ variant,
4287
+ variantResultRecord
4288
+ );
4289
+ if (providerExecutionPathLine) {
4290
+ console.log(chalk6.gray(` ${providerExecutionPathLine}`));
4291
+ }
4292
+ if (variantData.scores) {
4293
+ console.log(chalk6.gray(" Scores:"));
4294
+ for (const [criterion, score] of Object.entries(variantData.scores)) {
4295
+ console.log(chalk6.gray(` ${criterion}: ${score}`));
4296
+ }
4297
+ }
4298
+ const primaryScore = getVariantOverallScore(variantData);
4299
+ if (typeof primaryScore === "number" && Number.isFinite(primaryScore)) {
4300
+ const primaryLabel = variantData.scoreSource === "bucket_scores" || typeof variantData.rankingScore === "number" || typeof variantData.compositeScore === "number" ? "Ranking Score" : "Overall";
4301
+ console.log(chalk6.gray(` ${primaryLabel}: ${primaryScore.toFixed(1)}`));
4302
+ }
4303
+ if (typeof variantData.qualityScore === "number" && Number.isFinite(variantData.qualityScore) && (primaryScore === null || Math.abs(primaryScore - variantData.qualityScore) > 0.05)) {
4304
+ console.log(
4305
+ chalk6.gray(` Quality Score: ${variantData.qualityScore.toFixed(1)}`)
4306
+ );
4307
+ }
4308
+ const variantSelfConfidence = getDisplayableSelfConfidence(variantData);
4309
+ if (variantSelfConfidence !== void 0) {
4310
+ console.log(
4311
+ chalk6.gray(
4312
+ ` Self-Confidence: ${formatConfidencePercent(variantSelfConfidence)}`
4313
+ )
4314
+ );
4315
+ }
4316
+ printCandidateEvidenceLines(variantResultRecord);
4317
+ const undeliveredLine = undeliveredLineFromTelemetry(
4318
+ telemetry.variantsModule,
4319
+ validatedTaskId,
4320
+ [variantExecution?.variant, variant]
4321
+ );
4322
+ if (undeliveredLine) console.log(chalk6.gray(` ${undeliveredLine}`));
4323
+ if (variantData.rationale?.reasoning) {
4324
+ console.log(
4325
+ chalk6.yellow.dim(
4326
+ " Warning: AI analysis may contain unverified claims. Verify critical findings with linter/tests."
4327
+ )
4328
+ );
4329
+ console.log(chalk6.gray(` Reasoning: ${variantData.rationale.reasoning}`));
4330
+ }
4331
+ }
4332
+ const isTimedOut = variantResultRecord?.timedOut === true;
4333
+ const hasPartialEdits = variantResultRecord?.partialEdits === true;
4334
+ const partialStats = variantResultRecord ? extractPartialEditStats(variantResultRecord) : null;
4335
+ if (isTimedOut && (hasPartialEdits || partialStats)) {
4336
+ console.log(
4337
+ chalk6.yellow(
4338
+ ` Partial edits: ${partialStats?.filesChanged ?? 0} files, +${partialStats?.linesAdded ?? 0}/-${partialStats?.linesRemoved ?? 0}`
4339
+ )
4340
+ );
4341
+ }
4342
+ console.log();
4343
+ }
4344
+ }
4345
+ if (evaluation.synthesisGenerated && evaluation.synthesisCode) {
4346
+ console.log(chalk6.blue.bold("Tip: Synthesis:\n"));
4347
+ console.log(chalk6.gray(evaluation.synthesisCode));
4348
+ console.log();
4349
+ }
4350
+ if (synthesisArtifact) {
4351
+ renderSynthesisTelemetryHuman(synthesisArtifact, synthesisArtifactRead.artifact);
4352
+ }
4353
+ if (synthesisArtifactRead.parseWarning) {
4354
+ console.log(
4355
+ chalk6.yellow(
4356
+ `Warning: Synthesis artifact unreadable: ${synthesisArtifactRead.parseWarning}`
4357
+ )
4358
+ );
4359
+ console.log();
4360
+ }
4361
+ renderPerJudgeVariantScores(judgeEvaluations);
4362
+ if (multiJudgeRun) {
4363
+ renderMultiJudgeRun(multiJudgeRun);
4364
+ }
4365
+ renderMatrixResultsSummary(matrixSummary);
4366
+ if (evaluation.variantScores && Object.keys(evaluation.variantScores).length > 0) {
4367
+ for (const [variantId, data] of Object.entries(evaluation.variantScores)) {
4368
+ if (!data || typeof data !== "object" || !("scores" in data)) {
4369
+ continue;
4370
+ }
4371
+ try {
4372
+ const variantExecution = telemetry.getVariantExecution(validatedTaskId, variantId);
4373
+ if (variantExecution) {
4374
+ const resultJson = variantExecution.resultJson ? parseJsonWithContext(
4375
+ variantExecution.resultJson,
4376
+ `Variant result JSON (${variantExecution.variant})`
4377
+ ) : null;
4378
+ if (resultJson && Array.isArray(resultJson.warnings) && resultJson.warnings.length > 0) {
4379
+ console.log(chalk6.blue.bold(`
4380
+ Warning: Warnings for ${variantId}:`));
4381
+ console.log(warningFormatter.formatWarnings(resultJson.warnings));
4382
+ console.log(
4383
+ chalk6.gray(` Summary: ${warningFormatter.formatSummary(resultJson.warnings)}`)
4384
+ );
4385
+ }
4386
+ if (resultJson?.validationResult) {
4387
+ console.log(chalk6.blue.bold(`
4388
+ Validation for ${variantId}:`));
4389
+ console.log(chalk6.gray(JSON.stringify(resultJson.validationResult, null, 2)));
4390
+ }
4391
+ }
4392
+ } catch {
4393
+ }
4394
+ }
4395
+ } else if (statusText || outcomeText) {
4396
+ if (statusText === "tie") {
4397
+ const tiedVariants = evaluation.winnerRationale?.tiedVariants;
4398
+ const tiedLabel = Array.isArray(tiedVariants) && tiedVariants.length > 0 ? tiedVariants.filter((v) => typeof v === "string" && v.trim().length > 0).join(", ") : "all tied variants";
4399
+ console.log(chalk6.cyan.bold("Tie:"));
4400
+ console.log(chalk6.cyan(` Variants: ${tiedLabel}`));
4401
+ } else {
4402
+ console.log(chalk6.yellow.bold("Warning: No Winner Declared"));
4403
+ }
4404
+ const parts = [];
4405
+ if (statusText) parts.push(`status=${statusText}`);
4406
+ if (outcomeText) parts.push(`outcome=${outcomeText}`);
4407
+ if (marginText !== null) parts.push(`margin=${marginText.toFixed(1)}`);
4408
+ if (top2List && top2List.length >= 2) {
4409
+ const first = top2List[0];
4410
+ const second = top2List[1];
4411
+ const firstLabel = typeof first?.variant === "string" ? `${first.variant}` : "unknown";
4412
+ const firstScore = typeof first?.score === "number" && Number.isFinite(first.score) ? `(${first.score.toFixed(1)})` : "";
4413
+ const secondLabel = typeof second?.variant === "string" ? `${second.variant}` : "unknown";
4414
+ const secondScore = typeof second?.score === "number" && Number.isFinite(second.score) ? `(${second.score.toFixed(1)})` : "";
4415
+ parts.push(`top2=${firstLabel}${firstScore} vs ${secondLabel}${secondScore}`);
4416
+ }
4417
+ if (parts.length > 0) {
4418
+ console.log(chalk6.yellow(` Decision: ${parts.join(" \u2022 ")}`));
4419
+ }
4420
+ if (coverageSummary) {
4421
+ console.log(chalk6.yellow(` Coverage: ${coverageSummary}`));
4422
+ }
4423
+ if (evaluation.winnerRationale?.reasoning) {
4424
+ console.log(
4425
+ chalk6.yellow.dim(" Warning: AI analysis may contain unverified claims.")
4426
+ );
4427
+ console.log(chalk6.gray(` Rationale: ${evaluation.winnerRationale.reasoning}`));
4428
+ }
4429
+ if (variantLabelMapping.length > 0) {
4430
+ console.log(chalk6.gray(" Label Mapping:"));
4431
+ for (const entry of variantLabelMapping) {
4432
+ console.log(chalk6.gray(` ${entry.label} -> ${entry.variant}`));
4433
+ }
4434
+ }
4435
+ console.log();
4436
+ }
4437
+ } catch (error) {
4438
+ if (error instanceof z.ZodError) {
4439
+ console.error(chalk6.red("\nError: Invalid task ID format"));
4440
+ console.error(
4441
+ chalk6.gray(
4442
+ "Task ID must contain only alphanumeric characters, hyphens, and underscores\n"
4443
+ )
4444
+ );
4445
+ } else if (error instanceof AmbiguousLabTaskIdError) {
4446
+ if (options2.json) {
4447
+ console.log(JSON.stringify(error.toJson(), null, 2));
4448
+ } else {
4449
+ console.error(chalk6.red(`
4450
+ Error: ${error.message}
4451
+ `));
4452
+ }
4453
+ } else {
4454
+ console.error(chalk6.red("\nError: Retrieving evaluation results failed:"));
4455
+ console.error(chalk6.gray(error instanceof Error ? error.message : String(error)));
4456
+ console.log();
4457
+ }
4458
+ process.exitCode = 1;
4459
+ } finally {
4460
+ try {
4461
+ resolved?.dispose();
4462
+ } catch {
4463
+ }
4464
+ }
4465
+ });
4466
+ return cmd;
4467
+ }
4468
+ function renderFallbackResults(taskId, candidates, winner, noWinnerReason, state, fusionAnalysisRead, requiredGatePolicyValue, options = {}) {
4469
+ const isFusion = state?.runMetadata?.runSemantics === "fusion";
4470
+ if (isFusion && options.inspect !== true && tryRenderFusionReadHuman(fusionAnalysisRead, {
4471
+ inspect: false
4472
+ })) {
4473
+ return;
4474
+ }
4475
+ const requiredGatePolicy = normalizeRequiredGatePolicy(requiredGatePolicyValue);
4476
+ console.log(chalk6.blue.bold(`
4477
+ ${isFusion ? "Fusion" : "Competition"} Results: ${taskId}
4478
+ `));
4479
+ console.log(
4480
+ chalk6.yellow(
4481
+ isFusion ? "Fusion synthesis uses contributor execution data and peer integration.\n" : "AI Judge row telemetry not available for this competition. Showing persisted competition state:\n"
4482
+ )
4483
+ );
4484
+ const judgeSummary = state ? buildFallbackJudgeSummary(state) : null;
4485
+ const decisionSummary = state ? buildFallbackDecisionSummary(state) : null;
4486
+ if (isFusion && state) {
4487
+ const synthesis = state.runMetadata?.synthesis;
4488
+ const hasIntegratedContributorCount = typeof synthesis?.contributorCount === "number";
4489
+ const contributors = hasIntegratedContributorCount ? synthesis.contributorCount : candidates.filter((candidate) => candidate.success === true).length;
4490
+ console.log(chalk6.blue.bold("Fusion Summary:"));
4491
+ console.log(chalk6.blue(" Run semantics: fusion"));
4492
+ if (synthesis?.status) {
4493
+ console.log(chalk6.blue(` Synthesis: ${synthesis.status}`));
4494
+ }
4495
+ if (typeof synthesis?.artifactPath === "string") {
4496
+ console.log(chalk6.blue(` Synthesis artifact: ${synthesis.artifactPath}`));
4497
+ }
4498
+ if (typeof synthesis?.jsonPath === "string") {
4499
+ console.log(chalk6.blue(` Synthesis JSON: ${synthesis.jsonPath}`));
4500
+ }
4501
+ console.log(
4502
+ chalk6.blue(
4503
+ `${hasIntegratedContributorCount ? " Contributors integrated" : " Contributors completed"}: ${contributors}/${candidates.length}`
4504
+ )
4505
+ );
4506
+ if (options.inspect === true && tryRenderFusionReadHuman(fusionAnalysisRead, {
4507
+ inspect: true
4508
+ })) {
4509
+ } else {
4510
+ renderFusionAnalysisSynthesisDetails({
4511
+ taskId,
4512
+ requestedTaskId: taskId,
4513
+ read: fusionAnalysisRead ?? null
4514
+ });
4515
+ }
4516
+ console.log();
4517
+ } else if (judgeSummary || decisionSummary) {
4518
+ console.log(chalk6.blue.bold("Persisted Decision:"));
4519
+ const requested = typeof judgeSummary?.requested === "string" ? judgeSummary.requested : void 0;
4520
+ const status = typeof judgeSummary?.status === "string" ? judgeSummary.status : void 0;
4521
+ const decisionStatus = typeof decisionSummary?.decisionStatus === "string" ? decisionSummary.decisionStatus : void 0;
4522
+ const decisionOutcome = typeof decisionSummary?.decisionOutcome === "string" ? decisionSummary.decisionOutcome : void 0;
4523
+ const selectedVariant = typeof decisionSummary?.selectedVariant === "string" ? decisionSummary.selectedVariant : void 0;
4524
+ const reason = typeof decisionSummary?.reason === "string" ? decisionSummary.reason : void 0;
4525
+ const winnerVariant = winner?.variant ?? [winner?.provider, winner?.resolvedModel ?? winner?.model].filter((part) => Boolean(part)).join(":");
4526
+ const selectedCandidate = findDecisionCandidateForResults(
4527
+ candidates,
4528
+ selectedVariant,
4529
+ winnerVariant
4530
+ );
4531
+ console.log(chalk6.blue(` Judge: ${requested ?? "unknown"}${status ? ` (${status})` : ""}`));
4532
+ if (decisionStatus || decisionOutcome) {
4533
+ const suppressVerifiedDecisionSuffix = decisionOutcome === "verified" && hasAnalysisIntentEvidence(state, candidates);
4534
+ const contradictsVerifiedDecision = decisionOutcome === "verified" && !suppressVerifiedDecisionSuffix && selectedCandidate !== null && candidateHasFailingVerificationForDisplay(selectedCandidate, requiredGatePolicy);
4535
+ const decisionOutcomeSuffix = decisionOutcome && !suppressVerifiedDecisionSuffix && !contradictsVerifiedDecision ? ` / ${decisionOutcome}` : "";
4536
+ console.log(chalk6.blue(` Outcome: ${decisionStatus ?? "unknown"}${decisionOutcomeSuffix}`));
4537
+ if (suppressVerifiedDecisionSuffix) {
4538
+ console.log(chalk6.blue(" Verification: not applicable (analysis intent)"));
4539
+ } else if (contradictsVerifiedDecision) {
4540
+ console.log(chalk6.blue(" Verification: unverified (required gate evidence failed)"));
4541
+ }
4542
+ }
4543
+ if (selectedVariant && !isFusion) {
4544
+ console.log(chalk6.blue(` Selected: ${selectedVariant}`));
4545
+ }
4546
+ if (reason) {
4547
+ console.log(chalk6.gray(` Reason: ${reason}`));
4548
+ }
4549
+ console.log();
4550
+ }
4551
+ const applicationLine = formatApplicationVerificationLine(state?.application);
4552
+ if (applicationLine) console.log(chalk6.yellow(`${applicationLine}
4553
+ `));
4554
+ if (winner && !isFusion && noWinnerReason === "judge_off") {
4555
+ const identityVariant = winner.variant ?? [winner.provider, winner.resolvedModel ?? winner.model].filter((part) => Boolean(part)).join(":");
4556
+ console.log(
4557
+ [
4558
+ chalk6.yellow.bold("Ungraded Result:"),
4559
+ chalk6.yellow(` Identity: ${identityVariant || "unknown"}`),
4560
+ chalk6.gray(" Judge status: disabled (--judge off); no judge ran."),
4561
+ ""
4562
+ ].join("\n")
4563
+ );
4564
+ } else if (winner && !isFusion) {
4565
+ const winnerVariant = winner.variant ?? [winner.provider, winner.resolvedModel ?? winner.model].filter((part) => Boolean(part)).join(":");
4566
+ console.log(
4567
+ [chalk6.green.bold("Winner:"), chalk6.green(` Variant: ${winnerVariant || "unknown"}`)].join(
4568
+ "\n"
4569
+ )
4570
+ );
4571
+ console.log(
4572
+ chalk6.gray(
4573
+ decisionSummary?.decisionStatus === "declared" ? " Provenance: competition handle; persisted judge decision" : " Provenance: competition handle; judge row telemetry unavailable"
4574
+ )
4575
+ );
4576
+ console.log();
4577
+ } else if (!isFusion && noWinnerReason === "judge_off") {
4578
+ console.log(chalk6.yellow.bold("No Final Winner"));
4579
+ console.log(chalk6.yellow(" Judge status: disabled (--judge off); no winner was selected."));
4580
+ console.log();
4581
+ }
4582
+ if (candidates.length === 0) {
4583
+ console.log(chalk6.gray("No variant entries recorded in competition handle."));
4584
+ return;
4585
+ }
4586
+ for (const candidate of candidates) {
4587
+ const candidateRecord = candidate;
4588
+ const provider = String(candidateRecord.provider ?? "unknown");
4589
+ const requestedProvider = typeof candidateRecord.requestedProvider === "string" ? candidateRecord.requestedProvider : null;
4590
+ const requestedModel = typeof candidateRecord.requestedModel === "string" ? candidateRecord.requestedModel : null;
4591
+ const executedModel = typeof candidateRecord.resolvedModel === "string" ? candidateRecord.resolvedModel : typeof candidateRecord.model === "string" ? candidateRecord.model : null;
4592
+ const hasRequestedExecutedMismatch = requestedProvider !== null && (requestedProvider !== provider || requestedModel !== null && requestedModel !== executedModel);
4593
+ const variantLabel = typeof candidateRecord.variant === "string" && candidateRecord.variant.trim().length > 0 ? candidateRecord.variant.trim() : `${provider}:${executedModel ?? "default"}`;
4594
+ const hasReportedSuccess = typeof candidateRecord.success === "boolean";
4595
+ const providerCompleted = isFusion ? candidateRecord.success === true : Boolean(candidateRecord.success);
4596
+ const verificationFailed = candidateHasFailingVerificationForDisplay(
4597
+ candidateRecord,
4598
+ requiredGatePolicy
4599
+ );
4600
+ const success = providerCompleted && !verificationFailed;
4601
+ const terminationReason = candidateRecord.terminationReason;
4602
+ const isCanceled = typeof terminationReason === "string" && (terminationReason === "canceled_early_exit" || terminationReason === "canceled_budget" || terminationReason === "canceled_user");
4603
+ const isTimedOut = candidateRecord.timedOut === true || typeof terminationReason === "string" && terminationReason === "timeout";
4604
+ const status = success ? chalk6.green("Success") : isFusion ? hasReportedSuccess ? chalk6.gray("Not completed") : chalk6.gray("Unknown") : isCanceled ? chalk6.yellow("Canceled") : chalk6.red("Failed");
4605
+ const completenessValue = candidateRecord.completeness;
4606
+ const completeness = typeof completenessValue === "number" ? `${completenessValue}%` : "not reported";
4607
+ const prNumber = candidateRecord.prNumber;
4608
+ const prInfo = typeof prNumber === "number" ? `PR #${prNumber}${typeof candidateRecord.prUrl === "string" && candidateRecord.prUrl.length > 0 ? ` (${candidateRecord.prUrl})` : ""}` : "No PR recorded";
4609
+ const durationValue = candidateRecord.duration;
4610
+ const duration = typeof durationValue === "number" ? `${durationValue.toFixed(1)}s` : "n/a";
4611
+ console.log(chalk6.white.bold(`- ${variantLabel}`));
4612
+ if (hasRequestedExecutedMismatch) {
4613
+ console.log(
4614
+ chalk6.gray(
4615
+ ` Requested: ${[requestedProvider, requestedModel].filter(Boolean).join(":")}`
4616
+ )
4617
+ );
4618
+ console.log(
4619
+ chalk6.gray(` Executed: ${[provider, executedModel].filter(Boolean).join(":")}`)
4620
+ );
4621
+ }
4622
+ console.log(chalk6.gray(` ${status}`));
4623
+ if (terminationReason && typeof terminationReason === "string") {
4624
+ const reasonColor = isCanceled ? chalk6.yellow : chalk6.red;
4625
+ console.log(reasonColor(` Termination: ${terminationReason}`));
4626
+ }
4627
+ if (isFusion) {
4628
+ const contribution = formatFusionFallbackContribution(candidateRecord.success).replace(
4629
+ /_/g,
4630
+ " "
4631
+ );
4632
+ console.log(chalk6.gray(` Contribution: ${contribution}`));
4633
+ } else {
4634
+ console.log(chalk6.gray(` Completeness: ${completeness}`));
4635
+ }
4636
+ const testVerificationLine = formatVariantTestVerificationLine(candidateRecord);
4637
+ if (testVerificationLine) {
4638
+ const testColor = testVerificationLine.endsWith("passed") ? chalk6.green : testVerificationLine.endsWith("failed") ? chalk6.red : chalk6.yellow;
4639
+ console.log(testColor(` ${testVerificationLine}`));
4640
+ }
4641
+ printCandidateEvidenceLines(candidateRecord);
4642
+ const undeliveredLine = options.undeliveredLineFor?.(variantLabel);
4643
+ if (undeliveredLine) console.log(chalk6.gray(` ${undeliveredLine}`));
4644
+ const inputSpecWarning = normaliseInputSpecWarning(candidateRecord.inputSpecWarning);
4645
+ if (inputSpecWarning?.hasFillPlaceholders) {
4646
+ const missingFields = inputSpecWarning.missingFields && inputSpecWarning.missingFields.length > 0 ? `; missing: ${inputSpecWarning.missingFields.join(", ")}` : "";
4647
+ console.log(
4648
+ chalk6.yellow(
4649
+ ` Input spec warning: incomplete (${typeof inputSpecWarning.completenessScore === "number" ? `${Math.round(inputSpecWarning.completenessScore * 100)}%` : "unknown"}${missingFields})`
4650
+ )
4651
+ );
4652
+ }
4653
+ console.log(chalk6.gray(` Duration: ${duration}`));
4654
+ console.log(chalk6.gray(` ${prInfo}`));
4655
+ const partialStats = extractPartialEditStats(candidateRecord);
4656
+ if (isTimedOut && (candidateRecord.partialEdits === true || partialStats)) {
4657
+ console.log(
4658
+ chalk6.yellow(
4659
+ ` Partial edits: ${partialStats?.filesChanged ?? 0} files, +${partialStats?.linesAdded ?? 0}/-${partialStats?.linesRemoved ?? 0}`
4660
+ )
4661
+ );
4662
+ }
4663
+ if (typeof candidateRecord.errorMessage === "string") {
4664
+ console.log(chalk6.gray(` Error: ${candidateRecord.errorMessage}`));
4665
+ }
4666
+ console.log();
4667
+ }
4668
+ }
4669
+
4670
+ export {
4671
+ resolveCompetitionStatusFromCompetitionState,
4672
+ competitionStatusStateFromBasicResult,
4673
+ resolveDefaultCompetitionId,
4674
+ secondaryJudgePicks,
4675
+ getLatestMultiJudgeRunForTask,
4676
+ renderMultiJudgeRun,
4677
+ resolveCompetitionResultsTaskId,
4678
+ formatJudgeEvaluationModelLine,
4679
+ readLatestProfileMatrixSummary,
4680
+ resolveWarningVerbosity,
4681
+ getDisplayableSelfConfidence,
4682
+ formatProviderExecutionPathLine,
4683
+ candidateHasFailingVerificationForDisplay,
4684
+ shouldRenderUnretainedJudgeTopPick,
4685
+ formatVariantTestVerificationLine,
4686
+ formatDonorDecisionDiagnostics,
4687
+ summarizeDonorSelectionDecisions,
4688
+ summarizeSynthesisArtifact,
4689
+ formatSynthesisTelemetrySummaryLines,
4690
+ formatDonorMaterialSummaryLine,
4691
+ buildSynthesisResultsJson,
4692
+ buildFusionSynthesisResultsJson,
4693
+ createCompeteResultsCommand,
4694
+ renderFallbackResults
4695
+ };
4696
+ //# sourceMappingURL=chunk-762ACDZJ.js.map