@ggui-ai/ui-gen 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (308) hide show
  1. package/dist/{adapter-h4_V69LI.d.ts → adapter-DLQ-5COm.d.ts} +1 -1
  2. package/dist/adapters/base.js +2 -27
  3. package/dist/adapters/base.js.map +1 -1
  4. package/dist/adapters/generation-dispatch.d.ts +14 -6
  5. package/dist/adapters/generation-dispatch.js +40 -19260
  6. package/dist/adapters/generation-dispatch.js.map +1 -1
  7. package/dist/adapters/index.d.ts +1 -1
  8. package/dist/adapters/index.js +25 -3561
  9. package/dist/adapters/index.js.map +1 -1
  10. package/dist/adapters/types.js +2 -9
  11. package/dist/adapters/types.js.map +1 -1
  12. package/dist/advanced/index.d.ts +13 -12
  13. package/dist/advanced/index.js +63 -21954
  14. package/dist/advanced/index.js.map +1 -1
  15. package/dist/{bank-Ctdp3FUA.d.ts → bank-LWaiAtaA.d.ts} +1 -1
  16. package/dist/blueprint-validator.js +6 -2301
  17. package/dist/blueprint-validator.js.map +1 -1
  18. package/dist/boilerplate.d.ts +3 -2
  19. package/dist/boilerplate.js +6 -1867
  20. package/dist/boilerplate.js.map +1 -1
  21. package/dist/check/index.d.ts +3 -2
  22. package/dist/check/index.js +6 -1923
  23. package/dist/check/index.js.map +1 -1
  24. package/dist/chunk-33B3BAWS.js +24 -0
  25. package/dist/chunk-33B3BAWS.js.map +1 -0
  26. package/dist/chunk-3HSGA6NI.js +591 -0
  27. package/dist/chunk-3HSGA6NI.js.map +1 -0
  28. package/dist/chunk-3NNNGNTO.js +1707 -0
  29. package/dist/chunk-3NNNGNTO.js.map +1 -0
  30. package/dist/chunk-3T2HMTON.js +79 -0
  31. package/dist/chunk-3T2HMTON.js.map +1 -0
  32. package/dist/chunk-3ZSSDV3L.js +123 -0
  33. package/dist/chunk-3ZSSDV3L.js.map +1 -0
  34. package/dist/chunk-4MBR5GA3.js +99 -0
  35. package/dist/chunk-4MBR5GA3.js.map +1 -0
  36. package/dist/chunk-56NJFD55.js +337 -0
  37. package/dist/chunk-56NJFD55.js.map +1 -0
  38. package/dist/chunk-5AGTY555.js +26 -0
  39. package/dist/chunk-5AGTY555.js.map +1 -0
  40. package/dist/chunk-5EJM7EGY.js +115 -0
  41. package/dist/chunk-5EJM7EGY.js.map +1 -0
  42. package/dist/chunk-5KXCQLLR.js +529 -0
  43. package/dist/chunk-5KXCQLLR.js.map +1 -0
  44. package/dist/chunk-5VBXHVEH.js +171 -0
  45. package/dist/chunk-5VBXHVEH.js.map +1 -0
  46. package/dist/chunk-6KDDEING.js +515 -0
  47. package/dist/chunk-6KDDEING.js.map +1 -0
  48. package/dist/chunk-6VDRWAP6.js +123 -0
  49. package/dist/chunk-6VDRWAP6.js.map +1 -0
  50. package/dist/chunk-732IBFEJ.js +2400 -0
  51. package/dist/chunk-732IBFEJ.js.map +1 -0
  52. package/dist/chunk-73AURS3I.js +46 -0
  53. package/dist/chunk-73AURS3I.js.map +1 -0
  54. package/dist/chunk-77H5SKLX.js +8 -0
  55. package/dist/chunk-77H5SKLX.js.map +1 -0
  56. package/dist/chunk-7QE3AHLE.js +35 -0
  57. package/dist/chunk-7QE3AHLE.js.map +1 -0
  58. package/dist/chunk-A375NNWN.js +11 -0
  59. package/dist/chunk-A375NNWN.js.map +1 -0
  60. package/dist/chunk-AOU33EFS.js +140 -0
  61. package/dist/chunk-AOU33EFS.js.map +1 -0
  62. package/dist/chunk-BA4QYA6E.js +461 -0
  63. package/dist/chunk-BA4QYA6E.js.map +1 -0
  64. package/dist/chunk-DBP764GL.js +3 -0
  65. package/dist/chunk-DBP764GL.js.map +1 -0
  66. package/dist/chunk-DUU3ZJDQ.js +41 -0
  67. package/dist/chunk-DUU3ZJDQ.js.map +1 -0
  68. package/dist/chunk-DXKRBXNU.js +30 -0
  69. package/dist/chunk-DXKRBXNU.js.map +1 -0
  70. package/dist/chunk-FB7OEEAH.js +1467 -0
  71. package/dist/chunk-FB7OEEAH.js.map +1 -0
  72. package/dist/chunk-FLRNMZV2.js +18 -0
  73. package/dist/chunk-FLRNMZV2.js.map +1 -0
  74. package/dist/chunk-FWJIMKFZ.js +2032 -0
  75. package/dist/chunk-FWJIMKFZ.js.map +1 -0
  76. package/dist/chunk-FXRHWYIQ.js +163 -0
  77. package/dist/chunk-FXRHWYIQ.js.map +1 -0
  78. package/dist/chunk-G3PMV62Z.js +33 -0
  79. package/dist/chunk-G3PMV62Z.js.map +1 -0
  80. package/dist/chunk-GAJI7Y3P.js +13 -0
  81. package/dist/chunk-GAJI7Y3P.js.map +1 -0
  82. package/dist/chunk-GYINWMPR.js +2052 -0
  83. package/dist/chunk-GYINWMPR.js.map +1 -0
  84. package/dist/chunk-HD6ABIK7.js +484 -0
  85. package/dist/chunk-HD6ABIK7.js.map +1 -0
  86. package/dist/chunk-HDQVHYO6.js +100 -0
  87. package/dist/chunk-HDQVHYO6.js.map +1 -0
  88. package/dist/chunk-IHUT3SIW.js +7 -0
  89. package/dist/chunk-IHUT3SIW.js.map +1 -0
  90. package/dist/chunk-JDH5EGNZ.js +126 -0
  91. package/dist/chunk-JDH5EGNZ.js.map +1 -0
  92. package/dist/chunk-JMD4RGSV.js +37 -0
  93. package/dist/chunk-JMD4RGSV.js.map +1 -0
  94. package/dist/chunk-KJWGZL5B.js +33 -0
  95. package/dist/chunk-KJWGZL5B.js.map +1 -0
  96. package/dist/chunk-MKMDQFZ7.js +86 -0
  97. package/dist/chunk-MKMDQFZ7.js.map +1 -0
  98. package/dist/chunk-NF6JUZWF.js +85 -0
  99. package/dist/chunk-NF6JUZWF.js.map +1 -0
  100. package/dist/chunk-O2YC6XDC.js +1933 -0
  101. package/dist/chunk-O2YC6XDC.js.map +1 -0
  102. package/dist/chunk-OVLH5ICV.js +29 -0
  103. package/dist/chunk-OVLH5ICV.js.map +1 -0
  104. package/dist/chunk-PBOYHGSD.js +106 -0
  105. package/dist/chunk-PBOYHGSD.js.map +1 -0
  106. package/dist/chunk-PJFH7QWA.js +81 -0
  107. package/dist/chunk-PJFH7QWA.js.map +1 -0
  108. package/dist/chunk-PUH4CXGZ.js +284 -0
  109. package/dist/chunk-PUH4CXGZ.js.map +1 -0
  110. package/dist/chunk-QLXXPGTV.js +18 -0
  111. package/dist/chunk-QLXXPGTV.js.map +1 -0
  112. package/dist/chunk-R5GIGPW2.js +2845 -0
  113. package/dist/chunk-R5GIGPW2.js.map +1 -0
  114. package/dist/chunk-RH4IUSTO.js +83 -0
  115. package/dist/chunk-RH4IUSTO.js.map +1 -0
  116. package/dist/chunk-S2GVXKKY.js +153 -0
  117. package/dist/chunk-S2GVXKKY.js.map +1 -0
  118. package/dist/chunk-TVHGKFJS.js +58 -0
  119. package/dist/chunk-TVHGKFJS.js.map +1 -0
  120. package/dist/chunk-U7GALWLG.js +66 -0
  121. package/dist/chunk-U7GALWLG.js.map +1 -0
  122. package/dist/chunk-VTC263LT.js +256 -0
  123. package/dist/chunk-VTC263LT.js.map +1 -0
  124. package/dist/chunk-WEOXFEVE.js +739 -0
  125. package/dist/chunk-WEOXFEVE.js.map +1 -0
  126. package/dist/chunk-WYHP46LT.js +28 -0
  127. package/dist/chunk-WYHP46LT.js.map +1 -0
  128. package/dist/chunk-XGLO5LGG.js +274 -0
  129. package/dist/chunk-XGLO5LGG.js.map +1 -0
  130. package/dist/chunk-XRBCRKA2.js +29 -0
  131. package/dist/chunk-XRBCRKA2.js.map +1 -0
  132. package/dist/chunk-XW7ADFFV.js +340 -0
  133. package/dist/chunk-XW7ADFFV.js.map +1 -0
  134. package/dist/chunk-YIQ42IUX.js +34 -0
  135. package/dist/chunk-YIQ42IUX.js.map +1 -0
  136. package/dist/chunk-YJZTUY7B.js +101 -0
  137. package/dist/chunk-YJZTUY7B.js.map +1 -0
  138. package/dist/chunk-Z3CXME3K.js +107 -0
  139. package/dist/chunk-Z3CXME3K.js.map +1 -0
  140. package/dist/classifier/index.js +2 -527
  141. package/dist/classifier/index.js.map +1 -1
  142. package/dist/client-JBPCXU7W.js +4 -0
  143. package/dist/client-JBPCXU7W.js.map +1 -0
  144. package/dist/compose.js +3 -367
  145. package/dist/compose.js.map +1 -1
  146. package/dist/cost-tracker-HHGQ4FTW.js +67 -0
  147. package/dist/cost-tracker-HHGQ4FTW.js.map +1 -0
  148. package/dist/{create-ui-generator-BrZHF0cf.d.ts → create-ui-generator-BY-WeaPi.d.ts} +3 -3
  149. package/dist/{design-mode-DGWN_Gkm.d.ts → design-mode-XyOQmzE0.d.ts} +4 -3
  150. package/dist/{dispatch-B07TI30d.d.ts → dispatch-8LzTddKw.d.ts} +3 -2
  151. package/dist/dist-UALN6ZVB.js +543 -0
  152. package/dist/dist-UALN6ZVB.js.map +1 -0
  153. package/dist/dupe-break-X6K7QFIS.js +4 -0
  154. package/dist/dupe-break-X6K7QFIS.js.map +1 -0
  155. package/dist/evaluation/axis-checks/index.d.ts +5 -4
  156. package/dist/evaluation/axis-checks/index.js +6 -1914
  157. package/dist/evaluation/axis-checks/index.js.map +1 -1
  158. package/dist/evaluation/axis-checks/registry.d.ts +3 -2
  159. package/dist/evaluation/axis-checks/registry.js +3 -1844
  160. package/dist/evaluation/axis-checks/registry.js.map +1 -1
  161. package/dist/evaluation/index.d.ts +49 -132
  162. package/dist/evaluation/index.js +302 -6466
  163. package/dist/evaluation/index.js.map +1 -1
  164. package/dist/evaluation/types.d.ts +3 -2
  165. package/dist/evaluation/types.js +2 -5
  166. package/dist/evaluation/types.js.map +1 -1
  167. package/dist/fragments/index.js +2 -338
  168. package/dist/fragments/index.js.map +1 -1
  169. package/dist/{generate-tSO_shQ0.d.ts → generate-DQ4ci90s.d.ts} +1 -1
  170. package/dist/harness/check/runtime-render/index.d.ts +35 -15
  171. package/dist/harness/check/runtime-render/index.js +6 -2390
  172. package/dist/harness/check/runtime-render/index.js.map +1 -1
  173. package/dist/harness/check/runtime-render/render-check-worker.js +4 -1739
  174. package/dist/harness/check/runtime-render/render-check-worker.js.map +1 -1
  175. package/dist/harness/index.d.ts +3 -2
  176. package/dist/harness/index.js +23 -5126
  177. package/dist/harness/index.js.map +1 -1
  178. package/dist/harness/llm-trace-sink.js +2 -24
  179. package/dist/harness/llm-trace-sink.js.map +1 -1
  180. package/dist/harness/prompts.d.ts +2 -2
  181. package/dist/harness/prompts.js +8 -324
  182. package/dist/harness/prompts.js.map +1 -1
  183. package/dist/harness/result-types.d.ts +6 -5
  184. package/dist/harness/result-types.js +2 -0
  185. package/dist/harness/result-types.js.map +1 -1
  186. package/dist/harness/runtime.d.ts +22 -5
  187. package/dist/harness/runtime.js +10 -2313
  188. package/dist/harness/runtime.js.map +1 -1
  189. package/dist/harness/types-public.d.ts +3 -2
  190. package/dist/harness/types-public.js +16 -2954
  191. package/dist/harness/types-public.js.map +1 -1
  192. package/dist/harness/validator-trace-sink.d.ts +3 -2
  193. package/dist/harness/validator-trace-sink.js +2 -26
  194. package/dist/harness/validator-trace-sink.js.map +1 -1
  195. package/dist/hash.js +2 -39
  196. package/dist/hash.js.map +1 -1
  197. package/dist/hashline-5OKREIRM.js +4 -0
  198. package/dist/hashline-5OKREIRM.js.map +1 -0
  199. package/dist/index.d.ts +50 -11
  200. package/dist/index.js +57 -22015
  201. package/dist/index.js.map +1 -1
  202. package/dist/llm-evaluator-PN3WFCS4.js +653 -0
  203. package/dist/llm-evaluator-PN3WFCS4.js.map +1 -0
  204. package/dist/magic-string.es-2NZTC4GZ.js +1307 -0
  205. package/dist/magic-string.es-2NZTC4GZ.js.map +1 -0
  206. package/dist/patch.d.ts +3 -2
  207. package/dist/patch.js +2 -56
  208. package/dist/patch.js.map +1 -1
  209. package/dist/policy-VCYKGSAC.js +5 -0
  210. package/dist/policy-VCYKGSAC.js.map +1 -0
  211. package/dist/policy.js +2 -35
  212. package/dist/policy.js.map +1 -1
  213. package/dist/primitive-index-2OF6F4TZ.js +131 -0
  214. package/dist/primitive-index-2OF6F4TZ.js.map +1 -0
  215. package/dist/primitive-slice-WTMBLYFJ.js +235 -0
  216. package/dist/primitive-slice-WTMBLYFJ.js.map +1 -0
  217. package/dist/{prompts-BhNUuRoZ.d.ts → prompts-CLZGywMP.d.ts} +1 -1
  218. package/dist/provider-adapter-contract.js +10407 -14204
  219. package/dist/provider-adapter-contract.js.map +1 -1
  220. package/dist/provider-adapter.js +2 -44
  221. package/dist/provider-adapter.js.map +1 -1
  222. package/dist/providers/index.d.ts +89 -1
  223. package/dist/providers/index.js +115 -44
  224. package/dist/providers/index.js.map +1 -1
  225. package/dist/raw-C6KBH5I3.js +141 -0
  226. package/dist/raw-C6KBH5I3.js.map +1 -0
  227. package/dist/raw-FXSBXQTZ.js +7 -0
  228. package/dist/raw-FXSBXQTZ.js.map +1 -0
  229. package/dist/raw-MURDUPGK.js +8 -0
  230. package/dist/raw-MURDUPGK.js.map +1 -0
  231. package/dist/raw-T3GW3UVX.js +8 -0
  232. package/dist/raw-T3GW3UVX.js.map +1 -0
  233. package/dist/render-check-host-ZNIS6BJ5.js +5 -0
  234. package/dist/render-check-host-ZNIS6BJ5.js.map +1 -0
  235. package/dist/sdk-4JNSDNSR.js +6 -0
  236. package/dist/sdk-4JNSDNSR.js.map +1 -0
  237. package/dist/sdk-DIVJMHCX.js +7 -0
  238. package/dist/sdk-DIVJMHCX.js.map +1 -0
  239. package/dist/sdk-QRJOCRTS.js +7 -0
  240. package/dist/sdk-QRJOCRTS.js.map +1 -0
  241. package/dist/tag-balance-CTHCTRJ7.js +123 -0
  242. package/dist/tag-balance-CTHCTRJ7.js.map +1 -0
  243. package/dist/tools/get-primitives-ts.d.ts +1 -1
  244. package/dist/tools/get-primitives-ts.js +3 -1
  245. package/dist/tools/get-primitives-ts.js.map +1 -1
  246. package/dist/tools/render-check-worker.js +3 -40
  247. package/dist/tools/render-check-worker.js.map +1 -1
  248. package/dist/{types-public-h8IMnYuh.d.ts → types-public-hYlrerZh.d.ts} +35 -2
  249. package/dist/validation/index.d.ts +2 -2
  250. package/dist/validation/index.js +3 -498
  251. package/dist/validation/index.js.map +1 -1
  252. package/dist/{visual-evaluator-C2strxqD.d.ts → visual-evaluator-KskajxD5.d.ts} +14 -4
  253. package/dist/visual-evaluator-TGEXYQTP.js +12 -0
  254. package/dist/visual-evaluator-TGEXYQTP.js.map +1 -0
  255. package/dist/workflows.d.ts +3 -2
  256. package/dist/workflows.js +2 -151
  257. package/dist/workflows.js.map +1 -1
  258. package/package.json +20 -16
  259. package/src/adapters/claude/sdk.ts +4 -2
  260. package/src/adapters/claude/tool-bridge.ts +2 -1
  261. package/src/adapters/generation-dispatch.ts +9 -0
  262. package/src/adapters/openai/raw.ts +4 -0
  263. package/src/adapters/openai/sdk.ts +6 -1
  264. package/src/adapters/openai/tokens.ts +21 -7
  265. package/src/adapters/tool-bridge.ts +1 -1
  266. package/src/adapters/tools.ts +1 -1
  267. package/src/advanced/feedback.ts +1 -2
  268. package/src/advanced/generator.ts +4 -3
  269. package/src/boilerplate/free-design-prompt.ts +7 -0
  270. package/src/boilerplate/generate.ts +18 -5
  271. package/src/boilerplate/hard-sections.ts +8 -3
  272. package/src/boilerplate/react-hooks.ts +56 -0
  273. package/src/boilerplate/system-prompt.ts +12 -3
  274. package/src/check/run-tier0.ts +233 -8
  275. package/src/check/type-checker.ts +128 -16
  276. package/src/coding-agent/tools.ts +26 -3
  277. package/src/design-mode.ts +4 -9
  278. package/src/evaluation/axis-checks/checks/state-merge.ts +2 -4
  279. package/src/evaluation/axis-checks/checks/state-payload.ts +1 -28
  280. package/src/evaluation/axis-checks/checks/tint.ts +197 -0
  281. package/src/evaluation/axis-checks/helpers.ts +121 -0
  282. package/src/evaluation/axis-checks/registry.ts +2 -0
  283. package/src/evaluation/criteria/__fixtures__/edge-v2-draw2.json +4629 -0
  284. package/src/evaluation/criteria/bank.ts +1 -1
  285. package/src/evaluation/criteria/edge-instruments.ts +14 -0
  286. package/src/evaluation/criteria/edge-probe-v2.ts +352 -0
  287. package/src/evaluation/criteria/edge-v2.ts +242 -0
  288. package/src/evaluation/criteria/resolve.ts +24 -5
  289. package/src/evaluation/index.ts +3 -5
  290. package/src/evaluation/mcp-server.ts +0 -50
  291. package/src/evaluation/types-public.ts +6 -1
  292. package/src/evaluation/visual-evaluator.ts +161 -30
  293. package/src/harness/check/runtime-render/index.ts +28 -4
  294. package/src/harness/check/runtime-render/render-check.ts +20 -21
  295. package/src/harness/claude-agent-sdk-loader.ts +93 -0
  296. package/src/harness/claude-code-login-query.ts +1 -1
  297. package/src/harness/coding/generate-task-runner.ts +1 -0
  298. package/src/harness/coding/run-coding-turn.ts +3 -0
  299. package/src/harness/coding/run-eval-round.ts +9 -0
  300. package/src/harness/llm-router.ts +50 -2
  301. package/src/harness/runtime.ts +17 -0
  302. package/src/index.ts +9 -0
  303. package/src/providers/anthropic-tool-call.ts +263 -0
  304. package/src/providers/index.ts +13 -0
  305. package/src/tools/get-primitives-ts.ts +1 -1
  306. package/src/tools/render-check.ts +4 -4
  307. package/src/validation/primitives.ts +2 -1
  308. package/src/evaluation/loop.ts +0 -218
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/harness/coding/assemble-result.ts","../src/coding-agent/self-check.ts","../src/coding-agent/tools.ts","../src/harness/coding/run-coding-turn.ts","../src/harness/enforced-coding.ts","../src/harness/coding/run-eval-round.ts","../src/harness/coding/generate-task-runner.ts","../src/coding-agent/workspace.ts","../src/harness/in-loop-evaluation.ts","../src/harness/coding/init-session.ts","../src/adapters/generation-dispatch.ts"],"names":["applyPatch","allIssues","PRIMITIVES_DOCUMENTATION"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,eAAsB,yBACpB,KAAA,EAC2B;AAC3B,EAAA,MAAM,EAAE,OAAA,EAAS,SAAA,EAAW,MAAA,EAAO,GAAI,KAAA;AACvC,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,OAAA,CAAQ,OAAA,CAAQ,IAAA,KAAS,QAAA;AAGhD,EAAA,IAAI,0BAAA,GAA6B,KAAA;AACjC,EAAA,IACE,QAAQ,WAAA,KAAgB,cAAA,IAC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B,CAAA;AAMD,EAAA,IAAI,CAAC,UAAU,EAAA,EAAI;AACjB,IAAA,OAAA,CAAQ,KAAA;AAAA,MACN,qCAAqC,SAAA,CAAU,MAAM,YACxC,SAAA,CAAU,WAAA,GAAc,UAAU,WAAA,CAAY,MAAA,GAAS,GAAA,GAAM,MAAM,cAClE,SAAA,CAAU,aAAA,GAAgB,UAAU,aAAA,CAAc,MAAA,GAAS,MAAM,MAAM,CAAA,CAAA;AAAA,KACvF;AAAA,EACF;AAMA,EAAA,MAAM,WAAA,GAAc,UAAU,WAAA,IAAe,EAAA;AAI7C,EAAA,MAAM,MAAA,GAA2B,MAAM,wBAAA,CAAyB;AAAA,IAC9D,OAAA;AAAA,IACA,SAAA;AAAA,IACA,MAAA,EAAQ;AAAA,GACT,CAAA;AAKD,EAAA,OAAO,aAAA,CAAc,QAAQ,MAAM,CAAA;AACrC;AAWA,SAAS,aAAA,CACP,QACA,MAAA,EACkB;AAClB,EAAA,MAAM,cAAA,GACJ,MAAA,CAAO,MAAA,KACN,MAAA,CAAO,UAAA,KAAe,MAAA,GACnB,kBAAA,CAAmB,MAAA,CAAO,SAAA,EAAW,MAAA,CAAO,MAAM,CAAA,GAClD,MAAA,CAAA;AACN,EAAA,OAAO;AAAA,IACL,GAAG,MAAA;AAAA,IACH,GAAI,OAAO,UAAA,KAAe,MAAA,GAAY,EAAE,UAAA,EAAY,MAAA,CAAO,UAAA,EAAW,GAAI,EAAC;AAAA,IAC3E,GAAI,cAAA,KAAmB,MAAA,GAAY,EAAE,MAAA,EAAQ,cAAA,KAAmB;AAAC,GACnE;AACF","file":"chunk-R5GIGPW2.js","sourcesContent":["// Convert a finished CodingSession + GenerateTelemetry into the\n// GenerationResult shape callers expect at the dispatchGeneration\n// boundary.\n\nimport { getActionableIssues } from \"../../evaluation/types-public.js\";\nimport type { GenerationResult } from \"../result-types.js\";\nimport type { CodingSession } from \"./init-session.js\";\nimport type { GenerateTelemetry } from \"./generate-task-runner.js\";\n\nexport interface AssembleResultInput {\n readonly session: CodingSession;\n readonly telemetry: GenerateTelemetry;\n /** Final source — the closure returns this; pass it through here. */\n readonly source: string;\n}\n\n/**\n * Build the GenerationResult, log the final timing + SUMMARY lines, and\n * cleanup the coding agent. Mirrors the tail of runSimpleHarness exactly.\n *\n * Caller must invoke this AFTER the generate runner has finished and\n * BEFORE returning to its own caller — agent cleanup is non-optional.\n */\nexport async function assembleGenerationResult(\n input: AssembleResultInput,\n): Promise<GenerationResult> {\n const { session, telemetry, source } = input;\n const a1Mode = session.harness.process.mode === \"staged\";\n\n // ── auto-improve: signal background work if warns remain after pass ──\n let needsBackgroundImprovement = false;\n if (\n session.qualityMode === \"auto-improve\" &&\n telemetry.evalResult &&\n session.tiersMod\n ) {\n const remaining = getActionableIssues(\n telemetry.evalResult,\n \"high-quality\",\n );\n if (remaining.length > 0) {\n needsBackgroundImprovement = true;\n console.log(\n `[simple] auto-improve: ${remaining.length} remaining issues → background improvement needed`,\n );\n }\n }\n\n // ── Timing ──\n // `telemetry.codingMs` captures the FULL inner loop (coding turns + eval\n // rounds + eval-fix turns). Coding-only time is computed by subtracting\n // accumulated eval wall. `setupMs` catches everything outside the loop\n // (session init, pre-warm, agent cleanup is after this block so it's not\n // included but typically < 100ms). Invariant: codingOnlyMs + evalWallMs\n // + setupMs ≈ totalMs (within a few ms of measurement slop).\n const totalMs = Date.now() - session.startedAtMs;\n const evalWallMs = telemetry.cumulativeEvalWallMs;\n const codingOnlyMs = Math.max(0, telemetry.codingMs - evalWallMs);\n const setupMs = Math.max(0, totalMs - telemetry.codingMs);\n const timing: Record<string, number> = {\n codingMs: codingOnlyMs,\n evalMs: evalWallMs,\n setupMs,\n totalMs,\n };\n\n await session.codingAgent.cleanup();\n\n console.log(\n `[simple] timing: coding=${codingOnlyMs}ms eval=${evalWallMs}ms setup=${setupMs}ms total=${totalMs}ms`,\n );\n console.log(\n `[simple] DONE | ${totalMs}ms | turns=${telemetry.turnsUsed} | ` +\n `evalRounds=${telemetry.evalRoundsUsed} | ` +\n `tokens=${telemetry.totalIn + telemetry.totalOut} | ` +\n `compiled=${telemetry.compiledCode.length}B`,\n );\n\n // Machine-parseable breakdown — key=value so grep/awk parses without regex heroics.\n const { phases, outcomes } = telemetry.counters;\n console.log(\n `[simple] SUMMARY | turns=${telemetry.turnsUsed} ` +\n `impl=${phases.impl} patch=${phases.patch} evalFix=${phases.evalFix}` +\n (a1Mode ? ` scaffold=${phases.scaffold} fill=${phases.fill}` : \"\") +\n ` | ` +\n `pass=${outcomes.pass} patchInvalid=${outcomes.patchInvalid} ` +\n `selfCheckFail=${outcomes.selfCheckFail} diffFail=${outcomes.diffFail} | ` +\n `evalRounds=${telemetry.evalRoundsUsed} | ` +\n `codingLlmMs=${telemetry.cumulativeLlmMs} ` +\n `evalLlmMs=${telemetry.cumulativeEvalLlmMs} ` +\n `toolMs=${telemetry.cumulativeToolMs} ` +\n `evalWallMs=${evalWallMs}`,\n );\n\n return {\n compiledCode: telemetry.compiledCode,\n sourceCode: source,\n tokens: {\n input: telemetry.totalIn,\n output: telemetry.totalOut,\n // ggui#1186: the FULL processed footprint — the adapters' convention\n // (non-cached input + cache creation + cache reads + output) — so a\n // row's cached count is `total − input − output` even where the cache\n // fields are not published. `input + output` alone priced the cached\n // prefix and hid it (a 36k-token luna turn published as 1.6k).\n total:\n telemetry.totalIn +\n (telemetry.cacheCreationTokens ?? 0) +\n (telemetry.cacheReadTokens ?? 0) +\n telemetry.totalOut,\n },\n // Prompt-cache counters are provider-specific — pass through truthfully.\n // Absent on the telemetry (provider didn't report) stays absent here,\n // never defaulted to 0, so the downstream observability ratio reflects\n // real cache activity instead of a structural zero.\n ...(telemetry.cacheReadTokens !== undefined\n ? { cacheReadTokens: telemetry.cacheReadTokens }\n : {}),\n ...(telemetry.cacheCreationTokens !== undefined\n ? { cacheCreationTokens: telemetry.cacheCreationTokens }\n : {}),\n // ggui#1522 — the in-loop visual judge's spend, beside `tokens` and never inside it.\n ...(telemetry.inLoopVisualTokens !== undefined ? { inLoopVisualTokens: telemetry.inLoopVisualTokens } : {}),\n generationTimeMs: totalMs,\n turnsUsed: telemetry.turnsUsed,\n passesUsed: 1,\n // ggui#1261 — the contract-feedback round's record rides the result the\n // generation ends with (whose probe stamp is the post-round verdict).\n evalResult:\n telemetry.evalResult !== undefined && telemetry.contractFeedback !== undefined\n ? { ...telemetry.evalResult, contractFeedback: telemetry.contractFeedback }\n : telemetry.evalResult,\n // ggui#404 — present only when the same-exchange guard ended the run.\n ...(telemetry.sameExchangeBreak !== undefined ? { sameExchangeBreak: telemetry.sameExchangeBreak } : {}),\n ...(telemetry.sameFailureBreak !== undefined ? { sameFailureBreak: telemetry.sameFailureBreak } : {}),\n needsBackgroundImprovement,\n selfCheckPassed: telemetry.selfCheckPassed,\n timing,\n breakdown: {\n phases: { ...phases },\n outcomes: { ...outcomes },\n evalRounds: telemetry.evalRoundsUsed,\n // `llmMs` retained as coding-turn LLM (stable semantics for existing\n // consumers in benchmarks/multi-sdk/runner.ts:312); `evalLlmMs` is\n // new, covers eval-round parallel LLM+visual wall-time.\n llmMs: telemetry.cumulativeLlmMs,\n evalLlmMs: telemetry.cumulativeEvalLlmMs,\n toolMs: telemetry.cumulativeToolMs,\n evalMs: evalWallMs,\n codingMs: codingOnlyMs,\n setupMs,\n },\n };\n}\n","// packages/ui-gen/src/coding-agent/self-check.ts\n//\n// Self-check rules for the coding agent.\n// Reuses runSelfChecks from adapters/tools.ts + contract validation.\n\nimport { runSelfChecks } from '../adapters/tools';\nimport { validateAllContracts } from '../check/index.js';\nimport { checkWirePreservation, type WireKind } from '../check/index.js';\nimport type { DataContract } from '@ggui-ai/protocol';\nimport type { BuildResult } from './types';\n\nexport interface SelfCheckResult {\n passed: boolean;\n violations: string[];\n}\n\n/** Map wire kind to the matching `@ggui-ai/wire` hook name. */\nconst HOOK_NAME_FOR: Readonly<Record<WireKind, string>> = {\n action: 'useAction',\n stream: 'useStream',\n context: 'useGguiContext',\n};\n\n/**\n * Run all self-checks on generated component code.\n * All rules always apply — single-file standalone mode only.\n */\nexport async function runCodingAgentSelfCheck(\n code: string,\n buildResult: BuildResult,\n contract?: DataContract,\n): Promise<SelfCheckResult> {\n const violations: string[] = [];\n\n // ── Build check ────────────────────────────────────\n if (!buildResult.success) {\n violations.push(\n `builds_clean: Build failed${buildResult.errors?.length ? ': ' + buildResult.errors.join('; ') : ''}`,\n );\n }\n\n // ── Self-checks (imports, types, security, a11y) ──\n try {\n const { issues } = await runSelfChecks(code, contract);\n for (const issue of issues) {\n const fixHint = issue.fix ? ` → Fix: ${issue.fix}` : '';\n violations.push(`${issue.check}: ${issue.message} (line ${issue.line})${fixHint}`);\n }\n } catch {\n // runSelfChecks may fail if code is malformed — treat as non-blocking\n }\n\n // ── Contract validation ────────────────────────────\n if (contract) {\n try {\n const contractIssues = validateAllContracts(code, contract);\n for (const ci of contractIssues) {\n if (ci.severity === 'error') {\n violations.push(`contract:${ci.field}: ${ci.message} → Fix: ${ci.fix}`);\n }\n }\n } catch {\n // contract validation may fail on malformed code\n }\n }\n\n // ── Wire preservation ──────────────────────────────────────────────\n // The boilerplate generator emits one `const X = use{Action,Stream}('X')`\n // call per contract-declared wire plus one `useGguiContext('slot')` per\n // contextSpec slot. Those hook declarations ARE the contract-completeness\n // manifest. If the LLM's apply_patch deletes any of them, the component\n // will not fire the wire at runtime — but `pnpm typecheck` won't flag the\n // absence (a missing call is a missing side effect, not a type error).\n // This rule closes that gap at the deterministic self_check tier.\n // `agentCapabilities.tools` (catalog declaration, NOT a hook) and `clientCapabilities`\n // (vendor-package hooks, not @ggui-ai/wire) are intentionally excluded.\n if (contract) {\n try {\n const report = checkWirePreservation(code, contract);\n for (const site of report.missing) {\n const hook = HOOK_NAME_FOR[site.kind];\n violations.push(\n `wire_preservation:${site.kind}:${site.name}: ` +\n `Contract declares ${site.kind} '${site.name}' but no ${hook}('${site.name}') ` +\n `call exists in the component. The boilerplate placed this hook for you — ` +\n `restore it at the top of the function body and consume the returned binding ` +\n `(in JSX, a callback, or an effect).`,\n );\n }\n } catch {\n // Malformed code surfaces as a primary error elsewhere — don't\n // mask it with a wire-preservation noise-violation here.\n }\n }\n\n return {\n passed: violations.length === 0,\n violations,\n };\n}\n\n/**\n * Get soft warnings (non-blocking quality checks).\n */\nexport function getSoftWarnings(code: string): string[] {\n const warnings: string[] = [];\n\n if (!/var\\(--ggui-/.test(code)) {\n warnings.push(\n 'uses_design_tokens: No CSS variables (var(--ggui-*)) found — consider using design system tokens',\n );\n }\n\n if (!/aria-label/.test(code)) {\n warnings.push(\n 'has_aria_labels: No aria-label attributes found — consider adding for accessibility',\n );\n }\n\n return warnings;\n}\n","// packages/ui-gen/src/coding-agent/tools.ts\n//\n// Tool executor for the harness coding loop (`harness/coding/\n// run-coding-turn.ts` advertises the tool surface and routes every\n// LLM tool call through `executeTool`).\n//\n// Key design: write and apply_changes include a commit_message field\n// and auto-commit + auto-self-check after execution. The LLM never\n// calls commit directly — it's implicit in every mutation tool.\n\nimport * as esbuild from 'esbuild';\nimport { AgentWorkspace } from './workspace';\nimport { getSoftWarnings } from './self-check';\nimport { restoreReactImport } from '../boilerplate/react-hooks.js';\nimport { runTier0Checks } from '../check/index.js';\nimport { runGatedAxisChecks, traceAxisChecksSkipped } from '../evaluation/axis-checks/dispatch.js';\nimport type { AxisCheck, AxisCheckInput, EvalIssue } from '../evaluation/types-public.js';\nimport type { Classification } from '../classifier/axes.js';\nimport type { CanvasClass } from '../design-mode.js';\nimport { PRIMITIVES_DOCUMENTATION } from '../validation/index.js';\nimport type { DataContract, JsonObject } from '@ggui-ai/protocol';\nimport type {\n ToolResult,\n CommitMetadata,\n} from './types';\nimport { DEFAULT_DESIGN_MODE, type DesignMode } from '../design-mode.js';\n\n/**\n * ggui#1876 — the auto-commit line's axis field: the F/W counts, then the check ids behind them, so a\n * WARN the model saw at a turn is attributable in the log (the `[WARN]` text otherwise appears only at\n * the final evaluation). `0F/1W[W:universal.tint_category_in_words]`; nothing appended at `0F/0W`.\n * The `<n>F/<n>W` prefix is unchanged, so anything that reads the counts reads them as before. An\n * issue with no `subcategory` (the axis checks always set one, as their id) is named by its category.\n */\nexport function axisCountsWithIds(issues: readonly EvalIssue[]): string {\n const idOf = (i: EvalIssue): string => i.subcategory ?? i.category;\n const warns = issues.filter((i) => i.result === 'warn').map(idOf);\n const fails = issues.filter((i) => i.result !== 'warn').map(idOf);\n const groups = [...(fails.length > 0 ? [`F:${fails.join(',')}`] : []), ...(warns.length > 0 ? [`W:${warns.join(',')}`] : [])];\n return `${fails.length}F/${warns.length}W${groups.length > 0 ? `[${groups.join(' ')}]` : ''}`;\n}\n\n/**\n * Extract documentation for a single component from the full primitives docs.\n * Returns ~200-500 tokens instead of 43K.\n */\nfunction getComponentDocumentation(name: string): string {\n // The docs use \"### ComponentName\" as headers\n const marker = `### ${name}`;\n const startIdx = PRIMITIVES_DOCUMENTATION.indexOf(marker);\n if (startIdx === -1) {\n return `Component \"${name}\" not found. Available primitives: Container, Card, Stack, Row, Box, Text, Heading, Button, Input, Select, Checkbox, Toggle, Badge, Alert, Progress, Image, Icon, Divider, Tabs, Accordion, Table, Tooltip, Spinner, Avatar, Link`;\n }\n\n // Find the next ### (next component) to get just this one's docs\n const nextMarker = PRIMITIVES_DOCUMENTATION.indexOf('### ', startIdx + marker.length);\n const section = nextMarker === -1\n ? PRIMITIVES_DOCUMENTATION.slice(startIdx)\n : PRIMITIVES_DOCUMENTATION.slice(startIdx, nextMarker);\n\n // Unescape the string (it's stored with \\\\n)\n return section.replace(/\\\\n/g, '\\n').replace(/\\\\\"/g, '\"').slice(0, 3000);\n}\n\n// =============================================================================\n// Auto-commit helper (shared by write and apply_changes)\n// =============================================================================\n\n/**\n * The deterministic axis family at auto-commit (ggui#1122) — what a caller with a\n * harness hands `executeTool` so the checks run on EVERY commit the coding agent\n * makes, i.e. on the serve path, not only inside the eval round a serving deployment\n * never enters. `checks` is the harness's pre-filtered list (`harness.check.axisChecks`)\n * — the same list `run-check.ts` feeds the same pure runner. Absent: nothing runs.\n */\nexport interface AutoCommitAxisChecks {\n readonly checks: readonly AxisCheck[];\n readonly classification: Classification;\n /** The ORIGINAL request — several checks read it (labels invented past the copy, terminal words). */\n readonly originalPrompt: string;\n /** The canvas the harness was built for (ggui#1117); absent = no rendering context, never a default. */\n readonly canvas?: CanvasClass;\n /** The props the probe and judge render with (ggui#1285); absent = the fixture-echo check stands down. */\n readonly fixtureProps?: JsonObject;\n}\n\nasync function autoCommit(\n workspace: AgentWorkspace,\n commitMeta: Map<string, CommitMetadata>,\n message: string,\n contract?: DataContract,\n /**\n * Optional ContextPolicy — when `labeledTier0` is true, the self-check\n * violation formatter prefixes `[P0-*]` / `[P1-*]` priority tags so the\n * LLM can rank retry feedback against the prompt's P0/P1/P2 schema.\n * Defaults to unlabeled.\n */\n contextPolicy?: import(\"../harness/policy.js\").ContextPolicy,\n /**\n * A `package -> .d.ts content` map for third-party gadget wrappers.\n * Threaded into `runTier0Checks` → `typecheck`, which overlays each\n * wrapper `.d.ts` at `node_modules/<package>/index.d.ts` so a\n * generated direct import `import { useLeafletMap } from\n * '@scope/leaflet'` resolves against the real declaration (strict\n * option/return narrowing). Without it, third-party hooks narrow to\n * `any` (no option/return typechecking). Standard-library-only\n * callers omit it; the shipped `@ggui-ai/gadgets` `.d.ts` covers the\n * stdlib hooks unconditionally.\n */\n gadgetTypes?: Readonly<Record<string, string>>,\n /** Which tier-0 legs fire — see `runTier0Checks`'s `designMode`. */\n designMode: DesignMode = DEFAULT_DESIGN_MODE,\n /** ggui#1122: run the harness's axis checks here too; absent, none run. */\n axis?: AutoCommitAxisChecks,\n): Promise<ToolResult> {\n const commitStart = Date.now();\n const raw = workspace.read();\n if (!raw && raw !== '') {\n return { result: 'FAILED: no file to compile', error: true };\n }\n\n // No post-compile formatting — the generated TSX is built as-is.\n // (Prettier auto-format was removed; it added a dependency + repair\n // churn without a quality gain.)\n // ggui#1932: the boilerplate's DO NOT EDIT React import is code's to keep — restored here, before\n // the build and tier-0, so a dropped hook never becomes a refusal the model spends a turn on.\n const restore = restoreReactImport(raw);\n if (restore.added.length > 0) {\n workspace.write(restore.source);\n console.log(`[coding-agent] react-import restored: ${restore.added.map((h) => `+${h}`).join(',')}`);\n }\n const formatted = restore.source;\n\n // Build with esbuild — keep all imports (react, @ggui-ai/design)\n // esbuild.transform() passes them through as-is, the runtime resolves them\n const buildStart = Date.now();\n let buildSuccess = false;\n let compiledCode = '';\n const buildErrors: string[] = [];\n try {\n const result = await esbuild.transform(formatted, {\n loader: 'tsx',\n target: 'es2020',\n format: 'esm',\n jsx: 'automatic',\n jsxImportSource: 'react',\n minify: true,\n keepNames: true,\n });\n compiledCode = result.code;\n buildSuccess = true;\n } catch (e) {\n buildErrors.push(e instanceof Error ? e.message : String(e));\n }\n const buildMs = Date.now() - buildStart;\n\n const buildResult = {\n success: buildSuccess,\n compiledCode: buildSuccess ? compiledCode : undefined,\n errors: buildErrors.length > 0 ? buildErrors : undefined,\n };\n\n // Tier 0 checks (replaces self-check — includes build, security, imports,\n // tokens, types, contract, TS type checking, React hooks linting)\n const selfCheckStart = Date.now();\n const tier0Issues = await runTier0Checks(\n formatted,\n contract,\n buildResult.errors,\n gadgetTypes,\n designMode,\n );\n // ggui#1122: the deterministic axis family runs HERE — on every commit the coding\n // agent makes, which is the serve path — through the one pure runner `run-check.ts`\n // feeds (the ggui#1046 trace line prints on both paths). Posture is the founder's:\n // warn-as-warn, fail-as-fail. A WARN that started blocking a served generation\n // because it moved surface would be a posture change, not a relocation, and comes\n // to him as a named item. Only a source that BUILT is judged: on a build failure\n // the checks are not asked (the same stand-down the gate+run wrapper makes) and\n // the ggui#1046 trace says so — a skipped round never reads as a clean one.\n const axisFacts = axis !== undefined\n ? {\n sourceCode: formatted,\n ...(contract !== undefined ? { contract } : {}),\n originalPrompt: axis.originalPrompt,\n classification: axis.classification,\n designMode,\n ...(axis.canvas !== undefined ? { canvas: axis.canvas } : {}),\n ...(axis.fixtureProps !== undefined ? { fixtureProps: axis.fixtureProps } : {}),\n }\n : undefined;\n if (axisFacts !== undefined && !buildSuccess) traceAxisChecksSkipped(axisFacts, 'build failed — no check ran');\n const axisRun = axis !== undefined && axisFacts !== undefined && buildSuccess\n ? runGatedAxisChecks(axis.checks, { ...axisFacts, compiledCode } satisfies AxisCheckInput)\n : undefined;\n const axisIssues = axisRun?.issues ?? [];\n const checkIssues = [...tier0Issues, ...axisIssues];\n const tier0Fails = checkIssues.filter(i => i.result === 'fail');\n const selfCheckPassed = tier0Fails.length === 0;\n // When contextPolicy.labeledTier0 is set, prefix each violation with\n // its P0/P1/P2 priority so the LLM can rank against the prompt's\n // schema. The default (off) emits unlabeled feedback.\n const violations = checkIssues\n .filter(i => i.result === 'fail')\n .map(i => contextPolicy?.labeledTier0\n ? `[${i.priority ?? 'P0'}-${i.category}] ${i.description}\\n Fix: ${i.fix}`\n : `[${i.category}] ${i.description}\\n Fix: ${i.fix}`);\n // Axis WARNs ride the existing non-blocking channel — feedback the model sees, never a block.\n const axisWarnings = axisIssues\n .filter(i => i.result === 'warn')\n .map(i => `[${i.subcategory}] ${i.description} Fix: ${i.fix}`);\n const softWarnings = [...getSoftWarnings(raw), ...axisWarnings];\n const selfCheckMs = Date.now() - selfCheckStart;\n\n // Always commit (preserves history)\n const gitStart = Date.now();\n const oid = await workspace.commit(message);\n commitMeta.set(oid, { build: buildResult, selfCheck: { passed: selfCheckPassed, violations } });\n const gitMs = Date.now() - gitStart;\n\n const status = buildSuccess && selfCheckPassed ? 'PASS' : 'FAIL';\n console.log(\n `[coding-agent] auto-commit: ${status} | build=${buildMs}ms self-check=${selfCheckMs}ms git=${gitMs}ms total=${Date.now() - commitStart}ms | violations=${violations.length} | axis=${axisRun === undefined ? 'off' : axisCountsWithIds(axisIssues)}`,\n );\n if (violations.length > 0) {\n for (const v of violations) {\n console.log(`[coding-agent] ✗ ${v}`);\n }\n }\n\n if (buildSuccess && selfCheckPassed) {\n const warnStr = softWarnings.length > 0\n ? `\\nWarnings (non-blocking): ${softWarnings.join('; ')}`\n : '';\n return {\n result: `Committed ${oid.slice(0, 7)}: \"${message}\"\\nBuild: OK\\nSelf-check: PASS${warnStr}`,\n done: true,\n compiledCode,\n };\n }\n\n const errors = [\n ...(buildErrors.length > 0 ? [`Build errors:\\n${buildErrors.join('\\n')}`] : []),\n ...(!selfCheckPassed ? [`Self-check violations:\\n${violations.join('\\n')}`] : []),\n ];\n return {\n result: `Committed ${oid.slice(0, 7)}: \"${message}\"\\n${errors.join('\\n')}\\nFix the issues.`,\n };\n}\n\n// =============================================================================\n// Tool Executor\n// =============================================================================\n\nexport async function executeTool(\n workspace: AgentWorkspace,\n tool: string,\n input: Record<string, unknown>,\n commitMeta: Map<string, CommitMetadata>,\n contract?: DataContract,\n applyPatch?: import(\"../harness/types-public.js\").PatchFn,\n /**\n * Optional context policy — when provided, `apply_changes` preflight\n * renders the PATCH_INVALID retry message according to policy. Callers\n * that don't pass one get unlabeled feedback. Harness-driven callers\n * (run-coding-turn) should pass `harness.policy.context` so the\n * resolved policy wins.\n */\n contextPolicy?: import(\"../harness/policy.js\").ContextPolicy,\n /**\n * A `package -> .d.ts content` map for third-party gadget wrappers.\n * Forwarded to `autoCommit` → `runTier0Checks` → `typecheck` so the\n * TS sandbox overlays each wrapper's real `.d.ts` and a generated\n * direct import `import { useX } from '<package>'` gets strict\n * option/return narrowing instead of `any`. Standard-library-only\n * callers omit it.\n */\n gadgetTypes?: Readonly<Record<string, string>>,\n /** Which tier-0 legs fire on auto-commit — see `runTier0Checks`'s `designMode`. */\n designMode: DesignMode = DEFAULT_DESIGN_MODE,\n /** ggui#1122: the harness's axis checks, run at every auto-commit — see `AutoCommitAxisChecks`. */\n axis?: AutoCommitAxisChecks,\n): Promise<ToolResult> {\n switch (tool) {\n case 'write':\n case 'rewrite': {\n const code = input.code as string | undefined;\n if (!code && code !== '') {\n console.warn(\n `[coding-agent] write: no \"code\" field. Keys: [${Object.keys(input).join(', ')}]`,\n );\n return {\n result: `FAILED: write requires a \"code\" field. Received: [${Object.keys(input).join(', ')}]`,\n error: true,\n };\n }\n workspace.write(code);\n await workspace.stage();\n const lineCount = code.split('\\n').length;\n const message = (input.commit_message as string) || `write ${lineCount} lines`;\n\n console.log(`[coding-agent] write: ${lineCount} lines → auto-commit`);\n return autoCommit(workspace, commitMeta, message, contract, contextPolicy, gadgetTypes, designMode, axis);\n }\n\n case 'apply_changes': {\n const currentFile = workspace.read();\n if (!currentFile && currentFile !== '') {\n return { result: 'FAILED: No file exists.', error: true };\n }\n\n type RawChange = {\n startLine: number | string;\n endLine: number | string;\n code: string[] | string;\n description?: string;\n };\n // `input.changes` can legitimately arrive as either a single\n // RawChange (LLM forgot the array wrapper) or RawChange[]. Normalize\n // up front so downstream code only sees the array shape.\n const inputChanges = input.changes as RawChange | RawChange[] | undefined;\n const rawChanges: RawChange[] = inputChanges\n ? Array.isArray(inputChanges)\n ? inputChanges\n : [inputChanges]\n : [];\n // Option C: opt-in \"allowBroken\" — LLM deliberately commits a patch\n // that may fail syntax preflight, planning to finish the repair\n // across follow-up turns. The workspace is updated + a warning is\n // returned so the LLM sees the error location without the patch\n // being reverted.\n const allowBroken = input.allowBroken === true;\n\n // Shape-normalize each change. `startLine` / `endLine` may arrive as:\n // - number (numeric-line schema)\n // - string like \"47:a3\" (hashline schema) — parse into line\n // number + expected hash so we can validate against the\n // current file before applying.\n const { parseHashlineRef, validateHashlineRefs, formatHashlineStaleMessage } =\n await import('../harness/hashline.js');\n const normalizedChanges: Array<{\n startLine: number;\n endLine: number;\n code: string[];\n description: string;\n expectedStartHash?: string;\n expectedEndHash?: string;\n }> = [];\n for (let i = 0; i < (rawChanges ?? []).length; i++) {\n const c = rawChanges![i]!;\n let startLine: number;\n let expectedStartHash: string | undefined;\n if (typeof c.startLine === 'string') {\n const parsed = parseHashlineRef(c.startLine);\n if (!parsed) {\n return {\n result: `FAILED: change[${i}].startLine = ${JSON.stringify(c.startLine)} is not a valid hashline ref (expected \"N:hh\" format).`,\n error: true,\n };\n }\n startLine = parsed.line;\n expectedStartHash = parsed.expectedHash;\n } else {\n startLine = c.startLine;\n }\n let endLine: number;\n let expectedEndHash: string | undefined;\n if (typeof c.endLine === 'string') {\n const parsed = parseHashlineRef(c.endLine);\n if (!parsed) {\n return {\n result: `FAILED: change[${i}].endLine = ${JSON.stringify(c.endLine)} is not a valid hashline ref (expected \"N:hh\" format).`,\n error: true,\n };\n }\n endLine = parsed.line;\n expectedEndHash = parsed.expectedHash;\n } else {\n endLine = c.endLine;\n }\n normalizedChanges.push({\n startLine,\n endLine,\n code: Array.isArray(c.code) ? c.code : typeof c.code === 'string' ? c.code.split('\\n') : [],\n description: c.description ?? `change ${i + 1}`,\n expectedStartHash,\n expectedEndHash,\n });\n }\n\n // ── Hashline validation — any change with expected hashes must match\n // the current file BEFORE we apply. Mismatch = LLM's view is stale\n // (file drifted under it) → reject with HASHLINE_STALE + current\n // content so the LLM can re-orient. This is the ONE case where we\n // still reject-and-revert under the never-revert default: patching\n // based on stale hashes would corrupt the file silently.\n const hashlineIssues = validateHashlineRefs(currentFile, normalizedChanges);\n if (hashlineIssues.length > 0) {\n const ranges = normalizedChanges\n .map((c) => `${c.startLine}-${c.endLine}`)\n .join(', ');\n console.log(\n `[coding-agent] apply_changes: HASHLINE_STALE | ranges=${ranges} | ${hashlineIssues.length} mismatch(es)`,\n );\n return {\n result: formatHashlineStaleMessage(hashlineIssues),\n error: true,\n };\n }\n\n // ── Gutter-transcription reject (P3.3, ggui Exp 49) ──\n // The `## Current File` view renders `N│ content` (workspace.ts) and\n // models occasionally transcribe that gutter into the patch payload\n // verbatim — the payload is then unusable by construction, so this\n // is the one pre-apply rejection that cannot misfire (real TSX never\n // begins a line with `digits│`). Distinct from the deliberate\n // apply-and-warn posture below, which is about *broken* code, not\n // *decorated* code.\n const gutterLine = normalizedChanges\n .flatMap((c) => c.code)\n .find((l) => /^\\s*\\d+(?::[0-9a-f]{2})?│/.test(l));\n if (gutterLine !== undefined) {\n console.log(\n `[coding-agent] apply_changes: GUTTER_TRANSCRIBED | ${JSON.stringify(gutterLine.slice(0, 60))}`,\n );\n return {\n result:\n `PATCH_INVALID: your \\`code\\` contains the line-number gutter from the Current File view ` +\n `(e.g. ${JSON.stringify(gutterLine.trim().slice(0, 40))}). The \\`N│\\` prefix is display decoration — ` +\n `\\`code\\` must be raw file content only. Re-emit the patch without the gutter.`,\n error: true,\n };\n }\n\n // ── Patch application — via harness.what.applyPatch when provided,\n // else fall back to the default pure engine. Both enforce the same\n // invariants (sort, non-overlap, line bounds, reverse apply).\n const { defaultApplyPatch } = await import('../patch.js');\n const patcher = applyPatch ?? defaultApplyPatch;\n const patchResult = await patcher({\n sourceBefore: currentFile,\n changes: normalizedChanges,\n });\n if (!patchResult.ok) {\n // ggui#1261: the engine refused the patch (overlap, line bounds, missing range) before\n // anything applied. Say so in the log, and call it what it is — PATCH_INVALID, like every\n // other structural refusal in this tool — so the turn is never counted as a self-check\n // failure that did not run.\n console.log(`[coding-agent] apply_changes: REJECTED | ${patchResult.error}`);\n return { result: `PATCH_INVALID: ${patchResult.error}`, error: true };\n }\n const candidate = patchResult.sourceAfter ?? currentFile;\n\n // Log each applied change for traceability (matches prior output shape).\n const changes = [...normalizedChanges].sort((a, b) => a.startLine - b.startLine);\n for (const c of changes) {\n console.log(\n `[coding-agent] change: lines ${c.startLine}-${c.endLine} → ${c.code.length} lines | ${c.description}`,\n );\n }\n\n // `candidate` already set above from patchResult.sourceAfter.\n const resultLines = candidate.split('\\n');\n\n // ── Structural tag-balance DIAGNOSTIC ──\n // Counts per-tag (opens, closes, self-closes) across the whole\n // patch and logs any net imbalance. This is NOT a gate — esbuild\n // remains the gate.\n //\n // The balance check is deliberately not used as a rejection gate:\n // an abstract summary message (\"you have 1 unclosed <Stack>\")\n // gives the LLM less to work with than esbuild's line-specific\n // error (\"Unexpected closing Container at line 183\").\n //\n // Instead, the imbalance summary is appended as SUPPLEMENTARY\n // context to the PATCH_APPLIED_BROKEN message when esbuild also\n // fails. esbuild's precise line stays the primary signal; the\n // imbalance counts become a hint.\n let tagImbalanceSummary: string | null = null;\n {\n const { checkPatchTagBalance } = await import('./tag-balance.js');\n const imbalance = checkPatchTagBalance(currentFile, changes);\n if (imbalance.imbalanced) {\n const ranges = changes\n .map((c) => `${c.startLine}-${c.endLine}`)\n .join(', ');\n const totalsSummary = imbalance.totals\n .map((d) => `${d.tag}${d.netDelta >= 0 ? '+' : ''}${d.netDelta}`)\n .join(' ');\n console.log(\n `[coding-agent] apply_changes: tag-balance-diag | ranges=${ranges} | ${totalsSummary}`,\n );\n tagImbalanceSummary = totalsSummary;\n }\n }\n\n // ── Step 6: Syntax preflight — parse candidate before mutating workspace ──\n // Catches broken JSX/TSX from the patch (mismatched tags, stray braces, etc.)\n // BEFORE we write/stage/commit. On failure: keep last-good file, return\n // PATCH_INVALID so the LLM can retry from stable ground (distinct from\n // SELF_CHECK_FAIL, which means valid TSX but rejected by tier-0 checks).\n // esbuild settings must match the real build path in autoCommit().\n try {\n await esbuild.transform(candidate, {\n loader: 'tsx',\n target: 'es2020',\n format: 'esm',\n jsx: 'automatic',\n jsxImportSource: 'react',\n minify: true,\n keepNames: true,\n });\n } catch (e) {\n // esbuild throws a TransformFailure with structured `errors[]` including\n // { text, location: { line, column, lineText } }. Center the retry slice\n // on the ACTUAL error line (first error), not the first changed range.\n // If the error has no location (rare), fall back to first change.\n const errMsg = e instanceof Error ? e.message : String(e);\n const esErrs = (e as { errors?: Array<{ text?: string; location?: { line?: number; column?: number; lineText?: string } }> }).errors ?? [];\n const firstErr = esErrs[0];\n const errLine = firstErr?.location?.line;\n const errCol = firstErr?.location?.column;\n const errText = firstErr?.text ?? errMsg.split('\\n')[0];\n\n const ranges = changes\n .map(c => `${c.startLine}-${c.endLine}`)\n .join(', ');\n\n // Pick slice center: esbuild's error line if available, else first change.\n let sliceStart: number;\n let sliceEnd: number;\n let sliceLabel: string;\n if (typeof errLine === 'number' && errLine > 0) {\n sliceStart = Math.max(0, errLine - 6);\n sliceEnd = Math.min(resultLines.length, errLine + 5);\n sliceLabel = `Candidate slice (±5 lines around esbuild error at line ${errLine}${typeof errCol === 'number' ? `:${errCol}` : ''})`;\n } else {\n const first = changes[0];\n sliceStart = Math.max(0, first.startLine - 6);\n sliceEnd = Math.min(resultLines.length, first.endLine + 5);\n sliceLabel = `Candidate slice (around first changed range)`;\n }\n const slice = resultLines\n .slice(sliceStart, sliceEnd)\n .map((l, i) => {\n const lineNum = sliceStart + i + 1;\n const marker = lineNum === errLine ? ' ◄── esbuild error here' : '';\n return `${lineNum}│${l}${marker}`;\n })\n .join('\\n');\n\n // ── Apply-and-warn on syntax failure ──\n // An earlier approach reverted the workspace + returned a\n // PATCH_INVALID error. The problem: the LLM never saw its own\n // broken patch persisted, so across retries it replayed from\n // the prior-good file and often re-emitted variations of the\n // same broken patch (\"chasing a moving target\").\n //\n // Now: ALWAYS write the candidate to workspace; DON'T git-commit\n // (the prior-good commit stays as the eval ancestor, and\n // compiledCode only updates when esbuild passes). The LLM sees its\n // broken patch on the next turn and iterates forward from broken\n // state toward a fixed one — matches how an engineer actually\n // debugs. The final eval gate is the compile/render at eval time:\n // if the workspace never converges to a compilable state, the\n // compiledCode stays at prior-good (or empty) and eval fails\n // naturally — no need to block per-turn.\n //\n // The `allowBroken` input field is retained for back-compat but\n // is now a no-op (behavior is always apply-and-warn).\n workspace.write(candidate);\n console.log(\n `[coding-agent] apply_changes: APPLIED-BROKEN (preflight failed)${allowBroken ? ' [allowBroken]' : ''} | ranges=${ranges} | line=${errLine ?? '?'} | ${errText}`,\n );\n const preflightPrefix = contextPolicy?.labeledPreflight\n ? `[P0-compile] `\n : ``;\n const imbalanceHint = tagImbalanceSummary\n ? `\\n\\nPatch tag-balance imbalance: ${tagImbalanceSummary}\\n` +\n `(Net opens vs closes inside your edit ranges. If a tag has +N, you opened N more than you closed within the patch — verify each <Tag> has a matching </Tag> in your changes, or that the surrounding scaffold provides the closer.)`\n : '';\n // P3.1 (ggui Exp 49) — when the error lands exactly on the first\n // line of a patched range, the range and the payload usually\n // disagree about syntactic context. Fires only on two unambiguous\n // shapes; silent otherwise. Informational, never a gate — the\n // #41–#44 lesson (information helps, compulsion hurts) stands.\n const contextAddendum = buildRangeContextAddendum(\n errLine,\n changes,\n currentFile.split('\\n'),\n );\n if (contextAddendum.length > 0) {\n // Tool RESULT texts never reach bench logs — this line is the\n // measurable fire signal (same rationale as tag-balance-diag).\n console.log(\n `[coding-agent] apply_changes: RANGE_CONTEXT_DIAG | line=${errLine} | ${JSON.stringify(contextAddendum.slice(0, 80))}`,\n );\n }\n return {\n result:\n `${preflightPrefix}PATCH_APPLIED_BROKEN: patch applied but file has a syntax error. Workspace updated; no git commit yet.\\n` +\n `Changed ranges: ${ranges}\\n` +\n `esbuild error: ${errText}${typeof errLine === 'number' ? ` (line ${errLine}${typeof errCol === 'number' ? `, col ${errCol}` : ''})` : ''}\\n\\n` +\n `${sliceLabel}:\\n${slice}\\n\\n` +\n `The file now reflects your latest patch. Submit a follow-up apply_changes targeting the error location above to converge toward a compilable file.${contextAddendum}${imbalanceHint}`,\n error: false,\n };\n }\n\n workspace.write(candidate);\n await workspace.stage();\n const message = (input.commit_message as string) || 'apply changes';\n\n console.log(`[coding-agent] apply_changes: ${changes.length} changes applied → auto-commit`);\n return autoCommit(workspace, commitMeta, message, contract, contextPolicy, gadgetTypes, designMode, axis);\n }\n\n case 'get_components_info': {\n const names = (input.names as string[]) ?? [];\n const docs = names.map((name) => getComponentDocumentation(name));\n return { result: docs.join('\\n\\n---\\n\\n') };\n }\n\n case 'write_plan': {\n // Plan-commitment. Echo the plan back so it stays visible in\n // conversation history for subsequent turns.\n const components = (input.components as string[]) ?? [];\n const structure = (input.structure as string) ?? '';\n const wiring = (input.wiring as string) ?? '';\n const summary =\n `PLAN_COMMITTED\\n\\n` +\n `Components: ${components.join(', ')}\\n\\n` +\n `Structure: ${structure}\\n\\n` +\n `Wiring: ${wiring}\\n\\n` +\n `On the next turn, use apply_changes to write the code. Fetch more component docs only if needed.`;\n return { result: summary };\n }\n\n // `cat` is NOT advertised on the bench's coding-turn tool list —\n // `run-coding-turn.ts::selectTurnTools` omits it because every turn's\n // prompt already injects the current file as a `## Current File`\n // block, so no read-tool is needed there. The case stays for\n // dev-agent workflows that don't auto-inject file content.\n case 'cat':\n return {\n result: workspace.cat(\n input.start_line as number | undefined,\n input.end_line as number | undefined,\n ),\n };\n\n case 'grep':\n return {\n result: workspace.grep(\n input.pattern as string,\n input.context as number | undefined,\n ),\n };\n\n case 'diff':\n return { result: await workspace.diffWorking() };\n\n case 'log': {\n const commits = await workspace.log(input.depth as number | undefined);\n if (commits.length === 0) return { result: '(no commits)' };\n const lines = commits.map((c) => {\n const meta = commitMeta.get(c.oid);\n const status = meta?.selfCheck.passed\n ? 'PASS'\n : meta?.selfCheck\n ? 'FAIL'\n : '—';\n return `${c.oid.slice(0, 7)} [${status}] ${c.commit.message.trim()}`;\n });\n return { result: lines.join('\\n') };\n }\n\n case 'show': {\n const oidPrefix = input.oid as string;\n const commits = await workspace.log();\n const idx = commits.findIndex((c) => c.oid.startsWith(oidPrefix));\n if (idx === -1) {\n return { result: `Commit not found: ${oidPrefix}`, error: true };\n }\n const thisOid = commits[idx].oid;\n const parentOid = idx + 1 < commits.length ? commits[idx + 1].oid : null;\n if (!parentOid) {\n const content = await workspace.readFileAtCommit(thisOid);\n return { result: `(initial commit)\\n${content}` };\n }\n return { result: await workspace.diffBetween(parentOid, thisOid) };\n }\n\n case 'revert': {\n const oidPrefix = input.oid as string;\n const commits = await workspace.log();\n const match = commits.find((c) => c.oid.startsWith(oidPrefix));\n if (!match) {\n const available = commits.map((c) => c.oid.slice(0, 7)).join(', ');\n return {\n result: `OID not found: ${oidPrefix}. Available: ${available || '(none)'}`,\n error: true,\n };\n }\n await workspace.checkout(match.oid);\n return { result: `Reverted working copy to ${match.oid.slice(0, 7)}` };\n }\n\n default:\n return { result: `Unknown tool: ${tool}`, error: true };\n }\n}\n\n/**\n * P3.1 (ggui Exp 49) — structural-context diagnosis for\n * `PATCH_APPLIED_BROKEN`. When esbuild's error line is exactly the FIRST\n * line of a patched range, the dominant google failure shape (15/33 of\n * its broken patches in the d8 cohort) is a range/payload context\n * mismatch. Two unambiguous, always-genuinely-broken shapes are named\n * factually; anything else returns '' (silence beats a wrong diagnosis).\n *\n * Exported for unit tests.\n */\nexport function buildRangeContextAddendum(\n errLine: number | undefined,\n changes: ReadonlyArray<{ startLine: number; code: readonly string[] }>,\n originalLines: readonly string[],\n): string {\n if (typeof errLine !== 'number') return '';\n const hit = changes.find((c) => c.startLine === errLine);\n if (!hit) return '';\n const firstPayloadLine = hit.code.find((l) => l.trim().length > 0) ?? '';\n const declMatch = /^\\s*(const|let|var|function|type|interface)\\b/.exec(\n firstPayloadLine,\n );\n\n // Shape (a): payload opens with a declaration while the range starts\n // just inside the returned JSX — the nearest non-blank ORIGINAL line\n // above the range start ends with `return (`.\n if (declMatch) {\n for (let i = hit.startLine - 2; i >= 0; i--) {\n const line = originalLines[i];\n if (line === undefined || line.trim().length === 0) continue;\n if (/\\breturn\\s*\\($/.test(line.trim())) {\n return (\n `\\n\\nRange/context mismatch: line ${i + 1} is \\`return (\\` — your range starts at ` +\n `${hit.startLine}, INSIDE the returned JSX expression, but your payload begins with a ` +\n `declaration (\\`${declMatch[1]}\\`). Declarations cannot live inside JSX: start the range ` +\n `at or before line ${i + 1} and re-emit \\`return (\\` after them.`\n );\n }\n break; // nearest non-blank line is not `return (` — stay silent\n }\n }\n\n // Shape (b): payload re-emits the component definition while the range\n // starts below the existing `export default function` — producing a\n // nested second definition.\n if (hit.code.some((l) => l.includes('export default function'))) {\n const existing = originalLines.findIndex((l) =>\n l.includes('export default function'),\n );\n if (existing >= 0 && existing + 1 < hit.startLine) {\n return (\n `\\n\\nRange/context mismatch: your payload emits a second \\`export default function\\` but the ` +\n `range starts at line ${hit.startLine}, INSIDE the existing component that opens at line ` +\n `${existing + 1}. Patch within the existing function body — do not re-emit the component definition.`\n );\n }\n }\n\n return '';\n}\n","// packages/ui-gen/src/harness/coding/run-coding-turn.ts\n//\n// One iteration of the apply_changes coding loop, extracted from\n// runSimpleHarness as part of the runHarness migration (#142, step 1).\n//\n// Owns: prompt assembly for this turn (scaffold/fill/impl/patch/eval-fix),\n// the LLM call, the executeTool dispatch, outcome classification, and the\n// per-turn token / latency / breakdown accounting.\n//\n// Does NOT own: the do/while wrapper, staged-process phase transitions,\n// initialResult delivery, or the eval round (axis + LLM + visual +\n// merge + feedback) — those are driven by the harness runtime.\n//\n// Behavior MUST match the inlined original byte-for-byte — this is a\n// mechanical extraction, not a redesign.\n\nimport type { DataContract, JsonObject } from \"@ggui-ai/protocol\";\nimport type { CommitMetadata } from \"../../coding-agent/types.js\";\nimport type { AgentWorkspace } from \"../../coding-agent/workspace.js\";\nimport { executeTool } from \"../../coding-agent/tools.js\";\nimport type { CostTracker } from \"../../evaluation/cost-tracker.js\";\nimport type { LLMAgent } from \"../llm-router.js\";\nimport type { Harness } from \"../types-public.js\";\nimport type { SameExchangeBreak, SameFailureBreak } from \"../result-types.js\";\nimport {\n APPLY_CHANGES_HASHLINE_TOOL,\n APPLY_CHANGES_HASHLINE_TOOL_FLAT,\n APPLY_CHANGES_TOOL,\n APPLY_CHANGES_TOOL_FLAT,\n APPLY_CHANGES_TOOL_SCOPED,\n GET_COMPONENTS_INFO_TOOL,\n GET_ICONS_TOOL,\n ICON_LIST_NO_MATCH_GUIDANCE,\n REWRITE_TOOL,\n type LLMToolDef,\n WRITE_PLAN_TOOL,\n} from \"../../tools.js\";\nimport { LUCIDE_ICON_NAMES } from \"@ggui-ai/design\";\nimport { formatWithHashlines } from \"../hashline.js\";\nimport {\n clearWriteFailures,\n recordToolExchange,\n recordWriteFailure,\n SAME_EXCHANGE_BREAK_AT,\n SAME_EXCHANGE_NUDGE,\n SAME_FAILURE_BREAK_AT,\n SAME_FAILURE_NUDGE,\n SAME_FAILURE_NUDGE_AT,\n} from \"./dupe-break.js\";\nimport type { RepeatedFailure } from \"./dupe-break.js\";\n\n/** Staged process-mode phase machine — also defined in runtime.ts. */\nexport type A1Phase = \"scaffold\" | \"fill\" | \"post\";\n\n/**\n * Tool set advertised to the LLM for a given turn. Exactly ONE\n * authoring tool is advertised per turn so the LLM never has to choose;\n * the harness picks based on workspace state.\n *\n * - forceEscape (dupe-fingerprint hit): `APPLY_CHANGES_TOOL_SCOPED` only,\n * one-shot, ≤20 lines — narrow blast radius for transport-error recovery\n * (notably Google Gemini malformed_tool_call).\n * - consecutiveBrokenApplies ≥ 3: `REWRITE_TOOL` only — the LLM has been\n * iterating on broken state via apply-and-warn and hasn't converged;\n * reset the file with a full rewrite.\n * - Otherwise (including turn 1, since a boilerplate was scaffolded into\n * the workspace before coding started): `APPLY_CHANGES_TOOL` plus the\n * read-only `get_available_icons` helper.\n *\n * Notes:\n * - No more `write` on turn 1. Boilerplate is committed by initSession at\n * scaffold time; turn-1 patches fill it in. This removes the ambiguous\n * \"apply vs write\" choice the LLM used to have.\n * - Rename: `WRITE_TOOL` → `REWRITE_TOOL` to match its new role as\n * escape-only, not primary authoring.\n */\n/**\n * Extract a coarse error signature from a failed apply_changes result.\n * Used by dupe-break fingerprinting to detect \"same patch, same failure\"\n * loops across PATCH_INVALID + PATCH_APPLIED_BROKEN + SELF_CHECK_FAIL.\n *\n * Priority order — return the first match:\n * 1. `esbuild error: <msg>` — preflight + apply-and-warn paths\n * 2. First `[CATEGORY] description` line — tier-0 self-check violation\n * 3. `Build errors:` followed by next non-empty line — esbuild build fail\n * after a successful preflight (rare)\n * 4. Empty string — fingerprint still works on (ranges, code).\n */\nfunction extractFailSignature(resultText: string): string {\n const esbuildMatch = resultText.match(/esbuild error: ([^\\n]+)/);\n if (esbuildMatch) return esbuildMatch[1];\n const violationMatch = resultText.match(/^\\[[A-Z][^\\]]*\\] [^\\n]+/m);\n if (violationMatch) return violationMatch[0];\n const buildErrMatch = resultText.match(/Build errors:\\s*\\n([^\\n]+)/);\n if (buildErrMatch) return buildErrMatch[1];\n return \"\";\n}\n\nexport function selectTurnTools(\n turnsUsed: number,\n forceEscape = false,\n consecutiveBrokenApplies = 0,\n hashlineMode: \"off\" | \"v2\" = \"off\",\n primitiveIndexMode: \"off\" | \"names-only\" | \"with-props\" = \"off\",\n primitiveIndexForceFetch = false,\n primitiveIndexPlanTurn = false,\n planFirstTurn = false,\n codeFormat: \"array\" | \"flat\" = \"array\",\n): LLMToolDef[] {\n if (forceEscape) return [APPLY_CHANGES_TOOL_SCOPED];\n if (consecutiveBrokenApplies >= 3) return [REWRITE_TOOL];\n // Plan-first turn (independent of index mode). When on, turn 1 is\n // write_plan only; turn 2+ is normal write tools.\n if (planFirstTurn && turnsUsed === 1) {\n return [WRITE_PLAN_TOOL];\n }\n // Force turn 1 to fetch-only when `primitiveIndexForceFetch` is on.\n // This removes the LLM's ability to guess prop values; it must load\n // enum docs before writing any JSX.\n if (primitiveIndexForceFetch && primitiveIndexMode !== \"off\" && turnsUsed === 1) {\n return [GET_COMPONENTS_INFO_TOOL];\n }\n // Force turn 2 to write_plan only when `primitiveIndexPlanTurn` is\n // on. Combined with the turn-1 fetch-only step, this produces the\n // fetch → plan → write pipeline, which breaks fetch-loops where the\n // model over-fetches without committing to a structure.\n if (primitiveIndexPlanTurn && primitiveIndexMode !== \"off\" && turnsUsed === 2) {\n return [WRITE_PLAN_TOOL];\n }\n // Hashline profile: swap the numeric-line apply_changes for the\n // hash-verified variant. Independently, `codeFormat` picks the\n // flat-code variant when \"flat\" — a shallower JSON schema that some\n // model decoders handle more reliably.\n const applyTool =\n hashlineMode === \"v2\"\n ? codeFormat === \"flat\"\n ? APPLY_CHANGES_HASHLINE_TOOL_FLAT\n : APPLY_CHANGES_HASHLINE_TOOL\n : codeFormat === \"flat\"\n ? APPLY_CHANGES_TOOL_FLAT\n : APPLY_CHANGES_TOOL;\n const tools: LLMToolDef[] = [applyTool, GET_ICONS_TOOL];\n // Tool-driven primitive docs. Advertise the component-docs fetch\n // tool alongside the authoring tool so the LLM can pull full prop\n // APIs on demand when the compact index isn't enough signal.\n if (primitiveIndexMode !== \"off\") tools.push(GET_COMPONENTS_INFO_TOOL);\n return tools;\n}\n\n/** Pre-warmed eval context handle (lazy-loaded module type). */\ntype PreWarmedEvalContext =\n import(\"../../evaluation/llm-evaluator.js\").PreWarmedEvalContext;\n\n/**\n * Persistent coding-loop context — captured once per generation, reused\n * across every turn. After the closure-based migration (step 3), these\n * will move into a session object held by the generate task runner.\n */\nexport interface CodingTurnContext {\n readonly workspace: AgentWorkspace;\n readonly codingAgent: LLMAgent;\n readonly codingModel: string;\n readonly systemPrompt: string;\n readonly harness: Harness;\n readonly contract: DataContract | undefined;\n /**\n * The ORIGINAL request (ggui#1122) — what the eval round has always judged\n * against, now handed to auto-commit so the axis checks run on the serve\n * path with the same input. Required: a caller that forgot it would silently\n * run no axis checks on every served generation.\n */\n readonly originalPrompt: string;\n readonly commitMeta: Map<string, CommitMetadata>;\n readonly originalProps: string | undefined;\n /** The props the probe and judge render with (ggui#1285) — handed to auto-commit's axis checks; absent = the echo check stands down. */\n readonly fixtureProps?: JsonObject;\n readonly costTracker: CostTracker | null;\n /**\n * Runtime-resolved context policy. Defaults to `harness.policy.context`\n * when the caller hasn't threaded a dispatched override through. Closure\n * callers (generate-task-runner) pass `session.resolvedPolicy.context`\n * so experiment profiles (see policy.ts / C2) apply.\n */\n readonly contextPolicy?: import(\"../policy.js\").ContextPolicy;\n /**\n * Mutable duplicate-patch-break state (see dupe-break.ts). Safe to\n * mutate in place — the caller (generate-task-runner) holds the same\n * reference and reads from it on the next turn. Always provided; the\n * `breakDuplicatePatch` policy flag gates whether this turn reads it.\n */\n readonly dupeBreak?: import(\"./dupe-break.js\").DupeBreakState;\n /** Told the system prompt and user message this turn hands the coding agent, just before the call. */\n readonly onPrompt?: (sent: import(\"../runtime.js\").CodingTurnPrompt) => void;\n}\n\n/**\n * Per-turn input — mutates between turns based on prior turn's result.\n */\nexport interface CodingTurnInput {\n /** 1-indexed turn counter (caller increments before calling). */\n readonly turnsUsed: number;\n readonly a1Phase: A1Phase;\n /** Feedback text from prior turn — issues to fix in patch / eval-fix mode. */\n readonly lastResultText: string;\n readonly lastDiffFailed: boolean;\n /** True when lastResultText came from the eval round (vs self-check). */\n readonly isEvalFeedback: boolean;\n /** Cached lucide icon name list (populated lazily on first get_icons call). */\n readonly iconNamesCache: string | null;\n readonly preWarmedContext: PreWarmedEvalContext | null | undefined;\n readonly preWarmPromise: Promise<PreWarmedEvalContext | null> | undefined;\n}\n\n/**\n * Outcome class used in benchmark breakdowns. Mirrors the original\n * runtime.ts string literals so log/grep tooling keeps working unchanged.\n */\nexport type CodingTurnOutcome =\n | \"PASS\"\n | \"PATCH_INVALID\"\n | \"DIFF_FAIL\"\n | \"SELF_CHECK_FAIL\";\n\n/** Phase label used in breakdowns. */\nexport type CodingTurnPhase = \"scaffold\" | \"fill\" | \"impl\" | \"patch\" | \"eval-fix\";\n\n/**\n * Flow-control instruction the caller acts on:\n * \"break\" — no tool call; abort the do/while\n * \"continue\" — self-check failed (or icon branch); feed back + next turn\n * \"proceed\" — self-check passed; advance to phase transition / eval round\n */\nexport type CodingTurnControl = \"break\" | \"continue\" | \"proceed\";\n\nexport interface CodingTurnResult {\n readonly control: CodingTurnControl;\n /** Set only when control === \"proceed\" — best compiled code from commitMeta. */\n readonly compiledCode: string;\n readonly selfCheckPassed: boolean;\n /** Outcome label for breakdown counters. Undefined when control === \"break\". */\n readonly outcome: CodingTurnOutcome | undefined;\n readonly phase: CodingTurnPhase | undefined;\n readonly tokens: { input: number; output: number };\n /**\n * Prompt-cache accounting for this turn, when the provider reports it.\n * Optional because not every provider exposes cache tokens — absent\n * means \"unreported\", never zero.\n */\n readonly cacheReadTokens?: number;\n readonly cacheCreationTokens?: number;\n readonly llmMs: number;\n readonly toolMs: number;\n /** Updated state — caller stores back into its own variables for next turn. */\n readonly lastResultText: string;\n readonly lastDiffFailed: boolean;\n readonly isEvalFeedback: boolean;\n readonly iconNamesCache: string | null;\n readonly preWarmedContext: PreWarmedEvalContext | null | undefined;\n /**\n * Set only on the `break` the same-exchange guard returns (ggui#404) — the\n * one way a caller can tell this guard ended the run, since `break` is a\n * control value many exits share. No key on any other turn.\n */\n readonly sameExchangeBreak?: SameExchangeBreak;\n /**\n * Set only on the `break` the same-failure guard returns (ggui#1791). No\n * key on any other turn.\n */\n readonly sameFailureBreak?: SameFailureBreak;\n}\n\n/**\n * Run one coding turn. Mutates `ctx.workspace` (file writes, commits) and\n * `ctx.commitMeta` (build/self-check metadata side-channel from executeTool).\n * Returns flow-control + measurements; caller threads them back as state.\n */\nexport async function runCodingTurn(\n ctx: CodingTurnContext,\n input: CodingTurnInput,\n): Promise<CodingTurnResult> {\n const {\n workspace,\n codingAgent,\n codingModel,\n systemPrompt,\n harness,\n contract,\n commitMeta,\n originalProps,\n costTracker,\n } = ctx;\n const {\n turnsUsed,\n a1Phase,\n lastResultText,\n lastDiffFailed,\n isEvalFeedback,\n } = input;\n let { iconNamesCache, preWarmedContext } = input;\n\n // Restore Props interface if the LLM changed it\n if (originalProps) {\n const current = workspace.read() ?? \"\";\n const currentProps = current.match(/interface Props \\{[\\s\\S]*?\\n\\}/)?.[0];\n if (currentProps && currentProps !== originalProps) {\n workspace.write(current.replace(currentProps, originalProps));\n await workspace.stage();\n }\n }\n\n // Hashline format: when the profile is on, the\n // `## Current File` view includes per-line 2-char content hashes\n // (`N:hh│content`). Otherwise, the existing numeric-only format.\n const hashlineMode = ctx.contextPolicy?.hashline ?? \"off\";\n const currentFile =\n hashlineMode === \"v2\"\n ? formatWithHashlines(workspace.read() ?? \"\")\n : workspace.cat();\n let userPrompt: string;\n\n if (a1Phase === \"scaffold\") {\n // ── Scaffold pass (experimental, env: GGUI_A1=1) ──\n // Goal: a compileable structural first pass — no feature content\n // yet. The smaller patch surface means next-turn fills tend to have\n // fewer JSX tag-geometry failures than a one-shot implementation.\n userPrompt = `Produce a COMPILEABLE structural first pass. This is turn 1 of 2 — you are NOT implementing the feature yet.\n\n## Required this turn (non-negotiable)\n\n1. Declare all hooks from the boilerplate: \\`useState\\` for local state you'll need, plus every \\`useAction\\` / \\`useStream\\` / \\`useGguiContext\\` from the contract, plus any capability hooks declared in \\`clientCapabilities\\` (from \\`@ggui-ai/gadgets\\`)\n2. Build a minimal valid JSX skeleton — one top-level \\`<Container>\\` or \\`<Card>\\` with a \\`<Stack>\\` of empty-but-valid region containers (one per logical section of the UI)\n3. Keep the \\`export default function\\` signature + \\`Props\\` interface exactly as in the boilerplate\n\n## NOT required yet (next turn will fill these in)\n\n- Rendering prop values or real content\n- Wiring hook callbacks to UI elements (empty \\`onClick={() => {}}\\` is fine)\n- Styling polish, icons, badges, variants\n- Interactive flows and derived state\n\n**Goal: compile + pass syntactic checks. Broken JSX wastes the whole round-trip — keep it minimal and valid.**\n\n## Current File\n\\`\\`\\`tsx\n${currentFile}\n\\`\\`\\``;\n } else if (a1Phase === \"fill\") {\n // ── Fill pass (experimental) ──\n // The skeleton compiled. Flesh it out against a known-good tree.\n userPrompt = `The scaffold compiled. Now FILL in the details against the compiled skeleton. Make minimal, targeted patches — don't rewrite the whole file.\n\n## Required this turn (non-negotiable)\n\n1. Render every required prop from the Props interface in the appropriate region\n2. Wire every hook to a real interactive element with the correct payload shape\n3. Add real content — text, labels, icons, variants — so the UI matches the user's request\n\n## Allowed to simplify (ONLY flourishes/polish)\n\n- Elaborate animations → plain CSS transitions or static styles\n- Rare empty states → skip the branch\n- Fancy layout refinements → simpler grid/stack\n\n**Preserve the scaffolded region containers wherever possible.** Patch surgically inside them instead of rewriting the tree. Broken JSX or type errors waste a whole round-trip.\n\n## Current File (scaffolded, compiles)\n\\`\\`\\`tsx\n${currentFile}\n\\`\\`\\``;\n } else if (turnsUsed === 1) {\n // ── Phase 1: Implementation ──────────────────────────\n // The load-bearing structure of this prompt: 3 numbered\n // non-negotiables plus an explicit \"allowed to simplify\" scope.\n // Benchmarking found this shape produces materially better\n // implementation-pass rates and fewer malformed tool calls than\n // either a longer or a flatter variant.\n // v2.1 falsified \"fallback wording = universal fix\" — helped multi-step\n // forms (+44pp onboarding) but regressed rendering commits (-45pp\n // product-page) and slowed Google/OpenAI. Multi-shape need is A2 scaffold\n // territory, not prompt wording.\n userPrompt = `Deliver a compileable, end-to-end first pass in one turn.\n\n## Required this turn (non-negotiable)\n\n1. JSX structure that parses — balanced tags, closed fragments, no stray braces\n2. Render every required prop from the Props interface\n3. Wire every \\`useAction\\` / \\`useStream\\` / \\`useGguiContext\\` hook from the boilerplate to a visible element. If the contract declared \\`clientCapabilities\\`, the boilerplate emits a capability-hook call for each (e.g., \\`const loc = useGeolocation();\\`); call \\`.start()\\` from a UI control and render the result.\n\n## Allowed to simplify (ONLY flourishes/polish — NOT core work above)\n\n- Elaborate animations → plain CSS transitions or static styles\n- Rare empty states → skip the branch entirely\n- Fancy layout refinements → simpler grid/stack\n\n**If a flourish risks broken JSX or type errors, OMIT it rather than leaving a placeholder or partial structure.** No TODOs, no half-finished helpers, no stub components. Broken syntax or missing core work wastes a whole round-trip.\n\nRead the boilerplate comments — each hook has its type and call signature inline. Follow P0 → P1 → P2 priority from the system prompt.\n\n## Current File\n\\`\\`\\`tsx\n${currentFile}\n\\`\\`\\``;\n } else {\n // ── Phase 2: Targeted patches (self-check or eval issues) ──\n // Prioritize issues so the LLM fixes the most critical first.\n const issues = lastResultText;\n const diffHint = lastDiffFailed\n ? `\\n**Your last diff did not apply.** Make sure context lines match the current file exactly. Use 3 lines of context around each change.\\n`\n : \"\";\n\n // Resolve dynamic criteria from pre-warm (non-blocking: if not ready yet, skip)\n if (!preWarmedContext && input.preWarmPromise) {\n // Race: resolve immediately if ready, otherwise skip this turn\n preWarmedContext = await Promise.race([\n input.preWarmPromise,\n new Promise<null>((r) => setTimeout(r, 0, null)),\n ]);\n }\n const issueHeader = isEvalFeedback ? \"## Evaluation Issues (fix all)\" : \"## Issues (fix all)\";\n\n // ─────────────────────────────────────────────────────────────────────\n // Diagnostic retry prompt.\n // ─────────────────────────────────────────────────────────────────────\n // When a duplicate-patch was detected on the prior turn AND the policy\n // selected the diagnostic intervention, replace the normal \"Fix the\n // issues below\" blueprint with a focused, structured retry prompt:\n //\n // - line-numbered excerpt around the failing range (not full file)\n // - enumeration of the prior 2 failed fingerprints\n // - structured-diagnosis instruction routed via `commit_message`\n // - explicit \"next patch must differ materially\" rule\n //\n // Tool surface is UNCHANGED — same apply_changes + get_icons. The\n // intervention targets the LLM's reasoning state, not its tool\n // selection. See ui-generation-experiments.md #43.\n if (ctx.dupeBreak?.pendingDiagnosticTurn) {\n ctx.dupeBreak.pendingDiagnosticTurn = false;\n ctx.dupeBreak.awaitingDiagnosticOutcome = true;\n const recents = ctx.dupeBreak.recentFailedPatches;\n const head = recents[0];\n // Build a focused excerpt: ±15 lines around the most recent failing\n // range. The current file is shown with line numbers prefixed so\n // the LLM can name \"line X\" precisely. Falls back to full file if\n // we can't parse a range (defensive).\n const lines = currentFile.split(\"\\n\");\n const firstRange = head?.rangesShort.split(\",\")[0]?.trim() ?? \"\";\n const m = /^(\\d+)-(\\d+)$/.exec(firstRange);\n const focusStart = m ? Math.max(1, parseInt(m[1]!, 10) - 15) : 1;\n const focusEnd = m\n ? Math.min(lines.length, parseInt(m[2]!, 10) + 15)\n : lines.length;\n const numbered = lines\n .slice(focusStart - 1, focusEnd)\n .map((line, i) => `${String(focusStart + i).padStart(4, \"0\")}: ${line}`)\n .join(\"\\n\");\n const priorBlock = recents\n .map(\n (p, i) =>\n ` Attempt ${recents.length - i}: ranges=[${p.rangesShort}] error=\"${p.errClass}\" fp=${p.fingerprint.slice(0, 12)}`,\n )\n .join(\"\\n\");\n\n // #44 family-final ablation: when action is \"diagnostic-noforce\",\n // emit information-only — drop the \"must differ materially\" rule.\n // Tests whether information alone unlocks Gate 5 vs the coercion.\n // (Recompute policy here — effectivePolicy is computed later in\n // the post-tool-call detection block; this path runs earlier.)\n const promptPolicy = ctx.contextPolicy ?? harness.policy.context;\n const noForce = promptPolicy.dupeBreakAction === \"diagnostic-noforce\";\n const step2 = noForce\n ? `2. Then call \\`apply_changes\\`. The information above (line numbers + prior fingerprints) should let you see exactly what's wrong. If your patch turns out to be the same one you tried before, that's fine — but make sure you've verified line-by-line against the focused excerpt that the patch is actually correct.`\n : `2. Then call \\`apply_changes\\` with a patch that **differs materially** from your prior failed attempt — different ranges OR meaningfully different code at the same range. Re-emitting the same patch is not allowed.`;\n\n userPrompt = `[LOOP DETECTED] Your last patch was byte-identical to a prior failed patch and produced the same preflight error. You are stuck in a fixed point — apply_changes alone won't escape this loop unless you re-examine the file.\n\n## Prior failed attempts (most recent first)\n${priorBlock}\n\n## Failing region — focused excerpt (lines ${focusStart}–${focusEnd}, line-numbered)\n\\`\\`\\`tsx\n${numbered}\n\\`\\`\\`\n\n## What to emit on this turn\n\n1. Set \\`commit_message\\` to a one-line structured diagnosis in this exact format:\n \\`DIAG: why=<why the prior patch failed, ≤80 chars> | next=<what you will change instead, ≤80 chars> | lines=<startLine-endLine you will target>\\`\n${step2}\n\n## Issues from prior turn (full text — for context)\n${issues}\n`;\n } else {\n // NOTE: exp61 tested batch-fix emphasis (fix ALL errors in ONE\n // call). Bisect (exp62) showed that variants — strong text,\n // gated N≥2, split self-check/eval — all introduced regressions\n // on at least one provider/fixture combination. LLMs batch\n // naturally; the explicit instruction over-pressured them into\n // wide patches that reference undefined functions. Reverted to\n // the original short prompt. `GGUI_BATCH_FIX=on` preserved as\n // env-opt-in if future experimentation wants to revisit.\n const batchFixForced = typeof process !== \"undefined\" && process.env?.GGUI_BATCH_FIX === \"on\";\n const closingInstruction = batchFixForced\n ? `**Fix EVERY error listed above in THIS single \\`apply_changes\\` call.** Emit multiple \\`changes[]\\` entries — one per range.`\n : `Produce ONE \\`apply_changes\\` call targeting only the lines that need fixing.`;\n userPrompt = `Fix the issues below. Make **minimal, targeted changes** — do NOT rewrite the whole file.${diffHint}\n\n${issueHeader}\n${issues}\n\n## Current File\n\\`\\`\\`tsx\n${currentFile}\n\\`\\`\\`\n\n${closingInstruction}`;\n }\n }\n\n // Scoped fallback: if the provider exhausts retries with\n // malformed_tool_call (a transport error — the payload is too\n // complex), the router falls back to the narrower schema so the next\n // attempt fits within the JSON size ceiling.\n // When the prior patch turn's fingerprint matched, force\n // APPLY_CHANGES_TOOL_SCOPED for this one turn only. The flag is\n // consumed here so the next turn goes back to apply_changes unless\n // the chain re-triggers. The cooldown ticks down at turn start so\n // detection re-enables after N turns.\n const forceEscape = ctx.dupeBreak?.forceEscapeNextTurn === true;\n if (ctx.dupeBreak && forceEscape) ctx.dupeBreak.forceEscapeNextTurn = false;\n if (ctx.dupeBreak && ctx.dupeBreak.cooldown > 0) ctx.dupeBreak.cooldown--;\n const consecutiveBrokenApplies = ctx.dupeBreak?.consecutiveBrokenApplies ?? 0;\n const primitiveIndexMode = ctx.contextPolicy?.primitiveIndex ?? \"off\";\n const primitiveIndexForceFetch = ctx.contextPolicy?.primitiveIndexForceFetch ?? false;\n const primitiveIndexPlanTurn = ctx.contextPolicy?.primitiveIndexPlanTurn ?? false;\n const planFirstTurn = ctx.contextPolicy?.planFirstTurn ?? false;\n const codeFormat = ctx.contextPolicy?.codeFormat ?? \"array\";\n const tools = selectTurnTools(\n turnsUsed,\n forceEscape,\n consecutiveBrokenApplies,\n hashlineMode,\n primitiveIndexMode,\n primitiveIndexForceFetch,\n primitiveIndexPlanTurn,\n planFirstTurn,\n codeFormat,\n );\n ctx.onPrompt?.({ turn: turnsUsed, systemPrompt, userPrompt });\n const llmStart = Date.now();\n const response = await codingAgent.callTools(\n codingModel,\n systemPrompt,\n userPrompt,\n tools,\n \"required\",\n [APPLY_CHANGES_TOOL_SCOPED],\n );\n const llmMs = Date.now() - llmStart;\n if (costTracker) {\n // ggui#1524 — the cache counts reach the cap: a cached prefix is billed, so it is spend.\n costTracker.record(codingModel, response.inputTokens, response.outputTokens, {\n ...(response.cacheReadTokens !== undefined ? { read: response.cacheReadTokens } : {}),\n ...(response.cacheCreationTokens !== undefined ? { write: response.cacheCreationTokens } : {}),\n });\n }\n\n const tokens = { input: response.inputTokens, output: response.outputTokens };\n // Prompt-cache counters travel separately — only some providers report\n // them. Build a spread object so the four turn-return sites carry the\n // optional fields without defaulting absent ones to 0.\n const cacheTokens = {\n ...(response.cacheReadTokens !== undefined\n ? { cacheReadTokens: response.cacheReadTokens }\n : {}),\n ...(response.cacheCreationTokens !== undefined\n ? { cacheCreationTokens: response.cacheCreationTokens }\n : {}),\n };\n\n const call = response.toolCalls[0];\n if (!call) {\n // Track consecutive no-tool-calls. One observed fail mode is: turn\n // 1 broken-apply (preflight fail), turn 2 no-tool-call → break →\n // SKIP. Force one retry on the FIRST no-tool-call (the model has\n // the prior broken-patch context in scope and usually recovers);\n // break only on the second consecutive no-tool-call.\n if (ctx.dupeBreak) {\n ctx.dupeBreak.consecutiveNoToolCalls += 1;\n }\n const noToolStreak = ctx.dupeBreak?.consecutiveNoToolCalls ?? 1;\n const shouldBreak = noToolStreak >= 2;\n console.warn(\n `[simple] turn ${turnsUsed}: no tool call` +\n (shouldBreak ? ` — breaking (streak=${noToolStreak})` : ` — retrying (streak=${noToolStreak})`),\n );\n // On retry, prepend a directive to the next turn's lastResultText\n // so the prompt explicitly tells the LLM that no tool call was\n // observed and one is REQUIRED. Combined with the existing broken-\n // apply diagnostic (already in lastResultText from prior turn), the\n // model gets the full picture: \"your patch was broken AND you\n // didn't try again — fix the patch NOW.\"\n const retryDirective = shouldBreak\n ? lastResultText\n : `${lastResultText ?? \"\"}\\n\\n[harness] Your previous turn returned no tool call. You MUST issue an apply_changes (or scoped) tool call. Re-read the current file state and emit a corrected patch.`.trim();\n return {\n control: shouldBreak ? \"break\" : \"continue\",\n compiledCode: \"\",\n selfCheckPassed: false,\n outcome: undefined,\n phase: undefined,\n tokens,\n ...cacheTokens,\n llmMs,\n toolMs: 0,\n lastResultText: retryDirective,\n lastDiffFailed,\n isEvalFeedback,\n iconNamesCache,\n preWarmedContext,\n };\n }\n // Tool call present — reset the no-tool-call streak.\n if (ctx.dupeBreak) {\n ctx.dupeBreak.consecutiveNoToolCalls = 0;\n }\n\n // Handle get_available_icons — return icon list without consuming a turn\n if (call.name === \"get_available_icons\") {\n if (!iconNamesCache) {\n // The one list the Icon primitive renders (ggui#1015) — the same\n // export the check leg reads, so the tool never advertises a name\n // the primitive does not know (the former dist-relative dynamic\n // import fell back to a 40-name string whenever the path missed).\n iconNamesCache = LUCIDE_ICON_NAMES.join(\", \");\n }\n console.log(`[simple] turn ${turnsUsed}: get_available_icons`);\n let iconResult = `Available Lucide icon names (use with <Icon name=\"...\">):\\n${iconNamesCache}\\n\\n${ICON_LIST_NO_MATCH_GUIDANCE}`;\n // ggui#404 same-call circuit breaker. The icon list is constant by\n // construction, so every repeat is an identical exchange — record on\n // the BASE text (pre-nudge) so the chain keys stay stable across the\n // nudged turn. claude-balanced burned turns 5-15 on this exact loop.\n let iconRepeats = 0;\n if (ctx.dupeBreak) {\n iconRepeats = recordToolExchange(ctx.dupeBreak, call.name, call.input, iconResult);\n if (iconRepeats === 2) iconResult += SAME_EXCHANGE_NUDGE;\n }\n await codingAgent.sendToolResult([{ callId: call.id, name: call.name, result: iconResult }]);\n if (iconRepeats >= SAME_EXCHANGE_BREAK_AT) {\n console.log(\n `[coding-agent] SAME_EXCHANGE_BREAK | tool=${call.name} | repeats=${iconRepeats} — terminating run (ggui#404)`,\n );\n return {\n control: \"break\",\n compiledCode: \"\",\n selfCheckPassed: false,\n outcome: undefined,\n phase: undefined,\n tokens,\n ...cacheTokens,\n llmMs,\n toolMs: 0,\n lastResultText: iconResult,\n lastDiffFailed: false,\n isEvalFeedback: false,\n iconNamesCache,\n preWarmedContext,\n sameExchangeBreak: { tool: call.name, repeats: iconRepeats },\n };\n }\n return {\n control: \"continue\",\n compiledCode: \"\",\n selfCheckPassed: false,\n outcome: undefined,\n phase: undefined,\n tokens,\n ...cacheTokens,\n llmMs,\n toolMs: 0,\n lastResultText: iconResult,\n lastDiffFailed: false,\n isEvalFeedback: false,\n iconNamesCache,\n preWarmedContext,\n };\n }\n\n const toolStart = Date.now();\n const result = await executeTool(\n workspace,\n call.name,\n call.input,\n commitMeta,\n contract,\n harness.what.applyPatch,\n // Prefer the caller-threaded runtime-resolved policy\n // (session.resolvedPolicy.context) so experimental profiles take\n // effect. Falls back to the harness's static policy.\n ctx.contextPolicy ?? harness.policy.context,\n // Forward the third-party wrapper `.d.ts` map so autoCommit's\n // typecheck overlays the real wrapper declarations and a generated\n // direct gadget import gets strict option/return narrowing.\n harness.what.gadgetTypes,\n // Which tier-0 legs fire — the design-vocabulary legs stand down in\n // `free` mode; every contract leg runs in both.\n harness.designMode,\n // ggui#1122: the harness's pre-filtered axis checks run at auto-commit — the serve path.\n {\n checks: harness.check.axisChecks,\n classification: harness.classification,\n originalPrompt: ctx.originalPrompt,\n ...(harness.canvas !== undefined ? { canvas: harness.canvas } : {}),\n ...(ctx.fixtureProps !== undefined ? { fixtureProps: ctx.fixtureProps } : {}),\n },\n );\n const toolMs = Date.now() - toolStart;\n\n // ─────────────────────────────────────────────────────────────────────────\n // SCOPED_ESCAPE_USED mechanism check.\n // ─────────────────────────────────────────────────────────────────────────\n // When the prior turn fingerprint-matched, this turn was forced to\n // APPLY_CHANGES_TOOL_SCOPED (single change, ≤20 lines). Verify the LLM\n // actually emitted a conforming scoped call — otherwise the detector\n // fired but the escape path wasn't engaged, which is a wiring bug.\n //\n // The scoped tool shares `call.name === \"apply_changes\"` with the main\n // variant — distinguish by payload shape (changes.length === 1 and\n // endLine - startLine ≤ 20).\n if (forceEscape && ctx.dupeBreak && call.name === \"apply_changes\") {\n const changes = (call.input?.changes as\n | ReadonlyArray<{ startLine: number; endLine: number; code: string[] }>\n | undefined) ?? [];\n const scopedShape =\n changes.length === 1 &&\n changes[0] !== undefined &&\n changes[0].endLine - changes[0].startLine <= 20;\n if (scopedShape) {\n ctx.dupeBreak.scopedEscapeUsedCount++;\n console.log(\n `[coding-agent] SCOPED_ESCAPE_USED | range=${changes[0]?.startLine}-${changes[0]?.endLine} | count=${ctx.dupeBreak.scopedEscapeUsedCount}`,\n );\n }\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Duplicate-patch break detection (escape tool: APPLY_CHANGES_TOOL_SCOPED).\n // ─────────────────────────────────────────────────────────────────────────\n // Scope:\n // - Only `apply_changes` tool calls (the patch tool; `write` is full\n // rewrite, not comparable across turns).\n // - Across patch / impl / eval-fix phases. The fingerprint includes\n // the full sorted ranges + code + error class — if two consecutive\n // turns emit a byte-identical patch with the same preflight error,\n // it's a real loop regardless of which \"issue\" the LLM nominally\n // thinks it's addressing. Initial #42 bench had this gate set to\n // \"patch only\" (inherited from #41), which suppressed every fire\n // because eval-fix → patch transitions are the most common dupe\n // pathway in our risk:high logs.\n // - Only when `breakDuplicatePatch` policy flag is on.\n //\n // On dupe detection: augment the retry message with an explicit\n // [DUPLICATE_PATCH] preface so the LLM sees WHY the next turn is\n // restricted, and flip `forceEscapeNextTurn` + set cooldown=3 so the\n // next turn is forced to a scoped single-change apply_changes.\n // After a non-dupe fail, record the fingerprint for the next comparison.\n //\n // See ./dupe-break.ts for the state shape + fingerprint.\n const effectivePolicy = ctx.contextPolicy ?? harness.policy.context;\n const isPatchInvalid = !!result.error && result.result.startsWith(\"PATCH_INVALID\");\n const isApplyChanges = call.name === \"apply_changes\";\n // Dupe-break also covers SELF_CHECK_FAIL. An observed pathology: many\n // turns of identical apply_changes patches, each producing the same\n // tier-0/build-error result. The patch applied (not PATCH_INVALID)\n // but the resulting source failed self-check the same way every turn\n // — dupe-break would never fire if it gated on PATCH_INVALID only.\n //\n // `isFailedPatch` widens the gate to \"any failed apply_changes turn\";\n // `extractErrSignature` pulls a coarse error class from either:\n // - PATCH_INVALID: `esbuild error: <msg>`\n // - PATCH_APPLIED_BROKEN: `esbuild error: <msg>` (different prefix, same line)\n // - SELF_CHECK_FAIL: first violation line (e.g. \"[security] ...\" / \"Build errors: ...\")\n // A failed patch with an unrecognizable error format still fingerprints\n // (errClass becomes empty string, ranges+code carry the load).\n const isFailedPatch = !result.done && isApplyChanges;\n\n // ─────────────────────────────────────────────────────────────────────────\n // Diagnostic outcome scoring.\n // ─────────────────────────────────────────────────────────────────────────\n // The PRIOR turn rendered the diagnostic retry prompt. Score what\n // happened on this turn before any new dupe detection runs:\n // - did commit_message contain a parseable `DIAG:` (engagement)?\n // - did the LLM escape the loop (PASS, OR PATCH_INVALID with a\n // fingerprint that differs from `lastFailedPatchFingerprint`,\n // which still holds the dupe fingerprint we just intervened on)?\n //\n // Cleared regardless of outcome — one-shot scoring window.\n if (ctx.dupeBreak?.awaitingDiagnosticOutcome) {\n ctx.dupeBreak.awaitingDiagnosticOutcome = false;\n const commitMsg =\n typeof call.input?.commit_message === \"string\"\n ? call.input.commit_message\n : \"\";\n const returnedDiag = /^\\s*DIAG\\s*:/i.test(commitMsg);\n if (returnedDiag) {\n ctx.dupeBreak.diagnosticReturnedCount++;\n console.log(\n `[coding-agent] DUPE_DIAGNOSTIC_RETURNED | msg=${JSON.stringify(commitMsg.slice(0, 120))}`,\n );\n } else {\n console.log(\n `[coding-agent] DUPE_DIAGNOSTIC_RETURNED=false | msg=${JSON.stringify(commitMsg.slice(0, 120))}`,\n );\n }\n // Did the dupe loop break? The gate covers any failed\n // apply_changes (matching the detection block above). PASS /\n // DIFF_FAIL count as broken-by-progress; SELF_CHECK_FAIL on a\n // different patch counts as broken; an identical SELF_CHECK_FAIL\n // counts as stuck.\n const dupeFp = ctx.dupeBreak.lastFailedPatchFingerprint;\n let brokeLoop = false;\n if (result.done) {\n brokeLoop = true;\n } else if (isApplyChanges && dupeFp) {\n const { computePatchFingerprint } = await import(\"./dupe-break.js\");\n const changes2 = (call.input?.changes as\n | ReadonlyArray<{ startLine: number; endLine: number; code: string[] }>\n | undefined) ?? [];\n const errText2 = extractFailSignature(result.result);\n const currentFp = computePatchFingerprint(changes2, errText2);\n brokeLoop = currentFp !== dupeFp;\n } else {\n brokeLoop = true;\n }\n if (brokeLoop) {\n ctx.dupeBreak.diagnosticBrokeLoopCount++;\n console.log(`[coding-agent] DUPE_DIAGNOSTIC_BROKE_LOOP=true`);\n } else {\n console.log(`[coding-agent] DUPE_DIAGNOSTIC_BROKE_LOOP=false`);\n }\n }\n\n let augmentedResultText = result.result;\n if (\n isFailedPatch &&\n effectivePolicy?.breakDuplicatePatch &&\n ctx.dupeBreak\n ) {\n const { computePatchFingerprint } = await import(\"./dupe-break.js\");\n const changes = (call.input?.changes as\n | ReadonlyArray<{ startLine: number; endLine: number; code: string[] }>\n | undefined) ?? [];\n const errText = extractFailSignature(result.result);\n const fingerprint = computePatchFingerprint(changes, errText);\n const priorPrint = ctx.dupeBreak.lastFailedPatchFingerprint;\n const inCooldown = ctx.dupeBreak.cooldown > 0;\n if (priorPrint && priorPrint === fingerprint && !inCooldown) {\n // Dupe detected — branch on the policy's intervention choice.\n ctx.dupeBreak.cooldown = 3;\n ctx.dupeBreak.firedCount++;\n const action = effectivePolicy.dupeBreakAction ?? \"escape\";\n console.log(\n `[coding-agent] DUPLICATE_PATCH_BREAK fired | action=${action} | fingerprint=${fingerprint.slice(0, 12)} error=${JSON.stringify(errText.slice(0, 48))}`,\n );\n // Always record this failure into the recent-patches ring (newest first,\n // cap 2). Read by the diagnostic prompt; harmless under \"escape\" action.\n const codeHead = (() => {\n const sorted = [...changes].sort(\n (a, b) => a.startLine - b.startLine || a.endLine - b.endLine,\n );\n const flat = sorted\n .map((c) => (Array.isArray(c.code) ? c.code.join(\"\\n\") : String(c.code ?? \"\")))\n .join(\"\\n\");\n return flat.slice(0, 200);\n })();\n const rangesShort = [...changes]\n .sort((a, b) => a.startLine - b.startLine || a.endLine - b.endLine)\n .map((c) => `${c.startLine}-${c.endLine}`)\n .join(\", \");\n const errClass = (errText || \"unknown\").toLowerCase().slice(0, 60);\n const summary = { rangesShort, codeHead, errClass, fingerprint };\n ctx.dupeBreak.recentFailedPatches = [\n summary,\n ...ctx.dupeBreak.recentFailedPatches,\n ].slice(0, 2);\n\n if (action === \"diagnostic\" || action === \"diagnostic-noforce\") {\n // #43 / #44: leave tool surface alone; switch the next turn's\n // prompt to the structured-diagnosis variant. The prompt\n // assembly checks `action` again to decide whether to include\n // the \"must differ materially\" rule (#43) or omit it (#44).\n ctx.dupeBreak.pendingDiagnosticTurn = true;\n ctx.dupeBreak.diagnosticFiredCount++;\n // The augmented retry text below explains WHY the next prompt\n // will look different. Tools still unrestricted.\n augmentedResultText =\n `[DUPLICATE_PATCH] Identical failed patch detected.\\n` +\n `Your previous patch was byte-identical to one you tried before ` +\n `and failed for the same reason. The next prompt will give you a ` +\n `focused excerpt of the failing region with line numbers and ` +\n `require a one-line structured diagnosis (in commit_message) ` +\n `before your next patch. Your next apply_changes MUST differ ` +\n `materially from the prior failed patch — different ranges OR ` +\n `meaningfully different code.\\n\\n` +\n `Repeated error: ${errText}\\n\\n---\\n\\n` +\n result.result;\n } else {\n // #41/#42 (dormant): tool-surface escape via APPLY_CHANGES_TOOL_SCOPED.\n ctx.dupeBreak.forceEscapeNextTurn = true;\n augmentedResultText =\n `[DUPLICATE_PATCH] Identical failed patch detected.\\n` +\n `Your previous patch failed with the same error, and this retry is byte-identical.\\n` +\n `The next turn is FORCED to a scoped single-change apply_changes ` +\n `(one change, ≤20 lines). Target the minimal failing region — ` +\n `do not retry the full patch. The rest of the file is correct.\\n\\n` +\n `Repeated error: ${errText}\\n\\n---\\n\\n` +\n result.result;\n }\n }\n // Always record the current fingerprint so the NEXT patch turn can compare.\n ctx.dupeBreak.lastFailedPatchFingerprint = fingerprint;\n }\n // A successful done-patch breaks the chain — the LLM moved on. Reset\n // so we don't match stale fingerprints if a later successful patch\n // happens to land on the same ranges. The gate is `result.done` so\n // the SELF_CHECK_FAIL / PATCH_APPLIED_BROKEN paths still persist\n // their fingerprint for the next-turn comparison.\n if (result.done && ctx.dupeBreak?.lastFailedPatchFingerprint) {\n ctx.dupeBreak.lastFailedPatchFingerprint = null;\n }\n\n // Track consecutive PATCH_APPLIED_BROKEN (apply-and-warn) events so\n // selectTurnTools can escalate to REWRITE_TOOL after N in a row. The\n // counter resets on any clean apply (PASS / auto-commit success) so\n // the escape triggers only on sustained tangled states.\n if (ctx.dupeBreak && call.name === \"apply_changes\") {\n const wasBrokenApply = result.result.startsWith(\"PATCH_APPLIED_BROKEN\");\n if (wasBrokenApply) {\n ctx.dupeBreak.consecutiveBrokenApplies++;\n } else if (!result.error) {\n // clean apply (or non-error result for any reason) — reset\n ctx.dupeBreak.consecutiveBrokenApplies = 0;\n }\n } else if (ctx.dupeBreak && call.name === \"rewrite\") {\n // rewrite succeeded — file is fresh, reset the escape counter\n if (!result.error) ctx.dupeBreak.consecutiveBrokenApplies = 0;\n }\n\n // ggui#404 same-call circuit breaker — record the (name, input, BASE\n // result) exchange. Keying on the base `result.result` (not the\n // augmented text, whose dupe-break prefaces vary) keeps the chain\n // stable; identical input alone is NOT counted (a re-read after a\n // patch legitimately repeats input with a fresh result). Second\n // identical exchange gets one explicit recovery nudge; the third\n // terminates the run below instead of burning the remaining turns.\n let sameExchangeRepeats = 0;\n if (ctx.dupeBreak) {\n sameExchangeRepeats = recordToolExchange(\n ctx.dupeBreak,\n call.name,\n call.input,\n result.result,\n );\n if (sameExchangeRepeats === 2) {\n augmentedResultText += SAME_EXCHANGE_NUDGE;\n }\n }\n\n // ggui#1791 same-failure guard — the patch fingerprint above keys on the\n // PATCH, so the same failure under a different patch each turn (a reworded\n // comment, a moved line) never counts as stuck. This keys on the FAILURE:\n // each failing check a write reports is counted since the last passing\n // write, whatever failed in between. The third report of one gets a nudge,\n // the fifth ends the run. A passing write clears the counts; a non-write\n // tool (cat, icons) changes nothing and leaves them as they were.\n const isWrite = call.name === \"apply_changes\" || call.name === \"rewrite\";\n let repeatedFailure: RepeatedFailure | undefined;\n if (ctx.dupeBreak && isWrite) {\n if (result.done) {\n clearWriteFailures(ctx.dupeBreak);\n } else {\n repeatedFailure = recordWriteFailure(ctx.dupeBreak, result.result);\n if (repeatedFailure?.repeats === SAME_FAILURE_NUDGE_AT) {\n augmentedResultText += SAME_FAILURE_NUDGE;\n }\n }\n }\n\n // Send tool result back to close the API contract (Google/OpenAI/OpenRouter)\n // This enables proper session chaining on the next callTools() invocation.\n await codingAgent.sendToolResult([{\n callId: call.id,\n name: call.name,\n result: augmentedResultText,\n isError: !!result.error,\n }]);\n\n if (sameExchangeRepeats >= SAME_EXCHANGE_BREAK_AT) {\n console.log(\n `[coding-agent] SAME_EXCHANGE_BREAK | tool=${call.name} | repeats=${sameExchangeRepeats} — terminating run (ggui#404)`,\n );\n return {\n control: \"break\",\n compiledCode: \"\",\n selfCheckPassed: false,\n outcome: undefined,\n phase: undefined,\n tokens,\n ...cacheTokens,\n llmMs,\n toolMs,\n lastResultText: augmentedResultText,\n lastDiffFailed: false,\n isEvalFeedback: false,\n iconNamesCache,\n preWarmedContext,\n sameExchangeBreak: { tool: call.name, repeats: sameExchangeRepeats },\n };\n }\n\n if (repeatedFailure !== undefined && repeatedFailure.repeats >= SAME_FAILURE_BREAK_AT) {\n const signature = repeatedFailure.signature.slice(0, 160);\n console.log(\n `[coding-agent] SAME_FAILURE_BREAK | tool=${call.name} | repeats=${repeatedFailure.repeats} | failure=${JSON.stringify(signature.slice(0, 80))} — terminating run (ggui#1791)`,\n );\n return {\n control: \"break\",\n compiledCode: \"\",\n selfCheckPassed: false,\n outcome: undefined,\n phase: undefined,\n tokens,\n ...cacheTokens,\n llmMs,\n toolMs,\n lastResultText: augmentedResultText,\n lastDiffFailed: false,\n isEvalFeedback: false,\n iconNamesCache,\n preWarmedContext,\n sameFailureBreak: { signature, repeats: repeatedFailure.repeats },\n };\n }\n\n // Track whether the diff itself failed to apply (vs applied but had violations)\n const turnDiffFailed = !!result.error && result.result.includes(\"DIFF\");\n\n // (`isPatchInvalid` was already computed above for dupe-break detection.)\n const isDiffFail = turnDiffFailed && !isPatchInvalid;\n const outcome: CodingTurnOutcome = result.done\n ? \"PASS\"\n : isPatchInvalid\n ? \"PATCH_INVALID\"\n : isDiffFail\n ? \"DIFF_FAIL\"\n : \"SELF_CHECK_FAIL\";\n\n const phase: CodingTurnPhase =\n a1Phase === \"scaffold\"\n ? \"scaffold\"\n : a1Phase === \"fill\"\n ? \"fill\"\n : turnsUsed === 1\n ? \"impl\"\n : isEvalFeedback\n ? \"eval-fix\"\n : \"patch\";\n\n console.log(\n `[simple] turn ${turnsUsed} (${phase}): ${outcome} | llm=${llmMs}ms tool=${toolMs}ms | in=${response.inputTokens} out=${response.outputTokens}`,\n );\n // Preview model output for debugging — show first tool call summary\n if (!result.done) {\n const preview = JSON.stringify(call.input).slice(0, 150);\n console.log(`[simple] turn ${turnsUsed} preview: ${preview}...`);\n }\n\n if (!result.done) {\n // Self-check failed — feed back errors for next turn (phase 2)\n return {\n control: \"continue\",\n compiledCode: \"\",\n selfCheckPassed: false,\n outcome,\n phase,\n tokens,\n ...cacheTokens,\n llmMs,\n toolMs,\n // Use the augmented text so the next turn's prompt gets the\n // [DUPLICATE_PATCH] preface when dupe-break fired (noop otherwise).\n lastResultText: augmentedResultText,\n lastDiffFailed: turnDiffFailed,\n isEvalFeedback: false,\n iconNamesCache,\n preWarmedContext,\n };\n }\n\n // ── Self-check passed — extract best compiled code from commit metadata ──\n let compiledCode = \"\";\n let selfCheckPassed = false;\n for (const [, meta] of commitMeta) {\n if (meta.build.success && meta.selfCheck.passed && meta.build.compiledCode) {\n compiledCode = meta.build.compiledCode;\n selfCheckPassed = true;\n }\n }\n if (!compiledCode) {\n // Fallback: use compiled-but-self-check-failed code (best effort for this session,\n // but should NOT be cached in pool — may have runtime bugs)\n for (const [, meta] of commitMeta) {\n if (meta.build.success && meta.build.compiledCode) {\n compiledCode = meta.build.compiledCode;\n }\n }\n }\n\n return {\n control: \"proceed\",\n compiledCode,\n selfCheckPassed,\n outcome,\n phase,\n tokens,\n ...cacheTokens,\n llmMs,\n toolMs,\n lastResultText,\n lastDiffFailed: turnDiffFailed,\n isEvalFeedback,\n iconNamesCache,\n preWarmedContext,\n };\n}\n","// packages/ui-gen/src/harness/enforced-coding.ts\n//\n// Provider-name mapping shared by the harness coding session\n// (`harness/coding/init-session.ts`, `harness/coding/run-eval-round.ts`).\n//\n// The text-only enforced coding loop that used to live here\n// (`runEnforcedCodingLoop` + its prompt builders) was superseded by the\n// tool-driven loop in `harness/coding/run-coding-turn.ts` and deleted.\n\n// =============================================================================\n// Provider Mapping\n// =============================================================================\n\n/**\n * Map AgentConfig provider names ('anthropic') to evaluator provider names ('claude').\n * The evaluator.ts uses 'claude' | 'openai' | 'google', while AgentConfig uses 'anthropic' | 'openai' | 'google'.\n */\nexport function mapProviderForEvaluator(provider: 'anthropic' | 'openai' | 'google' | 'openrouter'): 'claude' | 'openai' | 'google' | 'openrouter' {\n return provider === 'anthropic' ? 'claude' : provider;\n}\n\n/**\n * The visual judge's provider for an agent's provider (ggui#1248) — only the\n * providers whose SDK path takes an image (`createVisionAgent`: Anthropic,\n * Google). `undefined` for a provider with no vision path, so a caller must\n * decide what the visual leg does there instead of asserting it away: the\n * in-loop judge inherits the generation's agent by default, and an OpenAI or\n * OpenRouter lane reaching `createVisionAgent` got `undefined` back and threw.\n */\nexport function visionJudgeProvider(provider: 'anthropic' | 'openai' | 'google' | 'openrouter'): 'claude' | 'google' | undefined {\n switch (provider) {\n case 'anthropic':\n return 'claude';\n case 'google':\n return 'google';\n case 'openai':\n case 'openrouter':\n return undefined;\n }\n}\n","// packages/ui-gen/src/harness/coding/run-eval-round.ts\n//\n// One eval round (axis-checks + LLM eval + visual eval + merge + feedback\n// formatting), extracted from runSimpleHarness as part of the runHarness\n// migration (#142, step 2).\n//\n// Owns: the eval-round body — runCheck dispatch, low-risk bypass, parallel\n// LLM + visual eval, cost tracking, issue merge, cross-round subcategory\n// diff log, the continue/break/feedback decision, and feedback formatting\n// (capped at MAX_FEEDBACK_ISSUES per turn).\n//\n// Does NOT own: the do/while wrapper, the eligibility gate at the call\n// site (`!evalDone && compiledCode && ((tiersMod && (codeEval || visualEval))\n// || probeOnlyEnabled)` — the evaluation lane, or the probe-only lane a\n// serving deployment runs when it wires the runtime probe without an\n// evaluator, ggui#1380), or the threading of mutable state — caller still\n// owns those for now and the closure migration (step 3) will move them too.\n//\n// Behavior MUST match the inlined original byte-for-byte — this is a\n// mechanical extraction, not a redesign.\n\nimport type { DataContract, JsonObject } from \"@ggui-ai/protocol\";\nimport { criteriaContextFor } from \"../../evaluation/criteria/context.js\";\nimport { listContractGadgets } from \"@ggui-ai/protocol\";\nimport type { Classification } from \"../../classifier/index.js\";\nimport type { AgentWorkspace } from \"../../coding-agent/workspace.js\";\nimport type { CostTracker } from \"../../evaluation/cost-tracker.js\";\nimport type {\n ContractFeedbackRecord,\n EvalIssue,\n EvalResult,\n RuntimeProbeMeta,\n RuntimeProbeMetaDetail,\n RuntimeProbeRepair,\n VisualEvalSummary,\n VisualCoverage,\n} from \"../../evaluation/types-public.js\";\nimport { notApplicableCoverage } from \"../../evaluation/types-public.js\";\nimport { mapProviderForEvaluator, visionJudgeProvider } from \"../enforced-coding.js\";\nimport { runCheck } from \"../index.js\";\nimport {\n RENDER_CHECK_KINDS,\n isRecoverableRenderCrash,\n parseRuntimeSubcategory,\n type RenderCheckKind,\n} from \"../check/runtime-render/index.js\";\nimport type { Harness, RuntimeRenderOutcome } from \"../types-public.js\";\nimport type { AgentSpec, SingleComponentParams } from \"../runtime.js\";\nimport type {\n CanvasFitReading,\n VisualEvalContext,\n VisualEvalOutcome,\n VisualFitConfig,\n VisualFitOutcome,\n VisualLegTokens,\n} from \"../../evaluation/visual-evaluator.js\";\n\ntype PreWarmedEvalContext =\n import(\"../../evaluation/llm-evaluator.js\").PreWarmedEvalContext;\ntype LlmEvalMod = typeof import(\"../../evaluation/llm-evaluator.js\");\ntype LLMEvalTokenUsage = import(\"../../evaluation/llm-evaluator.js\").LLMEvalTokenUsage;\ntype VisualEvalMod = typeof import(\"../../evaluation/visual-evaluator.js\");\n\n/**\n * Persistent eval context — captured once per generation, reused across\n * every eval round. After step 3's closure migration, these will move\n * into the generate-runner's session state.\n */\nexport interface EvalRoundContext {\n readonly workspace: AgentWorkspace;\n readonly harness: Harness;\n readonly contract: DataContract | undefined;\n readonly userPrompt: string;\n readonly fixtureProps: JsonObject | undefined;\n readonly classification: Classification;\n readonly evaluationAgent: AgentSpec;\n readonly visualEvalAgent: AgentSpec;\n readonly visualEvaluation: SingleComponentParams[\"visualEvaluation\"];\n /** ggui#1436 — the shell as the caller named it, for the criteria selector's context; absent reads `unknown`. */\n readonly shellType?: SingleComponentParams[\"shellType\"];\n readonly visualThreshold: number;\n readonly qualityMode: \"fast\" | \"auto-improve\" | \"high-quality\";\n readonly maxEvalRounds: number;\n /**\n * The evaluation lane's cost tracker. `null` on the probe-only lane, which\n * runs no evaluator and records no cost; an evaluation round without one\n * lands on the round's infra-skipped stamp (ggui#1110) with the reason\n * {@link COST_TRACKER_ABSENT_REASON} — never a dereference.\n */\n readonly costTracker: CostTracker | null;\n readonly llmEvalMod: LlmEvalMod | null;\n readonly visualMod: VisualEvalMod | null;\n readonly preWarmPromise: Promise<PreWarmedEvalContext | null> | undefined;\n readonly onProgress?: (event: unknown) => void;\n /**\n * ggui#1380 — the probe-only lane: a serving deployment that wires the\n * runtime probe and configures NO evaluator. The round runs the probe\n * once and nothing else (no axis checks — the deterministic checks already\n * ran in the coding turns' self-check — no evaluator, no visual leg).\n * REQUIRED and explicit: it is never inferred from null modules, because the\n * evaluation lane with null modules is a different round (the evaluation\n * lane's own exit probe) and must stay one.\n */\n readonly probeOnly: boolean;\n /**\n * ggui#1380 — whether this generation already spent its one repair turn.\n * `false` on the first probe-only round: a recoverable render crash there\n * buys the turn. `true` on the second: the round breaks whatever the probe\n * reads and records the repair with the probe that bought it as `trigger`.\n * Meaningful on the probe-only lane only.\n */\n readonly probeRepairUsed: boolean;\n /**\n * ggui#1380 C2b — on the second probe-only round, the probe that bought the\n * repair turn (the first round's meta), recorded as `runtimeProbeRepair.trigger`\n * so the crash that happened is never lost behind the re-probe. The runner\n * sets it together with `probeRepairUsed`; a re-probe round without it is a\n * harness defect.\n */\n readonly probeRepairTrigger?: RuntimeProbeMeta;\n}\n\n/**\n * Per-round inputs that change between rounds.\n */\nexport interface EvalRoundInput {\n /** Compiled code from the most recent self-check-passing turn. */\n readonly compiledCode: string;\n /** Round counter BEFORE this round runs (function increments internally). */\n readonly evalRoundsUsed: number;\n readonly preWarmedContext: PreWarmedEvalContext | null | undefined;\n /** Mode-check subcategory keys from prior round, for cross-round diff log. */\n readonly prevModeSubcats: Set<string>;\n /**\n * Fail-fingerprints from prior round. Used by the stuck-loop detector:\n * if round N's fails are a strict subset of round N-1's fails, the LLM\n * is patching things the eval keeps re-flagging — exit early instead\n * of burning more turns. Tier-1 LLM-eval `functionality` fails are the\n * common offender on complex contract (chat-interface, kanban-board)\n * because the criterion auto-promotes any \"ALL features met?\" nitpick\n * to fail+critical, which the LLM can't always make go away.\n */\n readonly prevFailFingerprints: Set<string>;\n}\n\n/**\n * Flow-control instruction the caller acts on:\n * \"break\" — exit the do/while (low-risk bypass / no blocking / max\n * rounds / budget exhausted / eval error)\n * \"feedback\" — format issues into next coding turn's input; let the\n * outer while-condition re-enter for another turn\n */\nexport type EvalRoundControl = \"break\" | \"feedback\";\n\n/**\n * One call's (or one round's) token accounting. `input` is the NON-cached\n * input; the cache counts are present only when the provider reported them —\n * absent means unreported, never zero. The runner folds every coding turn and\n * every eval round through the same rule (`absorbTokens`), so the published\n * `tokens.total` holds one convention across both (ggui#1281, #1186).\n */\nexport interface TokenUsage {\n readonly input: number;\n readonly output: number;\n readonly cacheRead?: number;\n readonly cacheCreation?: number;\n}\n\nexport interface EvalRoundResult {\n readonly control: EvalRoundControl;\n /** True only on the low-risk bypass + clean-pass paths. */\n readonly evalDone: boolean;\n /** Latest evalResult — undefined only when the round didn't produce one\n * (eval error caught at the very top before runCheck completed). */\n readonly evalResult: EvalResult | undefined;\n /** Updated round counter (caller stores back). */\n readonly evalRoundsUsed: number;\n /** Updated subcategory set (caller stores back for next round's diff log). */\n readonly prevModeSubcats: Set<string>;\n /** Updated fail-fingerprint set (caller stores back for stuck detection). */\n readonly prevFailFingerprints: Set<string>;\n readonly preWarmedContext: PreWarmedEvalContext | null | undefined;\n /** Tokens added during this round — caller adds to its own totals. */\n readonly evalTokens: TokenUsage;\n /**\n * ggui#1522 — the in-loop visual judge's spend this round, apart from {@link evalTokens} (the text evaluator's,\n * priced at its model): already recorded in the cost tracker at the visual agent's model. Absent when no visual\n * leg ran or it reported no tokens.\n */\n readonly inLoopVisualTokens?: VisualLegTokens;\n /** Wall-clock of the parallel LLM + visual eval block (zero on the\n * low-risk bypass path, which exits before `Promise.all`). Caller\n * accumulates into its `cumulativeEvalLlmMs`. */\n readonly evalLlmMs: number;\n /** Feedback state — only meaningful when control === \"feedback\". */\n readonly lastResultText: string;\n readonly isEvalFeedback: boolean;\n readonly lastDiffFailed: boolean;\n /**\n * ggui#1261 — set ONLY on the round that granted a contract-feedback round:\n * what bought it and the source it was fed back on. The caller keeps it past\n * this round (the next round rebuilds `evalResult`) and stamps it on the\n * result the generation ends with.\n */\n readonly contractFeedback?: ContractFeedbackRecord;\n}\n\n/** Cap feedback to N issues per eval-fix turn so the LLM stays surgical. */\nconst MAX_FEEDBACK_ISSUES = 3;\n\n/**\n * ggui#1195 — the visual leg's deterministic fit verdict: the inline card's\n * content is taller than the box it was judged at (`canvas-overflow`,\n * critical ⇒ fail). Recognised by the marker the evaluator emits, never by\n * the description's wording.\n */\nfunction isFitFail(issue: EvalIssue): boolean {\n return issue.result === \"fail\" && issue.category === \"visual\" && issue.subcategory === \"canvas-overflow\";\n}\n/** The same marker as {@link isFitFail}, on the fingerprint `fingerprintFail` builds (`category|subcategory|…`). */\nconst FIT_FINGERPRINT_PREFIX = \"visual|canvas-overflow|\";\n\n/** `[fit]`-tagged so the LLM can see the violation is the box, not the judge's taste. */\nfunction formatFitFeedback(issue: EvalIssue): string {\n return `[fit] ${issue.category}/${issue.subcategory ?? \"\"}: ${issue.description}\\n Fix: ${issue.fix ?? \"\"}`;\n}\n\n/**\n * `criteriaCoverage` reason stamped on the same-image low-risk bypass\n * exits: tier-1/2 evaluation is never invoked there BY DESIGN, so every\n * criterion is `not-applicable` (excluded from coverage denominators),\n * not `skipped` (which would count as silent absence).\n */\n/** Why an eval result carries no criteria: the round itself threw (ggui#1110). */\nconst EVAL_ROUND_THREW_REASON = \"eval round threw\";\n\n/**\n * ggui#1380 — the coverage reasons a probe-only round stamps: no evaluator\n * and no visual leg are configured, BY DESIGN, so every criterion is\n * `not-applicable` (never `skipped`, which would read as a silent absence).\n */\nconst PROBE_ONLY_CRITERIA_REASON = \"probe-only round: no evaluator configured\";\nconst PROBE_ONLY_VISUAL_REASON = \"probe-only round: no visual evaluator configured\";\n/** The `pass` entry a probe-only round records — the probe was the only gate. */\nconst PROBE_ONLY_PASS = \"probe-only\";\n\n/**\n * D3 (ggui#1380) — the evaluation lane's one named guard: a round that\n * reaches the evaluator without a cost tracker cannot record what it spends,\n * so it stops HERE, on the ggui#1110 infra-skipped stamp with this reason,\n * instead of dereferencing `null` somewhere past the evaluator call.\n */\nexport const COST_TRACKER_ABSENT_REASON = \"cost tracker absent on an evaluation round\";\n\nfunction requireCostTracker(costTracker: CostTracker | null): CostTracker {\n if (costTracker === null) throw new Error(COST_TRACKER_ABSENT_REASON);\n return costTracker;\n}\n\n/**\n * The in-loop visual leg, made total (ggui#1248). The judge runs on a VISION\n * provider: the agent's provider narrowed by `visionJudgeProvider`, never\n * asserted into the vision union — a lane whose generation provider has no\n * vision path (OpenAI, OpenRouter) gets a leg recorded as SKIPPED with the\n * reason, and the judge is not called. And whatever the leg does, it resolves:\n * a rejection becomes the same skipped coverage with the error, so the round\n * never takes its thrown path on account of the visual leg and the runtime\n * probe still runs — a bar that requires the probe decides on the probe, not\n * on a judge that could not be reached.\n *\n * The leg's FIT half does not need the judge (ggui#1195): the fit verdict is a\n * frame at the declared box and a scroll height, so a no-vision lane with\n * canvases runs `measureFit` alone. Its canvas-overflow fail rides the round's\n * issues like the judge path's would — so the `[fit]` round the cap grants\n * can fire on that lane — and the coverage still reads `skipped` for the judge,\n * with what the fit half measured (or why it could not) appended. Without\n * that half, a card taller than its declared chat box on such a lane was\n * never told so in the loop, so the composition fix was never asked for.\n */\nfunction runVisualLeg(\n visualEvalAgent: AgentSpec,\n run: (provider: \"claude\" | \"google\") => Promise<VisualEvalOutcome>,\n measureFit: (() => Promise<VisualFitOutcome>) | undefined,\n): Promise<VisualEvalOutcome> {\n const provider = visionJudgeProvider(visualEvalAgent.provider);\n if (provider === undefined) {\n const noJudge = `no vision judge for provider '${visualEvalAgent.provider}' (model ${visualEvalAgent.model}) — the in-loop visual judge runs on a vision provider (anthropic, google)`;\n if (measureFit === undefined) {\n return Promise.resolve({ issues: [], coverage: { status: \"skipped\", reason: noJudge } });\n }\n const notMeasured = (why: string): VisualEvalOutcome => ({\n issues: [],\n coverage: { status: \"skipped\", reason: `${noJudge}; fit not measured: ${why}` },\n });\n return measureFit().then(\n (fit): VisualEvalOutcome =>\n fit.status === \"measured\"\n ? {\n issues: fit.issues,\n coverage: { status: \"skipped\", reason: `${noJudge}; fit measured without the judge: ${describeFitReadings(fit.readings)}` },\n }\n : notMeasured(fit.reason),\n (e: unknown): VisualEvalOutcome => notMeasured(e instanceof Error ? e.message : String(e)),\n );\n }\n return run(provider).catch((e: unknown): VisualEvalOutcome => ({\n issues: [],\n coverage: { status: \"skipped\", reason: `visual leg failed: ${e instanceof Error ? e.message : String(e)}` },\n }));\n}\n\n/** The fit half's receipt on the coverage: `xs-chat-card 384×516 content 535px (overflow)`, one per canvas. */\nfunction describeFitReadings(readings: readonly CanvasFitReading[]): string {\n return readings\n .map((r) => `${r.canvas} ${r.viewport.width}×${r.viewport.height} content ${r.contentHeight ?? \"?\"}px${r.overflow ? \" (overflow)\" : \"\"}`)\n .join(\", \");\n}\n\nconst LOW_RISK_BYPASS_REASON =\n \"same-image low-risk bypass: axis checks clean, tier-1/2 evaluation not invoked\";\n\n/**\n * Pick the ≤{@link MAX_FEEDBACK_ISSUES} issues an eval-fix turn feeds\n * back. Provenance-aware (Exp 54 P1 addendum): ONE slot is reserved\n * for the first deterministic tier-0 fail (axis/mode checks —\n * machine-verified findings) when one exists; the rest fill\n * fails-first then warns. Without the reservation, the merge order\n * put deterministic findings last and any round with ≥3 LLM-judge\n * fails silently starved them — the model never saw a precision-1.00\n * structural finding while the stuck detector blamed it for not\n * fixing it. Exactly one slot, so crash-class LLM fails keep the\n * other two. Exported for the pins.\n */\nexport function selectActionableFeedback(issues: readonly EvalIssue[]): EvalIssue[] {\n const pool = issues.filter((i) => i.result === \"fail\" || i.result === \"warn\");\n const reserved = pool.find((i) => i.tier === 0 && i.result === \"fail\");\n return [\n ...(reserved ? [reserved] : []),\n ...pool\n .filter((i) => i !== reserved)\n .sort((a, b) => (a.result === \"fail\" ? 0 : 1) - (b.result === \"fail\" ? 0 : 1)),\n ].slice(0, MAX_FEEDBACK_ISSUES);\n}\n\n/**\n * Fingerprint a fail issue for cross-round stuck detection. Identifies the\n * \"same fail\" without being thrown by minor description-text variation.\n * Format: `category|subcategory|first 40 chars of description, lowercased,\n * collapsed whitespace, line numbers stripped`. Line numbers are stripped\n * because the LLM may shift them while leaving the underlying bug intact —\n * we want those to fingerprint identical.\n */\nfunction fingerprintFail(issue: EvalIssue): string {\n const cat = issue.category ?? \"\";\n const sub = issue.subcategory ?? \"\";\n const desc = (issue.description ?? \"\")\n .toLowerCase()\n .replace(/line\\s+\\d+/g, \"line N\")\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, 40);\n return `${cat}|${sub}|${desc}`;\n}\n\n/**\n * Result of running the in-loop runtime probe at an exit-decision point.\n *\n * The eval-round orchestrator turns this into a `feedback` control with a\n * `[runtime]` violation when `recoverableFail === true`, granting the\n * harness ONE additional patch turn with the class-specific fix advice.\n * On `recoverableFail === false` the orchestrator falls through to the\n * original break path (the issues are still merged into the eval result\n * for telemetry / scoring).\n */\ninterface ProbeAtExitResult {\n readonly fired: boolean;\n /** True when probe produced ≥1 fail with a class `classifyRenderCrashFix` recognizes. */\n readonly recoverableFail: boolean;\n readonly probeIssues: readonly EvalIssue[];\n /**\n * Execution meta for the `EvalResult.runtimeProbe` stamp — the channel\n * that keeps \"probe never ran\" distinguishable from \"probe ran clean\"\n * downstream (ggui#403: the bench scored infra-dead probes as PASS\n * because zero `runtime:*` issues was its only signal).\n */\n readonly meta: RuntimeProbeMeta;\n}\n\n/**\n * The distinct check kinds among a probe's `result: 'fail'` issues, in the\n * order {@link RENDER_CHECK_KINDS} declares them (a render crash reads\n * first). Parsed from the `runtime:<check>[:<subject>]` subcategory the\n * adapter writes; a warn, an issue with no subcategory, or a subcategory that\n * names no check contributes nothing.\n */\nfunction failedCheckKinds(probeIssues: readonly EvalIssue[]): readonly RenderCheckKind[] {\n const failed = new Set<RenderCheckKind>();\n for (const issue of probeIssues) {\n if (issue.result !== \"fail\" || issue.subcategory === undefined) continue;\n const kind = parseRuntimeSubcategory(issue.subcategory);\n if (kind !== undefined) failed.add(kind);\n }\n return RENDER_CHECK_KINDS.filter((kind) => failed.has(kind));\n}\n\n/**\n * ONE builder for the meta every exit probe stamps (ggui#1380): the\n * probe-only round and the evaluation lane's exit probe both go through\n * `runProbeAtExit`, and this is where its outcome becomes a verdict. The\n * verdict is computed from the PROBE'S OWN issues: `fail` when any check\n * failed (`failChecks` = the distinct failing kinds), `pass` when none did;\n * a probe that did not run to a verdict (`timed-out`, `infra-skipped`,\n * `not-applicable`) carries no verdict key at all.\n *\n * The verdict is not the repair trigger. `fail` names ANY failing check;\n * the one repair turn fires on a `render-no-throw` fail that\n * `isRecoverableRenderCrash` recognises, and on nothing else — a `fail`\n * verdict whose checks are `prop-sensitivity`, `action-wiring` or any other\n * kind is recorded on the meta and never fed back.\n */\nfunction probeMetaOf(outcome: RuntimeRenderOutcome, probeIssues: readonly EvalIssue[]): RuntimeProbeMeta {\n const detail: RuntimeProbeMetaDetail = {\n ...(outcome.reason !== undefined ? { reason: outcome.reason } : {}),\n ...(outcome.renderMs !== undefined ? { renderMs: outcome.renderMs } : {}),\n ...(outcome.hostLoad !== undefined ? { hostLoad: outcome.hostLoad } : {}),\n ...(outcome.queuedMs !== undefined ? { queuedMs: outcome.queuedMs } : {}),\n ...(outcome.pendingAffordance !== undefined ? { pendingAffordance: outcome.pendingAffordance } : {}),\n };\n const elapsed = outcome.elapsedMs !== undefined ? { elapsedMs: outcome.elapsedMs } : {};\n if (outcome.status !== \"ran\") {\n return { status: outcome.status, ...elapsed, ...detail };\n }\n const [first, ...rest] = failedCheckKinds(probeIssues);\n if (first === undefined) {\n return { status: \"ran\", verdict: \"pass\", ...elapsed, ...detail };\n }\n return { status: \"ran\", verdict: \"fail\", failChecks: [first, ...rest], ...elapsed, ...detail };\n}\n\n/** The probe's status and, when it ran, its verdict — for the round's log line. */\nfunction describeProbeMeta(meta: RuntimeProbeMeta): string {\n if (meta.verdict === undefined) return meta.status;\n return meta.verdict === \"pass\" ? \"ran, verdict pass\" : `ran, verdict fail (${meta.failChecks.join(\", \")})`;\n}\n\n/**\n * Run the runtime-render probe ONCE at an exit-decision point. Off the\n * per-turn hot path: `runCheck` is invoked with `skipRuntimeRender: true`\n * every round; the probe (~500ms-2s) only fires here, when the harness\n * would otherwise exit.\n *\n * Returns `{ fired: false }` when there's nothing to probe (no compiled\n * code, no runtimeRender check on the harness, or the contract is empty).\n */\nasync function runProbeAtExit(input: {\n harness: Harness;\n sourceCode: string;\n compiledCode: string;\n contract: DataContract | undefined;\n fixtureProps: JsonObject | undefined;\n}): Promise<ProbeAtExitResult> {\n const { harness, sourceCode, compiledCode, contract, fixtureProps } = input;\n const probe = harness.check.runtimeRender;\n if (!probe || !compiledCode) {\n return {\n fired: false,\n recoverableFail: false,\n probeIssues: [],\n meta: {\n status: \"not-applicable\",\n reason: probe ? \"no compiled code\" : \"no runtimeRender check configured\",\n },\n };\n }\n let outcome: Awaited<ReturnType<typeof probe.run>>;\n try {\n outcome = await probe.run({\n sourceCode,\n compiledCode,\n contract,\n fixtureProps,\n });\n } catch (e) {\n // Probe infra failure that escaped even the adapter's catch — never\n // penalize the LLM for env mismatch, but carry the did-not-run\n // status so scoring can't mistake this for a clean pass.\n const message = e instanceof Error ? e.message : String(e);\n console.warn(`[simple] in-loop probe at exit: infra failure — ${message}`);\n return {\n fired: false,\n recoverableFail: false,\n probeIssues: [],\n meta: { status: \"infra-skipped\", reason: message },\n };\n }\n const meta = probeMetaOf(outcome, outcome.issues);\n if (outcome.status !== \"ran\") {\n return { fired: false, recoverableFail: false, probeIssues: [], meta };\n }\n const probeIssues = outcome.issues;\n const recoverableFail = probeIssues.some(\n (i) =>\n i.result === \"fail\" &&\n typeof i.subcategory === \"string\" &&\n i.subcategory.startsWith(\"runtime:render-no-throw\") &&\n typeof i.description === \"string\" &&\n isRecoverableRenderCrash(i.description),\n );\n return { fired: true, recoverableFail, probeIssues, meta };\n}\n\n/**\n * Format a single probe-emitted runtime issue as a `[runtime]` feedback\n * line for the next coding turn. Mirrors the loop's existing feedback\n * formatter (`[FAIL] category/subcat: ...\\n Fix: ...`) but tags it\n * `[runtime]` so the LLM can see the violation came from the in-loop\n * runtime probe rather than self-check / LLM eval.\n */\nfunction formatRuntimeProbeFeedback(issue: EvalIssue): string {\n const subcat = issue.subcategory ? `/${issue.subcategory}` : \"\";\n return (\n `[runtime] ${issue.category}${subcat}: ${issue.description}\\n` +\n ` Fix: ${issue.fix ?? \"\"}`\n );\n}\n\n/**\n * Exit-probe checks whose FAIL buys ONE feedback round although it is not a\n * crash: a contract defect the probe diagnoses deterministically, with a fix\n * text the model can act on in a turn. Without the round the loop recorded the\n * finding and shipped it — its own evaluator named the defect and the model\n * never heard. Named, and grown only with evidence: `prop-sensitivity` (a\n * declared prop ignored, a literal baked in its place — \"You\" for\n * `currentUser`) is the class measured failing across models (ggui#1261).\n */\nconst FEEDBACK_PROBE_CHECKS: readonly string[] = [\"prop-sensitivity\"];\n\n/** Rounds past the cap the contract-feedback round may use: one, as the fit round (ggui#1195). */\nconst CONTRACT_FEEDBACK_BONUS = 1;\n\n/** `runtime:<check>` or `runtime:<check>:<subject>` for a named feedback check, FAIL only. */\nfunction isFeedbackProbeFail(issue: EvalIssue): boolean {\n const sub = issue.subcategory;\n if (issue.result !== \"fail\" || typeof sub !== \"string\") return false;\n return FEEDBACK_PROBE_CHECKS.some((check) => sub === `runtime:${check}` || sub.startsWith(`runtime:${check}:`));\n}\n\n/**\n * The exit probe's feedback-worthy FAILs this generation has not been told\n * about yet. A finding whose fingerprint already rode a feedback round and\n * recurred is left out — one attempt per finding, then it ships as recorded.\n */\n/** The round's record: the findings that bought it, and the source they were found on. */\nfunction contractFeedbackRecord(fails: readonly EvalIssue[], sourceBefore: string): ContractFeedbackRecord {\n return { firedOn: fails.flatMap((i) => (i.subcategory !== undefined ? [i.subcategory] : [])), sourceBefore };\n}\n\nfunction contractFeedbackFails(exitProbe: ProbeAtExitResult, alreadyFedBack: ReadonlySet<string>): EvalIssue[] {\n if (!exitProbe.fired) return [];\n return exitProbe.probeIssues.filter((i) => isFeedbackProbeFail(i) && !alreadyFedBack.has(fingerprintFail(i)));\n}\n\n/**\n * Run one eval round. Mutates `ctx.costTracker` (records LLM eval tokens)\n * and `ctx.workspace` is read-only from this function's POV. Returns\n * flow-control + updated state; caller threads them back as variables.\n */\nexport async function runEvalRound(\n ctx: EvalRoundContext,\n input: EvalRoundInput,\n): Promise<EvalRoundResult> {\n const {\n workspace,\n harness,\n contract,\n userPrompt,\n fixtureProps,\n classification,\n evaluationAgent,\n visualEvalAgent,\n visualEvaluation,\n visualThreshold,\n qualityMode,\n maxEvalRounds,\n llmEvalMod,\n visualMod,\n preWarmPromise,\n onProgress,\n probeOnly,\n probeRepairUsed,\n probeRepairTrigger,\n } = ctx;\n const { compiledCode, prevModeSubcats, prevFailFingerprints } = input;\n let { evalRoundsUsed, preWarmedContext } = input;\n\n evalRoundsUsed++;\n onProgress?.({ type: \"generating\", phase: \"evaluating\" });\n const currentSource = workspace.read() ?? \"\";\n\n let evalResult: EvalResult | undefined;\n let evalTokens: TokenUsage = { input: 0, output: 0 };\n let inLoopVisualTokens: VisualLegTokens | undefined = undefined;\n let evalLlmMs = 0;\n\n try {\n // ── The probe-only round (ggui#1380) ──\n // A serving deployment that wires the runtime probe and configures no\n // evaluator: the probe runs ONCE, before anything else, and no axis\n // check runs (the served card is the coding turns' — its deterministic\n // checks ran in their self-check). A recoverable render crash on the\n // first round buys exactly one repair turn; the second round breaks\n // whatever it reads and records the repair's after. Timed-out,\n // infra-skipped and not-applicable never block and never repair.\n if (probeOnly) {\n const exitProbe = await runProbeAtExit({\n harness,\n sourceCode: currentSource,\n compiledCode,\n contract,\n fixtureProps,\n });\n const probeOnlyResult: EvalResult = {\n issues: [...exitProbe.probeIssues],\n pass: [PROBE_ONLY_PASS],\n runtimeProbe: exitProbe.meta,\n criteriaCoverage: notApplicableCoverage(PROBE_ONLY_CRITERIA_REASON),\n visualCoverage: { status: \"not-applicable\", reason: PROBE_ONLY_VISUAL_REASON },\n };\n const recoverableFail = exitProbe.fired && exitProbe.recoverableFail;\n if (probeRepairUsed) {\n // This round IS the re-probe (a repair that did not compile never\n // reaches a round — the runner stamps `compiled: false` itself). The\n // top level is the re-probe; the record names the probe that bought\n // the turn as `trigger`, so each probe is recorded exactly once.\n if (probeRepairTrigger === undefined) {\n throw new Error(\"harness defect: a probe-only re-probe round without the probe that bought the repair turn\");\n }\n const repair: RuntimeProbeRepair = { attempted: true, compiled: true, trigger: probeRepairTrigger };\n evalResult = { ...probeOnlyResult, runtimeProbeRepair: repair };\n console.log(\n `[simple] eval round ${evalRoundsUsed}: probe-only re-probe after the repair turn — ` +\n `${describeProbeMeta(exitProbe.meta)}${recoverableFail ? \", recoverable crash still present\" : \"\"} — serving`,\n );\n return {\n control: \"break\",\n evalDone: true,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats,\n prevFailFingerprints,\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: \"\",\n isEvalFeedback: false,\n lastDiffFailed: false,\n };\n }\n evalResult = probeOnlyResult;\n if (recoverableFail) {\n const runtimeFails = exitProbe.probeIssues.filter(\n (i) => i.result === \"fail\" && i.subcategory?.startsWith(\"runtime:\"),\n );\n const lines = runtimeFails.slice(0, MAX_FEEDBACK_ISSUES).map(formatRuntimeProbeFeedback);\n console.log(\n `[simple] eval round ${evalRoundsUsed}: probe-only round — runtime probe fail (recoverable) — granting the one repair turn`,\n );\n return {\n control: \"feedback\",\n evalDone: false,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats,\n prevFailFingerprints,\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: lines.join(\"\\n\\n\"),\n isEvalFeedback: true,\n lastDiffFailed: false,\n };\n }\n console.log(\n `[simple] eval round ${evalRoundsUsed}: probe-only round — probe ${describeProbeMeta(exitProbe.meta)} — serving`,\n );\n return {\n control: \"break\",\n evalDone: true,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats,\n prevFailFingerprints,\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: \"\",\n isEvalFeedback: false,\n lastDiffFailed: false,\n };\n }\n\n // Tier 0 already ran in autoCommit — go straight to mode-checks + LLM eval.\n\n // ── Axis-keyed deterministic checks ──────────────\n // Contract-semantic, no LLM call, <100ms. Pre-filtered onto\n // harness.check.axisChecks at createHarness time; runCheck iterates\n // the already-gated list. Used up front so we can bypass the\n // expensive tier-1/2 LLM eval for low-risk vectors.\n //\n // 2026-04-27 (in-loop probe trigger): skip the runtime-render probe\n // here. The probe (~500ms-2s) runs ONCE at exit-decision time below,\n // not on every round. Goal: keep per-turn latency lean while still\n // catching crash-class fails before the harness ships broken UI.\n const checkResult = await runCheck({\n harness,\n sourceCode: currentSource,\n compiledCode,\n contract,\n prompt: userPrompt,\n fixtureProps,\n skipRuntimeRender: true,\n });\n const modeIssues: EvalIssue[] = [...checkResult.issues];\n const modeHasBlocking = modeIssues.some((i) => i.result === \"fail\");\n\n // A contract that declares `clientCapabilities.gadgets` always runs\n // the full LLM eval — a gadget is a contract obligation and the\n // evaluator is the only check that confirms it was actually USED.\n // A map / chart classifies as low-risk passive display, so without\n // this carve-out the bypass below would ship a component that\n // imports `<LeafletMap>` / `<Chart>` and never renders it, unseen.\n const contractDeclaresGadgets =\n contract !== undefined && listContractGadgets(contract).length > 0;\n\n // ── Low-risk bypass ──\n // Pure passive display (riskTier=low → state ∈ {none,ui-affordance},\n // writes=none, realtime=none, fetch=none) with clean axis checks\n // skips the LLM eval round — its findings are typically polish\n // warns, not worth the 3-6s Haiku cost. Gadget contracts are exempt\n // (see above) — they always need the evaluator.\n if (\n classification.riskTier === \"low\" &&\n !modeHasBlocking &&\n !contractDeclaresGadgets\n ) {\n // ── In-loop probe at exit-decision (one-shot) ──\n // Low-risk fixtures still ship runtime crashes (e.g.,\n // \"is not iterable\" on an empty array prop). Probe here before\n // declaring evalDone; if recoverable → +1 turn with [runtime]\n // violation; otherwise the probe issues (if any) merge into the\n // evalResult for telemetry and we exit clean.\n const exitProbe = await runProbeAtExit({\n harness,\n sourceCode: currentSource,\n compiledCode,\n contract,\n fixtureProps,\n });\n if (exitProbe.fired && exitProbe.recoverableFail) {\n const runtimeFails = exitProbe.probeIssues.filter(\n (i) => i.result === \"fail\" && i.subcategory?.startsWith(\"runtime:\"),\n );\n const lines = runtimeFails.slice(0, MAX_FEEDBACK_ISSUES).map(formatRuntimeProbeFeedback);\n const allIssues = [...modeIssues, ...exitProbe.probeIssues];\n evalResult = {\n issues: allIssues,\n pass: [\"axis.low-risk\"],\n criteriaCoverage: notApplicableCoverage(LOW_RISK_BYPASS_REASON),\n runtimeProbe: exitProbe.meta,\n };\n console.log(\n `[simple] eval round ${evalRoundsUsed}: low-risk bypass clean BUT ` +\n `runtime probe fail (recoverable) — granting +1 turn`,\n );\n return {\n control: \"feedback\",\n evalDone: false,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats,\n prevFailFingerprints,\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: lines.join(\"\\n\\n\"),\n isEvalFeedback: true,\n lastDiffFailed: false,\n };\n }\n evalResult = {\n issues: [...modeIssues, ...exitProbe.probeIssues],\n pass: [\"axis.low-risk\"],\n criteriaCoverage: notApplicableCoverage(LOW_RISK_BYPASS_REASON),\n runtimeProbe: exitProbe.meta,\n };\n console.log(\n `[simple] eval round ${evalRoundsUsed}: low-risk bypass ` +\n `(axis-checks clean, tier-1/2 skipped${exitProbe.fired ? \", probe ran\" : `, probe ${exitProbe.meta.status}`}) — PASS`,\n );\n return {\n control: \"break\",\n evalDone: true,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats,\n prevFailFingerprints,\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: \"\",\n isEvalFeedback: false,\n lastDiffFailed: false,\n };\n }\n\n // D3 (ggui#1380) — the evaluation lane records what it spends; without a\n // tracker it stops here, on the thrown-round stamp, with the reason.\n const costTracker = requireCostTracker(ctx.costTracker);\n\n // Await pre-warmed context (only on first eval round, generated during coding)\n if (evalRoundsUsed === 1 && !preWarmedContext && preWarmPromise) {\n preWarmedContext = await preWarmPromise;\n }\n\n // ── Tier 1+2: LLM evaluation + Visual eval in parallel ──\n let llmResult: (EvalResult & LLMEvalTokenUsage) | null = null;\n let visualIssues: EvalIssue[] | null = null;\n\n // The visual leg's page and frame — ONE value each, read by the judge and\n // by its fit half alike, so both frame the same component the same way.\n const visualContext: VisualEvalContext = {\n compiledCode,\n originalPrompt: userPrompt,\n profile: harness.profile,\n // The caller's theme, when named — the round paints what the app paints.\n ...(visualEvaluation?.cssTokens !== undefined ? { cssTokens: visualEvaluation.cssTokens } : {}),\n // ggui#1436 — the criteria bank and the card's context; the judge selects per canvas, report-only.\n ...(visualEvaluation?.criteriaBank !== undefined\n ? {\n criteria: {\n bank: visualEvaluation.criteriaBank,\n context: criteriaContextFor({\n classification,\n contract,\n cssTokens: visualEvaluation.cssTokens,\n profile: harness.profile,\n shell: ctx.shellType ?? \"unknown\",\n ...(visualEvaluation.criteriaKind !== undefined ? { kind: visualEvaluation.criteriaKind } : {}),\n }),\n },\n }\n : {}),\n };\n const visualFrame: VisualFitConfig = {\n // The in-loop visual round renders the same sample the runtime probe\n // does (the caller's fixture) unless the config names its own.\n sampleProps: visualEvaluation?.sampleProps ?? fixtureProps,\n // Per-canvas judging (arm-neutral) — absent = single shot.\n ...(visualEvaluation?.canvases !== undefined ? { canvases: visualEvaluation.canvases } : {}),\n // ggui#1195 — the declared box per canvas (same-target with the composer).\n ...(visualEvaluation?.canvasViewports !== undefined ? { canvasViewports: visualEvaluation.canvasViewports } : {}),\n };\n // The fit verdict is per canvas: a single-shot leg has no box to hold content against.\n const measureFit =\n visualMod && visualFrame.canvases !== undefined && visualFrame.canvases.length > 0\n ? () => visualMod.runVisualFit(visualContext, visualFrame)\n : undefined;\n\n const evalLlmStart = Date.now();\n const [llm, visual] = await Promise.all([\n llmEvalMod\n ? llmEvalMod.runLLMEvaluation(\n {\n sourceCode: currentSource,\n originalPrompt: userPrompt,\n contract,\n // Criteria + mother prompt follow the triad that produced\n // the source (free mode: color-only tokens, arm-neutral\n // visual judging).\n designMode: harness.designMode,\n profile: harness.profile,\n },\n {\n provider: mapProviderForEvaluator(evaluationAgent.provider),\n model: evaluationAgent.model,\n // #484 — thread the coding-agent's routing override\n // through to the evaluator so its LLM call never falls\n // back to `process.env` either (the eval calls run\n // inside the same concurrent generation, so the race is\n // real here too, not just on the coding turn).\n routeOverride: evaluationAgent.routeOverride,\n // #489 — thread the same provider-429-retry observer.\n // Without this, a rate-limited retry inside the\n // evaluation agent's apiCall() happens (the base-class\n // retry loop is unconditional) but never reaches the\n // caller, silently missing the host application's\n // structured log.\n onRetry: evaluationAgent.onRetry,\n },\n preWarmedContext,\n )\n : null,\n visualMod\n ? runVisualLeg(\n visualEvalAgent,\n (provider) =>\n visualMod.runVisualEval(visualContext, {\n provider,\n model: visualEvalAgent.model,\n passThreshold: visualThreshold,\n viewport: visualEvaluation?.viewport,\n ...visualFrame,\n // #484/#489 — same threading as the LLM-eval leg above:\n // the visual eval's multimodal call runs inside the same\n // concurrent generation, so it needs the same routing\n // override (never fall back to `process.env`) and the\n // same provider-429-retry observer (retries reach the\n // host application's structured log).\n routeOverride: visualEvalAgent.routeOverride,\n onRetry: visualEvalAgent.onRetry,\n }),\n measureFit,\n )\n : null,\n ]);\n evalLlmMs = Date.now() - evalLlmStart;\n llmResult = llm;\n visualIssues = visual?.issues ?? null;\n // ggui#1522 — the in-loop visual judge's own spend: recorded in the tracker at the VISUAL agent's model, so\n // `canContinue()` sees it, and carried apart from `evalTokens` (the text evaluator's model).\n // The report-only criteria calls (ggui#1436) count toward the cap too, deliberately: the cap bounds MONEY SPENT,\n // and a cap that left out real spend would under-count exactly as this leg did before. So under a tight cap a\n // configured criteria bank's calls can end the eval loop earlier — the one place a report-only block reaches an\n // outcome, and it does so through its cost, never through its answers. The tracker's total feeds no metered figure.\n inLoopVisualTokens = visual?.tokens;\n if (inLoopVisualTokens !== undefined) {\n costTracker.record(visualEvalAgent.model, inLoopVisualTokens.inputTokens, inLoopVisualTokens.outputTokens);\n const criteriaSpend = inLoopVisualTokens.criteria;\n if (criteriaSpend !== undefined) costTracker.record(visualEvalAgent.model, criteriaSpend.inputTokens, criteriaSpend.outputTokens);\n }\n const visualSummary: VisualEvalSummary | undefined = visual?.summary;\n // ggui#1221 — the judge leg's coverage is ALWAYS stamped: ran / skipped (with the\n // reason) / not-applicable when no visual leg was configured for this round.\n const visualCoverage: VisualCoverage = visual?.coverage ?? { status: 'not-applicable', reason: 'visual leg not configured' };\n if (visualCoverage.status === 'skipped') {\n console.log(`[eval] visual-judge: SKIPPED (${visualCoverage.reason ?? 'no reason recorded'})`);\n }\n\n // Track costs from LLM eval calls\n if (llmResult) {\n // ggui#1524 — the text evaluator's cache counts reach the cap too.\n costTracker.record(evaluationAgent.model, llmResult.inputTokens, llmResult.outputTokens, {\n ...(llmResult.cacheReadTokens !== undefined ? { read: llmResult.cacheReadTokens } : {}),\n ...(llmResult.cacheCreationTokens !== undefined ? { write: llmResult.cacheCreationTokens } : {}),\n });\n evalTokens = {\n input: llmResult.inputTokens,\n output: llmResult.outputTokens,\n ...(llmResult.cacheReadTokens !== undefined ? { cacheRead: llmResult.cacheReadTokens } : {}),\n ...(llmResult.cacheCreationTokens !== undefined ? { cacheCreation: llmResult.cacheCreationTokens } : {}),\n };\n }\n\n // ── Merge LLM + visual + mode-check issues into EvalResult ──\n const allIssues: EvalIssue[] = [\n ...(llmResult?.issues ?? []),\n ...(visualIssues ?? []),\n ...modeIssues,\n ];\n const allPass: string[] = [...(llmResult?.pass ?? [])];\n // Carry the per-criterion coverage stamp from the evaluator; every\n // later re-stamp of evalResult below spreads this base so the field\n // survives to the assembled result (benchmark reads it per run).\n evalResult = {\n issues: allIssues,\n pass: allPass,\n ...(llmResult?.criteriaCoverage !== undefined\n ? { criteriaCoverage: llmResult.criteriaCoverage }\n : {}),\n // Per-canvas visual summary — present only when canvases were\n // requested and the leg ran; every later re-stamp spreads this\n // base so it survives to the assembled result.\n ...(visualSummary !== undefined ? { visual: visualSummary } : {}),\n visualCoverage,\n };\n\n // ── Log merged results, with mode-check subcategory breakdown ──\n const fails = allIssues.filter((i) => i.result === \"fail\");\n const warns = allIssues.filter((i) => i.result === \"warn\");\n const modeFails = modeIssues.filter((i) => i.result === \"fail\").length;\n const modeWarns = modeIssues.filter((i) => i.result === \"warn\").length;\n const modeSubcatCounts = modeIssues.reduce<Record<string, number>>((acc, i) => {\n const key = i.subcategory ?? \"mode\";\n acc[key] = (acc[key] ?? 0) + 1;\n return acc;\n }, {});\n const modeBreakdown = Object.entries(modeSubcatCounts)\n .map(([k, v]) => `${k}×${v}`)\n .join(\", \");\n\n // Cross-round diff — only emit when round > 1 AND there's something to report\n const currSubcats = new Set(Object.keys(modeSubcatCounts));\n let crossRound = \"\";\n if (evalRoundsUsed > 1 && (prevModeSubcats.size > 0 || currSubcats.size > 0)) {\n const unresolved = [...currSubcats].filter((s) => prevModeSubcats.has(s));\n const fixed = [...prevModeSubcats].filter((s) => !currSubcats.has(s));\n const fresh = [...currSubcats].filter((s) => !prevModeSubcats.has(s));\n const parts: string[] = [];\n if (unresolved.length) parts.push(`unresolved=[${unresolved.join(\",\")}]`);\n if (fixed.length) parts.push(`fixed=[${fixed.join(\",\")}]`);\n if (fresh.length) parts.push(`new=[${fresh.join(\",\")}]`);\n if (parts.length) crossRound = ` | ${parts.join(\" \")}`;\n }\n const updatedPrevModeSubcats = currSubcats;\n\n console.log(\n `[simple] eval round ${evalRoundsUsed}: ${fails.length} fails, ${warns.length} warns | ` +\n `cost=$${costTracker.getTotal().toFixed(4)} | ` +\n `tiers: t1+2=${llmResult?.issues.length ?? 0} visual=${visualIssues?.length ?? 0} ` +\n `axis[${classification.riskTier}]=${modeFails}F/${modeWarns}W${modeBreakdown ? ` (${modeBreakdown})` : \"\"}${crossRound}`,\n );\n\n // ── Decide whether to continue the loop ──\n // In fast mode: only fails trigger another iteration, plus (ggui#1542) the visual JUDGE's major findings when\n // `visualEvaluation.actOn` is 'major'. They are taken from the visual outcome itself, never by category over the\n // merged list, because the text evaluator has a tier-2 `visual` criterion of its own. Only findings whose\n // `origin` is `judge` act (ggui#1545): the instruments' warn-level majors (fit's `canvas-overflow*` today) are\n // deterministic and run with or without a judge, so acting on them would switch a second feedback source on\n // with the judge's. Selecting by origin rather than excluding by name fails closed: a new instrument check, or\n // any issue with no origin, never joins the treatment unless it is marked a judge finding.\n // In auto-improve / high-quality: fails + warns trigger iterations.\n const blocking = evalResult.issues.filter((i) => i.result === \"fail\");\n const visualMajorsActed =\n visualEvaluation?.actOn === \"major\"\n ? (visualIssues ?? []).filter((i) => i.origin === \"judge\" && i.result === \"warn\" && i.severity === \"major\")\n : [];\n const shouldContinue =\n qualityMode === \"fast\"\n ? blocking.length > 0 || visualMajorsActed.length > 0\n : blocking.length > 0 || warns.length > 0;\n\n // Compute current round's fail fingerprints — used by the stuck-loop\n // detector (round N+1) and threaded back to caller for round N+2.\n const currFailFingerprints = new Set(blocking.map(fingerprintFail));\n\n if (!shouldContinue) {\n // ── In-loop probe at exit-decision (one-shot) ──\n // Tier-1/2 LLM eval said clean. The probe is the last gate before\n // the harness ships — if it catches a recoverable runtime crash\n // (function-not-iterable on Google × stock-ticker etc.), grant\n // +1 turn with class-specific [runtime] advice. Otherwise probe\n // issues merge into evalResult for scoring and we exit clean.\n const exitProbe = await runProbeAtExit({\n harness,\n sourceCode: currentSource,\n compiledCode,\n contract,\n fixtureProps,\n });\n if (exitProbe.fired && exitProbe.recoverableFail) {\n const runtimeFails = exitProbe.probeIssues.filter(\n (i) => i.result === \"fail\" && i.subcategory?.startsWith(\"runtime:\"),\n );\n const lines = runtimeFails.slice(0, MAX_FEEDBACK_ISSUES).map(formatRuntimeProbeFeedback);\n const enrichedIssues = [...allIssues, ...exitProbe.probeIssues];\n evalResult = { ...evalResult, issues: enrichedIssues, pass: allPass, runtimeProbe: exitProbe.meta };\n const enrichedFingerprints = new Set([\n ...currFailFingerprints,\n ...runtimeFails.map(fingerprintFail),\n ]);\n console.log(\n `[simple] eval round ${evalRoundsUsed}: tier-1/2 clean BUT ` +\n `runtime probe fail (recoverable) — granting +1 turn`,\n );\n return {\n control: \"feedback\",\n evalDone: false,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats: updatedPrevModeSubcats,\n prevFailFingerprints: enrichedFingerprints,\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: lines.join(\"\\n\\n\"),\n isEvalFeedback: true,\n lastDiffFailed: false,\n };\n }\n // ggui#1261 — a contract defect the probe diagnosed (a named check,\n // FAIL) that this generation has not been told about: ONE feedback\n // round with the probe's own diagnosis and fix. The next round re-runs\n // the probe at its exit, so the result this generation ends with\n // carries the post-fix stamp, never this one.\n const contractFails = contractFeedbackFails(exitProbe, prevFailFingerprints);\n if (contractFails.length > 0 && evalRoundsUsed < maxEvalRounds + CONTRACT_FEEDBACK_BONUS) {\n const lines = contractFails.slice(0, MAX_FEEDBACK_ISSUES).map(formatRuntimeProbeFeedback);\n evalResult = {\n ...evalResult,\n issues: [...allIssues, ...exitProbe.probeIssues],\n pass: allPass,\n runtimeProbe: exitProbe.meta,\n };\n console.log(\n `[simple] eval round ${evalRoundsUsed}: tier-1/2 clean BUT contract probe fail — granting +1 turn ` +\n `(ggui#1261; ${contractFails.map((i) => i.subcategory).join(\", \")})`,\n );\n return {\n control: \"feedback\",\n evalDone: false,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats: updatedPrevModeSubcats,\n prevFailFingerprints: new Set([...currFailFingerprints, ...contractFails.map(fingerprintFail)]),\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: lines.join(\"\\n\\n\"),\n isEvalFeedback: true,\n lastDiffFailed: false,\n contractFeedback: contractFeedbackRecord(contractFails, currentSource),\n };\n }\n // Probe didn't trip a recoverable fail — fold its issues (if any)\n // into the merged result and ALWAYS stamp its execution meta, so a\n // did-not-run probe is visible downstream even on this clean exit.\n evalResult = {\n ...evalResult,\n issues: [...allIssues, ...exitProbe.probeIssues],\n pass: allPass,\n runtimeProbe: exitProbe.meta,\n };\n console.log(`[simple] eval round ${evalRoundsUsed}: no blocking issues — PASS`);\n return {\n control: \"break\",\n evalDone: true,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats: updatedPrevModeSubcats,\n prevFailFingerprints: currFailFingerprints,\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: \"\",\n isEvalFeedback: false,\n lastDiffFailed: false,\n };\n }\n\n // Stuck-loop detector. From round 2 onward, if every fail this round was\n // also a fail last round, the LLM made no fail-resolving progress — the\n // eval keeps re-flagging the same issues (commonly tier-1 `functionality`\n // nitpicks the LLM can't make go away on complex contract). Burning more\n // turns risks introducing new bugs (saw \"Too many re-renders\" on chat-\n // interface in v7). Exit early; the post-eval scoring still runs.\n // 2026-04-27 (rev 3): runtime probe fails are exempt from stuck-loop\n // exit. claude × survey-form run3 hit stuck-loop at round 2 with a\n // SINGLE runtime fail recurring — exiting there gave the LLM only 1\n // retry. Runtime crashes are critical and the LLM often needs 3+ tries\n // to localize them; the +2 max-rounds extension is the right escape\n // hatch, not stuck-loop exit. Keep stuck-loop active for non-runtime\n // fail-sets (the original tier-1 nitpick case it was built for).\n // ggui#1195 follow-up: a FIT fail (`visual|canvas-overflow|…`) is exempt\n // the same way — its escape hatch is the one `[fit]` round at the cap, and\n // a card whose measured height did not move between rounds would otherwise\n // exit here as \"stuck\" before that round is ever reached (the adversarial\n // review ran the commit's own test and found round 2's break WAS the stuck\n // exit). Bounded: the cap block grants the fit round exactly once.\n const onlyExtensionExemptFails =\n currFailFingerprints.size > 0 &&\n [...currFailFingerprints].every((fp) => fp.includes(\"|runtime:\") || fp.startsWith(FIT_FINGERPRINT_PREFIX));\n if (\n evalRoundsUsed > 1 &&\n currFailFingerprints.size > 0 &&\n !onlyExtensionExemptFails &&\n [...currFailFingerprints].every((fp) => prevFailFingerprints.has(fp))\n ) {\n console.log(\n `[simple] eval round ${evalRoundsUsed}: stuck — all ${currFailFingerprints.size} ` +\n `fails recur from prior round, exiting eval-fix loop`,\n );\n // The stuck exit still SHIPS the code, so it gets the same exit\n // probe as every other exit path — issues merge for telemetry and\n // the runtimeProbe stamp lands (Exp 48 found this exit surfacing\n // as \"SKIP — no runtimeProbe stamp\" in the bench: honest, but a\n // probe here is cheap and the shipped code deserves the signal).\n // The RECURRING fails get no more feedback — stuck means the model\n // saw them and stopped converging on them.\n const stuckExitProbe = await runProbeAtExit({\n harness,\n sourceCode: currentSource,\n compiledCode,\n contract,\n fixtureProps,\n });\n evalResult = {\n ...evalResult,\n issues: [...evalResult.issues, ...stuckExitProbe.probeIssues],\n runtimeProbe: stuckExitProbe.meta,\n };\n // ggui#1261 — a contract defect the exit probe diagnosed here was never\n // DELIVERED: the stuck set is non-runtime by construction (runtime-only\n // sets are exempt above), and the stuck premise is \"the model saw these\n // and did not resolve them\". So it gets the same one round as at the\n // clean-PASS and cap exits — the probe's diagnosis only, never the\n // recurring fail; one attempt per finding; bounded at the cap + 1 (Exp\n // 011, candidate r5: the one FAIL that shipped without a round).\n const stuckContractFails = contractFeedbackFails(stuckExitProbe, prevFailFingerprints);\n if (stuckContractFails.length > 0 && evalRoundsUsed < maxEvalRounds + CONTRACT_FEEDBACK_BONUS) {\n const lines = stuckContractFails.slice(0, MAX_FEEDBACK_ISSUES).map(formatRuntimeProbeFeedback);\n console.log(\n `[simple] eval round ${evalRoundsUsed}: stuck BUT contract probe fail never delivered — granting +1 turn ` +\n `(ggui#1261; ${stuckContractFails.map((i) => i.subcategory).join(\", \")})`,\n );\n return {\n control: \"feedback\",\n evalDone: false,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats: updatedPrevModeSubcats,\n prevFailFingerprints: new Set([...currFailFingerprints, ...stuckContractFails.map(fingerprintFail)]),\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: lines.join(\"\\n\\n\"),\n isEvalFeedback: true,\n lastDiffFailed: false,\n contractFeedback: contractFeedbackRecord(stuckContractFails, currentSource),\n };\n }\n return {\n control: \"break\",\n evalDone: false,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats: updatedPrevModeSubcats,\n prevFailFingerprints: currFailFingerprints,\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: \"\",\n isEvalFeedback: false,\n lastDiffFailed: false,\n };\n }\n\n // Max eval rounds reached — exit, EXCEPT when there's an active runtime\n // probe fail. Runtime crashes are the harshest production failure\n // (broken UI ships) and are worth up to 2 extra retry rounds.\n //\n // 2026-04-27 (rev 2): widened from \"newly-introduced only\" to \"any\n // active runtime fail, up to maxEvalRounds + 2\". Class-specific fix\n // advice is plumbed through; the LLM needs more attempts for hard\n // crash classes (e.g., \"Too many re-renders\", which requires reasoning\n // about which setState is unbounded). Runaway risk is bounded by:\n // 1. The stuck-loop detector above — exits if every fail recurs\n // from the prior round.\n // 2. Hard cap at maxEvalRounds + 2.\n // The \"newly-introduced only\" gate was too tight: when an LLM patch\n // surfaces a runtime crash AND introduces other fixable fails, the\n // stuck-loop detector won't fire (some fails change), but the cap\n // hits with the runtime fail unresolved.\n const RUNTIME_EXTENSION_BONUS = 2;\n // ggui#1195 — a fit fail (the hello does not fit its declared first\n // screen — the founder's ruling is FAIL, not warn) active at the cap is\n // worth ONE more round: the fix is a composition change the LLM can make\n // in a turn, and without the round the card ships cut off.\n const FIT_EXTENSION_BONUS = 1;\n if (evalRoundsUsed >= maxEvalRounds) {\n // 2026-04-27 (in-loop probe trigger): probe is now off the per-turn\n // hot path; `blocking` from runCheck won't contain `runtime:*` fails\n // because we passed `skipRuntimeRender: true`. To honor the\n // RUNTIME_EXTENSION_BONUS gate, run the probe ONCE at this exit.\n const exitProbe = await runProbeAtExit({\n harness,\n sourceCode: currentSource,\n compiledCode,\n contract,\n fixtureProps,\n });\n const hasRuntimeFail =\n exitProbe.fired && exitProbe.recoverableFail;\n const allowRuntimeExtension =\n hasRuntimeFail &&\n evalRoundsUsed < maxEvalRounds + RUNTIME_EXTENSION_BONUS;\n const fitFails = evalResult.issues.filter(isFitFail);\n const allowFitExtension =\n !allowRuntimeExtension &&\n fitFails.length > 0 &&\n evalRoundsUsed < maxEvalRounds + FIT_EXTENSION_BONUS;\n if (allowFitExtension) {\n const fitLines = fitFails.slice(0, MAX_FEEDBACK_ISSUES).map(formatFitFeedback);\n evalResult = {\n ...evalResult,\n issues: [...evalResult.issues, ...exitProbe.probeIssues],\n runtimeProbe: exitProbe.meta,\n };\n console.log(\n `[simple] eval round ${evalRoundsUsed}: fit fail active at cap — granting +1 retry (ggui#1195; ${fitFails.length} canvas-overflow)`,\n );\n return {\n control: \"feedback\",\n evalDone: false,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats: updatedPrevModeSubcats,\n prevFailFingerprints: new Set([...currFailFingerprints, ...fitFails.map(fingerprintFail)]),\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: fitLines.join(\"\\n\\n\"),\n isEvalFeedback: true,\n lastDiffFailed: false,\n };\n }\n // ggui#1261 — a named contract FAIL from the exit probe active at the\n // cap: the same one round as at the clean exit, bounded at the cap + 1.\n const capContractFails = allowRuntimeExtension ? [] : contractFeedbackFails(exitProbe, prevFailFingerprints);\n if (capContractFails.length > 0 && evalRoundsUsed < maxEvalRounds + CONTRACT_FEEDBACK_BONUS) {\n const contractLines = capContractFails.slice(0, MAX_FEEDBACK_ISSUES).map(formatRuntimeProbeFeedback);\n evalResult = {\n ...evalResult,\n issues: [...evalResult.issues, ...exitProbe.probeIssues],\n runtimeProbe: exitProbe.meta,\n };\n console.log(\n `[simple] eval round ${evalRoundsUsed}: contract probe fail active at cap — granting +1 retry ` +\n `(ggui#1261; ${capContractFails.map((i) => i.subcategory).join(\", \")})`,\n );\n return {\n control: \"feedback\",\n evalDone: false,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats: updatedPrevModeSubcats,\n prevFailFingerprints: new Set([...currFailFingerprints, ...capContractFails.map(fingerprintFail)]),\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: contractLines.join(\"\\n\\n\"),\n isEvalFeedback: true,\n lastDiffFailed: false,\n contractFeedback: contractFeedbackRecord(capContractFails, currentSource),\n };\n }\n if (!allowRuntimeExtension) {\n // Fold probe issues (if any) into evalResult for telemetry and\n // ALWAYS stamp the probe's execution meta, even though we're not\n // granting an extension — a did-not-run probe must stay visible.\n evalResult = {\n ...evalResult,\n issues: [...evalResult.issues, ...exitProbe.probeIssues],\n runtimeProbe: exitProbe.meta,\n };\n console.log(`[simple] eval round ${evalRoundsUsed}: max eval rounds reached — stopping`);\n return {\n control: \"break\",\n evalDone: false,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats: updatedPrevModeSubcats,\n prevFailFingerprints: currFailFingerprints,\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: \"\",\n isEvalFeedback: false,\n lastDiffFailed: false,\n };\n }\n // Recoverable probe fail at the cap → grant +1 retry, switch the\n // feedback path to the probe diagnostic so the LLM sees a [runtime]\n // violation instead of the prior round's tier-1 nitpicks.\n const runtimeFails = exitProbe.probeIssues.filter(\n (i) => i.result === \"fail\" && i.subcategory?.startsWith(\"runtime:\"),\n );\n const probeLines = runtimeFails\n .slice(0, MAX_FEEDBACK_ISSUES)\n .map(formatRuntimeProbeFeedback);\n const enrichedIssues = [...evalResult.issues, ...exitProbe.probeIssues];\n evalResult = { ...evalResult, issues: enrichedIssues, runtimeProbe: exitProbe.meta };\n console.log(\n `[simple] eval round ${evalRoundsUsed}: runtime-probe fail active at cap — granting +1 retry (${maxEvalRounds + RUNTIME_EXTENSION_BONUS - evalRoundsUsed} of ${RUNTIME_EXTENSION_BONUS} bonus rounds remain)`,\n );\n return {\n control: \"feedback\",\n evalDone: false,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats: updatedPrevModeSubcats,\n prevFailFingerprints: new Set([\n ...currFailFingerprints,\n ...runtimeFails.map(fingerprintFail),\n ]),\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: probeLines.join(\"\\n\\n\"),\n isEvalFeedback: true,\n lastDiffFailed: false,\n };\n }\n\n // Budget exhausted — exit\n if (!costTracker.canContinue()) {\n console.log(\n `[simple] eval: budget exhausted (spent=$${costTracker.getTotal().toFixed(4)}) — stopping`,\n );\n return {\n control: \"break\",\n evalDone: false,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats: updatedPrevModeSubcats,\n prevFailFingerprints: currFailFingerprints,\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: \"\",\n isEvalFeedback: false,\n lastDiffFailed: false,\n };\n }\n\n // ── Limit feedback to at most MAX_FEEDBACK_ISSUES per eval-fix turn ──\n // Feeding too many issues at once causes the LLM to make many simultaneous\n // changes, breaking JSX nesting in complex components. Prioritize fails\n // first, then warns, capped to keep fixes surgical.\n //\n // Provenance-aware selection (Exp 54 P1 addendum): deterministic\n // tier-0 fails (axis/mode checks — machine-verified, precision-1.00\n // findings) get ONE reserved slot, first. Before this, the merge\n // order (`allIssues = [...llm, ...visual, ...mode]`) + stable sort\n // + slice meant any round where the LLM leg emitted ≥3 fails\n // silently starved every deterministic finding — the model never\n // saw it, the fingerprint set still recorded it, and the stuck\n // detector exited on an issue that was never delivered (2/9 cells\n // shipped a P0 structural defect this way, one displaced by\n // design-token nits). Exactly one slot is reserved so crash-class\n // LLM fails keep the other two.\n const allActionable = selectActionableFeedback(evalResult.issues);\n const issueLines = allActionable.map((issue) => {\n const tag = issue.result === \"fail\" ? \"FAIL\" : \"WARN\";\n return `[${tag}] ${issue.category}${issue.subcategory ? \"/\" + issue.subcategory : \"\"}: ${issue.description}\\n Fix: ${issue.fix}`;\n });\n\n console.log(\n `[simple] eval round ${evalRoundsUsed}: ${allActionable.length} issues (${blocking.length} fail, ${warns.length} warn) → feeding back to coding loop`,\n );\n // ggui#1981 — one line per deterministic (tier-0) finding on a feedback round, and whether it took one of the\n // MAX_FEEDBACK_ISSUES slots, so a bench read can count a warn that displaced a repair instead of inferring it.\n for (const issue of evalResult.issues) {\n if (issue.tier !== 0 || (issue.result !== \"fail\" && issue.result !== \"warn\")) continue;\n console.log(\n `[simple] eval round ${evalRoundsUsed}: tier0 ${issue.result} ${issue.subcategory ?? issue.category} ` +\n `delivered=${allActionable.includes(issue)}`,\n );\n }\n // ggui#1542 — WHY this round continued, for a caller that set `actOn`: the manipulation check of an experiment on\n // the setting reads this line. `visual majors acted` counts the judge's majors only (fit's are never acted on).\n if (visualEvaluation?.actOn !== undefined) {\n console.log(\n `[simple] eval round ${evalRoundsUsed}: continuing: fails=${blocking.length}, visual majors acted=${visualMajorsActed.length} ` +\n `(actOn=${visualEvaluation.actOn})`,\n );\n }\n\n return {\n control: \"feedback\",\n evalDone: false,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats: updatedPrevModeSubcats,\n // DELIVERED fails only (Exp 54 P1 addendum, proposal 2): the\n // stuck detector's premise is \"the LLM saw these and did not\n // resolve them\" — recording fails that the MAX_FEEDBACK_ISSUES\n // cap cut from the feedback turns truncation into a premature\n // stuck-exit (the model never saw the issue it is blamed for\n // not fixing). An undelivered fail recurring next round now\n // reads as NEW, gets delivered, and earns its fix round.\n prevFailFingerprints: new Set(\n allActionable.filter((i) => i.result === \"fail\").map(fingerprintFail),\n ),\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: issueLines.join(\"\\n\\n\"),\n isEvalFeedback: true,\n lastDiffFailed: false,\n };\n } catch (e) {\n // The round threw. Until ggui#1110 this returned `evalResult` UNDEFINED and\n // said so only in a console line: downstream the generation carried no\n // evaluation at all, an offline mint exported no `eval.json`, and the bar\n // read the missing file as \"probe skipped\" — a thrown evaluation and an\n // evaluation that never ran became the same fact, with the reason lost.\n // Now the failure IS the result: the round reports what threw, on the\n // channel a judge reads, and can never be mistaken for a pass (`pass` is\n // empty, the probe status is `infra-skipped`, and a bar that requires the\n // probe still refuses — with a cause instead of a silence).\n const message = e instanceof Error ? e.message : String(e);\n console.error(\"[simple] eval failed:\", message);\n evalResult = evalResult ?? {\n issues: [],\n pass: [],\n criteriaCoverage: notApplicableCoverage(`${EVAL_ROUND_THREW_REASON}: ${message}`),\n runtimeProbe: { status: \"infra-skipped\", reason: `${EVAL_ROUND_THREW_REASON}: ${message}` },\n };\n return {\n control: \"break\",\n evalDone: false,\n evalResult,\n evalRoundsUsed,\n prevModeSubcats,\n prevFailFingerprints,\n preWarmedContext,\n evalTokens,\n ...(inLoopVisualTokens !== undefined ? { inLoopVisualTokens } : {}),\n evalLlmMs,\n lastResultText: \"\",\n isEvalFeedback: false,\n lastDiffFailed: false,\n };\n }\n}\n","// Closure-based generate TaskRunner — wraps a CodingSession and drives\n// the multi-turn coding + eval loop.\n//\n// The closure captures all per-generation mutable state (totals,\n// breakdowns, prevModeSubcats, evalRoundsUsed, phase machine, …) so the\n// same coding agent + workspace + pre-warm carry across every iteration\n// runHarness drives. This matters for prompt-cache reuse: the agent is\n// never recreated between turns, so the cache stays warm.\n//\n// Wired into dispatchGeneration via\n// runHarness({ taskRunners: { generate } }).\n\nimport type { Classification } from \"../../classifier/index.js\";\nimport type { JsonValue } from \"@ggui-ai/protocol\";\nimport type { ContractFeedbackRecord, EvalResult, RuntimeProbeMeta } from \"../../evaluation/types-public.js\";\nimport type { Harness, Task, TaskContext } from \"../types-public.js\";\nimport type { SingleComponentParams } from \"../runtime.js\";\nimport type { TaskRunner } from \"../index.js\";\nimport type { CodingSession } from \"./init-session.js\";\nimport {\n runCodingTurn,\n type A1Phase,\n type CodingTurnResult,\n} from \"./run-coding-turn.js\";\nimport { runEvalRound } from \"./run-eval-round.js\";\nimport type { TokenUsage } from \"./run-eval-round.js\";\nimport type { VisualLegTokens } from \"../../evaluation/visual-evaluator.js\";\nimport type { SameExchangeBreak, SameFailureBreak } from \"../result-types.js\";\n\ntype PreWarmedEvalContext =\n import(\"../../evaluation/llm-evaluator.js\").PreWarmedEvalContext;\n\n/**\n * Per-generation breakdown counters — exposed so result assembly can\n * read them back after the closure finishes.\n */\nexport interface BreakdownCounters {\n phases: { impl: number; patch: number; evalFix: number; scaffold: number; fill: number };\n outcomes: { pass: number; patchInvalid: number; selfCheckFail: number; diffFail: number };\n}\n\n/**\n * Per-generation telemetry handles. The closure mutates these in place;\n * the lifecycle owner reads them after generate returns to assemble the\n * GenerationResult.\n */\nexport interface GenerateTelemetry {\n readonly counters: BreakdownCounters;\n /** Read after generate(): turns the closure actually ran. */\n turnsUsed: number;\n /** Read after generate(): eval rounds the closure actually ran. */\n evalRoundsUsed: number;\n /** Cumulative LLM wall-time across coding turns only. Does NOT include\n * eval-round LLM calls (those live in {@link cumulativeEvalLlmMs}). */\n cumulativeLlmMs: number;\n /** Cumulative tool-execution wall-time across all turns. */\n cumulativeToolMs: number;\n /** Cumulative wall-clock across all eval rounds. Measured at the\n * runEvalRound call-site (includes axis-checks, parallel LLM+visual,\n * merge, logging). */\n cumulativeEvalWallMs: number;\n /** Cumulative parallel-wall of LLM eval calls inside eval rounds (wraps the\n * `Promise.all([runLLMEvaluation, runVisualEval])` in run-eval-round.ts).\n * Distinct from {@link cumulativeLlmMs}, which is coding-turn only. */\n cumulativeEvalLlmMs: number;\n /** Total input tokens billed across coding + eval. */\n totalIn: number;\n /** Total output tokens billed across coding + eval. */\n totalOut: number;\n /**\n * Prompt-cache tokens accumulated across coding turns AND eval rounds\n * (ggui#1281), when the provider reports them. Optional: stays\n * `undefined` for providers that don't expose cache accounting (never\n * defaulted to 0 here, so the boundary can distinguish \"no cache reads\"\n * from \"unreported\").\n */\n cacheReadTokens?: number;\n cacheCreationTokens?: number;\n /**\n * ggui#1522 — the in-loop visual judge's spend across eval rounds, apart from {@link totalIn} / {@link totalOut}\n * (priced at the coding and text-evaluator models): this part is priced at the VISUAL agent's model. Stays\n * `undefined` while no round reported one.\n */\n inLoopVisualTokens?: VisualLegTokens;\n /** Latest evalResult — undefined when eval was disabled or never ran. */\n evalResult: EvalResult | undefined;\n /**\n * ggui#1380 — whether the probe-only lane's one repair turn has been\n * spent. Set when the first probe-only round fed a recoverable render\n * crash back; read by the next round (which then always breaks) and by\n * the turn after the repair (which never loops on a failed self-check).\n * Stays `false` on every other lane.\n */\n probeRepairUsed: boolean;\n /** ggui#1380 C2b — the probe that bought the repair turn (the first probe-only round's meta), recorded on round 2 as `trigger`. */\n probeRepairTrigger: RuntimeProbeMeta | undefined;\n /**\n * ggui#1261 — the contract-feedback round, once one fired: kept across the\n * rounds after it (each rebuilds `evalResult`) so the assembled result can\n * carry the round's before beside the source the generation ends with.\n */\n contractFeedback: ContractFeedbackRecord | undefined;\n /**\n * The same-exchange guard's record (ggui#404), set by the turn it ended —\n * undefined unless that guard is what stopped the loop.\n */\n sameExchangeBreak: SameExchangeBreak | undefined;\n /** ggui#1791 — set when the same-failure guard ended the run. */\n sameFailureBreak: SameFailureBreak | undefined;\n /** Latest compiled code — empty string until the first self-check pass. */\n compiledCode: string;\n /**\n * Source that pairs with `compiledCode`. Distinct from\n * `session.workspace.read()` because a later eval-fix turn may have\n * mutated the workspace without producing a passing compile. The\n * caller (dispatchGeneration) returns THIS string as the final source\n * so that source ↔ compiled stay paired across the boundary.\n */\n pairedSource: string;\n /** True after at least one self-check passed. */\n selfCheckPassed: boolean;\n /** True after onInitialResult fired (or would have fired). */\n initialResultDelivered: boolean;\n /** Wall-clock when coding loop started (set when generate is invoked). */\n codingStartedAtMs: number;\n /** Time spent in coding loop only — set when the loop exits. */\n codingMs: number;\n}\n\n/**\n * Build a fresh telemetry record. One per generate-runner instance.\n */\nexport function createTelemetry(): GenerateTelemetry {\n return {\n counters: {\n phases: { impl: 0, patch: 0, evalFix: 0, scaffold: 0, fill: 0 },\n outcomes: { pass: 0, patchInvalid: 0, selfCheckFail: 0, diffFail: 0 },\n },\n turnsUsed: 0,\n evalRoundsUsed: 0,\n cumulativeLlmMs: 0,\n cumulativeToolMs: 0,\n cumulativeEvalWallMs: 0,\n cumulativeEvalLlmMs: 0,\n totalIn: 0,\n totalOut: 0,\n evalResult: undefined,\n probeRepairUsed: false,\n probeRepairTrigger: undefined,\n contractFeedback: undefined,\n sameExchangeBreak: undefined,\n sameFailureBreak: undefined,\n compiledCode: \"\",\n pairedSource: \"\",\n selfCheckPassed: false,\n initialResultDelivered: false,\n codingStartedAtMs: 0,\n codingMs: 0,\n };\n}\n\n/**\n * Fold one call's (or one eval round's) tokens into the run's totals — the ONE\n * rule for coding turns and eval rounds alike (ggui#1281: the eval path used to\n * add input/output only, so `tokens.total` dropped every eval call's cached\n * prefix). A cache counter is seeded on its first report and stays `undefined`\n * while nothing has reported one: unreported, never zero.\n */\nexport function absorbTokens(telemetry: GenerateTelemetry, usage: TokenUsage): void {\n telemetry.totalIn += usage.input;\n telemetry.totalOut += usage.output;\n if (usage.cacheRead !== undefined) {\n telemetry.cacheReadTokens = (telemetry.cacheReadTokens ?? 0) + usage.cacheRead;\n }\n if (usage.cacheCreation !== undefined) {\n telemetry.cacheCreationTokens = (telemetry.cacheCreationTokens ?? 0) + usage.cacheCreation;\n }\n}\n\n/** ggui#1522 — fold one round's in-loop visual spend into the run's own part (never into `totalIn` / `totalOut`). */\nexport function absorbInLoopVisualTokens(telemetry: GenerateTelemetry, part: VisualLegTokens | undefined): void {\n if (part === undefined) return;\n const prev = telemetry.inLoopVisualTokens;\n const prevCriteria = prev?.criteria;\n const criteria =\n part.criteria === undefined\n ? prevCriteria\n : {\n inputTokens: (prevCriteria?.inputTokens ?? 0) + part.criteria.inputTokens,\n outputTokens: (prevCriteria?.outputTokens ?? 0) + part.criteria.outputTokens,\n };\n telemetry.inLoopVisualTokens = {\n inputTokens: (prev?.inputTokens ?? 0) + part.inputTokens,\n outputTokens: (prev?.outputTokens ?? 0) + part.outputTokens,\n ...(criteria !== undefined ? { criteria } : {}),\n };\n}\n\n/**\n * Fold one coding turn's measurements into the run's telemetry — tokens (via\n * {@link absorbTokens}), timings, the phase/outcome counters, and the\n * same-exchange guard's record when that guard ended the turn (ggui#404). One\n * function so every per-turn fact the result is assembled from lands in one\n * place.\n */\nexport function absorbTurn(telemetry: GenerateTelemetry, turn: CodingTurnResult): void {\n absorbTokens(telemetry, {\n input: turn.tokens.input,\n output: turn.tokens.output,\n ...(turn.cacheReadTokens !== undefined ? { cacheRead: turn.cacheReadTokens } : {}),\n ...(turn.cacheCreationTokens !== undefined ? { cacheCreation: turn.cacheCreationTokens } : {}),\n });\n telemetry.cumulativeLlmMs += turn.llmMs;\n telemetry.cumulativeToolMs += turn.toolMs;\n if (turn.phase) {\n if (turn.phase === \"scaffold\") telemetry.counters.phases.scaffold++;\n else if (turn.phase === \"fill\") telemetry.counters.phases.fill++;\n else if (turn.phase === \"impl\") telemetry.counters.phases.impl++;\n else if (turn.phase === \"eval-fix\") telemetry.counters.phases.evalFix++;\n else telemetry.counters.phases.patch++;\n }\n if (turn.outcome) {\n if (turn.outcome === \"PASS\") telemetry.counters.outcomes.pass++;\n else if (turn.outcome === \"PATCH_INVALID\") telemetry.counters.outcomes.patchInvalid++;\n else if (turn.outcome === \"DIFF_FAIL\") telemetry.counters.outcomes.diffFail++;\n else telemetry.counters.outcomes.selfCheckFail++;\n }\n if (turn.sameExchangeBreak !== undefined) telemetry.sameExchangeBreak = turn.sameExchangeBreak;\n if (turn.sameFailureBreak !== undefined) telemetry.sameFailureBreak = turn.sameFailureBreak;\n}\n\nexport interface CreateGenerateRunnerInput {\n readonly session: CodingSession;\n readonly params: SingleComponentParams;\n readonly classification: Classification;\n /** Mutated in place — caller reads after generate() returns. */\n readonly telemetry: GenerateTelemetry;\n /** Hard cap on coding turns (defaults to 30 to match runSimpleHarness). */\n readonly maxTurns?: number;\n}\n\n/**\n * Build a `generate` TaskRunner that drives the full multi-turn coding +\n * eval loop using the captured session. Returns the final source string\n * (read from workspace.read()) as its task output.\n *\n * The TaskRunner ignores its `task` and `ctx` params — it derives all\n * inputs from the closure-captured session/params/classification, so\n * the same instance works across runHarness iterations without needing\n * workflow-context plumbing for feedback.\n */\nexport function createGenerateTaskRunner(input: CreateGenerateRunnerInput): TaskRunner {\n const { session, params, classification, telemetry } = input;\n const maxTurns = input.maxTurns ?? 30;\n\n // ── Process-mode phase machine ──\n // staged → A1 scaffold → fill → post; everything else → \"post\" from turn 1.\n const a1Mode = session.harness.process.mode === \"staged\";\n let a1Phase: A1Phase = a1Mode ? \"scaffold\" : \"post\";\n\n // ── Mutable loop state owned by the closure (preserved across iterations) ──\n let lastResultText = \"\";\n let lastDiffFailed = false;\n let isEvalFeedback = false;\n let iconNamesCache: string | null = null;\n let preWarmedContext: PreWarmedEvalContext | null | undefined;\n let prevModeSubcats = new Set<string>();\n let prevFailFingerprints = new Set<string>();\n let evalDone = false;\n\n return async function generate(_task: Task, _ctx: TaskContext): Promise<JsonValue> {\n // Mark the start of the coding window for telemetry / SUMMARY logging.\n if (telemetry.codingStartedAtMs === 0) {\n telemetry.codingStartedAtMs = Date.now();\n params.onProgress?.({ type: \"generating\", phase: \"coding\" });\n }\n\n do {\n telemetry.turnsUsed++;\n\n // ── One coding turn ──\n const turn = await runCodingTurn(\n {\n workspace: session.workspace,\n codingAgent: session.codingAgent,\n codingModel: session.agents.coding.model,\n systemPrompt: session.systemPrompt,\n harness: session.harness,\n contract: params.contract,\n originalPrompt: params.userPrompt,\n commitMeta: session.commitMeta,\n originalProps: session.originalProps,\n // ggui#1285: the fixture the probe and judge render with, for the echo check at auto-commit.\n ...(params.fixtureProps !== undefined ? { fixtureProps: params.fixtureProps } : {}),\n costTracker: session.costTracker,\n // Thread the dispatch-resolved policy so experimental\n // profiles take effect on both preflight and tier-0 retry\n // feedback.\n contextPolicy: session.resolvedPolicy.context,\n // Dupe-break state is mutable; runCodingTurn updates it in\n // place (fingerprint + cooldown + forceEscape +\n // scopedEscapeUsedCount).\n dupeBreak: session.dupeBreak,\n ...(params.onCodingTurnPrompt !== undefined ? { onPrompt: params.onCodingTurnPrompt } : {}),\n },\n {\n turnsUsed: telemetry.turnsUsed,\n a1Phase,\n lastResultText,\n lastDiffFailed,\n isEvalFeedback,\n iconNamesCache,\n preWarmedContext,\n preWarmPromise: session.preWarmPromise,\n },\n );\n\n absorbTurn(telemetry, turn);\n iconNamesCache = turn.iconNamesCache;\n preWarmedContext = turn.preWarmedContext;\n\n // ggui#1380 — the probe-only lane's repair turn did not produce a\n // self-check-passing compile (a failed self-check, or no tool call):\n // the lane grants AT MOST ONE eval-fix turn, so the loop never feeds\n // the self-check violations back for another. The pre-repair card is\n // what ships (`compiledCode` / `pairedSource` are untouched since the\n // turn that compiled it), and the round's result records the repair\n // as attempted but not compiled.\n if (turn.control !== \"proceed\" && session.probeOnlyEnabled && telemetry.probeRepairUsed) {\n if (telemetry.evalResult !== undefined) {\n telemetry.evalResult = { ...telemetry.evalResult, runtimeProbeRepair: { attempted: true, compiled: false } };\n }\n console.log(\n `[simple] probe-only repair turn did not compile (${turn.outcome ?? \"no tool call\"}) — serving the pre-repair card`,\n );\n break;\n }\n if (turn.control === \"break\") break;\n if (turn.control === \"continue\") {\n lastResultText = turn.lastResultText;\n lastDiffFailed = turn.lastDiffFailed;\n isEvalFeedback = turn.isEvalFeedback;\n continue;\n }\n\n // ── Self-check passed (control === \"proceed\") ──\n telemetry.compiledCode = turn.compiledCode;\n // Pair the source that was just compiled. workspace.read() at this\n // point reflects the patch the LLM just applied AND that the\n // compile passed — so source/compiled match. A later failed\n // eval-fix turn may mutate the workspace, so we snapshot the\n // pairing now and only update on subsequent proceeds.\n telemetry.pairedSource = session.workspace.read() ?? \"\";\n telemetry.selfCheckPassed = turn.selfCheckPassed;\n\n // ── A1: scaffold passed → transition to fill ──\n if (a1Mode && a1Phase === \"scaffold\" && telemetry.selfCheckPassed && telemetry.compiledCode) {\n console.log(\n `[simple] A1: scaffold compiled (${telemetry.compiledCode.length}B, turns=${telemetry.turnsUsed}) → entering fill phase`,\n );\n a1Phase = \"fill\";\n telemetry.selfCheckPassed = false;\n telemetry.compiledCode = \"\";\n telemetry.pairedSource = \"\";\n lastResultText = \"\";\n isEvalFeedback = false;\n continue;\n }\n if (a1Mode && a1Phase === \"fill\" && telemetry.selfCheckPassed) {\n console.log(`[simple] A1: fill completed (turns=${telemetry.turnsUsed}) → post phase`);\n a1Phase = \"post\";\n }\n\n // ── Deliver initial result on first successful compile ──\n if (!telemetry.initialResultDelivered && telemetry.compiledCode) {\n const sourceCode = session.workspace.read() ?? \"\";\n console.log(`[simple] compiled: ${telemetry.compiledCode.length}B`);\n if (params.onInitialResult) {\n await params.onInitialResult({ componentCode: telemetry.compiledCode, sourceCode });\n }\n telemetry.initialResultDelivered = true;\n\n const codingDoneMs = Date.now() - telemetry.codingStartedAtMs;\n console.log(\n `[simple] initial result delivered | ${codingDoneMs}ms | turns=${telemetry.turnsUsed} | tokens=${telemetry.totalIn + telemetry.totalOut} | compiled=${telemetry.compiledCode.length}B`,\n );\n }\n\n // ── Eval round ──\n // Two lanes open the gate: the evaluation lane (its modules loaded, an\n // evaluator configured) and the probe-only lane (ggui#1380: the probe\n // wired, no evaluator — the round runs the probe once and nothing else).\n if (\n !evalDone &&\n telemetry.compiledCode &&\n ((session.tiersMod && (session.codeEvalEnabled || session.visualEvalEnabled)) ||\n session.probeOnlyEnabled)\n ) {\n // Measure eval-round wall-clock here (not inside runEvalRound) so the\n // accumulator covers axis-checks + LLM+visual parallel + merge +\n // logging. Complements cumulativeEvalLlmMs which measures only the\n // inner Promise.all.\n const evalRoundStart = Date.now();\n const round = await runEvalRound(\n {\n workspace: session.workspace,\n harness: session.harness,\n contract: params.contract,\n userPrompt: params.userPrompt,\n fixtureProps: params.fixtureProps,\n classification,\n evaluationAgent: session.agents.evaluation,\n visualEvalAgent: session.agents.visualEval,\n visualEvaluation: params.visualEvaluation,\n shellType: params.shellType,\n visualThreshold: session.visualThreshold,\n qualityMode: session.qualityMode,\n maxEvalRounds: session.maxEvalRounds,\n costTracker: session.costTracker,\n llmEvalMod: session.llmEvalMod,\n visualMod: session.visualMod,\n preWarmPromise: session.preWarmPromise,\n onProgress: params.onProgress,\n probeOnly: session.probeOnlyEnabled,\n probeRepairUsed: telemetry.probeRepairUsed,\n ...(telemetry.probeRepairTrigger !== undefined ? { probeRepairTrigger: telemetry.probeRepairTrigger } : {}),\n },\n {\n compiledCode: telemetry.compiledCode,\n evalRoundsUsed: telemetry.evalRoundsUsed,\n preWarmedContext,\n prevModeSubcats,\n prevFailFingerprints,\n },\n );\n telemetry.cumulativeEvalWallMs += Date.now() - evalRoundStart;\n telemetry.cumulativeEvalLlmMs += round.evalLlmMs;\n\n telemetry.evalRoundsUsed = round.evalRoundsUsed;\n prevModeSubcats = round.prevModeSubcats;\n prevFailFingerprints = round.prevFailFingerprints;\n preWarmedContext = round.preWarmedContext;\n if (round.evalResult) telemetry.evalResult = round.evalResult;\n if (round.contractFeedback) telemetry.contractFeedback = round.contractFeedback;\n evalDone = round.evalDone;\n absorbTokens(telemetry, round.evalTokens);\n absorbInLoopVisualTokens(telemetry, round.inLoopVisualTokens);\n\n if (round.control === \"break\") break;\n // round.control === \"feedback\" — set next coding turn input.\n // On the probe-only lane this is the one repair turn (ggui#1380).\n if (session.probeOnlyEnabled) {\n telemetry.probeRepairUsed = true;\n telemetry.probeRepairTrigger = round.evalResult?.runtimeProbe;\n }\n lastResultText = round.lastResultText;\n isEvalFeedback = round.isEvalFeedback;\n lastDiffFailed = round.lastDiffFailed;\n } else {\n // Eval not enabled or already done — exit loop.\n break;\n }\n } while (telemetry.turnsUsed < maxTurns && !evalDone);\n\n // ggui#1380 — the probe-only lane's one repair turn was granted by the\n // round but the turn cap had already been reached, so it was never taken:\n // the card ships as it was, the probe's record stays, and no repair record\n // is stamped (nothing was attempted). Say so, so the absence reads as the\n // cap and not as a repair that vanished.\n if (\n session.probeOnlyEnabled &&\n telemetry.probeRepairUsed &&\n telemetry.evalResult !== undefined &&\n telemetry.evalResult.runtimeProbeRepair === undefined\n ) {\n console.log(`[simple] probe-only repair turn not taken — turn cap (${maxTurns}) reached before it`);\n }\n\n telemetry.codingMs = Date.now() - telemetry.codingStartedAtMs;\n\n // ── Fallback: pull compiled code from commitMeta if loop exited dry ──\n // Walks commitMeta back to its most recent successful compile and uses\n // the workspace state at THIS moment as the paired source. Imperfect\n // (workspace may have drifted past the commit), but matches donor\n // behavior. The honest pairing path above (in the proceed branch)\n // covers the common case.\n if (!telemetry.compiledCode) {\n for (const [, meta] of session.commitMeta) {\n if (meta.build.success && meta.selfCheck.passed && meta.build.compiledCode) {\n telemetry.compiledCode = meta.build.compiledCode;\n telemetry.selfCheckPassed = true;\n }\n }\n if (!telemetry.compiledCode) {\n for (const [, meta] of session.commitMeta) {\n if (meta.build.success && meta.build.compiledCode) {\n telemetry.compiledCode = meta.build.compiledCode;\n }\n }\n }\n if (telemetry.compiledCode && !telemetry.pairedSource) {\n telemetry.pairedSource = session.workspace.read() ?? \"\";\n }\n console.log(`[simple] compiled (fallback): ${telemetry.compiledCode.length}B`);\n }\n\n // ── Deliver result if not yet delivered ──\n if (!telemetry.initialResultDelivered && params.onInitialResult && telemetry.compiledCode) {\n await params.onInitialResult({\n componentCode: telemetry.compiledCode,\n sourceCode: telemetry.pairedSource,\n });\n }\n\n // Return the paired source — the one that corresponds to compiledCode.\n // dispatchGeneration uses this same value as the canonical final source\n // so source ↔ compiled stay in sync at the boundary. Falls back to\n // workspace.read() only when no compile succeeded (no pairing exists).\n return telemetry.pairedSource || (session.workspace.read() ?? \"\");\n };\n}\n\n/** Read-only view of a partially-typed harness — passed where TaskContext does. */\nexport type GenerateTaskRunner = ReturnType<typeof createGenerateTaskRunner>;\n\n/** Convenience export so callers can import the harness type without round-trips. */\nexport type { Harness };\n","// packages/ui-gen/src/coding-agent/workspace.ts\n//\n// In-memory git workspace for single-file UI component management.\n// Uses isomorphic-git + memfs + diff package.\n\nimport git, { type ReadCommitResult } from 'isomorphic-git';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport { createPatch, applyPatch } from 'diff';\nimport type { ApplyResult } from './types';\n\nconst FILE = 'ui.tsx';\nconst DIR = '/workspace';\nconst FILEPATH = `${DIR}/${FILE}`;\nconst AUTHOR = { name: 'ggui-agent', email: 'agent@ggui.ai' };\n\nexport { type ReadCommitResult };\n\nexport class AgentWorkspace {\n private vol: InstanceType<typeof Volume>;\n private fs: ReturnType<typeof createFsFromVolume>;\n\n constructor() {\n this.vol = new Volume();\n this.fs = createFsFromVolume(this.vol);\n }\n\n async init(): Promise<void> {\n this.fs.mkdirSync(DIR, { recursive: true });\n await git.init({ fs: this.fs, dir: DIR });\n }\n\n // ── File Operations ────────────────────────────────\n\n read(): string | null {\n try {\n return this.fs.readFileSync(FILEPATH, 'utf-8') as string;\n } catch {\n return null;\n }\n }\n\n write(code: string): void {\n this.fs.writeFileSync(FILEPATH, code);\n }\n\n cat(startLine?: number, endLine?: number): string {\n const content = this.read();\n if (!content) return '(no file yet — use `write` to create it)';\n\n const lines = content.split('\\n');\n const start = (startLine ?? 1) - 1;\n const end = endLine ?? lines.length;\n const padWidth = String(end).length;\n\n return lines\n .slice(start, end)\n .map((line, i) => `${String(start + i + 1).padStart(padWidth)}│ ${line}`)\n .join('\\n');\n }\n\n grep(pattern: string, contextLines: number = 0): string {\n const content = this.read();\n if (!content) return '(no file)';\n\n const lines = content.split('\\n');\n const matchedIndices = new Set<number>();\n const matchLines = new Set<number>();\n\n // Find matching lines\n for (let i = 0; i < lines.length; i++) {\n if (new RegExp(pattern, 'gi').test(lines[i])) {\n matchLines.add(i);\n for (\n let j = Math.max(0, i - contextLines);\n j <= Math.min(lines.length - 1, i + contextLines);\n j++\n ) {\n matchedIndices.add(j);\n }\n }\n }\n\n if (matchedIndices.size === 0) return '(no matches)';\n\n const padWidth = String(lines.length).length;\n return [...matchedIndices]\n .sort((a, b) => a - b)\n .map((i) => {\n const prefix = matchLines.has(i) ? '>' : ' ';\n return `${prefix} ${String(i + 1).padStart(padWidth)}│ ${lines[i]}`;\n })\n .join('\\n');\n }\n\n // ── Git Operations ─────────────────────────────────\n\n async stage(): Promise<void> {\n await git.add({ fs: this.fs, dir: DIR, filepath: FILE });\n }\n\n async commit(message: string): Promise<string> {\n await this.stage();\n return git.commit({\n fs: this.fs,\n dir: DIR,\n message,\n author: AUTHOR,\n });\n }\n\n async log(depth?: number): Promise<ReadCommitResult[]> {\n try {\n return await git.log({ fs: this.fs, dir: DIR, depth: depth ?? 20 });\n } catch {\n return [];\n }\n }\n\n async readFileAtCommit(oid: string): Promise<string> {\n const { blob } = await git.readBlob({\n fs: this.fs,\n dir: DIR,\n oid,\n filepath: FILE,\n });\n return new TextDecoder().decode(blob);\n }\n\n async checkout(oid: string): Promise<void> {\n const content = await this.readFileAtCommit(oid);\n this.write(content);\n }\n\n // ── Diff Operations ────────────────────────────────\n\n async diffWorking(): Promise<string> {\n const commits = await this.log(1);\n if (commits.length === 0) return '(no commits yet — new file)';\n\n const committed = await this.readFileAtCommit(commits[0].oid);\n const working = this.read() ?? '';\n return createPatch(FILE, committed, working, 'committed', 'working', {\n context: 3,\n });\n }\n\n async diffBetween(oldOid: string, newOid: string): Promise<string> {\n const oldContent = await this.readFileAtCommit(oldOid);\n const newContent = await this.readFileAtCommit(newOid);\n return createPatch(\n FILE,\n oldContent,\n newContent,\n oldOid.slice(0, 7),\n newOid.slice(0, 7),\n { context: 3 },\n );\n }\n\n applyDiff(patch: string): ApplyResult {\n const current = this.read() ?? '';\n\n // Validate patch has at least one hunk header\n if (!patch.includes('@@')) {\n return {\n success: false,\n error:\n 'Invalid diff format — missing @@ hunk headers. Use standard unified diff format.',\n };\n }\n\n // Try to apply with fuzz matching\n const result = applyPatch(current, patch, {\n fuzzFactor: 2,\n compareLine: (\n _lineNum: number,\n line: string,\n _op: string,\n patchContent: string,\n ) => {\n return line.trimEnd() === patchContent.trimEnd();\n },\n });\n\n if (result === false) {\n return {\n success: false,\n error:\n 'Patch failed to apply — context lines in your diff do not match the current file. Re-read the current file provided in the prompt and produce a corrected diff.',\n };\n }\n\n this.write(result);\n return { success: true };\n }\n}\n","/**\n * Which in-loop evaluation legs a generation runs (ggui#1513).\n *\n * The harness gates its evaluation rounds on this, and nothing else does:\n * the text evaluator runs when `evaluation.enabled`, and the visual judge\n * runs when `visualEvaluation.enabled` or when a quality config asks for it\n * (`qualityConfig.visualEval`). A host that needs to know whether a\n * generation's token counts (`GenerationMetadata`) can include evaluation\n * calls reads it here, with the options it configured the generator with,\n * instead of keeping its own copy of the rule.\n */\nimport type { QualityConfig } from \"../evaluation/types-public.js\";\n\n/** The switches that turn an in-loop evaluation leg on. */\nexport interface InLoopEvaluationSwitches {\n readonly evaluation?: { readonly enabled: boolean };\n readonly visualEvaluation?: { readonly enabled: boolean };\n readonly qualityConfig?: Pick<QualityConfig, \"visualEval\">;\n}\n\n/** The in-loop evaluation legs these options turn on. */\nexport function inLoopEvaluation(options: InLoopEvaluationSwitches): {\n readonly text: boolean;\n readonly visual: boolean;\n} {\n return {\n text: options.evaluation?.enabled === true,\n visual: options.visualEvaluation?.enabled === true || options.qualityConfig?.visualEval === true,\n };\n}\n\n/**\n * True when these options turn either leg on: a generation built with them\n * can spend tokens on evaluation calls as well as on its coding turns.\n */\nexport function runsInLoopEvaluation(options: InLoopEvaluationSwitches): boolean {\n const legs = inLoopEvaluation(options);\n return legs.text || legs.visual;\n}\n","// packages/ui-gen/src/harness/coding/init-session.ts\n//\n// Build a coding session — workspace, agent, lazy-loaded eval modules,\n// pre-warm promise. Captured once per generation, reused for every\n// coding turn + eval round inside the closure-based generate runner.\n//\n// Step 3 of the runHarness migration (#142). Pure additive — the\n// existing runSimpleHarness still builds its own session inline.\n\nimport { AgentWorkspace } from \"../../coding-agent/workspace.js\";\nimport type { CommitMetadata } from \"../../coding-agent/types.js\";\nimport type { CostTracker } from \"../../evaluation/cost-tracker.js\";\nimport { mapProviderForEvaluator } from \"../enforced-coding.js\";\nimport { createAgent } from \"../llm-router.js\";\nimport type { LLMAgent } from \"../llm-router.js\";\nimport { APPLY_CHANGES_TOOL, GET_ICONS_TOOL } from \"../../tools.js\";\nimport type { Harness } from \"../types-public.js\";\nimport type { AgentSpec, SingleComponentParams } from \"../runtime.js\";\nimport type { ResolvedRunPolicy } from \"../policy.js\";\nimport { DEFAULT_HARNESS_POLICY } from \"../policy.js\";\nimport { createDupeBreakState, type DupeBreakState } from \"./dupe-break.js\";\nimport { inLoopEvaluation } from \"../in-loop-evaluation.js\";\n\ntype PreWarmedEvalContext =\n import(\"../../evaluation/llm-evaluator.js\").PreWarmedEvalContext;\ntype TiersMod = typeof import(\"../../check/index.js\");\ntype LlmEvalMod = typeof import(\"../../evaluation/llm-evaluator.js\");\ntype VisualEvalMod = typeof import(\"../../evaluation/visual-evaluator.js\");\n\nexport interface SessionAgents {\n /** Coding agent + model — drives apply_changes turns. */\n readonly coding: AgentSpec;\n /** Code-eval agent + model — falls back to coding when caller omits. */\n readonly evaluation: AgentSpec;\n /** Visual-eval agent + model — falls back to evaluation. */\n readonly visualEval: AgentSpec;\n}\n\nexport interface CodingSession {\n // Long-lived per-generation state (closure-captured by the task runner).\n readonly harness: Harness;\n readonly workspace: AgentWorkspace;\n readonly codingAgent: LLMAgent;\n readonly agents: SessionAgents;\n readonly commitMeta: Map<string, CommitMetadata>;\n readonly boilerplate: string;\n readonly originalProps: string | undefined;\n readonly systemPrompt: string;\n\n // Eval gate config (computed once from params/qualityConfig).\n readonly codeEvalEnabled: boolean;\n readonly visualEvalEnabled: boolean;\n /**\n * ggui#1380 — the probe-only lane: the harness wires the runtime-render\n * check and NO evaluator is configured (neither code nor visual). A\n * serving deployment runs the probe once after the coding turns, observes,\n * and buys one repair turn on a recoverable render crash. `evaluation:\n * { enabled: false }` beside a wired probe is this lane too: a config\n * that enables nothing is no evaluator. False whenever an evaluator runs —\n * that lane's exit probe is a different round — and false without a probe.\n */\n readonly probeOnlyEnabled: boolean;\n readonly maxEvalRounds: number;\n readonly visualThreshold: number;\n readonly qualityMode: \"fast\" | \"auto-improve\" | \"high-quality\";\n\n // Lazy-loaded eval modules — null when eval disabled.\n readonly tiersMod: TiersMod | null;\n readonly llmEvalMod: LlmEvalMod | null;\n readonly visualMod: VisualEvalMod | null;\n readonly costTracker: CostTracker | null;\n\n // Pre-warm runs concurrently with coding so the first eval round skips\n // the criteria-generation cost.\n readonly preWarmPromise: Promise<PreWarmedEvalContext | null> | undefined;\n\n /**\n * Runtime-resolved policy for this generation. Defaults to the\n * harness's static policy. dispatchGeneration may call\n * {@link resolveRunPolicyForProfile} and pass a provider-aware\n * override here when an experimental profile is active.\n */\n readonly resolvedPolicy: ResolvedRunPolicy;\n\n /**\n * Mutable duplicate-patch-break state machine. Gated by\n * `resolvedPolicy.context.breakDuplicatePatch`. Always initialized\n * (so downstream code can read safely) but no-ops when the flag is off.\n * See {@link DupeBreakState} in `./dupe-break.ts`.\n */\n readonly dupeBreak: DupeBreakState;\n\n /** Wall-clock at session creation. Used for total-elapsed in result assembly. */\n readonly startedAtMs: number;\n}\n\n/**\n * Resolve agent specs from caller config, applying the documented fallbacks:\n * evaluation ← codingAgent\n * visualEval ← evaluationAgent ← codingAgent\n */\nexport function resolveSessionAgents(config: {\n codingAgent: AgentSpec;\n evaluationAgent?: AgentSpec;\n visualEvalAgent?: AgentSpec;\n}): SessionAgents {\n const coding = config.codingAgent;\n const evaluation = config.evaluationAgent ?? coding;\n const visualEval = config.visualEvalAgent ?? evaluation;\n return { coding, evaluation, visualEval };\n}\n\n/**\n * Construct a coding session: init workspace, scaffold-commit the\n * boilerplate, create + warm-cache the coding agent, lazy-load eval\n * modules, and kick off pre-warm.\n */\nexport async function initSession(input: {\n harness: Harness;\n params: SingleComponentParams;\n agents: SessionAgents;\n /** Optional runtime-resolved policy. Defaults to the harness's static\n * policy when omitted. */\n resolvedPolicy?: ResolvedRunPolicy;\n /** Optional override for the first-turn system prompt. When provided,\n * replaces `harness.how.systemPrompt` verbatim. Used by\n * `dispatchGeneration` to inject the axis-keyed primitives doc slice\n * without rebuilding the Harness. `harness.how.systemPrompt` is still\n * the default when this is undefined. */\n systemPromptOverride?: string;\n}): Promise<CodingSession> {\n const { harness, params, agents } = input;\n const resolvedPolicy =\n input.resolvedPolicy ?? harness.policy ?? DEFAULT_HARNESS_POLICY;\n const startedAtMs = Date.now();\n\n // ── Boilerplate (from harness — WHAT leg) ──\n const boilerplate = harness.what.boilerplate;\n console.log(\n `[simple] boilerplate: ${boilerplate.split(\"\\n\").length} lines, ` +\n `shell=${params.shellType ?? \"fullscreen\"}, ` +\n `screen=${params.screen ?? \"universal\"}`,\n );\n\n // ── Init workspace + scaffold commit ──\n const workspace = new AgentWorkspace();\n await workspace.init();\n const commitMeta = new Map<string, CommitMetadata>();\n\n workspace.write(boilerplate);\n await workspace.stage();\n await workspace.commit(\"scaffold: boilerplate\");\n\n // ── System prompt (from harness — HOW leg, or override for #45) ──\n const systemPrompt = input.systemPromptOverride ?? harness.how.systemPrompt;\n\n // ── Create + warm-cache the coding agent ──\n // Pass the full spec (not just `.provider`) so a caller-supplied\n // `routeOverride` (#484) reaches the constructed `LLMAgent` instance\n // and it never falls back to reading `process.env`.\n const codingAgent = createAgent(agents.coding);\n await codingAgent.warmCache(\n agents.coding.model,\n systemPrompt,\n [APPLY_CHANGES_TOOL, GET_ICONS_TOOL],\n \"required\",\n );\n\n // ggui#1513 — the one rule for which evaluation legs run; a host reads the same export.\n const { text: codeEvalEnabled, visual: visualEvalEnabled } = inLoopEvaluation(params);\n\n // ── Pre-warm eval (overlaps with coding turn 1) ──\n // Uses a separate agent instance so it doesn't disturb the coding cache.\n let preWarmPromise: Promise<PreWarmedEvalContext | null> | undefined;\n if (codeEvalEnabled) {\n const evalSpec = agents.evaluation;\n preWarmPromise = import(\"../../evaluation/llm-evaluator.js\")\n .then((mod) =>\n mod.preWarmEval(\n {\n sourceCode: \"\",\n originalPrompt: params.userPrompt,\n contract: params.contract,\n designContext: undefined,\n designMode: harness.designMode,\n profile: harness.profile,\n },\n {\n provider: mapProviderForEvaluator(evalSpec.provider),\n model: evalSpec.model,\n },\n ),\n )\n .catch((e) => {\n console.warn(`[simple] eval pre-warm failed: ${e instanceof Error ? e.message : e}`);\n return null;\n });\n }\n\n // ── Extract un-diffable Props interface ──\n // After each apply_changes the runner restores it so the LLM can't break\n // the contract by mutating the props shape.\n const propsMatch = boilerplate.match(/interface Props \\{[\\s\\S]*?\\n\\}/);\n const originalProps = propsMatch?.[0];\n\n // ── Eval gate + lazy-loaded modules ──\n const qualityConfig = params.qualityConfig;\n const qualityMode = qualityConfig?.quality ?? \"fast\";\n const probeOnlyEnabled =\n harness.check.runtimeRender !== undefined && !codeEvalEnabled && !visualEvalEnabled;\n const maxEvalRounds =\n qualityMode === \"high-quality\"\n ? (params.evaluation?.maxRounds ?? 3)\n : (params.evaluation?.maxRounds ?? 2);\n const visualThreshold = params.visualEvaluation?.passThreshold ?? 70;\n\n let tiersMod: TiersMod | null = null;\n let llmEvalMod: LlmEvalMod | null = null;\n let visualMod: VisualEvalMod | null = null;\n let costTracker: CostTracker | null = null;\n\n if (codeEvalEnabled || visualEvalEnabled) {\n tiersMod = await import(\"../../check/index.js\");\n const costTrackerMod = await import(\"../../evaluation/cost-tracker.js\");\n costTracker = new costTrackerMod.CostTracker(\n qualityConfig?.maxCostPerGeneration ?? null,\n );\n if (codeEvalEnabled) {\n llmEvalMod = await import(\"../../evaluation/llm-evaluator.js\");\n }\n if (visualEvalEnabled) {\n visualMod = await import(\"../../evaluation/visual-evaluator.js\").catch(() => null);\n }\n }\n\n return {\n harness,\n workspace,\n codingAgent,\n agents,\n commitMeta,\n boilerplate,\n originalProps,\n systemPrompt,\n codeEvalEnabled,\n visualEvalEnabled,\n probeOnlyEnabled,\n maxEvalRounds,\n visualThreshold,\n qualityMode,\n tiersMod,\n llmEvalMod,\n visualMod,\n costTracker,\n preWarmPromise,\n resolvedPolicy,\n dupeBreak: createDupeBreakState(),\n startedAtMs,\n };\n}\n","// Dispatches generation through the closure-based harness pipeline.\n// Used by the benchmark runner and the production Lambda generator.\n// Single implementation — provider-agnostic; the harness handles all\n// providers uniformly.\n//\n// Pipeline:\n// resolveSessionAgents — fallback chain coding → eval → visualEval\n// classifyAxes — read the multi-axis vector from contract + prompt\n// createHarness — assemble HOW/WHAT/CHECK/Process legs\n// initSession — workspace, agent (warm-cached), pre-warm,\n// lazy eval modules, costTracker\n// createTelemetry — fresh per-generation counters/totals record\n// createGenerateTaskRunner — closure capturing session + telemetry;\n// drives the multi-turn coding + eval loop\n// using runCodingTurn + runEvalRound\n// runHarness — workflow lifecycle wrapper; the closure\n// does the inner loop, runHarness adds\n// compile-null safety + iteration telemetry\n// assembleGenerationResult — telemetry → GenerationResult shape\n\nimport { classifyAxes } from \"../classifier/index.js\";\nimport { createHarness } from \"../harness/index.js\";\nimport { runHarness } from \"../harness/index.js\";\nimport { resolveHarnessPolicy } from \"../harness/policy.js\";\n// Fully-populated system-prompt builder. The `createHarness`\n// constructor uses a skeleton builder with empty content blocks by\n// default; this callsite injects the full builder so production\n// prompts carry pitfalls + design-system docs + primitives + wire\n// content.\nimport { buildSystemPrompt as buildSystemPromptWithFunnel } from \"../harness/runtime.js\";\nimport type { CodingTurnPrompt } from \"../harness/runtime.js\";\n\nexport type { CodingTurnPrompt };\n// Axis-check registry filter. The `createHarness` constructor accepts a\n// pre-filtered axisChecks list; this callsite runs the `matches()`\n// predicate against the full registry and passes the filtered result.\nimport { REGISTRY as AXIS_CHECK_REGISTRY } from \"../evaluation/axis-checks/registry.js\";\nimport { matches as axisCheckMatches } from \"../evaluation/types-public.js\";\n// Runtime-render check. The `createHarness` constructor accepts an\n// optional runtimeRender; this callsite wires the caller's instance\n// (`params.runtimeRender`) or, absent one, `DEFAULT_RUNTIME_RENDER_CHECK`,\n// so production keeps the happy-dom-backed contract-wiring verification\n// step. The dispatch never BUILDS a check: the instance carries the\n// concurrency cap, so its lifetime must be the caller's (one per\n// generator), never one per generation.\nimport { DEFAULT_RUNTIME_RENDER_CHECK } from \"../harness/check/runtime-render/adapter.js\";\nimport type { RuntimeRenderCheck } from \"../harness/types-public.js\";\nimport { warmupRuntimeRenderProbe } from \"../harness/check/runtime-render/index.js\";\nimport { assembleGenerationResult } from \"../harness/coding/assemble-result.js\";\nimport {\n createGenerateTaskRunner,\n createTelemetry,\n} from \"../harness/coding/generate-task-runner.js\";\nimport { initSession, resolveSessionAgents } from \"../harness/coding/init-session.js\";\nimport type {\n DataContract,\n ModelRoles,\n GenerationResult,\n RenderingContext,\n} from \"../harness/result-types.js\";\nimport type { ProviderName, ToolDefinition } from \"./types.js\";\nimport type { QualityConfig } from \"../evaluation/types-public.js\";\nimport type { AgentConfig } from \"../harness/llm-router.js\";\nimport { type GadgetDescriptor, type JsonObject } from \"@ggui-ai/protocol\";\nimport { canvasForRendering, type CanvasClass, type DesignMode } from \"../design-mode.js\";\nimport type { VisionProvider } from \"../harness/llm-router.js\";\nimport type { CriteriaBank } from \"../evaluation/criteria/bank.js\";\nimport type { GenerationProfileInput } from \"../boilerplate/styling-profile.js\";\n\n/**\n * ggui#1250 — the in-loop VISUAL judge as its own agent: a vision provider (typed so an OpenAI judge cannot\n * be written), a model, and — when the caller resolves provider keys itself — that provider's key, which\n * becomes the agent's own `routeOverride`. Never the coding agent's route: where this exists (an OpenAI\n * coding lane), the coding key is another provider's.\n */\nexport interface VisualEvalAgentSpec {\n readonly provider: VisionProvider;\n readonly model: string;\n readonly apiKey?: string;\n}\n\nexport interface GenerationDispatchParams {\n provider: ProviderName;\n model: string;\n userPrompt: string;\n tools: ToolDefinition[];\n models?: ModelRoles;\n originalPrompt?: string;\n /** Evaluation config — controls the evaluate-then-regenerate loop. */\n evaluation?: import(\"../evaluation/types.js\").EvaluationConfig;\n rendering?: RenderingContext;\n contract?: DataContract;\n /** Shell type for layout-adaptive boilerplate */\n shellType?: \"chat\" | \"fullscreen\" | \"spatial\";\n /** Target screen size for responsive layout */\n screen?: \"mobile\" | \"tablet\" | \"desktop\" | \"universal\";\n /**\n * Maximum coding attempts per generation pass (default: 8). This is\n * the harness turn cap — there is no separate `maxTurns` knob.\n */\n maxAttempts?: number;\n /** Maximum evaluation rounds (default: 10) */\n maxEvalRounds?: number;\n /**\n * Visual evaluation config (screenshot + multimodal LLM scoring).\n * The judge model is NOT configured here — visual eval runs on the\n * session's evaluation agent (`models.evaluation`, falling back to\n * the coding agent). See `resolveSessionAgents` in\n * `harness/coding/init-session.ts`.\n */\n visualEvaluation?: {\n enabled: boolean;\n passThreshold?: number;\n sampleProps?: JsonObject;\n viewport?: { width: number; height: number };\n /**\n * Per-canvas judging — see `VisualEvalConfig.canvases`. When set, the\n * eval round screenshots + judges once per class and the harness\n * stamps `EvalResult.visual` with the PNG-free summary. Unset =\n * today's single screenshot at `viewport`.\n */\n canvases?: readonly CanvasClass[];\n /**\n * ggui#1195 — per-canvas viewport override for the in-loop round: the\n * box the composer targeted (`rendering.viewport`) so the round judges\n * the same box. See `VisualEvalConfig.canvasViewports`.\n */\n canvasViewports?: Partial<Readonly<Record<CanvasClass, { width: number; height: number }>>>;\n /** ggui#1436 — see `SingleComponentParams.visualEvaluation.criteriaBank`. */\n criteriaBank?: CriteriaBank;\n criteriaKind?: string;\n /** ggui#1542 — see `SingleComponentParams.visualEvaluation.actOn`. */\n actOn?: \"critical\" | \"major\";\n };\n /** Quality config controlling eval tiers and improvement behavior */\n qualityConfig?: QualityConfig;\n /**\n * Optional fixture props (e.g., from a benchmark commit's `props` field).\n * Forwarded to runCheck → runtimeRender for schema-first mockup synthesis.\n * Production callers can omit this; benchmark runners should pass commit.props.\n */\n fixtureProps?: JsonObject;\n /**\n * Observer of the exact prompt each coding turn sends — the system prompt after the component-reference swap\n * below, and the turn's user message (see `CodingTurnPrompt`). Read-only; nothing sent changes. Absent = no report.\n */\n onCodingTurnPrompt?: (sent: CodingTurnPrompt) => void;\n /**\n * Whether to wire the runtime-render check (`runtimeRender` when given,\n * else `DEFAULT_RUNTIME_RENDER_CHECK`) into the harness's check leg.\n * When `true` (default), the runtime-render probe runs ONCE\n * at the exit decision, after the coding turns, in an isolated\n * subprocess — never on the per-turn hot path. Without an `evaluation`\n * config that round is observe + one repair turn (ggui#1380): a\n * recoverable render crash buys exactly one repair turn and one\n * re-probe, then the generation serves what it has; a probe that timed\n * out, could not run, or had nothing to probe never blocks and never\n * repairs. With an `evaluation` config the probe is the evaluation\n * round's exit gate. Its status and timing land on\n * `evalResult.runtimeProbe` (and on the generation's metadata through\n * `createUiGenerator`).\n *\n * When `false`, the harness omits runtime-render entirely: no probe\n * round runs, and a caller can run the probe externally as a final\n * post-generation check instead.\n *\n * Default: `true`.\n */\n enableRuntimeRender?: boolean;\n /**\n * The runtime-render check to wire (ggui#1380) — built by the CALLER with\n * `createRuntimeRenderCheck(config)` and kept for the caller's lifetime,\n * because the check instance owns the probe's concurrency cap: one\n * instance per generator bounds the workers a serving deployment has\n * live at once; one per dispatch would give every generation its own\n * free slots and bound nothing. Absent ⇒ `DEFAULT_RUNTIME_RENDER_CHECK`\n * (the evaluation lane's bounds, no concurrency cap). Only read when\n * `enableRuntimeRender` is on.\n */\n runtimeRender?: RuntimeRenderCheck;\n /**\n * Operator-registered gadget catalog forwarded to the\n * code-gen system prompt's `clientCapabilities — registered\n * catalog` section (see `buildSystemPrompt`/`SystemPromptInputs`\n * in `@ggui-ai/ui-gen/boilerplate`). Threaded by the render handler\n * from the bound `AppMetadataStore` so the code-gen LLM sees the\n * same gadget set as the synth + decision LLMs.\n *\n * When omitted, the system prompt defaults to `STDLIB_GADGETS`.\n * Production callers (render, ops-generate) pass the resolved catalog;\n * benchmark / direct callers may omit it.\n */\n appGadgets?: readonly GadgetDescriptor[];\n /**\n * A `package -> .d.ts content` map for third-party gadget wrappers.\n * The render handler parallel-fetches each non-stdlib\n * gadget's `.d.ts` (via `GadgetDescriptor.typesUrl` + SRI verify)\n * and threads the result here (`UiGenerateInput.gadgetTypes`). It\n * flows two ways:\n * 1. into `createHarness({ gadgetTypes })` → `WhatLeg` → the\n * coding-agent's typecheck overlay, so third-party hooks get\n * strict option/return narrowing in the TS sandbox;\n * 2. into the code-gen `systemPromptBuilder`, so the prompt\n * renders a `Type:` line per third-party gadget — the LLM sees\n * the real call shape of a wrapper it cannot otherwise know.\n *\n * Stdlib gadgets (`@ggui-ai/gadgets`) need no entry — their `.d.ts`\n * is in the sandbox VFS and they carry an `example`. Omit for\n * STDLIB-only / bench / direct callers.\n */\n gadgetTypes?: Readonly<Record<string, string>>;\n /**\n * Explicit per-call credentials/routing (#484) — see\n * `AgentConfig.routeOverride`. Threaded onto the coding + evaluation\n * agent specs so `resolveSessionAgents` → `createAgent` never falls\n * back to reading `process.env`. Absent (default) preserves\n * existing behavior for callers that don't set it.\n */\n routeOverride?: AgentConfig[\"routeOverride\"];\n /**\n * ggui#1250 — the in-loop visual judge named as its own agent (see {@link VisualEvalAgentSpec}).\n * Absent (default, every existing caller): today's chain, `visualEval ← evaluation ← coding`, which on\n * a lane without a vision path records the score half as skipped (#1248). Off by default; a measurement\n * knob first, a product knob only by ruling.\n */\n visualEvalAgent?: VisualEvalAgentSpec;\n /**\n * Retry observer (#489) — see `AgentConfig.onRetry`. Threaded onto\n * the coding + evaluation agent specs so a rate-limited retry inside\n * either agent's `apiCall()` reaches the caller. Absent (default) is\n * a no-op.\n */\n onRetry?: AgentConfig[\"onRetry\"];\n /**\n * Which triad to materialise — see `CreateHarnessInput.designMode`.\n * Reaches the system prompt, the boilerplate, the tier-0 gate, the\n * axis checks and the evaluator criteria through the harness. Absent\n * means `constrained` (byte-identical to the pre-`designMode` path).\n */\n designMode?: DesignMode;\n /**\n * Rendering canvas class — see `CreateHarnessInput.canvas`. Absent, the\n * harness derives it from `shellType` × `screen` (ggui#1117), so the axis\n * checks always judge for the canvas the generation renders on; the\n * `free` prompt renders it, the constrained prompt ignores it.\n */\n canvas?: CanvasClass;\n /** The app's generation profile (#991). */\n profile?: GenerationProfileInput;\n}\n\n/**\n * Map ProviderName ('claude' | 'openai' | 'google') to AgentConfig provider ('anthropic' | 'openai' | 'google').\n * The LLM router uses 'anthropic' while the rest of the codebase uses 'claude'.\n */\nfunction mapProviderForLLMRouter(\n provider: ProviderName\n): \"anthropic\" | \"openai\" | \"google\" | \"openrouter\" {\n return provider === \"claude\" ? \"anthropic\" : provider;\n}\n\n/**\n * Dispatch to the closure-based harness pipeline. Single-implementation,\n * provider-agnostic.\n */\nexport async function dispatchGeneration(\n params: GenerationDispatchParams\n): Promise<GenerationResult> {\n // NOTE: userPrompt arrives already enriched with rendering context + contract\n // (including examples) from the caller (runner.ts / generator.ts).\n // The contract are injected via injectContracts() which calls propsSpecToTypeScript()\n // to render PropEntry.example values as // Example: {...} comments in the TS interface.\n // Do NOT re-inject here.\n\n // Pre-warm runtime-render probe deps in parallel with the LLM cold\n // call. The probe lazily loads happy-dom +\n // @testing-library + @ggui-ai/wire on first use (~700-1500ms cold);\n // pre-warming so it overlaps with the first LLM round-trip means the\n // first runCheck call hits warm modules (~50ms). Fire-and-forget — if\n // the probe runs before pre-warm completes, runCheck just pays the\n // cold cost on first invocation.\n if ((params.enableRuntimeRender ?? true) === true) {\n void warmupRuntimeRenderProbe().catch(() => {\n // Pre-warm is best-effort; per-cell probe surfaces real failures\n // through the standard check pipeline if a dep is missing.\n });\n }\n\n const routerProvider = mapProviderForLLMRouter(params.provider);\n const resolvedModel = params.models?.coding ?? params.models?.default ?? params.model;\n const codingAgent = {\n provider: routerProvider,\n model: resolvedModel,\n routeOverride: params.routeOverride,\n onRetry: params.onRetry,\n };\n const evaluationAgent = params.models?.evaluation\n ? {\n provider: routerProvider,\n model: params.models.evaluation,\n routeOverride: params.routeOverride,\n onRetry: params.onRetry,\n }\n : undefined;\n // ggui#1250 — the in-loop visual judge as its own agent when named: its own provider and its own key\n // route, never the coding agent's. Absent: today's chain, visualEval ← evaluation ← coding, inside\n // resolveSessionAgents (ModelRoles has no visualEval slot — a role is a model, and this needs a provider).\n const visualEvalAgent = params.visualEvalAgent\n ? {\n provider: params.visualEvalAgent.provider,\n model: params.visualEvalAgent.model,\n ...(params.visualEvalAgent.apiKey !== undefined ? { routeOverride: { apiKey: params.visualEvalAgent.apiKey } } : {}),\n onRetry: params.onRetry,\n }\n : undefined;\n\n // ── Contract enrichment ──────────────────────────────────────────────\n // The contract is used as-is: `clientCapabilities.gadgets`\n // is package-keyed and carries identity only — `(package, export\n // name)` — so there is no enrichment overlay. The resolved descriptor\n // list arrives as a separate `appGadgets` array — this dispatcher's\n // downstream consumers consult it directly when they need transport\n // metadata.\n const effectiveContract = params.contract;\n\n // ── Build SingleComponentParams (the closure + assembleGenerationResult\n // both consume this shape).\n const sessionParams = {\n userPrompt: params.originalPrompt ?? params.userPrompt,\n contract: effectiveContract,\n shellType: params.shellType,\n screen: params.screen,\n evaluation: params.evaluation\n ? {\n enabled: params.evaluation.enabled,\n passThreshold: params.evaluation.passThreshold,\n maxRounds: params.evaluation.maxRounds ?? params.maxEvalRounds,\n }\n : undefined,\n visualEvaluation: params.visualEvaluation,\n qualityConfig: params.qualityConfig,\n fixtureProps: params.fixtureProps,\n ...(params.onCodingTurnPrompt !== undefined ? { onCodingTurnPrompt: params.onCodingTurnPrompt } : {}),\n };\n\n // ── Classify + build harness.\n const classification = classifyAxes({\n contract: (effectiveContract ?? {}) as Parameters<typeof classifyAxes>[0][\"contract\"],\n prompt: sessionParams.userPrompt,\n });\n const harness = createHarness({\n classification,\n contract: (effectiveContract ?? {}) as Parameters<typeof createHarness>[0][\"contract\"],\n prompt: sessionParams.userPrompt,\n shellType: sessionParams.shellType,\n screen: sessionParams.screen,\n // Forward the registered catalog into createHarness so\n // `generateBoilerplate` emits correct `import { useLeafletMap }\n // from '<package>'` lines for thin contract refs. The closure\n // capture below (systemPromptBuilder) wires the SAME catalog\n // into the HOW leg.\n ...(params.appGadgets !== undefined ? { appGadgets: params.appGadgets } : {}),\n // Forward the third-party wrapper `.d.ts` map so\n // `WhatLeg.gadgetTypes` reaches the coding-agent's typecheck\n // overlay (autoCommit → runTier0Checks → typecheck). The\n // systemPromptBuilder closure below also captures `gadgetTypes`\n // from `params` directly for the prompt `Type:` lines.\n ...(params.gadgetTypes !== undefined ? { gadgetTypes: params.gadgetTypes } : {}),\n // Design mode + canvas — the harness carries them to every leg.\n ...(params.designMode !== undefined ? { designMode: params.designMode } : {}),\n // ggui#1117 — the canvas is ALWAYS carried: a stated one, else the class\n // shell × screen renders on. The axis checks judge for it\n // (`universal.root_width_cap` stands down without one — which is what every\n // served generation got, since the serving runtime states no canvas); the\n // constrained prompt ignores it (INVARIANT 1, `design-mode.pin.test.ts`),\n // so the prompt digests do not move; the free prompt renders it as before.\n canvas: params.canvas ?? canvasForRendering(params.shellType, params.screen),\n ...(params.profile !== undefined ? { profile: params.profile } : {}),\n // Policy is pre-resolved at the dispatch boundary so `createHarness`\n // stays free of experiment plumbing. `resolveHarnessPolicy` applies\n // the `GGUI_POLICY_PROFILE` experimental-profile layer and hands the\n // result to the constructor.\n policy: resolveHarnessPolicy(classification),\n // Fully-populated system-prompt builder. This `buildSystemPrompt`\n // wrapper pre-fills pitfalls + design-system docs + primitives +\n // wire content.\n //\n // `appGadgets` is captured from `params` at dispatch time and\n // threaded into the wrapper so the code-gen prompt's\n // `clientCapabilities — registered catalog` section renders the\n // operator-registered gadget set (Leaflet, Mapbox, …) instead of\n // falling back to STDLIB. When omitted, the wrapper defaults to\n // STDLIB-only.\n // `params.gadgetTypes` is captured into the closure so the code-gen\n // prompt's gadget catalog renders a `Type:` line per third-party\n // gadget (the LLM sees a wrapper's real call shape it otherwise\n // can't know).\n systemPromptBuilder: ({\n userRequest,\n shellType,\n screen,\n axisDelta,\n designMode,\n canvas,\n profile,\n }) =>\n buildSystemPromptWithFunnel(\n userRequest,\n shellType,\n screen,\n axisDelta,\n params.appGadgets,\n params.gadgetTypes,\n designMode,\n canvas,\n profile\n ),\n // Pre-filtered axis-check registry. The `matches()` predicate\n // selects the checks relevant to this generation's axis vector.\n axisChecks: AXIS_CHECK_REGISTRY.filter((check) =>\n axisCheckMatches(classification.vector, check)\n ),\n // The runtime-render check, built under the caller's probe config.\n // Heavy deps (happy-dom + wire + design) stay on the dispatch side of\n // the boundary; the skeleton createHarness defaults this to undefined.\n //\n // Gated behind `enableRuntimeRender` (default true) so\n // benchmark/dev callers can opt out of in-loop probe execution and\n // run the probe externally as a final post-generation check.\n runtimeRender:\n (params.enableRuntimeRender ?? true)\n ? (params.runtimeRender ?? DEFAULT_RUNTIME_RENDER_CHECK)\n : undefined,\n });\n console.log(\n `[harness] id=${harness.id} name=${harness.name} workflow=${harness.process.workflow.name} overrides=${harness.meta.overrides.join(\",\") || \"none\"}`\n );\n console.log(\n `[simple] axis-vector: ${JSON.stringify(classification.vector)} risk=${classification.riskTier}`\n );\n\n // ── Guard: staged workflow is not wired on the dispatch path. ──\n // The STAGED workflow defines `architect` + `coder` task nodes, but\n // this dispatch path only registers a `generate` TaskRunner (the\n // closure-based coding loop). Unrecognised tasks silently fall\n // through to runWorkflow's noopDefaultRunner which returns the task\n // name as a literal string — that fails compile with a 5-byte\n // \"source\" and burns a full generation before the failure surfaces.\n //\n // Tests that exercise STAGED (harness.integrated.test.ts, run-workflow.test.ts,\n // create-harness.test.ts) wire architect+coder runners themselves, so\n // this guard only fires on the production dispatch path — the only path\n // that lacks those runners today.\n //\n // Callers that want staged behaviour should set `process.mode === \"staged\"`\n // with `process.workflow.name === \"single_pass\"` — the in-task A1 phase\n // machine (scaffold → fill) lives inside the `generate` runner and will\n // fire without needing the workflow topology.\n if (harness.process.workflow.name === \"staged\") {\n throw new Error(\n `[dispatch] STAGED workflow routed but architect/coder TaskRunners are not wired on the dispatch path. ` +\n `This is a misconfiguration (probably pickProcessMode returning WORKFLOWS.staged). ` +\n `For staged-like behaviour, set process.mode=\"staged\" + workflow.name=\"single_pass\" instead — the A1 ` +\n `scaffold→fill phase machine lives inside the generate runner and fires without the workflow topology. ` +\n `See ralph #3 report (2026-04-14) for the full rationale.`\n );\n }\n\n // ── Resolve agents + spin up the session.\n const agents = resolveSessionAgents({\n codingAgent,\n evaluationAgent,\n ...(visualEvalAgent !== undefined ? { visualEvalAgent } : {}),\n });\n\n // ── Runtime policy resolution ──\n // Experimental profiles opt in via the GGUI_POLICY_PROFILE env var.\n // The production Lambda / CLI never sets it; benchmark scripts can set\n // it explicitly to exercise provider-aware overrides. When unset,\n // resolveRunPolicyForProfile falls through to the identity\n // resolveRunPolicy — byte-identical to the default behavior.\n const { resolveRunPolicyForProfile } = await import(\"../harness/policy.js\");\n const resolvedPolicy = resolveRunPolicyForProfile(process.env.GGUI_POLICY_PROFILE, harness, {\n provider: routerProvider,\n modelId: resolvedModel,\n });\n\n // ── The primitives reference the first-turn prompt carries ──\n // The system prompt embeds PRIMITIVES_DOCUMENTATION (markdown) verbatim.\n // Three policy knobs decide what is SENT in its place, composed in this\n // order (ggui#1324, speed/002 — the slice applies to the format in force;\n // slicing the markdown before the TS swap sent a sliced markdown doc about\n // the size of the full TS doc, which speed/001 measured as a trim):\n // 1. primitiveDocFormat: \"markdown\" (the embedded doc) or \"ts\" (its\n // TypeScript-interface form, ~55% smaller, same information);\n // 2. primitiveDocSlice: \"full\", or an axis-keyed allowlist from the\n // classification (\"axis-keyed\", or \"axis-keyed+contract\" which adds the\n // inputs the contract implies) applied to THAT format's doc;\n // 3. primitiveIndex: a name-only index that replaces whatever is left\n // (tool-driven docs; wins when on).\n // Every cell logs `[simple] primitive-doc-bytes … mode=…` (the slice) and\n // `[simple] system-prompt-bytes … doc-format=… doc-bytes=…` (what is sent),\n // so a prompt-size claim is auditable from the log, not inferred.\n let systemPromptOverride: string | undefined;\n {\n const { PRIMITIVES_DOCUMENTATION } = await import(\"../validation/index.js\");\n const fullBytes = Buffer.byteLength(PRIMITIVES_DOCUMENTATION, \"utf8\");\n const docFormat = resolvedPolicy.context.primitiveDocFormat ?? \"markdown\";\n const indexMode = resolvedPolicy.context.primitiveIndex ?? \"off\";\n const mode = resolvedPolicy.context.primitiveDocSlice ?? \"full\";\n\n let doc = PRIMITIVES_DOCUMENTATION;\n if (docFormat === \"ts\" && indexMode === \"off\") {\n const { PRIMITIVES_DOCUMENTATION_TS } = await import(\"../tools/get-primitives-ts.js\");\n doc = PRIMITIVES_DOCUMENTATION_TS;\n const tsBytes = Buffer.byteLength(doc, \"utf8\");\n console.log(\n `[simple] primitive-doc-ts-bytes=${tsBytes} baseline=${fullBytes} drop=${((1 - tsBytes / fullBytes) * 100).toFixed(1)}%`\n );\n }\n const formatBytes = Buffer.byteLength(doc, \"utf8\");\n\n if (mode === \"axis-keyed\" || mode === \"axis-keyed+contract\") {\n const {\n computePrimitiveAllowlist,\n computeContractPrimitives,\n slicePrimitiveDocumentation,\n slicePrimitiveDocumentationTs,\n } = await import(\"../harness/primitive-slice.js\");\n let allowlist = computePrimitiveAllowlist(classification);\n if (mode === \"axis-keyed+contract\") {\n const fromContract = computeContractPrimitives(effectiveContract);\n allowlist = [...new Set([...allowlist, ...fromContract])].sort();\n }\n // Apply policy-driven excludes — some policy profiles drop\n // near-synonym layout primitives (e.g. Row/Box/Spacer).\n const excludes = resolvedPolicy.context.primitiveDocExcludes ?? [];\n if (excludes.length > 0) {\n const excludeSet = new Set(excludes);\n allowlist = allowlist.filter((p) => !excludeSet.has(p));\n }\n doc =\n docFormat === \"ts\" && indexMode === \"off\"\n ? slicePrimitiveDocumentationTs(doc, allowlist)\n : slicePrimitiveDocumentation(doc, allowlist);\n const slicedBytes = Buffer.byteLength(doc, \"utf8\");\n const excludeTag = excludes.length ? ` excludes=${excludes.join(\",\")}` : \"\";\n console.log(\n `[simple] primitive-doc-bytes=${slicedBytes} mode=${mode} baseline=${formatBytes} drop=${((1 - slicedBytes / formatBytes) * 100).toFixed(1)}% allowlist=${allowlist.length}/${allowlist.join(\",\")}${excludeTag}`\n );\n } else {\n console.log(\n `[simple] primitive-doc-bytes=${formatBytes} mode=full baseline=${formatBytes} drop=0.0%`\n );\n }\n\n // ── Tool-driven primitive docs ──\n // A name-only index replaces whatever is left (it is the more\n // aggressive cut). The two are mutually exclusive in practice via\n // profile selection; this ordering just defines the tiebreak.\n if (indexMode !== \"off\") {\n const { buildPrimitiveIndex } = await import(\"../harness/primitive-index.js\");\n doc = buildPrimitiveIndex(PRIMITIVES_DOCUMENTATION, indexMode);\n const indexBytes = Buffer.byteLength(doc, \"utf8\");\n console.log(\n `[simple] primitive-index-bytes=${indexBytes} mode=${indexMode} baseline=${fullBytes} drop=${((1 - indexBytes / fullBytes) * 100).toFixed(1)}%`\n );\n }\n\n if (doc !== PRIMITIVES_DOCUMENTATION) {\n systemPromptOverride = harness.how.systemPrompt.replace(PRIMITIVES_DOCUMENTATION, doc);\n }\n const sentPrompt = systemPromptOverride ?? harness.how.systemPrompt;\n console.log(\n `[simple] system-prompt-bytes=${Buffer.byteLength(sentPrompt, \"utf8\")} doc-format=${docFormat === \"ts\" && indexMode === \"off\" ? \"ts\" : docFormat} doc-bytes=${Buffer.byteLength(doc, \"utf8\")} mode=${indexMode !== \"off\" ? `index:${indexMode}` : mode}`\n );\n\n // ── plan→impl pipeline augmentation ──\n // Append a 2-phase flow description when planFirstTurn is active so\n // the LLM understands why turn 1 only advertises write_plan.\n if (resolvedPolicy.context.planFirstTurn) {\n const phaseGuidance = `\\n\\n## Generation Phases\\n\\nThis generation runs in TWO phases:\\n\\n**Turn 1 — PLAN.** The harness only advertises the \\`write_plan\\` tool. Commit to:\\n • \\`components\\`: which primitives/components you will use (from the reference above).\\n • \\`structure\\`: a brief JSX outline showing nesting.\\n • \\`wiring\\`: state/actions/streams you will use.\\nDo NOT attempt to write code — \\`apply_changes\\` is not available on turn 1.\\n\\n**Turn 2+ — EXECUTE.** Now write code via \\`apply_changes\\`. If your patches accumulate into a tangled broken state, \\`rewrite\\` is available as an escape. There is no fetch tool — the component reference above is complete.\\n\\nYour plan is a commitment, not a design doc. Keep it tight. Do not over-plan; just enough to pick components and sketch structure before writing.`;\n systemPromptOverride = (systemPromptOverride ?? harness.how.systemPrompt) + phaseGuidance;\n console.log(`[simple] plan-first-turn=on`);\n }\n }\n\n const session = await initSession({\n harness,\n params: sessionParams,\n agents,\n resolvedPolicy,\n systemPromptOverride,\n });\n\n // ── Build the closure-based generate runner.\n const telemetry = createTelemetry();\n const generate = createGenerateTaskRunner({\n session,\n params: sessionParams,\n classification,\n telemetry,\n maxTurns: params.maxAttempts ?? 8,\n });\n\n // ── Drive via runHarness — wrapper owns lifecycle + iteration telemetry.\n // The closure runs the inner coding+eval loop itself; runHarness's check\n // is skipped (skipCheck: true) to avoid double-firing LLM + visual eval\n // that the closure already ran internally. compile reads the closure's\n // pairedSource→compiledCode pairing so runHarness's compile-null safety\n // fires when the closure failed to produce a working compile.\n const runResult = await runHarness({\n harness,\n prompt: sessionParams.userPrompt,\n contract: (params.contract ?? { intent: \"\" }) as DataContract,\n taskRunners: { generate },\n compile: async () => telemetry.compiledCode || null,\n passes: () => true,\n skipCheck: true,\n maxIterations: 1,\n });\n\n // ── Propagate runHarness terminal failures.\n // Without this short-circuit, no-source / compile-failed silently fall\n // through to assembleGenerationResult and produce a \"successful\" result\n // with empty compiledCode — caller can't distinguish from a real success.\n if (!runResult.ok) {\n console.error(\n `[dispatch] runHarness terminated: ${runResult.reason} ` +\n `(source=${runResult.finalSource ? runResult.finalSource.length + \"B\" : \"null\"}, ` +\n `compiled=${runResult.finalCompiled ? runResult.finalCompiled.length + \"B\" : \"null\"})`\n );\n }\n\n // ── Assemble + return the legacy GenerationResult shape.\n // Source comes from runResult.finalSource (which is the closure's\n // pairedSource via the workflow output) — guaranteed to pair with\n // telemetry.compiledCode when runResult.ok is true.\n const finalSource = runResult.finalSource ?? \"\";\n // `assembleGenerationResult` is async — the spread below must see the\n // RESOLVED result, never the promise (a spread promise is `{}`: every\n // consumer downstream lost `compiledCode` / `tokens` on 2026-09-09).\n const result: GenerationResult = await assembleGenerationResult({\n session,\n telemetry,\n source: finalSource,\n });\n // Record the arm this generation ran under (bench reports read it per\n // cell). The canvas is the one the free prompt stated: explicit when\n // passed, else the same shell × screen derivation the prompt used.\n // Nothing is stamped on the default (constrained, no option) path.\n return withArmRecord(result, params);\n}\n\n/**\n * Stamp the arm record (`designMode` / `canvas`) onto a RESOLVED\n * {@link GenerationResult}. The input must be the resolved result, never a\n * promise — a spread promise is `{}` and every consumer downstream loses\n * `compiledCode` / `tokens` (2026-09-09; gate:\n * `generation-dispatch.resolved-result.test.ts`). Nothing is stamped on the\n * default (constrained, no option) path, so a default run's result is\n * byte-identical to the input.\n */\nfunction withArmRecord(\n result: GenerationResult,\n params: Pick<GenerationDispatchParams, \"designMode\" | \"canvas\" | \"shellType\" | \"screen\">\n): GenerationResult {\n const recordedCanvas: CanvasClass | undefined =\n params.canvas ??\n (params.designMode === \"free\"\n ? canvasForRendering(params.shellType, params.screen)\n : undefined);\n return {\n ...result,\n ...(params.designMode !== undefined ? { designMode: params.designMode } : {}),\n ...(recordedCanvas !== undefined ? { canvas: recordedCanvas } : {}),\n };\n}\n"]}