agentworkshop 0.8.0 → 0.8.1

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 (396) hide show
  1. package/.AgentWorkShop/prompts/host-tools.json +123 -0
  2. package/.output/.AgentWorkShop/prompts/host-tools.json +123 -0
  3. package/.output/nitro.json +1 -1
  4. package/.output/public/_nuxt/{DJJDigim2.js → -FhgRqJl2.js} +1 -1
  5. package/.output/public/_nuxt/{CGk_VUhO2.js → 0qvcO_KM2.js} +1 -1
  6. package/.output/public/_nuxt/26OL4Ao82.js +1 -0
  7. package/.output/public/_nuxt/{sBDZymdy2.js → 2Kwo_j9G2.js} +1 -1
  8. package/.output/public/_nuxt/{BqYVLAcm.js → 2v5GdspM.js} +1 -1
  9. package/.output/public/_nuxt/{DkQBMVTs2.js → 8M7wFbEN2.js} +1 -1
  10. package/.output/public/_nuxt/{DtiY69xi2.js → 8SZLbrI42.js} +1 -1
  11. package/.output/public/_nuxt/{DF32f5EL2.js → B2NbzUau2.js} +1 -1
  12. package/.output/public/_nuxt/{CwZW1ZCe2.js → B4JlRHBB2.js} +1 -1
  13. package/.output/public/_nuxt/{BQOn0q6Y.js → B6C4WofF.js} +1 -1
  14. package/.output/public/_nuxt/{BC7W6lNm.js → B6UwtJ1a.js} +1 -1
  15. package/.output/public/_nuxt/{BfQ-ptH0.js → B8HFUsMH.js} +1 -1
  16. package/.output/public/_nuxt/{DzBbYWrw2.js → BBB_j2LU2.js} +1 -1
  17. package/.output/public/_nuxt/BCLUwdP52.js +1 -0
  18. package/.output/public/_nuxt/{CLxmY3Rh.js → BK4wbfGS.js} +1 -1
  19. package/.output/public/_nuxt/{BRMVDfPl2.js → BKidykmV2.js} +1 -1
  20. package/.output/public/_nuxt/BPUQZ9Lq2.js +8 -0
  21. package/.output/public/_nuxt/BRYBzVMJ.js +1 -0
  22. package/.output/public/_nuxt/{Bj5sjA5O.js → BRci9D_l.js} +1 -1
  23. package/.output/public/_nuxt/{Dmgqz2np2.js → BVGzwAxr2.js} +1 -1
  24. package/.output/public/_nuxt/BVg2R2VB2.js +1 -0
  25. package/.output/public/_nuxt/{C3aUN4Vp2.js → BW2uTUx52.js} +1 -1
  26. package/.output/public/_nuxt/{B5FKaMM02.js → BY3Lbz3h2.js} +1 -1
  27. package/.output/public/_nuxt/{DIwmMa_7.js → BYzim_Bn.js} +1 -1
  28. package/.output/public/_nuxt/{D8xUsQGt.js → B_Obcbiu.js} +1 -1
  29. package/.output/public/_nuxt/BaYDgyaR.js +3 -0
  30. package/.output/public/_nuxt/{DZJ11BTI.js → BbACaREb.js} +1 -1
  31. package/.output/public/_nuxt/{BJrj5JVe2.js → BcosvNXb2.js} +1 -1
  32. package/.output/public/_nuxt/{B_-vAvzb.js → BfeXib9G.js} +1 -1
  33. package/.output/public/_nuxt/{CeLqojCJ.js → BfgTar9L.js} +1 -1
  34. package/.output/public/_nuxt/BfvuWqSa.js +1 -0
  35. package/.output/public/_nuxt/{D8r8PNQa2.js → BiZWwdcD2.js} +1 -1
  36. package/.output/public/_nuxt/{DIFkTkdS.js → BkEokGX5.js} +1 -1
  37. package/.output/public/_nuxt/{CJSohaqk2.js → BklGqEto2.js} +2 -2
  38. package/.output/public/_nuxt/{DkpmSnHX.js → Bko5adbu.js} +1 -1
  39. package/.output/public/_nuxt/{DTQTGA6v2.js → BmBlIIJo2.js} +1 -1
  40. package/.output/public/_nuxt/{D_NjL-Hz.js → Bmvt9ydE.js} +1 -1
  41. package/.output/public/_nuxt/{Cp4r6Eiz.js → BoyuIoSm.js} +1 -1
  42. package/.output/public/_nuxt/{62J4vljm.js → Bq-tmkst.js} +1 -1
  43. package/.output/public/_nuxt/{BMMoqi94.js → BqFaZ4kS.js} +1 -1
  44. package/.output/public/_nuxt/BsJYieAL2.js +1 -0
  45. package/.output/public/_nuxt/{DD4J2Otc.js → BtZKe9ZV.js} +1 -1
  46. package/.output/public/_nuxt/{BnpY_zNx.js → BtumQhZK.js} +1 -1
  47. package/.output/public/_nuxt/{BjLzqWJH2.js → BwWs9EdO2.js} +1 -1
  48. package/.output/public/_nuxt/{Bx2a9cuY2.js → BxxpJxZf2.js} +1 -1
  49. package/.output/public/_nuxt/{qRXa-PM22.js → ByTnUqFw2.js} +1 -1
  50. package/.output/public/_nuxt/{DvOETuoT2.js → Byiiiwc72.js} +1 -1
  51. package/.output/public/_nuxt/{Car2lkbb.js → C1-SuwUN.js} +1 -1
  52. package/.output/public/_nuxt/{Dg81dOEO.js → C14pM5G4.js} +1 -1
  53. package/.output/public/_nuxt/{MDhaRQq_.js → C2Yp-B8m.js} +1 -1
  54. package/.output/public/_nuxt/{BJ2nJNlK2.js → C4e6_nom2.js} +1 -1
  55. package/.output/public/_nuxt/{CiCEprsp2.js → C5OStZJ62.js} +1 -1
  56. package/.output/public/_nuxt/{ByMj6e7s.js → C6lssmvl.js} +2 -2
  57. package/.output/public/_nuxt/{C6uBP0Xa.js → CC-GEjfN.js} +1 -1
  58. package/.output/public/_nuxt/CC2Pv8VL2.js +1 -0
  59. package/.output/public/_nuxt/{DKiqdYnj.js → CCcMgxV9.js} +1 -1
  60. package/.output/public/_nuxt/{5S26I34j2.js → CDL30A2z2.js} +1 -1
  61. package/.output/public/_nuxt/{B8C-QJB5.js → CDYLasP8.js} +1 -1
  62. package/.output/public/_nuxt/CElzwyXQ.js +1 -0
  63. package/.output/public/_nuxt/{2KE8xGVm.js → CEvJu-xI.js} +1 -1
  64. package/.output/public/_nuxt/{CR612R752.js → CFQRFctQ2.js} +1 -1
  65. package/.output/public/_nuxt/{DnzjxC0u.js → CHk9XxNi.js} +2 -2
  66. package/.output/public/_nuxt/{Bx4MR0jd.js → CLFmtXU7.js} +1 -1
  67. package/.output/public/_nuxt/{DW8k_0dQ.js → CMJi6yYS.js} +1 -1
  68. package/.output/public/_nuxt/{DD-r0S1p.js → CPvFGbr8.js} +1 -1
  69. package/.output/public/_nuxt/{CCgbgkid.js → CQSxS_Ek.js} +2 -2
  70. package/.output/public/_nuxt/{jGxHnjW6.js → CQuo31jF.js} +1 -1
  71. package/.output/public/_nuxt/{SoO2K-di.js → CRCrWy-6.js} +1 -1
  72. package/.output/public/_nuxt/CUCFFL9m.js +84 -0
  73. package/.output/public/_nuxt/CZYNy60j2.js +1 -0
  74. package/.output/public/_nuxt/{WPwdj9pg.js → CZsFf7ck.js} +1 -1
  75. package/.output/public/_nuxt/CfFUK6932.js +2 -0
  76. package/.output/public/_nuxt/{DAsjfdZD.js → CfIbFnJz.js} +1 -1
  77. package/.output/public/_nuxt/{Tk6TQZjU.js → CjF4QY9h.js} +1 -1
  78. package/.output/public/_nuxt/{DlUQa0wn.js → Cjo1t2IF.js} +1 -1
  79. package/.output/public/_nuxt/{CDn0eDn8.js → CmuGMxDP.js} +1 -1
  80. package/.output/public/_nuxt/Cn6EojFe.js +1 -0
  81. package/.output/public/_nuxt/{DLqSQbGv.js → CnYazk8d.js} +1 -1
  82. package/.output/public/_nuxt/{DQfy6R_2.js → CnrGVJIr.js} +1 -1
  83. package/.output/public/_nuxt/{C0YL0HKK.js → CtcBhkci.js} +1 -1
  84. package/.output/public/_nuxt/{h5gsh8E92.js → Cv-Mv7_h2.js} +1 -1
  85. package/.output/public/_nuxt/{vPcnBJsa2.js → CzlZrfq82.js} +1 -1
  86. package/.output/public/_nuxt/{C2YYOgMe.js → CznnUTZx.js} +2 -2
  87. package/.output/public/_nuxt/{csitHKnE2.js → D-80EfyA2.js} +1 -1
  88. package/.output/public/_nuxt/{BRdoISnJ2.js → D1C6qtS12.js} +1 -1
  89. package/.output/public/_nuxt/{Cnrmlixo.js → D1MkndMZ.js} +2 -2
  90. package/.output/public/_nuxt/{BLwDhlaa.js → D37gODe0.js} +1 -1
  91. package/.output/public/_nuxt/{NXY37IO62.js → D6FhDrYe2.js} +1 -1
  92. package/.output/public/_nuxt/{Btx8wL4-.js → D7TZLu4F.js} +1 -1
  93. package/.output/public/_nuxt/{qoUdVDnC.js → D7tEwf-o.js} +3 -3
  94. package/.output/public/_nuxt/D8HQPtm62.js +1 -0
  95. package/.output/public/_nuxt/D9O4L4jK.js +1 -0
  96. package/.output/public/_nuxt/{aQ1B7BZa2.js → D9lL3fJM2.js} +2 -2
  97. package/.output/public/_nuxt/{CT-vTjcG2.js → DC-2eKo62.js} +1 -1
  98. package/.output/public/_nuxt/DF9ETYJ32.js +1 -0
  99. package/.output/public/_nuxt/DGGBrc0q2.js +1 -0
  100. package/.output/public/_nuxt/DGu_fna7.js +1 -0
  101. package/.output/public/_nuxt/{BupBjt6B.js → DKOvbitt.js} +1 -1
  102. package/.output/public/_nuxt/{B1PzYsqN.js → DNxudyND.js} +1 -1
  103. package/.output/public/_nuxt/{BfX6_AjY.js → DOT-XQyi.js} +1 -1
  104. package/.output/public/_nuxt/{BsTZnkVK.js → DPPC9Teq.js} +1 -1
  105. package/.output/public/_nuxt/{HxohXQ_r.js → DRskyE7l.js} +1 -1
  106. package/.output/public/_nuxt/{B-U7E_Mc2.js → DW4ZgInh2.js} +1 -1
  107. package/.output/public/_nuxt/{BErG4kzc2.js → DWe6BMlp2.js} +1 -1
  108. package/.output/public/_nuxt/{BH8RvpVy.js → DWy0AjON.js} +1 -1
  109. package/.output/public/_nuxt/{Bc_k6AVA.js → DXgw1dVL.js} +4 -4
  110. package/.output/public/_nuxt/{C3sWJ8SD2.js → DZsKIzKD2.js} +1 -1
  111. package/.output/public/_nuxt/D_59BNP1.js +14 -0
  112. package/.output/public/_nuxt/{BQIO4MkA2.js → D_FZ3KZI2.js} +1 -1
  113. package/.output/public/_nuxt/{n_Njdwii2.js → D__vJGHF2.js} +1 -1
  114. package/.output/public/_nuxt/{C9gErLQc2.js → DaizNGUm2.js} +1 -1
  115. package/.output/public/_nuxt/{C-MY-JQE.js → DdyE0ylS.js} +1 -1
  116. package/.output/public/_nuxt/DhLlTxQh2.js +1 -0
  117. package/.output/public/_nuxt/{CxVhG0Xx.js → DhW7cFOa.js} +1 -1
  118. package/.output/public/_nuxt/{Rt2i6k7C2.js → DhjgWrB62.js} +1 -1
  119. package/.output/public/_nuxt/{KwT4sN_d.js → DiWcX4gj.js} +1 -1
  120. package/.output/public/_nuxt/DiloA8vK.js +1 -0
  121. package/.output/public/_nuxt/{DX-c5laM2.js → DlS-SkQ42.js} +1 -1
  122. package/.output/public/_nuxt/{D_Zspo1y.js → DmHp9yQ3.js} +1 -1
  123. package/.output/public/_nuxt/{dq1HKoGD.js → DoL9u6wu.js} +1 -1
  124. package/.output/public/_nuxt/{CIvMT5Ic.js → DqxBCeDe.js} +1 -1
  125. package/.output/public/_nuxt/{BnNmkGJS2.js → DrlnrdvY2.js} +3 -3
  126. package/.output/public/_nuxt/{BAcjVcku2.js → Dt8TL8_X2.js} +1 -1
  127. package/.output/public/_nuxt/{BtfwbNC0.js → Du7gS8RU.js} +1 -1
  128. package/.output/public/_nuxt/DuUc4bbY2.js +1 -0
  129. package/.output/public/_nuxt/{DPUXbTg9.js → DudoisLM.js} +1 -1
  130. package/.output/public/_nuxt/{Ce5R-ZGf2.js → DwgVlehj2.js} +1 -1
  131. package/.output/public/_nuxt/Dyxf2xZw.js +1 -0
  132. package/.output/public/_nuxt/Dz9C2pTa.js +1 -0
  133. package/.output/public/_nuxt/{BYxG9Hb2.js → EMbqTHfT.js} +1 -1
  134. package/.output/public/_nuxt/{B1SzppY12.js → FsRVXpyF2.js} +1 -1
  135. package/.output/public/_nuxt/{0MLy6ogg2.js → GQrEW8nk2.js} +1 -1
  136. package/.output/public/_nuxt/{Tuz5LcLM.js → IXR1BWP5.js} +1 -1
  137. package/.output/public/_nuxt/{-jpUnM1I2.js → Iub61dX92.js} +1 -1
  138. package/.output/public/_nuxt/{CQgOzpvI.js → JegDslce.js} +2 -2
  139. package/.output/public/_nuxt/{DrF3TWoj.js → KzK37yIr.js} +1 -1
  140. package/.output/public/_nuxt/{Br3MggOL.js → N-CCmCsX.js} +1 -1
  141. package/.output/public/_nuxt/{DHhmq7s_.js → NfvZ5Lzv.js} +1 -1
  142. package/.output/public/_nuxt/{CzX_kaPL.js → POTcePF_.js} +1 -1
  143. package/.output/public/_nuxt/{D7s96J3r2.js → Q-JpBT032.js} +1 -1
  144. package/.output/public/_nuxt/{DzwIZ81f2.js → R1g64DNi2.js} +1 -1
  145. package/.output/public/_nuxt/{JgheoP3e.js → R5Pz7BqB.js} +1 -1
  146. package/.output/public/_nuxt/{yLyz0-Yz.js → SvjzWbn8.js} +1 -1
  147. package/.output/public/_nuxt/{Dd7MZc_Q.js → XqXoaoDs.js} +1 -1
  148. package/.output/public/_nuxt/{B6jtLy6z.js → YAA98rWJ.js} +11 -11
  149. package/.output/public/_nuxt/{HX4_xnak2.js → YLYSczSq2.js} +1 -1
  150. package/.output/public/_nuxt/{BBw9ylUY2.js → YNhAoK-R2.js} +1 -1
  151. package/.output/public/_nuxt/Zkbt8Uk5.js +1 -0
  152. package/.output/public/_nuxt/aml.PalMp-5n.css +1 -0
  153. package/.output/public/_nuxt/{C41CcsiD.js → b7UcqLKi.js} +1 -1
  154. package/.output/public/_nuxt/builds/latest.json +1 -1
  155. package/.output/public/_nuxt/builds/meta/fa0af8b5-3929-428d-a6de-3b5cc6b8248f.json +1 -0
  156. package/.output/public/_nuxt/{DVkFSOZi.js → cKj4vSo5.js} +1 -1
  157. package/.output/public/_nuxt/{r1CpGsFp.js → dHwWyr6b.js} +1 -1
  158. package/.output/public/_nuxt/{DlcA9Gxl.js → eePbiWEh.js} +1 -1
  159. package/.output/public/_nuxt/{cjRzSvAg2.js → eymRov9Y2.js} +1 -1
  160. package/.output/public/_nuxt/{B8cViLJT.js → geMze5qw.js} +1 -1
  161. package/.output/public/_nuxt/{uu1wfdfR2.js → gh-WMxV_2.js} +1 -1
  162. package/.output/public/_nuxt/{Ce6e1mPk2.js → hCN555XP2.js} +1 -1
  163. package/.output/public/_nuxt/{rdUE8Khf.js → hZG5MLjK.js} +3 -3
  164. package/.output/public/_nuxt/{CcX_jP-d.js → hlfahYxK.js} +1 -1
  165. package/.output/public/_nuxt/{cGSl2GZp2.js → ilJHF1nA2.js} +1 -1
  166. package/.output/public/_nuxt/{D6ZcgHPz.js → jDuiDtGb.js} +1 -1
  167. package/.output/public/_nuxt/{DbeNMehP.js → k9b520K-.js} +1 -1
  168. package/.output/public/_nuxt/ontology.B_3Wn907.css +1 -0
  169. package/.output/public/_nuxt/optimizer.CLA8I1sy.css +1 -0
  170. package/.output/public/_nuxt/{DSORcpTJ.js → rDvMijKA.js} +2 -2
  171. package/.output/public/_nuxt/{CAiHhX8P2.js → rF7mggl72.js} +2 -2
  172. package/.output/public/_nuxt/ri9UF8rk.js +2 -0
  173. package/.output/public/_nuxt/{KgnxOsMr.js → toG_qAMH.js} +1 -1
  174. package/.output/public/_nuxt/{KQZmHR_K.js → u3h4pGpm.js} +2 -2
  175. package/.output/public/_nuxt/{dJ7gK7C2.js → uomnHjhM.js} +1 -1
  176. package/.output/public/_nuxt/{BUTg4W_x2.js → v77qozuJ2.js} +1 -1
  177. package/.output/public/_nuxt/{BcEr7tIB.js → v7cV7hJa.js} +1 -1
  178. package/.output/public/_nuxt/{D25dVZ822.js → vkQoYNQR2.js} +2 -2
  179. package/.output/public/_nuxt/{wR_w07322.js → vp3LtnTz2.js} +1 -1
  180. package/.output/public/_nuxt/{Bnc8HELj2.js → we7-sMSo2.js} +1 -1
  181. package/.output/public/_nuxt/{kN3ZzR1-.js → wxISMS1i.js} +1 -1
  182. package/.output/public/_nuxt/{DGrrucbG.js → zy7efYKR.js} +1 -1
  183. package/.output/server/chunks/_/data-export.mjs +5 -5
  184. package/.output/server/chunks/_/data-query.mjs +2 -2
  185. package/.output/server/chunks/_/eda-run.repo.mjs +2 -2
  186. package/.output/server/chunks/_/features.mjs +4 -4
  187. package/.output/server/chunks/_/golden.mjs +2 -2
  188. package/.output/server/chunks/_/index.mjs +1 -1
  189. package/.output/server/chunks/_/mes-console.mjs +1 -1
  190. package/.output/server/chunks/_/nitro.mjs +2149 -1520
  191. package/.output/server/chunks/_/nitro.mjs.map +1 -1
  192. package/.output/server/chunks/_/spc.mjs +1 -1
  193. package/.output/server/chunks/build/TownView-BWMDbosY.mjs +1 -1
  194. package/.output/server/chunks/build/{_wsId_-BNKrrV1H.mjs → _wsId_-BPy-Aj9L.mjs} +3 -3
  195. package/.output/server/chunks/build/{_wsId_-BNKrrV1H.mjs.map → _wsId_-BPy-Aj9L.mjs.map} +1 -1
  196. package/.output/server/chunks/build/{agents-8tV9xL97.mjs → agents-CpNLdI8E.mjs} +6 -6
  197. package/.output/server/chunks/build/{agents-8tV9xL97.mjs.map → agents-CpNLdI8E.mjs.map} +1 -1
  198. package/.output/server/chunks/build/{aml-BNTEDOsl.mjs → aml-DRAFRcGU.mjs} +15 -12
  199. package/.output/server/chunks/build/{aml-BNTEDOsl.mjs.map → aml-DRAFRcGU.mjs.map} +1 -1
  200. package/.output/server/chunks/build/{channel-templates-Iot9Y3vV.mjs → channel-templates-ByHOQQkO.mjs} +2 -2
  201. package/.output/server/chunks/build/{channel-templates-Iot9Y3vV.mjs.map → channel-templates-ByHOQQkO.mjs.map} +1 -1
  202. package/.output/server/chunks/build/daq-CdxcfY_G.mjs +1 -1
  203. package/.output/server/chunks/build/dcw-BlDQtS4q.mjs +1 -1
  204. package/.output/server/chunks/build/{default-CJkOcmrm.mjs → default-CNWS6NUw.mjs} +4 -4
  205. package/.output/server/chunks/build/{default-CJkOcmrm.mjs.map → default-CNWS6NUw.mjs.map} +1 -1
  206. package/.output/server/chunks/build/{dropdown-CjwsxU39.mjs → dropdown-BNwTVGde.mjs} +2 -2
  207. package/.output/server/chunks/build/{dropdown-CjwsxU39.mjs.map → dropdown-BNwTVGde.mjs.map} +1 -1
  208. package/.output/server/chunks/build/{dropdown-C6YH_kSO.mjs → dropdown-Cd-xPhR6.mjs} +2 -2
  209. package/.output/server/chunks/build/{dropdown-C6YH_kSO.mjs.map → dropdown-Cd-xPhR6.mjs.map} +1 -1
  210. package/.output/server/chunks/build/input-number-BNlNDK7H.mjs +1 -1
  211. package/.output/server/chunks/build/{logs-BTfJQ6vQ.mjs → logs-pRb-TMWa.mjs} +3 -3
  212. package/.output/server/chunks/build/{logs-BTfJQ6vQ.mjs.map → logs-pRb-TMWa.mjs.map} +1 -1
  213. package/.output/server/chunks/build/{monitor-DvaR3yo8.mjs → monitor-Cq6hRFeQ.mjs} +6 -6
  214. package/.output/server/chunks/build/{monitor-DvaR3yo8.mjs.map → monitor-Cq6hRFeQ.mjs.map} +1 -1
  215. package/.output/server/chunks/build/{ontology-C3HS5pMo.mjs → ontology-DK0Mf0zT.mjs} +510 -81
  216. package/.output/server/chunks/build/ontology-DK0Mf0zT.mjs.map +1 -0
  217. package/.output/server/chunks/build/{operations-Cl8nVm9D.mjs → operations-SMQrRAcr.mjs} +3 -3
  218. package/.output/server/chunks/build/{operations-Cl8nVm9D.mjs.map → operations-SMQrRAcr.mjs.map} +1 -1
  219. package/.output/server/chunks/build/optimizer-BlWTsM-W.mjs +202 -0
  220. package/.output/server/chunks/build/optimizer-BlWTsM-W.mjs.map +1 -0
  221. package/.output/server/chunks/build/{pagination-KaIvHBzi.mjs → pagination-DTAconUo.mjs} +2 -2
  222. package/.output/server/chunks/build/{pagination-KaIvHBzi.mjs.map → pagination-DTAconUo.mjs.map} +1 -1
  223. package/.output/server/chunks/build/{permissions-CVTfixZj.mjs → permissions-DgXQZSyx.mjs} +6 -6
  224. package/.output/server/chunks/build/{permissions-CVTfixZj.mjs.map → permissions-DgXQZSyx.mjs.map} +1 -1
  225. package/.output/server/chunks/build/{schedules-BLhn2CLn.mjs → schedules-dSnr8url.mjs} +6 -6
  226. package/.output/server/chunks/build/{schedules-BLhn2CLn.mjs.map → schedules-dSnr8url.mjs.map} +1 -1
  227. package/.output/server/chunks/build/{select--XFl7CtY.mjs → select-B3Dsb9yq.mjs} +3 -3
  228. package/.output/server/chunks/build/{select--XFl7CtY.mjs.map → select-B3Dsb9yq.mjs.map} +1 -1
  229. package/.output/server/chunks/build/{settings-DIf_iYdu.mjs → settings-BrIhnS2Z.mjs} +2 -2
  230. package/.output/server/chunks/build/{settings-DIf_iYdu.mjs.map → settings-BrIhnS2Z.mjs.map} +1 -1
  231. package/.output/server/chunks/build/{table-DIu_YCJN.mjs → table-CmVD-cA9.mjs} +4 -4
  232. package/.output/server/chunks/build/{table-DIu_YCJN.mjs.map → table-CmVD-cA9.mjs.map} +1 -1
  233. package/.output/server/chunks/build/{teams-B2J6ouRY.mjs → teams-B1d32eHK.mjs} +4 -4
  234. package/.output/server/chunks/build/{teams-B2J6ouRY.mjs.map → teams-B1d32eHK.mjs.map} +1 -1
  235. package/.output/server/chunks/build/{tokens-DFQGaN2n.mjs → tokens-GYaGJ35Z.mjs} +6 -6
  236. package/.output/server/chunks/build/{tokens-DFQGaN2n.mjs.map → tokens-GYaGJ35Z.mjs.map} +1 -1
  237. package/.output/server/chunks/build/{tools-DWJFnU_t.mjs → tools-s_9U1Djj.mjs} +6 -6
  238. package/.output/server/chunks/build/{tools-DWJFnU_t.mjs.map → tools-s_9U1Djj.mjs.map} +1 -1
  239. package/.output/server/chunks/build/types-D6J7slEa.mjs +1 -1
  240. package/.output/server/chunks/build/useDaqAddNode-D_Rkju0f.mjs +1 -1
  241. package/.output/server/chunks/build/useDaqDetailNode-DeOsDxK5.mjs +1 -1
  242. package/.output/server/chunks/build/useDaqDetailParams-Cm9a9r5G.mjs +1 -1
  243. package/.output/server/chunks/build/useDaqFilters-CctmO03p.mjs +1 -1
  244. package/.output/server/chunks/build/useDaqStream-B9ZBVQrI.mjs +1 -1
  245. package/.output/server/chunks/build/useDaqTemplates-CK37sMfi.mjs +1 -1
  246. package/.output/server/chunks/build/useDcwAddNode-DACVcEHs.mjs +1 -1
  247. package/.output/server/chunks/build/useDcwStream-Dir5ufAU.mjs +1 -1
  248. package/.output/server/chunks/build/{users-BWw0VCr9.mjs → users-DjiVC_tS.mjs} +6 -6
  249. package/.output/server/chunks/build/{users-BWw0VCr9.mjs.map → users-DjiVC_tS.mjs.map} +1 -1
  250. package/.output/server/chunks/routes/api/mcp/workshop.mjs +1 -1
  251. package/.output/server/chunks/routes/api/system/backup/run.post.mjs +2 -2
  252. package/.output/server/chunks/routes/api/workshop/aml/models/_id_.patch.mjs +7 -1
  253. package/.output/server/chunks/routes/api/workshop/aml/models/_id_.patch.mjs.map +1 -1
  254. package/.output/server/chunks/routes/api/workshop/channel-templates/_id/instantiate.post.mjs +1 -1
  255. package/.output/server/chunks/routes/api/workshop/channels.post.mjs +6 -6
  256. package/.output/server/chunks/routes/api/workshop/daq/_id/ingest.post.mjs +2 -2
  257. package/.output/server/chunks/routes/api/workshop/harnesses/_id/providers.get.mjs +1 -1
  258. package/.output/server/chunks/routes/api/workshop/index.mjs +1 -1
  259. package/.output/server/chunks/routes/api/workshop/index.put.mjs +1 -1
  260. package/.output/server/chunks/routes/api/workshop/ontology/drafts/_draftId/autofix.mjs +52 -0
  261. package/.output/server/chunks/routes/api/workshop/ontology/drafts/_draftId/autofix.mjs.map +1 -0
  262. package/.output/server/chunks/routes/api/workshop/ontology/drafts/_draftId/compile.mjs +1 -1
  263. package/.output/server/chunks/routes/api/workshop/ontology/drafts/_draftId/evidence.mjs +1 -1
  264. package/.output/server/chunks/routes/api/workshop/ontology/drafts/_draftId/publish.mjs +1 -1
  265. package/.output/server/chunks/routes/api/workshop/ontology/drafts/_draftId/rules/_ruleId/approval-decision.mjs +1 -1
  266. package/.output/server/chunks/routes/api/workshop/ontology/drafts/_draftId/rules/_ruleId/approval.mjs +1 -1
  267. package/.output/server/chunks/routes/api/workshop/ontology/drafts/_draftId/rules/_ruleId/transition.mjs +1 -1
  268. package/.output/server/chunks/routes/api/workshop/ontology/drafts/_draftId/subgraph.mjs +38 -0
  269. package/.output/server/chunks/routes/api/workshop/ontology/drafts/_draftId/subgraph.mjs.map +1 -0
  270. package/.output/server/chunks/routes/api/workshop/ontology/drafts/_draftId/validate.mjs +1 -1
  271. package/.output/server/chunks/routes/api/workshop/ontology/export/_ontologyId_.mjs +1 -1
  272. package/.output/server/chunks/routes/api/workshop/ontology/index.mjs +1 -1
  273. package/.output/server/chunks/routes/api/workshop/ontology/scene.mjs +8 -1
  274. package/.output/server/chunks/routes/api/workshop/ontology/scene.mjs.map +1 -1
  275. package/.output/server/chunks/routes/api/workshop/ontology/traces/_ontologyId_.mjs +1 -1
  276. package/.output/server/chunks/routes/api/workshop/ontology/versions/_ontologyId/compare.mjs +1 -1
  277. package/.output/server/chunks/routes/api/workshop/ontology/versions/_ontologyId_.mjs +1 -1
  278. package/.output/server/chunks/routes/api/workshop/optimization/capabilities.get.mjs +1 -1
  279. package/.output/server/chunks/routes/api/workshop/optimization/index.mjs +1 -1
  280. package/.output/server/chunks/routes/api/workshop/optimization/index2.mjs +1 -1
  281. package/.output/server/chunks/routes/api/workshop/optimization/profiles/_id/publish.post.mjs +1 -1
  282. package/.output/server/chunks/routes/api/workshop/optimization/recommendations/_id/crosscheck.post.mjs +1 -1
  283. package/.output/server/chunks/routes/api/workshop/optimization/recommendations/_id/dispatch.post.mjs +1 -1
  284. package/.output/server/chunks/routes/api/workshop/optimization/solve.post.mjs +1 -1
  285. package/.output/server/chunks/routes/api/workshop/plugins/_name/disable.post.mjs +1 -1
  286. package/.output/server/chunks/routes/api/workshop/plugins/_name/enable.post.mjs +1 -1
  287. package/.output/server/chunks/routes/api/workshop/process-model/datasets.post.mjs +1 -1
  288. package/.output/server/chunks/routes/api/workshop/process-model/eligibility.mjs +1 -1
  289. package/.output/server/chunks/routes/api/workshop/process-model/index.mjs +1 -1
  290. package/.output/server/chunks/routes/api/workshop/process-model/specs/_id/publish.post.mjs +1 -1
  291. package/.output/server/chunks/routes/api/workshop/process-model/train.post.mjs +1 -1
  292. package/.output/server/chunks/routes/api/workshop/scene/layouts/_channelId_.delete.mjs +1 -1
  293. package/.output/server/chunks/routes/api/workshop/scene/layouts/_channelId_.put.mjs +1 -1
  294. package/.output/server/chunks/routes/api/workshop/tools/sync.post.mjs +1 -1
  295. package/.output/server/chunks/routes/api/workshop/workspaces/_id/channel-templates/_tplId_.post.mjs +1 -1
  296. package/.output/server/chunks/routes/renderer.mjs +2 -2
  297. package/.output/server/chunks/virtual/entry.mjs +92 -18
  298. package/.output/server/chunks/virtual/precomputed.mjs +1 -1
  299. package/.output/server/package.json +1 -1
  300. package/README-zh.md +5 -4
  301. package/README.md +6 -5
  302. package/app/components/aml/AmlModelsTable.vue +5 -0
  303. package/app/components/ontology/OntologyGraph.vue +356 -0
  304. package/app/pages/aml/styles.css +1 -0
  305. package/app/pages/ontology/index.vue +318 -35
  306. package/app/pages/ontology/types.ts +42 -0
  307. package/app/pages/optimizer/index.vue +21 -4
  308. package/config.yml +1 -1
  309. package/docs/cli.en.md +2 -2
  310. package/docs/cli.md +2 -2
  311. package/docs/plugins.en.md +1 -1
  312. package/docs/plugins.md +1 -1
  313. package/docs/sdk.en.md +1 -1
  314. package/docs/sdk.md +1 -1
  315. package/i18n/locales/en.ts +26 -0
  316. package/i18n/locales/zh-CN.ts +26 -0
  317. package/mcp/aw-mcp-server.mjs +20 -2
  318. package/package.json +1 -1
  319. package/scripts/e2e-direct-rest-simulator-paper.mjs +624 -0
  320. package/scripts/e2e-idd-results.mjs +177 -0
  321. package/scripts/e2e-model-loop-live.mjs +58 -4
  322. package/scripts/e2e-ontology-live.mjs +138 -3
  323. package/scripts/e2e-ontology.mjs +393 -328
  324. package/scripts/e2e-pi-simulator-paper.mjs +2316 -0
  325. package/scripts/e2e-registered-harness-simulator-paper.mjs +1926 -0
  326. package/scripts/e2e-simulator-optimizer-paper.mjs +264 -0
  327. package/scripts/fixtures/omp-paper-harness.mjs +163 -0
  328. package/sdk/context.mjs +6 -0
  329. package/sdk/index.d.mts +2 -0
  330. package/server/api/workshop/aml/models/[id].patch.ts +36 -30
  331. package/server/api/workshop/ontology/drafts/[draftId]/autofix.ts +31 -0
  332. package/server/api/workshop/ontology/drafts/[draftId]/subgraph.ts +24 -0
  333. package/server/api/workshop/ontology/scene.ts +14 -1
  334. package/server/plugins-builtin/diag-bridge/client.mjs +390 -239
  335. package/server/plugins-builtin/diag-bridge/host/helpers.mjs +80 -0
  336. package/server/plugins-builtin/diag-bridge/host/plugin.mjs +264 -2
  337. package/server/plugins-builtin/diag-bridge/i18n.json +84 -4
  338. package/server/services/workshop/agents/adapters/omp-rpc-client/frames.ts +129 -111
  339. package/server/services/workshop/agents/host-tool-bridge/tools/industrial.ts +6 -3
  340. package/server/services/workshop/agents/industrial/aml-job-tools.ts +602 -569
  341. package/server/services/workshop/agents/industrial/grant-guard.ts +15 -1
  342. package/server/services/workshop/agents/industrial/index.ts +2 -2
  343. package/server/services/workshop/agents/industrial/ontology-tools.ts +66 -6
  344. package/server/services/workshop/agents/industrial/ops-tools.ts +54 -16
  345. package/server/services/workshop/agents/industrial/optimizer-tools.ts +2 -0
  346. package/server/services/workshop/agents/industrial/recipe-gate.ts +19 -6
  347. package/server/services/workshop/agents/industrial/recipe-propose-tools.ts +1 -1
  348. package/server/services/workshop/agents/omp-agent/supervision-history.ts +38 -0
  349. package/server/services/workshop/agents/omp-agent/tools-steer.ts +18 -1
  350. package/server/services/workshop/aml/aml.repo.ts +16 -0
  351. package/server/services/workshop/daq/bus/index.ts +12 -5
  352. package/server/services/workshop/db/database/open.ts +97 -97
  353. package/server/services/workshop/db/database/schema.ts +1 -0
  354. package/server/services/workshop/ontology/autofix.ts +198 -0
  355. package/server/services/workshop/ontology/contracts.ts +3 -1
  356. package/server/services/workshop/ontology/index.ts +2 -0
  357. package/server/services/workshop/ontology/ontology.service.ts +46 -0
  358. package/server/services/workshop/ontology/subgraph.core.ts +300 -0
  359. package/server/services/workshop/ontology/subgraph.service.ts +113 -0
  360. package/server/services/workshop/optimization/contracts.ts +2 -0
  361. package/server/services/workshop/optimization/profile-adopt.service.ts +5 -0
  362. package/server/services/workshop/optimization/profile.repo.ts +6 -4
  363. package/.output/public/_nuxt/B3Y5bCrM.js +0 -1
  364. package/.output/public/_nuxt/B8N8nsad2.js +0 -2
  365. package/.output/public/_nuxt/BO0BJx3w2.js +0 -8
  366. package/.output/public/_nuxt/BWn-lfCp2.js +0 -1
  367. package/.output/public/_nuxt/Bcs9zzO62.js +0 -1
  368. package/.output/public/_nuxt/BwO2Y5FH2.js +0 -1
  369. package/.output/public/_nuxt/Byf4IxU2.js +0 -14
  370. package/.output/public/_nuxt/C-LU6xv_.js +0 -1
  371. package/.output/public/_nuxt/CJ0bjZ6v2.js +0 -1
  372. package/.output/public/_nuxt/CJ3Vul2u.js +0 -1
  373. package/.output/public/_nuxt/CNwx04ln.js +0 -84
  374. package/.output/public/_nuxt/CVCscYzb2.js +0 -1
  375. package/.output/public/_nuxt/C_A0MCol2.js +0 -1
  376. package/.output/public/_nuxt/CnP6snIz.js +0 -3
  377. package/.output/public/_nuxt/D0mzKkZr.js +0 -1
  378. package/.output/public/_nuxt/D3buuIkE.js +0 -1
  379. package/.output/public/_nuxt/D4_INWgq.js +0 -1
  380. package/.output/public/_nuxt/D5kCimyw2.js +0 -1
  381. package/.output/public/_nuxt/DBtXLkyA.js +0 -1
  382. package/.output/public/_nuxt/DHURbGkn2.js +0 -1
  383. package/.output/public/_nuxt/DaBzS-iu.js +0 -1
  384. package/.output/public/_nuxt/DnlhV7Xe.js +0 -1
  385. package/.output/public/_nuxt/GtI6PUI32.js +0 -1
  386. package/.output/public/_nuxt/Nw_6OpQZ.js +0 -1
  387. package/.output/public/_nuxt/Y4sMSPrS2.js +0 -1
  388. package/.output/public/_nuxt/aml.CeLxRzvI.css +0 -1
  389. package/.output/public/_nuxt/builds/meta/7a79a7e4-d691-4cf5-ae3a-3b01814479fb.json +0 -1
  390. package/.output/public/_nuxt/goF_oZHF.js +0 -2
  391. package/.output/public/_nuxt/ontology.QMGeh66l.css +0 -1
  392. package/.output/public/_nuxt/optimizer.B8gCbU1b.css +0 -1
  393. package/.output/public/_nuxt/rJ7To74v2.js +0 -1
  394. package/.output/server/chunks/build/ontology-C3HS5pMo.mjs.map +0 -1
  395. package/.output/server/chunks/build/optimizer-BOtGWEtc.mjs +0 -200
  396. package/.output/server/chunks/build/optimizer-BOtGWEtc.mjs.map +0 -1
