@wenathlan/devthink 2.0.13 → 2.0.15

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 (444) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/accounts.ts +2087 -0
  3. package/agent.ts +2331 -0
  4. package/antigravity.ts +2139 -0
  5. package/apifreeze.ts +4146 -0
  6. package/auth.ts +642 -0
  7. package/background.ts +16837 -0
  8. package/bridge.ts +2080 -0
  9. package/build.ts +54 -0
  10. package/bun.ts +26 -0
  11. package/capture.ts +1614 -0
  12. package/checksecrets.ts +72 -0
  13. package/cjs.ts +9 -0
  14. package/cli.ts +3500 -0
  15. package/commands.ts +1101 -0
  16. package/companion.ts +450 -0
  17. package/compatibility.ts +37 -0
  18. package/config.ts +3137 -0
  19. package/constants.ts +943 -0
  20. package/core.ts +1473 -0
  21. package/crossbrowser.ts +1359 -0
  22. package/dashdone.ts +605 -0
  23. package/data.ts +943 -0
  24. package/database.ts +133 -0
  25. package/debug.ts +850 -0
  26. package/deno.ts +27 -0
  27. package/devthink.ts +707 -0
  28. package/dist/accounts.d.ts +409 -0
  29. package/dist/agent.d.ts +837 -0
  30. package/dist/antigravity.d.ts +380 -0
  31. package/dist/apifreeze.d.ts +113 -0
  32. package/dist/auth.d.ts +224 -0
  33. package/{bridge.d.ts → dist/bridge.d.ts} +1 -1
  34. package/dist/capture.d.ts +595 -0
  35. package/dist/cjs.d.ts +6 -0
  36. package/{cli.js → dist/cli.js} +2 -2
  37. package/dist/commands.d.ts +310 -0
  38. package/dist/compatibility.d.ts +17 -0
  39. package/dist/config.d.ts +1853 -0
  40. package/dist/constants.d.ts +637 -0
  41. package/dist/core.d.ts +361 -0
  42. package/dist/data.d.ts +330 -0
  43. package/dist/database.d.ts +24 -0
  44. package/dist/debug.d.ts +270 -0
  45. package/dist/engine.d.ts +74 -0
  46. package/dist/environments.d.ts +244 -0
  47. package/dist/evidence.d.ts +277 -0
  48. package/dist/export.d.ts +311 -0
  49. package/dist/fingerprint.d.ts +594 -0
  50. package/dist/flow.d.ts +300 -0
  51. package/dist/gates.d.ts +103 -0
  52. package/dist/identity.d.ts +51 -0
  53. package/dist/ids.d.ts +7 -0
  54. package/dist/llm.d.ts +652 -0
  55. package/dist/models.d.ts +1807 -0
  56. package/dist/net.d.ts +325 -0
  57. package/dist/neutral.d.ts +41 -0
  58. package/dist/oauth.d.ts +703 -0
  59. package/dist/page.d.ts +1166 -0
  60. package/dist/perf.d.ts +481 -0
  61. package/dist/plan.d.ts +134 -0
  62. package/dist/project.d.ts +395 -0
  63. package/dist/providers.d.ts +37 -0
  64. package/dist/quota.d.ts +453 -0
  65. package/dist/recovery.d.ts +621 -0
  66. package/dist/request.d.ts +1492 -0
  67. package/dist/run.d.ts +779 -0
  68. package/dist/runtime.d.ts +212 -0
  69. package/dist/search.d.ts +375 -0
  70. package/dist/security.d.ts +534 -0
  71. package/dist/serve.d.ts +136 -0
  72. package/dist/session.d.ts +296 -0
  73. package/dist/storage.d.ts +53 -0
  74. package/dist/streaming.d.ts +1119 -0
  75. package/dist/swarm.d.ts +328 -0
  76. package/dist/tools.d.ts +170 -0
  77. package/dist/types.d.ts +8357 -0
  78. package/dist/utils.d.ts +82 -0
  79. package/dist/version.d.ts +7 -0
  80. package/dist/versionregistry.d.ts +406 -0
  81. package/dist/views.d.ts +579 -0
  82. package/dist/workbenchsession.d.ts +69 -0
  83. package/dist/workflow.d.ts +649 -0
  84. package/docs/readme.md +92 -0
  85. package/docs/schemas/antigravity.json +192 -0
  86. package/engine.ts +1524 -0
  87. package/environments.ts +1005 -0
  88. package/evidence.ts +643 -0
  89. package/export.ts +889 -0
  90. package/fingerprint.ts +1458 -0
  91. package/flow.ts +1190 -0
  92. package/gates.ts +307 -0
  93. package/gateway.ts +34 -0
  94. package/hardening.ts +191 -0
  95. package/headless.ts +369 -0
  96. package/http.ts +2110 -0
  97. package/identity.ts +246 -0
  98. package/ids.ts +26 -0
  99. package/index.ts +369 -0
  100. package/llm.ts +2682 -0
  101. package/mcp.ts +1835 -0
  102. package/{memory.js → memory.ts} +3834 -2310
  103. package/models.ts +3805 -0
  104. package/modes.ts +43 -0
  105. package/net.ts +1214 -0
  106. package/neutral.ts +362 -0
  107. package/node.ts +26 -0
  108. package/oauth.ts +2216 -0
  109. package/offscreen.ts +170 -0
  110. package/pack.ts +956 -0
  111. package/package.json +175 -82
  112. package/page.ts +7824 -0
  113. package/pagebridge.ts +1116 -0
  114. package/perf.ts +957 -0
  115. package/plan.ts +672 -0
  116. package/plugin.ts +76 -0
  117. package/{policy.js → policy.ts} +5073 -4679
  118. package/prisma.config.ts +27 -0
  119. package/progress.ts +1308 -0
  120. package/project.ts +1291 -0
  121. package/protocol.ts +4187 -0
  122. package/providers.ts +246 -0
  123. package/quota.ts +1887 -0
  124. package/recovery.ts +2433 -0
  125. package/request.ts +4482 -0
  126. package/run.ts +2135 -0
  127. package/runtime.ts +526 -0
  128. package/search.ts +1760 -0
  129. package/security.ts +1673 -0
  130. package/serve.ts +419 -0
  131. package/server.ts +5538 -0
  132. package/session.ts +1162 -0
  133. package/storage.ts +182 -0
  134. package/streaming.ts +4101 -0
  135. package/swarm.ts +884 -0
  136. package/sync.ts +56 -0
  137. package/tests/agentcert.test.ts +128 -0
  138. package/tests/agentfleet.test.ts +214 -0
  139. package/tests/agentreview.test.ts +241 -0
  140. package/tests/agentstream.test.ts +335 -0
  141. package/tests/agentwork.test.ts +356 -0
  142. package/tests/apifreeze.test.ts +290 -0
  143. package/tests/apimap.test.ts +112 -0
  144. package/tests/approvalgate.test.ts +175 -0
  145. package/tests/artifactmanifest.test.ts +204 -0
  146. package/tests/attentionfeed.test.ts +163 -0
  147. package/tests/backgroundruns.test.ts +100 -0
  148. package/tests/batchscheduling.test.ts +131 -0
  149. package/tests/blackboard.test.ts +238 -0
  150. package/tests/bridge.test.ts +1088 -0
  151. package/tests/browsercoverage.test.ts +134 -0
  152. package/tests/browserpolyfills.test.ts +124 -0
  153. package/tests/build.mjs +1260 -0
  154. package/tests/clientauth.test.ts +223 -0
  155. package/tests/clitools.test.ts +578 -0
  156. package/tests/confirmgates.test.ts +190 -0
  157. package/tests/containerpack.test.ts +143 -0
  158. package/tests/controlflow.test.ts +2120 -0
  159. package/tests/coordination.test.ts +345 -0
  160. package/tests/copyscreen.test.ts +139 -0
  161. package/tests/core.test.ts +417 -0
  162. package/tests/costcert.test.ts +95 -0
  163. package/tests/crossbrowser.test.ts +115 -0
  164. package/tests/cspaudit.test.ts +79 -0
  165. package/tests/dashdone.test.ts +615 -0
  166. package/tests/datagrid.test.ts +137 -0
  167. package/tests/doccheck.test.ts +107 -0
  168. package/tests/dombatch.test.ts +109 -0
  169. package/tests/emulation.test.ts +282 -0
  170. package/tests/environments.test.ts +259 -0
  171. package/tests/evidenceviews.test.ts +88 -0
  172. package/tests/exporttools.test.ts +185 -0
  173. package/tests/firefoxprep.test.ts +134 -0
  174. package/tests/flowlibrary.test.ts +242 -0
  175. package/tests/flowrun.test.ts +303 -0
  176. package/tests/forensics.test.ts +439 -0
  177. package/tests/gateway.test.ts +939 -0
  178. package/tests/headlesslib.test.ts +171 -0
  179. package/tests/httpstream.test.ts +277 -0
  180. package/tests/immutablelog.test.ts +157 -0
  181. package/tests/inboundguard.test.ts +177 -0
  182. package/tests/lazyload.test.ts +72 -0
  183. package/tests/librarymodes.test.ts +623 -0
  184. package/tests/llm.test.ts +696 -0
  185. package/tests/manifest.test.ts +226 -0
  186. package/tests/maskinputs.test.ts +150 -0
  187. package/tests/matrixverify.test.ts +111 -0
  188. package/tests/mavenpack.test.ts +75 -0
  189. package/tests/mcpserver.test.ts +704 -0
  190. package/tests/memory.test.ts +4155 -0
  191. package/tests/memorycare.test.ts +230 -0
  192. package/tests/migrateplan.test.ts +349 -0
  193. package/tests/minimization.test.ts +414 -0
  194. package/tests/modelroute.test.ts +112 -0
  195. package/tests/multiagent.test.ts +440 -0
  196. package/tests/nativebridge.test.ts +807 -0
  197. package/tests/navigation.test.ts +284 -0
  198. package/tests/nugetpack.test.ts +83 -0
  199. package/tests/orchestration.test.ts +449 -0
  200. package/tests/originpolicy.test.ts +405 -0
  201. package/tests/outputcompare.test.ts +97 -0
  202. package/tests/package.test.ts +91 -0
  203. package/tests/pagebridge.test.ts +5909 -0
  204. package/tests/pentest.test.ts +75 -0
  205. package/tests/perfrecords.test.ts +257 -0
  206. package/tests/permdiff.test.ts +85 -0
  207. package/tests/phishguard.test.ts +128 -0
  208. package/tests/pickerviews.test.ts +155 -0
  209. package/tests/pipelines.test.ts +381 -0
  210. package/tests/planlint.test.ts +240 -0
  211. package/tests/planreview.test.ts +383 -0
  212. package/tests/platformtargets.test.ts +56 -0
  213. package/tests/policy.test.ts +8284 -0
  214. package/tests/portability.test.ts +96 -0
  215. package/tests/progress.test.ts +1036 -0
  216. package/tests/promptlibrary.test.ts +116 -0
  217. package/tests/protocol.test.ts +4793 -0
  218. package/tests/publishingpipeline.test.ts +314 -0
  219. package/tests/quickactions.test.ts +164 -0
  220. package/tests/readiness.test.ts +78 -0
  221. package/tests/recipes.test.ts +163 -0
  222. package/tests/redactshots.test.ts +216 -0
  223. package/tests/registernvidiakeys.ts +51 -0
  224. package/tests/relayserve.test.ts +304 -0
  225. package/tests/releasenotes.test.ts +276 -0
  226. package/tests/resilience.test.ts +467 -0
  227. package/tests/resourceaware.test.ts +187 -0
  228. package/tests/runbudget.test.ts +125 -0
  229. package/tests/runhistory.test.ts +299 -0
  230. package/tests/runreplay.test.ts +113 -0
  231. package/tests/runresume.test.ts +184 -0
  232. package/tests/runstate.test.ts +288 -0
  233. package/tests/runtimeadapters.test.ts +251 -0
  234. package/tests/safariskeleton.test.ts +115 -0
  235. package/tests/sandboxframe.test.ts +196 -0
  236. package/tests/sbom.test.ts +105 -0
  237. package/tests/secretvault.test.ts +188 -0
  238. package/tests/selcache.test.ts +111 -0
  239. package/tests/sessioninterface.test.ts +791 -0
  240. package/tests/sessions.test.ts +591 -0
  241. package/tests/siteprefs.test.ts +228 -0
  242. package/tests/snapshotdelta.test.ts +165 -0
  243. package/tests/statusviews.test.ts +237 -0
  244. package/tests/stepmeter.test.ts +200 -0
  245. package/tests/streamparse.test.ts +163 -0
  246. package/tests/stylepruning.test.ts +90 -0
  247. package/tests/surfaces.test.ts +282 -0
  248. package/tests/sweep.test.ts +78 -0
  249. package/tests/syncbridge.test.ts +164 -0
  250. package/tests/taskqueue.test.ts +206 -0
  251. package/tests/toolcalls.test.ts +336 -0
  252. package/tests/toolcatalog.test.ts +201 -0
  253. package/tests/torture-agent.test.ts +706 -0
  254. package/tests/torture-auth.test.ts +461 -0
  255. package/tests/torture-commands.test.ts +895 -0
  256. package/tests/torture-data.test.ts +923 -0
  257. package/tests/torture-environments.test.ts +285 -0
  258. package/tests/torture-export.test.ts +263 -0
  259. package/tests/torture-http.test.ts +1379 -0
  260. package/tests/torture-llm.test.ts +808 -0
  261. package/tests/torture-memory.test.ts +1084 -0
  262. package/tests/torture-plan.test.ts +829 -0
  263. package/tests/torture-run.test.ts +626 -0
  264. package/tests/torture-session.test.ts +928 -0
  265. package/tests/torture-swarm.test.ts +1245 -0
  266. package/tests/torture-tools.test.ts +964 -0
  267. package/tests/torture-workflow.test.ts +2354 -0
  268. package/tests/tourviews.test.ts +52 -0
  269. package/tests/transparency.test.ts +147 -0
  270. package/tests/trigger.test.ts +941 -0
  271. package/tests/v1sunset.test.ts +428 -0
  272. package/tests/virtlist.test.ts +94 -0
  273. package/tests/vision.test.ts +540 -0
  274. package/tests/vsixpack.test.ts +145 -0
  275. package/tests/webapi.test.ts +523 -0
  276. package/tests/workflow.test.ts +1785 -0
  277. package/tests/workfloweditor.test.ts +759 -0
  278. package/tests/xpipack.test.ts +128 -0
  279. package/tools.ts +734 -0
  280. package/types.ts +9908 -0
  281. package/umd.ts +9 -0
  282. package/utils.ts +249 -0
  283. package/version.ts +8 -0
  284. package/versionregistry.ts +1310 -0
  285. package/views.ts +2153 -0
  286. package/vitest.config.ts +12 -0
  287. package/web/App.tsx +78 -0
  288. package/web/README.md +47 -0
  289. package/web/capacitor.config.ts +46 -0
  290. package/web/const.ts +19 -0
  291. package/web/control.shell.tsx +66 -0
  292. package/web/dashboardpage.ts +554 -0
  293. package/web/db.ts +493 -0
  294. package/web/design.html +541 -0
  295. package/web/gatewayview/Gateway.tsx +345 -0
  296. package/web/gatewayview/config.ts +1042 -0
  297. package/web/gatewayview/definition.ts +174 -0
  298. package/web/icons.ts +15 -0
  299. package/{manifest.json → web/manifest.json} +1 -1
  300. package/web/optionspage.ts +691 -0
  301. package/web/popup.ts +1651 -0
  302. package/web/schema.prisma +176 -0
  303. package/web/sidepanel.ts +7941 -0
  304. package/web/sitemanifest.json +13 -0
  305. package/web/terminal-ui.tsx +622 -0
  306. package/web/transparencypage.ts +541 -0
  307. package/web/vite.config.ts +39 -0
  308. package/web/workspace.ts +23 -0
  309. package/workbenchmemory.ts +104 -0
  310. package/workbenchsession.ts +304 -0
  311. package/workflow.ts +4495 -0
  312. package/bridge.d.ts.map +0 -1
  313. package/bridge.js +0 -1877
  314. package/bun.d.ts.map +0 -1
  315. package/bun.js +0 -52329
  316. package/caps/background.json +0 -712
  317. package/caps/cli.json +0 -360
  318. package/caps/library.json +0 -3611
  319. package/caps/mcp.json +0 -126
  320. package/caps/pagebridge.json +0 -377
  321. package/caps/popup.json +0 -51
  322. package/caps/sidepanel.json +0 -522
  323. package/checksums.txt +0 -142
  324. package/cli.d.ts.map +0 -1
  325. package/companion.d.ts.map +0 -1
  326. package/companion.js +0 -389
  327. package/crossbrowser.d.ts.map +0 -1
  328. package/crossbrowser.js +0 -1191
  329. package/dashdone.d.ts.map +0 -1
  330. package/dashdone.js +0 -368
  331. package/deno.d.ts.map +0 -1
  332. package/deno.js +0 -52325
  333. package/devthink.umd.js +0 -52346
  334. package/fixtures/bun.ts +0 -7
  335. package/fixtures/cjs.js +0 -6
  336. package/fixtures/deno.ts +0 -6
  337. package/fixtures/example-org-pagestate.json +0 -22
  338. package/fixtures/importers/automa-workflow.json +0 -18
  339. package/fixtures/importers/selenium-side.json +0 -20
  340. package/fixtures/importers/tabular-plan.csv +0 -7
  341. package/fixtures/importers/uivision-macro.json +0 -10
  342. package/fixtures/importers/v1-plan.json +0 -13
  343. package/fixtures/mcp-client.mjs +0 -14
  344. package/fixtures/pages/checkout.html +0 -192
  345. package/fixtures/pages/dashboard.html +0 -110
  346. package/fixtures/pages/feed.html +0 -113
  347. package/fixtures/pages/product-grid.html +0 -150
  348. package/fixtures/plans/form-inventory-plan.json +0 -11
  349. package/fixtures/plans/release-notes-plan.json +0 -11
  350. package/fixtures/recipes/agentscompete.json +0 -11
  351. package/fixtures/recipes/agentsforms.json +0 -11
  352. package/fixtures/recipes/agentsmonitor.json +0 -11
  353. package/fixtures/recipes/agentsreview.json +0 -29
  354. package/fixtures/recipes/agentswarm.json +0 -11
  355. package/fixtures/recipes/fillcalendar.json +0 -12
  356. package/fixtures/recipes/fillcheckout.json +0 -13
  357. package/fixtures/recipes/filldependentdropdowns.json +0 -12
  358. package/fixtures/recipes/fillfromcsv.json +0 -13
  359. package/fixtures/recipes/fillloginform.json +0 -12
  360. package/fixtures/recipes/fillmultistepwizard.json +0 -13
  361. package/fixtures/recipes/fillregistration.json +0 -12
  362. package/fixtures/recipes/fillsearchfilters.json +0 -12
  363. package/fixtures/recipes/filltypeahead.json +0 -11
  364. package/fixtures/recipes/monitoralerts.json +0 -12
  365. package/fixtures/recipes/monitoravailability.json +0 -11
  366. package/fixtures/recipes/monitornetworkquiet.json +0 -12
  367. package/fixtures/recipes/monitorpagechanges.json +0 -11
  368. package/fixtures/recipes/monitorpricechange.json +0 -11
  369. package/fixtures/recipes/monitorschedule.json +0 -12
  370. package/fixtures/recipes/scrapedynamicprices.json +0 -13
  371. package/fixtures/recipes/scrapeimagegallery.json +0 -12
  372. package/fixtures/recipes/scrapeinfinitefeed.json +0 -13
  373. package/fixtures/recipes/scrapenestedlists.json +0 -12
  374. package/fixtures/recipes/scrapeproductgrid.json +0 -12
  375. package/fixtures/recipes/scrapereviews.json +0 -12
  376. package/fixtures/recipes/scrapesearchresults.json +0 -12
  377. package/fixtures/recipes/scrapetablepagination.json +0 -12
  378. package/fixtures/recipes/testaccessibility.json +0 -34
  379. package/fixtures/recipes/testconsoleerrors.json +0 -12
  380. package/fixtures/recipes/testdeeplinks.json +0 -12
  381. package/fixtures/recipes/testformvalidation.json +0 -13
  382. package/fixtures/recipes/testlayoutshift.json +0 -12
  383. package/fixtures/recipes/testlinkcheck.json +0 -12
  384. package/fixtures/recipes/testloadtiming.json +0 -12
  385. package/fixtures/recipes/testvisualdiff.json +0 -12
  386. package/fixtures/workflows/changelog-digest-workflow.json +0 -13
  387. package/fixtures/workflows/form-survey-workflow.json +0 -13
  388. package/gallery.json +0 -706
  389. package/hardening.d.ts.map +0 -1
  390. package/hardening.js +0 -188
  391. package/headless.d.ts.map +0 -1
  392. package/headless.js +0 -11522
  393. package/http.d.ts.map +0 -1
  394. package/http.js +0 -2165
  395. package/index.cjs +0 -54682
  396. package/index.d.ts.map +0 -1
  397. package/index.js +0 -52310
  398. package/index.neutral.js +0 -46343
  399. package/mcp.d.ts.map +0 -1
  400. package/mcp.js +0 -20515
  401. package/memory.d.ts.map +0 -1
  402. package/nativehost.template.json +0 -10
  403. package/node.cjs +0 -54686
  404. package/node.d.ts.map +0 -1
  405. package/pack.d.ts.map +0 -1
  406. package/pack.js +0 -805
  407. package/policy.d.ts.map +0 -1
  408. package/progress.d.ts.map +0 -1
  409. package/progress.js +0 -645
  410. package/protocol.d.ts.map +0 -1
  411. package/protocol.js +0 -8334
  412. package/schemas/audit.schema.json +0 -226
  413. package/schemas/capability.schema.json +0 -113
  414. package/schemas/envelope.schema.json +0 -162
  415. package/schemas/memory.schema.json +0 -51
  416. package/schemas/observation.schema.json +0 -113
  417. package/schemas/plan.schema.json +0 -208
  418. package/schemas/progress.schema.json +0 -126
  419. package/schemas/proposal.schema.json +0 -68
  420. package/schemas/session.schema.json +0 -82
  421. package/schemas/tool.schema.json +0 -94
  422. package/server.d.ts.map +0 -1
  423. package/server.js +0 -28877
  424. package/umd-example.html +0 -18
  425. package/umd.d.ts.map +0 -1
  426. /package/{bun.d.ts → dist/bun.d.ts} +0 -0
  427. /package/{cli.d.ts → dist/cli.d.ts} +0 -0
  428. /package/{companion.d.ts → dist/companion.d.ts} +0 -0
  429. /package/{crossbrowser.d.ts → dist/crossbrowser.d.ts} +0 -0
  430. /package/{dashdone.d.ts → dist/dashdone.d.ts} +0 -0
  431. /package/{deno.d.ts → dist/deno.d.ts} +0 -0
  432. /package/{hardening.d.ts → dist/hardening.d.ts} +0 -0
  433. /package/{headless.d.ts → dist/headless.d.ts} +0 -0
  434. /package/{http.d.ts → dist/http.d.ts} +0 -0
  435. /package/{index.d.ts → dist/index.d.ts} +0 -0
  436. /package/{mcp.d.ts → dist/mcp.d.ts} +0 -0
  437. /package/{memory.d.ts → dist/memory.d.ts} +0 -0
  438. /package/{node.d.ts → dist/node.d.ts} +0 -0
  439. /package/{pack.d.ts → dist/pack.d.ts} +0 -0
  440. /package/{policy.d.ts → dist/policy.d.ts} +0 -0
  441. /package/{progress.d.ts → dist/progress.d.ts} +0 -0
  442. /package/{protocol.d.ts → dist/protocol.d.ts} +0 -0
  443. /package/{server.d.ts → dist/server.d.ts} +0 -0
  444. /package/{umd.d.ts → dist/umd.d.ts} +0 -0
