@wenathlan/devthink 2.0.14 → 2.0.19

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 +60 -0
  2. package/{dist/bridge.d.ts → bridge.d.ts} +1 -1
  3. package/bridge.d.ts.map +1 -0
  4. package/bridge.js +1877 -0
  5. package/bun.d.ts.map +1 -0
  6. package/bun.js +52329 -0
  7. package/caps/background.json +712 -0
  8. package/caps/cli.json +360 -0
  9. package/caps/library.json +3611 -0
  10. package/caps/mcp.json +126 -0
  11. package/caps/pagebridge.json +377 -0
  12. package/caps/popup.json +51 -0
  13. package/caps/sidepanel.json +522 -0
  14. package/checksums.txt +142 -0
  15. package/cli.d.ts.map +1 -0
  16. package/{dist/cli.js → cli.js} +2 -2
  17. package/companion.d.ts.map +1 -0
  18. package/companion.js +389 -0
  19. package/crossbrowser.d.ts.map +1 -0
  20. package/crossbrowser.js +1191 -0
  21. package/dashdone.d.ts.map +1 -0
  22. package/dashdone.js +368 -0
  23. package/deno.d.ts.map +1 -0
  24. package/deno.js +52325 -0
  25. package/devthink.umd.js +52346 -0
  26. package/fixtures/bun.ts +7 -0
  27. package/fixtures/cjs.js +6 -0
  28. package/fixtures/deno.ts +6 -0
  29. package/fixtures/example-org-pagestate.json +22 -0
  30. package/fixtures/importers/automa-workflow.json +18 -0
  31. package/fixtures/importers/selenium-side.json +20 -0
  32. package/fixtures/importers/tabular-plan.csv +7 -0
  33. package/fixtures/importers/uivision-macro.json +10 -0
  34. package/fixtures/importers/v1-plan.json +13 -0
  35. package/fixtures/mcp-client.mjs +14 -0
  36. package/fixtures/pages/checkout.html +192 -0
  37. package/fixtures/pages/dashboard.html +110 -0
  38. package/fixtures/pages/feed.html +113 -0
  39. package/fixtures/pages/product-grid.html +150 -0
  40. package/fixtures/plans/form-inventory-plan.json +11 -0
  41. package/fixtures/plans/release-notes-plan.json +11 -0
  42. package/fixtures/recipes/agentscompete.json +11 -0
  43. package/fixtures/recipes/agentsforms.json +11 -0
  44. package/fixtures/recipes/agentsmonitor.json +11 -0
  45. package/fixtures/recipes/agentsreview.json +29 -0
  46. package/fixtures/recipes/agentswarm.json +11 -0
  47. package/fixtures/recipes/fillcalendar.json +12 -0
  48. package/fixtures/recipes/fillcheckout.json +13 -0
  49. package/fixtures/recipes/filldependentdropdowns.json +12 -0
  50. package/fixtures/recipes/fillfromcsv.json +13 -0
  51. package/fixtures/recipes/fillloginform.json +12 -0
  52. package/fixtures/recipes/fillmultistepwizard.json +13 -0
  53. package/fixtures/recipes/fillregistration.json +12 -0
  54. package/fixtures/recipes/fillsearchfilters.json +12 -0
  55. package/fixtures/recipes/filltypeahead.json +11 -0
  56. package/fixtures/recipes/monitoralerts.json +12 -0
  57. package/fixtures/recipes/monitoravailability.json +11 -0
  58. package/fixtures/recipes/monitornetworkquiet.json +12 -0
  59. package/fixtures/recipes/monitorpagechanges.json +11 -0
  60. package/fixtures/recipes/monitorpricechange.json +11 -0
  61. package/fixtures/recipes/monitorschedule.json +12 -0
  62. package/fixtures/recipes/scrapedynamicprices.json +13 -0
  63. package/fixtures/recipes/scrapeimagegallery.json +12 -0
  64. package/fixtures/recipes/scrapeinfinitefeed.json +13 -0
  65. package/fixtures/recipes/scrapenestedlists.json +12 -0
  66. package/fixtures/recipes/scrapeproductgrid.json +12 -0
  67. package/fixtures/recipes/scrapereviews.json +12 -0
  68. package/fixtures/recipes/scrapesearchresults.json +12 -0
  69. package/fixtures/recipes/scrapetablepagination.json +12 -0
  70. package/fixtures/recipes/testaccessibility.json +34 -0
  71. package/fixtures/recipes/testconsoleerrors.json +12 -0
  72. package/fixtures/recipes/testdeeplinks.json +12 -0
  73. package/fixtures/recipes/testformvalidation.json +13 -0
  74. package/fixtures/recipes/testlayoutshift.json +12 -0
  75. package/fixtures/recipes/testlinkcheck.json +12 -0
  76. package/fixtures/recipes/testloadtiming.json +12 -0
  77. package/fixtures/recipes/testvisualdiff.json +12 -0
  78. package/fixtures/workflows/changelog-digest-workflow.json +13 -0
  79. package/fixtures/workflows/form-survey-workflow.json +13 -0
  80. package/gallery.json +706 -0
  81. package/hardening.d.ts.map +1 -0
  82. package/hardening.js +188 -0
  83. package/headless.d.ts.map +1 -0
  84. package/headless.js +11522 -0
  85. package/http.d.ts.map +1 -0
  86. package/http.js +2165 -0
  87. package/index.cjs +54682 -0
  88. package/index.d.ts.map +1 -0
  89. package/index.js +52310 -0
  90. package/index.neutral.js +46343 -0
  91. package/{web/manifest.json → manifest.json} +1 -1
  92. package/mcp.d.ts.map +1 -0
  93. package/mcp.js +20515 -0
  94. package/memory.d.ts.map +1 -0
  95. package/{memory.ts → memory.js} +2310 -3834
  96. package/nativehost.template.json +10 -0
  97. package/node.cjs +54686 -0
  98. package/node.d.ts.map +1 -0
  99. package/pack.d.ts.map +1 -0
  100. package/pack.js +805 -0
  101. package/package.json +83 -176
  102. package/policy.d.ts.map +1 -0
  103. package/{policy.ts → policy.js} +4679 -5073
  104. package/progress.d.ts.map +1 -0
  105. package/progress.js +645 -0
  106. package/protocol.d.ts.map +1 -0
  107. package/protocol.js +8334 -0
  108. package/schemas/audit.schema.json +226 -0
  109. package/schemas/capability.schema.json +113 -0
  110. package/schemas/envelope.schema.json +162 -0
  111. package/schemas/memory.schema.json +51 -0
  112. package/schemas/observation.schema.json +113 -0
  113. package/schemas/plan.schema.json +208 -0
  114. package/schemas/progress.schema.json +126 -0
  115. package/schemas/proposal.schema.json +68 -0
  116. package/schemas/session.schema.json +82 -0
  117. package/schemas/tool.schema.json +94 -0
  118. package/server.d.ts.map +1 -0
  119. package/server.js +28877 -0
  120. package/umd-example.html +18 -0
  121. package/umd.d.ts.map +1 -0
  122. package/accounts.ts +0 -2087
  123. package/agent.ts +0 -2331
  124. package/antigravity.ts +0 -2139
  125. package/apifreeze.ts +0 -4146
  126. package/auth.ts +0 -642
  127. package/background.ts +0 -16837
  128. package/bridge.ts +0 -2080
  129. package/build.ts +0 -54
  130. package/bun.ts +0 -26
  131. package/capture.ts +0 -1614
  132. package/checksecrets.ts +0 -72
  133. package/cjs.ts +0 -9
  134. package/cli.ts +0 -3500
  135. package/commands.ts +0 -1101
  136. package/companion.ts +0 -450
  137. package/compatibility.ts +0 -37
  138. package/config.ts +0 -3137
  139. package/constants.ts +0 -943
  140. package/core.ts +0 -1473
  141. package/crossbrowser.ts +0 -1359
  142. package/dashdone.ts +0 -605
  143. package/data.ts +0 -943
  144. package/database.ts +0 -133
  145. package/debug.ts +0 -850
  146. package/deno.ts +0 -27
  147. package/devthink.ts +0 -707
  148. package/dist/accounts.d.ts +0 -409
  149. package/dist/agent.d.ts +0 -837
  150. package/dist/antigravity.d.ts +0 -380
  151. package/dist/apifreeze.d.ts +0 -113
  152. package/dist/auth.d.ts +0 -224
  153. package/dist/capture.d.ts +0 -595
  154. package/dist/cjs.d.ts +0 -6
  155. package/dist/commands.d.ts +0 -310
  156. package/dist/compatibility.d.ts +0 -17
  157. package/dist/config.d.ts +0 -1853
  158. package/dist/constants.d.ts +0 -637
  159. package/dist/core.d.ts +0 -361
  160. package/dist/data.d.ts +0 -330
  161. package/dist/database.d.ts +0 -24
  162. package/dist/debug.d.ts +0 -270
  163. package/dist/engine.d.ts +0 -74
  164. package/dist/environments.d.ts +0 -244
  165. package/dist/evidence.d.ts +0 -277
  166. package/dist/export.d.ts +0 -311
  167. package/dist/fingerprint.d.ts +0 -594
  168. package/dist/flow.d.ts +0 -300
  169. package/dist/gates.d.ts +0 -103
  170. package/dist/identity.d.ts +0 -51
  171. package/dist/ids.d.ts +0 -7
  172. package/dist/llm.d.ts +0 -652
  173. package/dist/models.d.ts +0 -1807
  174. package/dist/net.d.ts +0 -325
  175. package/dist/neutral.d.ts +0 -41
  176. package/dist/oauth.d.ts +0 -703
  177. package/dist/page.d.ts +0 -1166
  178. package/dist/perf.d.ts +0 -481
  179. package/dist/plan.d.ts +0 -134
  180. package/dist/project.d.ts +0 -395
  181. package/dist/providers.d.ts +0 -37
  182. package/dist/quota.d.ts +0 -453
  183. package/dist/recovery.d.ts +0 -621
  184. package/dist/request.d.ts +0 -1492
  185. package/dist/run.d.ts +0 -779
  186. package/dist/runtime.d.ts +0 -212
  187. package/dist/search.d.ts +0 -375
  188. package/dist/security.d.ts +0 -534
  189. package/dist/serve.d.ts +0 -136
  190. package/dist/session.d.ts +0 -296
  191. package/dist/storage.d.ts +0 -53
  192. package/dist/streaming.d.ts +0 -1119
  193. package/dist/swarm.d.ts +0 -328
  194. package/dist/tools.d.ts +0 -170
  195. package/dist/types.d.ts +0 -8357
  196. package/dist/utils.d.ts +0 -82
  197. package/dist/version.d.ts +0 -7
  198. package/dist/versionregistry.d.ts +0 -406
  199. package/dist/views.d.ts +0 -579
  200. package/dist/workbenchsession.d.ts +0 -69
  201. package/dist/workflow.d.ts +0 -649
  202. package/docs/readme.md +0 -92
  203. package/docs/schemas/antigravity.json +0 -192
  204. package/engine.ts +0 -1524
  205. package/environments.ts +0 -1005
  206. package/evidence.ts +0 -643
  207. package/export.ts +0 -889
  208. package/fingerprint.ts +0 -1458
  209. package/flow.ts +0 -1190
  210. package/gates.ts +0 -307
  211. package/gateway.ts +0 -34
  212. package/hardening.ts +0 -191
  213. package/headless.ts +0 -369
  214. package/http.ts +0 -2110
  215. package/identity.ts +0 -246
  216. package/ids.ts +0 -26
  217. package/index.ts +0 -369
  218. package/llm.ts +0 -2682
  219. package/mcp.ts +0 -1835
  220. package/models.ts +0 -3805
  221. package/modes.ts +0 -43
  222. package/net.ts +0 -1214
  223. package/neutral.ts +0 -362
  224. package/node.ts +0 -26
  225. package/oauth.ts +0 -2216
  226. package/offscreen.ts +0 -170
  227. package/pack.ts +0 -956
  228. package/page.ts +0 -7824
  229. package/pagebridge.ts +0 -1116
  230. package/perf.ts +0 -957
  231. package/plan.ts +0 -672
  232. package/plugin.ts +0 -76
  233. package/prisma.config.ts +0 -27
  234. package/progress.ts +0 -1308
  235. package/project.ts +0 -1291
  236. package/protocol.ts +0 -4187
  237. package/providers.ts +0 -246
  238. package/quota.ts +0 -1887
  239. package/recovery.ts +0 -2433
  240. package/request.ts +0 -4482
  241. package/run.ts +0 -2135
  242. package/runtime.ts +0 -526
  243. package/search.ts +0 -1760
  244. package/security.ts +0 -1673
  245. package/serve.ts +0 -419
  246. package/server.ts +0 -5538
  247. package/session.ts +0 -1162
  248. package/storage.ts +0 -182
  249. package/streaming.ts +0 -4101
  250. package/swarm.ts +0 -884
  251. package/sync.ts +0 -56
  252. package/tests/agentcert.test.ts +0 -128
  253. package/tests/agentfleet.test.ts +0 -214
  254. package/tests/agentreview.test.ts +0 -241
  255. package/tests/agentstream.test.ts +0 -335
  256. package/tests/agentwork.test.ts +0 -356
  257. package/tests/apifreeze.test.ts +0 -290
  258. package/tests/apimap.test.ts +0 -112
  259. package/tests/approvalgate.test.ts +0 -175
  260. package/tests/artifactmanifest.test.ts +0 -204
  261. package/tests/attentionfeed.test.ts +0 -163
  262. package/tests/backgroundruns.test.ts +0 -100
  263. package/tests/batchscheduling.test.ts +0 -131
  264. package/tests/blackboard.test.ts +0 -238
  265. package/tests/bridge.test.ts +0 -1088
  266. package/tests/browsercoverage.test.ts +0 -134
  267. package/tests/browserpolyfills.test.ts +0 -124
  268. package/tests/build.mjs +0 -1260
  269. package/tests/clientauth.test.ts +0 -223
  270. package/tests/clitools.test.ts +0 -578
  271. package/tests/confirmgates.test.ts +0 -190
  272. package/tests/containerpack.test.ts +0 -143
  273. package/tests/controlflow.test.ts +0 -2120
  274. package/tests/coordination.test.ts +0 -345
  275. package/tests/copyscreen.test.ts +0 -139
  276. package/tests/core.test.ts +0 -417
  277. package/tests/costcert.test.ts +0 -95
  278. package/tests/crossbrowser.test.ts +0 -115
  279. package/tests/cspaudit.test.ts +0 -79
  280. package/tests/dashdone.test.ts +0 -615
  281. package/tests/datagrid.test.ts +0 -137
  282. package/tests/doccheck.test.ts +0 -107
  283. package/tests/dombatch.test.ts +0 -109
  284. package/tests/emulation.test.ts +0 -282
  285. package/tests/environments.test.ts +0 -259
  286. package/tests/evidenceviews.test.ts +0 -88
  287. package/tests/exporttools.test.ts +0 -185
  288. package/tests/firefoxprep.test.ts +0 -134
  289. package/tests/flowlibrary.test.ts +0 -242
  290. package/tests/flowrun.test.ts +0 -303
  291. package/tests/forensics.test.ts +0 -439
  292. package/tests/gateway.test.ts +0 -939
  293. package/tests/headlesslib.test.ts +0 -171
  294. package/tests/httpstream.test.ts +0 -277
  295. package/tests/immutablelog.test.ts +0 -157
  296. package/tests/inboundguard.test.ts +0 -177
  297. package/tests/lazyload.test.ts +0 -72
  298. package/tests/librarymodes.test.ts +0 -623
  299. package/tests/llm.test.ts +0 -696
  300. package/tests/manifest.test.ts +0 -226
  301. package/tests/maskinputs.test.ts +0 -150
  302. package/tests/matrixverify.test.ts +0 -111
  303. package/tests/mavenpack.test.ts +0 -75
  304. package/tests/mcpserver.test.ts +0 -704
  305. package/tests/memory.test.ts +0 -4155
  306. package/tests/memorycare.test.ts +0 -230
  307. package/tests/migrateplan.test.ts +0 -349
  308. package/tests/minimization.test.ts +0 -414
  309. package/tests/modelroute.test.ts +0 -112
  310. package/tests/multiagent.test.ts +0 -440
  311. package/tests/nativebridge.test.ts +0 -807
  312. package/tests/navigation.test.ts +0 -284
  313. package/tests/nugetpack.test.ts +0 -83
  314. package/tests/orchestration.test.ts +0 -449
  315. package/tests/originpolicy.test.ts +0 -405
  316. package/tests/outputcompare.test.ts +0 -97
  317. package/tests/package.test.ts +0 -91
  318. package/tests/pagebridge.test.ts +0 -5909
  319. package/tests/pentest.test.ts +0 -75
  320. package/tests/perfrecords.test.ts +0 -257
  321. package/tests/permdiff.test.ts +0 -85
  322. package/tests/phishguard.test.ts +0 -128
  323. package/tests/pickerviews.test.ts +0 -155
  324. package/tests/pipelines.test.ts +0 -381
  325. package/tests/planlint.test.ts +0 -240
  326. package/tests/planreview.test.ts +0 -383
  327. package/tests/platformtargets.test.ts +0 -56
  328. package/tests/policy.test.ts +0 -8284
  329. package/tests/portability.test.ts +0 -96
  330. package/tests/progress.test.ts +0 -1036
  331. package/tests/promptlibrary.test.ts +0 -116
  332. package/tests/protocol.test.ts +0 -4793
  333. package/tests/publishingpipeline.test.ts +0 -314
  334. package/tests/quickactions.test.ts +0 -164
  335. package/tests/readiness.test.ts +0 -78
  336. package/tests/recipes.test.ts +0 -163
  337. package/tests/redactshots.test.ts +0 -216
  338. package/tests/registernvidiakeys.ts +0 -51
  339. package/tests/relayserve.test.ts +0 -304
  340. package/tests/releasenotes.test.ts +0 -276
  341. package/tests/resilience.test.ts +0 -467
  342. package/tests/resourceaware.test.ts +0 -187
  343. package/tests/runbudget.test.ts +0 -125
  344. package/tests/runhistory.test.ts +0 -299
  345. package/tests/runreplay.test.ts +0 -113
  346. package/tests/runresume.test.ts +0 -184
  347. package/tests/runstate.test.ts +0 -288
  348. package/tests/runtimeadapters.test.ts +0 -251
  349. package/tests/safariskeleton.test.ts +0 -115
  350. package/tests/sandboxframe.test.ts +0 -196
  351. package/tests/sbom.test.ts +0 -105
  352. package/tests/secretvault.test.ts +0 -188
  353. package/tests/selcache.test.ts +0 -111
  354. package/tests/sessioninterface.test.ts +0 -791
  355. package/tests/sessions.test.ts +0 -591
  356. package/tests/siteprefs.test.ts +0 -228
  357. package/tests/snapshotdelta.test.ts +0 -165
  358. package/tests/statusviews.test.ts +0 -237
  359. package/tests/stepmeter.test.ts +0 -200
  360. package/tests/streamparse.test.ts +0 -163
  361. package/tests/stylepruning.test.ts +0 -90
  362. package/tests/surfaces.test.ts +0 -282
  363. package/tests/sweep.test.ts +0 -78
  364. package/tests/syncbridge.test.ts +0 -164
  365. package/tests/taskqueue.test.ts +0 -206
  366. package/tests/toolcalls.test.ts +0 -336
  367. package/tests/toolcatalog.test.ts +0 -201
  368. package/tests/torture-agent.test.ts +0 -706
  369. package/tests/torture-auth.test.ts +0 -461
  370. package/tests/torture-commands.test.ts +0 -895
  371. package/tests/torture-data.test.ts +0 -923
  372. package/tests/torture-environments.test.ts +0 -285
  373. package/tests/torture-export.test.ts +0 -263
  374. package/tests/torture-http.test.ts +0 -1379
  375. package/tests/torture-llm.test.ts +0 -808
  376. package/tests/torture-memory.test.ts +0 -1084
  377. package/tests/torture-plan.test.ts +0 -829
  378. package/tests/torture-run.test.ts +0 -626
  379. package/tests/torture-session.test.ts +0 -928
  380. package/tests/torture-swarm.test.ts +0 -1245
  381. package/tests/torture-tools.test.ts +0 -964
  382. package/tests/torture-workflow.test.ts +0 -2354
  383. package/tests/tourviews.test.ts +0 -52
  384. package/tests/transparency.test.ts +0 -147
  385. package/tests/trigger.test.ts +0 -941
  386. package/tests/v1sunset.test.ts +0 -428
  387. package/tests/virtlist.test.ts +0 -94
  388. package/tests/vision.test.ts +0 -540
  389. package/tests/vsixpack.test.ts +0 -145
  390. package/tests/webapi.test.ts +0 -523
  391. package/tests/workflow.test.ts +0 -1785
  392. package/tests/workfloweditor.test.ts +0 -759
  393. package/tests/xpipack.test.ts +0 -128
  394. package/tools.ts +0 -734
  395. package/types.ts +0 -9908
  396. package/umd.ts +0 -9
  397. package/utils.ts +0 -249
  398. package/version.ts +0 -8
  399. package/versionregistry.ts +0 -1310
  400. package/views.ts +0 -2153
  401. package/vitest.config.ts +0 -12
  402. package/web/App.tsx +0 -78
  403. package/web/README.md +0 -47
  404. package/web/capacitor.config.ts +0 -46
  405. package/web/const.ts +0 -19
  406. package/web/control.shell.tsx +0 -66
  407. package/web/dashboardpage.ts +0 -554
  408. package/web/db.ts +0 -493
  409. package/web/design.html +0 -541
  410. package/web/gatewayview/Gateway.tsx +0 -345
  411. package/web/gatewayview/config.ts +0 -1042
  412. package/web/gatewayview/definition.ts +0 -174
  413. package/web/icons.ts +0 -15
  414. package/web/optionspage.ts +0 -691
  415. package/web/popup.ts +0 -1651
  416. package/web/schema.prisma +0 -176
  417. package/web/sidepanel.ts +0 -7941
  418. package/web/sitemanifest.json +0 -13
  419. package/web/terminal-ui.tsx +0 -622
  420. package/web/transparencypage.ts +0 -541
  421. package/web/vite.config.ts +0 -39
  422. package/web/workspace.ts +0 -23
  423. package/workbenchmemory.ts +0 -104
  424. package/workbenchsession.ts +0 -304
  425. package/workflow.ts +0 -4495
  426. /package/{dist/bun.d.ts → bun.d.ts} +0 -0
  427. /package/{dist/cli.d.ts → cli.d.ts} +0 -0
  428. /package/{dist/companion.d.ts → companion.d.ts} +0 -0
  429. /package/{dist/crossbrowser.d.ts → crossbrowser.d.ts} +0 -0
  430. /package/{dist/dashdone.d.ts → dashdone.d.ts} +0 -0
  431. /package/{dist/deno.d.ts → deno.d.ts} +0 -0
  432. /package/{dist/hardening.d.ts → hardening.d.ts} +0 -0
  433. /package/{dist/headless.d.ts → headless.d.ts} +0 -0
  434. /package/{dist/http.d.ts → http.d.ts} +0 -0
  435. /package/{dist/index.d.ts → index.d.ts} +0 -0
  436. /package/{dist/mcp.d.ts → mcp.d.ts} +0 -0
  437. /package/{dist/memory.d.ts → memory.d.ts} +0 -0
  438. /package/{dist/node.d.ts → node.d.ts} +0 -0
  439. /package/{dist/pack.d.ts → pack.d.ts} +0 -0
  440. /package/{dist/policy.d.ts → policy.d.ts} +0 -0
  441. /package/{dist/progress.d.ts → progress.d.ts} +0 -0
  442. /package/{dist/protocol.d.ts → protocol.d.ts} +0 -0
  443. /package/{dist/server.d.ts → server.d.ts} +0 -0
  444. /package/{dist/umd.d.ts → umd.d.ts} +0 -0
@@ -1,2120 +0,0 @@
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
- });