simplify3x-connect 0.0.0-stage → 0.28.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 (363) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +117 -3
  3. package/dist/acText.d.ts +12 -0
  4. package/dist/acText.d.ts.map +1 -0
  5. package/dist/acText.js +44 -0
  6. package/dist/acText.js.map +1 -0
  7. package/dist/adapters/factory.d.ts +25 -0
  8. package/dist/adapters/factory.d.ts.map +1 -0
  9. package/dist/adapters/factory.js +55 -0
  10. package/dist/adapters/factory.js.map +1 -0
  11. package/dist/adapters/http.d.ts +62 -0
  12. package/dist/adapters/http.d.ts.map +1 -0
  13. package/dist/adapters/http.js +138 -0
  14. package/dist/adapters/http.js.map +1 -0
  15. package/dist/adapters/remoteMcp/adapter.d.ts +112 -0
  16. package/dist/adapters/remoteMcp/adapter.d.ts.map +1 -0
  17. package/dist/adapters/remoteMcp/adapter.js +259 -0
  18. package/dist/adapters/remoteMcp/adapter.js.map +1 -0
  19. package/dist/adapters/simplifyqa/adapter.d.ts +1390 -0
  20. package/dist/adapters/simplifyqa/adapter.d.ts.map +1 -0
  21. package/dist/adapters/simplifyqa/adapter.js +9126 -0
  22. package/dist/adapters/simplifyqa/adapter.js.map +1 -0
  23. package/dist/adapters/simplifyqa/apiFailureReason.d.ts +11 -0
  24. package/dist/adapters/simplifyqa/apiFailureReason.d.ts.map +1 -0
  25. package/dist/adapters/simplifyqa/apiFailureReason.js +35 -0
  26. package/dist/adapters/simplifyqa/apiFailureReason.js.map +1 -0
  27. package/dist/adapters/simplifyqa/desktopConditions.d.ts +50 -0
  28. package/dist/adapters/simplifyqa/desktopConditions.d.ts.map +1 -0
  29. package/dist/adapters/simplifyqa/desktopConditions.js +95 -0
  30. package/dist/adapters/simplifyqa/desktopConditions.js.map +1 -0
  31. package/dist/adapters/simplifyqa/executionFailures.d.ts +59 -0
  32. package/dist/adapters/simplifyqa/executionFailures.d.ts.map +1 -0
  33. package/dist/adapters/simplifyqa/executionFailures.js +641 -0
  34. package/dist/adapters/simplifyqa/executionFailures.js.map +1 -0
  35. package/dist/adapters/simplifyqa/failureCategory.d.ts +26 -0
  36. package/dist/adapters/simplifyqa/failureCategory.d.ts.map +1 -0
  37. package/dist/adapters/simplifyqa/failureCategory.js +208 -0
  38. package/dist/adapters/simplifyqa/failureCategory.js.map +1 -0
  39. package/dist/adapters/simplifyqa/failureReport.d.ts +50 -0
  40. package/dist/adapters/simplifyqa/failureReport.d.ts.map +1 -0
  41. package/dist/adapters/simplifyqa/failureReport.js +383 -0
  42. package/dist/adapters/simplifyqa/failureReport.js.map +1 -0
  43. package/dist/adapters/simplifyqa/failureTypes.d.ts +193 -0
  44. package/dist/adapters/simplifyqa/failureTypes.d.ts.map +1 -0
  45. package/dist/adapters/simplifyqa/failureTypes.js +8 -0
  46. package/dist/adapters/simplifyqa/failureTypes.js.map +1 -0
  47. package/dist/adapters/simplifyqa/flow.d.ts +58 -0
  48. package/dist/adapters/simplifyqa/flow.d.ts.map +1 -0
  49. package/dist/adapters/simplifyqa/flow.js +335 -0
  50. package/dist/adapters/simplifyqa/flow.js.map +1 -0
  51. package/dist/adapters/simplifyqa/functionMatch.d.ts +53 -0
  52. package/dist/adapters/simplifyqa/functionMatch.d.ts.map +1 -0
  53. package/dist/adapters/simplifyqa/functionMatch.js +110 -0
  54. package/dist/adapters/simplifyqa/functionMatch.js.map +1 -0
  55. package/dist/adapters/simplifyqa/heal/apply.d.ts +59 -0
  56. package/dist/adapters/simplifyqa/heal/apply.d.ts.map +1 -0
  57. package/dist/adapters/simplifyqa/heal/apply.js +213 -0
  58. package/dist/adapters/simplifyqa/heal/apply.js.map +1 -0
  59. package/dist/adapters/simplifyqa/heal/diagnose.d.ts +24 -0
  60. package/dist/adapters/simplifyqa/heal/diagnose.d.ts.map +1 -0
  61. package/dist/adapters/simplifyqa/heal/diagnose.js +211 -0
  62. package/dist/adapters/simplifyqa/heal/diagnose.js.map +1 -0
  63. package/dist/adapters/simplifyqa/heal/index.d.ts +37 -0
  64. package/dist/adapters/simplifyqa/heal/index.d.ts.map +1 -0
  65. package/dist/adapters/simplifyqa/heal/index.js +83 -0
  66. package/dist/adapters/simplifyqa/heal/index.js.map +1 -0
  67. package/dist/adapters/simplifyqa/heal/plan.d.ts +67 -0
  68. package/dist/adapters/simplifyqa/heal/plan.d.ts.map +1 -0
  69. package/dist/adapters/simplifyqa/heal/plan.js +338 -0
  70. package/dist/adapters/simplifyqa/heal/plan.js.map +1 -0
  71. package/dist/adapters/simplifyqa/heal/store.d.ts +10 -0
  72. package/dist/adapters/simplifyqa/heal/store.d.ts.map +1 -0
  73. package/dist/adapters/simplifyqa/heal/store.js +40 -0
  74. package/dist/adapters/simplifyqa/heal/store.js.map +1 -0
  75. package/dist/adapters/simplifyqa/mapLimit.d.ts +3 -0
  76. package/dist/adapters/simplifyqa/mapLimit.d.ts.map +1 -0
  77. package/dist/adapters/simplifyqa/mapLimit.js +14 -0
  78. package/dist/adapters/simplifyqa/mapLimit.js.map +1 -0
  79. package/dist/adapters/simplifyqa/mapper.d.ts +159 -0
  80. package/dist/adapters/simplifyqa/mapper.d.ts.map +1 -0
  81. package/dist/adapters/simplifyqa/mapper.js +1767 -0
  82. package/dist/adapters/simplifyqa/mapper.js.map +1 -0
  83. package/dist/adapters/simplifyqa/planTree.d.ts +31 -0
  84. package/dist/adapters/simplifyqa/planTree.d.ts.map +1 -0
  85. package/dist/adapters/simplifyqa/planTree.js +110 -0
  86. package/dist/adapters/simplifyqa/planTree.js.map +1 -0
  87. package/dist/adapters/simplifyqa/searchEngine.d.ts +254 -0
  88. package/dist/adapters/simplifyqa/searchEngine.d.ts.map +1 -0
  89. package/dist/adapters/simplifyqa/searchEngine.js +1248 -0
  90. package/dist/adapters/simplifyqa/searchEngine.js.map +1 -0
  91. package/dist/adapters/simplifyqa/searchRegistry.d.ts +117 -0
  92. package/dist/adapters/simplifyqa/searchRegistry.d.ts.map +1 -0
  93. package/dist/adapters/simplifyqa/searchRegistry.js +1664 -0
  94. package/dist/adapters/simplifyqa/searchRegistry.js.map +1 -0
  95. package/dist/adapters/simplifyqa/searchResolve.d.ts +84 -0
  96. package/dist/adapters/simplifyqa/searchResolve.d.ts.map +1 -0
  97. package/dist/adapters/simplifyqa/searchResolve.js +319 -0
  98. package/dist/adapters/simplifyqa/searchResolve.js.map +1 -0
  99. package/dist/adapters/simplifyqa/stepDiagnostics.d.ts +25 -0
  100. package/dist/adapters/simplifyqa/stepDiagnostics.d.ts.map +1 -0
  101. package/dist/adapters/simplifyqa/stepDiagnostics.js +89 -0
  102. package/dist/adapters/simplifyqa/stepDiagnostics.js.map +1 -0
  103. package/dist/adapters/simplifyqa/stepRules.d.ts +91 -0
  104. package/dist/adapters/simplifyqa/stepRules.d.ts.map +1 -0
  105. package/dist/adapters/simplifyqa/stepRules.js +228 -0
  106. package/dist/adapters/simplifyqa/stepRules.js.map +1 -0
  107. package/dist/adapters/types.d.ts +514 -0
  108. package/dist/adapters/types.d.ts.map +1 -0
  109. package/dist/adapters/types.js +2 -0
  110. package/dist/adapters/types.js.map +1 -0
  111. package/dist/adapters/walnut/actionTypes.d.ts +16 -0
  112. package/dist/adapters/walnut/actionTypes.d.ts.map +1 -0
  113. package/dist/adapters/walnut/actionTypes.js +178 -0
  114. package/dist/adapters/walnut/actionTypes.js.map +1 -0
  115. package/dist/adapters/walnut/adapter.d.ts +235 -0
  116. package/dist/adapters/walnut/adapter.d.ts.map +1 -0
  117. package/dist/adapters/walnut/adapter.js +1120 -0
  118. package/dist/adapters/walnut/adapter.js.map +1 -0
  119. package/dist/adapters/walnut/mapper.d.ts +55 -0
  120. package/dist/adapters/walnut/mapper.d.ts.map +1 -0
  121. package/dist/adapters/walnut/mapper.js +364 -0
  122. package/dist/adapters/walnut/mapper.js.map +1 -0
  123. package/dist/cli.d.ts +3 -0
  124. package/dist/cli.d.ts.map +1 -0
  125. package/dist/cli.js +38 -0
  126. package/dist/cli.js.map +1 -0
  127. package/dist/config.d.ts +109 -0
  128. package/dist/config.d.ts.map +1 -0
  129. package/dist/config.js +272 -0
  130. package/dist/config.js.map +1 -0
  131. package/dist/connection.d.ts +105 -0
  132. package/dist/connection.d.ts.map +1 -0
  133. package/dist/connection.js +255 -0
  134. package/dist/connection.js.map +1 -0
  135. package/dist/domain/heal.d.ts +163 -0
  136. package/dist/domain/heal.d.ts.map +1 -0
  137. package/dist/domain/heal.js +55 -0
  138. package/dist/domain/heal.js.map +1 -0
  139. package/dist/domain/types.d.ts +1328 -0
  140. package/dist/domain/types.d.ts.map +1 -0
  141. package/dist/domain/types.js +8 -0
  142. package/dist/domain/types.js.map +1 -0
  143. package/dist/domain/validate.d.ts +3 -0
  144. package/dist/domain/validate.d.ts.map +1 -0
  145. package/dist/domain/validate.js +67 -0
  146. package/dist/domain/validate.js.map +1 -0
  147. package/dist/drafts/apiPatch.d.ts +9 -0
  148. package/dist/drafts/apiPatch.d.ts.map +1 -0
  149. package/dist/drafts/apiPatch.js +27 -0
  150. package/dist/drafts/apiPatch.js.map +1 -0
  151. package/dist/drafts/bulk.d.ts +24 -0
  152. package/dist/drafts/bulk.d.ts.map +1 -0
  153. package/dist/drafts/bulk.js +44 -0
  154. package/dist/drafts/bulk.js.map +1 -0
  155. package/dist/drafts/duplicate.d.ts +12 -0
  156. package/dist/drafts/duplicate.d.ts.map +1 -0
  157. package/dist/drafts/duplicate.js +59 -0
  158. package/dist/drafts/duplicate.js.map +1 -0
  159. package/dist/drafts/store.d.ts +91 -0
  160. package/dist/drafts/store.d.ts.map +1 -0
  161. package/dist/drafts/store.js +244 -0
  162. package/dist/drafts/store.js.map +1 -0
  163. package/dist/gateway.d.ts +37 -0
  164. package/dist/gateway.d.ts.map +1 -0
  165. package/dist/gateway.js +71 -0
  166. package/dist/gateway.js.map +1 -0
  167. package/dist/httpMain.d.ts +3 -0
  168. package/dist/httpMain.d.ts.map +1 -0
  169. package/dist/httpMain.js +20 -0
  170. package/dist/httpMain.js.map +1 -0
  171. package/dist/index.d.ts +3 -0
  172. package/dist/index.d.ts.map +1 -0
  173. package/dist/index.js +46 -0
  174. package/dist/index.js.map +1 -0
  175. package/dist/initAgents.d.ts +2 -0
  176. package/dist/initAgents.d.ts.map +1 -0
  177. package/dist/initAgents.js +508 -0
  178. package/dist/initAgents.js.map +1 -0
  179. package/dist/log.d.ts +17 -0
  180. package/dist/log.d.ts.map +1 -0
  181. package/dist/log.js +49 -0
  182. package/dist/log.js.map +1 -0
  183. package/dist/mcpResult.d.ts +39 -0
  184. package/dist/mcpResult.d.ts.map +1 -0
  185. package/dist/mcpResult.js +19 -0
  186. package/dist/mcpResult.js.map +1 -0
  187. package/dist/mount.d.ts +33 -0
  188. package/dist/mount.d.ts.map +1 -0
  189. package/dist/mount.js +213 -0
  190. package/dist/mount.js.map +1 -0
  191. package/dist/paramTokens.d.ts +18 -0
  192. package/dist/paramTokens.d.ts.map +1 -0
  193. package/dist/paramTokens.js +50 -0
  194. package/dist/paramTokens.js.map +1 -0
  195. package/dist/projectStore.d.ts +5 -0
  196. package/dist/projectStore.d.ts.map +1 -0
  197. package/dist/projectStore.js +60 -0
  198. package/dist/projectStore.js.map +1 -0
  199. package/dist/requestConnection.d.ts +22 -0
  200. package/dist/requestConnection.d.ts.map +1 -0
  201. package/dist/requestConnection.js +50 -0
  202. package/dist/requestConnection.js.map +1 -0
  203. package/dist/serve.d.ts +10 -0
  204. package/dist/serve.d.ts.map +1 -0
  205. package/dist/serve.js +37 -0
  206. package/dist/serve.js.map +1 -0
  207. package/dist/server.d.ts +41 -0
  208. package/dist/server.d.ts.map +1 -0
  209. package/dist/server.js +370 -0
  210. package/dist/server.js.map +1 -0
  211. package/dist/tools/actionCatalog.d.ts +24 -0
  212. package/dist/tools/actionCatalog.d.ts.map +1 -0
  213. package/dist/tools/actionCatalog.js +56 -0
  214. package/dist/tools/actionCatalog.js.map +1 -0
  215. package/dist/tools/attachment.tools.d.ts +15 -0
  216. package/dist/tools/attachment.tools.d.ts.map +1 -0
  217. package/dist/tools/attachment.tools.js +104 -0
  218. package/dist/tools/attachment.tools.js.map +1 -0
  219. package/dist/tools/backlog.tools.d.ts +13 -0
  220. package/dist/tools/backlog.tools.d.ts.map +1 -0
  221. package/dist/tools/backlog.tools.js +690 -0
  222. package/dist/tools/backlog.tools.js.map +1 -0
  223. package/dist/tools/connection.tools.d.ts +16 -0
  224. package/dist/tools/connection.tools.d.ts.map +1 -0
  225. package/dist/tools/connection.tools.js +120 -0
  226. package/dist/tools/connection.tools.js.map +1 -0
  227. package/dist/tools/defects.tools.d.ts +7 -0
  228. package/dist/tools/defects.tools.d.ts.map +1 -0
  229. package/dist/tools/defects.tools.js +108 -0
  230. package/dist/tools/defects.tools.js.map +1 -0
  231. package/dist/tools/discovery.tools.d.ts +23 -0
  232. package/dist/tools/discovery.tools.d.ts.map +1 -0
  233. package/dist/tools/discovery.tools.js +1746 -0
  234. package/dist/tools/discovery.tools.js.map +1 -0
  235. package/dist/tools/executionPlan.tools.d.ts +14 -0
  236. package/dist/tools/executionPlan.tools.d.ts.map +1 -0
  237. package/dist/tools/executionPlan.tools.js +184 -0
  238. package/dist/tools/executionPlan.tools.js.map +1 -0
  239. package/dist/tools/failure.tools.d.ts +14 -0
  240. package/dist/tools/failure.tools.d.ts.map +1 -0
  241. package/dist/tools/failure.tools.js +65 -0
  242. package/dist/tools/failure.tools.js.map +1 -0
  243. package/dist/tools/formulas.tools.d.ts +7 -0
  244. package/dist/tools/formulas.tools.d.ts.map +1 -0
  245. package/dist/tools/formulas.tools.js +84 -0
  246. package/dist/tools/formulas.tools.js.map +1 -0
  247. package/dist/tools/functionReuse.d.ts +77 -0
  248. package/dist/tools/functionReuse.d.ts.map +1 -0
  249. package/dist/tools/functionReuse.js +384 -0
  250. package/dist/tools/functionReuse.js.map +1 -0
  251. package/dist/tools/gapAnalysis.tools.d.ts +31 -0
  252. package/dist/tools/gapAnalysis.tools.d.ts.map +1 -0
  253. package/dist/tools/gapAnalysis.tools.js +287 -0
  254. package/dist/tools/gapAnalysis.tools.js.map +1 -0
  255. package/dist/tools/heal.tools.d.ts +20 -0
  256. package/dist/tools/heal.tools.d.ts.map +1 -0
  257. package/dist/tools/heal.tools.js +268 -0
  258. package/dist/tools/heal.tools.js.map +1 -0
  259. package/dist/tools/impactAnalysis.tools.d.ts +17 -0
  260. package/dist/tools/impactAnalysis.tools.d.ts.map +1 -0
  261. package/dist/tools/impactAnalysis.tools.js +352 -0
  262. package/dist/tools/impactAnalysis.tools.js.map +1 -0
  263. package/dist/tools/markdown.d.ts +13 -0
  264. package/dist/tools/markdown.d.ts.map +1 -0
  265. package/dist/tools/markdown.js +145 -0
  266. package/dist/tools/markdown.js.map +1 -0
  267. package/dist/tools/objects.tools.d.ts +7 -0
  268. package/dist/tools/objects.tools.d.ts.map +1 -0
  269. package/dist/tools/objects.tools.js +458 -0
  270. package/dist/tools/objects.tools.js.map +1 -0
  271. package/dist/tools/pipeline.tools.d.ts +11 -0
  272. package/dist/tools/pipeline.tools.d.ts.map +1 -0
  273. package/dist/tools/pipeline.tools.js +100 -0
  274. package/dist/tools/pipeline.tools.js.map +1 -0
  275. package/dist/tools/preference.tools.d.ts +15 -0
  276. package/dist/tools/preference.tools.d.ts.map +1 -0
  277. package/dist/tools/preference.tools.js +114 -0
  278. package/dist/tools/preference.tools.js.map +1 -0
  279. package/dist/tools/privileges.tools.d.ts +65 -0
  280. package/dist/tools/privileges.tools.d.ts.map +1 -0
  281. package/dist/tools/privileges.tools.js +186 -0
  282. package/dist/tools/privileges.tools.js.map +1 -0
  283. package/dist/tools/project.tools.d.ts +13 -0
  284. package/dist/tools/project.tools.d.ts.map +1 -0
  285. package/dist/tools/project.tools.js +199 -0
  286. package/dist/tools/project.tools.js.map +1 -0
  287. package/dist/tools/query.tools.d.ts +23 -0
  288. package/dist/tools/query.tools.d.ts.map +1 -0
  289. package/dist/tools/query.tools.js +368 -0
  290. package/dist/tools/query.tools.js.map +1 -0
  291. package/dist/tools/recording.tools.d.ts +58 -0
  292. package/dist/tools/recording.tools.d.ts.map +1 -0
  293. package/dist/tools/recording.tools.js +1050 -0
  294. package/dist/tools/recording.tools.js.map +1 -0
  295. package/dist/tools/recordingNames.d.ts +3 -0
  296. package/dist/tools/recordingNames.d.ts.map +1 -0
  297. package/dist/tools/recordingNames.js +16 -0
  298. package/dist/tools/recordingNames.js.map +1 -0
  299. package/dist/tools/report.tools.d.ts +12 -0
  300. package/dist/tools/report.tools.d.ts.map +1 -0
  301. package/dist/tools/report.tools.js +104 -0
  302. package/dist/tools/report.tools.js.map +1 -0
  303. package/dist/tools/run.tools.d.ts +25 -0
  304. package/dist/tools/run.tools.d.ts.map +1 -0
  305. package/dist/tools/run.tools.js +1295 -0
  306. package/dist/tools/run.tools.js.map +1 -0
  307. package/dist/tools/schemas.d.ts +860 -0
  308. package/dist/tools/schemas.d.ts.map +1 -0
  309. package/dist/tools/schemas.js +220 -0
  310. package/dist/tools/schemas.js.map +1 -0
  311. package/dist/tools/storySync.tools.d.ts +167 -0
  312. package/dist/tools/storySync.tools.d.ts.map +1 -0
  313. package/dist/tools/storySync.tools.js +678 -0
  314. package/dist/tools/storySync.tools.js.map +1 -0
  315. package/dist/tools/suiteManage.tools.d.ts +14 -0
  316. package/dist/tools/suiteManage.tools.d.ts.map +1 -0
  317. package/dist/tools/suiteManage.tools.js +112 -0
  318. package/dist/tools/suiteManage.tools.js.map +1 -0
  319. package/dist/tools/tasks.tools.d.ts +7 -0
  320. package/dist/tools/tasks.tools.d.ts.map +1 -0
  321. package/dist/tools/tasks.tools.js +101 -0
  322. package/dist/tools/tasks.tools.js.map +1 -0
  323. package/dist/tools/tcEditPublisher.d.ts +29 -0
  324. package/dist/tools/tcEditPublisher.d.ts.map +1 -0
  325. package/dist/tools/tcEditPublisher.js +61 -0
  326. package/dist/tools/tcEditPublisher.js.map +1 -0
  327. package/dist/tools/testCaseLint.d.ts +5 -0
  328. package/dist/tools/testCaseLint.d.ts.map +1 -0
  329. package/dist/tools/testCaseLint.js +112 -0
  330. package/dist/tools/testCaseLint.js.map +1 -0
  331. package/dist/tools/testPlan.tools.d.ts +12 -0
  332. package/dist/tools/testPlan.tools.d.ts.map +1 -0
  333. package/dist/tools/testPlan.tools.js +104 -0
  334. package/dist/tools/testPlan.tools.js.map +1 -0
  335. package/dist/tools/testcase.tools.d.ts +86 -0
  336. package/dist/tools/testcase.tools.d.ts.map +1 -0
  337. package/dist/tools/testcase.tools.js +1591 -0
  338. package/dist/tools/testcase.tools.js.map +1 -0
  339. package/dist/tools/testdata.tools.d.ts +7 -0
  340. package/dist/tools/testdata.tools.d.ts.map +1 -0
  341. package/dist/tools/testdata.tools.js +636 -0
  342. package/dist/tools/testdata.tools.js.map +1 -0
  343. package/dist/tools/xlsx.d.ts +8 -0
  344. package/dist/tools/xlsx.d.ts.map +1 -0
  345. package/dist/tools/xlsx.js +113 -0
  346. package/dist/tools/xlsx.js.map +1 -0
  347. package/dist/vendor/actionSignatures.d.ts +117 -0
  348. package/dist/vendor/actionSignatures.d.ts.map +1 -0
  349. package/dist/vendor/actionSignatures.js +420 -0
  350. package/dist/vendor/actionSignatures.js.map +1 -0
  351. package/dist/vendor/logger.d.ts +43 -0
  352. package/dist/vendor/logger.d.ts.map +1 -0
  353. package/dist/vendor/logger.js +184 -0
  354. package/dist/vendor/logger.js.map +1 -0
  355. package/dist/version.d.ts +10 -0
  356. package/dist/version.d.ts.map +1 -0
  357. package/dist/version.js +10 -0
  358. package/dist/version.js.map +1 -0
  359. package/dist/versionName.d.ts +21 -0
  360. package/dist/versionName.d.ts.map +1 -0
  361. package/dist/versionName.js +48 -0
  362. package/dist/versionName.js.map +1 -0
  363. package/package.json +62 -4