@@ -0,0 +1,1926 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Bounded integration evidence for the registered `omp` harness.
4
+ *
5
+ * The default mode uses a deterministic local RPC fixture. The opt-in
6
+ * PAPER_E2E_HARNESS_MODE=real-omp mode uses the locally authenticated OMP CLI
7
+ * and a fixed provider/model for three bounded trials in each simulator scene.
8
+ * Both modes use a fresh AW_HOME and local simulator/application services.
9
+ */
10
+ import { spawn, spawnSync } from 'node:child_process'
11
+ import { createHash, randomBytes } from 'node:crypto'
12
+ import { chmodSync, closeSync, copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, symlinkSync, writeFileSync } from 'node:fs'
13
+ import { createServer } from 'node:net'
14
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
15
+ import { fileURLToPath } from 'node:url'
16
+ import { setTimeout as delay } from 'node:timers/promises'
17
+ import { resolveRunMode } from '../shared/config/home.mjs'
18
+
19
+ const REPO = resolve(dirname(fileURLToPath(import.meta.url)), '..')
20
+ const AW_PORT = 3997
21
+ const SIM_PORT = 4020
22
+ const MQTT_PORT = 18840
23
+ const OFFLINE_TSDB_PORT = 45321
24
+ const OFFLINE_OBJECTSTORE_PORT = 45322
25
+ const OFFLINE_APP_MQTT_QUEUE_PORT = 45323
26
+ const FORBIDDEN_PORT = 4010
27
+ const APP_BASE = `http://127.0.0.1:${AW_PORT}`
28
+ const SIM_BASE = `http://127.0.0.1:${SIM_PORT}`
29
+ const FIXTURE = resolve(REPO, 'scripts', 'fixtures', 'omp-paper-harness.mjs')
30
+ const SIM_SOURCE = resolve(REPO, 'plc-node-simulator')
31
+ const VERSION = JSON.parse(readFileSync(join(REPO, 'package.json'), 'utf8')).version
32
+ const TAG = `rhe${Date.now().toString(36)}`
33
+ mkdirSync(join(REPO, '.omc'), { recursive: true })
34
+ const ROOT = mkdtempSync(join(REPO, '.omc', 'registered-harness-paper-'))
35
+ const HOME = join(ROOT, 'aw-home')
36
+ const EVIDENCE_PATH = join(ROOT, 'evidence.json')
37
+ const SIM_ROOT = join(ROOT, 'simulator')
38
+ const SIM_LOG = join(ROOT, 'simulator.log')
39
+ const APP_LOG = join(ROOT, 'agentworkshop.log')
40
+ const EMPTY_DOTENV = join(HOME, 'empty.env')
41
+ const ISOLATED_PROMPTS_DIR = join(HOME, 'prompts')
42
+ const NUXT_CLI = join(REPO, 'node_modules', 'nuxt', 'bin', 'nuxt.mjs')
43
+ const RAG_BRIDGE_DISABLED_BASE_URL = 'http://paper-harness-outbound-disabled.invalid'
44
+ const SIM_LOG_FD = openSync(SIM_LOG, 'a')
45
+ const APP_LOG_FD = openSync(APP_LOG, 'a')
46
+ const HARNESS_MODE = process.env.PAPER_E2E_HARNESS_MODE ?? 'fixture'
47
+ const REAL_OMP_PROVIDER = 'zhipu-coding-plan'
48
+ const REAL_OMP_MODEL = 'glm-5.3-flash'
49
+ const REAL_OMP_TRIALS_PER_SCENE = 3
50
+ const REAL_OMP_APPROVAL_TIMEOUT_MS = 180_000
51
+ const REAL_OMP_TASK_COMPLETION_TIMEOUT_MS = 180_000
52
+ const REAL_OMP_PROMPT_TIMEOUT_MS = 360_000
53
+
54
+ const evidence = {
55
+ schemaVersion: 1,
56
+ experiment: {
57
+ id: TAG,
58
+ projectVersion: VERSION,
59
+ ...(HARNESS_MODE === 'real-omp'
60
+ ? {
61
+ campaign: 'R20',
62
+ harnessMode: 'real-omp',
63
+ provider: REAL_OMP_PROVIDER,
64
+ model: REAL_OMP_MODEL,
65
+ trialsPerScene: REAL_OMP_TRIALS_PER_SCENE,
66
+ runOutcomes: [],
67
+ }
68
+ : {
69
+ fixture: 'deterministic local OMP-RPC transport; no LLM or autonomous harness decision',
70
+ }),
71
+ startedAt: new Date().toISOString(),
72
+ postTrialSnapshotDelaySeconds: 20,
73
+ scenes: [],
74
+ },
75
+ isolation: {
76
+ result: 'pending',
77
+ awHome: 'fresh isolated AW_HOME',
78
+ appBase: APP_BASE,
79
+ simulatorBase: SIM_BASE,
80
+ simulatorMqttLoopbackPort: MQTT_PORT,
81
+ appMqttQueueOfflineProbePort: OFFLINE_APP_MQTT_QUEUE_PORT,
82
+ explicitLoopbackOnly: HARNESS_MODE !== 'real-omp',
83
+ externalLlmDisabled: HARNESS_MODE !== 'real-omp',
84
+ ...(HARNESS_MODE === 'real-omp' ? { externalLlmAllowedOnlyForRegisteredOmpProcess: true } : {}),
85
+ forbiddenServicePortExcluded: true,
86
+ checks: [],
87
+ },
88
+ checks: [],
89
+ status: 'running',
90
+ }
91
+
92
+ let appProcess
93
+ let simProcess
94
+ let wrapperPath
95
+ let currentStage = 'preflight'
96
+ let currentScene
97
+ let authToken
98
+ let syntheticAdminId
99
+ let isolatedPluginNames = []
100
+ let expectedPluginNames = []
101
+ const allowedEnabledPluginNames = ['rag-bridge']
102
+ let projectPluginTreeAtPrepare
103
+ let projectPromptTreeAtPrepare
104
+ let promptTreeAtPrepare
105
+ const generatedSessionPassword = randomBytes(32).toString('hex')
106
+ const children = new Set()
107
+ const allocatedDevicePorts = []
108
+ const CHILD_OS_ENV_KEYS = process.platform === 'win32'
109
+ ? ['PATH', 'PATHEXT', 'SystemRoot', 'WINDIR', 'TEMP', 'TMP', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'HOMEDRIVE', 'HOMEPATH', 'ProgramData']
110
+ : ['PATH', 'HOME', 'TMPDIR', 'TMP', 'TEMP', 'LANG', 'LC_ALL']
111
+ const CHILD_EXTRA_ENV_KEYS = new Set(['SIM_PORT', 'MQTT_BROKER_PORT'])
112
+ const RELEASE_CHECK_SUFFIXES = ['-process-stopped', '-port-released']
113
+
114
+ function check(id, pass, detail = {}) {
115
+ evidence.checks.push({ id, status: pass ? 'pass' : 'fail', detail })
116
+ if (!pass) throw new Error(`check failed: ${id}`)
117
+ }
118
+
119
+ function noteIsolation(id, pass, detail = {}) {
120
+ evidence.isolation.checks.push({ id, status: pass ? 'pass' : 'fail', detail })
121
+ if (!pass) throw new Error(`isolation preflight failed: ${id}`)
122
+ }
123
+
124
+ function safeText(value, limit = 500) {
125
+ let text = String(value ?? '')
126
+ if (authToken) text = text.split(authToken).join('[REDACTED]')
127
+ text = text.replace(/\but-[a-f\d]{32}\b/gi, '[REDACTED_TOKEN]')
128
+ text = text.replace(/\bBearer\s+[^\s,;]+/gi, 'Bearer [REDACTED]')
129
+ text = text.replace(/\b(?:api[_-]?key|access[_-]?token|client[_-]?secret|password|secret)\s*[:=]\s*["']?[^\s,"'}]+/gi, '[REDACTED_CREDENTIAL]')
130
+ text = text.replace(/\bsk-[A-Za-z0-9_-]{16,}\b/g, '[REDACTED_CREDENTIAL]')
131
+ return text.slice(0, limit)
132
+ }
133
+
134
+ function compactError(error) {
135
+ const message = error instanceof Error ? error.message : String(error)
136
+ return { name: error instanceof Error ? error.name : 'Error', message: safeText(message) }
137
+ }
138
+
139
+ function assertLoopbackUrl(url, expectedPort) {
140
+ const parsed = new URL(url)
141
+ if (parsed.protocol !== 'http:' || parsed.hostname !== '127.0.0.1' || Number(parsed.port) !== expectedPort || Number(parsed.port) === FORBIDDEN_PORT) {
142
+ throw new Error('network boundary rejected a non-approved loopback URL')
143
+ }
144
+ }
145
+
146
+ function fixtureTracePath(sceneId) {
147
+ if (!['cast-film', 'annealing'].includes(sceneId)) throw new Error('fixture trace scene is not approved')
148
+ const root = resolve(ROOT)
149
+ const tracePath = resolve(root, `fixture-${sceneId}.json`)
150
+ const relativePath = relative(root, tracePath)
151
+ if (isAbsolute(relativePath) || relativePath === '..' || relativePath.startsWith(`..${sep}`)) {
152
+ throw new Error('fixture trace path escaped the experiment root')
153
+ }
154
+ return tracePath
155
+ }
156
+
157
+ async function assertFreeLoopback(port, label) {
158
+ if (!Number.isInteger(port) || port < 1024 || port > 65535 || port === FORBIDDEN_PORT) {
159
+ throw new Error(`port allocation rejected for ${label}`)
160
+ }
161
+ const server = createServer()
162
+ await new Promise((resolvePromise, reject) => {
163
+ server.once('error', reject)
164
+ server.listen(port, '127.0.0.1', resolvePromise)
165
+ })
166
+ await new Promise(resolvePromise => server.close(resolvePromise))
167
+ }
168
+
169
+ async function preflight() {
170
+ if (!['fixture', 'real-omp'].includes(HARNESS_MODE)) throw new Error('PAPER_E2E_HARNESS_MODE must be fixture or real-omp')
171
+ if (VERSION !== '0.8.0') throw new Error(`expected current package version 0.8.0; found ${safeText(VERSION, 80)}`)
172
+ if ((HARNESS_MODE === 'fixture' && !existsSync(FIXTURE)) || !existsSync(join(SIM_SOURCE, 'src', 'server', 'index.ts')) || !existsSync(join(SIM_SOURCE, 'node_modules')) || !existsSync(NUXT_CLI)) {
173
+ throw new Error('required local harness input or simulator runtime is missing')
174
+ }
175
+ if (existsSync(HOME)) throw new Error('fresh AW_HOME path unexpectedly exists')
176
+ const mode = resolveRunMode({ cwd: REPO, packageRoot: REPO, env: { AW_HOME: HOME, AW_MODE: 'home' } })
177
+ if (mode.mode !== 'home' || resolve(mode.home) !== resolve(HOME) || resolve(mode.dataDir) !== resolve(join(HOME, 'data'))) {
178
+ throw new Error('AW_HOME did not resolve to a new isolated home-mode data directory')
179
+ }
180
+ noteIsolation('fresh-home-mode-resolution', true, { mode: mode.mode, dataDir: mode.dataDir })
181
+ for (const [label, port] of [['app', AW_PORT], ['simulator-http', SIM_PORT], ['simulator-mqtt', MQTT_PORT], ['offline-app-mqtt-queue-probe', OFFLINE_APP_MQTT_QUEUE_PORT], ['offline-timescale-probe', OFFLINE_TSDB_PORT], ['offline-objectstore-probe', OFFLINE_OBJECTSTORE_PORT]]) {
182
+ await assertFreeLoopback(port, label)
183
+ noteIsolation(`${label}-free-loopback-port`, true, { port, host: '127.0.0.1' })
184
+ }
185
+ if (AW_PORT === FORBIDDEN_PORT || SIM_PORT === FORBIDDEN_PORT || MQTT_PORT === FORBIDDEN_PORT) {
186
+ throw new Error('forbidden service port appeared in explicit service configuration')
187
+ }
188
+ noteIsolation('project-version-and-local-inputs', true, {
189
+ version: VERSION,
190
+ simulatorSourcePresent: true,
191
+ fixturePresent: HARNESS_MODE === 'fixture' ? true : null,
192
+ nuxtCliPresent: true,
193
+ noUserOrBusinessArchiveInput: true,
194
+ })
195
+ noteIsolation('strict-child-environment-allowlist', true, HARNESS_MODE === 'fixture'
196
+ ? { osKeys: CHILD_OS_ENV_KEYS, fixtureOnlyHarness: true, noStorageServiceEnvironment: true }
197
+ : { osKeys: CHILD_OS_ENV_KEYS, harnessMode: HARNESS_MODE, credentialValuesExposedToRunnerOrEvidence: false, noStorageServiceEnvironment: true })
198
+ }
199
+
200
+ function cleanChildEnv(extra = {}) {
201
+ const env = {}
202
+ for (const key of CHILD_OS_ENV_KEYS) {
203
+ if (process.env[key] !== undefined) env[key] = process.env[key]
204
+ }
205
+ env.AW_HOME = HOME
206
+ env.AW_MODE = 'home'
207
+ env.AW_PROMPTS_DIR = ISOLATED_PROMPTS_DIR
208
+ env.NUXT_SESSION_PASSWORD = generatedSessionPassword
209
+ env.NO_PROXY = '127.0.0.1,localhost'
210
+ env.no_proxy = '127.0.0.1,localhost'
211
+ if (HARNESS_MODE === 'fixture') {
212
+ env.AW_PAPER_FIXTURE_NODE = process.execPath
213
+ env.AW_PAPER_FIXTURE_SCRIPT = FIXTURE
214
+ }
215
+ for (const [key, value] of Object.entries(extra)) {
216
+ if (!CHILD_EXTRA_ENV_KEYS.has(key)) throw new Error(`child environment rejected unsupported override ${key}`)
217
+ env[key] = String(value)
218
+ }
219
+ return env
220
+ }
221
+
222
+ function gitText(cwd, args) {
223
+ const result = spawnSync('git', args, {
224
+ cwd,
225
+ windowsHide: true,
226
+ encoding: 'utf8',
227
+ stdio: ['ignore', 'pipe', 'pipe'],
228
+ env: cleanChildEnv(),
229
+ })
230
+ if (result.error || result.status !== 0) {
231
+ throw new Error(`could not capture source identity: ${safeText(result.stderr || result.error?.message || result.status)}`)
232
+ }
233
+ return String(result.stdout ?? '').trim()
234
+ }
235
+
236
+ function hashGitFiles(cwd, roots) {
237
+ const names = gitText(cwd, ['ls-files', '-co', '--exclude-standard', '--', ...roots])
238
+ .split(/\r?\n/).filter(Boolean).sort()
239
+ if (names.length === 0) throw new Error(`source identity has no files under ${roots.join(', ')}`)
240
+ return hashFileList(cwd, names)
241
+ }
242
+
243
+ function hashFileList(cwd, names) {
244
+ const hash = createHash('sha256')
245
+ for (const name of names) {
246
+ hash.update(name.replaceAll('\\', '/') + '\0')
247
+ hash.update(readFileSync(join(cwd, name)))
248
+ hash.update('\0')
249
+ }
250
+ return { sha256: hash.digest('hex'), fileCount: names.length }
251
+ }
252
+
253
+ function hashDirectoryTree(root) {
254
+ if (!existsSync(root)) return hashFileList(root, [])
255
+ const names = []
256
+ const visit = (directory) => {
257
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
258
+ const absolute = join(directory, entry.name)
259
+ const name = relative(root, absolute).replaceAll('\\', '/')
260
+ if (entry.isSymbolicLink()) throw new Error(`source identity rejected symlink in plugin tree: ${name}`)
261
+ if (entry.isDirectory()) visit(absolute)
262
+ else if (entry.isFile()) names.push(name)
263
+ }
264
+ }
265
+ visit(root)
266
+ names.sort()
267
+ return hashFileList(root, names)
268
+ }
269
+
270
+ function pluginNamesUnder(root) {
271
+ if (!existsSync(root)) return []
272
+ return readdirSync(root, { withFileTypes: true })
273
+ .filter(entry => entry.isDirectory() && existsSync(join(root, entry.name, 'index.mjs')))
274
+ .map(entry => entry.name)
275
+ .sort()
276
+ }
277
+
278
+ function captureSourceIdentity() {
279
+ const appRoots = ['app', 'server', 'shared', 'mcp', 'cli', 'sdk', 'i18n', 'public', 'tsconfig.json', 'package.json', 'pnpm-lock.yaml', 'nuxt.config.ts', 'config.yml']
280
+ const simulatorRoots = ['src', 'package.json', 'package-lock.json']
281
+ const simulatorSourceFiles = gitText(SIM_SOURCE, ['ls-files', '-co', '--exclude-standard', '--', ...simulatorRoots])
282
+ .split(/\r?\n/).filter(Boolean).sort()
283
+ const executedSimulatorFiles = simulatorSourceFiles.filter(name => existsSync(join(SIM_ROOT, name)))
284
+ if (!executedSimulatorFiles.includes('src/server/index.ts') || !executedSimulatorFiles.includes('package.json')) {
285
+ throw new Error('executed simulator copy is missing required source files for provenance')
286
+ }
287
+ const projectPluginTree = hashDirectoryTree(join(REPO, '.AgentWorkShop', 'plugins'))
288
+ if (projectPluginTree.sha256 !== projectPluginTreeAtPrepare?.sha256) {
289
+ throw new Error('project plugin source changed after isolation was prepared')
290
+ }
291
+ const promptTree = hashDirectoryTree(ISOLATED_PROMPTS_DIR)
292
+ if (promptTree.sha256 !== promptTreeAtPrepare?.sha256) {
293
+ throw new Error('isolated prompt assets changed after isolation was prepared')
294
+ }
295
+ const ompVersion = HARNESS_MODE === 'real-omp'
296
+ ? spawnSync('omp', ['--version'], { cwd: HOME, windowsHide: true, encoding: 'utf8', timeout: 5_000, env: cleanChildEnv() })
297
+ : null
298
+ if (ompVersion && (ompVersion.error || ompVersion.status !== 0)) {
299
+ throw new Error('could not record the OMP CLI version for real-harness provenance')
300
+ }
301
+ return {
302
+ recordedAt: new Date().toISOString(),
303
+ nodeVersion: process.version,
304
+ platform: process.platform,
305
+ architecture: process.arch,
306
+ app: {
307
+ version: VERSION,
308
+ gitHead: gitText(REPO, ['rev-parse', 'HEAD']),
309
+ sourceTree: hashGitFiles(REPO, appRoots),
310
+ workingTreeStatus: gitText(REPO, ['status', '--porcelain', '--', ...appRoots]),
311
+ packageManifestSha256: createHash('sha256').update(readFileSync(join(REPO, 'package.json'))).digest('hex'),
312
+ lockfileSha256: createHash('sha256').update(readFileSync(join(REPO, 'pnpm-lock.yaml'))).digest('hex'),
313
+ projectPluginTree,
314
+ projectPluginNames: pluginNamesUnder(join(REPO, '.AgentWorkShop', 'plugins')),
315
+ },
316
+ pluginIsolation: {
317
+ disabledNames: isolatedPluginNames,
318
+ enabledAllowlist: allowedEnabledPluginNames,
319
+ setupExpectedForOtherPlugins: false,
320
+ disabledStatePath: 'AW_HOME/plugins-state.json',
321
+ projectPluginNames: pluginNamesUnder(join(REPO, '.AgentWorkShop', 'plugins')),
322
+ projectPluginTree,
323
+ },
324
+ promptIsolation: {
325
+ sourceDirectory: 'repository/.AgentWorkShop/prompts',
326
+ isolatedDirectory: 'AW_HOME/prompts',
327
+ sourceTree: projectPromptTreeAtPrepare,
328
+ runtimeTree: promptTree,
329
+ },
330
+ experimentScriptSha256: createHash('sha256').update(readFileSync(fileURLToPath(import.meta.url))).digest('hex'),
331
+ registeredHarness: {
332
+ mode: HARNESS_MODE,
333
+ provider: HARNESS_MODE === 'real-omp' ? REAL_OMP_PROVIDER : null,
334
+ model: HARNESS_MODE === 'real-omp' ? REAL_OMP_MODEL : null,
335
+ ompCliVersion: ompVersion ? safeText(ompVersion.stdout.trim(), 120) : null,
336
+ fixtureSha256: HARNESS_MODE === 'fixture' ? createHash('sha256').update(readFileSync(FIXTURE)).digest('hex') : null,
337
+ launcherSha256: wrapperPath ? createHash('sha256').update(readFileSync(wrapperPath)).digest('hex') : null,
338
+ },
339
+ simulator: {
340
+ gitlinkHead: gitText(REPO, ['rev-parse', 'HEAD:plc-node-simulator']),
341
+ gitHead: gitText(SIM_SOURCE, ['rev-parse', 'HEAD']),
342
+ sourceTree: hashGitFiles(SIM_SOURCE, simulatorRoots),
343
+ workingTreeStatus: gitText(SIM_SOURCE, ['status', '--porcelain', '--', ...simulatorRoots]),
344
+ executedTree: hashFileList(SIM_ROOT, executedSimulatorFiles),
345
+ lockfileSha256: createHash('sha256').update(readFileSync(join(SIM_SOURCE, 'package-lock.json'))).digest('hex'),
346
+ copyPatch: 'bind copied simulator HTTP and MQTT listeners to 127.0.0.1 and remap only their ports; source script hash records the transformation',
347
+ },
348
+ }
349
+ }
350
+
351
+ function prepareIsolatedHome() {
352
+ mkdirSync(join(HOME, 'data'), { recursive: true })
353
+ copyFileSync(join(REPO, 'config.yml'), join(HOME, 'config.yml'))
354
+ const overrides = {
355
+ 'daq.startInfrastructure': 'never',
356
+ 'daq.mqtt.host': '127.0.0.1',
357
+ 'daq.mqtt.port': OFFLINE_APP_MQTT_QUEUE_PORT,
358
+ 'daq.timescale.host': '127.0.0.1',
359
+ 'daq.timescale.port': OFFLINE_TSDB_PORT,
360
+ 'daq.objectstore.host': '127.0.0.1',
361
+ 'daq.objectstore.port': OFFLINE_OBJECTSTORE_PORT,
362
+ 'plugins.rag-bridge.base_url': RAG_BRIDGE_DISABLED_BASE_URL,
363
+ }
364
+ const runtimeSettingsPath = join(HOME, 'runtime-settings.json')
365
+ writeFileSync(runtimeSettingsPath, `${JSON.stringify({ version: 1, updatedAt: new Date().toISOString(), overrides }, null, 2)}\n`, 'utf8')
366
+ const savedOverrides = JSON.parse(readFileSync(runtimeSettingsPath, 'utf8')).overrides
367
+ if (savedOverrides?.['plugins.rag-bridge.base_url'] !== overrides['plugins.rag-bridge.base_url']) {
368
+ throw new Error('isolated runtime settings did not preserve the rag-bridge outbound-disable host guard setting')
369
+ }
370
+ const ragBridgeKvDir = join(HOME, 'data', 'plugins', 'rag-bridge')
371
+ mkdirSync(ragBridgeKvDir, { recursive: true })
372
+ const ragBridgeKvPath = join(ragBridgeKvDir, 'kv.json')
373
+ writeFileSync(ragBridgeKvPath, `${JSON.stringify({ 'kb.base_url': RAG_BRIDGE_DISABLED_BASE_URL }, null, 2)}\n`, 'utf8')
374
+ const savedRagBridgeKv = JSON.parse(readFileSync(ragBridgeKvPath, 'utf8'))
375
+ if (savedRagBridgeKv?.['kb.base_url'] !== RAG_BRIDGE_DISABLED_BASE_URL) {
376
+ throw new Error('isolated rag-bridge KV fallback did not preserve the outbound-disable host guard setting')
377
+ }
378
+ const projectPromptsRoot = join(REPO, '.AgentWorkShop', 'prompts')
379
+ if (!existsSync(projectPromptsRoot)) throw new Error('project prompt source directory is missing')
380
+ cpSync(projectPromptsRoot, ISOLATED_PROMPTS_DIR, { recursive: true })
381
+ projectPromptTreeAtPrepare = hashDirectoryTree(projectPromptsRoot)
382
+ promptTreeAtPrepare = hashDirectoryTree(ISOLATED_PROMPTS_DIR)
383
+ if (projectPromptTreeAtPrepare.sha256 !== promptTreeAtPrepare.sha256) {
384
+ throw new Error('isolated prompt copy differs from the repository prompt source')
385
+ }
386
+ writeFileSync(EMPTY_DOTENV, '', 'utf8')
387
+ const builtinPlugins = pluginNamesUnder(join(REPO, 'server', 'plugins-builtin'))
388
+ const projectPluginsRoot = join(REPO, '.AgentWorkShop', 'plugins')
389
+ const projectPlugins = pluginNamesUnder(projectPluginsRoot)
390
+ const userPlugins = pluginNamesUnder(join(HOME, 'plugins'))
391
+ expectedPluginNames = [...new Set([...builtinPlugins, ...projectPlugins, ...userPlugins])].sort()
392
+ isolatedPluginNames = expectedPluginNames.filter(name => !allowedEnabledPluginNames.includes(name))
393
+ projectPluginTreeAtPrepare = hashDirectoryTree(projectPluginsRoot)
394
+ const pluginStatePath = join(HOME, 'plugins-state.json')
395
+ writeFileSync(pluginStatePath, `${JSON.stringify({ version: 1, updatedAt: new Date().toISOString(), disabled: isolatedPluginNames }, null, 2)}\n`, 'utf8')
396
+ const savedPluginState = JSON.parse(readFileSync(pluginStatePath, 'utf8'))
397
+ if (JSON.stringify([...savedPluginState.disabled].sort()) !== JSON.stringify(isolatedPluginNames)) {
398
+ throw new Error('isolated plugin state did not disable every discovered plugin')
399
+ }
400
+ noteIsolation('isolated-runtime-config', true, {
401
+ configRoot: 'fresh isolated AW_HOME',
402
+ startInfrastructure: overrides['daq.startInfrastructure'],
403
+ simulatorMqttBroker: `127.0.0.1:${MQTT_PORT}`,
404
+ appMqttQueueProbe: `127.0.0.1:${OFFLINE_APP_MQTT_QUEUE_PORT}`,
405
+ offlineTimescaleProbe: `127.0.0.1:${OFFLINE_TSDB_PORT}`,
406
+ offlineObjectstoreProbe: `127.0.0.1:${OFFLINE_OBJECTSTORE_PORT}`,
407
+ ragBridgeOutboundGuardSetting: 'plugins.rag-bridge.base_url',
408
+ ragBridgeOutboundGuardConfigPresent: true,
409
+ ragBridgeOutboundGuardKvFallbackPresent: true,
410
+ emptyDotenv: true,
411
+ repoDotenvBypassed: true,
412
+ })
413
+ noteIsolation('pre-existing-plugin-scopes-disabled', true, {
414
+ builtinNames: builtinPlugins,
415
+ projectNames: projectPlugins,
416
+ userNames: userPlugins,
417
+ disabledStatePath: 'AW_HOME/plugins-state.json',
418
+ projectPluginTreeSha256: projectPluginTreeAtPrepare.sha256,
419
+ enabledPluginAllowlist: allowedEnabledPluginNames,
420
+ })
421
+ noteIsolation('project-prompt-assets-isolated', true, {
422
+ sourceDirectory: 'repository/.AgentWorkShop/prompts',
423
+ isolatedDirectory: 'AW_HOME/prompts',
424
+ sourceTreeSha256: projectPromptTreeAtPrepare.sha256,
425
+ runtimeTreeSha256: promptTreeAtPrepare.sha256,
426
+ awPromptsDir: 'AW_HOME/prompts',
427
+ })
428
+ }
429
+
430
+ async function assertPluginIsolation() {
431
+ const expectedNames = expectedPluginNames
432
+ let plugins = []
433
+ for (let attempt = 0; attempt < 40; attempt++) {
434
+ const result = requireSuccess(await app('GET', '/api/workshop/plugins'), 'isolated plugin manifest')
435
+ plugins = Array.isArray(result.plugins) ? result.plugins : []
436
+ const actualNames = plugins.map(plugin => plugin.name).sort()
437
+ if (JSON.stringify(actualNames) === JSON.stringify(expectedNames)) {
438
+ const enabledNames = plugins.filter(plugin => plugin.enabled === true).map(plugin => plugin.name).sort()
439
+ const enabledMatchesAllowlist = JSON.stringify(enabledNames) === JSON.stringify([...allowedEnabledPluginNames].sort())
440
+ const statesMatchPolicy = plugins.every(plugin => allowedEnabledPluginNames.includes(plugin.name)
441
+ ? plugin.enabled === true
442
+ : plugin.enabled === false)
443
+ check('only-outbound-disabled-rag-bridge-enabled', enabledMatchesAllowlist && statesMatchPolicy, {
444
+ names: actualNames,
445
+ enabledNames,
446
+ disabledNames: plugins.filter(plugin => plugin.enabled === false).map(plugin => plugin.name).sort(),
447
+ invalidStateNames: plugins.filter(plugin => typeof plugin.enabled !== 'boolean').map(plugin => plugin.name),
448
+ })
449
+ return
450
+ }
451
+ await delay(250)
452
+ }
453
+ throw new Error(`isolated plugin manifest differed from the expected built-in/user set: ${plugins.map(plugin => plugin.name).sort().join(', ')}`)
454
+ }
455
+
456
+ function spawnLogged(command, args, { cwd = REPO, env = cleanChildEnv(), logFd, label }) {
457
+ const child = spawn(command, args, {
458
+ cwd,
459
+ env,
460
+ stdio: ['ignore', logFd, logFd],
461
+ windowsHide: true,
462
+ detached: process.platform !== 'win32',
463
+ })
464
+ child.label = label
465
+ children.add(child)
466
+ child.once('exit', () => children.delete(child))
467
+ child.once('error', () => children.delete(child))
468
+ return child
469
+ }
470
+
471
+ async function waitForExit(child, timeoutMs = 8_000) {
472
+ if (!child || child.exitCode !== null || child.signalCode !== null) return
473
+ await Promise.race([
474
+ new Promise(resolvePromise => child.once('exit', resolvePromise)),
475
+ delay(timeoutMs),
476
+ ])
477
+ }
478
+
479
+ function processGroupExists(pid) {
480
+ try {
481
+ process.kill(-pid, 0)
482
+ return true
483
+ }
484
+ catch (error) {
485
+ if (error?.code === 'ESRCH') return false
486
+ if (error?.code === 'EPERM') return true
487
+ throw error
488
+ }
489
+ }
490
+
491
+ function windowsProcessExists(pid) {
492
+ const result = spawnSync('tasklist.exe', ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'], {
493
+ windowsHide: true,
494
+ encoding: 'utf8',
495
+ stdio: ['ignore', 'pipe', 'ignore'],
496
+ env: cleanChildEnv(),
497
+ })
498
+ if (result.error || result.status !== 0) return null
499
+ return (result.stdout ?? '').split(/\r?\n/).some((line) => {
500
+ const columns = line.match(/^"(?:[^"]|"")*","(\d+)"(?:,|$)/)
501
+ return columns?.[1] === String(pid)
502
+ })
503
+ }
504
+
505
+ async function stopProcessTree(child, label) {
506
+ if (!child?.pid) return false
507
+ const wasAlreadyExited = child.exitCode !== null || child.signalCode !== null
508
+ let terminationStatus = null
509
+ try {
510
+ if (process.platform === 'win32' && child.pid) {
511
+ const result = spawnSync('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore', env: cleanChildEnv() })
512
+ terminationStatus = result.error ? 'spawn-error' : result.status
513
+ }
514
+ else if (process.platform !== 'win32' && child.pid) {
515
+ process.kill(-child.pid, 'SIGTERM')
516
+ }
517
+ }
518
+ catch { /* a process may have already exited */ }
519
+ await waitForExit(child)
520
+ if (process.platform !== 'win32' && processGroupExists(child.pid)) {
521
+ try {
522
+ process.kill(-child.pid, 'SIGKILL')
523
+ terminationStatus = 'SIGKILL'
524
+ }
525
+ catch { /* already gone */ }
526
+ }
527
+ else if (process.platform === 'win32' && windowsProcessExists(child.pid) === true) {
528
+ const result = spawnSync('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore', env: cleanChildEnv() })
529
+ terminationStatus = result.error ? 'spawn-error' : result.status
530
+ }
531
+ await waitForExit(child, 2_000)
532
+ let treePresent
533
+ if (process.platform === 'win32') treePresent = windowsProcessExists(child.pid)
534
+ else {
535
+ const deadline = Date.now() + 3_000
536
+ do {
537
+ treePresent = processGroupExists(child.pid)
538
+ if (!treePresent) break
539
+ await delay(100)
540
+ } while (Date.now() < deadline)
541
+ }
542
+ const pass = !wasAlreadyExited && treePresent === false && (process.platform !== 'win32' || terminationStatus === 0)
543
+ evidence.checks.push({
544
+ id: `${label}-process-stopped`,
545
+ status: pass ? 'pass' : 'fail',
546
+ detail: { pid: child.pid, terminationStatus, processTreePresentAfterCleanup: treePresent, rootWasAlreadyExited: wasAlreadyExited },
547
+ })
548
+ return pass
549
+ }
550
+
551
+ function buildHarnessShim() {
552
+ if (process.platform === 'win32') {
553
+ const compiler = [
554
+ join(process.env.WINDIR || 'C:\\Windows', 'Microsoft.NET', 'Framework64', 'v4.0.30319', 'csc.exe'),
555
+ join(process.env.WINDIR || 'C:\\Windows', 'Microsoft.NET', 'Framework', 'v4.0.30319', 'csc.exe'),
556
+ ].find(existsSync)
557
+ if (!compiler) throw new Error('Windows C# compiler unavailable; cannot safely launch a registered fixture executable')
558
+ const source = join(ROOT, 'omp-fixture-shim.cs')
559
+ wrapperPath = join(ROOT, 'omp-fixture-shim.exe')
560
+ writeFileSync(source, String.raw`using System;
561
+ using System.Diagnostics;
562
+ using System.IO;
563
+ using System.Linq;
564
+ using System.Text;
565
+ using System.Threading;
566
+ class OmpFixtureShim {
567
+ static string Quote(string value) {
568
+ var result = new StringBuilder("\"");
569
+ int backslashes = 0;
570
+ foreach (char c in value) {
571
+ if (c == '\\') { backslashes++; continue; }
572
+ if (c == '"') {
573
+ result.Append('\\', backslashes * 2 + 1);
574
+ result.Append('"');
575
+ }
576
+ else {
577
+ result.Append('\\', backslashes);
578
+ result.Append(c);
579
+ }
580
+ backslashes = 0;
581
+ }
582
+ result.Append('\\', backslashes * 2);
583
+ result.Append('"');
584
+ return result.ToString();
585
+ }
586
+ static void Copy(Stream source, Stream destination) {
587
+ byte[] buffer = new byte[4096];
588
+ int count;
589
+ while ((count = source.Read(buffer, 0, buffer.Length)) > 0) {
590
+ destination.Write(buffer, 0, count);
591
+ destination.Flush();
592
+ }
593
+ }
594
+ static int Main(string[] args) {
595
+ string node = Environment.GetEnvironmentVariable("AW_PAPER_FIXTURE_NODE");
596
+ string script = Environment.GetEnvironmentVariable("AW_PAPER_FIXTURE_SCRIPT");
597
+ if (String.IsNullOrWhiteSpace(node) || String.IsNullOrWhiteSpace(script)) return 125;
598
+ var psi = new ProcessStartInfo(node);
599
+ psi.UseShellExecute = false;
600
+ psi.CreateNoWindow = true;
601
+ psi.RedirectStandardInput = true;
602
+ psi.RedirectStandardOutput = true;
603
+ psi.RedirectStandardError = true;
604
+ psi.Arguments = Quote(script) + " " + String.Join(" ", args.Skip(2).Select(Quote));
605
+ using (var child = Process.Start(psi)) {
606
+ if (child == null) return 126;
607
+ var stdin = new Thread(() => {
608
+ try {
609
+ Copy(Console.OpenStandardInput(), child.StandardInput.BaseStream);
610
+ }
611
+ finally {
612
+ child.StandardInput.Close();
613
+ }
614
+ });
615
+ var stdout = new Thread(() => Copy(child.StandardOutput.BaseStream, Console.OpenStandardOutput()));
616
+ var stderr = new Thread(() => Copy(child.StandardError.BaseStream, Console.OpenStandardError()));
617
+ stdin.IsBackground = true;
618
+ stdout.IsBackground = true;
619
+ stderr.IsBackground = true;
620
+ stdin.Start();
621
+ stdout.Start();
622
+ stderr.Start();
623
+ child.WaitForExit();
624
+ stdout.Join();
625
+ stderr.Join();
626
+ return child.ExitCode;
627
+ }
628
+ }
629
+ }`.replace(/\n/g, '\n'), 'utf8')
630
+ const result = spawnSync(compiler, ['/nologo', '/target:exe', `/out:${wrapperPath}`, source], { cwd: ROOT, windowsHide: true, encoding: 'utf8', timeout: 30_000, env: cleanChildEnv() })
631
+ if (result.error || result.status !== 0 || !existsSync(wrapperPath)) {
632
+ throw new Error(`could not compile isolated OMP fixture shim: ${safeText(result.stderr || result.stdout || result.error?.message || result.status)}`)
633
+ }
634
+ return wrapperPath
635
+ }
636
+ if (process.platform === 'linux' || process.platform === 'darwin') {
637
+ wrapperPath = join(ROOT, 'omp-fixture-shim')
638
+ writeFileSync(wrapperPath, '#!/bin/sh\nshift 2\nexec "$AW_PAPER_FIXTURE_NODE" "$AW_PAPER_FIXTURE_SCRIPT" "$@"\n', 'utf8')
639
+ chmodSync(wrapperPath, 0o755)
640
+ return wrapperPath
641
+ }
642
+ throw new Error(`unsupported fixture shim platform ${process.platform}`)
643
+ }
644
+
645
+ function extractPayload(body) {
646
+ return body && typeof body === 'object' && Object.prototype.hasOwnProperty.call(body, 'data') ? body.data : body
647
+ }
648
+
649
+ async function request(base, expectedPort, method, path, body, { token, timeoutMs = 10_000 } = {}) {
650
+ assertLoopbackUrl(base, expectedPort)
651
+ if (!path.startsWith('/api/')) throw new Error('API path boundary rejected')
652
+ const response = await fetch(`${base}${path}`, {
653
+ method,
654
+ headers: {
655
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
656
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
657
+ },
658
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
659
+ signal: AbortSignal.timeout(timeoutMs),
660
+ })
661
+ const parsed = await response.json().catch(() => null)
662
+ return { status: response.status, body: parsed, data: extractPayload(parsed) }
663
+ }
664
+
665
+ const app = (method, path, body, opts = {}) => request(APP_BASE, AW_PORT, method, path, body, { token: opts.token ?? authToken, timeoutMs: opts.timeoutMs })
666
+ const sim = (method, path, body) => request(SIM_BASE, SIM_PORT, method, path, body, { timeoutMs: 8_000 })
667
+
668
+ function requireSuccess(result, label, status = 200) {
669
+ if (result.status !== status) {
670
+ const payload = result.body && typeof result.body === 'object' ? result.body : {}
671
+ throw new Error(`${label} returned HTTP ${result.status}: ${safeText(payload.message || payload.statusMessage || payload.code || 'no response detail')}`)
672
+ }
673
+ return result.data
674
+ }
675
+
676
+ async function bootSimulator() {
677
+ mkdirSync(SIM_ROOT, { recursive: true })
678
+ cpSync(join(SIM_SOURCE, 'src'), join(SIM_ROOT, 'src'), { recursive: true })
679
+ cpSync(join(SIM_SOURCE, 'package.json'), join(SIM_ROOT, 'package.json'))
680
+ const simulatorEntry = join(SIM_ROOT, 'src', 'server', 'index.ts')
681
+ const originalSource = readFileSync(simulatorEntry, 'utf8')
682
+ const listenCall = 'server.listen(PORT, () => resolve())'
683
+ const brokerCall = 'await startBroker(Number(process.env.MQTT_BROKER_PORT ?? 18830))'
684
+ if (originalSource.split(listenCall).length !== 2) throw new Error('simulator copied source did not contain exactly one expected listener call')
685
+ if (originalSource.split(brokerCall).length !== 2) throw new Error('simulator copied source did not contain exactly one expected broker startup call')
686
+ const loopbackListenCall = `server.listen(PORT, '127.0.0.1', () => {
687
+ const boundAddress = server.address()
688
+ if (!boundAddress || typeof boundAddress === 'string' || boundAddress.address !== '127.0.0.1' || boundAddress.port !== PORT) {
689
+ console.error('[paper-isolation] simulator listener address verification failed')
690
+ server.close(() => process.exit(70))
691
+ return
692
+ }
693
+ console.log('[paper-isolation] listener=' + boundAddress.address + ':' + boundAddress.port)
694
+ resolve()
695
+ })`
696
+ const loopbackSource = originalSource
697
+ .replace(listenCall, loopbackListenCall)
698
+ .replace(brokerCall, `await startBroker(Number(process.env.MQTT_BROKER_PORT ?? 18830), '127.0.0.1')`)
699
+ writeFileSync(simulatorEntry, loopbackSource, 'utf8')
700
+ const modules = join(SIM_SOURCE, 'node_modules')
701
+ symlinkSync(modules, join(SIM_ROOT, 'node_modules'), process.platform === 'win32' ? 'junction' : 'dir')
702
+ simProcess = spawnLogged(process.execPath, [join(REPO, 'node_modules', 'tsx', 'dist', 'cli.mjs'), join(SIM_ROOT, 'src', 'server', 'index.ts')], {
703
+ cwd: SIM_ROOT,
704
+ logFd: SIM_LOG_FD,
705
+ label: 'simulator',
706
+ env: cleanChildEnv({ SIM_PORT: String(SIM_PORT), MQTT_BROKER_PORT: String(MQTT_PORT) }),
707
+ })
708
+ for (let i = 0; i < 50; i++) {
709
+ if (simProcess.exitCode !== null) throw new Error(`simulator exited during startup (code ${simProcess.exitCode})`)
710
+ try {
711
+ const result = await sim('GET', '/api/nodes')
712
+ if (result.status === 200) {
713
+ const data = result.data
714
+ const expectedListener = `[paper-isolation] listener=127.0.0.1:${SIM_PORT}`
715
+ const simulatorLog = readFileSync(SIM_LOG, 'utf8')
716
+ const expectedBroker = `[mqtt-broker] 内置 broker 就绪 mqtt://127.0.0.1:${MQTT_PORT}`
717
+ if (!simulatorLog.includes(expectedListener)) throw new Error('simulator did not report the verified 127.0.0.1 HTTP listener address')
718
+ if (!simulatorLog.includes(expectedBroker) || simulatorLog.includes('内置 broker 启动失败')) {
719
+ throw new Error('simulator did not confirm its embedded loopback MQTT broker before application startup')
720
+ }
721
+ noteIsolation('simulator-listener-address-verified', true, { address: '127.0.0.1', port: SIM_PORT, copiedSourceOnly: true })
722
+ noteIsolation('simulator-mqtt-broker-loopback-ready', true, { address: '127.0.0.1', port: MQTT_PORT, brokerStartupConfirmed: true })
723
+ noteIsolation('simulator-local-http-ready', true, { version: 'local repository source', port: SIM_PORT, host: '127.0.0.1' })
724
+ return data
725
+ }
726
+ }
727
+ catch { /* the local simulator is still starting */ }
728
+ await delay(400)
729
+ }
730
+ throw new Error('isolated simulator startup timed out')
731
+ }
732
+
733
+ function normalizeLocalNetworkConfig(value, portMap, key = '') {
734
+ if (Array.isArray(value)) return value.map(item => normalizeLocalNetworkConfig(item, portMap, key))
735
+ if (!value || typeof value !== 'object') {
736
+ if (typeof value !== 'string') return value
737
+ if (/^[a-z][a-z\d+.-]*:\/\//i.test(value)) {
738
+ const parsed = new URL(value)
739
+ if (!['127.0.0.1', 'localhost', '::1'].includes(parsed.hostname)) throw new Error('simulator preset contains a non-loopback endpoint')
740
+ if (parsed.port && portMap.has(Number(parsed.port))) parsed.port = String(portMap.get(Number(parsed.port)))
741
+ parsed.hostname = '127.0.0.1'
742
+ return parsed.toString()
743
+ }
744
+ if (/(?:host|hostname|ip|address)$/i.test(key)) return '127.0.0.1'
745
+ return value
746
+ }
747
+ const out = {}
748
+ for (const [childKey, childValue] of Object.entries(value)) {
749
+ if (/^port$/i.test(childKey) && typeof childValue === 'number' && portMap.has(childValue)) {
750
+ out[childKey] = portMap.get(childValue)
751
+ }
752
+ else if (/(?:host|hostname|ip|address)$/i.test(childKey) && typeof childValue === 'string') {
753
+ out[childKey] = '127.0.0.1'
754
+ }
755
+ else {
756
+ out[childKey] = normalizeLocalNetworkConfig(childValue, portMap, childKey)
757
+ }
758
+ }
759
+ return out
760
+ }
761
+
762
+ async function simulatorScene(scene) {
763
+ const presetResponse = await sim('GET', `/api/presets/${encodeURIComponent(scene.preset)}`)
764
+ const blueprint = requireSuccess(presetResponse, `${scene.id} simulator preset`)
765
+ if (!blueprint?.plantModel || !Array.isArray(blueprint.nodes)) throw new Error(`${scene.id} simulator preset shape is invalid`)
766
+
767
+ const portMapByDeviceId = new Map()
768
+ const toCreate = []
769
+ let nextPort = 44_000 + evidence.experiment.scenes.length * 100
770
+ for (const raw of blueprint.nodes) {
771
+ const node = structuredClone(raw)
772
+ if ((node.protocol && /serial|rtu/i.test(String(node.protocol))) || /serialPort|comPort|devicePath/i.test(JSON.stringify(node.config ?? {}))) continue
773
+ node.config ||= {}
774
+ const oldPort = Number(node.config.port)
775
+ const portMap = new Map()
776
+ if (Number.isInteger(oldPort) && oldPort > 0) {
777
+ while (allocatedDevicePorts.includes(nextPort) || nextPort === FORBIDDEN_PORT) nextPort += 1
778
+ await assertFreeLoopback(nextPort, `${scene.id}-simulator-device`)
779
+ portMap.set(oldPort, nextPort)
780
+ allocatedDevicePorts.push(nextPort)
781
+ noteIsolation(`${scene.id}-device-port-free-loopback`, true, { port: nextPort, host: '127.0.0.1', protocol: node.protocol ?? 'unspecified' })
782
+ node.config.port = nextPort
783
+ nextPort += 1
784
+ }
785
+ node.config = normalizeLocalNetworkConfig(node.config, portMap)
786
+ if (node.protocol === 'mqtt' || /mqtt/i.test(String(node.protocol))) node.config.brokerUrl = `mqtt://127.0.0.1:${MQTT_PORT}`
787
+ portMapByDeviceId.set(node.id, portMap)
788
+ toCreate.push(node)
789
+ }
790
+ if (toCreate.length === 0) throw new Error(`${scene.id} simulator preset has no loopback-safe device nodes`)
791
+
792
+ for (const node of toCreate) {
793
+ const created = await sim('POST', '/api/nodes', node)
794
+ requireSuccess(created, `${scene.id} simulator device ${safeText(node.id, 80)}`)
795
+ }
796
+ const plant = { ...blueprint.plantModel, id: `${TAG}-${scene.id}`, seed: 42, timeScale: 1, truthExport: false }
797
+ const loaded = await sim('PUT', '/api/plant/config', { plantModel: plant, warm: true, upsert: true })
798
+ requireSuccess(loaded, `${scene.id} simulator plant model`)
799
+
800
+ const exports = []
801
+ for (const node of toCreate) {
802
+ const result = await sim('GET', `/api/nodes/${encodeURIComponent(node.id)}/export`)
803
+ const data = requireSuccess(result, `${scene.id} simulator export ${safeText(node.id, 80)}`)
804
+ for (const item of data?.items ?? []) exports.push({ ...item, deviceId: node.id })
805
+ }
806
+ for (const item of exports) {
807
+ item.driverConfig = normalizeLocalNetworkConfig(item.driverConfig ?? {}, portMapByDeviceId.get(item.deviceId) ?? new Map())
808
+ for (const [key, value] of Object.entries(item.driverConfig)) {
809
+ if (/^(?:host|hostname|ip|address)$/i.test(key) && !['127.0.0.1', 'localhost', '::1'].includes(String(value))) {
810
+ throw new Error(`${scene.id} exported driver config escaped loopback boundary`)
811
+ }
812
+ }
813
+ }
814
+ const mv = exports.find(item => item.deviceId === scene.sourceDevice && item.signal === scene.mvSignal)
815
+ const cv = exports.find(item => item.signal === scene.cvSignal)
816
+ if (!mv || !cv) throw new Error(`${scene.id} simulator export lacks required MV/CV signals`)
817
+ if (!['opcua', 'modbus-tcp'].includes(String(mv.driver))) throw new Error(`${scene.id} MV driver is outside the approved simulator protocol set`)
818
+ const evidenceSignal = signal => Object.fromEntries(Object.entries(signal).filter(([key]) => key !== 'curl'))
819
+ return {
820
+ mv: evidenceSignal(mv),
821
+ cv: evidenceSignal(cv),
822
+ plant: { id: plant.id, kind: plant.kind ?? 'simulator', seed: 42, timeScale: 1 },
823
+ deviceCount: toCreate.length,
824
+ }
825
+ }
826
+
827
+ async function registerAdmin() {
828
+ const response = await app('POST', '/api/users/register', {
829
+ name: `Paper Test ${TAG}`,
830
+ email: `${TAG}@example.invalid`,
831
+ password: `Paper-${Date.now()}-safe9`,
832
+ }, { token: undefined })
833
+ const data = requireSuccess(response, 'isolated synthetic administrator registration')
834
+ if (!data?.token || data?.user?.role !== 'admin') throw new Error('fresh-home registration did not return its first administrator token')
835
+ authToken = String(data.token)
836
+ syntheticAdminId = String(data.user.id)
837
+ return { id: syntheticAdminId, role: 'admin' }
838
+ }
839
+
840
+ async function verifyRagBridgeOutboundDisabled() {
841
+ const ragBridgeHealth = requireSuccess(await app('GET', '/api/plugins/rag-bridge/health'), 'rag-bridge outbound guard health check')
842
+ const deadline = Date.now() + 3_000
843
+ let startupLogConfirmed = false
844
+ while (Date.now() < deadline) {
845
+ startupLogConfirmed = /\[rag-bridge\].*出站调用已禁用:/.test(readFileSync(APP_LOG, 'utf8'))
846
+ if (startupLogConfirmed) break
847
+ await delay(100)
848
+ }
849
+ noteIsolation('rag-bridge-outbound-disabled', ragBridgeHealth?.outbound === false && startupLogConfirmed, {
850
+ setting: 'plugins.rag-bridge.base_url',
851
+ pluginHealthOutbound: ragBridgeHealth?.outbound ?? null,
852
+ startupLogConfirmed,
853
+ })
854
+ }
855
+
856
+ function realOmpSystemPrompt(scene, recipe, control, decisionStimulus) {
857
+ const choices = decisionStimulus.allowedValues.join(', ')
858
+ return [
859
+ 'You are operating AgentWorkShop for one bounded task in a local process simulator.',
860
+ `Process scene: ${scene.processDescription}.`,
861
+ `Before task submission, the registered drivers measured the control at ${decisionStimulus.controlValue} ${control.unit} and the process variable at ${decisionStimulus.processValue} ${decisionStimulus.processUnit}.`,
862
+ `The task target band is ${decisionStimulus.targetMin} to ${decisionStimulus.targetMax} ${decisionStimulus.processUnit}.`,
863
+ `For this single trial, the only prevalidated candidate values are ${choices} ${control.unit}; the current control value is ${decisionStimulus.controlValue} ${control.unit}, and each candidate respects the configured engineering range and step bound.`,
864
+ 'Choose one candidate from that set using the measured target error and make one conservative, bounded recipe trial if a change is warranted. The candidate choice is yours; do not claim that it will improve or settle the process.',
865
+ `Use exactly one host-tool call named recipe_trial, with recipe_id "${recipe.id}", one params entry for node_id "${control.id}", and your selected candidate value. Put only a concise selection rationale in hypothesis.`,
866
+ 'Do not call any other tool. Do not retry. Do not create, update, apply, or roll back a recipe. If you cannot justify a permitted candidate, stop without a tool call.',
867
+ 'After the tool result, give a brief factual report and make no further tool calls.',
868
+ ].join('\n')
869
+ }
870
+
871
+ async function setupScene(scene, simDetails) {
872
+ currentScene = scene.id
873
+ currentStage = `${scene.id}:application-setup`
874
+ const sceneEvidence = {
875
+ id: scene.id,
876
+ simulatorPreset: scene.preset,
877
+ simulator: simDetails,
878
+ status: 'running',
879
+ approvals: [],
880
+ runs: [],
881
+ }
882
+ evidence.experiment.scenes.push(sceneEvidence)
883
+
884
+ const line = requireSuccess(await app('POST', '/api/workshop/dcw/lines', {
885
+ name: `${TAG}-${scene.id}`,
886
+ description: 'Synthetic isolated paper integration run',
887
+ simulated: true,
888
+ simSceneId: scene.preset,
889
+ controlMode: 'manual',
890
+ }), `${scene.id} line creation`).line
891
+ const product = requireSuccess(await app('POST', '/api/workshop/dcw/products', {
892
+ name: `${TAG}-${scene.id}-product`, lineId: line.id,
893
+ }), `${scene.id} product creation`).product
894
+ const template = requireSuccess(await app('POST', '/api/workshop/dcw/templates', {
895
+ name: `${TAG}-${scene.id}-control-template`,
896
+ unit: simDetails.mv.unit,
897
+ min: simDetails.mv.min,
898
+ max: simDetails.mv.max,
899
+ decimals: simDetails.mv.decimals ?? 0,
900
+ }), `${scene.id} control template creation`).template
901
+ const control = requireSuccess(await app('POST', '/api/workshop/dcw', {
902
+ templateRef: template.key,
903
+ name: `${TAG}-${scene.id}-control`,
904
+ driver: simDetails.mv.driver,
905
+ driverConfig: simDetails.mv.driverConfig,
906
+ lineId: line.id,
907
+ min: simDetails.mv.min,
908
+ max: simDetails.mv.max,
909
+ unit: simDetails.mv.unit,
910
+ decimals: simDetails.mv.decimals ?? 0,
911
+ stepLimit: 30,
912
+ writeLockSeconds: 0,
913
+ holdIntervalMs: 0,
914
+ readIntervalMs: 500,
915
+ semantics: `Bounded simulated ${scene.mvSignal} setpoint for integration evidence`,
916
+ }), `${scene.id} control node creation`).node
917
+ const daq = requireSuccess(await app('POST', '/api/workshop/daq', {
918
+ templateRef: 'daq-temp-tc',
919
+ name: `${TAG}-${scene.id}-daq-cv`,
920
+ driver: simDetails.cv.driver,
921
+ driverConfig: simDetails.cv.driverConfig,
922
+ lineId: line.id,
923
+ min: simDetails.cv.min,
924
+ max: simDetails.cv.max,
925
+ unit: simDetails.cv.unit,
926
+ intervalMs: 1000,
927
+ publishIntervalMs: 0,
928
+ semantics: `Bounded simulated ${scene.cvSignal} controlled variable for run-tagged sampling`,
929
+ }), `${scene.id} DAQ node creation`).node
930
+ const recipe = requireSuccess(await app('POST', '/api/workshop/dcw/recipes', {
931
+ name: `${TAG}-${scene.id}-recipe`,
932
+ productId: product.id,
933
+ params: [{ nodeId: control.id, templateRef: template.key, value: scene.baseline, min: simDetails.mv.min, max: simDetails.mv.max, stepLimit: 30 }],
934
+ daqWindows: [{ nodeId: daq.id, min: simDetails.cv.min, max: simDetails.cv.max }],
935
+ }), `${scene.id} recipe creation`).recipe
936
+
937
+ const start = requireSuccess(await app('POST', `/api/workshop/dcw/lines/${encodeURIComponent(line.id)}/start`, { recipeId: recipe.id }), `${scene.id} line start`)
938
+ const runId = String(start.run?.id ?? '')
939
+ if (!runId) throw new Error(`${scene.id} line start returned no run identifier`)
940
+ sceneEvidence.activeRun = { id: runId, status: start.run?.status ?? null, startedAt: start.run?.startedAt ?? null, recipeId: start.run?.recipeId ?? recipe.id }
941
+
942
+ let decisionStimulus
943
+ if (HARNESS_MODE === 'real-omp') {
944
+ let controlRead
945
+ let controlReadAttempts = 0
946
+ do {
947
+ controlRead = await app('POST', `/api/workshop/dcw/${encodeURIComponent(control.id)}/read`)
948
+ controlReadAttempts += 1
949
+ if (controlRead.status === 409 && controlReadAttempts < 3) await delay(500)
950
+ } while (controlRead.status === 409 && controlReadAttempts < 3)
951
+ const controlReadData = requireSuccess(controlRead, `${scene.id} pre-task control read`)
952
+ const controlData = controlReadData?.outcome ?? controlReadData?.read ?? controlReadData
953
+ const controlValue = Number(controlData?.value ?? controlData?.data?.value)
954
+ let processProbeResponse
955
+ let processProbeAttempts = 0
956
+ do {
957
+ processProbeResponse = await app('POST', `/api/workshop/daq/${encodeURIComponent(daq.id)}/test`)
958
+ processProbeAttempts += 1
959
+ if (processProbeResponse.status === 409 && processProbeAttempts < 3) await delay(500)
960
+ } while (processProbeResponse.status === 409 && processProbeAttempts < 3)
961
+ const processProbe = requireSuccess(processProbeResponse, `${scene.id} pre-task process probe`).test
962
+ const processValue = Number(processProbe?.sampleValue)
963
+ if (!Number.isFinite(controlValue) || processProbe?.ok !== true || !Number.isFinite(processValue)) {
964
+ throw new Error(`${scene.id} pre-task protocol reads did not provide finite control and process values`)
965
+ }
966
+ decisionStimulus = {
967
+ controlValue,
968
+ processValue,
969
+ processUnit: simDetails.cv.unit,
970
+ targetMin: scene.targetMin,
971
+ targetMax: scene.targetMax,
972
+ allowedValues: [...scene.candidates],
973
+ probeDriver: simDetails.cv.driver,
974
+ probeLatencyMs: Number.isFinite(Number(processProbe.latencyMs)) ? Number(processProbe.latencyMs) : null,
975
+ controlReadAttempts,
976
+ processProbeAttempts,
977
+ measuredAt: new Date().toISOString(),
978
+ }
979
+ sceneEvidence.decisionStimulus = decisionStimulus
980
+ sceneEvidence.simulator.candidateChoices = [...scene.candidates]
981
+ }
982
+
983
+ const channel = requireSuccess(await app('POST', '/api/workshop/channels', {
984
+ name: `${TAG}-${scene.id}-harness-channel`,
985
+ description: HARNESS_MODE === 'real-omp' ? 'Bounded real OMP simulator integration trial channel' : 'One-turn deterministic OMP transport fixture channel',
986
+ }), `${scene.id} channel creation`)
987
+ const agentConfig = HARNESS_MODE === 'real-omp'
988
+ ? {
989
+ command: 'omp',
990
+ cwd: HOME,
991
+ args: ['--no-extensions', '--no-skills', '--no-rules', '--no-lsp', '--no-pty', '--no-tools'],
992
+ provider: REAL_OMP_PROVIDER,
993
+ model: REAL_OMP_MODEL,
994
+ rpcMode: 'rpc',
995
+ promptTimeoutMs: REAL_OMP_PROMPT_TIMEOUT_MS,
996
+ systemPromptPrefix: realOmpSystemPrompt(scene, recipe, control, decisionStimulus),
997
+ }
998
+ : {
999
+ command: wrapperPath,
1000
+ args: [
1001
+ '--scene', scene.id,
1002
+ '--recipe-id', recipe.id,
1003
+ '--node-id', control.id,
1004
+ '--value', String(scene.candidate),
1005
+ '--trace-root', ROOT,
1006
+ '--trace-path', fixtureTracePath(scene.id),
1007
+ ],
1008
+ rpcMode: 'rpc',
1009
+ }
1010
+ const agent = requireSuccess(await app('POST', `/api/workshop/channels/${encodeURIComponent(channel.channelId)}/agents`, {
1011
+ name: `${TAG}-${scene.id}-${HARNESS_MODE === 'real-omp' ? 'omp-real' : 'omp-fixture'}`,
1012
+ harness: 'omp',
1013
+ role: 'lead',
1014
+ config: agentConfig,
1015
+ }), `${scene.id} registered OMP lead creation`)
1016
+
1017
+ const recipeBinding = requireSuccess(await app('POST', '/api/workshop/agent-tools/bindings', {
1018
+ agentId: agent.id, nodeId: recipe.id, kind: 'recipe',
1019
+ }), `${scene.id} recipe binding`).binding
1020
+ const daqBinding = requireSuccess(await app('POST', '/api/workshop/agent-tools/bindings', {
1021
+ agentId: agent.id, nodeId: daq.id, kind: 'daq', mode: 'auto',
1022
+ }), `${scene.id} DAQ binding`).binding
1023
+ check(`${scene.id}-registered-omp`, agent.harness === 'omp' && Boolean(agent.id), { harness: agent.harness, agentId: agent.id })
1024
+ check(`${scene.id}-manual-recipe-binding`, recipeBinding.kind === 'recipe' && recipeBinding.mode === 'manual', { kind: recipeBinding.kind, mode: recipeBinding.mode })
1025
+ check(`${scene.id}-daq-observation-binding`, daqBinding.kind === 'daq', { kind: daqBinding.kind })
1026
+
1027
+ sceneEvidence.entities = { lineId: line.id, productId: product.id, recipeId: recipe.id, controlNodeId: control.id, daqNodeId: daq.id, channelId: channel.channelId, agentId: agent.id }
1028
+ sceneEvidence.bindings = { recipe: { kind: recipeBinding.kind, mode: recipeBinding.mode }, daq: { kind: daqBinding.kind, mode: daqBinding.mode } }
1029
+ sceneEvidence.routePolicy = { tool: 'recipe_trial', emergency: false, cadenceBypass: false, recipeBindingMode: recipeBinding.mode }
1030
+ sceneEvidence.status = 'setup-complete'
1031
+ return { line, product, template, control, daq, recipe, channel, agent, runId, evidence: sceneEvidence }
1032
+ }
1033
+
1034
+ async function submitFixtureTask(context) {
1035
+ currentStage = `${context.evidence.id}:submit-lead-task`
1036
+ const sent = requireSuccess(await app('POST', `/api/workshop/channels/${encodeURIComponent(context.channel.channelId)}/tasks`, {
1037
+ title: `Isolated ${context.evidence.id} recipe_trial verification`,
1038
+ description: `Execute the preconfigured isolated ${context.evidence.id} recipe_trial candidate once and return the tool outcome.`,
1039
+ fromLabel: 'Synthetic isolated test driver',
1040
+ }), `${context.evidence.id} lead task submission`)
1041
+ context.evidence.taskId = sent.id ?? sent.task?.id ?? null
1042
+ }
1043
+
1044
+ async function submitRealOmpTask(context) {
1045
+ currentStage = `${context.evidence.id}:submit-real-omp-task`
1046
+ const sent = requireSuccess(await app('POST', `/api/workshop/channels/${encodeURIComponent(context.channel.channelId)}/tasks`, {
1047
+ title: `R20 ${context.evidence.id} recipe_trial with explicit task closure`,
1048
+ description: [
1049
+ 'Use the measured process context in your registered system prompt to choose one candidate from its prevalidated set.',
1050
+ `Call recipe_trial exactly once with recipe_id ${context.recipe.id} and one params entry for node_id ${context.control.id} using your selected value.`,
1051
+ 'After receiving the recipe_trial result, call complete_task exactly once on the active root task shown in the supervision context. Include the selected value and returned command-verification outcome in a concise summary and deliverable.',
1052
+ 'Do not make any other tool calls. Do not retry, save, update, apply, or roll back a recipe. If no candidate is justified, abstain and explicitly close the task with that limitation.',
1053
+ ].join(' '),
1054
+ fromLabel: 'Synthetic isolated R20 test driver',
1055
+ }), `${context.evidence.id} real OMP lead task submission`)
1056
+ context.evidence.taskId = sent.id ?? sent.task?.id ?? null
1057
+ if (!context.evidence.taskId) throw new Error(`${context.evidence.id} real OMP task submission returned no task identifier`)
1058
+ }
1059
+
1060
+ function taskToolEvents(task) {
1061
+ const events = []
1062
+ for (const message of task?.history ?? []) {
1063
+ for (const part of message?.parts ?? []) {
1064
+ const text = typeof part?.text === 'string' ? part.text : ''
1065
+ const match = text.match(/^🔧\s+([a-z][a-z\d_]*)/i)
1066
+ if (!match) continue
1067
+ events.push({
1068
+ toolName: match[1],
1069
+ phase: /(?:✅\s*完成|❌\s*失败)/.test(text) ? 'result' : 'call',
1070
+ isError: /❌\s*失败/.test(text),
1071
+ messageId: message.messageId ?? null,
1072
+ text,
1073
+ })
1074
+ }
1075
+ }
1076
+ return events
1077
+ }
1078
+
1079
+ async function readRealOmpTask(context) {
1080
+ const result = await app('GET', `/api/workshop/tasks/${encodeURIComponent(context.evidence.taskId)}?channelId=${encodeURIComponent(context.channel.channelId)}`)
1081
+ if (result.status !== 200) throw new Error(`${context.evidence.id} task detail returned HTTP ${result.status}`)
1082
+ return result.data
1083
+ }
1084
+
1085
+ async function waitForRealOmpTaskCompletion(context) {
1086
+ const deadline = Date.now() + REAL_OMP_TASK_COMPLETION_TIMEOUT_MS
1087
+ let latest
1088
+ while (Date.now() < deadline) {
1089
+ latest = await readRealOmpTask(context)
1090
+ if (latest.state === 'COMPLETED') return latest
1091
+ if (['FAILED', 'CANCELED'].includes(latest.state)) {
1092
+ throw new Error(`${context.evidence.id} task reached ${latest.state} before completing the approved operation`)
1093
+ }
1094
+ await delay(500)
1095
+ }
1096
+ throw new Error(`${context.evidence.id} task did not reach COMPLETED within the bounded post-approval window (state=${latest?.state ?? 'unknown'})`)
1097
+ }
1098
+
1099
+ function assertSingleRealOmpCall(context, task) {
1100
+ const events = taskToolEvents(task)
1101
+ const calls = events.filter(event => event.phase === 'call')
1102
+ const recipeCalls = calls.filter(event => event.toolName === 'recipe_trial')
1103
+ const recipeResults = events.filter(event => event.toolName === 'recipe_trial' && event.phase === 'result')
1104
+ const completionCalls = calls.filter(event => event.toolName === 'complete_task')
1105
+ // The active lead turn is journaled through both the task-event mapper and
1106
+ // the supervisor listener. A single host invocation can therefore appear
1107
+ // twice in history; identical start text identifies that mirror. Route
1108
+ // ledgers below remain authoritative for the number of executed trials.
1109
+ const uniqueRecipeCalls = [...new Set(recipeCalls.map(event => event.text))]
1110
+ if (events.some(event => !['recipe_trial', 'complete_task'].includes(event.toolName))
1111
+ || recipeCalls.length < 1 || recipeCalls.length > 2 || uniqueRecipeCalls.length !== 1
1112
+ || recipeResults.length < 1 || recipeResults.length > 2 || recipeResults.some(event => event.isError)
1113
+ || completionCalls.length !== 1) {
1114
+ throw new Error(`${context.evidence.id} OMP task history must show one recipe_trial invocation (allowing its mirrored journal entry), a successful result, and one explicit task-completion call`)
1115
+ }
1116
+ return { events, calls: [recipeCalls[0]], results: [recipeResults[0]], completionCalls }
1117
+ }
1118
+
1119
+ async function approveRealOmpTrial(context) {
1120
+ currentStage = `${context.evidence.id}:await-real-omp-hitl-approval`
1121
+ const deadline = Date.now() + REAL_OMP_APPROVAL_TIMEOUT_MS
1122
+ let pending
1123
+ let latestTask
1124
+ while (Date.now() < deadline) {
1125
+ latestTask = await readRealOmpTask(context)
1126
+ if (['FAILED', 'CANCELED', 'COMPLETED'].includes(latestTask.state)) {
1127
+ throw new Error(`${context.evidence.id} task reached ${latestTask.state} before synthetic approval`)
1128
+ }
1129
+ const result = await app('GET', `/api/workshop/agent-tools/approvals?agentId=${encodeURIComponent(context.agent.id)}&scope=pending`)
1130
+ if (result.status === 200) {
1131
+ const matches = (result.data?.approvals ?? []).filter(item => item.agentId === context.agent.id && item.nodeId === `recipe:${context.recipe.id}` && item.status === 'pending')
1132
+ if (matches.length > 1) throw new Error(`${context.evidence.id} has multiple pending real OMP trial approvals`)
1133
+ if (matches.length === 1) {
1134
+ const payload = matches[0].payload
1135
+ const params = Array.isArray(payload?.params) ? payload.params : []
1136
+ const proposedValue = Number(params[0]?.to)
1137
+ const decisionStimulus = context.evidence.decisionStimulus
1138
+ const allowedValues = decisionStimulus?.allowedValues ?? []
1139
+ const isExpectedTrial = payload?.kind === 'recipe-gate'
1140
+ && payload?.op === 'trial'
1141
+ && payload?.recipeId === context.recipe.id
1142
+ && payload?.emergency !== true
1143
+ && payload?.emergency !== 'true'
1144
+ && params.length === 1
1145
+ && params[0]?.nodeId === context.control.id
1146
+ && Number.isFinite(proposedValue)
1147
+ && allowedValues.includes(proposedValue)
1148
+ && proposedValue >= Number(context.evidence.simulator.mv.min)
1149
+ && proposedValue <= Number(context.evidence.simulator.mv.max)
1150
+ && Math.abs(proposedValue - Number(decisionStimulus.controlValue)) <= 30
1151
+ if (!isExpectedTrial) throw new Error(`${context.evidence.id} refused a pending approval outside the registered recipe_trial candidate set`)
1152
+ context.evidence.simulator.candidate = proposedValue
1153
+ context.evidence.modelDecision = {
1154
+ source: 'registered OMP host-tool proposal, checked against current protocol reads and prevalidated set',
1155
+ controlValue: decisionStimulus.controlValue,
1156
+ processValue: decisionStimulus.processValue,
1157
+ targetBand: [decisionStimulus.targetMin, decisionStimulus.targetMax],
1158
+ allowedValues,
1159
+ selectedValue: proposedValue,
1160
+ selectionRationale: safeText(payload?.hypothesis ?? payload?.rationale ?? '', 400),
1161
+ selectedValueWithinRangeAndStep: true,
1162
+ }
1163
+ pending = matches[0]
1164
+ break
1165
+ }
1166
+ }
1167
+ await delay(500)
1168
+ }
1169
+ if (!pending) throw new Error(`${context.evidence.id} real OMP recipe_trial approval did not appear within the bounded window`)
1170
+ context.evidence.approvals.push({ id: pending.id, statusBeforeDecision: pending.status, nodeId: pending.nodeId, title: pending.title ?? null, candidateValue: context.evidence.simulator.candidate, decision: 'approve' })
1171
+ requireSuccess(await app('POST', `/api/workshop/agent-tools/approvals/${encodeURIComponent(pending.id)}/decide`, {
1172
+ approved: true,
1173
+ comment: 'Approved for the bounded R20 local simulator integration check.',
1174
+ }), `${context.evidence.id} synthetic real OMP HITL approval`)
1175
+ const history = await app('GET', `/api/workshop/agent-tools/approvals?agentId=${encodeURIComponent(context.agent.id)}&scope=history`)
1176
+ const finalApproval = (history.data?.approvals ?? []).find(item => item.id === pending.id)
1177
+ if (history.status !== 200 || finalApproval?.status !== 'approved' || finalApproval?.decidedBy !== syntheticAdminId) {
1178
+ throw new Error(`${context.evidence.id} real OMP HITL history did not confirm the synthetic administrator decision`)
1179
+ }
1180
+ context.evidence.approvals[0] = {
1181
+ ...context.evidence.approvals[0],
1182
+ statusAfterDecision: finalApproval.status,
1183
+ decisionActor: 'synthetic isolated administrator via protected approval API',
1184
+ commentRecorded: finalApproval.comment === 'Approved for the bounded R20 local simulator integration check.',
1185
+ }
1186
+ }
1187
+
1188
+ async function captureRealOmpUsage(context) {
1189
+ const unavailable = {
1190
+ source: 'not exposed by the channel queue endpoint',
1191
+ context: null,
1192
+ requestInputTokens: null,
1193
+ requestOutputTokens: null,
1194
+ costUsd: null,
1195
+ costAvailable: false,
1196
+ }
1197
+ if (!context?.channel?.channelId || !context?.agent?.id) return unavailable
1198
+ try {
1199
+ const queueResult = await app('GET', `/api/workshop/channels/${encodeURIComponent(context.channel.channelId)}/queue`)
1200
+ if (queueResult.status !== 200) return unavailable
1201
+ const queue = extractPayload(queueResult.body)
1202
+ const agentStatus = (Array.isArray(queue) ? queue : []).find(item => item.agentId === context.agent.id)
1203
+ const raw = agentStatus?.context
1204
+ if (!raw) return unavailable
1205
+ return {
1206
+ source: 'channel queue OMP context snapshot (not request-level billing)',
1207
+ context: {
1208
+ usedTokens: Number.isFinite(Number(raw.usedTokens)) ? Number(raw.usedTokens) : null,
1209
+ contextWindow: Number.isFinite(Number(raw.contextWindow)) ? Number(raw.contextWindow) : null,
1210
+ percent: Number.isFinite(Number(raw.percent)) ? Number(raw.percent) : null,
1211
+ compacting: raw.compacting === true,
1212
+ },
1213
+ requestInputTokens: null,
1214
+ requestOutputTokens: null,
1215
+ costUsd: null,
1216
+ costAvailable: false,
1217
+ }
1218
+ }
1219
+ catch { return unavailable }
1220
+ }
1221
+
1222
+ async function approvePendingTrial(context) {
1223
+ currentStage = `${context.evidence.id}:manual-hitl-approval`
1224
+ const deadline = Date.now() + 20_000
1225
+ let pending
1226
+ while (Date.now() < deadline) {
1227
+ const result = await app('GET', `/api/workshop/agent-tools/approvals?agentId=${encodeURIComponent(context.agent.id)}&scope=pending`)
1228
+ if (result.status === 200) {
1229
+ const matches = (result.data?.approvals ?? []).filter(item => item.agentId === context.agent.id && item.nodeId === `recipe:${context.recipe.id}` && item.status === 'pending')
1230
+ if (matches.length > 1) throw new Error(`${context.evidence.id} has multiple pending trial approvals`)
1231
+ if (matches.length === 1) {
1232
+ pending = matches[0]
1233
+ break
1234
+ }
1235
+ }
1236
+ await delay(400)
1237
+ }
1238
+ if (!pending) throw new Error(`${context.evidence.id} manual recipe_trial HITL approval did not appear within the bounded window`)
1239
+ context.evidence.approvals.push({ id: pending.id, statusBeforeDecision: pending.status, nodeId: pending.nodeId, title: pending.title ?? null, decision: 'approve' })
1240
+ const decided = await app('POST', `/api/workshop/agent-tools/approvals/${encodeURIComponent(pending.id)}/decide`, {
1241
+ approved: true,
1242
+ comment: 'Approved for the isolated deterministic simulator integration check.',
1243
+ })
1244
+ requireSuccess(decided, `${context.evidence.id} explicit HITL approval`)
1245
+ const history = await app('GET', `/api/workshop/agent-tools/approvals?agentId=${encodeURIComponent(context.agent.id)}&scope=history`)
1246
+ const finalApproval = (history.data?.approvals ?? []).find(item => item.id === pending.id)
1247
+ if (history.status !== 200 || finalApproval?.status !== 'approved' || finalApproval?.decidedBy !== syntheticAdminId) {
1248
+ throw new Error(`${context.evidence.id} HITL approval history failed to confirm the explicit administrator decision`)
1249
+ }
1250
+ context.evidence.approvals[0] = {
1251
+ ...context.evidence.approvals[0],
1252
+ statusAfterDecision: finalApproval.status,
1253
+ decisionActor: 'synthetic isolated administrator via protected approval API',
1254
+ commentRecorded: finalApproval.comment === 'Approved for the isolated deterministic simulator integration check.',
1255
+ }
1256
+ }
1257
+
1258
+ async function collectSceneEvidence(context) {
1259
+ currentStage = `${context.evidence.id}:collect-result-and-observations`
1260
+ let trace
1261
+ let toolName
1262
+ let toolText
1263
+ let toolIsError
1264
+ let realTask
1265
+ let realToolEvents
1266
+ if (HARNESS_MODE === 'real-omp') {
1267
+ // The supervisor journals compact host-tool start/result events on the
1268
+ // active root task. Approval and operation ledgers remain authoritative
1269
+ // for the proposal and its execution.
1270
+ realTask = await waitForRealOmpTaskCompletion(context)
1271
+ if (realTask.assigneeId !== context.agent.id) throw new Error(`${context.evidence.id} real OMP task was not executed by its registered lead agent`)
1272
+ realToolEvents = assertSingleRealOmpCall(context, realTask)
1273
+ const channelMessages = requireSuccess(await app('GET', `/api/workshop/channels/${encodeURIComponent(context.channel.channelId)}/messages?limit=500`), `${context.evidence.id} channel task evidence`)
1274
+ const taskMessages = (Array.isArray(channelMessages) ? channelMessages : []).filter(message => message.taskId === context.evidence.taskId)
1275
+ const usage = await captureRealOmpUsage(context)
1276
+ context.evidence.modelExecution = {
1277
+ provider: REAL_OMP_PROVIDER,
1278
+ model: REAL_OMP_MODEL,
1279
+ taskId: context.evidence.taskId,
1280
+ taskState: realTask.state,
1281
+ taskArtifactCount: Array.isArray(realTask.artifacts) ? realTask.artifacts.length : 0,
1282
+ evidenceSource: 'registered OMP task history, approval payload, task state, and route-specific recipe/ACK records',
1283
+ hostToolCallEvents: realToolEvents.calls.length + realToolEvents.completionCalls.length,
1284
+ hostToolResultEvents: realToolEvents.results.length,
1285
+ taskCompletionToolCallEvents: realToolEvents.completionCalls.length,
1286
+ taskToolEvents: realToolEvents.events.map(event => ({ toolName: event.toolName, phase: event.phase, isError: event.isError })),
1287
+ hostToolEventHistoryAvailable: realToolEvents.events.length > 0,
1288
+ approvedProposalValue: context.evidence.modelDecision?.selectedValue ?? null,
1289
+ approvedProposalCount: context.evidence.approvals.length,
1290
+ channelEvidence: {
1291
+ source: 'GET /api/workshop/channels/:id/messages',
1292
+ taskMessageCount: taskMessages.length,
1293
+ agentMessageCount: taskMessages.filter(message => message.fromAgentId === context.agent.id).length,
1294
+ roles: [...new Set(taskMessages.map(message => safeText(message.role, 40)))],
1295
+ },
1296
+ usage,
1297
+ }
1298
+ }
1299
+ else {
1300
+ const tracePath = fixtureTracePath(context.evidence.id)
1301
+ const deadline = Date.now() + 20_000
1302
+ while (Date.now() < deadline) {
1303
+ if (existsSync(tracePath)) {
1304
+ try {
1305
+ trace = JSON.parse(readFileSync(tracePath, 'utf8'))
1306
+ }
1307
+ catch { /* fixture is rewriting a small JSON trace */ }
1308
+ }
1309
+ if (trace?.hostToolResults?.length) break
1310
+ await delay(300)
1311
+ }
1312
+ if (!trace) throw new Error(`${context.evidence.id} deterministic fixture did not create its trace`)
1313
+ if (trace.hostToolCalls?.length !== 1 || trace.hostToolCalls[0]?.toolName !== 'recipe_trial' || trace.hostToolResults?.length !== 1) {
1314
+ throw new Error(`${context.evidence.id} fixture trace did not show exactly one recipe_trial host_tool_call/result`)
1315
+ }
1316
+ const toolResult = trace.hostToolResults[0].result
1317
+ toolText = String(toolResult?.content?.[0]?.text ?? '')
1318
+ toolName = trace.hostToolCalls[0].toolName
1319
+ toolIsError = Boolean(toolResult?.isError)
1320
+ if (toolIsError || !/全部设备证实|下发并全部设备证实/.test(toolText)) {
1321
+ throw new Error(`${context.evidence.id} recipe_trial did not return a fully verified device ACK`)
1322
+ }
1323
+ }
1324
+
1325
+ const readback = await app('POST', `/api/workshop/dcw/${encodeURIComponent(context.control.id)}/read`)
1326
+ requireSuccess(readback, `${context.evidence.id} DCW readback`)
1327
+
1328
+ const runData = await app('GET', `/api/workshop/dcw/runs/${encodeURIComponent(context.runId)}/data`)
1329
+ requireSuccess(runData, `${context.evidence.id} active run data`)
1330
+ const logs = await app('GET', `/api/workshop/ops-logs?scope=line&lineId=${encodeURIComponent(context.line.id)}&recipeId=${encodeURIComponent(context.recipe.id)}&limit=100`)
1331
+ requireSuccess(logs, `${context.evidence.id} recipe operation log`)
1332
+ const recipeRows = (logs.data?.logs ?? [])
1333
+ .filter(row => String(row.action).startsWith('recipe.'))
1334
+ .map((row) => {
1335
+ let detail = row.detail
1336
+ if (!detail || typeof detail !== 'object' || Array.isArray(detail)) {
1337
+ try {
1338
+ const parsed = JSON.parse(String(row.detailJson ?? '{}'))
1339
+ detail = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
1340
+ }
1341
+ catch { detail = {} }
1342
+ }
1343
+ return { ...row, detail }
1344
+ })
1345
+ const trialRows = recipeRows.filter(row => row.action === 'recipe.trial')
1346
+ const trialAckRows = recipeRows.filter(row => row.action === 'recipe.dispatch.ack' && row.detail?.trial === true)
1347
+ const trialRow = trialRows[0]
1348
+ const ackRow = trialAckRows[0]
1349
+ const trialRunId = String(ackRow?.detail?.runId ?? '')
1350
+ if (trialRows.length !== 1 || trialAckRows.length !== 1 || !trialRunId || String(trialRow?.detail?.runId ?? '') !== trialRunId) {
1351
+ throw new Error(`${context.evidence.id} recipe log did not contain exactly one matching recipe.trial and trial ACK pair`)
1352
+ }
1353
+ if (HARNESS_MODE === 'real-omp' && context.evidence.approvals.length !== 1) {
1354
+ throw new Error(`${context.evidence.id} expected exactly one approved real OMP proposal`)
1355
+ }
1356
+ const trialRunData = await app('GET', `/api/workshop/dcw/runs/${encodeURIComponent(trialRunId)}/data`)
1357
+ requireSuccess(trialRunData, `${context.evidence.id} trial run data`)
1358
+ const ack = ackRow.detail?.ackSummary ?? null
1359
+ if (!ack || ack.total !== 1 || ack.verified !== 1 || ack.failed !== 0 || ack.unverified !== 0) {
1360
+ throw new Error(`${context.evidence.id} logged trial ACK is not one-of-one verified`)
1361
+ }
1362
+ const returnedTrialRun = trialRunData.data?.run
1363
+ const trialResults = returnedTrialRun?.results
1364
+ if (returnedTrialRun?.id !== trialRunId || !Array.isArray(trialResults) || trialResults.length !== 1 || trialResults[0]?.verify?.verdict !== 'verified' || trialResults[0]?.ok !== true) {
1365
+ throw new Error(`${context.evidence.id} trial run data lacks an independently verified write result`)
1366
+ }
1367
+
1368
+ const snapshotDelayStartedAt = new Date().toISOString()
1369
+ await delay(20_000)
1370
+ const probeStartedAt = new Date().toISOString()
1371
+ const probeResponse = await app('POST', `/api/workshop/daq/${encodeURIComponent(context.daq.id)}/test`)
1372
+ const probe = requireSuccess(probeResponse, `${context.evidence.id} DAQ driver probe`).test
1373
+ const sampleValue = Number(probe?.sampleValue)
1374
+ if (probe?.ok !== true || !Number.isFinite(sampleValue)) {
1375
+ throw new Error(`${context.evidence.id} DAQ driver probe did not return a finite simulator value`)
1376
+ }
1377
+ const probeCompletedAt = new Date().toISOString()
1378
+ const ingestAt = probeCompletedAt
1379
+ const ingest = requireSuccess(await app('POST', `/api/workshop/daq/${encodeURIComponent(context.daq.id)}/ingest`, {
1380
+ at: ingestAt,
1381
+ value: sampleValue,
1382
+ state: 'ok',
1383
+ }), `${context.evidence.id} DAQ snapshot ingest`)
1384
+ if (ingest?.accepted !== true || ingest.nodeId !== context.daq.id || ingest.lineId !== context.line.id) {
1385
+ throw new Error(`${context.evidence.id} DAQ snapshot ingest was not accepted for the expected node and line`)
1386
+ }
1387
+
1388
+ const persistedAt = String(ingest.at ?? ingestAt)
1389
+ const persistedAtMs = Date.parse(persistedAt)
1390
+ if (!Number.isFinite(persistedAtMs)) throw new Error(`${context.evidence.id} DAQ snapshot ingest returned an invalid sample timestamp`)
1391
+ const fromMs = persistedAtMs
1392
+ const toMs = persistedAtMs + 1
1393
+ // Let the in-process queue and SQLite batch flush settle before a fixed-window query;
1394
+ // retries outlast the short query-cache TTL if the first lookup is still empty.
1395
+ await delay(800)
1396
+ const queryDeadline = Date.now() + 12_000
1397
+ let taggedQuery
1398
+ let taggedSeries
1399
+ let snapshotBucketAt
1400
+ while (Date.now() < queryDeadline) {
1401
+ const candidate = await app('GET', `/api/workshop/daq/query?line_id=${encodeURIComponent(context.line.id)}&node_ids=${encodeURIComponent(context.daq.id)}&run_id=${encodeURIComponent(context.runId)}&from=${fromMs}&to=${toMs}&bucket_ms=1000`)
1402
+ if (candidate.status === 200) {
1403
+ taggedQuery = candidate
1404
+ taggedSeries = candidate.data?.series?.find(series => series.nodeId === context.daq.id)
1405
+ const bucketMs = Number(candidate.data?.window?.bucketMs) || 1_000
1406
+ snapshotBucketAt = Math.floor(persistedAtMs / bucketMs) * bucketMs
1407
+ const matchingPoint = taggedSeries?.points?.find(point => Number(point.at) === snapshotBucketAt && Math.abs(Number(point.v) - sampleValue) <= 0.01)
1408
+ if (matchingPoint && candidate.data?.activeRun?.runId === context.runId) break
1409
+ }
1410
+ await delay(300)
1411
+ }
1412
+ if (!taggedQuery || !taggedSeries?.points?.length || taggedQuery.data?.activeRun?.runId !== context.runId) {
1413
+ throw new Error(`${context.evidence.id} platform DAQ query returned no snapshot tagged to the active run`)
1414
+ }
1415
+ const matchingProbePoint = taggedSeries.points.find(point => Number(point.at) === snapshotBucketAt && Math.abs(Number(point.v) - sampleValue) <= 0.01)
1416
+ if (!matchingProbePoint) {
1417
+ throw new Error(`${context.evidence.id} run-tagged DAQ data did not contain the driver-probe snapshot value`)
1418
+ }
1419
+
1420
+ if (HARNESS_MODE === 'real-omp') {
1421
+ const finalTask = await readRealOmpTask(context)
1422
+ context.evidence.hostToolExecution = {
1423
+ provenance: 'registered OMP model proposal → protected synthetic approval → one recipe.trial and one verified DCW receipt',
1424
+ hostToolEventHistoryAvailable: realToolEvents.events.length > 0,
1425
+ taskStateAfterObservation: finalTask.state,
1426
+ taskCompleted: finalTask.state === 'COMPLETED',
1427
+ approvedProposalCount: context.evidence.approvals.length,
1428
+ recipeTrialCount: trialRows.length,
1429
+ recipeTrialAckCount: trialAckRows.length,
1430
+ toolName: 'recipe_trial',
1431
+ resultReceived: ack?.verified === 1 && ack?.failed === 0,
1432
+ }
1433
+ context.evidence.modelExecution.taskStateAfterObservation = finalTask.state
1434
+ context.evidence.modelExecution.taskCompleted = finalTask.state === 'COMPLETED'
1435
+ }
1436
+ else {
1437
+ context.evidence.fixtureTrace = {
1438
+ fixture: trace.fixture,
1439
+ decisionSource: trace.decisionSource,
1440
+ hostToolCallCount: trace.hostToolCalls.length,
1441
+ toolName,
1442
+ resultReceived: trace.hostToolResults.length === 1,
1443
+ toolResultText: safeText(toolText, 1200),
1444
+ toolIsError,
1445
+ }
1446
+ }
1447
+ context.evidence.trial = {
1448
+ runId: trialRunId,
1449
+ toolName,
1450
+ approvalId: context.evidence.approvals[0].id,
1451
+ ackSummary: ack,
1452
+ resultCount: trialResults.length,
1453
+ resultRows: trialResults,
1454
+ }
1455
+ context.evidence.readback = {
1456
+ expectedCandidate: context.evidence.simulator.candidate,
1457
+ response: readback.data?.outcome ?? readback.data?.read ?? readback.data,
1458
+ resultMatchesCandidate: (() => {
1459
+ const details = readback.data?.outcome ?? readback.data?.read ?? readback.data ?? {}
1460
+ const observed = Number(details.value ?? details.data?.value ?? details.result?.value)
1461
+ return Number.isFinite(observed) && Math.abs(observed - context.evidence.simulator.candidate) <= 0.01
1462
+ })(),
1463
+ }
1464
+ context.evidence.daq = {
1465
+ nodeId: context.daq.id,
1466
+ method: 'single driver-probe/ingest snapshot',
1467
+ storageBackend: 'isolated AW_HOME SQLite time-series fallback',
1468
+ postTrialDelaySeconds: 20,
1469
+ snapshotDelayStartedAt,
1470
+ sampleCount: taggedSeries.points.length,
1471
+ runTags: [context.runId],
1472
+ expectedActiveRunId: context.runId,
1473
+ probe: {
1474
+ driver: context.daq.driver,
1475
+ startedAt: probeStartedAt,
1476
+ completedAt: probeCompletedAt,
1477
+ sampleValue,
1478
+ latencyMs: Number.isFinite(Number(probe.latencyMs)) ? Number(probe.latencyMs) : null,
1479
+ },
1480
+ ingest: {
1481
+ accepted: ingest.accepted,
1482
+ at: persistedAt,
1483
+ value: sampleValue,
1484
+ state: 'ok',
1485
+ },
1486
+ taggedQuery: {
1487
+ requestedRunId: context.runId,
1488
+ returnedRunId: taggedQuery.data?.activeRun?.runId ?? null,
1489
+ seriesPointCount: taggedSeries.points.length,
1490
+ probeValueMatched: true,
1491
+ snapshotBucketAt: new Date(snapshotBucketAt).toISOString(),
1492
+ matchingProbePoint,
1493
+ series: taggedSeries.points.slice(-5),
1494
+ },
1495
+ activeRunDataKeys: Object.keys(runData.data ?? {}),
1496
+ }
1497
+ context.evidence.recipeLog = {
1498
+ query: 'ops-logs filtered by lineId and recipeId (recipe_log-equivalent audit view)',
1499
+ rowCount: recipeRows.length,
1500
+ trialAction: trialRow.action,
1501
+ trialSummary: safeText(trialRow.summary, 600),
1502
+ ackAction: ackRow.action,
1503
+ ackSummary: safeText(ackRow.summary, 600),
1504
+ trialRunDataKeys: Object.keys(trialRunData.data ?? {}),
1505
+ }
1506
+ context.evidence.status = 'verified'
1507
+ }
1508
+
1509
+ async function runScene(scene) {
1510
+ const simDetails = await simulatorScene(scene)
1511
+ const context = await setupScene(scene, { ...simDetails, candidate: scene.candidate })
1512
+ context.evidence.simulator.candidate = scene.candidate
1513
+ context.evidence.simulator.baseline = scene.baseline
1514
+ await submitFixtureTask(context)
1515
+ await approvePendingTrial(context)
1516
+ await collectSceneEvidence(context)
1517
+ const stopped = await app('POST', `/api/workshop/dcw/lines/${encodeURIComponent(context.line.id)}/stop`)
1518
+ requireSuccess(stopped, `${scene.id} line stop`)
1519
+ context.evidence.activeRun.endedAt = stopped.data?.run?.endedAt ?? null
1520
+ check(`${scene.id}-host-dispatch-one-call`, context.evidence.fixtureTrace.hostToolCallCount === 1, { tool: context.evidence.fixtureTrace.toolName })
1521
+ check(`${scene.id}-ack-verified`, context.evidence.trial.ackSummary.verified === 1 && context.evidence.trial.ackSummary.failed === 0, context.evidence.trial.ackSummary)
1522
+ check(`${scene.id}-readback-matches`, context.evidence.readback.resultMatchesCandidate, context.evidence.readback)
1523
+ check(`${scene.id}-run-tagged-daq-probe-ingest-snapshot`, context.evidence.daq.taggedQuery.seriesPointCount >= 1 && context.evidence.daq.taggedQuery.probeValueMatched, {
1524
+ method: context.evidence.daq.method,
1525
+ value: context.evidence.daq.probe.sampleValue,
1526
+ runId: context.evidence.daq.expectedActiveRunId,
1527
+ matchingPoint: context.evidence.daq.taggedQuery.matchingProbePoint,
1528
+ })
1529
+ check(`${scene.id}-recipe-log`, context.evidence.recipeLog.rowCount >= 2, { trialAction: context.evidence.recipeLog.trialAction, ackAction: context.evidence.recipeLog.ackAction })
1530
+ }
1531
+
1532
+ async function recoverFailedRealOmpTrial(context, outcome) {
1533
+ const recovery = []
1534
+ if (context?.evidence?.taskId) {
1535
+ try {
1536
+ const task = await readRealOmpTask(context)
1537
+ if (!['COMPLETED', 'FAILED', 'CANCELED'].includes(task.state)) {
1538
+ const canceled = await app('POST', `/api/workshop/tasks/${encodeURIComponent(context.evidence.taskId)}/cancel`)
1539
+ recovery.push({ action: 'cancel-nonterminal-task', status: canceled.status === 200 ? 'completed' : `http-${canceled.status}` })
1540
+ }
1541
+ else recovery.push({ action: 'cancel-nonterminal-task', status: 'not-needed', taskState: task.state })
1542
+ }
1543
+ catch (error) { recovery.push({ action: 'cancel-nonterminal-task', status: 'failed', error: compactError(error) }) }
1544
+ }
1545
+ if (context?.channel?.channelId && context?.agent?.id) {
1546
+ try {
1547
+ const stopped = await app('POST', `/api/workshop/channels/${encodeURIComponent(context.channel.channelId)}/agents/${encodeURIComponent(context.agent.id)}/stop`)
1548
+ recovery.push({ action: 'stop-agent-runtime', status: stopped.status === 200 ? 'completed' : `http-${stopped.status}` })
1549
+ }
1550
+ catch (error) { recovery.push({ action: 'stop-agent-runtime', status: 'failed', error: compactError(error) }) }
1551
+ try {
1552
+ const pendingResult = await app('GET', `/api/workshop/agent-tools/approvals?agentId=${encodeURIComponent(context.agent.id)}&scope=pending`)
1553
+ const pending = pendingResult.status === 200
1554
+ ? (pendingResult.data?.approvals ?? []).filter(item => item.agentId === context.agent.id && item.status === 'pending')
1555
+ : []
1556
+ for (const approval of pending) {
1557
+ const denied = await app('POST', `/api/workshop/agent-tools/approvals/${encodeURIComponent(approval.id)}/decide`, {
1558
+ approved: false,
1559
+ comment: 'Denied during bounded R20 failure cleanup.',
1560
+ })
1561
+ recovery.push({ action: 'deny-pending-agent-approval', approvalId: approval.id, status: denied.status === 200 ? 'completed' : `http-${denied.status}` })
1562
+ }
1563
+ if (pendingResult.status !== 200) recovery.push({ action: 'deny-pending-agent-approval', status: `list-http-${pendingResult.status}` })
1564
+ else if (pending.length === 0) recovery.push({ action: 'deny-pending-agent-approval', status: 'not-needed' })
1565
+ }
1566
+ catch (error) { recovery.push({ action: 'deny-pending-agent-approval', status: 'failed', error: compactError(error) }) }
1567
+ }
1568
+ if (context?.line?.id) {
1569
+ try {
1570
+ const stopped = await app('POST', `/api/workshop/dcw/lines/${encodeURIComponent(context.line.id)}/stop`)
1571
+ recovery.push({ action: 'stop-line', status: stopped.status === 200 ? 'completed' : `http-${stopped.status}` })
1572
+ }
1573
+ catch (error) { recovery.push({ action: 'stop-line', status: 'failed', error: compactError(error) }) }
1574
+ }
1575
+ outcome.recovery = recovery
1576
+ }
1577
+
1578
+ async function runRealOmpScene(baseScene) {
1579
+ currentScene = baseScene.id
1580
+ let simDetails
1581
+ try {
1582
+ currentStage = `${baseScene.id}:simulator-setup-once`
1583
+ simDetails = await simulatorScene(baseScene)
1584
+ if (!Array.isArray(baseScene.candidates) || baseScene.candidates.length !== REAL_OMP_TRIALS_PER_SCENE
1585
+ || baseScene.candidates.some(candidate => !Number.isFinite(candidate)
1586
+ || candidate < Number(simDetails.mv.min)
1587
+ || candidate > Number(simDetails.mv.max)
1588
+ || Math.abs(candidate - baseScene.baseline) > 30)) {
1589
+ throw new Error(`${baseScene.id} real OMP candidates violate the configured count, process range, or 30-unit recipe step limit`)
1590
+ }
1591
+ }
1592
+ catch (error) {
1593
+ for (let repetition = 1; repetition <= REAL_OMP_TRIALS_PER_SCENE; repetition++) {
1594
+ const outcome = {
1595
+ id: `${baseScene.id}-r${repetition}`,
1596
+ scene: baseScene.id,
1597
+ repetition,
1598
+ provider: REAL_OMP_PROVIDER,
1599
+ model: REAL_OMP_MODEL,
1600
+ candidate: baseScene.candidates[repetition - 1],
1601
+ usage: { source: 'not available because simulator setup failed', context: null, requestInputTokens: null, requestOutputTokens: null, costUsd: null, costAvailable: false },
1602
+ costUsd: null,
1603
+ status: 'failed',
1604
+ failure: compactError(error),
1605
+ }
1606
+ evidence.experiment.runOutcomes.push(outcome)
1607
+ }
1608
+ return
1609
+ }
1610
+
1611
+ for (let repetition = 1; repetition <= REAL_OMP_TRIALS_PER_SCENE; repetition++) {
1612
+ const scene = { ...baseScene, id: `${baseScene.id}-r${repetition}` }
1613
+ const outcome = {
1614
+ id: scene.id,
1615
+ scene: baseScene.id,
1616
+ repetition,
1617
+ provider: REAL_OMP_PROVIDER,
1618
+ model: REAL_OMP_MODEL,
1619
+ candidate: null,
1620
+ candidateChoices: [...baseScene.candidates],
1621
+ usage: { source: 'not yet available', context: null, requestInputTokens: null, requestOutputTokens: null, costUsd: null, costAvailable: false },
1622
+ costUsd: null,
1623
+ status: 'running',
1624
+ startedAt: new Date().toISOString(),
1625
+ }
1626
+ evidence.experiment.runOutcomes.push(outcome)
1627
+ let context
1628
+ try {
1629
+ currentScene = scene.id
1630
+ const runSimDetails = { ...simDetails, candidateChoices: [...baseScene.candidates] }
1631
+ context = await setupScene(scene, runSimDetails)
1632
+ context.evidence.simulator.baseline = scene.baseline
1633
+ outcome.entities = context.evidence.entities
1634
+ outcome.runId = context.runId
1635
+ await submitRealOmpTask(context)
1636
+ outcome.taskId = context.evidence.taskId
1637
+ await approveRealOmpTrial(context)
1638
+ outcome.candidate = context.evidence.simulator.candidate
1639
+ outcome.modelDecision = context.evidence.modelDecision
1640
+ await collectSceneEvidence(context)
1641
+ const stopped = await app('POST', `/api/workshop/dcw/lines/${encodeURIComponent(context.line.id)}/stop`)
1642
+ requireSuccess(stopped, `${scene.id} line stop`)
1643
+ context.evidence.activeRun.endedAt = stopped.data?.run?.endedAt ?? null
1644
+ const finalTask = await readRealOmpTask(context)
1645
+ context.evidence.hostToolExecution.taskStateAfterObservation = finalTask.state
1646
+ context.evidence.hostToolExecution.taskCompleted = finalTask.state === 'COMPLETED'
1647
+ context.evidence.modelExecution.taskStateAfterObservation = finalTask.state
1648
+ context.evidence.modelExecution.taskCompleted = finalTask.state === 'COMPLETED'
1649
+ check(`${scene.id}-real-omp-approved-model-proposal`, context.evidence.modelExecution.approvedProposalCount === 1 && context.evidence.modelExecution.approvedProposalValue === context.evidence.simulator.candidate, {
1650
+ provider: REAL_OMP_PROVIDER,
1651
+ model: REAL_OMP_MODEL,
1652
+ selectedValue: context.evidence.modelExecution.approvedProposalValue,
1653
+ toolEventHistoryAvailable: context.evidence.modelExecution.hostToolEventHistoryAvailable,
1654
+ })
1655
+ check(`${scene.id}-real-omp-one-recipe-trial-ledger`, context.evidence.hostToolExecution.recipeTrialCount === 1 && context.evidence.hostToolExecution.recipeTrialAckCount === 1, {
1656
+ recipeTrialCount: context.evidence.hostToolExecution.recipeTrialCount,
1657
+ recipeTrialAckCount: context.evidence.hostToolExecution.recipeTrialAckCount,
1658
+ })
1659
+ check(`${scene.id}-ack-verified`, context.evidence.trial.ackSummary.verified === 1 && context.evidence.trial.ackSummary.failed === 0, context.evidence.trial.ackSummary)
1660
+ check(`${scene.id}-readback-matches`, context.evidence.readback.resultMatchesCandidate, context.evidence.readback)
1661
+ check(`${scene.id}-run-tagged-daq-probe-ingest-snapshot`, context.evidence.daq.taggedQuery.seriesPointCount >= 1 && context.evidence.daq.taggedQuery.probeValueMatched, {
1662
+ method: context.evidence.daq.method,
1663
+ value: context.evidence.daq.probe.sampleValue,
1664
+ runId: context.evidence.daq.expectedActiveRunId,
1665
+ matchingPoint: context.evidence.daq.taggedQuery.matchingProbePoint,
1666
+ })
1667
+ check(`${scene.id}-recipe-log`, context.evidence.recipeLog.rowCount >= 2, { trialAction: context.evidence.recipeLog.trialAction, ackAction: context.evidence.recipeLog.ackAction })
1668
+ check(`${scene.id}-real-omp-task-completed`, context.evidence.hostToolExecution.taskCompleted, {
1669
+ taskState: context.evidence.hostToolExecution.taskStateAfterObservation,
1670
+ })
1671
+ context.evidence.status = 'verified'
1672
+ outcome.status = context.evidence.hostToolExecution.taskCompleted ? 'verified' : 'verified-operation-task-incomplete'
1673
+ outcome.finishedAt = new Date().toISOString()
1674
+ outcome.trialRunId = context.evidence.trial.runId
1675
+ outcome.taskState = context.evidence.hostToolExecution.taskStateAfterObservation
1676
+ outcome.usage = context.evidence.modelExecution.usage
1677
+ outcome.costUsd = null
1678
+ outcome.evidenceSceneId = context.evidence.id
1679
+ }
1680
+ catch (error) {
1681
+ context && (context.evidence.status = 'failed')
1682
+ if (context) context.evidence.failure = compactError(error)
1683
+ outcome.status = 'failed'
1684
+ outcome.failure = compactError(error)
1685
+ outcome.finishedAt = new Date().toISOString()
1686
+ if (context) {
1687
+ outcome.usage = await captureRealOmpUsage(context)
1688
+ await recoverFailedRealOmpTrial(context, outcome)
1689
+ }
1690
+ }
1691
+ }
1692
+ }
1693
+
1694
+ async function startApplication() {
1695
+ currentStage = 'application-startup'
1696
+ await assertFreeLoopback(OFFLINE_APP_MQTT_QUEUE_PORT, 'offline-app-mqtt-queue-probe-before-startup')
1697
+ noteIsolation('offline-app-mqtt-queue-port-free-immediately-before-startup', true, {
1698
+ port: OFFLINE_APP_MQTT_QUEUE_PORT,
1699
+ host: '127.0.0.1',
1700
+ })
1701
+ appProcess = spawnLogged(process.execPath, [NUXT_CLI, 'dev', '--host', '127.0.0.1', '--port', String(AW_PORT), '--dotenv', EMPTY_DOTENV], {
1702
+ cwd: REPO,
1703
+ env: cleanChildEnv(),
1704
+ logFd: APP_LOG_FD,
1705
+ label: 'agentworkshop',
1706
+ })
1707
+ for (let i = 0; i < 90; i++) {
1708
+ if (appProcess.exitCode !== null) throw new Error(`AgentWorkShop startup exited (code ${appProcess.exitCode})`)
1709
+ try {
1710
+ const response = await app('GET', '/api/health', undefined, { token: undefined, timeoutMs: 2_000 })
1711
+ if (response.status === 200 && response.data?.status === 'ok' && response.data?.workshop === 'ready') {
1712
+ if (response.data?.version !== '0.8.0') throw new Error(`server reported unexpected version ${safeText(response.data?.version, 80)}`)
1713
+ noteIsolation('application-loopback-ready', true, { version: response.data.version, workshop: response.data.workshop, port: AW_PORT, host: '127.0.0.1' })
1714
+ return response.data
1715
+ }
1716
+ }
1717
+ catch (error) {
1718
+ if (error?.message?.startsWith('server reported unexpected version')) throw error
1719
+ }
1720
+ await delay(500)
1721
+ }
1722
+ throw new Error('isolated AgentWorkShop startup timed out or workshop manager did not become ready')
1723
+ }
1724
+
1725
+ async function main() {
1726
+ mkdirSync(join(REPO, '.omc'), { recursive: true })
1727
+ if (VERSION !== '0.8.0') throw new Error(`expected current package version 0.8.0; found ${VERSION}`)
1728
+ await preflight()
1729
+ prepareIsolatedHome()
1730
+ if (HARNESS_MODE === 'fixture') {
1731
+ currentStage = 'compile-local-omp-fixture-shim'
1732
+ wrapperPath = buildHarnessShim()
1733
+ noteIsolation('registered-omp-fixture-launcher-ready', true, { platform: process.platform, wrapper: 'local process shim; fixture is deterministic' })
1734
+ }
1735
+ else {
1736
+ noteIsolation('registered-omp-real-provider-model-declared', true, {
1737
+ command: 'omp from allowlisted PATH',
1738
+ provider: REAL_OMP_PROVIDER,
1739
+ model: REAL_OMP_MODEL,
1740
+ cwd: 'fresh isolated AW_HOME',
1741
+ authSource: 'local OMP auth store; value is not inspected or added to evidence',
1742
+ discoveryDisabled: ['extensions', 'skills', 'rules'],
1743
+ credentialValuesExposedToRunnerOrEvidence: false,
1744
+ })
1745
+ }
1746
+ currentStage = 'simulator-startup'
1747
+ await bootSimulator()
1748
+ const health = await startApplication()
1749
+ evidence.experiment.server = { version: health.version, mode: health.mode, workshop: health.workshop, uptimeMsAtReady: health.uptimeMs }
1750
+ evidence.experiment.sourceIdentity = captureSourceIdentity()
1751
+ const admin = await registerAdmin()
1752
+ evidence.experiment.syntheticAdmin = admin
1753
+ await assertPluginIsolation()
1754
+ await verifyRagBridgeOutboundDisabled()
1755
+ const daqStatus = requireSuccess(await app('GET', '/api/workshop/daq', undefined, { timeoutMs: 45_000 }), 'isolated DAQ backend status')
1756
+ const settings = requireSuccess(await app('GET', '/api/system/settings'), 'effective runtime settings snapshot')
1757
+ const effectiveMqttHost = settings.effective?.['daq.mqtt.host']
1758
+ const effectiveMqttPort = Number(settings.effective?.['daq.mqtt.port'])
1759
+ const effectiveMqttPortSource = settings.sources?.['daq.mqtt.port']
1760
+ const effectiveInfrastructurePolicy = settings.effective?.['daq.startInfrastructure']
1761
+ const effectiveInfrastructurePolicySource = settings.sources?.['daq.startInfrastructure']
1762
+ const runtimeTargetMatches = effectiveMqttHost === '127.0.0.1'
1763
+ && effectiveMqttPort === OFFLINE_APP_MQTT_QUEUE_PORT
1764
+ && effectiveMqttPortSource === 'runtime'
1765
+ && effectiveInfrastructurePolicy === 'never'
1766
+ && effectiveInfrastructurePolicySource === 'runtime'
1767
+ check('runtime-settings-target-offline-loopback-queue', runtimeTargetMatches, {
1768
+ mqttHost: effectiveMqttHost ?? null,
1769
+ mqttPort: effectiveMqttPort,
1770
+ mqttPortSource: effectiveMqttPortSource ?? null,
1771
+ infrastructurePolicy: effectiveInfrastructurePolicy ?? null,
1772
+ infrastructurePolicySource: effectiveInfrastructurePolicySource ?? null,
1773
+ })
1774
+ check('isolated-inproc-queue-and-sqlite-tsdb', runtimeTargetMatches && daqStatus.meta?.queue === 'inproc' && daqStatus.meta?.tsdb === 'sqlite-emulated', {
1775
+ queue: daqStatus.meta?.queue ?? null,
1776
+ tsdb: daqStatus.meta?.tsdb ?? null,
1777
+ effectiveMqttHost,
1778
+ effectiveMqttPort,
1779
+ effectiveMqttPortSource,
1780
+ })
1781
+ noteIsolation('application-message-path-is-inproc', runtimeTargetMatches && daqStatus.meta?.queue === 'inproc', {
1782
+ queue: daqStatus.meta?.queue ?? null,
1783
+ effectiveMqttHost,
1784
+ effectiveMqttPort,
1785
+ effectiveMqttPortSource: effectiveMqttPortSource ?? null,
1786
+ simulatorMqttBrokerRemainsLoopback: `127.0.0.1:${MQTT_PORT}`,
1787
+ })
1788
+ evidence.isolation.result = 'passed'
1789
+ noteIsolation('application-env-and-dotenv-isolation', true, {
1790
+ launch: 'direct Nuxt CLI; dev-guard .env preload bypassed',
1791
+ dotenvFile: EMPTY_DOTENV,
1792
+ childEnvironmentAllowlisted: true,
1793
+ storageEndpointsRestrictedToFreeLoopbackPorts: true,
1794
+ })
1795
+
1796
+ const scenes = [
1797
+ {
1798
+ id: 'cast-film', preset: 'cast-film-physics', sourceDevice: 'dev-extruder-opcua',
1799
+ mvSignal: 'ScrewSpeedSP', cvSignal: 'thick', baseline: 120, fixtureCandidate: 125,
1800
+ processDescription: 'cast-film extrusion; screw speed affects measured film thickness',
1801
+ targetMin: 48, targetMax: 52,
1802
+ candidates: [125, 130, 135],
1803
+ },
1804
+ {
1805
+ id: 'annealing', preset: 'anneal-line', sourceDevice: 'anneal-heating-mbtcp',
1806
+ mvSignal: '均热区3炉温SP', cvSignal: 'StripTemp', baseline: 730, fixtureCandidate: 735,
1807
+ processDescription: 'continuous annealing; zone-3 furnace setpoint affects measured strip temperature',
1808
+ targetMin: 700, targetMax: 760,
1809
+ candidates: [735, 740, 745],
1810
+ },
1811
+ ]
1812
+ if (HARNESS_MODE === 'real-omp') {
1813
+ check('real-omp-six-unique-trials-planned', scenes.length * REAL_OMP_TRIALS_PER_SCENE === 6 && new Set(scenes.flatMap(scene => Array.from({ length: REAL_OMP_TRIALS_PER_SCENE }, (_, index) => `${scene.id}-r${index + 1}`))).size === 6, {
1814
+ scenes: scenes.map(scene => scene.id),
1815
+ repetitionsPerScene: REAL_OMP_TRIALS_PER_SCENE,
1816
+ })
1817
+ for (const scene of scenes) await runRealOmpScene(scene)
1818
+ const failedRuns = evidence.experiment.runOutcomes.filter(outcome => outcome.status !== 'verified')
1819
+ evidence.status = failedRuns.length === 0 ? 'passed' : 'failed'
1820
+ if (failedRuns.length) {
1821
+ evidence.failure = {
1822
+ stage: 'real-omp-trial-set',
1823
+ name: 'RealOmpTrialSetError',
1824
+ message: `${failedRuns.length} of ${evidence.experiment.runOutcomes.length} bounded real OMP trials failed`,
1825
+ failedRunIds: failedRuns.map(outcome => outcome.id),
1826
+ }
1827
+ evidence.isolation.result = 'incomplete'
1828
+ }
1829
+ }
1830
+ else {
1831
+ for (const scene of scenes) await runScene({ ...scene, candidate: scene.fixtureCandidate })
1832
+ evidence.status = 'passed'
1833
+ }
1834
+ }
1835
+
1836
+ async function cleanup() {
1837
+ currentStage = 'cleanup'
1838
+ const processResults = []
1839
+ const processByChild = new Map()
1840
+ if (appProcess) processByChild.set(appProcess, 'agentworkshop')
1841
+ if (simProcess) processByChild.set(simProcess, 'simulator')
1842
+ for (const child of children) if (!processByChild.has(child)) processByChild.set(child, child.label ?? 'child')
1843
+ for (const [child, label] of [...processByChild.entries()].reverse()) {
1844
+ try {
1845
+ const stopped = await stopProcessTree(child, label)
1846
+ processResults.push(stopped)
1847
+ if (!evidence.checks.some(item => item.id === `${label}-process-stopped`)) {
1848
+ evidence.checks.push({ id: `${label}-process-stopped`, status: 'fail', detail: { pid: child.pid ?? null, reason: 'process pid unavailable for termination verification' } })
1849
+ }
1850
+ }
1851
+ catch (error) {
1852
+ evidence.checks.push({ id: `${label}-process-stopped`, status: 'fail', detail: { pid: child.pid ?? null, error: compactError(error) } })
1853
+ processResults.push(false)
1854
+ }
1855
+ }
1856
+ const portResults = []
1857
+ for (const [label, port] of [
1858
+ ['app', AW_PORT],
1859
+ ['simulator-http', SIM_PORT],
1860
+ ['simulator-mqtt', MQTT_PORT],
1861
+ ['offline-app-mqtt-queue-probe', OFFLINE_APP_MQTT_QUEUE_PORT],
1862
+ ['offline-timescale-probe', OFFLINE_TSDB_PORT],
1863
+ ['offline-objectstore-probe', OFFLINE_OBJECTSTORE_PORT],
1864
+ ...allocatedDevicePorts.map((port, index) => [`simulator-device-${index}`, port]),
1865
+ ]) {
1866
+ try {
1867
+ await assertFreeLoopback(port, label)
1868
+ evidence.checks.push({ id: `${label}-port-released`, status: 'pass', detail: { port, host: '127.0.0.1' } })
1869
+ portResults.push(true)
1870
+ }
1871
+ catch (error) {
1872
+ evidence.checks.push({ id: `${label}-port-released`, status: 'fail', detail: { port, host: '127.0.0.1', error: compactError(error) } })
1873
+ portResults.push(false)
1874
+ }
1875
+ }
1876
+ try {
1877
+ closeSync(SIM_LOG_FD)
1878
+ }
1879
+ catch { /* already closed */ }
1880
+ try {
1881
+ closeSync(APP_LOG_FD)
1882
+ }
1883
+ catch { /* already closed */ }
1884
+ const requiredProcessLabels = evidence.status === 'passed' ? ['agentworkshop', 'simulator'] : [...processByChild.values()]
1885
+ const verifiedProcessLabels = new Set(evidence.checks.filter(item => item.id.endsWith('-process-stopped') && item.status === 'pass').map(item => item.id.replace(/-process-stopped$/, '')))
1886
+ const allRequiredProcessesVerified = requiredProcessLabels.every(label => verifiedProcessLabels.has(label))
1887
+ return processResults.every(Boolean) && portResults.every(Boolean) && allRequiredProcessesVerified
1888
+ }
1889
+
1890
+ try {
1891
+ await main()
1892
+ }
1893
+ catch (error) {
1894
+ const preflightFailed = currentStage === 'preflight' || currentStage === 'compile-local-omp-fixture-shim' || currentStage === 'simulator-startup'
1895
+ evidence.status = preflightFailed ? 'blocked' : 'failed'
1896
+ evidence.failure = { stage: currentStage, scene: currentScene ?? null, ...compactError(error) }
1897
+ if (evidence.isolation.result === 'pending') evidence.isolation.result = preflightFailed ? 'failed' : 'incomplete'
1898
+ }
1899
+ finally {
1900
+ const cleanupPassed = await cleanup()
1901
+ if (!cleanupPassed) {
1902
+ evidence.status = 'failed'
1903
+ evidence.isolation.result = 'failed'
1904
+ evidence.failure ??= { stage: 'cleanup', name: 'CleanupVerificationError', message: 'process stop or loopback port release verification failed' }
1905
+ evidence.failure.cleanupVerificationFailed = true
1906
+ }
1907
+ if (evidence.status === 'passed') {
1908
+ const failedChecks = [...evidence.checks, ...evidence.isolation.checks].filter(item => item.status !== 'pass')
1909
+ const cleanupChecks = evidence.checks.filter(item => RELEASE_CHECK_SUFFIXES.some(suffix => item.id.endsWith(suffix)))
1910
+ if (failedChecks.length || !cleanupChecks.length || cleanupChecks.some(item => item.status !== 'pass')) {
1911
+ evidence.status = 'failed'
1912
+ evidence.isolation.result = 'failed'
1913
+ evidence.failure ??= { stage: 'final-verification', name: 'FinalVerificationError', message: 'not all experiment and cleanup checks passed' }
1914
+ }
1915
+ }
1916
+ evidence.cleanup = { status: cleanupPassed ? 'passed' : 'failed', requiredProcessAndPortChecks: true }
1917
+ evidence.experiment.finishedAt = new Date().toISOString()
1918
+ evidence.experiment.evidencePath = 'evidence.json'
1919
+ evidence.experiment.runtimeLogPaths = { app: 'agentworkshop.log', simulator: 'simulator.log' }
1920
+ writeFileSync(EVIDENCE_PATH, `${JSON.stringify(evidence, null, 2)}\n`, 'utf8')
1921
+ console.log(`REGISTERED_HARNESS_E2E=${evidence.status}`)
1922
+ console.log(`EVIDENCE=${EVIDENCE_PATH}`)
1923
+ console.log(`STAGE=${evidence.failure?.stage ?? 'complete'}`)
1924
+ }
1925
+
1926
+ if (evidence.status !== 'passed') process.exitCode = evidence.status === 'blocked' ? 2 : 1