@@ -0,0 +1,2120 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { composeworkflow, newworkflowrun, resolvevariable, runstep, runworkflow, workflowstepof } from "../workflow.js";
3
+ import {
4
+ applyretry,
5
+ applyruntimeout,
6
+ applytimeout,
7
+ backoffdelay,
8
+ branchof,
9
+ cancellederror,
10
+ choosebranch,
11
+ conditionof,
12
+ controlflowkinds,
13
+ controlsteps,
14
+ controlsummary,
15
+ defaultloopbound,
16
+ evaluatecondition,
17
+ foreachof,
18
+ iscontrolflowkind,
19
+ joinbranches,
20
+ loopof,
21
+ parallelof,
22
+ repeatuntilof,
23
+ runcontrolstep,
24
+ tryof,
25
+ whileof,
26
+ controlexecutor,
27
+ } from "../workflow.js";
28
+ import { actionrisk, dryrunprojection, isworkflowkind, validatestep } from "../policy.js";
29
+ import { outcomeresponse, parseworkflowproposal, workflowoutcome, workflowreport } from "../protocol.js";
30
+ import { protocolversion } from "../types.js";
31
+ import { loopshare, recordworkflow, workflowevidences } from "../progress.js";
32
+ import { sessionmemory } from "../memory.js";
33
+ import type {
34
+ agentplan,
35
+ agentsession,
36
+ controlflowdecision,
37
+ retryattempt,
38
+ runlogentry,
39
+ timeoutabort,
40
+ toolstep,
41
+ variablescope,
42
+ workflowstep,
43
+ } from "../types.js";
44
+
45
+ const now = 1_800_000_000_000;
46
+ const session: agentsession = {
47
+ id: "sess",
48
+ tabid: 4,
49
+ origin: "https://example.com",
50
+ startedat: now - 1000,
51
+ expiresat: now + 600_000,
52
+ grants: ["https://example.com"],
53
+ };
54
+ const plan: agentplan = {
55
+ id: "run",
56
+ objective: "Run the reviewed workflow with control flow",
57
+ origin: "https://example.com",
58
+ steps: [],
59
+ createdat: now - 2000,
60
+ expiresat: now + 600_000,
61
+ state: "approved",
62
+ };
63
+
64
+ function kindallowed(kind: string): boolean {
65
+ try {
66
+ actionrisk(kind as toolstep["kind"]);
67
+ return true;
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
72
+ function riskof(kind: string): "read" | "interaction" | "sensitive" {
73
+ return actionrisk(kind as toolstep["kind"]);
74
+ }
75
+
76
+ /** Builds one control flow step with its reviewed payload serialized into options. */
77
+ function controlstep(id: string, kind: string, payload: Record<string, unknown>): workflowstep {
78
+ const parsed = workflowstepof({ id, kind, label: `The ${kind} step`, options: JSON.stringify(payload) });
79
+ if (!parsed) throw new Error(`The ${kind} step did not normalize.`);
80
+ return parsed;
81
+ }
82
+
83
+ /** Builds one plain child step of a control body. */
84
+ function childstep(id: string, label: string, extra: Record<string, unknown> = {}): workflowstep {
85
+ const parsed = workflowstepof({ id, kind: "wait", label, value: "10", ...extra });
86
+ if (!parsed) throw new Error(`The child step ${id} did not normalize.`);
87
+ return parsed;
88
+ }
89
+
90
+ const rootscope = (
91
+ variables: Array<{
92
+ name: string;
93
+ kind: "string" | "number" | "boolean" | "list" | "element";
94
+ value: string | number | boolean | string[];
95
+ }>,
96
+ ): variablescope[] => [
97
+ {
98
+ name: "root",
99
+ variables: variables.map((variable) => ({
100
+ name: variable.name,
101
+ kind: variable.kind,
102
+ value: variable.value,
103
+ setat: now,
104
+ })),
105
+ },
106
+ ];
107
+
108
+ class fakeadapter {
109
+ private readonly data = new Map<string, unknown>();
110
+ async get<T>(key: string): Promise<T | undefined> {
111
+ return this.data.get(key) as T | undefined;
112
+ }
113
+ async set<T>(key: string, value: T): Promise<void> {
114
+ this.data.set(key, value);
115
+ }
116
+ }
117
+
118
+ describe("control flow kinds and payload grammar", () => {
119
+ it("lists the control kinds inside the risk table and the workflow family", () => {
120
+ expect(controlflowkinds).toEqual([
121
+ "condition",
122
+ "branch",
123
+ "loop",
124
+ "repeatuntil",
125
+ "whileloop",
126
+ "foreach",
127
+ "parallel",
128
+ "trycatch",
129
+ ]);
130
+ for (const kind of controlflowkinds) {
131
+ expect(iscontrolflowkind(kind)).toBe(true);
132
+ expect(isworkflowkind(kind as toolstep["kind"])).toBe(true);
133
+ expect(kindallowed(kind)).toBe(true);
134
+ }
135
+ expect(iscontrolflowkind("click")).toBe(false);
136
+ expect(actionrisk("condition")).toBe("read");
137
+ expect(actionrisk("branch")).toBe("read");
138
+ expect(actionrisk("loop")).toBe("interaction");
139
+ expect(actionrisk("repeatuntil")).toBe("interaction");
140
+ expect(actionrisk("whileloop")).toBe("interaction");
141
+ expect(actionrisk("foreach")).toBe("interaction");
142
+ expect(actionrisk("parallel")).toBe("interaction");
143
+ expect(actionrisk("trycatch")).toBe("interaction");
144
+ });
145
+
146
+ it("normalizes condition and branch payloads with unique paths and a mandatory else", () => {
147
+ expect(
148
+ conditionof({ expression: { left: { ref: "ready" }, operator: "not", result: "stop", resultkind: "boolean" } }),
149
+ ).toBeDefined();
150
+ expect(
151
+ conditionof({
152
+ expression: {
153
+ left: { literal: 1 },
154
+ right: { literal: 2 },
155
+ operator: "add",
156
+ result: "sum",
157
+ resultkind: "number",
158
+ },
159
+ }),
160
+ ).toBeUndefined();
161
+ expect(conditionof({})).toBeUndefined();
162
+ const branch = branchof({
163
+ paths: [
164
+ {
165
+ name: "fresh",
166
+ when: {
167
+ left: { ref: "count" },
168
+ right: { literal: 0 },
169
+ operator: "equal",
170
+ result: "isfresh",
171
+ resultkind: "boolean",
172
+ },
173
+ steps: [childstep("b1", "Fresh path")],
174
+ },
175
+ { name: "always", steps: [childstep("b2", "Unconditional path")] },
176
+ ],
177
+ else: { name: "fallback", steps: [] },
178
+ });
179
+ if (!branch) throw new Error("The reviewed branch payload did not normalize.");
180
+ expect(branch.paths).toHaveLength(2);
181
+ expect(branch.paths[0]?.when?.operator).toBe("equal");
182
+ expect(branch.paths[1]?.when).toBeUndefined();
183
+ expect(branch.else.steps).toEqual([]);
184
+ expect(
185
+ branchof({
186
+ paths: [
187
+ { name: "dup", steps: [childstep("b1", "One")] },
188
+ { name: "dup", steps: [childstep("b2", "Two")] },
189
+ ],
190
+ else: { name: "else", steps: [] },
191
+ }),
192
+ ).toBeUndefined();
193
+ expect(branchof({ paths: [{ name: "only", steps: [childstep("b1", "One")] }] })).toBeUndefined();
194
+ expect(
195
+ branchof({ paths: [{ name: "only", steps: [childstep("b1", "One")] }], else: { name: "only", steps: [] } }),
196
+ ).toBeUndefined();
197
+ expect(
198
+ branchof({
199
+ paths: [
200
+ {
201
+ name: "only",
202
+ when: { left: { literal: 1 }, right: { literal: 1 }, operator: "add", result: "x", resultkind: "number" },
203
+ steps: [childstep("b1", "One")],
204
+ },
205
+ ],
206
+ else: { name: "else", steps: [] },
207
+ }),
208
+ ).toBeUndefined();
209
+ expect(
210
+ branchof({
211
+ paths: [{ name: "only", steps: [childstep("b1", "One")] }],
212
+ else: { name: "else", steps: [childstep("b2", "Two")] },
213
+ extra: true,
214
+ }),
215
+ ).toBeDefined();
216
+ });
217
+
218
+ it("normalizes loop, repeat until, while and foreach payloads with user configured bounds", () => {
219
+ expect(
220
+ loopof({ list: "items", item: "item", index: "index", bound: 50, steps: [childstep("b1", "Body")] }),
221
+ ).toBeDefined();
222
+ expect(loopof({ list: "items", item: "item", index: "index", steps: [childstep("b1", "Body")] })).toBeDefined();
223
+ expect(loopof({ list: "items", item: "items", index: "index", steps: [childstep("b1", "Body")] })).toBeUndefined();
224
+ expect(loopof({ list: "items", item: "item", index: "item", steps: [childstep("b1", "Body")] })).toBeUndefined();
225
+ expect(
226
+ loopof({ list: "items", item: "item", index: "index", bound: 0, steps: [childstep("b1", "Body")] }),
227
+ ).toBeUndefined();
228
+ expect(
229
+ loopof({ list: "items", item: "item", index: "index", bound: 2.5, steps: [childstep("b1", "Body")] }),
230
+ ).toBeUndefined();
231
+ expect(loopof({ list: "items", item: "item", index: "index", steps: [] })).toBeUndefined();
232
+ expect(
233
+ repeatuntilof({
234
+ until: {
235
+ left: { ref: "count" },
236
+ right: { literal: 3 },
237
+ operator: "greaterequal",
238
+ result: "done",
239
+ resultkind: "boolean",
240
+ },
241
+ bound: 10,
242
+ steps: [childstep("b1", "Body")],
243
+ }),
244
+ ).toBeDefined();
245
+ expect(
246
+ repeatuntilof({
247
+ until: { left: { literal: 1 }, right: { literal: 2 }, operator: "add", result: "n", resultkind: "number" },
248
+ steps: [childstep("b1", "Body")],
249
+ }),
250
+ ).toBeUndefined();
251
+ expect(
252
+ whileof({
253
+ while: { left: { ref: "count" }, right: { literal: 3 }, operator: "less", result: "go", resultkind: "boolean" },
254
+ bound: 4,
255
+ steps: [childstep("b1", "Body")],
256
+ }),
257
+ ).toBeDefined();
258
+ expect(
259
+ whileof({
260
+ while: { left: { ref: "count" }, right: { literal: 3 }, operator: "less", result: "go", resultkind: "boolean" },
261
+ steps: [childstep("b1", "Body")],
262
+ }),
263
+ ).toBeUndefined();
264
+ expect(
265
+ foreachof({ selector: "li.item", item: "row", index: "rowindex", steps: [childstep("b1", "Body")] }),
266
+ ).toBeDefined();
267
+ expect(
268
+ foreachof({ selector: " ", item: "row", index: "rowindex", steps: [childstep("b1", "Body")] }),
269
+ ).toBeUndefined();
270
+ expect(
271
+ foreachof({ selector: "li.item", item: "row", index: "row", steps: [childstep("b1", "Body")] }),
272
+ ).toBeUndefined();
273
+ });
274
+
275
+ it("normalizes parallel and try payloads with join, retry and timeout policies", () => {
276
+ expect(
277
+ parallelof({
278
+ branches: [
279
+ { id: "one", steps: [childstep("a1", "A")] },
280
+ { id: "two", steps: [childstep("b1", "B")] },
281
+ ],
282
+ join: { strategy: "last", onfail: "cancel" },
283
+ }),
284
+ ).toBeDefined();
285
+ expect(
286
+ parallelof({
287
+ branches: [
288
+ { id: "one", steps: [childstep("a1", "A")] },
289
+ { id: "one", steps: [childstep("b1", "B")] },
290
+ ],
291
+ join: { strategy: "first", onfail: "continue" },
292
+ }),
293
+ ).toBeUndefined();
294
+ expect(
295
+ parallelof({
296
+ branches: [{ id: "one", steps: [childstep("a1", "A")] }],
297
+ join: { strategy: "merge", onfail: "continue" },
298
+ }),
299
+ ).toBeUndefined();
300
+ expect(
301
+ parallelof({
302
+ branches: [{ id: "one", steps: [childstep("a1", "A")] }],
303
+ join: { strategy: "fail", onfail: "ignore" },
304
+ }),
305
+ ).toBeUndefined();
306
+ expect(
307
+ tryof({ steps: [childstep("f1", "Fragile")], catch: { steps: [childstep("c1", "Handler")] } }),
308
+ ).toBeDefined();
309
+ expect(
310
+ tryof({
311
+ steps: [childstep("f1", "Fragile")],
312
+ catch: { steps: [childstep("c1", "Handler")], rerun: true },
313
+ retry: {
314
+ attempts: 5,
315
+ backoff: { shape: "exponential", base: 100, jitter: 20 },
316
+ retryable: ["timeout", "pageunresponsive"],
317
+ },
318
+ timeout: { stepms: 4000, runms: 30000 },
319
+ }),
320
+ ).toBeDefined();
321
+ expect(tryof({ steps: [childstep("f1", "Fragile")] })).toBeUndefined();
322
+ expect(tryof({ steps: [childstep("f1", "Fragile")], catch: { steps: [] } })).toBeUndefined();
323
+ expect(
324
+ tryof({
325
+ steps: [childstep("f1", "Fragile")],
326
+ catch: { steps: [childstep("c1", "Handler")] },
327
+ retry: { attempts: 0, backoff: { shape: "fixed", base: 0, jitter: 0 }, retryable: ["timeout"] },
328
+ }),
329
+ ).toBeUndefined();
330
+ expect(
331
+ tryof({
332
+ steps: [childstep("f1", "Fragile")],
333
+ catch: { steps: [childstep("c1", "Handler")] },
334
+ retry: { attempts: 2, backoff: { shape: "wave", base: 0, jitter: 0 }, retryable: ["timeout"] },
335
+ }),
336
+ ).toBeUndefined();
337
+ expect(
338
+ tryof({
339
+ steps: [childstep("f1", "Fragile")],
340
+ catch: { steps: [childstep("c1", "Handler")] },
341
+ retry: { attempts: 2, backoff: { shape: "fixed", base: -1, jitter: 0 }, retryable: ["timeout"] },
342
+ }),
343
+ ).toBeUndefined();
344
+ expect(
345
+ tryof({
346
+ steps: [childstep("f1", "Fragile")],
347
+ catch: { steps: [childstep("c1", "Handler")] },
348
+ timeout: { stepms: -5 },
349
+ }),
350
+ ).toBeUndefined();
351
+ expect(
352
+ tryof({ steps: [childstep("f1", "Fragile")], catch: { steps: [childstep("c1", "Handler")] }, timeout: {} }),
353
+ ).toBeUndefined();
354
+ });
355
+
356
+ it("collects every nested child step of a control payload recursively", () => {
357
+ const nested = controlstep("l1", "loop", {
358
+ loop: {
359
+ list: "items",
360
+ item: "item",
361
+ index: "index",
362
+ steps: [
363
+ childstep("b1", "Body read"),
364
+ controlstep("p1", "parallel", {
365
+ parallel: {
366
+ branches: [
367
+ { id: "one", steps: [childstep("a1", "Lane one")] },
368
+ { id: "two", steps: [childstep("a2", "Lane two")] },
369
+ ],
370
+ join: { strategy: "first", onfail: "continue" },
371
+ },
372
+ }),
373
+ controlstep("t1", "trycatch", {
374
+ try: { steps: [childstep("f1", "Fragile")], catch: { steps: [childstep("c1", "Handler")] } },
375
+ }),
376
+ ],
377
+ },
378
+ });
379
+ const children = controlsteps(nested);
380
+ expect(children.map((child) => child.id)).toEqual(["b1", "p1", "a1", "a2", "t1", "f1", "c1"]);
381
+ expect(controlsteps(childstep("b1", "Plain"))).toEqual([]);
382
+ const malformed = controlstep("l1", "loop", { loop: { list: "items", item: "item", index: "index" } });
383
+ expect(controlsteps(malformed)).toEqual([]);
384
+ });
385
+
386
+ it("summarizes every control kind for the review panel", () => {
387
+ expect(
388
+ controlsummary(
389
+ controlstep("c1", "condition", {
390
+ condition: { expression: { left: { ref: "ready" }, operator: "not", result: "stop", resultkind: "boolean" } },
391
+ }),
392
+ ),
393
+ ).toMatchObject({ kind: "condition", expression: expect.stringContaining("not") });
394
+ expect(
395
+ controlsummary(
396
+ controlstep("b1", "branch", {
397
+ branch: { paths: [{ name: "fast", steps: [childstep("x1", "Fast")] }], else: { name: "slow", steps: [] } },
398
+ }),
399
+ ),
400
+ ).toMatchObject({ kind: "branch", paths: ["fast"], elsepath: "slow" });
401
+ expect(
402
+ controlsummary(
403
+ controlstep("l1", "loop", {
404
+ loop: { list: "items", item: "item", index: "index", steps: [childstep("x1", "Body")] },
405
+ }),
406
+ ),
407
+ ).toMatchObject({ kind: "loop", list: "items", item: "item", index: "index", bound: defaultloopbound });
408
+ expect(
409
+ controlsummary(
410
+ controlstep("w1", "whileloop", {
411
+ while: {
412
+ while: { left: { literal: true }, operator: "not", result: "go", resultkind: "boolean" },
413
+ bound: 7,
414
+ steps: [childstep("x1", "Body")],
415
+ },
416
+ }),
417
+ ),
418
+ ).toMatchObject({ kind: "whileloop", bound: 7 });
419
+ expect(
420
+ controlsummary(
421
+ controlstep("p1", "parallel", {
422
+ parallel: {
423
+ branches: [
424
+ { id: "one", steps: [childstep("x1", "One")] },
425
+ { id: "two", steps: [childstep("x2", "Two")] },
426
+ ],
427
+ join: { strategy: "fail", onfail: "cancel" },
428
+ },
429
+ }),
430
+ ),
431
+ ).toMatchObject({ kind: "parallel", branches: ["one", "two"], strategy: "fail", onfail: "cancel" });
432
+ expect(
433
+ controlsummary(
434
+ controlstep("t1", "trycatch", {
435
+ try: {
436
+ steps: [childstep("f1", "Fragile")],
437
+ catch: { steps: [childstep("c1", "Handler")], rerun: true },
438
+ retry: { attempts: 3, backoff: { shape: "exponential", base: 100, jitter: 10 }, retryable: ["timeout"] },
439
+ timeout: { stepms: 500, runms: 5000 },
440
+ },
441
+ }),
442
+ ),
443
+ ).toMatchObject({ kind: "trycatch", attempts: 3, rerun: true, stepms: 500, runms: 5000 });
444
+ expect(controlsummary(childstep("b1", "Plain"))).toBeUndefined();
445
+ });
446
+ });
447
+
448
+ describe("condition and branch evaluation", () => {
449
+ it("evaluates conditions over extracted values with no page side effect", () => {
450
+ const condition = conditionof({
451
+ expression: {
452
+ left: { ref: "count" },
453
+ right: { literal: 3 },
454
+ operator: "greaterequal",
455
+ result: "done",
456
+ resultkind: "boolean",
457
+ },
458
+ });
459
+ if (!condition) throw new Error("The condition payload did not normalize.");
460
+ expect(evaluatecondition(condition, rootscope([{ name: "count", kind: "number", value: 3 }]))).toBe(true);
461
+ expect(evaluatecondition(condition, rootscope([{ name: "count", kind: "number", value: 2 }]))).toBe(false);
462
+ expect(() => evaluatecondition(condition, rootscope([]))).toThrow("undefined variable count");
463
+ expect(() =>
464
+ evaluatecondition(
465
+ {
466
+ expression: {
467
+ left: { literal: 1 },
468
+ right: { literal: 2 },
469
+ operator: "add",
470
+ result: "sum",
471
+ resultkind: "boolean",
472
+ },
473
+ },
474
+ [],
475
+ ),
476
+ ).toThrow("boolean");
477
+ });
478
+
479
+ it("chooses the first matching branch path and falls back to the else path", () => {
480
+ const branch = branchof({
481
+ paths: [
482
+ {
483
+ name: "empty",
484
+ when: {
485
+ left: { ref: "count" },
486
+ right: { literal: 0 },
487
+ operator: "equal",
488
+ result: "isempty",
489
+ resultkind: "boolean",
490
+ },
491
+ steps: [childstep("b1", "Empty path")],
492
+ },
493
+ {
494
+ name: "small",
495
+ when: {
496
+ left: { ref: "count" },
497
+ right: { literal: 10 },
498
+ operator: "less",
499
+ result: "issmall",
500
+ resultkind: "boolean",
501
+ },
502
+ steps: [childstep("b2", "Small path")],
503
+ },
504
+ ],
505
+ else: { name: "large", steps: [childstep("b3", "Large path")] },
506
+ });
507
+ if (!branch) throw new Error("The branch payload did not normalize.");
508
+ const empty = choosebranch({
509
+ stepid: "br1",
510
+ branch,
511
+ scopes: rootscope([{ name: "count", kind: "number", value: 0 }]),
512
+ now,
513
+ });
514
+ expect(empty.outcome.path).toBe("empty");
515
+ expect(empty.outcome.reason).toContain("condition of the path empty holds");
516
+ expect(empty.steps.map((step) => step.id)).toEqual(["b1"]);
517
+ const small = choosebranch({
518
+ stepid: "br1",
519
+ branch,
520
+ scopes: rootscope([{ name: "count", kind: "number", value: 5 }]),
521
+ now,
522
+ });
523
+ expect(small.outcome.path).toBe("small");
524
+ const fallback = choosebranch({
525
+ stepid: "br1",
526
+ branch,
527
+ scopes: rootscope([{ name: "count", kind: "number", value: 50 }]),
528
+ now,
529
+ });
530
+ expect(fallback.outcome.path).toBe("large");
531
+ expect(fallback.outcome.reason).toContain("No path condition held");
532
+ expect(fallback.steps.map((step) => step.id)).toEqual(["b3"]);
533
+ expect(fallback.outcome.at).toBe(now);
534
+ });
535
+
536
+ it("matches branch paths over the page state of the snapshot accessor", () => {
537
+ const branch = branchof({
538
+ paths: [
539
+ {
540
+ name: "ready",
541
+ when: { left: { ref: "pageready" }, operator: "not", result: "notready", resultkind: "boolean" },
542
+ steps: [childstep("b1", "Wait for load")],
543
+ },
544
+ {
545
+ name: "shop",
546
+ when: {
547
+ left: { ref: "pageurl" },
548
+ right: { literal: "https://shop.example.com/cart" },
549
+ operator: "equal",
550
+ result: "oncart",
551
+ resultkind: "boolean",
552
+ },
553
+ steps: [childstep("b2", "Cart path")],
554
+ },
555
+ ],
556
+ else: { name: "other", steps: [] },
557
+ });
558
+ if (!branch) throw new Error("The branch payload did not normalize.");
559
+ const ready = choosebranch({
560
+ stepid: "br1",
561
+ branch,
562
+ scopes: rootscope([]),
563
+ pagestate: { url: "https://shop.example.com/cart", ready: true },
564
+ now,
565
+ });
566
+ expect(ready.outcome.path).toBe("shop");
567
+ const loading = choosebranch({
568
+ stepid: "br1",
569
+ branch,
570
+ scopes: rootscope([]),
571
+ pagestate: { url: "https://example.com", ready: false },
572
+ now,
573
+ });
574
+ expect(loading.outcome.path).toBe("ready");
575
+ const other = choosebranch({
576
+ stepid: "br1",
577
+ branch,
578
+ scopes: rootscope([]),
579
+ pagestate: { url: "https://other.example.com", ready: true },
580
+ now,
581
+ });
582
+ expect(other.outcome.path).toBe("other");
583
+ });
584
+ });
585
+
586
+ describe("loop family runners", () => {
587
+ const execute = async (dispatched: workflowstep): Promise<{ ok: boolean; summary: string }> => ({
588
+ ok: true,
589
+ summary: `ran ${dispatched.id}`,
590
+ });
591
+
592
+ it("iterates a list variable rebinding the item and index per iteration", async () => {
593
+ const step = controlstep("l1", "loop", {
594
+ loop: {
595
+ list: "items",
596
+ item: "item",
597
+ index: "index",
598
+ bound: 10,
599
+ steps: [
600
+ workflowstepof({
601
+ id: "b1",
602
+ kind: "wait",
603
+ label: "Read the row",
604
+ value: "row ${item} at ${index}",
605
+ }) as workflowstep,
606
+ ],
607
+ },
608
+ });
609
+ const seen: string[] = [];
610
+ const result = await runcontrolstep({
611
+ step,
612
+ scopes: rootscope([{ name: "items", kind: "list", value: ["a", "b", "c"] }]),
613
+ outputs: {},
614
+ execute: async (dispatched) => {
615
+ seen.push(`${dispatched.id}:${dispatched.value}`);
616
+ return { ok: true, summary: "ok" };
617
+ },
618
+ now,
619
+ });
620
+ expect(result.output.ok).toBe(true);
621
+ expect(seen).toEqual(["b1:row a at 0", "b1:row b at 1", "b1:row c at 2"]);
622
+ const decision = result.output.details?.control as controlflowdecision;
623
+ expect(decision.kind).toBe("loop");
624
+ expect(decision.loops?.map((counter) => counter.iteration)).toEqual([0, 1, 2]);
625
+ expect(result.log.some((entry) => entry.label.includes("iteration 2"))).toBe(true);
626
+ expect(
627
+ result.log.some(
628
+ (entry) => entry.details !== undefined && (entry.details as { iteration?: number }).iteration === 1,
629
+ ),
630
+ ).toBe(true);
631
+ });
632
+
633
+ it("refuses a list longer than the reviewed bound with nothing running and reports the overflow", async () => {
634
+ const step = controlstep("l1", "loop", {
635
+ loop: { list: "items", item: "item", index: "index", bound: 2, steps: [childstep("b1", "Body")] },
636
+ });
637
+ let runs = 0;
638
+ const result = await runcontrolstep({
639
+ step,
640
+ scopes: rootscope([{ name: "items", kind: "list", value: ["a", "b", "c"] }]),
641
+ outputs: {},
642
+ execute: async () => {
643
+ runs += 1;
644
+ return { ok: true, summary: "never" };
645
+ },
646
+ now,
647
+ });
648
+ expect(result.output.ok).toBe(false);
649
+ expect(result.output.summary).toContain("exceeds the reviewed safety bound of 2");
650
+ expect(runs).toBe(0);
651
+ });
652
+
653
+ it("fails the loop when an iteration fails and keeps the counters of the passes", async () => {
654
+ const step = controlstep("l1", "loop", {
655
+ loop: { list: "items", item: "item", index: "index", steps: [childstep("b1", "Body")] },
656
+ });
657
+ const result = await runcontrolstep({
658
+ step,
659
+ scopes: rootscope([{ name: "items", kind: "list", value: ["a", "b"] }]),
660
+ outputs: {},
661
+ execute: async (dispatched) =>
662
+ dispatched.value === "10" && dispatched.id === "b1"
663
+ ? { ok: dispatched.id === "b1" ? false : true, summary: dispatched.id === "b1" ? "the row refused" : "ok" }
664
+ : { ok: true, summary: "ok" },
665
+ now,
666
+ });
667
+ expect(result.output.ok).toBe(false);
668
+ expect(result.output.summary).toContain("failed at iteration 1");
669
+ const decision = result.output.details?.control as controlflowdecision;
670
+ expect(decision.loops?.at(0)?.ok).toBe(false);
671
+ });
672
+
673
+ it("runs nested loops tracking the outer and inner index paths for audit", async () => {
674
+ const inner = controlstep("l2", "loop", {
675
+ loop: {
676
+ list: "columns",
677
+ item: "column",
678
+ index: "columnindex",
679
+ steps: [
680
+ workflowstepof({
681
+ id: "b2",
682
+ kind: "wait",
683
+ label: "Read the cell",
684
+ value: "cell ${item}${column}",
685
+ }) as workflowstep,
686
+ ],
687
+ },
688
+ });
689
+ const outer = controlstep("l1", "loop", { loop: { list: "items", item: "item", index: "index", steps: [inner] } });
690
+ const seen: string[] = [];
691
+ const result = await runcontrolstep({
692
+ step: outer,
693
+ scopes: rootscope([
694
+ { name: "items", kind: "list", value: ["a", "b"] },
695
+ { name: "columns", kind: "list", value: ["1", "2"] },
696
+ ]),
697
+ outputs: {},
698
+ execute: async (dispatched) => {
699
+ seen.push(`${dispatched.value}`);
700
+ return { ok: true, summary: "ok" };
701
+ },
702
+ now,
703
+ });
704
+ expect(seen).toEqual(["cell a1", "cell a2", "cell b1", "cell b2"]);
705
+ const decision = result.output.details?.control as controlflowdecision;
706
+ expect(decision.loops?.map((counter) => counter.path)).toEqual(["l1[0]", "l1[1]"]);
707
+ const innerlog = result.log.filter((entry) => entry.stepid === "l2");
708
+ expect(innerlog.length).toBeGreaterThanOrEqual(4);
709
+ });
710
+
711
+ it("runs repeat until convergence inside the bound and reports the overflow honestly", async () => {
712
+ const converging = controlstep("r1", "repeatuntil", {
713
+ repeatuntil: {
714
+ until: {
715
+ left: { ref: "count" },
716
+ right: { literal: 3 },
717
+ operator: "greaterequal",
718
+ result: "done",
719
+ resultkind: "boolean",
720
+ },
721
+ bound: 8,
722
+ steps: [
723
+ workflowstepof({
724
+ id: "b1",
725
+ kind: "wait",
726
+ label: "Nudge the counter",
727
+ value: "1",
728
+ expression: {
729
+ left: { ref: "count" },
730
+ right: { literal: 1 },
731
+ operator: "add",
732
+ result: "count",
733
+ resultkind: "number",
734
+ },
735
+ }) as workflowstep,
736
+ ],
737
+ },
738
+ });
739
+ const converged = await runcontrolstep({
740
+ step: converging,
741
+ scopes: rootscope([{ name: "count", kind: "number", value: 0 }]),
742
+ outputs: {},
743
+ execute,
744
+ now,
745
+ });
746
+ expect(converged.output.ok).toBe(true);
747
+ expect(converged.output.summary).toContain("converged after 3 iterations");
748
+ const decision = converged.output.details?.control as controlflowdecision;
749
+ expect(decision.loops).toHaveLength(3);
750
+
751
+ const stuck = controlstep("r1", "repeatuntil", {
752
+ repeatuntil: {
753
+ until: { left: { literal: true }, operator: "not", result: "never", resultkind: "boolean" },
754
+ bound: 2,
755
+ steps: [childstep("b1", "Body")],
756
+ },
757
+ });
758
+ const overflow = await runcontrolstep({ step: stuck, scopes: rootscope([]), outputs: {}, execute, now });
759
+ expect(overflow.output.ok).toBe(false);
760
+ expect(overflow.output.summary).toContain("never converged within the reviewed safety bound of 2");
761
+ });
762
+
763
+ it("runs while loops that end when the condition stops and refuses the endless ones at the bound", async () => {
764
+ const ending = controlstep("w1", "whileloop", {
765
+ while: {
766
+ while: { left: { ref: "count" }, right: { literal: 3 }, operator: "less", result: "go", resultkind: "boolean" },
767
+ bound: 10,
768
+ steps: [
769
+ workflowstepof({
770
+ id: "b1",
771
+ kind: "wait",
772
+ label: "Grow the counter",
773
+ value: "1",
774
+ expression: {
775
+ left: { ref: "count" },
776
+ right: { literal: 1 },
777
+ operator: "add",
778
+ result: "count",
779
+ resultkind: "number",
780
+ },
781
+ }) as workflowstep,
782
+ ],
783
+ },
784
+ });
785
+ const ended = await runcontrolstep({
786
+ step: ending,
787
+ scopes: rootscope([{ name: "count", kind: "number", value: 0 }]),
788
+ outputs: {},
789
+ execute,
790
+ now,
791
+ });
792
+ expect(ended.output.ok).toBe(true);
793
+ expect(ended.output.summary).toContain("ended after 3 iterations");
794
+ expect(resolvevariable(ended.scopes, "count")?.value).toBe(3);
795
+
796
+ const endless = controlstep("w1", "whileloop", {
797
+ while: {
798
+ while: { left: { literal: false }, operator: "not", result: "forever", resultkind: "boolean" },
799
+ bound: 2,
800
+ steps: [childstep("b1", "Body")],
801
+ },
802
+ });
803
+ const overflow = await runcontrolstep({ step: endless, scopes: rootscope([]), outputs: {}, execute, now });
804
+ expect(overflow.output.ok).toBe(false);
805
+ expect(overflow.output.summary).toContain(
806
+ "hit its reviewed safety bound of 2 iterations while its condition still held",
807
+ );
808
+
809
+ const nevers = controlstep("w1", "whileloop", {
810
+ while: {
811
+ while: { left: { literal: true }, operator: "not", result: "never", resultkind: "boolean" },
812
+ bound: 4,
813
+ steps: [childstep("b1", "Body")],
814
+ },
815
+ });
816
+ const zero = await runcontrolstep({
817
+ step: nevers,
818
+ scopes: rootscope([]),
819
+ outputs: {},
820
+ execute: async () => {
821
+ throw new Error("never");
822
+ },
823
+ now,
824
+ });
825
+ expect(zero.output.ok).toBe(true);
826
+ expect(zero.output.summary).toContain("ended after 0 iterations");
827
+ });
828
+
829
+ it("runs foreach over matched elements and reports the empty match as zero iterations", async () => {
830
+ const step = controlstep("f1", "foreach", {
831
+ foreach: {
832
+ selector: "li.row",
833
+ item: "row",
834
+ index: "rowindex",
835
+ steps: [
836
+ workflowstepof({
837
+ id: "b1",
838
+ kind: "wait",
839
+ label: "Read the element",
840
+ value: "element ${row} at ${rowindex}",
841
+ }) as workflowstep,
842
+ ],
843
+ },
844
+ });
845
+ const seen: string[] = [];
846
+ const filled = await runcontrolstep({
847
+ step,
848
+ scopes: rootscope([]),
849
+ outputs: {},
850
+ execute: async (dispatched) => {
851
+ seen.push(`${dispatched.value}`);
852
+ return { ok: true, summary: "ok" };
853
+ },
854
+ now,
855
+ resolveelements: async (selector) =>
856
+ selector === "li.row" ? ["li.row:nth-of-type(1)", "li.row:nth-of-type(2)"] : [],
857
+ });
858
+ expect(filled.output.ok).toBe(true);
859
+ expect(seen).toEqual(["element li.row:nth-of-type(1) at 0", "element li.row:nth-of-type(2) at 1"]);
860
+ expect(resolvevariable(filled.scopes, "row")?.kind).toBe("element");
861
+
862
+ const empty = await runcontrolstep({
863
+ step,
864
+ scopes: rootscope([]),
865
+ outputs: {},
866
+ execute,
867
+ now,
868
+ resolveelements: async () => [],
869
+ });
870
+ expect(empty.output.ok).toBe(true);
871
+ expect(empty.output.summary).toContain("matched no element and the foreach ran zero iterations");
872
+
873
+ await expect(runcontrolstep({ step, scopes: rootscope([]), outputs: {}, execute, now })).rejects.toThrow(
874
+ "element resolver",
875
+ );
876
+ });
877
+ });
878
+
879
+ describe("parallel branches and joins", () => {
880
+ it("runs branches concurrently with isolated scopes and merges their writes at the join", async () => {
881
+ const step = controlstep("p1", "parallel", {
882
+ parallel: {
883
+ branches: [
884
+ {
885
+ id: "one",
886
+ steps: [
887
+ workflowstepof({
888
+ id: "a1",
889
+ kind: "wait",
890
+ label: "Lane one",
891
+ value: "1",
892
+ expression: {
893
+ left: { literal: 10 },
894
+ right: { literal: 1 },
895
+ operator: "add",
896
+ result: "firsttotal",
897
+ resultkind: "number",
898
+ },
899
+ }) as workflowstep,
900
+ ],
901
+ },
902
+ {
903
+ id: "two",
904
+ steps: [
905
+ workflowstepof({
906
+ id: "b1",
907
+ kind: "wait",
908
+ label: "Lane two",
909
+ value: "2",
910
+ expression: {
911
+ left: { literal: 20 },
912
+ right: { literal: 2 },
913
+ operator: "add",
914
+ result: "secondtotal",
915
+ resultkind: "number",
916
+ },
917
+ }) as workflowstep,
918
+ ],
919
+ },
920
+ ],
921
+ join: { strategy: "last", onfail: "continue" },
922
+ },
923
+ });
924
+ const result = await runcontrolstep({
925
+ step,
926
+ scopes: rootscope([]),
927
+ outputs: {},
928
+ execute: async () => ({ ok: true, summary: "lane ok" }),
929
+ now,
930
+ });
931
+ expect(result.output.ok).toBe(true);
932
+ expect(result.output.summary).toContain("ran 2 concurrent branches");
933
+ expect(resolvevariable(result.scopes, "firsttotal")?.value).toBe(11);
934
+ expect(resolvevariable(result.scopes, "secondtotal")?.value).toBe(22);
935
+ const decision = result.output.details?.control as controlflowdecision;
936
+ expect(decision.kind).toBe("join");
937
+ expect(decision.join?.strategy).toBe("last");
938
+ expect(decision.join?.conflicts).toEqual([]);
939
+ expect(decision.join?.merged).toEqual(["firsttotal", "secondtotal"]);
940
+ expect(decision.branches?.map((outcome) => outcome.branchid)).toEqual(["one", "two"]);
941
+ });
942
+
943
+ it("keeps sibling variables invisible across the isolated branch scopes", async () => {
944
+ const step = controlstep("p1", "parallel", {
945
+ parallel: {
946
+ branches: [
947
+ {
948
+ id: "one",
949
+ steps: [
950
+ workflowstepof({
951
+ id: "a1",
952
+ kind: "wait",
953
+ label: "Lane one",
954
+ value: "1",
955
+ expression: {
956
+ left: { literal: 1 },
957
+ right: { literal: 1 },
958
+ operator: "add",
959
+ result: "sibling",
960
+ resultkind: "number",
961
+ },
962
+ }) as workflowstep,
963
+ ],
964
+ },
965
+ {
966
+ id: "two",
967
+ steps: [
968
+ workflowstepof({
969
+ id: "b1",
970
+ kind: "wait",
971
+ label: "Read the sibling",
972
+ value: "value ${sibling}",
973
+ }) as workflowstep,
974
+ ],
975
+ },
976
+ ],
977
+ join: { strategy: "last", onfail: "continue" },
978
+ },
979
+ });
980
+ const result = await runcontrolstep({
981
+ step,
982
+ scopes: rootscope([]),
983
+ outputs: {},
984
+ execute: async () => ({ ok: true, summary: "lane ok" }),
985
+ now,
986
+ });
987
+ const decision = result.output.details?.control as controlflowdecision;
988
+ expect(decision.branches?.find((outcome) => outcome.branchid === "two")?.ok).toBe(false);
989
+ expect(result.output.summary).toContain("merged 1 variable");
990
+ });
991
+
992
+ it("resolves join conflicts under the first, last and fail strategies", () => {
993
+ const branches = [
994
+ {
995
+ id: "one",
996
+ order: 0,
997
+ ok: true,
998
+ cancelled: false,
999
+ variables: [
1000
+ { name: "shared", kind: "string" as const, value: "first lane", setat: now },
1001
+ { name: "onlyone", kind: "number" as const, value: 1, setat: now },
1002
+ ],
1003
+ },
1004
+ {
1005
+ id: "two",
1006
+ order: 1,
1007
+ ok: true,
1008
+ cancelled: false,
1009
+ variables: [{ name: "shared", kind: "string" as const, value: "second lane", setat: now }],
1010
+ },
1011
+ ];
1012
+ const last = joinbranches({ stepid: "p1", branches, strategy: "last", now });
1013
+ expect(last.ok).toBe(true);
1014
+ expect(last.merged.find((variable) => variable.name === "shared")?.value).toBe("second lane");
1015
+ expect(last.conflicts).toEqual(["shared"]);
1016
+ expect(last.summary).toContain("resolved by the strategy");
1017
+ const first = joinbranches({ stepid: "p1", branches, strategy: "first", now });
1018
+ expect(first.ok).toBe(true);
1019
+ expect(first.merged.find((variable) => variable.name === "shared")?.value).toBe("first lane");
1020
+ const failed = joinbranches({ stepid: "p1", branches, strategy: "fail", now });
1021
+ expect(failed.ok).toBe(false);
1022
+ expect(failed.conflicts).toEqual(["shared"]);
1023
+ expect(failed.summary).toContain("refused the conflicting writes of shared");
1024
+ const cancelledbranch = { id: "one", order: 0, ok: true, cancelled: true, variables: branches[0]!.variables };
1025
+ const cancelledonly = joinbranches({ stepid: "p1", branches: [cancelledbranch], strategy: "fail", now });
1026
+ expect(cancelledonly.ok).toBe(true);
1027
+ expect(cancelledonly.merged).toEqual([]);
1028
+ });
1029
+
1030
+ it("cancels or continues sibling branches under the reviewed join policy on branch failure", async () => {
1031
+ const payload = (onfail: "cancel" | "continue"): workflowstep =>
1032
+ controlstep("p1", "parallel", {
1033
+ parallel: {
1034
+ branches: [
1035
+ { id: "one", steps: [childstep("a1", "Failing lane")] },
1036
+ {
1037
+ id: "two",
1038
+ steps: [
1039
+ workflowstepof({
1040
+ id: "b1",
1041
+ kind: "wait",
1042
+ label: "Sibling lane",
1043
+ value: "2",
1044
+ expression: {
1045
+ left: { literal: 2 },
1046
+ right: { literal: 2 },
1047
+ operator: "add",
1048
+ result: "siblingtotal",
1049
+ resultkind: "number",
1050
+ },
1051
+ }) as workflowstep,
1052
+ ],
1053
+ },
1054
+ ],
1055
+ join: { strategy: "last", onfail },
1056
+ },
1057
+ });
1058
+ const failing = async (dispatched: workflowstep): Promise<{ ok: boolean; summary: string }> =>
1059
+ dispatched.id === "a1" ? { ok: false, summary: "the lane failed" } : { ok: true, summary: "lane ok" };
1060
+ const cancelled = await runcontrolstep({
1061
+ step: payload("cancel"),
1062
+ scopes: rootscope([]),
1063
+ outputs: {},
1064
+ execute: failing,
1065
+ now,
1066
+ });
1067
+ expect(cancelled.output.ok).toBe(false);
1068
+ expect(cancelled.output.summary).toContain("failed on branch one");
1069
+ const decision = cancelled.output.details?.control as controlflowdecision;
1070
+ expect(decision.branches?.find((outcome) => outcome.branchid === "two")?.cancelled).toBe(true);
1071
+ expect(decision.join?.merged).toEqual([]);
1072
+
1073
+ const continued = await runcontrolstep({
1074
+ step: payload("continue"),
1075
+ scopes: rootscope([]),
1076
+ outputs: {},
1077
+ execute: failing,
1078
+ now,
1079
+ });
1080
+ expect(continued.output.ok).toBe(true);
1081
+ expect(resolvevariable(continued.scopes, "siblingtotal")?.value).toBe(4);
1082
+ const continuedecision = continued.output.details?.control as controlflowdecision;
1083
+ expect(continuedecision.branches?.find((outcome) => outcome.branchid === "one")?.ok).toBe(false);
1084
+ });
1085
+
1086
+ it("refuses the whole parallel block when the fail strategy meets conflicting writes", async () => {
1087
+ const step = controlstep("p1", "parallel", {
1088
+ parallel: {
1089
+ branches: [
1090
+ {
1091
+ id: "one",
1092
+ steps: [
1093
+ workflowstepof({
1094
+ id: "a1",
1095
+ kind: "wait",
1096
+ label: "Lane one",
1097
+ value: "1",
1098
+ expression: {
1099
+ left: { literal: 1 },
1100
+ right: { literal: 1 },
1101
+ operator: "add",
1102
+ result: "shared",
1103
+ resultkind: "number",
1104
+ },
1105
+ }) as workflowstep,
1106
+ ],
1107
+ },
1108
+ {
1109
+ id: "two",
1110
+ steps: [
1111
+ workflowstepof({
1112
+ id: "b1",
1113
+ kind: "wait",
1114
+ label: "Lane two",
1115
+ value: "2",
1116
+ expression: {
1117
+ left: { literal: 2 },
1118
+ right: { literal: 2 },
1119
+ operator: "add",
1120
+ result: "shared",
1121
+ resultkind: "number",
1122
+ },
1123
+ }) as workflowstep,
1124
+ ],
1125
+ },
1126
+ ],
1127
+ join: { strategy: "fail", onfail: "continue" },
1128
+ },
1129
+ });
1130
+ const result = await runcontrolstep({
1131
+ step,
1132
+ scopes: rootscope([]),
1133
+ outputs: {},
1134
+ execute: async () => ({ ok: true, summary: "lane ok" }),
1135
+ now,
1136
+ });
1137
+ expect(result.output.ok).toBe(false);
1138
+ expect(result.output.summary).toContain("refused the conflicting writes of shared under the fail strategy");
1139
+ });
1140
+ });
1141
+
1142
+ describe("try catch with retries and timeouts", () => {
1143
+ it("runs the catch handler after a fragile failure and reruns the body once on demand", async () => {
1144
+ const step = controlstep("t1", "trycatch", {
1145
+ try: { steps: [childstep("f1", "Fragile step")], catch: { steps: [childstep("c1", "Handler step")] } },
1146
+ });
1147
+ const plain = await runcontrolstep({
1148
+ step,
1149
+ scopes: rootscope([]),
1150
+ outputs: {},
1151
+ execute: async (dispatched) =>
1152
+ dispatched.id === "f1" ? { ok: false, summary: "the page refused" } : { ok: true, summary: "handled" },
1153
+ now,
1154
+ });
1155
+ expect(plain.output.ok).toBe(true);
1156
+ expect(plain.output.summary).toContain("The catch handler ran 1 step after the stepfailed failure");
1157
+ const decision = plain.output.details?.control as controlflowdecision;
1158
+ expect(decision.kind).toBe("catch");
1159
+ expect(decision.catch?.errorclass).toBe("stepfailed");
1160
+ expect(decision.catch?.message).toBe("the page refused");
1161
+ expect(decision.catch?.rerun).toBe(false);
1162
+
1163
+ const rerunstep = controlstep("t1", "trycatch", {
1164
+ try: {
1165
+ steps: [childstep("f1", "Fragile step")],
1166
+ catch: { steps: [childstep("c1", "Handler step")], rerun: true },
1167
+ },
1168
+ });
1169
+ let attempts = 0;
1170
+ const rerun = await runcontrolstep({
1171
+ step: rerunstep,
1172
+ scopes: rootscope([]),
1173
+ outputs: {},
1174
+ execute: async (dispatched) => {
1175
+ if (dispatched.id === "f1") {
1176
+ attempts += 1;
1177
+ return { ok: attempts > 1, summary: attempts > 1 ? "recovered" : "flaky" };
1178
+ }
1179
+ return { ok: true, summary: "handled" };
1180
+ },
1181
+ now,
1182
+ });
1183
+ expect(rerun.output.ok).toBe(true);
1184
+ expect(rerun.output.summary).toContain("rerun of the try body succeeded");
1185
+ expect(attempts).toBe(2);
1186
+ const rerundecision = rerun.output.details?.control as controlflowdecision;
1187
+ expect(rerundecision.catch?.rerun).toBe(true);
1188
+ });
1189
+
1190
+ it("captures the reviewed error class for the handler and fails when the handler fails", async () => {
1191
+ const step = controlstep("t1", "trycatch", {
1192
+ try: { steps: [childstep("f1", "Fragile step")], catch: { steps: [childstep("c1", "Handler step")] } },
1193
+ });
1194
+ const classy = await runcontrolstep({
1195
+ step,
1196
+ scopes: rootscope([]),
1197
+ outputs: {},
1198
+ execute: async (dispatched) =>
1199
+ dispatched.id === "f1"
1200
+ ? { ok: false, summary: "the page went away", details: { errorclass: "pageunresponsive" } }
1201
+ : { ok: true, summary: "handled" },
1202
+ now,
1203
+ });
1204
+ const classydecision = classy.output.details?.control as controlflowdecision;
1205
+ expect(classydecision.catch?.errorclass).toBe("pageunresponsive");
1206
+
1207
+ const failinghandler = await runcontrolstep({
1208
+ step,
1209
+ scopes: rootscope([]),
1210
+ outputs: {},
1211
+ execute: async () => ({ ok: false, summary: "handler also failed" }),
1212
+ now,
1213
+ });
1214
+ expect(failinghandler.output.ok).toBe(false);
1215
+ expect(failinghandler.output.summary).toContain("catch handler of the try block failed");
1216
+ });
1217
+
1218
+ it("retries a failed step under the policy with fixed and exponential backoff shapes", async () => {
1219
+ const policy = {
1220
+ attempts: 3,
1221
+ backoff: { shape: "exponential" as const, base: 10, jitter: 0 },
1222
+ retryable: ["pageunresponsive"],
1223
+ };
1224
+ let calls = 0;
1225
+ const recovered = await applyretry({
1226
+ stepid: "f1",
1227
+ policy,
1228
+ now,
1229
+ run: async () => {
1230
+ calls += 1;
1231
+ return { ok: calls >= 3, details: { errorclass: "pageunresponsive" } };
1232
+ },
1233
+ errorclass: (value) => String(value.details?.errorclass ?? "stepfailed"),
1234
+ });
1235
+ expect(calls).toBe(3);
1236
+ expect(recovered.value.ok).toBe(true);
1237
+ expect(recovered.attempts.map((attempt) => attempt.delay)).toEqual([10, 20]);
1238
+ expect(recovered.attempts.map((attempt) => attempt.errorclass)).toEqual(["pageunresponsive", "pageunresponsive"]);
1239
+ expect(recovered.exhausted).toBe(false);
1240
+
1241
+ let failures = 0;
1242
+ const exhausted = await applyretry({
1243
+ stepid: "f1",
1244
+ policy,
1245
+ now,
1246
+ run: async () => {
1247
+ failures += 1;
1248
+ return { ok: false, details: { errorclass: "pageunresponsive" } };
1249
+ },
1250
+ errorclass: (value) => String(value.details?.errorclass ?? "stepfailed"),
1251
+ });
1252
+ expect(failures).toBe(3);
1253
+ expect(exhausted.exhausted).toBe(true);
1254
+ expect(exhausted.value.ok).toBe(false);
1255
+
1256
+ let once = 0;
1257
+ const nonretryable = await applyretry({
1258
+ stepid: "f1",
1259
+ policy,
1260
+ now,
1261
+ run: async () => {
1262
+ once += 1;
1263
+ return { ok: false, details: { errorclass: "permissiondenied" } };
1264
+ },
1265
+ errorclass: (value) => String(value.details?.errorclass ?? "stepfailed"),
1266
+ });
1267
+ expect(once).toBe(1);
1268
+ expect(nonretryable.attempts).toEqual([]);
1269
+ expect(nonretryable.exhausted).toBe(false);
1270
+
1271
+ expect(backoffdelay({ attempts: 3, backoff: { shape: "fixed", base: 100, jitter: 0 }, retryable: [] }, 2, 1)).toBe(
1272
+ 100,
1273
+ );
1274
+ expect(
1275
+ backoffdelay({ attempts: 3, backoff: { shape: "exponential", base: 25, jitter: 0 }, retryable: [] }, 3, 1),
1276
+ ).toBe(100);
1277
+ for (let seed = 1; seed <= 50; seed += 1) {
1278
+ const jittered = backoffdelay(
1279
+ { attempts: 3, backoff: { shape: "fixed", base: 100, jitter: 40 }, retryable: [] },
1280
+ 1,
1281
+ seed,
1282
+ );
1283
+ expect(jittered).toBeGreaterThanOrEqual(80);
1284
+ expect(jittered).toBeLessThanOrEqual(120);
1285
+ }
1286
+ });
1287
+
1288
+ it("runs the retry policy of a try block over its children with the attempts recorded", async () => {
1289
+ const step = controlstep("t1", "trycatch", {
1290
+ try: {
1291
+ steps: [childstep("f1", "Fragile step")],
1292
+ catch: { steps: [childstep("c1", "Handler step")] },
1293
+ retry: { attempts: 3, backoff: { shape: "fixed", base: 0, jitter: 0 }, retryable: ["pageunresponsive"] },
1294
+ },
1295
+ });
1296
+ let calls = 0;
1297
+ const result = await runcontrolstep({
1298
+ step,
1299
+ scopes: rootscope([]),
1300
+ outputs: {},
1301
+ execute: async (dispatched) => {
1302
+ if (dispatched.id === "f1") {
1303
+ calls += 1;
1304
+ return {
1305
+ ok: calls >= 3,
1306
+ summary: calls >= 3 ? "recovered" : "flaky",
1307
+ details: { errorclass: "pageunresponsive" },
1308
+ };
1309
+ }
1310
+ return { ok: true, summary: "handled" };
1311
+ },
1312
+ now,
1313
+ });
1314
+ expect(result.output.ok).toBe(true);
1315
+ expect(result.output.summary).toContain("after 2 retry attempts");
1316
+ const decision = result.output.details?.control as controlflowdecision;
1317
+ expect(decision.kind).toBe("retry");
1318
+ expect(decision.retries?.map((attempt) => attempt.stepid)).toEqual(["f1", "f1"]);
1319
+ });
1320
+
1321
+ it("aborts one step that exceeds its per step budget and hands it to the catch handler", async () => {
1322
+ const step = controlstep("t1", "trycatch", {
1323
+ try: {
1324
+ steps: [childstep("f1", "Slow step")],
1325
+ catch: { steps: [childstep("c1", "Handler step")] },
1326
+ timeout: { stepms: 10 },
1327
+ },
1328
+ });
1329
+ const result = await runcontrolstep({
1330
+ step,
1331
+ scopes: rootscope([]),
1332
+ outputs: {},
1333
+ execute: async (dispatched) => {
1334
+ if (dispatched.id === "f1") await new Promise((resolve) => setTimeout(resolve, 40));
1335
+ return { ok: true, summary: "slow done" };
1336
+ },
1337
+ now,
1338
+ });
1339
+ expect(result.output.ok).toBe(true);
1340
+ expect(result.output.summary).toContain("catch handler ran");
1341
+ const decision = result.output.details?.control as controlflowdecision;
1342
+ expect(decision.timeouts).toHaveLength(1);
1343
+ expect(decision.timeouts?.[0]?.budget).toBe(10);
1344
+ expect(decision.timeouts?.[0]?.scope).toBe("step");
1345
+ });
1346
+
1347
+ it("aborts a whole try block that exceeds its per run budget", async () => {
1348
+ const step = controlstep("t1", "trycatch", {
1349
+ try: {
1350
+ steps: [childstep("f1", "Slow one"), childstep("f2", "Slow two"), childstep("f3", "Slow three")],
1351
+ catch: { steps: [childstep("c1", "Handler step")] },
1352
+ timeout: { runms: 15 },
1353
+ },
1354
+ });
1355
+ const result = await runcontrolstep({
1356
+ step,
1357
+ scopes: rootscope([]),
1358
+ outputs: {},
1359
+ execute: async () => {
1360
+ await new Promise((resolve) => setTimeout(resolve, 20));
1361
+ return { ok: true, summary: "slow done" };
1362
+ },
1363
+ now,
1364
+ });
1365
+ expect(result.output.ok).toBe(true);
1366
+ const decision = result.output.details?.control as controlflowdecision;
1367
+ expect(decision.timeouts?.[0]?.scope).toBe("run");
1368
+ expect(result.output.summary).toContain("catch handler ran");
1369
+ });
1370
+
1371
+ it("races the run timeout with the cancelled error class and keeps fast runs intact", async () => {
1372
+ const fast = await applyruntimeout({ budgetms: 500, run: async () => "value" });
1373
+ expect(fast.cancelled).toBe(false);
1374
+ if (!fast.cancelled) expect(fast.value).toBe("value");
1375
+ const slow = await applyruntimeout({
1376
+ budgetms: 5,
1377
+ run: async () => {
1378
+ await new Promise((resolve) => setTimeout(resolve, 30));
1379
+ return "late";
1380
+ },
1381
+ });
1382
+ expect(slow.cancelled).toBe(true);
1383
+ if (slow.cancelled) {
1384
+ expect(slow.error).toBeInstanceOf(cancellederror);
1385
+ expect(slow.error.name).toBe("cancellederror");
1386
+ expect(slow.error.message).toContain("exceeded its reviewed budget of 5 milliseconds");
1387
+ }
1388
+ const guarded = await applytimeout({
1389
+ stepid: "f1",
1390
+ budgetms: 500,
1391
+ run: async () => ({ ok: true, summary: "fast" }),
1392
+ });
1393
+ expect(guarded.aborted).toBe(false);
1394
+ const aborted = await applytimeout({
1395
+ stepid: "f1",
1396
+ budgetms: 5,
1397
+ run: async () => {
1398
+ await new Promise((resolve) => setTimeout(resolve, 30));
1399
+ return { ok: true, summary: "late" };
1400
+ },
1401
+ });
1402
+ expect(aborted.aborted).toBe(true);
1403
+ expect(aborted.output?.details?.errorclass).toBe("timeout");
1404
+ expect(aborted.output?.summary).toContain("exceeded its reviewed budget of 5 milliseconds");
1405
+ expect(aborted.abort?.budget).toBe(5);
1406
+ });
1407
+ });
1408
+
1409
+ describe("control flow policy", () => {
1410
+ const step = (kind: toolstep["kind"], options: Record<string, unknown>): toolstep => ({
1411
+ id: "w1",
1412
+ kind,
1413
+ summary: "Reviewed control step",
1414
+ risk: actionrisk(kind),
1415
+ options: JSON.stringify(options),
1416
+ });
1417
+ const listbody = {
1418
+ list: "items",
1419
+ item: "item",
1420
+ index: "index",
1421
+ bound: 5,
1422
+ steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }],
1423
+ };
1424
+ const branchbody = {
1425
+ paths: [
1426
+ {
1427
+ name: "fast",
1428
+ when: {
1429
+ left: { ref: "count" },
1430
+ right: { literal: 1 },
1431
+ operator: "equal",
1432
+ result: "isfast",
1433
+ resultkind: "boolean",
1434
+ },
1435
+ steps: [{ id: "b1", kind: "readtext", label: "Fast", target: "h1" }],
1436
+ },
1437
+ ],
1438
+ else: { name: "slow", steps: [] },
1439
+ };
1440
+
1441
+ it("validates the control grammar of every kind before any review", () => {
1442
+ expect(
1443
+ validatestep(
1444
+ step("condition", {
1445
+ condition: { expression: { left: { ref: "ready" }, operator: "not", result: "stop", resultkind: "boolean" } },
1446
+ }),
1447
+ "https://example.com",
1448
+ ),
1449
+ ).toEqual({ allowed: true });
1450
+ expect(
1451
+ validatestep(
1452
+ step("condition", {
1453
+ condition: {
1454
+ expression: {
1455
+ left: { literal: 1 },
1456
+ right: { literal: 1 },
1457
+ operator: "add",
1458
+ result: "n",
1459
+ resultkind: "number",
1460
+ },
1461
+ },
1462
+ }),
1463
+ "https://example.com",
1464
+ ),
1465
+ ).toMatchObject({ allowed: false });
1466
+ expect(validatestep(step("branch", { branch: branchbody }), "https://example.com")).toEqual({ allowed: true });
1467
+ expect(
1468
+ validatestep(
1469
+ step("branch", {
1470
+ branch: { paths: [{ name: "only", steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }] }] },
1471
+ }),
1472
+ "https://example.com",
1473
+ ),
1474
+ ).toMatchObject({ allowed: false, reason: expect.stringContaining("else path") });
1475
+ expect(validatestep(step("loop", { loop: listbody }), "https://example.com")).toEqual({ allowed: true });
1476
+ expect(validatestep(step("loop", { loop: { ...listbody, item: "items" } }), "https://example.com")).toMatchObject({
1477
+ allowed: false,
1478
+ });
1479
+ expect(
1480
+ validatestep(
1481
+ step("repeatuntil", {
1482
+ repeatuntil: {
1483
+ until: {
1484
+ left: { ref: "count" },
1485
+ right: { literal: 1 },
1486
+ operator: "greaterequal",
1487
+ result: "done",
1488
+ resultkind: "boolean",
1489
+ },
1490
+ steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }],
1491
+ },
1492
+ }),
1493
+ "https://example.com",
1494
+ ),
1495
+ ).toEqual({ allowed: true });
1496
+ expect(
1497
+ validatestep(
1498
+ step("whileloop", {
1499
+ while: {
1500
+ while: { left: { literal: true }, operator: "not", result: "go", resultkind: "boolean" },
1501
+ bound: 4,
1502
+ steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }],
1503
+ },
1504
+ }),
1505
+ "https://example.com",
1506
+ ),
1507
+ ).toEqual({ allowed: true });
1508
+ expect(
1509
+ validatestep(
1510
+ step("whileloop", {
1511
+ while: {
1512
+ while: { left: { literal: true }, operator: "not", result: "go", resultkind: "boolean" },
1513
+ steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }],
1514
+ },
1515
+ }),
1516
+ "https://example.com",
1517
+ ),
1518
+ ).toMatchObject({ allowed: false, reason: expect.stringContaining("safety bound") });
1519
+ expect(
1520
+ validatestep(
1521
+ step("foreach", {
1522
+ foreach: {
1523
+ selector: "li",
1524
+ item: "row",
1525
+ index: "rowindex",
1526
+ steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }],
1527
+ },
1528
+ }),
1529
+ "https://example.com",
1530
+ ),
1531
+ ).toEqual({ allowed: true });
1532
+ expect(
1533
+ validatestep(
1534
+ step("parallel", {
1535
+ parallel: {
1536
+ branches: [{ id: "one", steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }] }],
1537
+ join: { strategy: "first", onfail: "continue" },
1538
+ },
1539
+ }),
1540
+ "https://example.com",
1541
+ ),
1542
+ ).toEqual({ allowed: true });
1543
+ expect(
1544
+ validatestep(
1545
+ step("parallel", {
1546
+ parallel: {
1547
+ branches: [{ id: "one", steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }] }],
1548
+ join: { strategy: "bogus", onfail: "continue" },
1549
+ },
1550
+ }),
1551
+ "https://example.com",
1552
+ ),
1553
+ ).toMatchObject({ allowed: false });
1554
+ expect(
1555
+ validatestep(
1556
+ step("trycatch", {
1557
+ try: {
1558
+ steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }],
1559
+ catch: { steps: [{ id: "c1", kind: "wait", label: "Handle", value: "1" }] },
1560
+ retry: { attempts: 4, backoff: { shape: "exponential", base: 50, jitter: 10 }, retryable: ["timeout"] },
1561
+ timeout: { stepms: 3000 },
1562
+ },
1563
+ }),
1564
+ "https://example.com",
1565
+ ),
1566
+ ).toEqual({ allowed: true });
1567
+ expect(
1568
+ validatestep(
1569
+ step("trycatch", {
1570
+ try: {
1571
+ steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }],
1572
+ catch: { steps: [{ id: "c1", kind: "wait", label: "Handle", value: "1" }] },
1573
+ timeout: { stepms: -1 },
1574
+ },
1575
+ }),
1576
+ "https://example.com",
1577
+ ),
1578
+ ).toMatchObject({ allowed: false });
1579
+ expect(validatestep(step("loop", {}), "https://example.com")).toMatchObject({ allowed: false });
1580
+ });
1581
+
1582
+ it("refuses control payloads that hide an unreviewed child kind behind their bodies", () => {
1583
+ expect(
1584
+ validatestep(
1585
+ step("loop", {
1586
+ loop: {
1587
+ list: "items",
1588
+ item: "item",
1589
+ index: "index",
1590
+ steps: [{ id: "b1", kind: "explode", label: "Ghost kind" }],
1591
+ },
1592
+ }),
1593
+ "https://example.com",
1594
+ ),
1595
+ ).toMatchObject({ allowed: false, reason: expect.stringContaining("not a reviewed action kind") });
1596
+ expect(
1597
+ validatestep(
1598
+ step("branch", {
1599
+ branch: {
1600
+ paths: [{ name: "only", steps: [{ id: "b1", kind: "explode", label: "Ghost kind" }] }],
1601
+ else: { name: "else", steps: [] },
1602
+ },
1603
+ }),
1604
+ "https://example.com",
1605
+ ),
1606
+ ).toMatchObject({ allowed: false, reason: expect.stringContaining("not a reviewed action kind") });
1607
+ expect(
1608
+ validatestep(
1609
+ step("trycatch", {
1610
+ try: {
1611
+ steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }],
1612
+ catch: { steps: [{ id: "c1", kind: "explode", label: "Ghost kind" }] },
1613
+ },
1614
+ }),
1615
+ "https://example.com",
1616
+ ),
1617
+ ).toMatchObject({ allowed: false, reason: expect.stringContaining("not a reviewed action kind") });
1618
+ });
1619
+
1620
+ it("grades a composed workflow with control steps by its worst child kind", () => {
1621
+ const readonly = composeworkflow({
1622
+ name: "reader",
1623
+ version: 1,
1624
+ origins: ["https://example.com"],
1625
+ steps: [
1626
+ controlstep("l1", "loop", {
1627
+ loop: { ...listbody, steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }] },
1628
+ }),
1629
+ ] as never,
1630
+ now,
1631
+ kindallowed,
1632
+ riskof,
1633
+ });
1634
+ expect(readonly.risk).toBe("interaction");
1635
+ const mutating = composeworkflow({
1636
+ name: "writer",
1637
+ version: 1,
1638
+ origins: ["https://example.com"],
1639
+ steps: [
1640
+ controlstep("b1", "branch", {
1641
+ branch: {
1642
+ paths: [{ name: "only", steps: [{ id: "c1", kind: "click", label: "Click", target: "#submit" }] }],
1643
+ else: { name: "else", steps: [] },
1644
+ },
1645
+ }),
1646
+ ] as never,
1647
+ now,
1648
+ kindallowed,
1649
+ riskof,
1650
+ });
1651
+ expect(mutating.risk).toBe("sensitive");
1652
+ expect(() =>
1653
+ composeworkflow({
1654
+ name: "ghost",
1655
+ version: 1,
1656
+ origins: ["https://example.com"],
1657
+ steps: [controlstep("l1", "loop", { loop: { list: "items", item: "item", index: "index" } })] as never,
1658
+ now,
1659
+ kindallowed,
1660
+ riskof,
1661
+ }),
1662
+ ).toThrow("loop step needs");
1663
+ expect(() =>
1664
+ composeworkflow({
1665
+ name: "ghost",
1666
+ version: 1,
1667
+ origins: ["https://example.com"],
1668
+ steps: [
1669
+ controlstep("l1", "loop", { loop: { ...listbody, steps: [{ id: "b1", kind: "explode", label: "Ghost" }] } }),
1670
+ ] as never,
1671
+ now,
1672
+ kindallowed,
1673
+ riskof,
1674
+ }),
1675
+ ).toThrow("not a reviewed action kind");
1676
+ });
1677
+
1678
+ it("projects control steps for dry runs only when every child step grades read", () => {
1679
+ expect(
1680
+ dryrunprojection(
1681
+ controlstep("c1", "condition", {
1682
+ condition: { expression: { left: { ref: "ready" }, operator: "not", result: "stop", resultkind: "boolean" } },
1683
+ }),
1684
+ ),
1685
+ ).toContain("no page side effect");
1686
+ expect(
1687
+ dryrunprojection(
1688
+ controlstep("l1", "loop", {
1689
+ loop: { ...listbody, steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }] },
1690
+ }),
1691
+ ),
1692
+ ).toContain("safety bound");
1693
+ expect(
1694
+ dryrunprojection(
1695
+ controlstep("p1", "parallel", {
1696
+ parallel: {
1697
+ branches: [{ id: "one", steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }] }],
1698
+ join: { strategy: "first", onfail: "continue" },
1699
+ },
1700
+ }),
1701
+ ),
1702
+ ).toContain("join their outcomes");
1703
+ expect(
1704
+ dryrunprojection(
1705
+ controlstep("t1", "trycatch", {
1706
+ try: {
1707
+ steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }],
1708
+ catch: { steps: [{ id: "c1", kind: "wait", label: "Handle", value: "1" }] },
1709
+ },
1710
+ }),
1711
+ ),
1712
+ ).toContain("catch handler");
1713
+ expect(
1714
+ dryrunprojection(
1715
+ controlstep("l1", "loop", {
1716
+ loop: { ...listbody, steps: [{ id: "b1", kind: "click", label: "Click", target: "#submit" }] },
1717
+ }),
1718
+ ),
1719
+ ).toBeUndefined();
1720
+ expect(
1721
+ dryrunprojection(
1722
+ controlstep("t1", "trycatch", {
1723
+ try: {
1724
+ steps: [{ id: "b1", kind: "click", label: "Click", target: "#submit" }],
1725
+ catch: { steps: [{ id: "c1", kind: "wait", label: "Handle", value: "1" }] },
1726
+ },
1727
+ }),
1728
+ ),
1729
+ ).toBeUndefined();
1730
+ });
1731
+ });
1732
+
1733
+ describe("control flow inside the run loop", () => {
1734
+ it("runs a control step as a workflow step adopting its child runlog and merged scopes", async () => {
1735
+ const record = composeworkflow({
1736
+ name: "controlled",
1737
+ version: 1,
1738
+ origins: ["https://example.com"],
1739
+ steps: [
1740
+ controlstep("l1", "loop", {
1741
+ loop: {
1742
+ list: "items",
1743
+ item: "item",
1744
+ index: "index",
1745
+ bound: 4,
1746
+ steps: [
1747
+ workflowstepof({
1748
+ id: "b1",
1749
+ kind: "readtext",
1750
+ label: "Read the row",
1751
+ target: 'li[data-id="${item}"]',
1752
+ }) as workflowstep,
1753
+ ],
1754
+ },
1755
+ }),
1756
+ { id: "s2", kind: "wait", label: "Final wait", value: "10" },
1757
+ ] as never,
1758
+ now,
1759
+ kindallowed,
1760
+ riskof,
1761
+ });
1762
+ const seen: string[] = [];
1763
+ const baseexecute = async (dispatched: workflowstep): Promise<{ ok: boolean; summary: string }> => {
1764
+ seen.push(`${dispatched.id}:${dispatched.target ?? ""}`);
1765
+ return { ok: true, summary: "ok" };
1766
+ };
1767
+ const result = await runworkflow({
1768
+ record,
1769
+ run: newworkflowrun({ id: "run1", workflowid: record.id, now }),
1770
+ scopes: rootscope([{ name: "items", kind: "list", value: ["x", "y"] }]),
1771
+ execute: controlexecutor(baseexecute) as never,
1772
+ now,
1773
+ gates: { sessionactive: true, planapproved: true, origingranted: () => true },
1774
+ });
1775
+ expect(result.run.state).toBe("done");
1776
+ expect(result.run.cursor).toBe(2);
1777
+ expect(seen).toEqual(['b1:li[data-id="x"]', 'b1:li[data-id="y"]', "s2:"]);
1778
+ expect(result.log.map((entry) => entry.stepid)).toEqual(["b1", "l1", "b1", "l1", "l1", "s2"]);
1779
+ expect(result.log.every((entry) => entry.state === "done")).toBe(true);
1780
+ });
1781
+
1782
+ it("fails the run at a failing control step without advancing the checkpoint", async () => {
1783
+ const record = composeworkflow({
1784
+ name: "failing",
1785
+ version: 1,
1786
+ origins: ["https://example.com"],
1787
+ steps: [
1788
+ controlstep("l1", "loop", {
1789
+ loop: {
1790
+ list: "items",
1791
+ item: "item",
1792
+ index: "index",
1793
+ steps: [{ id: "b1", kind: "wait", label: "Body", value: "10" }],
1794
+ },
1795
+ }),
1796
+ { id: "s2", kind: "wait", label: "Never reached", value: "10" },
1797
+ ] as never,
1798
+ now,
1799
+ kindallowed,
1800
+ riskof,
1801
+ });
1802
+ const result = await runworkflow({
1803
+ record,
1804
+ run: newworkflowrun({ id: "run1", workflowid: record.id, now }),
1805
+ scopes: rootscope([{ name: "items", kind: "list", value: ["x"] }]),
1806
+ execute: controlexecutor(async () => ({ ok: false, summary: "the row refused" })) as never,
1807
+ now,
1808
+ gates: { sessionactive: true, planapproved: true, origingranted: () => true },
1809
+ });
1810
+ expect(result.run.state).toBe("failed");
1811
+ expect(result.run.cursor).toBe(0);
1812
+ expect(result.run.failreason).toContain("failed at iteration 1");
1813
+ });
1814
+
1815
+ it("keeps control steps inside the session, plan and origin gates", async () => {
1816
+ const record = composeworkflow({
1817
+ name: "gated",
1818
+ version: 1,
1819
+ origins: ["https://example.com"],
1820
+ steps: [
1821
+ controlstep("c1", "condition", {
1822
+ condition: {
1823
+ expression: { left: { literal: true }, operator: "not", result: "stop", resultkind: "boolean" },
1824
+ },
1825
+ }),
1826
+ ] as never,
1827
+ now,
1828
+ kindallowed,
1829
+ riskof,
1830
+ });
1831
+ const run = newworkflowrun({ workflowid: record.id, now });
1832
+ await expect(
1833
+ runworkflow({
1834
+ record,
1835
+ run,
1836
+ execute: controlexecutor(async () => ({ ok: true, summary: "x" })) as never,
1837
+ now,
1838
+ gates: { sessionactive: false, planapproved: true, origingranted: () => true },
1839
+ }),
1840
+ ).rejects.toThrow("approved session");
1841
+ await expect(
1842
+ runworkflow({
1843
+ record,
1844
+ run,
1845
+ execute: controlexecutor(async () => ({ ok: true, summary: "x" })) as never,
1846
+ now,
1847
+ gates: { sessionactive: true, planapproved: false, origingranted: () => true },
1848
+ }),
1849
+ ).rejects.toThrow("approved plan");
1850
+ await expect(
1851
+ runworkflow({
1852
+ record,
1853
+ run,
1854
+ execute: controlexecutor(async () => ({ ok: true, summary: "x" })) as never,
1855
+ now,
1856
+ gates: { sessionactive: true, planapproved: true, origingranted: () => false },
1857
+ }),
1858
+ ).rejects.toThrow("outside the session grants");
1859
+ });
1860
+
1861
+ it("runs one control step in isolation outside the run loop", async () => {
1862
+ const step = controlstep("c1", "condition", {
1863
+ condition: {
1864
+ expression: {
1865
+ left: { ref: "count" },
1866
+ right: { literal: 3 },
1867
+ operator: "greaterequal",
1868
+ result: "done",
1869
+ resultkind: "boolean",
1870
+ },
1871
+ },
1872
+ });
1873
+ const executed = await runstep({
1874
+ step,
1875
+ scopes: rootscope([{ name: "count", kind: "number", value: 5 }]),
1876
+ outputs: {},
1877
+ execute: controlexecutor(async () => ({ ok: true, summary: "never" })) as never,
1878
+ now,
1879
+ });
1880
+ expect(executed.output.ok).toBe(true);
1881
+ expect(executed.output.summary).toContain("holds over the extracted values");
1882
+ expect(resolvevariable(executed.scopes, "done")?.value).toBe(true);
1883
+ expect(executed.log.checkpoint).toBe(true);
1884
+ });
1885
+ });
1886
+
1887
+ describe("control flow protocol", () => {
1888
+ it("carries the control grammar summaries through a workflow proposal", () => {
1889
+ const proposal = parseworkflowproposal(
1890
+ {
1891
+ version: protocolversion,
1892
+ workflow: {
1893
+ name: "controlled",
1894
+ version: 1,
1895
+ origins: ["https://example.com"],
1896
+ steps: [
1897
+ controlstep("c1", "condition", {
1898
+ condition: {
1899
+ expression: { left: { literal: true }, operator: "not", result: "stop", resultkind: "boolean" },
1900
+ },
1901
+ }),
1902
+ controlstep("l1", "loop", {
1903
+ loop: {
1904
+ list: "items",
1905
+ item: "item",
1906
+ index: "index",
1907
+ bound: 12,
1908
+ steps: [{ id: "b1", kind: "readtext", label: "Read", target: "h1" }],
1909
+ },
1910
+ }),
1911
+ controlstep("t1", "trycatch", {
1912
+ try: {
1913
+ steps: [{ id: "f1", kind: "readtext", label: "Read", target: "p" }],
1914
+ catch: { steps: [{ id: "c1", kind: "wait", label: "Handle", value: "1" }] },
1915
+ },
1916
+ }),
1917
+ { id: "s2", kind: "wait", label: "Plain wait", value: "5" },
1918
+ ],
1919
+ blocks: [],
1920
+ },
1921
+ },
1922
+ "https://example.com",
1923
+ ["https://example.com"],
1924
+ );
1925
+ expect(proposal.control).toHaveLength(3);
1926
+ expect(proposal.control?.[0]).toMatchObject({ stepid: "c1", summary: { kind: "condition" } });
1927
+ expect(proposal.control?.[1]?.summary).toMatchObject({ kind: "loop", bound: 12 });
1928
+ expect(proposal.control?.[2]?.summary).toMatchObject({ kind: "trycatch" });
1929
+ const plain = parseworkflowproposal(
1930
+ {
1931
+ version: protocolversion,
1932
+ workflow: {
1933
+ name: "plain",
1934
+ version: 1,
1935
+ origins: ["https://example.com"],
1936
+ steps: [{ id: "s1", kind: "wait", label: "Wait", value: "5" }],
1937
+ },
1938
+ },
1939
+ "https://example.com",
1940
+ );
1941
+ expect(plain.control).toBeUndefined();
1942
+ });
1943
+
1944
+ it("carries branch outcomes, loop counters, retries and timeout aborts through the outcome envelope", () => {
1945
+ const run = { ...newworkflowrun({ id: "run1", workflowid: "wf1", now }), state: "done" as const };
1946
+ const decision: controlflowdecision = {
1947
+ runid: "run1",
1948
+ stepid: "l1",
1949
+ kind: "loop",
1950
+ at: now,
1951
+ loops: [{ stepid: "l1", path: "l1[0]", iteration: 0, ok: true, at: now }],
1952
+ };
1953
+ const entries: runlogentry[] = [
1954
+ {
1955
+ stepid: "l1",
1956
+ label: "The loop step",
1957
+ state: "done",
1958
+ startedat: now,
1959
+ duration: 9,
1960
+ summary: "The loop ran 1 iteration.",
1961
+ checkpoint: true,
1962
+ details: { control: decision },
1963
+ },
1964
+ { stepid: "s2", label: "Plain", state: "done", startedat: now + 5, duration: 1, summary: "ok" },
1965
+ ];
1966
+ const outcome = workflowoutcome({ run, entries });
1967
+ expect(outcome.steps[0]?.control).toEqual(decision);
1968
+ expect(outcome.steps[1]?.control).toBeUndefined();
1969
+ const single = workflowoutcome({ run, entries, stepid: "l1" });
1970
+ expect(single.steps).toHaveLength(1);
1971
+ expect(single.steps[0]?.control?.kind).toBe("loop");
1972
+ const report = workflowreport({ workflows: [], runs: [run], templates: [], control: [decision] });
1973
+ expect(report.control).toEqual([decision]);
1974
+ expect(workflowreport({ workflows: [], runs: [], templates: [] }).control).toEqual([]);
1975
+ });
1976
+
1977
+ it("reports timeout aborts and retry exhaustion distinctly in the response envelope", () => {
1978
+ const planapproved: agentplan = { ...plan, state: "approved" };
1979
+ const timeout: timeoutabort = { stepid: "f1", budget: 5000, scope: "step", at: now };
1980
+ const response = JSON.parse(
1981
+ outcomeresponse({
1982
+ outcome: { stepid: "w1", ok: false, summary: "The run failed after retries.", at: now },
1983
+ plan: planapproved,
1984
+ workflow: {
1985
+ runid: "run1",
1986
+ state: "failed",
1987
+ produced: ["count"],
1988
+ consumed: ["items"],
1989
+ timeout,
1990
+ retry: { stepid: "f1", attempts: 3, exhausted: true },
1991
+ },
1992
+ }),
1993
+ ) as { workflow?: { timeout?: timeoutabort; retry?: { attempts: number; exhausted: boolean } } };
1994
+ expect(response.workflow?.timeout).toEqual(timeout);
1995
+ expect(response.workflow?.retry).toEqual({ stepid: "f1", attempts: 3, exhausted: true });
1996
+ const clean = JSON.parse(
1997
+ outcomeresponse({
1998
+ outcome: { stepid: "w1", ok: true, summary: "done", at: now },
1999
+ plan: planapproved,
2000
+ workflow: { runid: "run2", state: "done", produced: [], consumed: [] },
2001
+ }),
2002
+ ) as { workflow?: { timeout?: unknown; retry?: unknown } };
2003
+ expect(clean.workflow?.timeout).toBeUndefined();
2004
+ expect(clean.workflow?.retry).toBeUndefined();
2005
+ });
2006
+ });
2007
+
2008
+ describe("control flow memory and progress", () => {
2009
+ it("stores branch, loop, retry, timeout and join decisions and returns the branch history of a workflow", async () => {
2010
+ const store = new sessionmemory(new fakeadapter());
2011
+ const decisions: controlflowdecision[] = [
2012
+ {
2013
+ runid: "run1",
2014
+ stepid: "b1",
2015
+ kind: "branch",
2016
+ at: now,
2017
+ branch: { stepid: "b1", path: "fast", reason: "The condition of the path fast holds.", at: now },
2018
+ },
2019
+ {
2020
+ runid: "run1",
2021
+ stepid: "l1",
2022
+ kind: "loop",
2023
+ at: now + 1,
2024
+ loops: [{ stepid: "l1", path: "l1[0]", iteration: 0, ok: true, at: now + 1 }],
2025
+ },
2026
+ {
2027
+ runid: "run1",
2028
+ stepid: "t1",
2029
+ kind: "retry",
2030
+ at: now + 2,
2031
+ retries: [{ stepid: "f1", attempt: 2, delay: 20, errorclass: "pageunresponsive", at: now + 2 }],
2032
+ },
2033
+ {
2034
+ runid: "run1",
2035
+ stepid: "t1",
2036
+ kind: "timeout",
2037
+ at: now + 3,
2038
+ timeouts: [{ stepid: "f1", budget: 5000, scope: "step", at: now + 3 }],
2039
+ },
2040
+ {
2041
+ runid: "run1",
2042
+ stepid: "p1",
2043
+ kind: "join",
2044
+ at: now + 4,
2045
+ join: { stepid: "p1", strategy: "last", conflicts: ["shared"], merged: ["shared"], at: now + 4 },
2046
+ },
2047
+ ];
2048
+ for (const decision of decisions) await store.addcontroldecision("run1", decision);
2049
+ expect((await store.listcontroldecisions("run1")).map((decision) => decision.kind)).toEqual([
2050
+ "branch",
2051
+ "loop",
2052
+ "retry",
2053
+ "timeout",
2054
+ "join",
2055
+ ]);
2056
+ expect(await store.listcontroldecisions("missing")).toEqual([]);
2057
+ const retryattempt: retryattempt = { stepid: "f1", attempt: 2, delay: 20, errorclass: "pageunresponsive", at: now };
2058
+ expect(retryattempt.delay).toBe(20);
2059
+ await store.setworkflowrun({
2060
+ id: "run1",
2061
+ workflowid: "wf1",
2062
+ state: "done",
2063
+ cursor: 1,
2064
+ startedat: now,
2065
+ endedat: now + 5,
2066
+ });
2067
+ await store.setworkflowrun({
2068
+ id: "run2",
2069
+ workflowid: "wf1",
2070
+ state: "done",
2071
+ cursor: 1,
2072
+ startedat: now + 10,
2073
+ endedat: now + 15,
2074
+ });
2075
+ await store.setworkflowrun({
2076
+ id: "run3",
2077
+ workflowid: "wf2",
2078
+ state: "done",
2079
+ cursor: 1,
2080
+ startedat: now + 20,
2081
+ endedat: now + 25,
2082
+ });
2083
+ await store.addcontroldecision("run2", {
2084
+ runid: "run2",
2085
+ stepid: "b1",
2086
+ kind: "branch",
2087
+ at: now + 11,
2088
+ branch: { stepid: "b1", path: "slow", reason: "No path condition held and the else path ran.", at: now + 11 },
2089
+ });
2090
+ const history = await store.getbranchhistory("wf1");
2091
+ expect(history.map((outcome) => outcome.path)).toEqual(["fast", "slow"]);
2092
+ expect(await store.getbranchhistory("wf2")).toEqual([]);
2093
+ });
2094
+
2095
+ it("counts loop iterations toward the user defined denominator in progress", () => {
2096
+ let progress = recordworkflow(
2097
+ undefined,
2098
+ "run",
2099
+ "w1",
2100
+ {
2101
+ family: "control",
2102
+ detail: "The control flow steps ran their loops",
2103
+ runid: "run1",
2104
+ iterations: 7,
2105
+ denominator: 10,
2106
+ },
2107
+ now,
2108
+ );
2109
+ const evidence = workflowevidences(progress, "run", "w1");
2110
+ expect(evidence[0]?.family).toBe("control");
2111
+ expect(evidence[0]?.iterations).toBe(7);
2112
+ expect(evidence[0]?.denominator).toBe(10);
2113
+ expect((progress.outcomes ?? [])[0]?.summary).toContain("7 iterations");
2114
+ expect((progress.outcomes ?? [])[0]?.summary).toContain("denominator 10");
2115
+ expect(loopshare(7, 10)).toBe(0.7);
2116
+ expect(loopshare(12, 10)).toBe(1);
2117
+ expect(loopshare(3, 0)).toBe(0);
2118
+ expect(workflowevidences(progress, "other", "w1")).toEqual([]);
2119
+ });
2120
+ });