@@ -0,0 +1,1591 @@
1
+ import { z } from 'zod';
2
+ import { ok, err } from '../mcpResult.js';
3
+ import { lintAutomatedTestCase, lintBlock } from './testCaseLint.js';
4
+ import { validateTestCase } from '../domain/validate.js';
5
+ import { WALNUT_ACTIONS, actionDefsFrom, offlineCatalogFor } from '../adapters/walnut/actionTypes.js';
6
+ import { resolveCatalogFor } from './actionCatalog.js';
7
+ import { toWalnutStep } from '../adapters/walnut/mapper.js';
8
+ import { stepsMarkdown, validationSummaryLine } from './markdown.js';
9
+ import { zCategory, zDraftOp, zNewStep, zPriority } from './schemas.js';
10
+ import { emitTcEdit, openTcViewerWindow, refreshRecorderWindow } from './tcEditPublisher.js';
11
+ import { nextVersionName, latestVersionId } from '../versionName.js';
12
+ import { recordingName } from './recordingNames.js';
13
+ import { askReplaceText, findFunctionCandidatesForTc, findFunctionMatches, proposeFunctionGroups, replaceMatchedRuns, selectMatches, suggestionText } from './functionReuse.js';
14
+ function describeError(e) {
15
+ return e instanceof Error ? e.message : String(e);
16
+ }
17
+ /** First text block from an MCP tool result, for forwarding agent-side save errors. */
18
+ function firstText(res) {
19
+ const r = res;
20
+ if (Array.isArray(r?.content)) {
21
+ const text = r.content.map((c) => (typeof c?.text === 'string' ? c.text : '')).filter(Boolean).join('\n');
22
+ if (text)
23
+ return text;
24
+ }
25
+ return 'Recorder save failed.';
26
+ }
27
+ /** The agent's `read_journal` emits an API step's whole request as top-level `apiData` (the wire
28
+ * key), whereas the neutral Step holds it as `api`. Fold it across so the save mapper finds it and
29
+ * emits a real API step (with its request + assertions) instead of an empty NORMAL_STATEMENT. */
30
+ export function normalizeJournalStep(step) {
31
+ const raw = step;
32
+ // The agent's read_journal emits an API step's request as top-level `apiData` and often labels the
33
+ // step "API Call" while leaving stepType as 'web'. Normalise it to a real API step, otherwise the
34
+ // save builder tries to resolve an action named "API Call" and the whole save fails — taking the
35
+ // parameters and test data with it.
36
+ const looksApi = !!raw.apiData && (step.stepType === 'api' ||
37
+ /^api\s*call$/i.test((step.actionType ?? '').trim()) ||
38
+ (raw.technologyType ?? '').toUpperCase() === 'API');
39
+ if (looksApi && !step.api) {
40
+ return { ...step, stepType: 'api', api: raw.apiData };
41
+ }
42
+ // A DESKTOP step is never a technology switch: its own window actions are named "Switch to Window by Name"
43
+ // (dsk-13) and "Switch to Root" (dsk-23), and they must stay steps.
44
+ if (step.stepType === 'desktop')
45
+ return step;
46
+ // "Switch to WEB/API/DB/…" journal rows arrive as a plain statement with that action name. Route
47
+ // them to the control-flow shape the save builder understands, so a mixed recording saves.
48
+ const sw = /^switch\s+to\s+(.+)$/i.exec((step.actionType ?? '').trim());
49
+ if (sw && !step.controlFlow) {
50
+ return { ...step, stepType: 'switch', controlFlow: { kind: `SWITCH_TO_${sw[1].trim().toUpperCase()}` } };
51
+ }
52
+ return step;
53
+ }
54
+ /**
55
+ * Recorder Save unavailable (the agent's `core_save_session` answers `recorder save request failed:
56
+ * null`, or reports an error): persist the journal STRAIGHT to the backend so the recording — its
57
+ * steps, parameters and default test-data row — is never lost. The save builder turns each step's
58
+ * `recordedParam` into real project parameters plus the ITR-1 row, which is exactly what the
59
+ * recorder UI save was failing to write.
60
+ *
61
+ * Only used as a fallback: when the recorder save works, that path (exact window parity) wins.
62
+ */
63
+ export async function saveJournalFallback(adapter, sessionId, target, name) {
64
+ if (!adapter.readJournal)
65
+ return null;
66
+ const view = await adapter.readJournal(sessionId);
67
+ const steps = (view?.steps ?? []).map(normalizeJournalStep);
68
+ if (!steps.length)
69
+ return null;
70
+ // The name the recording was started with. Without one, the session id plus the time: a recorder can keep one
71
+ // session id for several recordings, and the backend refuses a second test case with the same name.
72
+ const stamp = new Date().toISOString().replace('T', ' ').slice(0, 19);
73
+ const tc = {
74
+ title: name?.trim() || `Recording ${sessionId} ${stamp}`,
75
+ category: 'automated',
76
+ steps,
77
+ };
78
+ if (adapter.listModules) {
79
+ try {
80
+ const dflt = (await adapter.listModules()).find((m) => m.name?.trim().toLowerCase() === 'default module');
81
+ if (dflt?.id)
82
+ tc.folderOrModule = dflt.id;
83
+ }
84
+ catch { /* no module lookup — save without one */ }
85
+ }
86
+ // EXISTING-TC re-record (story sync): when the recording was opened against a test case, the
87
+ // fallback must create a NEW VERSION of that TC — never a separate new test case.
88
+ let ref = null;
89
+ let versionName;
90
+ const existingTcId = target?.testcaseId;
91
+ const newVersion = (target?.saveMode ?? 'new-version') === 'new-version';
92
+ if (existingTcId && newVersion && adapter.saveAsNewVersion) {
93
+ let base = null;
94
+ try {
95
+ base = await adapter.getTestCase(target.testcaseId);
96
+ }
97
+ catch { /* no name/version info */ }
98
+ const vName = target?.versionName
99
+ || nextVersionName(base)
100
+ || 'v2.0';
101
+ // Preserve the EXISTING test case's metadata (name, module, story, description, custom fields);
102
+ // only its steps are replaced. Passing a journal-built TC here used to RENAME the TC and blank
103
+ // its module, which also blocked the recorder window's Save (module is mandatory).
104
+ const merged = base
105
+ ? { ...base, category: base.category ?? 'automated', steps }
106
+ : tc;
107
+ ref = await adapter.saveAsNewVersion(target.testcaseId, {
108
+ versionName: vName,
109
+ tc: merged,
110
+ tdCopy: target?.copyTestdata !== false,
111
+ ...(target?.versionId ? { sourceVersionId: target.versionId } : {}),
112
+ ...(base?.currentVersionId ? {} : {}),
113
+ });
114
+ versionName = vName;
115
+ }
116
+ else {
117
+ ref = await adapter.createTestCase(tc);
118
+ }
119
+ if (!ref?.id)
120
+ return null;
121
+ // Formula-driven values: the steps were created with their concrete recorded values, so apply the
122
+ // recorded =NAME(...) expressions to the DEFAULT test-data row afterwards. Without this the fallback
123
+ // save (window unavailable) would silently freeze the recording's random values as literals.
124
+ let formulasApplied = 0;
125
+ const formulaSkipped = [];
126
+ // NEVER persist a recorded =NAME(...) as plain text. Written straight through, an unevaluated /
127
+ // unknown / mis-cased formula (e.g. =First_Name("", "") or =concatenate(=first_name(),...)) landed in
128
+ // the grid as text and showed #Error at execution. Evaluate it first; if the agent rejects it, keep
129
+ // the recorded literal value and REPORT the skip.
130
+ const cells = [];
131
+ for (const s of steps) {
132
+ for (const [paramName, rawFormula] of Object.entries(s.recordedParamFormula ?? {})) {
133
+ const literal = String((s.recordedParam ?? {})[paramName] ?? '');
134
+ if (!adapter.evaluateFormula) {
135
+ cells.push({ paramName, value: literal, formulaValue: rawFormula });
136
+ continue;
137
+ }
138
+ try {
139
+ const { value, expression } = await adapter.evaluateFormula({ expression: rawFormula });
140
+ cells.push({ paramName, value, formulaValue: expression });
141
+ }
142
+ catch (e) {
143
+ cells.push({ paramName, value: literal });
144
+ formulaSkipped.push(`${paramName}: "${rawFormula}" was NOT stored as a formula — ` +
145
+ `${e instanceof Error ? e.message : String(e)} (kept the recorded value).`);
146
+ }
147
+ }
148
+ }
149
+ if (cells.length > 0 && adapter.patchTestdataCells) {
150
+ try {
151
+ // Target the NEW version's iteration (a TC has one row per version; patching the first row
152
+ // would stamp the formulas onto the OLD version).
153
+ let targetVersionId = undefined;
154
+ if (existingTcId && versionName && adapter.getTestCase) {
155
+ try {
156
+ const after = await adapter.getTestCase(existingTcId);
157
+ targetVersionId = latestVersionId(after);
158
+ }
159
+ catch { /* fall back to the default row */ }
160
+ }
161
+ const r = await adapter.patchTestdataCells({ tcId: String(ref.id), cells, ...(targetVersionId ? { versionId: targetVersionId } : {}) });
162
+ formulasApplied = r.patched;
163
+ formulaSkipped.push(...r.skipped);
164
+ }
165
+ catch {
166
+ formulaSkipped.push('could not patch the test-data cells');
167
+ }
168
+ }
169
+ return {
170
+ id: String(ref.id),
171
+ ...(ref.productUrl ? { productUrl: ref.productUrl } : {}),
172
+ ...(versionName ? { versionName } : {}),
173
+ ...(cells.length ? { formulasApplied, formulaSkipped } : {}),
174
+ };
175
+ }
176
+ /**
177
+ * Asks a SEPARATELY-RUNNING local Walnut agent to draw the editor in its own
178
+ * Electron window, over a loopback HTTP call to POST /editor/open.
179
+ *
180
+ * This is the ORIGINAL common-qa-mcp behavior, preserved verbatim as the
181
+ * fallback for `TestcaseToolsDeps.openEditorWindow` being absent -- i.e. for
182
+ * the standalone stdio dev harness (src/mcp/qa/index.ts), which really is a
183
+ * different OS process from the agent and has no direct function to call.
184
+ * When this tool surface is mounted IN-PROCESS inside the agent
185
+ * (src/mcp/qa/mount.ts), that mount always supplies `deps.openEditorWindow`,
186
+ * which calls routes/editorWindow.routes.ts's openEditorWindow() directly and
187
+ * this HTTP path is never used.
188
+ *
189
+ * Returns false for every "not available" case -- agent not running, running as a
190
+ * plain node dev server (it answers 501), or slow -- because this is an
191
+ * optimisation over returning a link, never a failure the user should see. The
192
+ * short timeout keeps a stale port from stalling the tool call.
193
+ */
194
+ async function openInAgentWindowViaHttp(agentUrl, url, title) {
195
+ const base = agentUrl ?? 'http://127.0.0.1:4050';
196
+ const ctl = new AbortController();
197
+ const timer = setTimeout(() => ctl.abort(), 1500);
198
+ try {
199
+ const res = await fetch(`${base.replace(/\/$/, '')}/editor/open`, {
200
+ method: 'POST',
201
+ headers: { 'Content-Type': 'application/json' },
202
+ body: JSON.stringify({ url, title }),
203
+ signal: ctl.signal,
204
+ });
205
+ return res.ok;
206
+ }
207
+ catch {
208
+ return false;
209
+ }
210
+ finally {
211
+ clearTimeout(timer);
212
+ }
213
+ }
214
+ /** Every draft-returning tool shares this shape: markdown steps table +
215
+ * validation summary line in `content`, the neutral TestCase in
216
+ * `structuredContent` (spec: "one shared helper, not duplicated per tool").
217
+ * Exported so mcp/qa/tools/recording.tools.ts's `recording_save` (a
218
+ * draft-returning tool too -- it hands live-recorded steps into the SAME
219
+ * DraftStore) reuses this instead of a second hand-written literal. */
220
+ export function draftResult(draft, catalogFor = offlineCatalogFor) {
221
+ const issues = validateTestCase(draft.tc, catalogFor);
222
+ const summary = validationSummaryLine(draft.tc, issues);
223
+ const text = `Draft ${draft.draftId} · ${summary}\n\n${stepsMarkdown(draft.tc)}`;
224
+ return ok(text, { draftId: draft.draftId, tc: draft.tc, issues });
225
+ }
226
+ function toBase64Url(payload) {
227
+ return Buffer.from(JSON.stringify(payload), 'utf8')
228
+ .toString('base64')
229
+ .replace(/\+/g, '-')
230
+ .replace(/\//g, '_')
231
+ .replace(/=+$/, '');
232
+ }
233
+ /**
234
+ * Builds the exact `/embed/test-case-draft#d=<payload>` URL walnut-frontend's
235
+ * real TestStepsEditor reads, per scripts/open-in-walnut-editor.ts. `mode` is
236
+ * hardcoded to 'view' -- there is no save path in this server yet, so offering
237
+ * an editable Save affordance the backend can't fulfil would be misleading.
238
+ */
239
+ function buildEditorUrl(origin, draft) {
240
+ const trimmed = origin.endsWith('/') ? origin.slice(0, -1) : origin;
241
+ const payload = {
242
+ title: draft.tc.title,
243
+ priority: draft.tc.priority,
244
+ category: draft.tc.category,
245
+ draftId: draft.draftId,
246
+ mode: 'view',
247
+ test_steps: draft.tc.steps.map(toWalnutStep),
248
+ };
249
+ return `${trimmed}/embed/test-case-draft#d=${toBase64Url(payload)}`;
250
+ }
251
+ /**
252
+ * Registers the offline draft-authoring tool surface: actions_catalog plus the
253
+ * 5 tc_draft_* tools. Every handler here works with `adapter === null` and
254
+ * touches no network -- draft state lives entirely in `deps.drafts`
255
+ * (in-memory, per DraftStore's own contract) and validation runs against the
256
+ * static WALNUT_ACTIONS catalog via offlineCatalogFor. There is deliberately
257
+ * no save/persist tool: nothing this module does writes to any backend.
258
+ */
259
+ export function registerTestcaseTools(server, deps) {
260
+ // Provider-aware action-type catalog for draft validation. SimplifyQA NEVER uses Walnut's static
261
+ // table — it validates against the live SQA backend catalog (or skips when unreachable). Walnut
262
+ // (and unknown/offline) keeps the static table, unchanged.
263
+ const catalogFor = () => resolveCatalogFor(deps.getAdapter?.() ?? null, deps.isSimplifyqa?.() ?? false);
264
+ server.registerTool('actions_catalog', {
265
+ title: 'List the offline action-type catalog',
266
+ description: 'Static per-platform action-type vocabulary (web/android/ios/api/database/mainframe), used for '
267
+ + 'offline draft validation. No network call. NOTE mainframe is deliberately EMPTY (no source '
268
+ + 'list exists), and validate.ts skips validation entirely for an empty catalog — so a clean '
269
+ + 'mainframe draft means "not checked", not "checked and fine".',
270
+ inputSchema: { platform: z.enum(['web', 'android', 'ios', 'api', 'database', 'mainframe', 'desktop']).optional().describe('desktop: there is no offline list; on SimplifyQA the live catalog includes the DESKTOP actions (dsk-*: Launch Application, Click, Type Text, Switch to Window by Name, …).') },
271
+ annotations: { readOnlyHint: true },
272
+ }, async ({ platform }) => {
273
+ try {
274
+ // Prefer the LIVE backend catalog when connected — SQA rows carry numeric `id` that the
275
+ // model needs to round-trip existing steps (an SQA-hydrated step's actionType is the id
276
+ // string, not the name). Falls back to the offline walnut list when no adapter or when
277
+ // the adapter call fails, so the tool always returns something usable.
278
+ // On SimplifyQA there is NO walnut fallback: its action vocabulary is the backend's own,
279
+ // and showing Walnut's list would be actively misleading (the model would author steps
280
+ // against names the SQA backend does not have).
281
+ const adapter = deps.getAdapter?.();
282
+ let defs = null;
283
+ if (adapter?.actionsCatalog) {
284
+ try {
285
+ defs = await adapter.actionsCatalog(platform);
286
+ }
287
+ catch {
288
+ defs = null;
289
+ }
290
+ }
291
+ if (!defs) {
292
+ defs = deps.isSimplifyqa?.()
293
+ ? []
294
+ : (() => {
295
+ const all = actionDefsFrom(WALNUT_ACTIONS);
296
+ return platform ? all.filter((a) => a.platform === platform) : all;
297
+ })();
298
+ }
299
+ const text = `${defs.length} action type${defs.length === 1 ? '' : 's'}${platform ? ` for ${platform}` : ''}.\n\n` +
300
+ defs.map((a) => `- \`${a.actionType}\` (${a.platform})${a.id != null ? ` — id ${a.id}` : ''}`).join('\n');
301
+ return ok(text, { actions: defs });
302
+ }
303
+ catch (e) {
304
+ return err(describeError(e));
305
+ }
306
+ });
307
+ server.registerTool('tc_draft_from_tc', {
308
+ title: 'Load an existing test case as a draft for in-place editing',
309
+ description: 'Fetch a REAL test case from the connected product and hydrate it into a draft, carrying the ' +
310
+ "original tcId. Because the draft carries the id, a later `tc_save({ draftId })` UPDATES that " +
311
+ 'SAME test case (preserving id, run history, parameters, testdata bindings, and suite ' +
312
+ 'membership) instead of creating a sibling.\n\n' +
313
+ 'THIS is the tool for "tag/retag this EXISTING test case with a user story or module" — ' +
314
+ '`journal_modify`\'s `set_meta` does NOT support that on SimplifyQA (journal-only ops there), ' +
315
+ 'so this draft round-trip is the only path:\n' +
316
+ ' 1. tc_draft_from_tc({ tcId })\n' +
317
+ ' 2. tc_draft_update({ draftId, ops: [{ op: "set_meta", patch: { storyRef?, folderOrModule?, ' +
318
+ 'title?, priority?, ... } }] }) — resolve a story/module NAME to an id via story_list / ' +
319
+ 'list_modules FIRST; never guess one.\n' +
320
+ ' 3. tc_save({ draftId })\n' +
321
+ 'Same three steps also apply to applying a `story_sync_testcases` drift report (pass the ' +
322
+ 'filtered `proposedOps` at step 2 instead of a set_meta patch). Requires a live connection ' +
323
+ '(qa_connect).',
324
+ inputSchema: {
325
+ tcId: z.string().describe('The existing test-case id to load as a draft.'),
326
+ },
327
+ }, async ({ tcId }) => {
328
+ const adapter = deps.getAdapter?.();
329
+ if (!adapter) {
330
+ return err('Not connected to a product. Use qa_connect first — loading a real TC needs a live backend.');
331
+ }
332
+ try {
333
+ const tc = await adapter.getTestCase(tcId);
334
+ if (!tc.id)
335
+ tc.id = tcId; // adapter contract guarantees id, but belt-and-braces for the update path
336
+ const draftId = deps.drafts.create(tc);
337
+ return draftResult(deps.drafts.get(draftId), await catalogFor());
338
+ }
339
+ catch (e) {
340
+ return err(describeError(e));
341
+ }
342
+ });
343
+ server.registerTool('tc_draft_from_journal', {
344
+ title: 'Load a recording journal as an automation draft',
345
+ description: 'Load the steps from a recording session (the journal on the connected agent) into a new ' +
346
+ 'AUTOMATION draft. Use this to save a recording that finished — including one from an ' +
347
+ "earlier session. Then review with tc_draft_get and persist with tc_save. If the recording " +
348
+ 'targeted an existing TC, pass its id via `tcId` so the draft inherits title/module/project ' +
349
+ 'and tc_save UPDATES that TC instead of creating a new one. Requires a live connection ' +
350
+ '(qa_connect) with an agent that owns the recording journal.',
351
+ inputSchema: {
352
+ sessionId: z.string().describe('The recording session id — the same id used when the recording started.'),
353
+ tcId: z.string().optional().describe('Optional: an existing TC id to inherit title/module/project from (and to UPDATE on save).'),
354
+ title: z.string().optional().describe('Optional draft title (overrides tcId meta). Defaults to "Recording <sessionId>" when no tcId is passed.'),
355
+ },
356
+ }, async ({ sessionId, tcId, title }) => {
357
+ const adapter = deps.getAdapter?.();
358
+ if (!adapter) {
359
+ return err('Not connected to a product. Use qa_connect first — reading a journal needs a live agent.');
360
+ }
361
+ if (!adapter.readJournal) {
362
+ return err('This product has no recording journal.');
363
+ }
364
+ let view;
365
+ try {
366
+ view = await adapter.readJournal(sessionId);
367
+ }
368
+ catch (e) {
369
+ return err(`Could not read journal for session "${sessionId}": ${describeError(e)}`);
370
+ }
371
+ if (!view.steps || view.steps.length === 0) {
372
+ return err(`Journal for session "${sessionId}" is empty — nothing to save. Record steps first.`);
373
+ }
374
+ let meta = {};
375
+ if (tcId) {
376
+ try {
377
+ const existing = await adapter.getTestCase(tcId);
378
+ meta = existing;
379
+ }
380
+ catch (e) {
381
+ return err(`Could not fetch meta from tcId "${tcId}": ${describeError(e)}`);
382
+ }
383
+ }
384
+ const tc = {
385
+ ...meta,
386
+ title: title ?? meta.title ?? `Recording ${sessionId}`,
387
+ category: 'automated',
388
+ steps: view.steps.map(normalizeJournalStep),
389
+ // When no tcId: this is a NEW TC, so drop any id that leaked in from meta.
390
+ // When tcId: keep meta.id so tc_save UPDATES it in place.
391
+ ...(tcId ? {} : { id: undefined }),
392
+ };
393
+ const draftId = deps.drafts.create(tc, sessionId);
394
+ return draftResult(deps.drafts.get(draftId), await catalogFor());
395
+ });
396
+ server.registerTool('tc_draft_create', {
397
+ title: 'Create a test-case draft',
398
+ description: 'MANUAL-ONLY authoring. Call this when the user asked for a MANUAL test case: they said "manual", ' +
399
+ '"draft only", "plain prose", "no automation", or asked to cover a user story\'s acceptance criteria ' +
400
+ 'as manual cases. For those, this IS the right tool — call it.\n\n' +
401
+ 'Do NOT use for automated tests. "create a test case", "record this flow", "add a test for X" (with no ' +
402
+ '"manual" qualifier) mean AUTOMATED — route to the `web` / `mainframe` sub-agent to RECORD with real ' +
403
+ 'locators instead.\n\n' +
404
+ 'Create a new in-memory test-case draft from steps you author yourself. Nothing is persisted -- no disk, ' +
405
+ 'no backend, no network. Use tc_draft_open to hand it to the test-case editor for viewing.\n\n' +
406
+ 'DO NOT USE THIS FOR A REAL WEB APPLICATION. Steps written here have no locators, so the test case cannot ' +
407
+ 'execute -- it only reads plausibly. Whenever there is an app you can reach (the user gives a URL, names an ' +
408
+ 'environment, or asks for a test of a real flow), call the `web` sub-agent instead: that captures real ' +
409
+ 'locators, real element names and real parameters, and is the DEFAULT way to create a web test case. You ' +
410
+ 'do not need the user to say "record" -- if a test case for a real app is wanted, recording is how it is made.\n\n' +
411
+ 'Legitimate uses: a MANUAL test case the user explicitly asked for (no automation), API/database steps that ' +
412
+ 'need no element binding, restructuring or drafting steps the user supplied verbatim, or sketching a plan ' +
413
+ 'when no app is reachable -- and say plainly that the result is not executable until recorded.\n\n' +
414
+ 'PARAMETERISE EVERY DYNAMIC VALUE — this is mandatory for manual test cases whenever the step ' +
415
+ 'names a URL, credential, product name, form value, expected string, or anything the tester will ' +
416
+ 'type / compare. Instead of hard-coding "Enter admin in the Username field", write "Enter ${username} ' +
417
+ 'in the Username field" and pass `data: { username: "admin" }` at the TC level. Every `${name}` token ' +
418
+ 'becomes a Local parameter in the product and the value from `data` populates the test case\'s ' +
419
+ 'default test-data row (ITR-1) automatically. Steps with no `${...}` tokens create no parameters — ' +
420
+ 'that is only correct for pure checklist verifications ("verify heading is visible"). If a step ' +
421
+ 'references a real value, tokenise it.',
422
+ inputSchema: {
423
+ title: z.string().min(1),
424
+ priority: zPriority.optional(),
425
+ category: zCategory.optional(),
426
+ description: z.string().optional().describe('Optional test-case description / summary.'),
427
+ storyRef: z.string().optional().describe('Link this test case to a USER STORY — its id or business key (US_123, from story_list / ' +
428
+ 'story_get). Used when drafting MANUAL test cases for a story so they save linked to it.'),
429
+ folderOrModule: z.string().optional().describe('SimplifyQA-only: id of the MODULE / folder to file this test case under on save (from ' +
430
+ 'list_modules). ASK the user which module before drafting; SimplifyQA files test cases in ' +
431
+ 'a module tree. Walnut ignores this.'),
432
+ steps: z.array(zNewStep).optional(),
433
+ technologyType: z.string().optional().describe('SimplifyQA-only: the automation stack this test case targets — WEB | API | ANDROID | IOS | ' +
434
+ 'DATABASE | MAINFRAME | DESKTOP | SAP. REQUIRED when the draft is built only from FUNCTION ' +
435
+ 'calls (a function call carries no technology of its own); otherwise it is derived from the ' +
436
+ 'steps, or from the called functions\' fnType at save time.'),
437
+ executionPlatform: z.object({
438
+ id: z.string(), name: z.string(), technologyType: z.string(), type: z.string(),
439
+ cloudDeviceType: z.string().optional(),
440
+ }).optional().describe('SimplifyQA-only, ANDROID/IOS only: the device the test case targets — ' +
441
+ '{ id: <device serial>, name, technologyType: "ANDROID"|"IOS", type: "REAL_DEVICE"|"CLOUD_DEVICE" }. ' +
442
+ 'The backend rejects a mobile test case without it.'),
443
+ data: z.record(z.string(), z.string()).optional().describe('Default values for the `${name}` tokens in step descriptions — one entry per token. ' +
444
+ 'Populates the auto-created default test-data row (ITR-1) on save. Example: ' +
445
+ '`{ username: "admin", password: "admin123", url: "https://saucedemo.com" }`.'),
446
+ },
447
+ }, async ({ title, priority, category, description, storyRef, folderOrModule, steps, data, technologyType, executionPlatform }) => {
448
+ try {
449
+ const tc = {
450
+ title,
451
+ ...(priority ? { priority } : {}),
452
+ category: category ?? 'automated',
453
+ ...(description ? { description } : {}),
454
+ ...(storyRef ? { storyRef } : {}),
455
+ ...(folderOrModule ? { folderOrModule } : {}),
456
+ ...(technologyType ? { technologyType: technologyType.toUpperCase() } : {}),
457
+ ...(executionPlatform ? { executionPlatform } : {}),
458
+ ...(data ? { data } : {}),
459
+ // zod (zNewStep) is the runtime gate on shape; DraftStore.create
460
+ // assigns real step numbers regardless of what's passed here.
461
+ steps: (steps ?? []),
462
+ };
463
+ const draftId = deps.drafts.create(tc);
464
+ return draftResult(deps.drafts.get(draftId), await catalogFor());
465
+ }
466
+ catch (e) {
467
+ return err(describeError(e));
468
+ }
469
+ });
470
+ server.registerTool('tc_draft_update', {
471
+ title: 'Update a test-case draft',
472
+ description: 'Apply one or more ops (set_meta | add_step | update_step | remove_step | move_step | duplicate_step) to a draft. Steps renumber contiguously from 1 after every op.\n\n' +
473
+ 'To COPY a step ("add the same step 2 at the end") use duplicate_step { n, at? } — never rebuild it with add_step: duplicate_step clones the WHOLE step ' +
474
+ '(parameters and their values, object, flags, browser, API request, settings) so nothing is lost. For an IF / loop / function block pass `through` too (the last step of the block).\n\n' +
475
+ 'update_steps { where, patch } applies ONE patch to EVERY step matching `where` (numbers, from/to, stepType, actionType, object, descriptionContains, parameter) — use it for "skip every step that uses X"; an empty `where` is refused unless all:true. ' +
476
+ 'To change WHICH parameter a step uses, put `swapParams: [{ from, to, value? }]` in the step patch (it replaces the parameter in the SAME slot; `recordedParam` only adds). ' +
477
+ 'To edit a project parameter itself (Local <-> Runtime, default value) use parameter_update.\n' +
478
+ 'To change an API step IN PLACE (add an assertion, change the URL / a header / the body) use update_step with `patch.api`: it is MERGED into the saved request, ' +
479
+ 'so only what you pass changes. `api.addAssertions: [{ path, condition, expectedValue }]` appends assertions (e.g. path "statusCode", "$.body.id", "$.headers.X"); `api.assertions` replaces the whole list. ' +
480
+ 'NEVER remove_step + add_step to edit a step — that deletes it and creates a different one.\n\n' +
481
+ 'STEP TYPE — for add_step / update_step on a MANUAL test case (tc.category === "manual", or every existing step arrived with stepType "manual"), pass `stepType: "manual"`. ' +
482
+ 'For an AUTOMATED test case pick the execution technology ("web", "api", "android", …). ' +
483
+ 'Getting this wrong routes the row to the wrong UI card and it renders blank in the desktop viewer.\n\n' +
484
+ 'CALLING A SAVED FUNCTION — a function step is `{ stepType: "function", actionType: "function", description, functionCall: { testCaseId: "FN-12" } }` ' +
485
+ '(the numeric id also works). Its matching `function_end` row is generated automatically and the function\'s NEWEST version is pinned at save, so ' +
486
+ '"use these functions and create a new tc" is just one add_step per function in run order, then tc_save. Do NOT pass a real action name ' +
487
+ '(a function call has no action) and do NOT add `function_end` yourself.',
488
+ inputSchema: { draftId: z.string(), ops: z.array(zDraftOp).min(1) },
489
+ }, async ({ draftId, ops }) => {
490
+ try {
491
+ const draft = deps.drafts.applyOps(draftId, ops);
492
+ // Live-view fanout: emit one wire event per op so the Angular listener
493
+ // can apply position-only ops (DELETE/MOVE) surgically without a full
494
+ // reload. Shape-heavy ops (INSERT/UPDATE) currently log on the UI side
495
+ // pending Phase 1.5's step-shape mapper — see plan/tc-edit-live-protocol.md.
496
+ // set_meta has no wire event (§3 of the spec covers step-level only).
497
+ if (draft.sessionId) {
498
+ for (const op of ops) {
499
+ switch (op.op) {
500
+ case 'add_step':
501
+ void emitTcEdit(draft.sessionId, 'TC_EDIT_INSERT', { at: op.at, step: op.step });
502
+ break;
503
+ case 'update_step':
504
+ void emitTcEdit(draft.sessionId, 'TC_EDIT_UPDATE', { n: op.n, step: op.patch });
505
+ break;
506
+ case 'remove_step':
507
+ void emitTcEdit(draft.sessionId, 'TC_EDIT_DELETE', { n: op.n });
508
+ break;
509
+ case 'move_step':
510
+ void emitTcEdit(draft.sessionId, 'TC_EDIT_MOVE', { from: op.n, to: op.to });
511
+ break;
512
+ // set_meta, duplicate_step → no wire event; changes surface on next tc_save + reload
513
+ }
514
+ }
515
+ }
516
+ return draftResult(draft, await catalogFor());
517
+ }
518
+ catch (e) {
519
+ return err(describeError(e));
520
+ }
521
+ });
522
+ server.registerTool('tc_draft_get', {
523
+ title: 'Get a test-case draft',
524
+ description: 'Fetch a draft by id: readable steps table, validation summary, and the neutral TestCase.',
525
+ inputSchema: { draftId: z.string() },
526
+ annotations: { readOnlyHint: true },
527
+ }, async ({ draftId }) => {
528
+ try {
529
+ return draftResult(deps.drafts.get(draftId), await catalogFor());
530
+ }
531
+ catch (e) {
532
+ return err(describeError(e));
533
+ }
534
+ });
535
+ server.registerTool('tc_draft_discard', {
536
+ title: 'Discard a test-case draft',
537
+ description: 'Delete an in-memory draft. Nothing was ever persisted, so there is nothing else to undo.',
538
+ inputSchema: { draftId: z.string() },
539
+ }, async ({ draftId }) => {
540
+ try {
541
+ deps.drafts.delete(draftId);
542
+ return ok(`Discarded draft ${draftId}. Nothing was ever persisted.`);
543
+ }
544
+ catch (e) {
545
+ return err(describeError(e));
546
+ }
547
+ });
548
+ server.registerTool('tc_draft_open', {
549
+ title: 'Open a draft in the test-case editor',
550
+ description: "Show this draft in the product's real editor. Prefers the local agent's own native window when the agent is running; otherwise returns a link to open. The draft rides in the URL fragment -- nothing is uploaded, no backend call is made.",
551
+ inputSchema: {
552
+ draftId: z.string(),
553
+ frontendOrigin: z.string().optional(),
554
+ /** Set false to always return a link instead of using the agent window. */
555
+ useAgentWindow: z.boolean().optional(),
556
+ },
557
+ annotations: { readOnlyHint: true },
558
+ }, async ({ draftId, frontendOrigin, useAgentWindow }) => {
559
+ try {
560
+ const draft = deps.drafts.get(draftId);
561
+ const origin = frontendOrigin ?? deps.walnutUiOrigin ?? 'http://localhost:8080';
562
+ const url = buildEditorUrl(origin, draft);
563
+ const issues = validateTestCase(draft.tc, await catalogFor());
564
+ const summary = `Draft ${draft.draftId} · ${validationSummaryLine(draft.tc, issues)}`;
565
+ // Preferred path: the agent is Electron, so it can draw the editor in its
566
+ // own window -- no browser tab, and no need for the AI client to render UI.
567
+ // Any failure here is not an error for this tool: fall through to the link.
568
+ const openWindow = deps.openEditorWindow ?? ((u, t) => openInAgentWindowViaHttp(deps.agentUrl, u, t));
569
+ const openedInAgent = useAgentWindow === false ? false : await openWindow(url, draft.tc.title);
570
+ if (openedInAgent) {
571
+ return ok(`Opened "${draft.tc.title}" in the agent's editor window.\n\n${summary}\n\n` +
572
+ `If you would rather use a browser: ${url}`, { url, draftId: draft.draftId, openedIn: 'agent-window', tc: draft.tc });
573
+ }
574
+ return ok(`${url}\n\n` +
575
+ `Open this link to view "${draft.tc.title}" in the test-case editor -- nothing is uploaded, the draft rides in the URL fragment.\n\n` +
576
+ `${summary}`, { url, draftId: draft.draftId, openedIn: 'link', tc: draft.tc });
577
+ }
578
+ catch (e) {
579
+ return err(describeError(e));
580
+ }
581
+ });
582
+ server.registerTool('tc_edit_open', {
583
+ title: 'Open an existing test case for live prompt-driven step editing',
584
+ description: 'One-shot: hydrate an EXISTING test case as a draft, open it in the desktop TC-viewer window, ' +
585
+ 'and bind a live-edit session so subsequent tc_draft_update calls stream the changes into the ' +
586
+ 'window in real time (TC_EDIT_RESYNC on each op batch, per plan/tc-edit-live-protocol.md). ' +
587
+ '⚠️ THIS OPENS THE DESKTOP RECORDER/VIEWER WINDOW (scrcpy / SCRPY). Use it ONLY when the user ' +
588
+ 'explicitly wants to WATCH the edits live or asks to open the test case in the viewer. For a plain ' +
589
+ 'prompt like "add a step to TC N at step 3", "remove step 2", "change step 3" do NOT use it — call ' +
590
+ 'journal_modify({ tcId, ops:[{ op:"add_step", at, step }] }), which edits the saved test case directly ' +
591
+ 'with no window.\n\n' +
592
+ 'Returns { draftId, sessionId, tcId }. Follow up with tc_draft_update({ draftId, ops }) for edits ' +
593
+ 'and tc_save({ draftId }) to persist. Requires a live connection (qa_connect); the desktop app ' +
594
+ 'must be running on the same machine or the window-open call silently no-ops (the draft still ' +
595
+ 'mutates correctly — only the live view is lost).',
596
+ inputSchema: {
597
+ tcId: z.string().describe('The existing test-case id to open for editing.'),
598
+ hashRoute: z.string().optional().describe('Optional Angular hash route override, e.g. "#/user/testcase/details/593". Defaults to ' +
599
+ '"#/user/testcase/details/<numericTcId>" (matches the browser UI route). Pass this only if ' +
600
+ 'the product\'s testcase-details route differs from the default.'),
601
+ baseUrl: z.string().optional().describe('sqa-ui origin (defaults to whatever the desktop app is configured with).'),
602
+ accessToken: z.string().optional().describe('Bearer token forwarded to the desktop window for API calls.'),
603
+ userId: z.union([z.string(), z.number()]).optional(),
604
+ projectId: z.union([z.string(), z.number()]).optional(),
605
+ },
606
+ }, async ({ tcId, hashRoute, baseUrl, accessToken, userId, projectId }) => {
607
+ const adapter = deps.getAdapter?.();
608
+ if (!adapter) {
609
+ return err('Not connected to a product. Use qa_connect first — opening a real TC needs a live backend.');
610
+ }
611
+ let tc;
612
+ try {
613
+ tc = await adapter.getTestCase(tcId);
614
+ if (!tc.id)
615
+ tc.id = tcId;
616
+ }
617
+ catch (e) {
618
+ return err(`Could not fetch test case "${tcId}": ${describeError(e)}`);
619
+ }
620
+ // sessionId is our correlation key: (a) stamped on the draft so tc_draft_update knows where to
621
+ // fan out edits, (b) sent to Electron as the windowList key, (c) put in the URL query so the
622
+ // Angular renderer knows MCP owns edits (§6 of the wire spec). One id, three places.
623
+ const sessionId = `tc-edit-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
624
+ const draftId = deps.drafts.create(tc, sessionId);
625
+ const draft = deps.drafts.get(draftId);
626
+ // ponytail: fall back to the adapter's session context — the LLM has no way to know the
627
+ // bearer token, and without it the desktop app loads sqa-ui unauthenticated → skeleton
628
+ // loaders forever because API fetches 401. Caller args still win when explicitly provided.
629
+ const sess = (await adapter.getSessionContext?.()) ?? {};
630
+ const _baseUrl = baseUrl ?? sess.baseUrl;
631
+ const _accessToken = accessToken ?? sess.token;
632
+ const _userId = userId ?? sess.userId;
633
+ const _projectId = projectId ?? sess.projectId;
634
+ const opened = await openTcViewerWindow({
635
+ sessionId, tcId,
636
+ ...(hashRoute ? { hashRoute } : {}),
637
+ ...(_baseUrl ? { baseUrl: _baseUrl } : {}),
638
+ ...(_accessToken ? { accessToken: _accessToken } : {}),
639
+ ...(_userId !== undefined && _userId !== '' ? { userId: _userId } : {}),
640
+ ...(_projectId !== undefined && _projectId !== '' ? { projectId: _projectId } : {}),
641
+ });
642
+ // TC_EDIT_HELLO gives the UI its baseline. Skipped if the window didn't open — no consumer.
643
+ if (opened) {
644
+ void emitTcEdit(sessionId, 'TC_EDIT_HELLO', {
645
+ tcId, draftId, steps: draft.tc.steps,
646
+ });
647
+ }
648
+ const issues = validateTestCase(draft.tc, await catalogFor());
649
+ const summary = validationSummaryLine(draft.tc, issues);
650
+ const openedLine = opened
651
+ ? `Opened "${draft.tc.title}" in the desktop TC editor. Session ${sessionId}.`
652
+ : `Draft ${draftId} ready. Desktop app not reachable on this machine — edits will apply to the draft, but nothing will render live.`;
653
+ return ok(`${openedLine}\n\nDraft ${draft.draftId} · ${summary}\n\n${stepsMarkdown(draft.tc)}`, { draftId, sessionId, tcId, opened, tc: draft.tc, issues });
654
+ });
655
+ server.registerTool('tc_record_append', {
656
+ title: 'Record additional steps into a TC that is already open in the editor',
657
+ description: 'Start a live-browser recording session whose captured steps stream into the tc-viewer window ' +
658
+ 'bound by an earlier `tc_edit_open`. Each user interaction becomes a TC_EDIT_INSERT event in the ' +
659
+ 'editor. Returns instructions the model must follow (this tool itself does not touch the driver):\n' +
660
+ ' 1. `core_activate_technology({ technology:"WEB", mcpTcEditSessionId, testcaseName })` — starts ' +
661
+ ' the browser and binds captures to this window. The response `structuredContent.sessionId` is ' +
662
+ ' the RECORDING session id — remember it for step 3.\n' +
663
+ ' 2. Use `web_*` tools to drive the browser. Every captured step shows up live in the editor.\n' +
664
+ ' 3. When done, `tc_record_stop({ draftId, recordingSessionId })` reads the recording journal ' +
665
+ ' and appends the captured steps to the draft. Then `tc_save({ draftId })` to persist.\n\n' +
666
+ 'A DESKTOP test case gets a desktop guide instead: technology "DESKTOP", ' +
667
+ '`desktop_launch_application({ app_path })` first, then `desktop_snapshot` + `desktop_*` verbs.\n\n' +
668
+ 'The draft must have been opened via `tc_edit_open` first — its stored sessionId is what binds ' +
669
+ 'the recorder to the correct window.',
670
+ inputSchema: {
671
+ draftId: z.string().describe('The draft id from tc_edit_open.'),
672
+ },
673
+ }, async ({ draftId }) => {
674
+ let draft;
675
+ try {
676
+ draft = deps.drafts.get(draftId);
677
+ }
678
+ catch (e) {
679
+ return err(describeError(e));
680
+ }
681
+ if (!draft.sessionId) {
682
+ return err(`Draft "${draftId}" was not opened via tc_edit_open — no tc-viewer window is bound. ` +
683
+ 'Open it with tc_edit_open first, then call tc_record_append.');
684
+ }
685
+ // A DESKTOP test case records a Windows application, not a browser.
686
+ if ((draft.tc.technologyType ?? '').toUpperCase() === 'DESKTOP') {
687
+ const desktopGuide = `Recording will stream into the TC editor bound to session ${draft.sessionId}.\n\n` +
688
+ `1. core_activate_technology({ technology: "DESKTOP", mcpTcEditSessionId: "${draft.sessionId}", ` +
689
+ `testcaseName: "${draft.tc.title}" }) — response.structuredContent.sessionId is the RECORDING id.\n` +
690
+ `2. desktop_launch_application({ app_path: "<the application's full .exe path — ASK the user>" }) — must be ` +
691
+ `the first call. Ask the user to close the application first if it is open, and not to touch the mouse or ` +
692
+ `keyboard while you record.\n` +
693
+ `3. desktop_snapshot() for refs; desktop_click / desktop_enter_text / desktop_validate_text / etc. with { ref }. ` +
694
+ `After opening a right-click menu or a drop-down list: desktop_snapshot({ scope: "popups" }).\n` +
695
+ `4. core_close_session() when done recording.\n` +
696
+ `5. tc_record_stop({ draftId: "${draftId}", recordingSessionId: "<from step 1>" }) — append to draft.\n` +
697
+ `6. tc_save({ draftId: "${draftId}" }) — persist to the SAME test case, same version.`;
698
+ return ok(desktopGuide, { draftId, tcViewerSessionId: draft.sessionId, tcId: draft.tc.id });
699
+ }
700
+ const guide = `Recording will stream into the TC editor bound to session ${draft.sessionId}.\n\n` +
701
+ `1. core_activate_technology({ technology: "WEB", mcpTcEditSessionId: "${draft.sessionId}", ` +
702
+ `testcaseName: "${draft.tc.title}" }) — response.structuredContent.sessionId is the RECORDING id.\n` +
703
+ `2. web_launch_application({ url: "..." }) — must be the first browser call.\n` +
704
+ `3. web_snapshot() before each action; web_click / web_enter_text / web_validate_text / etc. to drive.\n` +
705
+ `4. core_close_session() when done recording.\n` +
706
+ `5. tc_record_stop({ draftId: "${draftId}", recordingSessionId: "<from step 1>" }) — append to draft.\n` +
707
+ `6. tc_save({ draftId: "${draftId}" }) — persist to the SAME test case, same version.`;
708
+ return ok(guide, { draftId, tcViewerSessionId: draft.sessionId, tcId: draft.tc.id });
709
+ });
710
+ server.registerTool('tc_record_stop', {
711
+ title: 'Append recorded steps to the draft after tc_record_append',
712
+ description: 'Read the recording journal for a session and add each captured step to the draft as an ' +
713
+ '`add_step` op. Pairs with `tc_record_append`. Follow with `tc_save({ draftId })` to persist.\n\n' +
714
+ 'CAVEAT: The recording journal is process-scoped and may contain steps from earlier recordings ' +
715
+ 'in the same Java-server process. Pass `fromIndex` to skip the first N steps if the journal ' +
716
+ 'accumulated prior state — usually the count of steps recorded before `tc_record_append` was called.',
717
+ inputSchema: {
718
+ draftId: z.string(),
719
+ recordingSessionId: z.string().describe('The session id from `core_activate_technology`\'s response.structuredContent.sessionId.'),
720
+ fromIndex: z.number().int().nonnegative().optional().describe('Optional: skip the first N steps in the journal (defaults to 0 = take all).'),
721
+ },
722
+ }, async ({ draftId, recordingSessionId, fromIndex }) => {
723
+ const adapter = deps.getAdapter?.();
724
+ if (!adapter) {
725
+ return err('Not connected to a product. Use qa_connect first — reading a journal needs a live agent.');
726
+ }
727
+ if (!adapter.readJournal) {
728
+ return err('This product has no recording journal.');
729
+ }
730
+ let draft;
731
+ try {
732
+ draft = deps.drafts.get(draftId);
733
+ }
734
+ catch (e) {
735
+ return err(describeError(e));
736
+ }
737
+ let view;
738
+ try {
739
+ view = await adapter.readJournal(recordingSessionId);
740
+ }
741
+ catch (e) {
742
+ return err(`Could not read journal for session "${recordingSessionId}": ${describeError(e)}`);
743
+ }
744
+ const skip = fromIndex ?? 0;
745
+ const toAppend = (view.steps ?? []).slice(skip);
746
+ if (toAppend.length === 0) {
747
+ return ok(`No new steps to append (journal had ${view.steps?.length ?? 0} steps, skipped ${skip}).`, { draftId, appended: 0, tc: draft.tc });
748
+ }
749
+ const ops = toAppend.map((step) => ({
750
+ op: 'add_step',
751
+ step: { ...step, n: undefined },
752
+ }));
753
+ try {
754
+ const updated = deps.drafts.applyOps(draftId, ops);
755
+ // The per-op TC_EDIT_INSERT events already streamed to the editor DURING recording;
756
+ // no re-emit here or the UI would double-render.
757
+ return ok(`Appended ${toAppend.length} recorded step(s) to draft ${draftId}. Call tc_save to persist.`, { draftId, appended: toAppend.length, tc: updated.tc });
758
+ }
759
+ catch (e) {
760
+ return err(describeError(e));
761
+ }
762
+ });
763
+ server.registerTool('tc_suggest_functions', {
764
+ title: 'Suggest existing functions for the recorded steps',
765
+ description: 'Call this RIGHT AFTER a recording finishes (before asking the user to save). It compares the ' +
766
+ "recorded steps with the project's existing reusable functions and returns the groups of steps " +
767
+ 'that already exist as a function. If it returns matches, show them to the user and ASK which ' +
768
+ 'function(s) to replace (all / some / none) — do not decide for them. Read-only: nothing changes. ' +
769
+ 'Pass EXACTLY ONE of `sessionId` (live/finished recording), `draftId`, or `tcId` (already saved).',
770
+ inputSchema: {
771
+ sessionId: z.string().optional().describe('Recording session id (core_activate_technology / core_active_recordings).'),
772
+ draftId: z.string().optional().describe('A draft id.'),
773
+ tcId: z.string().optional().describe('A saved test case id or business key. Matched on step IDs (actionId/objectId/stepType/technologyType + parameter names), not on display names.'),
774
+ versionId: z.string().optional().describe("For tcId only: which version's steps to match (an id from the TC's versions[]). Omit for the TC's currently-selected version; on a multi-version TC ASK the user first."),
775
+ minConfidence: z.enum(['exact', 'strong']).optional().describe("For tcId only. 'exact' (default) = same action/element AND the same parameter names; " +
776
+ "'strong' also accepts the same action/element with a different parameter set (a " +
777
+ 're-parameterised copy of the flow).'),
778
+ },
779
+ annotations: { readOnlyHint: true },
780
+ }, async ({ sessionId, draftId, tcId, versionId, minConfidence }) => {
781
+ const adapter = deps.getAdapter?.();
782
+ if (!adapter)
783
+ return err('Not connected to a product. Use qa_connect first.');
784
+ if ([sessionId, draftId, tcId].filter(Boolean).length !== 1) {
785
+ return err('Pass exactly one of sessionId, draftId or tcId.');
786
+ }
787
+ let steps = [];
788
+ let where;
789
+ let applyHint;
790
+ let matches = [];
791
+ try {
792
+ if (sessionId) {
793
+ if (!adapter.readJournal)
794
+ return err('This product has no recording journal.');
795
+ steps = ((await adapter.readJournal(sessionId)).steps ?? []).map(normalizeJournalStep);
796
+ where = 'the recording';
797
+ applyHint = `Replace/some → save with tc_save({ sessionId: "${sessionId}", replaceWithFunctions: true | ["<function id>", …] }) ` +
798
+ 'once the user asks to save; if they already saved from the recorder window, use tc_replace_with_functions on the saved TC instead.';
799
+ }
800
+ else if (draftId) {
801
+ steps = deps.drafts.get(draftId).tc.steps ?? [];
802
+ where = 'the draft';
803
+ applyHint = `Replace/some → tc_save({ draftId: "${draftId}", replaceWithFunctions: true | ["<function id>", …] }) once the user asks to save.`;
804
+ }
805
+ else {
806
+ where = `test case ${tcId}`;
807
+ applyHint = `Replace/some → tc_replace_with_functions({ tcId: "${tcId}", functionIds: ["<function id>", …] }) (omit functionIds for all), ` +
808
+ 'or name the exact range with replace: [{ fnId: "<id>", stepSeqs: [<seq>, …] }].';
809
+ }
810
+ if (sessionId || draftId) {
811
+ matches = await findFunctionMatches(adapter, steps);
812
+ }
813
+ else {
814
+ // Identity-based: actionId/objectId/stepType/technologyType + parameter names.
815
+ matches = await findFunctionCandidatesForTc(adapter, tcId, {
816
+ ...(versionId !== undefined ? { versionId } : {}),
817
+ ...(minConfidence !== undefined ? { minConfidence } : {}),
818
+ });
819
+ // Provider without raw-step access → fall back to the name-based matcher.
820
+ if (!matches.length) {
821
+ steps = (await adapter.getTestCase(tcId)).steps ?? [];
822
+ matches = await findFunctionMatches(adapter, steps);
823
+ }
824
+ }
825
+ }
826
+ catch (e) {
827
+ return err(describeError(e));
828
+ }
829
+ if (!matches.length) {
830
+ return ok('No recorded steps match an existing function — nothing to replace; continue the normal flow.', { matches: [] });
831
+ }
832
+ return ok(suggestionText(matches, where, applyHint), { matches });
833
+ });
834
+ server.registerTool('tc_suggest_function_groups', {
835
+ title: 'Suggest functions for the steps just recorded (create + replace)',
836
+ description: 'THE post-recording step: call this as soon as a recording finishes and BEFORE asking the user to save. ' +
837
+ 'It returns BOTH kinds of suggestion in one answer: ' +
838
+ '`replace` — blocks of recorded steps that already exist as a reusable function (offer to swap them for ' +
839
+ 'a call to that function), and `create` — contiguous blocks that are good candidates for a NEW reusable ' +
840
+ 'function (offer to extract them). Read-only: nothing is created, replaced or saved. ' +
841
+ 'Show both lists and ASK the user per block: create as a new function (ask for the name) / replace with ' +
842
+ 'the existing FN-x / keep as recorded. Apply AFTER the test case is saved (tc_steps_to_function with ' +
843
+ 'replaceInSource:true, or tc_replace_with_functions). ' +
844
+ 'Pass EXACTLY ONE of `sessionId` (a finished recording), `draftId`, or `tcId` (already saved).',
845
+ inputSchema: {
846
+ sessionId: z.string().optional().describe('Recording session id (core_activate_technology / core_active_recordings).'),
847
+ draftId: z.string().optional().describe('A draft id (tc_draft_from_journal / tc_draft_from_tc / tc_draft_create).'),
848
+ tcId: z.string().optional().describe('A saved test case id or business key.'),
849
+ versionId: z.string().optional().describe('For tcId only: which version to analyse (an id from the TC versions[]).'),
850
+ groupSize: z.number().int().min(3).max(20).optional().describe('Target steps per proposed new function. Default 6, minimum 3.'),
851
+ },
852
+ annotations: { readOnlyHint: true },
853
+ }, async ({ sessionId, draftId, tcId, versionId, groupSize }) => {
854
+ const adapter = deps.getAdapter?.();
855
+ if (!adapter)
856
+ return err('Not connected to a product. Use qa_connect first.');
857
+ if ([sessionId, draftId, tcId].filter(Boolean).length !== 1) {
858
+ return err('Pass exactly one of sessionId, draftId or tcId.');
859
+ }
860
+ let steps = [];
861
+ let matches = [];
862
+ let where;
863
+ try {
864
+ if (sessionId) {
865
+ if (!adapter.readJournal)
866
+ return err('This product has no recording journal.');
867
+ steps = ((await adapter.readJournal(sessionId)).steps ?? []).map(normalizeJournalStep);
868
+ where = 'the recording';
869
+ }
870
+ else if (draftId) {
871
+ steps = deps.drafts.get(draftId).tc.steps ?? [];
872
+ where = 'the draft';
873
+ }
874
+ else {
875
+ where = `test case ${tcId}`;
876
+ matches = await findFunctionCandidatesForTc(adapter, tcId, {
877
+ ...(versionId !== undefined ? { versionId } : {}),
878
+ });
879
+ steps = (await adapter.getTestCase(tcId)).steps ?? [];
880
+ }
881
+ if (sessionId || draftId)
882
+ matches = await findFunctionMatches(adapter, steps);
883
+ }
884
+ catch (e) {
885
+ return err(describeError(e));
886
+ }
887
+ // Steps already covered by an existing-function match are not proposed again as new groups.
888
+ const covered = new Set();
889
+ for (const m of matches)
890
+ for (const n of m.stepNs)
891
+ covered.add(n);
892
+ const groups = proposeFunctionGroups(steps, { ...(groupSize !== undefined ? { groupSize } : {}), exclude: covered });
893
+ if (!matches.length && !groups.length) {
894
+ return ok(`Nothing to suggest for ${where}: no recorded block matches an existing function and there is no run of ` +
895
+ `${'3+'} consecutive steps worth extracting. Continue the normal flow (review + save).`, { replace: [], create: [] });
896
+ }
897
+ const lines = [`NOTHING HAS CHANGED — suggestions only for ${where}. Ask the user, then apply.`];
898
+ if (matches.length) {
899
+ lines.push('', 'ALREADY EXIST AS A FUNCTION — offer to replace:');
900
+ for (const m of matches) {
901
+ const label = [m.fnCode, m.fnName].filter(Boolean).join(' — ') || m.fnId;
902
+ lines.push(` • steps ${m.stepNs[0]}–${m.stepNs[m.stepNs.length - 1]} (${m.length} steps) → ${label} (id ${m.fnId})`);
903
+ }
904
+ }
905
+ if (groups.length) {
906
+ lines.push('', 'COULD BECOME A NEW FUNCTION — offer to extract:');
907
+ for (const g of groups) {
908
+ lines.push(` • steps ${g.fromSeq}–${g.toSeq} (${g.stepCount} steps) — suggested name "${g.suggestedName}"`);
909
+ }
910
+ }
911
+ lines.push('', 'ASK the user, per block: "create a new function (name?)", "replace with FN-x", or "keep as is". Do NOT decide for them.', 'APPLY AFTER THE TEST CASE IS SAVED (both need a saved tcId):', ' • create → tc_steps_to_function({ tcId, stepSeqs, name, moduleId, replaceInSource: true }) — saves the function AND leaves a function call in its place.', ' • replace → tc_replace_with_functions({ tcId, replace: [{ fnId, stepSeqs }] }).');
912
+ return ok(lines.join('\n'), { replace: matches, create: groups });
913
+ });
914
+ server.registerTool('tc_replace_with_functions', {
915
+ title: 'Replace steps of a SAVED test case with existing functions',
916
+ description: 'After the user has chosen (from tc_suggest_functions) which functions to use, swap the matching ' +
917
+ 'steps of an already-saved test case for a call to each chosen function. Use this when the user ' +
918
+ 'saved from the recorder window; if the recording is not saved yet, pass the choice to tc_save ' +
919
+ "instead. `functionIds` = the user's picks; omit for all matches. The replaced steps' own testdata " +
920
+ "is dropped and the function's default iterations are used. ONLY call after the user said yes.",
921
+ inputSchema: {
922
+ tcId: z.string().describe('Saved test case id or business key.'),
923
+ functionIds: z.array(z.string()).optional().describe('Function ids to apply (from tc_suggest_functions). Omit = all matches.'),
924
+ replace: z.array(z.object({
925
+ fnId: z.string().describe('Function id (FN_12 / numeric).'),
926
+ stepSeqs: z.array(z.number().int().positive()).min(1).describe('The `seq`s of the test case steps to swap for this function — use this when the user names the ' +
927
+ 'function AND the range. Must be contiguous.'),
928
+ })).optional().describe('Explicit picks: replace exactly these seqs with these functions, skipping the matcher. Takes ' +
929
+ 'precedence over functionIds. This is the "use FN-12 for steps 3-6" path.'),
930
+ versionId: z.string().optional().describe('Version to edit (an id from the TC versions[]). Omit for the current version.'),
931
+ },
932
+ annotations: { readOnlyHint: false },
933
+ }, async ({ tcId, functionIds, replace, versionId }) => {
934
+ const adapter = deps.getAdapter?.();
935
+ if (!adapter)
936
+ return err('Not connected to a product. Use qa_connect first.');
937
+ // Explicit "use THIS function for THESE steps" — no matching needed.
938
+ if (replace && replace.length) {
939
+ if (!adapter.replaceStepsWithExistingFunction) {
940
+ return err('This provider cannot swap steps for a function call.');
941
+ }
942
+ const notes = [];
943
+ for (const pick of replace) {
944
+ const lo = Math.min(...pick.stepSeqs);
945
+ const hi = Math.max(...pick.stepSeqs);
946
+ try {
947
+ await adapter.replaceStepsWithExistingFunction(tcId, {
948
+ functionId: pick.fnId,
949
+ stepSeqs: [...pick.stepSeqs].sort((a, b) => a - b),
950
+ ...(versionId !== undefined ? { versionId } : {}),
951
+ });
952
+ notes.push(`replaced steps ${lo}–${hi} with function ${pick.fnId}`);
953
+ }
954
+ catch (e) {
955
+ notes.push(`⚠️ could not replace steps ${lo}–${hi} with ${pick.fnId}: ${describeError(e)}`);
956
+ }
957
+ }
958
+ return ok(`Test case ${tcId}. Function reuse: ${notes.join('; ')}.`, { tcId });
959
+ }
960
+ let steps;
961
+ try {
962
+ steps = (await adapter.getTestCase(tcId)).steps ?? [];
963
+ }
964
+ catch (e) {
965
+ return err(`Could not read test case "${tcId}": ${describeError(e)}`);
966
+ }
967
+ // Prefer the ID-based matcher; fall back to the name-based one for providers without it.
968
+ let matches = await findFunctionCandidatesForTc(adapter, tcId, {
969
+ ...(versionId !== undefined ? { versionId } : {}),
970
+ minConfidence: 'strong',
971
+ });
972
+ if (!matches.length) {
973
+ matches = await findFunctionMatches(adapter, steps, functionIds ? new Set(functionIds.map(String)) : undefined);
974
+ }
975
+ const wantedIds = functionIds ? functionIds.map(String) : undefined;
976
+ matches = selectMatches(matches, functionIds ?? true);
977
+ const missing = wantedIds ? wantedIds.filter((id) => !matches.some((m) => String(m.fnId) === id)) : [];
978
+ if (!matches.length) {
979
+ return err(`No steps in ${tcId} match the chosen function(s) — nothing replaced.` +
980
+ (missing.length ? ` Could not locate: ${missing.join(', ')}.` : ''));
981
+ }
982
+ const note = await replaceMatchedRuns(adapter, tcId, matches, {
983
+ trustSeqs: true,
984
+ ...(versionId !== undefined ? { versionId } : {}),
985
+ });
986
+ // Never report a bare success when part of the user's choice could not be applied.
987
+ const partial = missing.length
988
+ ? `\n⚠️ NOT replaced (no matching steps found in this test case): ${missing.join(', ')}. ` +
989
+ 'Pass `replace: [{ fnId, stepSeqs }]` to force an exact range, or re-run the suggestion.'
990
+ : '';
991
+ return ok(`Test case ${tcId}.${note}${partial}`, { tcId, ...(missing.length ? { missing } : {}) });
992
+ });
993
+ server.registerTool('tc_save', {
994
+ title: 'Save a draft or a live recording',
995
+ description: 'Persist a test case to the connected product. Pass EXACTLY ONE of:\n' +
996
+ ' • `draftId` — validate and save a draft (create, or update when the draft carries an id).\n' +
997
+ ' • `sessionId` — save a LIVE/RECENT recording by asking the /mcp-recorder window to click ' +
998
+ 'its OWN Save button. This is the exact-parity path: the recorder editor saves the steps, ' +
999
+ 'objects, parameters, control flow, functions, API popup values and title/module/story that ' +
1000
+ 'the user is looking at, including edits made in the window. The recorder window must be ' +
1001
+ 'open; it stays open for review after saving. Returns the created test case id + deep link.\n' +
1002
+ 'Requires a live connection (qa_connect).\n' +
1003
+ 'EXCEPTION — API recordings: after the LAST `api_send_request`, call this ONCE with the sessionId ' +
1004
+ 'WITHOUT asking, so the recorded API test case is persisted and searchable immediately (the user ' +
1005
+ 'must not have to click Send and Save first). Only once per recording; never per request.\n' +
1006
+ '⚠️ OTHERWISE CALL ONLY ON AN EXPLICIT USER SAVE INSTRUCTION (e.g. "save it", "save this", "persist it"). ' +
1007
+ 'RECORDING or AUTHORING a test case is NOT a save instruction; neither is the user approving the ' +
1008
+ 'content ("looks good", "nice"). After a recording/draft finishes, SHOW the steps and ASK — do NOT ' +
1009
+ 'auto-save. When unsure whether a reply meant save, ASK rather than saving. Never save a recording ' +
1010
+ 'TWICE (UI Save + tc_save): if the user already clicked Save in the recorder, treat it as done.',
1011
+ inputSchema: {
1012
+ draftId: z.string().optional().describe('Draft id from tc_draft_create / tc_draft_open. Omit when saving a live recording.'),
1013
+ sessionId: z.string().optional().describe('Recording session id from core_activate_technology (or core_active_recordings). Saves via the recorder window\'s own Save button.'),
1014
+ allowDuplicate: z.boolean().optional().describe('Set true ONLY after the user confirms they want a new test case with the same name as an existing one. Default: a new test case whose name already exists is saved as name_1, name_2, ….'),
1015
+ replaceWithFunctions: z.union([z.boolean(), z.array(z.string())]).optional().describe("Function reuse. Before saving, the steps are compared with the project's existing functions. If " +
1016
+ 'some already exist as a function and this is OMITTED, the tool does NOT save — it returns the ' +
1017
+ 'matches and you MUST ASK the user "replace with the existing function(s)?". Then call again with ' +
1018
+ 'true (replace ALL matches), an array of function ids (replace only those — the user picked some), or ' +
1019
+ 'false (save as recorded, the normal flow). Never choose for the user. No matches → saves normally ' +
1020
+ 'and this is ignored. tc_suggest_functions shows the same matches right after recording.'),
1021
+ copyTestdataFrom: z.string().optional().describe('Optional source TC id (or TC code). After the recording is saved, copy that TC\'s default-' +
1022
+ 'iteration testdata onto the new test case, matching parameters BY NAME. Use this when ' +
1023
+ 'converting a manual TC (tc_automate) so the converted TC keeps the manual testdata instead ' +
1024
+ 'of the values typed during recording. Omit for a normal recording.'),
1025
+ },
1026
+ annotations: { readOnlyHint: false },
1027
+ }, async ({ draftId, sessionId, allowDuplicate, copyTestdataFrom, replaceWithFunctions }) => {
1028
+ const adapter = deps.getAdapter?.();
1029
+ if (!adapter) {
1030
+ return err('Not connected to a product. Use qa_connect first — saving persists to the backend.');
1031
+ }
1032
+ if (!!draftId === !!sessionId) {
1033
+ return err('Pass exactly one of draftId (save a draft) or sessionId (save a live recording via the recorder window).');
1034
+ }
1035
+ if (sessionId) {
1036
+ if (!adapter.callRaw) {
1037
+ return err('Saving a live recording needs a local recorder agent. Use qa_connect with an agent, or save a draft with draftId.');
1038
+ }
1039
+ // Function reuse: offer to swap already-existing functions in for the recorded steps. Skipped
1040
+ // when the user already said no; a failed lookup never blocks the save.
1041
+ let fnMatches = [];
1042
+ if (replaceWithFunctions !== false && adapter.readJournal) {
1043
+ try {
1044
+ const view = await adapter.readJournal(sessionId);
1045
+ fnMatches = await findFunctionMatches(adapter, (view.steps ?? []).map(normalizeJournalStep));
1046
+ }
1047
+ catch { /* no journal / lookup failed — save normally */ }
1048
+ if (fnMatches.length && replaceWithFunctions === undefined) {
1049
+ return err(askReplaceText(fnMatches, `Then call tc_save again with sessionId: "${sessionId}".`));
1050
+ }
1051
+ }
1052
+ let res;
1053
+ let recorderError = null;
1054
+ // Existing-TC target (story sync): if the recording was opened against a declared test case,
1055
+ // a journal fallback must create a NEW VERSION of it rather than a separate test case.
1056
+ let recordingTarget;
1057
+ try {
1058
+ const ctxRes = (await adapter.callRaw('core_active_recordings', {}));
1059
+ const rec = ctxRes?.structuredContent?.recordings?.[0];
1060
+ if (rec && typeof rec['testcaseId'] === 'string' && rec['testcaseId']) {
1061
+ recordingTarget = {
1062
+ testcaseId: String(rec['testcaseId']),
1063
+ ...(rec['versionId'] ? { versionId: String(rec['versionId']) } : {}),
1064
+ ...(rec['versionName'] ? { versionName: String(rec['versionName']) } : {}),
1065
+ ...(rec['saveMode'] ? { saveMode: String(rec['saveMode']) } : {}),
1066
+ copyTestdata: rec['copyTestdata'] !== false,
1067
+ ...(rec['append'] === true || rec['append'] === 'true' ? { append: true } : {}),
1068
+ };
1069
+ }
1070
+ }
1071
+ catch { /* no context — normal create */ }
1072
+ // APPEND MODE — the recording was opened against an existing test case with append=true
1073
+ // (core_activate_technology({ testcaseId, append:true })). The recorded steps must be ADDED to
1074
+ // that test case: not a new TC, not a new version, and the existing steps must survive.
1075
+ // The session/window stay open, so further steps can be appended by another tc_save.
1076
+ if (recordingTarget?.testcaseId && recordingTarget.append
1077
+ && adapter.readJournal && adapter.getTestCase && adapter.updateTestCase) {
1078
+ try {
1079
+ const view = await adapter.readJournal(sessionId);
1080
+ const steps = (view?.steps ?? []).map(normalizeJournalStep);
1081
+ if (!steps.length) {
1082
+ return ok(`Nothing to append yet — recording ${sessionId} has no captured steps.`, {
1083
+ saved: { id: recordingTarget.testcaseId, via: 'append', appended: 0 },
1084
+ });
1085
+ }
1086
+ const targetTc = await adapter.getTestCase(recordingTarget.testcaseId);
1087
+ const before = targetTc.steps?.length ?? 0;
1088
+ targetTc.steps = [...(targetTc.steps ?? []), ...steps];
1089
+ const ref = await adapter.updateTestCase(String(targetTc.id ?? recordingTarget.testcaseId), targetTc);
1090
+ // The window is still open and wrote nothing — it still shows the pre-append step list.
1091
+ // Ask it to re-read the test case so the user sees the steps the save just stored.
1092
+ await refreshRecorderWindow(sessionId);
1093
+ // Clear the LIVE steps (recorder window + journal) so the next Save appends only new ones.
1094
+ // The tool's argument is `numbers` (1-based step numbers), and it needs confirm:true.
1095
+ let cleared = false;
1096
+ try {
1097
+ await adapter.callRaw('core_remove_steps', {
1098
+ sessionId,
1099
+ numbers: steps.map((_, i) => i + 1),
1100
+ confirm: true,
1101
+ });
1102
+ const after = (await adapter.callRaw('core_active_recordings', {}));
1103
+ cleared = Number(after?.structuredContent?.recordings?.[0]?.['stepCount'] ?? 0) === 0;
1104
+ }
1105
+ catch { /* fall through to the warning below */ }
1106
+ return ok(`Appended ${steps.length} step(s) to ${recordingTarget.testcaseId} ` +
1107
+ `(now ${before + steps.length} steps). The recording stays open for more steps.` +
1108
+ (cleared ? '' :
1109
+ '\n⚠️ The live steps could not be cleared from the recorder window — close/dispose that ' +
1110
+ 'window before adding more, otherwise the next save re-appends them.'), {
1111
+ saved: {
1112
+ id: ref.id ?? recordingTarget.testcaseId,
1113
+ via: 'append',
1114
+ appended: steps.length,
1115
+ stepCount: before + steps.length,
1116
+ },
1117
+ });
1118
+ }
1119
+ catch (e) {
1120
+ return err(`Could not append the recorded steps to ${recordingTarget.testcaseId}: ${describeError(e)}`);
1121
+ }
1122
+ }
1123
+ try {
1124
+ res = await adapter.callRaw('core_save_session', { sessionId, timeoutMs: 60000 });
1125
+ }
1126
+ catch (e) {
1127
+ recorderError = describeError(e);
1128
+ }
1129
+ const r = res;
1130
+ const saved = r?.structuredContent?.saved;
1131
+ const id = saved?.tcId ?? saved?.id;
1132
+ if (id == null) {
1133
+ const why = recorderError
1134
+ ?? (r?.isError ? firstText(res) : firstText(res) || 'recorder returned no test case id');
1135
+ // Fallback: the recorder's own Save is unavailable in this build (it answers
1136
+ // "recorder save request failed: null"). Persist the journal straight to the backend so
1137
+ // the steps AND their parameters / default test-data row are written instead of lost.
1138
+ let fallbackError;
1139
+ try {
1140
+ const fb = await saveJournalFallback(adapter, sessionId, recordingTarget, recordingName(sessionId));
1141
+ if (fb) {
1142
+ const fbLink = fb.productUrl ? `\n${fb.productUrl}` : '';
1143
+ let fbCopy = '';
1144
+ if (copyTestdataFrom && adapter.copyTestdata) {
1145
+ try {
1146
+ const c = await adapter.copyTestdata({ fromTcId: copyTestdataFrom, toTcId: fb.id });
1147
+ fbCopy = `\nTestdata copied from ${copyTestdataFrom}: ${c.copied} value(s)` +
1148
+ (c.skipped.length ? `; skipped (no matching parameter): ${c.skipped.join(', ')}` : '') + '.';
1149
+ }
1150
+ catch (e) {
1151
+ fbCopy = `\n⚠️ Testdata copy from ${copyTestdataFrom} failed: ${describeError(e)}.`;
1152
+ }
1153
+ }
1154
+ const fbFormula = fb.formulasApplied
1155
+ ? `\n${fb.formulasApplied} formula(s) were applied to the default test-data row.` +
1156
+ (fb.formulaSkipped?.length ? ` Skipped: ${fb.formulaSkipped.join('; ')}.` : '')
1157
+ : '';
1158
+ return ok((fb.versionName
1159
+ ? `Created ${fb.versionName} of ${recordingTarget?.testcaseId ?? 'the test case'} from the recording journal — the recorder's own Save was unavailable (${why}). `
1160
+ : `Created test case ${fb.id} from the recording journal — the recorder's own Save was unavailable (${why}). `) +
1161
+ `Parameters and test data were rebuilt from the journal's recorded values.${fbLink}${fbCopy}${fbFormula}`, {
1162
+ saved: {
1163
+ id: fb.id,
1164
+ ...(fb.productUrl ? { productUrl: fb.productUrl } : {}),
1165
+ ...(fb.versionName ? { versionName: fb.versionName } : {}),
1166
+ via: 'journal',
1167
+ ...(fb.formulasApplied !== undefined ? { formulasApplied: fb.formulasApplied } : {}),
1168
+ },
1169
+ });
1170
+ }
1171
+ }
1172
+ catch (e) {
1173
+ fallbackError = describeError(e); // reported with the recorder's error, not swallowed
1174
+ }
1175
+ return err(`Recorder save failed: ${why}` +
1176
+ (fallbackError ? `\nSaving from the recording journal failed too: ${fallbackError}` : ''));
1177
+ }
1178
+ const code = saved?.code != null ? String(saved.code) : String(id);
1179
+ const verb = saved?.created === false ? 'Updated' : 'Created';
1180
+ const savedVersion = typeof saved?.versionName === 'string' ? saved.versionName : undefined;
1181
+ const versionNote = savedVersion ? ` as ${savedVersion}` : '';
1182
+ const productUrl = typeof saved?.productUrl === 'string' ? saved.productUrl : undefined;
1183
+ const link = productUrl ? `\n${productUrl}` : '';
1184
+ // tc_automate: make the converted TC's testdata come strictly from the SOURCE manual TC,
1185
+ // overwriting whatever values the recording typed. Best-effort — the save already succeeded.
1186
+ let copyNote = '';
1187
+ if (copyTestdataFrom) {
1188
+ if (!adapter.copyTestdata) {
1189
+ copyNote = `\n⚠️ Testdata was NOT copied from ${copyTestdataFrom}: this provider has no testdata store.`;
1190
+ }
1191
+ else {
1192
+ try {
1193
+ const c = await adapter.copyTestdata({ fromTcId: copyTestdataFrom, toTcId: String(id) });
1194
+ copyNote = `\nTestdata copied from ${copyTestdataFrom}: ${c.copied} value(s)` +
1195
+ (c.skipped.length ? `; skipped (no matching parameter): ${c.skipped.join(', ')}` : '') + '.';
1196
+ }
1197
+ catch (e) {
1198
+ copyNote = `\n⚠️ Testdata copy from ${copyTestdataFrom} failed: ${describeError(e)}. ` +
1199
+ 'The test case was saved; copy the testdata manually.';
1200
+ }
1201
+ }
1202
+ }
1203
+ const chosenMatches = selectMatches(fnMatches, replaceWithFunctions);
1204
+ const fnNote = chosenMatches.length ? await replaceMatchedRuns(adapter, String(id), chosenMatches) : '';
1205
+ // The recorder window stamps the recorded formulas onto the default testdata iteration before
1206
+ // answering; report how many landed so a save that silently skipped them is visible.
1207
+ const formulasApplied = Number(saved?.formulasApplied ?? 0);
1208
+ const formulaNote = formulasApplied > 0
1209
+ ? `\n${formulasApplied} recorded formula(s) applied to the default test-data iteration.`
1210
+ : '';
1211
+ return ok(`${verb} test case ${code}${versionNote}.${link}${copyNote}${fnNote}${formulaNote}`, {
1212
+ saved: {
1213
+ id: String(id),
1214
+ ...(productUrl ? { productUrl } : {}),
1215
+ ...(copyTestdataFrom ? { copyTestdataFrom } : {}),
1216
+ ...(formulasApplied > 0 ? { formulasApplied } : {}),
1217
+ ...(savedVersion ? { versionName: savedVersion } : {}),
1218
+ },
1219
+ });
1220
+ }
1221
+ if (!draftId) {
1222
+ return err('Pass exactly one of draftId or sessionId.');
1223
+ }
1224
+ let draft;
1225
+ try {
1226
+ draft = deps.drafts.get(draftId);
1227
+ }
1228
+ catch {
1229
+ return err(`No draft "${draftId}". Author one with tc_draft_create, or open an existing test case with tc_draft_open.`);
1230
+ }
1231
+ const issues = validateTestCase(draft.tc, await catalogFor());
1232
+ if (issues.length) {
1233
+ const detail = issues.map((i) => `- step ${i.step ?? '-'}${i.field ? ` (${i.field})` : ''}: ${i.msg}`).join('\n');
1234
+ return err(`Cannot save "${draft.tc.title}" — ${issues.length} validation issue(s):\n${detail}`);
1235
+ }
1236
+ const isCreate = !draft.tc.id;
1237
+ if (isCreate && !(draft.tc.steps ?? []).length) {
1238
+ // An empty draft posts nothing and the backend answers without an id — the call used to
1239
+ // report "created" while persisting nothing. Say so instead.
1240
+ return err(`Cannot save "${draft.tc.title}" — the draft has no steps, so there is nothing to persist. ` +
1241
+ `Add steps with tc_draft_update ({ op: "add_step" }) first, then save. ` +
1242
+ `(To build a test case out of saved functions, add one step per function: ` +
1243
+ `{ op: "add_step", step: { description, actionType: "function", stepType: "function", ` +
1244
+ `functionCall: { testCaseId: "FN-12" } } } — its FUNCTION_END is added automatically.)`);
1245
+ }
1246
+ let draftFnMatches = [];
1247
+ if (replaceWithFunctions !== false && draft.tc.category === 'automated') {
1248
+ draftFnMatches = await findFunctionMatches(adapter, draft.tc.steps ?? []);
1249
+ if (draftFnMatches.length && replaceWithFunctions === undefined) {
1250
+ return err(askReplaceText(draftFnMatches, `Then call tc_save again with draftId: "${draftId}".`));
1251
+ }
1252
+ }
1253
+ if (isCreate && adapter.listModules && !draft.tc.folderOrModule) {
1254
+ // No module chosen: file it under the project's "Default Module" (what the UI's form pre-selects)
1255
+ // when there is one. Only if there is none do we fall back to asking the user.
1256
+ try {
1257
+ const dflt = (await adapter.listModules()).find((m) => m.name?.trim().toLowerCase() === 'default module');
1258
+ // Mutate the stored draft directly: applyOps would drop its recorder sessionId.
1259
+ if (dflt?.id)
1260
+ draft.tc = { ...draft.tc, folderOrModule: dflt.id };
1261
+ }
1262
+ catch { /* lookup failed — fall through to asking */ }
1263
+ }
1264
+ if (isCreate && adapter.listModules && !draft.tc.folderOrModule) {
1265
+ return err(`Cannot save "${draft.tc.title}" — SimplifyQA files every test case under a module. ` +
1266
+ 'Call list_modules, ASK the user which module to file this test case under, then ' +
1267
+ `tc_draft_update({ draftId: "${draftId}", ops: [{ op: "set_meta", patch: { folderOrModule: "<module id>" } }] }) ` +
1268
+ 'before retrying tc_save.');
1269
+ }
1270
+ let renamedFrom;
1271
+ if (isCreate && !allowDuplicate) {
1272
+ // A name that already exists is auto-suffixed (name_1, name_2, …) rather than saved as a
1273
+ // duplicate. Best-effort: a failed lookup must not block the save.
1274
+ try {
1275
+ const base = draft.tc.title.trim();
1276
+ const hits = await adapter.listTestCases({ search: base, limit: 200 });
1277
+ const taken = new Set(hits.map((t) => t.title.trim().toLowerCase()));
1278
+ if (taken.has(base.toLowerCase())) {
1279
+ let n = 1;
1280
+ while (taken.has(`${base}_${n}`.toLowerCase()))
1281
+ n++;
1282
+ // Mutate the stored draft directly: applyOps would drop its recorder sessionId.
1283
+ draft.tc = { ...draft.tc, title: `${base}_${n}` };
1284
+ renamedFrom = base;
1285
+ }
1286
+ }
1287
+ catch {
1288
+ // lookup failed — fall through to save
1289
+ }
1290
+ }
1291
+ {
1292
+ const missing = [];
1293
+ const data = draft.tc.data ?? {};
1294
+ for (const s of draft.tc.steps ?? []) {
1295
+ for (const m of (s.description ?? '').matchAll(/\$\{([A-Za-z0-9_]+)\}/g)) {
1296
+ const name = m[1];
1297
+ const hasData = Object.prototype.hasOwnProperty.call(data, name) && data[name] !== '';
1298
+ const hasStepValue = draft.tc.category !== 'manual' && s.value !== undefined && s.value !== '';
1299
+ if (!hasData && !hasStepValue)
1300
+ missing.push({ n: s.n, name });
1301
+ }
1302
+ }
1303
+ if (missing.length) {
1304
+ const uniqueNames = [...new Set(missing.map((m) => m.name))];
1305
+ const perStep = missing.map((m) => `step ${m.n}: \${${m.name}}`).join(', ');
1306
+ return err(`Cannot save "${draft.tc.title}" — these step tokens have no resolvable value: ${perStep}. ` +
1307
+ 'Every `${name}` token needs either a default in the TC\'s `data` map, or (for automated/' +
1308
+ 'playwright steps) a `value` set on that step — otherwise the parameter gets bound with ' +
1309
+ 'nothing to resolve at execution. Update the draft: ' +
1310
+ `tc_draft_update({ draftId: "${draftId}", ops: [{ op: "set_meta", patch: { data: { ${uniqueNames.map((n) => `${n}: "<value>"`).join(', ')} } } }] }) ` +
1311
+ 'then retry tc_save.');
1312
+ }
1313
+ }
1314
+ if (draft.tc.category === 'automated') {
1315
+ // Every automation step needs a canonical actionType name + a stepType (technology). Without
1316
+ // these the adapter's resolveAutomationSteps throws deep inside the multipart POST — cryptic
1317
+ // for the caller. objectRef presence is action-dependent (launch has none, click needs one),
1318
+ // so we leave that check to the resolver which has the catalog and knows objectRequired.
1319
+ const stepIssues = [];
1320
+ (draft.tc.steps ?? []).forEach((s, i) => {
1321
+ if (!s.actionType)
1322
+ stepIssues.push(`step ${i + 1}: missing actionType (e.g. "Click", "Type Text")`);
1323
+ if (!s.stepType)
1324
+ stepIssues.push(`step ${i + 1}: missing stepType (e.g. "web", "android", "mainframe")`);
1325
+ });
1326
+ if (stepIssues.length) {
1327
+ return err(`Cannot save "${draft.tc.title}" — ${stepIssues.length} automation step issue(s):\n- ${stepIssues.join('\n- ')}\n` +
1328
+ 'Automation steps must carry a canonical actionType + stepType. Recorded drafts get these ' +
1329
+ 'from the recorder; hand-built drafts must set them via tc_draft_update. For a past recording, ' +
1330
+ 'use tc_draft_from_journal({ sessionId }) to load its journal into a save-ready draft.');
1331
+ }
1332
+ }
1333
+ // Optimistic-concurrency guard: refuse an UPDATE that would silently
1334
+ // overwrite someone else's changes. `draft.tc.version` snapshotted at
1335
+ // hydrate time (via tc_draft_from_tc / tc_edit_open) is compared against
1336
+ // the CURRENT backend version; a mismatch means the TC moved between
1337
+ // hydrate and save. Best-effort — the re-fetch failing is not a save
1338
+ // blocker (backend transient issue vs. genuine drift are indistinguishable
1339
+ // here, and the PUT itself will surface real errors).
1340
+ if (draft.tc.id && draft.tc.version != null) {
1341
+ try {
1342
+ const current = await adapter.getTestCase(draft.tc.id);
1343
+ if (current.version != null && current.version !== draft.tc.version) {
1344
+ return err(`Cannot save "${draft.tc.title}" — TC ${draft.tc.id} was modified externally ` +
1345
+ `since this draft was opened (version ${draft.tc.version} → ${current.version}). ` +
1346
+ `Discard this draft with tc_draft_discard, then re-open with tc_edit_open / ` +
1347
+ `tc_draft_from_tc to pick up the latest state, then re-apply your edits.`);
1348
+ }
1349
+ }
1350
+ catch {
1351
+ // Best-effort — proceed to the actual save if the version pre-check fails
1352
+ }
1353
+ }
1354
+ try {
1355
+ const isUpdate = !!draft.tc.id;
1356
+ const saved = isUpdate
1357
+ ? await adapter.updateTestCase(draft.tc.id, draft.tc)
1358
+ : await adapter.createTestCase(draft.tc);
1359
+ // Bind the draft to the id it was just created as, so a subsequent tc_draft_update + tc_save
1360
+ // UPDATES this same test case in place instead of creating a duplicate (the anisha TC_627→TC_628
1361
+ // trap). No-op on an update (already bound).
1362
+ if (!isUpdate && saved.id) {
1363
+ try {
1364
+ deps.drafts.markSaved(draft.draftId, saved.id);
1365
+ }
1366
+ catch { /* draft already gone — nothing to bind */ }
1367
+ }
1368
+ // The /mcp-recorder window is torn down by core_close_session (RecordingSubAgent.close →
1369
+ // ui.close), which is the ONE place windows close. tc_save no longer tries to close it
1370
+ // per-save — the previous callRaw('recording_window_close', ...) had no handler anywhere and
1371
+ // was a silently-swallowed no-op.
1372
+ const link = saved.productUrl ? `\n${saved.productUrl}` : '';
1373
+ const chosenDraft = selectMatches(draftFnMatches, replaceWithFunctions);
1374
+ const fnNote = chosenDraft.length ? await replaceMatchedRuns(adapter, String(saved.id), chosenDraft) : '';
1375
+ // Pre-run checks for DB / API test cases: warn about what will make the run fail or pass for the wrong
1376
+ // reason. Never blocks the save, and never throws into it.
1377
+ let lint = [];
1378
+ try {
1379
+ if (draft.tc.category === 'automated')
1380
+ lint = lintAutomatedTestCase(draft.tc);
1381
+ }
1382
+ catch { /* advisory only */ }
1383
+ return ok(`${isUpdate ? 'Updated' : 'Created'} test case ${saved.id}.` +
1384
+ (renamedFrom ? ` "${renamedFrom}" already existed, so it was saved as "${draft.tc.title}".` : '') +
1385
+ link + fnNote + lintBlock(lint), { saved, draftId: draft.draftId, ...(lint.length ? { warnings: lint } : {}) });
1386
+ }
1387
+ catch (e) {
1388
+ return err(describeError(e));
1389
+ }
1390
+ });
1391
+ server.registerTool('tc_automate', {
1392
+ title: 'Turn a manual test case into a recording guide (creates a NEW automated TC)',
1393
+ description: 'Read an EXISTING MANUAL test case and return a recording guide the model uses to drive a live ' +
1394
+ "recording via the connected agent's granular tools (web_launch_application, web_snapshot, " +
1395
+ 'web_click, web_enter_text, …, core_close_session). The Electron recorder window opens ' +
1396
+ 'automatically on web_launch_application; each captured step streams into it. The user reviews ' +
1397
+ 'and clicks Save in the recorder — that CREATES A NEW automated test case (via POST /tm/testcase); ' +
1398
+ 'the source manual TC is left untouched. Pass `url` unless the manual steps already contain one, ' +
1399
+ 'and `extra` for credentials / data / what to assert. Read-only from MCP: this tool composes text, ' +
1400
+ 'it never writes. Requires a live connection.',
1401
+ inputSchema: {
1402
+ tcId: z.string().describe('The manual test case id (or business key TC_123) to automate.'),
1403
+ url: z.string().optional().describe('Starting URL for the recording (the app under test).'),
1404
+ extra: z.string().optional().describe('Extra guidance for the recording: credentials, data, assertions.'),
1405
+ app_path: z.string().optional().describe('DESKTOP test cases only (tcType DESKTOP): the full path of the ' +
1406
+ 'application\'s .exe. A DESKTOP test case needs no `url`; its guide uses the desktop_* tools.'),
1407
+ },
1408
+ annotations: { readOnlyHint: true },
1409
+ }, async ({ tcId, url, extra, app_path }) => {
1410
+ const adapter = deps.getAdapter?.();
1411
+ if (!adapter)
1412
+ return err('Not connected to a product. Use qa_connect first.');
1413
+ let source;
1414
+ try {
1415
+ source = await adapter.getTestCase(tcId);
1416
+ }
1417
+ catch (e) {
1418
+ return err(`Could not read test case "${tcId}": ${describeError(e)}`);
1419
+ }
1420
+ if (source.category !== 'manual') {
1421
+ return err(`"${source.title}" (${tcId}) is not manual (category: ${source.category}). ` +
1422
+ 'tc_automate promotes MANUAL → automated. To re-record an automated TC, record + tc_save with a fresh title.');
1423
+ }
1424
+ // "US_7" → 7, "7" → 7, "MOD_12" → 12. Absent → undefined (don't invent).
1425
+ const numericSuffix = (s) => {
1426
+ if (!s)
1427
+ return undefined;
1428
+ const m = s.match(/(\d+)$/);
1429
+ return m ? parseInt(m[1], 10) : undefined;
1430
+ };
1431
+ const userstoryId = numericSuffix(source.storyRef);
1432
+ const moduleId = numericSuffix(source.folderOrModule);
1433
+ const stepLines = source.steps
1434
+ .map((s, i) => `${i + 1}. ${s.description}${s.expectedResult ? ` (expect: ${s.expectedResult})` : ''}`)
1435
+ .join('\n');
1436
+ // A DESKTOP test case records a Windows application: it needs an .exe path, not a URL.
1437
+ const isDesktopSource = (source.technologyType ?? '').toUpperCase() === 'DESKTOP';
1438
+ if (!isDesktopSource && !url && !/https?:\/\//.test(`${extra ?? ''}\n${stepLines}`)) {
1439
+ return err(`To automate "${source.title}" I need the app URL — the manual steps don't contain one. ` +
1440
+ 'Call again with `url` (and any credentials/data via `extra`).');
1441
+ }
1442
+ const storyLine = userstoryId !== undefined
1443
+ ? `userstoryId:${userstoryId} — is already selected in the recorder's story picker.`
1444
+ : 'no story on source — will need to be picked at Save in the recorder if the user wants a link.';
1445
+ const moduleLine = moduleId !== undefined
1446
+ ? `moduleId:${moduleId} — is already selected in the recorder's module bar.`
1447
+ : 'no module on source — the user picks one in the recorder before Save.';
1448
+ // The converted TC must take its testdata STRICTLY from the manual TC — not from whatever the
1449
+ // recording happens to type (previously the recording context's values became the new TC's
1450
+ // testdata). Read the source default iteration and put the exact values in the guide; the
1451
+ // post-save copy (tc_save copyTestdataFrom / recorder sourceTcId) then enforces them.
1452
+ let testData = null;
1453
+ try {
1454
+ if (adapter.getDefaultIteration) {
1455
+ const tpl = await adapter.getDefaultIteration({
1456
+ tcId,
1457
+ ...(source.currentVersionId ? { versionId: source.currentVersionId } : {}),
1458
+ });
1459
+ if (tpl.parameters.length)
1460
+ testData = tpl;
1461
+ }
1462
+ }
1463
+ catch {
1464
+ // testdata is best-effort — a broken store must not block the guide
1465
+ }
1466
+ const testDataBlock = testData
1467
+ ? `\n── Testdata from the source manual TC (env ${testData.environmentType}) — use EXACTLY these values ──\n` +
1468
+ testData.parameters
1469
+ .map((p) => p.protected
1470
+ ? `- ${p.name} = [PROTECTED on the source TC — ASK the user for the value; do not invent]`
1471
+ : `- ${p.name} = "${p.seed}"`)
1472
+ .join('\n') +
1473
+ `\nWhen a manual step fills one of these fields, pass the parameter NAME as \`parameter_name\` ` +
1474
+ `and type the value above. Do NOT invent values and do NOT reuse values from an earlier ` +
1475
+ `recording or the chat context. A parameter whose value is blank has no seed — generate a ` +
1476
+ `fresh random value (or reuse the previous session's ONLY if the user explicitly says so).\n`
1477
+ : `\n── Testdata ──\nThe source manual TC has no testdata. Generate fresh random values for the fields ` +
1478
+ `you type (or reuse the previous session's values ONLY if the user explicitly says so).\n`;
1479
+ const structuredTestData = testData
1480
+ ? {
1481
+ testData: {
1482
+ environmentType: testData.environmentType,
1483
+ parameters: testData.parameters.map((p) => ({
1484
+ name: p.name,
1485
+ seed: p.protected ? '*****' : p.seed,
1486
+ ...(p.protected ? { protected: true } : {}),
1487
+ })),
1488
+ },
1489
+ }
1490
+ : {};
1491
+ if (isDesktopSource) {
1492
+ const appPath = app_path?.trim();
1493
+ const desktopGuide = 'Automate this manual test case by recording it end-to-end.\n\n' +
1494
+ `testcaseName:"${source.title}"\n` +
1495
+ `Story: ${storyLine}\n` +
1496
+ `Module: ${moduleLine}\n` +
1497
+ (source.preconditions ? `Preconditions: ${source.preconditions}\n` : '') +
1498
+ (appPath ? `Application: ${appPath}\n` : '') +
1499
+ (extra ? `${extra}\n` : '') +
1500
+ testDataBlock +
1501
+ `\nManual steps (guide only — do not paste verbatim; each granular action captures a real step):\n${stepLines}\n\n` +
1502
+ '── Recording tools (call on the connected agent) ──\n' +
1503
+ `1. core_activate_technology({ technology: "DESKTOP", testcaseName, ` +
1504
+ (userstoryId !== undefined ? `userstoryId: ${userstoryId} (REQUIRED — links the new TC to the source's story), ` : '') +
1505
+ `moduleId?: ${moduleId ?? '<from source>'}, sourceTcId: "${tcId}" }) — session context. ` +
1506
+ 'sourceTcId lets the recorder copy the manual TC testdata at Save.\n' +
1507
+ `2. desktop_launch_application({ app_path: ${appPath ? JSON.stringify(appPath) : '"<the application\'s full .exe path — ASK the user>"'} }) ` +
1508
+ '— must be the FIRST call. If the application is already open, ask the user to close it first (a second ' +
1509
+ 'launch is refused), and ask them not to touch the mouse or keyboard while you record.\n' +
1510
+ '3. desktop_snapshot() — refs for the current window; take a new one after a step that changes the window.\n' +
1511
+ '4. desktop_click({ ref }) / desktop_enter_text({ ref, value }) / desktop_set_text({ ref, value })\n' +
1512
+ ' desktop_select_item_from_dropdown({ ref, item }) / desktop_set_checkbox({ ref, checked })\n' +
1513
+ ' desktop_invoke_menu_item({ ref }) — open the menu-bar menu with desktop_click first\n' +
1514
+ ' desktop_validate_text({ ref, expected }) / desktop_keyboard_action({ keys })\n' +
1515
+ ' Right-click menus and open drop-down lists: desktop_snapshot({ scope: "popups" }) after opening them.\n' +
1516
+ ' Windows switch by themselves; for a dialog that is not in the snapshot use desktop_list_windows + ' +
1517
+ 'desktop_switch_window.\n' +
1518
+ '5. core_close_session() — when the flow is done.\n\n' +
1519
+ '── Save ──\n' +
1520
+ 'The recorder window streams each step as it is captured. When done, STOP and ask the user to ' +
1521
+ 'review the step cards and click Save Testcase in the recorder — sourceTcId was passed at ' +
1522
+ 'activation, so the recorder copies the source manual TC\'s testdata onto the new TC. If the ' +
1523
+ `user explicitly asks you to save from chat, call tc_save({ sessionId, copyTestdataFrom: "${tcId}" }). ` +
1524
+ `Either way that CREATES A NEW automated test case; the source manual TC ${tcId} stays as-is.`;
1525
+ return ok(desktopGuide, {
1526
+ sourceTcId: tcId,
1527
+ sourceTitle: source.title,
1528
+ technology: 'DESKTOP',
1529
+ ...(userstoryId !== undefined ? { userstoryId } : {}),
1530
+ ...(moduleId !== undefined ? { moduleId } : {}),
1531
+ ...structuredTestData,
1532
+ });
1533
+ }
1534
+ const guide = 'Automate this manual test case by recording it end-to-end.\n\n' +
1535
+ `testcaseName:"${source.title}"\n` +
1536
+ `Story: ${storyLine}\n` +
1537
+ `Module: ${moduleLine}\n` +
1538
+ (source.preconditions ? `Preconditions: ${source.preconditions}\n` : '') +
1539
+ (url ? `Start URL: ${url}\n` : '') +
1540
+ (extra ? `${extra}\n` : '') +
1541
+ testDataBlock +
1542
+ `\nManual steps (guide only — do not paste verbatim; each granular action captures a real step):\n${stepLines}\n\n` +
1543
+ '── Recording tools (call on the connected agent) ──\n' +
1544
+ `1. core_activate_technology({ technology: "WEB", testcaseName, ` +
1545
+ // The source's story MUST be passed so the converted test case stays linked to it.
1546
+ (userstoryId !== undefined ? `userstoryId: ${userstoryId} (REQUIRED — links the new TC to the source's story), ` : '') +
1547
+ `moduleId?: ${moduleId ?? '<from source>'}, ` +
1548
+ `recordingMode, recordingModeAskedUser, sourceTcId: "${tcId}" }) — session context. ` +
1549
+ `ASK the user AI-only vs AI + Manual FIRST (AI + Manual = HYBRID; if they already named it, use that) and pass recordingMode + recordingModeAskedUser ` +
1550
+ `(they must match). sourceTcId lets the recorder copy the manual TC testdata at Save.\n` +
1551
+ `2. web_launch_application(${url ? `"${url}"` : '{ url }'}) — must be FIRST browser call; opens the Electron recorder window.\n` +
1552
+ '3. web_snapshot() — call BEFORE every action to get fresh element refs.\n' +
1553
+ '4. web_click({ ref }) / web_enter_text({ ref, value }) / web_select_item_from_dropdown({ ref, item })\n' +
1554
+ ' web_check_if_not_checked({ ref }) / web_un_check_if_checked({ ref })\n' +
1555
+ ' web_validate_text({ ref, expected }) / web_validate_partial_text({ ref, expected })\n' +
1556
+ ' web_keyboard_action({ keys, ref? }) / web_wait_until_element_present({ ref, timeout? })\n' +
1557
+ ' Tab / iframe: web_switch_to_tab, web_switch_to_parent_tab, web_close_tab,\n' +
1558
+ ' web_switch_to_iframe, web_switch_to_parent_iframe, web_switch_to_default_content.\n' +
1559
+ '5. core_close_session() — when the flow is done.\n\n' +
1560
+ '── Save ──\n' +
1561
+ 'The recorder window streams each step as it is captured. When done, STOP and ask the user to ' +
1562
+ 'review the step cards and click Save Testcase in the recorder — sourceTcId was passed at ' +
1563
+ 'activation, so the recorder copies the source manual TC\'s testdata onto the new TC. If the ' +
1564
+ `user explicitly asks you to save from chat, call tc_save({ sessionId, copyTestdataFrom: "${tcId}" }) ` +
1565
+ '— it clicks the recorder window\'s own Save button and then copies the manual testdata. ' +
1566
+ 'Either way that CREATES A NEW automated test case; the ' +
1567
+ `source manual TC ${tcId} stays as-is.\n\n` +
1568
+ 'Do NOT rely on values typed during the recording for the converted TC\'s testdata — they are ' +
1569
+ 'replaced by the source TC\'s values. Do NOT call tc_save({ draftId }) / ' +
1570
+ 'tc_draft_from_journal / update_testcase / journal_modify from MCP in this flow — the recorder UI is the persist step.';
1571
+ return ok(guide, {
1572
+ sourceTcId: tcId,
1573
+ sourceTitle: source.title,
1574
+ ...(userstoryId !== undefined ? { userstoryId } : {}),
1575
+ ...(moduleId !== undefined ? { moduleId } : {}),
1576
+ ...(testData
1577
+ ? {
1578
+ testData: {
1579
+ environmentType: testData.environmentType,
1580
+ parameters: testData.parameters.map((p) => ({
1581
+ name: p.name,
1582
+ seed: p.protected ? '*****' : p.seed,
1583
+ ...(p.protected ? { protected: true } : {}),
1584
+ })),
1585
+ },
1586
+ }
1587
+ : {}),
1588
+ });
1589
+ });
1590
+ }
1591
+ //# sourceMappingURL=testcase.tools.js.map