@sema-agent/core 7.70.0 → 7.71.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (439) hide show
  1. package/CHANGELOG.md +740 -0
  2. package/dist/agents/agent-transcript-tool.js +43 -19
  3. package/dist/agents/inherited-tool-pool.d.ts +5 -1
  4. package/dist/agents/inherited-tool-pool.js +6 -0
  5. package/dist/agents/retain-ledger.js +2 -0
  6. package/dist/agents/send-message-tool.d.ts +12 -1
  7. package/dist/agents/send-message-tool.js +47 -9
  8. package/dist/agents/subagent.js +31 -10
  9. package/dist/agents/tool-filter.js +1 -2
  10. package/dist/agents/verify.js +13 -2
  11. package/dist/agents/yield-adoption.js +11 -1
  12. package/dist/brain/claude-model-id.d.ts +11 -0
  13. package/dist/brain/claude-model-id.js +3 -1
  14. package/dist/config/catalog.js +10 -1
  15. package/dist/config/defaults.d.ts +3 -0
  16. package/dist/config/defaults.js +1 -0
  17. package/dist/core/allow-entry.js +1 -2
  18. package/dist/core/ask-origin.d.ts +55 -21
  19. package/dist/core/ask-origin.js +19 -11
  20. package/dist/core/ask-question.d.ts +4 -7
  21. package/dist/core/ask-question.js +2 -4
  22. package/dist/core/ask-unresolvable-notice.d.ts +17 -3
  23. package/dist/core/ask-unresolvable-notice.js +18 -4
  24. package/dist/core/attachment-source.d.ts +1 -1
  25. package/dist/core/attachment-source.js +2 -0
  26. package/dist/core/auto-compaction.d.ts +14 -4
  27. package/dist/core/auto-compaction.js +3 -2
  28. package/dist/core/auto-strip.js +2 -0
  29. package/dist/core/caller-text.d.ts +2 -33
  30. package/dist/core/caller-text.js +2 -23
  31. package/dist/core/caller-tool-name.js +1 -2
  32. package/dist/core/canonical-json.d.ts +9 -0
  33. package/dist/core/canonical-json.js +6 -0
  34. package/dist/core/checkpoint-features.d.ts +43 -80
  35. package/dist/core/checkpoint-features.js +10 -20
  36. package/dist/core/checkpoint-generation.d.ts +89 -19
  37. package/dist/core/checkpoint-generation.js +89 -14
  38. package/dist/core/checkpoint-queries.d.ts +95 -15
  39. package/dist/core/checkpoint-queries.js +108 -7
  40. package/dist/core/checkpoint-rekey.d.ts +2 -1
  41. package/dist/core/checkpoint-rekey.js +2 -2
  42. package/dist/core/checkpoint-requirements.d.ts +21 -7
  43. package/dist/core/checkpoint-requirements.js +2 -5
  44. package/dist/core/checkpoint-row-verdict.d.ts +3 -4
  45. package/dist/core/checkpoint-row-verdict.js +20 -41
  46. package/dist/core/checkpoint-store.d.ts +69 -41
  47. package/dist/core/checkpoint-store.js +28 -14
  48. package/dist/core/command-sandbox.d.ts +5 -3
  49. package/dist/core/command-sandbox.js +17 -9
  50. package/dist/core/config-refusal-codes.d.ts +1 -1
  51. package/dist/core/config-refusal-codes.js +1 -0
  52. package/dist/core/declaration-words.d.ts +2 -1
  53. package/dist/core/declaration-words.js +13 -2
  54. package/dist/core/effective-path-target.d.ts +23 -0
  55. package/dist/core/effective-path-target.js +15 -1
  56. package/dist/core/engine-attestation.d.ts +5 -1
  57. package/dist/core/engine-attestation.js +1 -0
  58. package/dist/core/engine-capabilities.d.ts +14 -9
  59. package/dist/core/engine-capabilities.js +1 -1
  60. package/dist/core/engine-notice.d.ts +62 -32
  61. package/dist/core/engine-version.js +1 -1
  62. package/dist/core/entries-not-applied.d.ts +1 -1
  63. package/dist/core/entries-not-applied.js +1 -0
  64. package/dist/core/file-history-store.d.ts +95 -11
  65. package/dist/core/file-history-store.js +117 -19
  66. package/dist/core/gate-fold.js +13 -7
  67. package/dist/core/gate-lanes.js +9 -9
  68. package/dist/core/governance-codes.d.ts +56 -7
  69. package/dist/core/governance-codes.js +105 -7
  70. package/dist/core/grant-holder.d.ts +53 -0
  71. package/dist/core/grant-holder.js +80 -0
  72. package/dist/core/hooks.d.ts +7 -3
  73. package/dist/core/hooks.js +2 -2
  74. package/dist/core/locked-config.d.ts +7 -1
  75. package/dist/core/locked-config.js +9 -2
  76. package/dist/core/mcp-call-meta.d.ts +52 -7
  77. package/dist/core/mcp-call-meta.js +21 -2
  78. package/dist/core/mcp-host-read.d.ts +1 -1
  79. package/dist/core/mcp-server-spec.d.ts +18 -0
  80. package/dist/core/mcp-server-spec.js +1 -0
  81. package/dist/core/mcp.js +2 -2
  82. package/dist/core/member-outcome.d.ts +22 -1
  83. package/dist/core/member-outcome.js +18 -6
  84. package/dist/core/memory-engine/delegation-settlement.js +5 -5
  85. package/dist/core/memory-engine/engine.js +19 -19
  86. package/dist/core/memory-engine/file-backend.d.ts +7 -2
  87. package/dist/core/memory-engine/file-backend.js +14 -12
  88. package/dist/core/memory-engine/frontmatter.js +1 -1
  89. package/dist/core/memory-engine/index.d.ts +1 -0
  90. package/dist/core/memory-engine/index.js +1 -0
  91. package/dist/core/memory-engine/layout.d.ts +34 -9
  92. package/dist/core/memory-engine/layout.js +36 -19
  93. package/dist/core/memory-engine/memory-deployment.js +8 -8
  94. package/dist/core/memory-engine/mount-failed-notice.d.ts +8 -5
  95. package/dist/core/memory-engine/mount-failed-notice.js +5 -2
  96. package/dist/core/mode-policy.d.ts +5 -0
  97. package/dist/core/mode-policy.js +6 -0
  98. package/dist/core/mods/host.d.ts +2 -1
  99. package/dist/core/mods/host.js +7 -6
  100. package/dist/core/mods/kernel/index.d.ts +1 -1
  101. package/dist/core/mods/kernel/index.js +1 -1
  102. package/dist/core/mods/kernel/registration.d.ts +5 -2
  103. package/dist/core/mods/kernel/registration.js +19 -3
  104. package/dist/core/mods/package.d.ts +12 -1
  105. package/dist/core/mods/package.js +36 -9
  106. package/dist/core/mods/stations.d.ts +7 -1
  107. package/dist/core/mods/stations.js +17 -3
  108. package/dist/core/mods/teammate-stations.d.ts +4 -1
  109. package/dist/core/mods/teammate-stations.js +1 -1
  110. package/dist/core/native-signal.d.ts +13 -0
  111. package/dist/core/native-signal.js +18 -0
  112. package/dist/core/park-resumability.d.ts +16 -14
  113. package/dist/core/park-resumability.js +9 -4
  114. package/dist/core/path-rule-binding.js +1 -1
  115. package/dist/core/permission-rule-model.d.ts +11 -5
  116. package/dist/core/permission-rule-model.js +5 -3
  117. package/dist/core/permission-rule-org.js +1 -1
  118. package/dist/core/permission-rule-provider.d.ts +5 -1
  119. package/dist/core/permission-rule-provider.js +6 -1
  120. package/dist/core/permission-rule-session.d.ts +35 -5
  121. package/dist/core/permission-rule-session.js +32 -1
  122. package/dist/core/permission-rule-store.d.ts +5 -1
  123. package/dist/core/permission-rule-store.js +28 -5
  124. package/dist/core/permission-rules.d.ts +2 -2
  125. package/dist/core/permission-rules.js +2 -3
  126. package/dist/core/principal-name.d.ts +12 -0
  127. package/dist/core/principal-name.js +6 -2
  128. package/dist/core/read-root-grant-screen.d.ts +7 -6
  129. package/dist/core/read-root-grant-screen.js +7 -8
  130. package/dist/core/remote-env.d.ts +42 -8
  131. package/dist/core/resume-config-judge.js +1 -1
  132. package/dist/core/resume-startup-cause.d.ts +19 -4
  133. package/dist/core/resume-startup-cause.js +25 -6
  134. package/dist/core/rewind-conversation.d.ts +4 -0
  135. package/dist/core/rewrite-rejudge.d.ts +9 -1
  136. package/dist/core/rewrite-rejudge.js +11 -1
  137. package/dist/core/rule-offer-read.js +3 -2
  138. package/dist/core/runner/assemble-result.d.ts +21 -11
  139. package/dist/core/runner/assemble-result.js +24 -4
  140. package/dist/core/runner/boundary-reminders.d.ts +104 -0
  141. package/dist/core/runner/boundary-reminders.js +108 -0
  142. package/dist/core/runner/branch-writeback.d.ts +21 -7
  143. package/dist/core/runner/branch-writeback.js +44 -6
  144. package/dist/core/runner/command-sandbox-frame.js +2 -1
  145. package/dist/core/runner/compact-session.js +11 -4
  146. package/dist/core/runner/constraint-layers.d.ts +24 -5
  147. package/dist/core/runner/constraint-layers.js +21 -2
  148. package/dist/core/runner/continuation-gate.js +3 -1
  149. package/dist/core/runner/contracts.d.ts +83 -13
  150. package/dist/core/runner/cross-boundary-lane.js +2 -1
  151. package/dist/core/runner/delegation-owner.d.ts +246 -45
  152. package/dist/core/runner/delegation-owner.js +237 -63
  153. package/dist/core/runner/expire-settle.d.ts +17 -0
  154. package/dist/core/runner/expire-settle.js +8 -2
  155. package/dist/core/runner/file-history-request.d.ts +4 -3
  156. package/dist/core/runner/file-history-request.js +4 -1
  157. package/dist/core/runner/file-history-restore.d.ts +11 -3
  158. package/dist/core/runner/file-history-restore.js +11 -3
  159. package/dist/core/runner/gate-exit.d.ts +22 -1
  160. package/dist/core/runner/gate-exit.js +12 -14
  161. package/dist/core/runner/nested-memory-content.js +1 -1
  162. package/dist/core/runner/nested-memory-lane.d.ts +10 -2
  163. package/dist/core/runner/nested-memory-lane.js +29 -8
  164. package/dist/core/runner/own-model-money-door.d.ts +13 -0
  165. package/dist/core/runner/own-model-money-door.js +17 -0
  166. package/dist/core/runner/park-commit.d.ts +4 -2
  167. package/dist/core/runner/park-commit.js +2 -1
  168. package/dist/core/runner/permission-rule-lanes.d.ts +4 -0
  169. package/dist/core/runner/permission-rule-lanes.js +7 -0
  170. package/dist/core/runner/person-path-rows.js +1 -1
  171. package/dist/core/runner/placement-fence.d.ts +8 -2
  172. package/dist/core/runner/placement-fence.js +8 -3
  173. package/dist/core/runner/policy-throw.d.ts +3 -2
  174. package/dist/core/runner/policy-throw.js +2 -2
  175. package/dist/core/runner/prepare-acquire-reconcile.d.ts +23 -14
  176. package/dist/core/runner/prepare-acquire-reconcile.js +33 -15
  177. package/dist/core/runner/prepare-artifact.d.ts +14 -1
  178. package/dist/core/runner/prepare-artifact.js +7 -2
  179. package/dist/core/runner/prepare-ask-lane.d.ts +8 -0
  180. package/dist/core/runner/prepare-ask-lane.js +14 -5
  181. package/dist/core/runner/prepare-boundary-parks.js +5 -4
  182. package/dist/core/runner/prepare-config-doors.d.ts +9 -4
  183. package/dist/core/runner/prepare-config-doors.js +25 -8
  184. package/dist/core/runner/prepare-defer-classify.d.ts +8 -4
  185. package/dist/core/runner/prepare-defer-classify.js +6 -6
  186. package/dist/core/runner/prepare-execution-env.d.ts +4 -1
  187. package/dist/core/runner/prepare-execution-env.js +8 -3
  188. package/dist/core/runner/prepare-file-history.d.ts +26 -0
  189. package/dist/core/runner/prepare-file-history.js +15 -1
  190. package/dist/core/runner/prepare-inherited-gate.d.ts +8 -3
  191. package/dist/core/runner/prepare-inherited-gate.js +9 -2
  192. package/dist/core/runner/prepare-leg-adoption.d.ts +2 -2
  193. package/dist/core/runner/prepare-park-ask.js +8 -5
  194. package/dist/core/runner/prepare-policy-chain.d.ts +5 -0
  195. package/dist/core/runner/prepare-policy-chain.js +18 -7
  196. package/dist/core/runner/prepare-prompt-assembly.d.ts +3 -0
  197. package/dist/core/runner/prepare-prompt-assembly.js +4 -3
  198. package/dist/core/runner/prepare-suspend-saga.d.ts +4 -1
  199. package/dist/core/runner/prepare-suspend-saga.js +19 -5
  200. package/dist/core/runner/prepare-task.d.ts +2 -5
  201. package/dist/core/runner/prepare-task.js +71 -26
  202. package/dist/core/runner/prepare-turn-wiring.js +7 -5
  203. package/dist/core/runner/prepare-workspace-restore.js +59 -28
  204. package/dist/core/runner/read-root-grant.d.ts +1 -0
  205. package/dist/core/runner/read-root-grant.js +1 -2
  206. package/dist/core/runner/resume-admission.d.ts +3 -0
  207. package/dist/core/runner/resume-admission.js +6 -4
  208. package/dist/core/runner/resume-apply.js +7 -5
  209. package/dist/core/runner/resume-claim.d.ts +2 -2
  210. package/dist/core/runner/resume-claim.js +4 -4
  211. package/dist/core/runner/resume-policy-outcome.d.ts +1 -1
  212. package/dist/core/runner/resume-policy-outcome.js +6 -4
  213. package/dist/core/runner/resume-preflight.d.ts +3 -0
  214. package/dist/core/runner/resume-preflight.js +10 -3
  215. package/dist/core/runner/rewind-conversation.js +11 -4
  216. package/dist/core/runner/rewind-files.js +29 -14
  217. package/dist/core/runner/rewind-outcome.d.ts +27 -0
  218. package/dist/core/runner/rewind-outcome.js +14 -0
  219. package/dist/core/runner/run-attachment-seats.js +2 -1
  220. package/dist/core/runner/run-clock-and-content.js +2 -0
  221. package/dist/core/runner/run-identity-wiring.js +2 -0
  222. package/dist/core/runner/run-leg.js +11 -1
  223. package/dist/core/runner/run-notification-lane.d.ts +3 -0
  224. package/dist/core/runner/run-notification-lane.js +2 -2
  225. package/dist/core/runner/run-settle-and-teardown.d.ts +4 -2
  226. package/dist/core/runner/run-settle-and-teardown.js +52 -40
  227. package/dist/core/runner/run-stop-and-final-verify.d.ts +4 -0
  228. package/dist/core/runner/run-stop-and-final-verify.js +5 -4
  229. package/dist/core/runner/run-terminal-adoption.d.ts +1 -1
  230. package/dist/core/runner/run-terminal-adoption.js +3 -3
  231. package/dist/core/runner/run-turn-boundary.js +7 -0
  232. package/dist/core/runner/runtask.d.ts +7 -4
  233. package/dist/core/runner/runtask.js +18 -9
  234. package/dist/core/runner/session-call-grant-station.d.ts +64 -0
  235. package/dist/core/runner/session-call-grant-station.js +119 -0
  236. package/dist/core/runner/session-file-state-replay.js +2 -2
  237. package/dist/core/runner/session-prompt-seats.d.ts +95 -0
  238. package/dist/core/runner/session-prompt-seats.js +62 -0
  239. package/dist/core/runner/session-rule-policy.js +1 -1
  240. package/dist/core/runner/session-write-ledger.d.ts +8 -0
  241. package/dist/core/runner/session-write-ledger.js +16 -0
  242. package/dist/core/runner/side-call-account.js +5 -1
  243. package/dist/core/runner/stop-tail-notice.d.ts +7 -0
  244. package/dist/core/runner/stop-tail-notice.js +23 -8
  245. package/dist/core/runner/stream-reap.js +4 -2
  246. package/dist/core/runner/stream-settle-backstop.d.ts +1 -1
  247. package/dist/core/runner/stream-settle-backstop.js +17 -18
  248. package/dist/core/runner/terminal-account.js +17 -8
  249. package/dist/core/runner/terminal-projection.d.ts +3 -2
  250. package/dist/core/runner/terminal-projection.js +1 -1
  251. package/dist/core/runner/tool-turn-repair-seat.d.ts +2 -2
  252. package/dist/core/runner/tool-turn-repair-seat.js +12 -7
  253. package/dist/core/runner/turn-attachments.d.ts +22 -1
  254. package/dist/core/runner/turn-attachments.js +20 -3
  255. package/dist/core/runner-deps.d.ts +6 -2
  256. package/dist/core/secret-env.d.ts +26 -6
  257. package/dist/core/secret-env.js +6 -6
  258. package/dist/core/session-call-grant-screen.d.ts +58 -0
  259. package/dist/core/session-call-grant-screen.js +18 -0
  260. package/dist/core/session-call-grant.d.ts +93 -0
  261. package/dist/core/session-call-grant.js +524 -0
  262. package/dist/core/session-checkout.d.ts +3 -0
  263. package/dist/core/session-checkout.js +8 -3
  264. package/dist/core/session-policy-store.d.ts +14 -0
  265. package/dist/core/session-policy-store.js +16 -2
  266. package/dist/core/session-store.d.ts +18 -1
  267. package/dist/core/session-store.js +20 -4
  268. package/dist/core/session.d.ts +36 -4
  269. package/dist/core/shared-artifact-reads.d.ts +93 -0
  270. package/dist/core/shared-artifact-reads.js +94 -0
  271. package/dist/core/skill-grant.js +1 -1
  272. package/dist/core/skills-directory.d.ts +9 -45
  273. package/dist/core/skills-directory.js +9 -722
  274. package/dist/core/spend-account.js +3 -0
  275. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +22 -4
  276. package/dist/core/store-contracts/checkpoint-store-contract.js +363 -29
  277. package/dist/core/store-contracts/file-history-store-contract.d.ts +11 -3
  278. package/dist/core/store-contracts/file-history-store-contract.js +62 -2
  279. package/dist/core/store-contracts/grant-fixture.d.ts +52 -0
  280. package/dist/core/store-contracts/grant-fixture.js +84 -0
  281. package/dist/core/store-contracts/session-repo-contract.js +18 -0
  282. package/dist/core/store-contracts/session-store-contract.d.ts +15 -1
  283. package/dist/core/store-contracts/session-store-contract.js +211 -2
  284. package/dist/core/store-contracts/workflow-journal-store-contract.js +47 -8
  285. package/dist/core/suspend-lane-reasons.d.ts +13 -0
  286. package/dist/core/suspend-lane-reasons.js +5 -0
  287. package/dist/core/synthetic-read-verdict.d.ts +5 -3
  288. package/dist/core/synthetic-read-verdict.js +1 -1
  289. package/dist/core/task-limits.d.ts +15 -0
  290. package/dist/core/task-notification.d.ts +33 -7
  291. package/dist/core/task-notification.js +34 -9
  292. package/dist/core/task-registry-agent.d.ts +1 -1
  293. package/dist/core/task-registry-agent.js +18 -7
  294. package/dist/core/task-registry-shared.d.ts +29 -4
  295. package/dist/core/task-registry-shared.js +7 -0
  296. package/dist/core/task-registry.d.ts +21 -1
  297. package/dist/core/task-registry.js +36 -9
  298. package/dist/core/task-result.d.ts +55 -1
  299. package/dist/core/task-spec.d.ts +17 -3
  300. package/dist/core/terminal-cause.d.ts +68 -5
  301. package/dist/core/tool-catalog-entries.js +1 -1
  302. package/dist/core/tool-check-reading.js +2 -1
  303. package/dist/core/tool-errors.js +1 -0
  304. package/dist/core/tool-list-grammar.d.ts +0 -47
  305. package/dist/core/tool-list-grammar.js +1 -75
  306. package/dist/core/tool-model-gate.d.ts +7 -11
  307. package/dist/core/tool-model-gate.js +5 -8
  308. package/dist/core/tool-name-aliases.js +2 -3
  309. package/dist/core/tool-name-readings.d.ts +4 -0
  310. package/dist/core/tool-name-readings.js +1 -0
  311. package/dist/core/tool-policy.d.ts +46 -4
  312. package/dist/core/tool-policy.js +47 -18
  313. package/dist/core/tool-result-store.d.ts +0 -24
  314. package/dist/core/tool-result-store.js +1 -36
  315. package/dist/core/tool-spec.d.ts +8 -4
  316. package/dist/core/untrusted-egress.js +2 -2
  317. package/dist/core/untrusted-text.d.ts +8 -0
  318. package/dist/core/untrusted-text.js +14 -0
  319. package/dist/core/user-attachment.d.ts +16 -1
  320. package/dist/core/user-attachment.js +42 -18
  321. package/dist/core/wiring-manifest.d.ts +4 -9
  322. package/dist/core/wiring-manifest.js +1 -1
  323. package/dist/core/workflow-journal-store.d.ts +55 -8
  324. package/dist/core/workflow-journal-store.js +34 -10
  325. package/dist/core/workflow-run-store-contract.js +56 -1
  326. package/dist/core/workflow-run-store.d.ts +43 -19
  327. package/dist/core/workflow-run-store.js +17 -2
  328. package/dist/engine/execution-env/node-execution-env.d.ts +3 -0
  329. package/dist/engine/execution-env/node-execution-env.js +4 -0
  330. package/dist/engine/harness/agent-harness.d.ts +10 -5
  331. package/dist/engine/harness/agent-harness.js +12 -4
  332. package/dist/engine/harness/types.d.ts +18 -0
  333. package/dist/engine/llm/tool-turns.d.ts +1 -1
  334. package/dist/engine/llm/types.d.ts +5 -4
  335. package/dist/engine/session/memory-repo.d.ts +15 -3
  336. package/dist/engine/session/memory-repo.js +21 -3
  337. package/dist/engine/session/memory-storage.d.ts +5 -0
  338. package/dist/engine/session/memory-storage.js +8 -3
  339. package/dist/engine/session/repo-utils.d.ts +9 -0
  340. package/dist/engine/session/repo-utils.js +14 -0
  341. package/dist/engine/session/storage-base.d.ts +20 -7
  342. package/dist/engine/session/storage-base.js +13 -1
  343. package/dist/index.d.ts +39 -21
  344. package/dist/index.js +32 -17
  345. package/dist/internal/harness.d.ts +1 -1
  346. package/dist/internal/harness.js +1 -1
  347. package/dist/orchestration/run-workflow-tool.d.ts +13 -1
  348. package/dist/orchestration/run-workflow-tool.js +101 -32
  349. package/dist/orchestration/workflow-park-adoption.d.ts +309 -92
  350. package/dist/orchestration/workflow-park-adoption.js +588 -323
  351. package/dist/orchestration/workflow-tree-id.d.ts +66 -0
  352. package/dist/orchestration/workflow-tree-id.js +66 -0
  353. package/dist/orchestration/workflow-types.d.ts +90 -11
  354. package/dist/orchestration/workflow-types.js +10 -1
  355. package/dist/orchestration/workflow.d.ts +30 -4
  356. package/dist/orchestration/workflow.js +424 -114
  357. package/dist/prompt-assembly/catalog/constitution.js +5 -1
  358. package/dist/prompt-assembly/catalog/core-behavior.d.ts +3 -4
  359. package/dist/prompt-assembly/catalog/core-behavior.js +61 -22
  360. package/dist/prompt-assembly/catalog/environment.js +2 -2
  361. package/dist/prompt-assembly/catalog/events.d.ts +16 -0
  362. package/dist/prompt-assembly/catalog/events.js +2 -0
  363. package/dist/prompt-assembly/catalog/locales/zh-Hans/core-behavior.js +72 -44
  364. package/dist/prompt-assembly/catalog/locales/zh-Hans/environment.js +2 -2
  365. package/dist/prompt-assembly/catalog/locales/zh-Hans/events.js +2 -0
  366. package/dist/prompt-assembly/catalog/schema.d.ts +5 -1
  367. package/dist/prompt-assembly/catalog/schema.js +2 -0
  368. package/dist/prompt-assembly/catalog/sections.js +3 -14
  369. package/dist/prompt-assembly/event-registry.js +2 -0
  370. package/dist/prompt-assembly/select.js +1 -0
  371. package/dist/prompt-assembly/tool-catalog.d.ts +10 -7
  372. package/dist/prompt-assembly/tool-catalog.js +21 -7
  373. package/dist/prompt-assembly/types.d.ts +3 -0
  374. package/dist/prompts/default.d.ts +4 -1
  375. package/dist/prompts/default.js +6 -0
  376. package/dist/stores/file/checkpoint-store.d.ts +11 -10
  377. package/dist/stores/file/checkpoint-store.js +36 -10
  378. package/dist/stores/file/file-history-store.d.ts +6 -0
  379. package/dist/stores/file/file-history-store.js +21 -4
  380. package/dist/stores/file/fs-atomic.d.ts +1 -1
  381. package/dist/stores/file/index.d.ts +14 -4
  382. package/dist/stores/file/index.js +21 -5
  383. package/dist/stores/file/process-anchor.d.ts +9 -1
  384. package/dist/stores/file/session-policy-store.js +2 -17
  385. package/dist/stores/file/session-store.d.ts +27 -0
  386. package/dist/stores/file/session-store.js +81 -9
  387. package/dist/stores/file/workflow-journal-store.d.ts +14 -4
  388. package/dist/stores/file/workflow-journal-store.js +32 -24
  389. package/dist/stores/file/workflow-run-store.d.ts +15 -4
  390. package/dist/stores/file/workflow-run-store.js +76 -0
  391. package/dist/tools/artifact/artifact-tool.d.ts +10 -3
  392. package/dist/tools/artifact/artifact-tool.js +16 -1
  393. package/dist/tools/fs/bash-program-position.d.ts +10 -4
  394. package/dist/tools/fs/bash-program-position.js +11 -8
  395. package/dist/tools/fs/bash-readonly-classifier.d.ts +3 -1
  396. package/dist/tools/fs/bash-readonly-classifier.js +9 -2
  397. package/dist/tools/fs/find-actions.d.ts +30 -16
  398. package/dist/tools/fs/find-actions.js +272 -19
  399. package/dist/tools/fs/fs-bash.js +8 -5
  400. package/dist/tools/fs/fs-shared.d.ts +0 -29
  401. package/dist/tools/fs/fs-shared.js +0 -5
  402. package/dist/tools/fs/fs-write.js +2 -1
  403. package/dist/tools/fs/read-deny.d.ts +6 -1
  404. package/dist/tools/fs/read-deny.js +6 -1
  405. package/dist/tools/fs/read-floor.d.ts +6 -0
  406. package/dist/tools/fs/read-floor.js +5 -1
  407. package/dist/tools/fs/removal-actions.d.ts +43 -0
  408. package/dist/tools/fs/removal-actions.js +25 -0
  409. package/dist/tools/fs/removal-targets.d.ts +2 -21
  410. package/dist/tools/fs/removal-targets.js +2 -3
  411. package/dist/tools/fs/safety.d.ts +37 -1
  412. package/dist/tools/fs/safety.js +52 -0
  413. package/dist/tools/fs/shell-climb.d.ts +46 -0
  414. package/dist/tools/fs/shell-climb.js +79 -0
  415. package/dist/tools/fs/shell-read-check.js +47 -19
  416. package/dist/tools/fs/shell-read-establish.js +36 -22
  417. package/dist/tools/fs/shell-read-judge.d.ts +10 -2
  418. package/dist/tools/fs/shell-read-judge.js +4 -4
  419. package/dist/tools/fs/shell-read-plan.d.ts +3 -0
  420. package/dist/tools/fs/shell-read-plan.js +1 -1
  421. package/dist/tools/fs/shell-read-workdir.js +3 -2
  422. package/dist/tools/fs/shell-read-write-targets.d.ts +4 -3
  423. package/dist/tools/fs/shell-read-write-targets.js +3 -0
  424. package/package.json +2 -2
  425. package/test/export-surface.snapshot.json +173 -15
  426. package/wire-changes/core-stores-sql@7.71.0.json +40 -0
  427. package/wire-changes/core-stores-sql@7.71.1.json +40 -0
  428. package/wire-changes/core@7.71.0.json +5827 -0
  429. package/wire-changes/core@7.71.1.json +118 -0
  430. package/wire-changes/mods-kernel@7.71.0.json +52 -0
  431. package/wire-changes/mods-kernel@7.71.1.json +40 -0
  432. package/wire-changes/primitives@7.71.0.json +473 -0
  433. package/wire-changes/primitives@7.71.1.json +40 -0
  434. package/wire-changes/wiki-gate@7.71.0.json +40 -0
  435. package/wire-changes/wiki-gate@7.71.1.json +40 -0
  436. package/dist/core/frontmatter-fence.d.ts +0 -10
  437. package/dist/core/frontmatter-fence.js +0 -6
  438. package/dist/core/permission-rule-syntax.d.ts +0 -46
  439. package/dist/core/permission-rule-syntax.js +0 -52
@@ -1,12 +1,13 @@
1
- import { createHash } from "node:crypto";
2
- import { journalKeepsLaunches, readKeptLaunch } from "../core/workflow-journal-store.js";
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { resumedFromOf, workflowRunCreationIdOf } from "../core/workflow-run-store.js";
3
+ import { journalKeepsLaunches, readKeptLaunch, RESUME_CLAIM_REMAINING_MS_MAX } from "../core/workflow-journal-store.js";
3
4
  import { parentConstraintChainVerdict } from "../core/runner/resume-checkpoint-screen.js";
4
5
  import { judgeCheckpointRow } from "../core/checkpoint-row-verdict.js";
5
6
  import { readMember, thrownName, thrownText } from "../core/thrown-value.js";
6
7
  import { inlineUntrusted } from "../core/untrusted-text.js";
7
8
  import { egressText } from "../core/untrusted-egress.js";
8
9
  import { foreignLine } from "../core/protocol-http-auth.js";
9
- import { WORKFLOW_AGENT_PARKED_ERROR_CODE, WORKFLOW_PARK_DECISION_MARK_BYTES_MAX, WORKFLOW_PARK_SETTLED_DECISIONS_MAX, WORKFLOW_STORE_WAIT_BOUND_MS, workflowParkHolderOf } from "./workflow-types.js";
10
+ import { WORKFLOW_AGENT_PARKED_ERROR_CODE, WORKFLOW_PARK_DECISION_MARK_BYTES_MAX, WORKFLOW_PARK_SETTLED_DECISIONS_MAX, WORKFLOW_STORE_WAIT_BOUND_MS, parkHolderAmong, workflowParkHolderOf } from "./workflow-types.js";
10
11
  export const WORKFLOW_PARK_UNUSED_REASONS = Object.freeze([
11
12
  "workflow_not_mounted",
12
13
  "entry_unreadable",
@@ -19,23 +20,56 @@ export const WORKFLOW_PARK_UNUSED_REASONS = Object.freeze([
19
20
  "host_changed",
20
21
  "denied",
21
22
  "ask_unanswerable",
23
+ "call_changed",
22
24
  "launch_refused",
23
25
  "continuing_elsewhere",
24
26
  "card_unresumable",
25
27
  "waiting_elsewhere",
26
28
  "run_not_ended",
27
29
  ]);
28
- export const WORKFLOW_PARK_SETTLING_REASONS = Object.freeze(["decision_spent", "card_unresumable", "launch_unreadable", "denied"]);
29
- const SETTLING = new Set(WORKFLOW_PARK_SETTLING_REASONS);
30
+ function frozenRows(table) {
31
+ for (const row of Object.values(table))
32
+ Object.freeze(row);
33
+ return Object.freeze(table);
34
+ }
35
+ export const WORKFLOW_PARK_UNUSED_REASON_CLASS = frozenRows({
36
+ workflow_not_mounted: { kept: "deliverable" },
37
+ entry_unreadable: { kept: "decide_again" },
38
+ record_unreadable: { kept: "deliverable" },
39
+ not_holder: { kept: "deliverable" },
40
+ not_pending: { kept: "withdraw" },
41
+ decision_spent: { spent: "decide_again" },
42
+ launch_unrecorded: { kept: "deliverable" },
43
+ launch_unreadable: { spent: "start_over" },
44
+ host_changed: { kept: "deliverable" },
45
+ denied: { kept: "deliverable", spent: "decide_again", spentWhen: "explicit" },
46
+ ask_unanswerable: { kept: "deliverable" },
47
+ call_changed: { kept: "deliverable" },
48
+ launch_refused: { kept: "deliverable" },
49
+ continuing_elsewhere: { kept: "deliverable" },
50
+ card_unresumable: { kept: "deliverable", spent: "start_over", spentWhen: "terminal" },
51
+ waiting_elsewhere: { kept: "deliverable" },
52
+ run_not_ended: { kept: "deliverable" },
53
+ });
54
+ export function workflowParkUnusedClassOf(reason, spent) {
55
+ if (typeof spent !== "boolean" || typeof reason !== "string" || !Object.hasOwn(WORKFLOW_PARK_UNUSED_REASON_CLASS, reason))
56
+ return undefined;
57
+ const row = WORKFLOW_PARK_UNUSED_REASON_CLASS[reason];
58
+ return spent ? row.spent : row.kept;
59
+ }
60
+ const SETTLING = new Set(WORKFLOW_PARK_UNUSED_REASONS.filter((r) => WORKFLOW_PARK_UNUSED_REASON_CLASS[r].spent !== undefined));
30
61
  const UNMARKED_REASONS = new Set(["workflow_not_mounted", "entry_unreadable", "record_unreadable", "run_not_ended", "not_pending", "not_holder"]);
31
62
  function settlesDecision(o) {
32
- return SETTLING.has(o.reason) && (o.reason !== "card_unresumable" || o.terminal === true) && (o.reason !== "denied" || o.explicit === true);
63
+ if (!Object.hasOwn(WORKFLOW_PARK_UNUSED_REASON_CLASS, o.reason))
64
+ return false;
65
+ const row = WORKFLOW_PARK_UNUSED_REASON_CLASS[o.reason];
66
+ return row.spent !== undefined && (row.kept === undefined || o[row.spentWhen] === true);
33
67
  }
34
68
  const UNUSED_REASONS = new Set(WORKFLOW_PARK_UNUSED_REASONS);
35
69
  function parkEntriesOn(token, records) {
36
70
  const out = [];
37
71
  for (const r of records) {
38
- if (r === null || r === undefined || !Array.isArray(r.parks))
72
+ if (!Array.isArray(r.parks))
39
73
  continue;
40
74
  for (const entry of r.parks)
41
75
  if (isObject(entry) && entry.token === token)
@@ -43,6 +77,11 @@ function parkEntriesOn(token, records) {
43
77
  }
44
78
  return out;
45
79
  }
80
+ function holderEntriesOn(token, records) {
81
+ const holder = parkHolderAmong(token, records);
82
+ const ids = holder.kind === "held" ? [holder.runId] : holder.kind === "fork" ? holder.runIds : [];
83
+ return parkEntriesOn(token, records).filter(({ runId, entry }) => ids.includes(runId) && entry.parkedBy === runId);
84
+ }
46
85
  function markKindOf(m) {
47
86
  if (!isObject(m) || typeof m.decisionId !== "string" || typeof m.reason !== "string")
48
87
  return undefined;
@@ -50,45 +89,44 @@ function markKindOf(m) {
50
89
  return SETTLING.has(m.reason) ? "final" : undefined;
51
90
  return typeof m.condition === "string" && m.condition !== "" && UNUSED_REASONS.has(m.reason) ? "recoverable" : undefined;
52
91
  }
53
- function settledMarkOf(token, decisionId, records) {
92
+ function holderMarkOf(token, decisionId, records) {
54
93
  for (const { runId, entry } of parkEntriesOn(token, records)) {
55
- if (!Array.isArray(entry.settledDecisions))
94
+ const m = Array.isArray(entry.settledDecisions) ? entry.settledDecisions.find((s) => markKindOf(s) === "final" && s.decisionId === decisionId) : undefined;
95
+ if (m !== undefined)
96
+ return { kind: "spent", runId, reason: m.reason, ...(typeof m.code === "string" ? { code: m.code } : {}), by: "mark" };
97
+ }
98
+ for (const { runId, entry } of holderEntriesOn(token, records)) {
99
+ const m = Array.isArray(entry.settledDecisions) ? entry.settledDecisions.find((s) => markKindOf(s) === "recoverable" && s.decisionId === decisionId) : undefined;
100
+ if (m === undefined)
56
101
  continue;
57
- for (const m of entry.settledDecisions) {
58
- if (markKindOf(m) !== "final" || m.decisionId !== decisionId)
59
- continue;
60
- return { kind: "spent", runId, reason: m.reason, ...(typeof m.code === "string" ? { code: m.code } : {}) };
61
- }
102
+ const inputs = Array.isArray(m.inputs) ? m.inputs.filter((k) => HOST_FOLD_INPUTS.includes(k)) : [];
103
+ return { kind: "blocked", runId, reason: m.reason, ...(typeof m.code === "string" ? { code: m.code } : {}), ...(inputs.length > 0 ? { inputs } : {}), condition: m.condition };
62
104
  }
63
105
  return undefined;
64
106
  }
65
- function recoverableMarkOn(entry, decisionId) {
66
- return Array.isArray(entry.settledDecisions) ? entry.settledDecisions.find((m) => markKindOf(m) === "recoverable" && m.decisionId === decisionId) : undefined;
107
+ export function workflowParkDecisionOf(token, decisionId, tree, card) {
108
+ if (card !== undefined && !PARK_CARD_STATES.has(card))
109
+ throw new TypeError(`workflowParkDecisionOf: card (${typeof card === "string" ? JSON.stringify(card) : `a ${typeof card}`}) is not one of ${[...PARK_CARD_STATES].join("/")}`);
110
+ const state = decisionStateOf(token, decisionId, tree);
111
+ if (card === undefined || card === "pending")
112
+ return state;
113
+ if (card !== "unread")
114
+ return { ...state, class: "withdraw" };
115
+ if (!("class" in state))
116
+ return state;
117
+ const { class: _class, ...rest } = state;
118
+ return rest;
67
119
  }
68
- function blockedMarkOf(token, decisionId, records) {
69
- let best;
70
- for (const { runId, entry } of parkEntriesOn(token, records)) {
71
- if (entry.parkedBy !== runId)
72
- continue;
73
- const mark = recoverableMarkOn(entry, decisionId);
74
- const generation = typeof entry.generation === "number" ? entry.generation : -1;
75
- if (mark !== undefined && (best === undefined || generation > best.generation))
76
- best = { runId, generation, mark };
77
- }
78
- if (best === undefined)
79
- return undefined;
80
- const { mark } = best;
81
- const inputs = Array.isArray(mark.inputs) ? mark.inputs.filter((k) => HOST_FOLD_INPUTS.includes(k)) : [];
82
- return { kind: "blocked", runId: best.runId, reason: mark.reason, ...(typeof mark.code === "string" ? { code: mark.code } : {}), ...(inputs.length > 0 ? { inputs } : {}), condition: mark.condition };
83
- }
84
- export function workflowParkDecisionOf(token, decisionId, records) {
120
+ const PARK_CARD_STATES = new Set(["pending", "resolved", "expired", "absent", "unread"]);
121
+ function decisionStateOf(token, decisionId, tree) {
122
+ const records = tree.records;
85
123
  const callKeys = new Set(parkEntriesOn(token, records).map(({ entry }) => entry.callKey).filter((k) => typeof k === "string"));
86
124
  let driven;
87
125
  let refused;
88
126
  let carried;
89
127
  for (const r of records) {
90
- const rows = r?.decisions;
91
- if (r === null || r === undefined || !Array.isArray(rows))
128
+ const rows = r.decisions;
129
+ if (!Array.isArray(rows))
92
130
  continue;
93
131
  for (const d of rows) {
94
132
  if (!isObject(d) || d.decisionId !== decisionId || typeof d.callKey !== "string" || !callKeys.has(d.callKey))
@@ -96,16 +134,50 @@ export function workflowParkDecisionOf(token, decisionId, records) {
96
134
  if (d.result === "driven")
97
135
  driven ??= { kind: "driven", runId: r.id };
98
136
  else if (d.result === "refused")
99
- refused ??= { kind: "spent", runId: r.id, reason: "decision_spent", ...(typeof d.code === "string" ? { code: d.code } : {}) };
137
+ refused ??= { kind: "spent", runId: r.id, reason: "decision_spent", ...(typeof d.code === "string" ? { code: d.code } : {}), by: "drive" };
100
138
  else if (d.result === "not_reached")
101
139
  carried ??= { kind: "carried", runId: r.id };
102
140
  }
103
141
  }
104
- return driven ?? settledMarkOf(token, decisionId, records) ?? refused ?? carried ?? blockedMarkOf(token, decisionId, records) ?? { kind: "open" };
142
+ const mark = holderMarkOf(token, decisionId, records);
143
+ return classed(driven ?? (mark?.kind === "spent" ? mark : undefined) ?? refused ?? carried ?? (mark?.kind === "blocked" ? mark : undefined) ?? { kind: "open" });
144
+ }
145
+ function classed(state) {
146
+ if (state.kind !== "spent" && state.kind !== "blocked")
147
+ return state;
148
+ const c = workflowParkUnusedClassOf(state.reason, state.kind === "spent");
149
+ return c === undefined ? state : { ...state, class: c };
150
+ }
151
+ export function claimRemainingOf(answer, now) {
152
+ let remaining;
153
+ try {
154
+ remaining = answer.remainingMs;
155
+ }
156
+ catch {
157
+ return { kind: "unreadable" };
158
+ }
159
+ if (remaining === undefined)
160
+ return { kind: "unsaid" };
161
+ if (typeof remaining !== "number" || !Number.isSafeInteger(remaining) || remaining < 1 || remaining > RESUME_CLAIM_REMAINING_MS_MAX)
162
+ return { kind: "unreadable" };
163
+ const at = now + remaining;
164
+ return claimLapseInstant(at) === undefined ? { kind: "unreadable" } : { kind: "at", at };
165
+ }
166
+ const ANSWER_RECORD_CLAIM_HOLDER_PREFIX = "answer-record:";
167
+ export function answerRecordClaimHolder() {
168
+ return `${ANSWER_RECORD_CLAIM_HOLDER_PREFIX}${randomUUID()}`;
169
+ }
170
+ export function isAnswerRecordClaimHolder(holder) {
171
+ return holder !== undefined && holder.startsWith(ANSWER_RECORD_CLAIM_HOLDER_PREFIX);
105
172
  }
106
173
  export function claimHeldOf(verdict) {
107
- return { ...(verdict.holder !== undefined ? { holder: verdict.holder } : {}), ...(verdict.expiresAt !== undefined ? { claimExpiresAt: verdict.expiresAt } : {}) };
174
+ const lapse = verdict.lapse;
175
+ return {
176
+ ...(isAnswerRecordClaimHolder(verdict.holder) ? { heldForAnswer: true } : verdict.holder !== undefined ? { holder: verdict.holder } : {}),
177
+ ...(lapse?.kind === "at" ? { claimExpiresAt: lapse.at } : lapse?.kind === "unreadable" ? { claimLapseUnreadable: true } : {}),
178
+ };
108
179
  }
180
+ export const CLAIM_REMAINING_UNREADABLE_NOTE = "the journal store answered a remaining time for the claim that does not read, so no time is named";
109
181
  export function claimLapseInstant(expiresAt) {
110
182
  if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt))
111
183
  return undefined;
@@ -171,84 +243,142 @@ export async function readWorkflowRunIn(store, id, scope, within) {
171
243
  return "unreadable";
172
244
  return got.value !== null && got.value.scope === scope ? got.value : null;
173
245
  }
174
- export async function workflowRunSuccessors(store, rootId, scope, within) {
246
+ export function isContinuationOf(a, b) {
247
+ if (resumedFromOf(b) !== a.id)
248
+ return false;
249
+ const named = b.resume?.fromCreationId;
250
+ return typeof named !== "string" || workflowRunCreationIdOf(a) === named;
251
+ }
252
+ const WORKFLOW_RUN_TREE = Symbol("WorkflowRunTree");
253
+ const mintTree = (root, records) => ({ root, records, [WORKFLOW_RUN_TREE]: true });
254
+ export function workflowRunTreeOfOne(run) {
255
+ return mintTree(run, [run]);
256
+ }
257
+ export function workflowRunInTree(tree, id) {
258
+ return tree.records.find((r) => r.id === id);
259
+ }
260
+ export function workflowRunsBelow(tree, id) {
261
+ const below = new Set([id]);
175
262
  const out = [];
176
- const seen = new Set([rootId]);
177
- let frontier = [rootId];
263
+ for (const r of tree.records) {
264
+ if (r === tree.root)
265
+ continue;
266
+ const up = resumedFromOf(r);
267
+ if (up !== undefined && below.has(up) && !below.has(r.id)) {
268
+ below.add(r.id);
269
+ out.push(r);
270
+ }
271
+ }
272
+ return out;
273
+ }
274
+ export function workflowRunChildrenIn(tree, id) {
275
+ return tree.records.filter((r) => r !== tree.root && resumedFromOf(r) === id);
276
+ }
277
+ export function workflowRunLineIn(tree, id) {
278
+ const line = [];
279
+ const byId = new Map(tree.records.map((r) => [r.id, r]));
280
+ let at = byId.get(id);
281
+ while (at !== undefined && line.length < tree.records.length) {
282
+ line.push(at.id);
283
+ if (at === tree.root)
284
+ break;
285
+ at = byId.get(resumedFromOf(at) ?? "");
286
+ }
287
+ return line;
288
+ }
289
+ export function workflowLineTailOf(tree, runId) {
290
+ let at = runId;
291
+ for (let n = 0; n <= tree.records.length; n++) {
292
+ const next = workflowRunChildrenIn(tree, at);
293
+ if (next.length === 0)
294
+ return { kind: "tail", runId: at };
295
+ if (next.length > 1) {
296
+ const below = workflowRunsBelow(tree, runId);
297
+ return { kind: "fork", leaves: below.filter((r) => workflowRunChildrenIn(tree, r.id).length === 0).map((r) => r.id) };
298
+ }
299
+ at = next[0].id;
300
+ }
301
+ return { kind: "tail", runId: at };
302
+ }
303
+ const FORK_LEAVES_NAMED_MAX = 4;
304
+ export function workflowLineForkReason(leaves) {
305
+ const shown = leaves.slice(0, FORK_LEAVES_NAMED_MAX).map((l) => `"${l}"`);
306
+ return `that run was already continued, and the runs that continued it split into ${leaves.length} lines, so which one to continue is not one answer. The last run of each line is ${shown.join(", ")}${leaves.length > shown.length ? `, and ${leaves.length - shown.length} more` : ""}: resume from the one you mean (resumeFromRunId set to it), or start the workflow again`;
307
+ }
308
+ export function readWorkflowRunTree(store, runId, scope) {
309
+ return readWorkflowRunTreeWithin(store, runId, scope, boundedStoreRead(WORKFLOW_STORE_WAIT_BOUND_MS));
310
+ }
311
+ export async function readWorkflowRunTreeWithin(store, runId, scope, within, self) {
312
+ const read = (id) => (self !== undefined && id === self.id ? Promise.resolve(self) : readWorkflowRunIn(store, id, scope, within));
313
+ const line = [];
314
+ let at = await read(runId);
315
+ if (at === "unreadable" || at === null)
316
+ return "unreadable";
317
+ for (;;) {
318
+ line.push(at);
319
+ const up = resumedFromOf(at);
320
+ if (up === undefined)
321
+ break;
322
+ if (line.some((r) => r.id === up))
323
+ return "unreadable";
324
+ const source = await read(up);
325
+ if (source === "unreadable")
326
+ return "unreadable";
327
+ if (source === null || !isContinuationOf(source, at))
328
+ break;
329
+ if (line.length >= WORKFLOW_TREE_RUNS_MAX)
330
+ return "over_bound";
331
+ at = source;
332
+ }
333
+ const root = line[line.length - 1];
334
+ const records = [root];
335
+ const seen = new Set([root.id]);
336
+ let frontier = [root];
178
337
  while (frontier.length > 0) {
179
338
  const next = [];
180
- for (const id of frontier) {
181
- const listed = await within(Promise.resolve().then(() => store.listByScope(scope, { resumedFrom: id })));
339
+ for (const parent of frontier) {
340
+ const listed = await within(Promise.resolve().then(() => store.listByScope(scope, { resumedFrom: parent.id })));
182
341
  if (!listed.ok)
183
342
  return "unreadable";
343
+ const ids = [];
184
344
  for (const s of listed.value) {
185
- if ("rowVerdict" in s || s.resumedFrom !== id)
186
- continue;
187
- const r = await readWorkflowRunIn(store, s.id, scope, within);
345
+ if ("rowVerdict" in s)
346
+ return "unreadable";
347
+ if (s.resumedFrom === parent.id)
348
+ ids.push(s.id);
349
+ }
350
+ if (self !== undefined && self.id !== root.id && resumedFromOf(self) === parent.id && !ids.includes(self.id))
351
+ ids.push(self.id);
352
+ for (const id of ids) {
353
+ const r = await read(id);
188
354
  if (r === "unreadable")
189
355
  return "unreadable";
190
- if (r === null || r.resume?.fromRunId !== id)
356
+ if (r === null || !isContinuationOf(parent, r))
191
357
  continue;
192
358
  if (seen.has(r.id))
193
- continue;
359
+ return "unreadable";
194
360
  seen.add(r.id);
195
- out.push(r);
196
- next.push(r.id);
197
- if (seen.size > WORKFLOW_TREE_RUNS_MAX)
361
+ records.push(r);
362
+ next.push(r);
363
+ if (records.length > WORKFLOW_TREE_RUNS_MAX)
198
364
  return "over_bound";
199
365
  }
200
366
  }
201
367
  frontier = next;
202
368
  }
203
- return out;
204
- }
205
- export async function readWorkflowRunChain(store, rootId, scope, within) {
206
- const root = await readWorkflowRunIn(store, rootId, scope, within);
207
- if (root === "unreadable" || root === null)
208
- return "unreadable";
209
- const successors = await workflowRunSuccessors(store, rootId, scope, within);
210
- return typeof successors === "string" ? successors : { root, successors };
211
- }
212
- export async function workflowTreeOf(store, runId, scope, within) {
213
- const walked = await workflowLineOf(store, runId, scope, within);
214
- return typeof walked === "string" ? walked : { root: walked.root, line: walked.line, recorded: walked.recorded };
215
- }
216
- async function workflowLineOf(store, runId, scope, within) {
217
- const line = [];
218
- const records = [];
219
- const seen = new Set();
220
- let id = runId;
221
- for (;;) {
222
- const r = await readWorkflowRunIn(store, id, scope, within);
223
- if (r === "unreadable")
224
- return "unreadable";
225
- if (r === null)
226
- return line.length === 0 ? { root: runId, line: [runId], recorded: false, records } : { root: line[line.length - 1], line, recorded: true, records };
227
- if (line.length >= WORKFLOW_TREE_RUNS_MAX)
228
- return "over_bound";
229
- line.push(id);
230
- records.push(r);
231
- seen.add(id);
232
- const up = r.resume?.fromRunId;
233
- if (up === undefined)
234
- return { root: id, line, recorded: true, records };
235
- if (seen.has(up))
369
+ for (const r of line) {
370
+ if (r === self)
371
+ continue;
372
+ const down = records.find((d) => d.id === r.id);
373
+ if (down === undefined || workflowRunCreationIdOf(down) !== workflowRunCreationIdOf(r))
236
374
  return "unreadable";
237
- id = up;
238
375
  }
376
+ return mintTree(root, records);
239
377
  }
240
- export async function otherWaitingLine(store, parkStore, fromRunId, scope, within, walked) {
241
- const tree = walked ?? (await workflowTreeOf(store, fromRunId, scope, within));
242
- if (typeof tree === "string")
243
- return { kind: tree };
244
- if (!tree.recorded)
245
- return { kind: "none", root: tree.root };
246
- const chain = await readWorkflowRunChain(store, tree.root, scope, within);
247
- if (typeof chain === "string")
248
- return { kind: chain };
249
- const records = [chain.root, ...chain.successors];
250
- const onLine = new Set(tree.line);
251
- const parentOf = new Map(records.map((r) => [r.id, r.resume?.fromRunId]));
378
+ export async function otherWaitingLine(tree, parkStore, fromRunId, within) {
379
+ const records = tree.records;
380
+ const onLine = new Set(workflowRunLineIn(tree, fromRunId));
381
+ const parentOf = new Map(records.map((r) => [r.id, r === tree.root ? undefined : resumedFromOf(r)]));
252
382
  const below = (id, top) => {
253
383
  for (let up = parentOf.get(id), n = 0; up !== undefined && n <= records.length; up = parentOf.get(up), n++)
254
384
  if (up === top)
@@ -262,20 +392,21 @@ export async function otherWaitingLine(store, parkStore, fromRunId, scope, withi
262
392
  for (const p of [...(r.parks ?? [])].sort((a, b) => own(a.token) - own(b.token))) {
263
393
  if (p.parkedBy !== r.id)
264
394
  continue;
265
- const holder = workflowParkHolderOf(p.token, records);
395
+ const holder = workflowParkHolderOf(p.token, tree);
266
396
  const counts = (holder.kind === "held" && holder.runId === r.id) || (holder.kind === "fork" && holder.runIds.includes(r.id) && (onLine.has(r.id) || !holder.runIds.some((id) => onLine.has(id))));
267
397
  if (!counts)
268
398
  continue;
269
399
  if (parkStore === undefined)
270
400
  return "unreadable";
271
- const read = await within(Promise.resolve().then(() => parkStore.get(p.token)));
272
- if (!read.ok)
401
+ const read = await within(Promise.resolve().then(() => parkStore.get(p.token)).then((row) => ({ row, state: parkCardStateOf(row, p.token) })));
402
+ if (!read.ok || read.value.state === "unread")
273
403
  return "unreadable";
274
- if (read.value === null || read.value.status !== "pending")
404
+ if (read.value.state !== "pending")
275
405
  continue;
406
+ const row = read.value.row;
276
407
  const label = r.agents.find((a) => a.parkedCheckpointToken === p.token)?.label;
277
- const checkpointId = read.value.checkpointId;
278
- return { runId: r.id, ...(label !== undefined ? { label } : {}), ...(typeof checkpointId === "string" ? { checkpointId } : {}), ...(read.value.gate.kind === "resource_limit" ? { yielded: true } : {}) };
408
+ const checkpointId = row.checkpointId;
409
+ return { runId: r.id, ...(label !== undefined ? { label } : {}), ...(typeof checkpointId === "string" ? { checkpointId } : {}), ...(row.gate.kind === "resource_limit" ? { yielded: true } : {}) };
279
410
  }
280
411
  return undefined;
281
412
  };
@@ -294,21 +425,21 @@ export async function otherWaitingLine(store, parkStore, fromRunId, scope, withi
294
425
  holding.push(w);
295
426
  }
296
427
  const heads = holding.filter((h) => !holding.some((o) => o !== h && below(o.runId, h.runId)));
297
- return heads.length === 0 ? { kind: "none", root: tree.root } : { kind: "waiting", root: tree.root, lines: heads };
428
+ return heads.length === 0 ? { kind: "none", root: tree.root.id } : { kind: "waiting", root: tree.root.id, lines: heads };
298
429
  }
299
- export function runThatDrove(records, callKey) {
300
- return records.find((r) => r.decisions?.some((d) => d.callKey === callKey && d.result === "driven") === true);
430
+ export function runThatDrove(records, token, callKey) {
431
+ return records.find((r) => (r.parks ?? []).some((p) => isObject(p) && p.token === token) && r.decisions?.some((d) => d.callKey === callKey && d.result === "driven") === true);
301
432
  }
302
- export function workflowParkWaitOf(token, runId, records, card) {
303
- const present = records.filter((r) => r !== null && r !== undefined);
433
+ export function workflowParkWaitOf(token, runId, tree, card) {
434
+ const present = tree.records;
304
435
  const own = present.find((r) => r.id === runId);
305
436
  const entry = own?.parks?.find((p) => isObject(p) && p.token === token && p.parkedBy === runId);
306
437
  if (own === undefined || entry === undefined)
307
438
  return { kind: "unknown", why: "chain_incomplete" };
308
- const drove = runThatDrove(present.filter((r) => r.id !== runId && (r.parks ?? []).some((p) => isObject(p) && p.token === token)), entry.callKey);
439
+ const drove = runThatDrove(present.filter((r) => r.id !== runId), token, entry.callKey);
309
440
  if (drove !== undefined)
310
441
  return { kind: "moved_on", runIds: [drove.id] };
311
- const holder = workflowParkHolderOf(token, present);
442
+ const holder = workflowParkHolderOf(token, tree);
312
443
  if (holder.kind === "held" && holder.runId !== runId)
313
444
  return { kind: "moved_on", runIds: [holder.runId] };
314
445
  if (holder.kind === "fork" && !holder.runIds.includes(runId))
@@ -317,30 +448,48 @@ export function workflowParkWaitOf(token, runId, records, card) {
317
448
  return { kind: "unknown", why: "chain_incomplete" };
318
449
  if (card === "unread")
319
450
  return { kind: "unknown", why: "card_unread" };
320
- return card === "pending" ? { kind: "waiting" } : { kind: "lapsed", card };
451
+ if (card !== "pending")
452
+ return { kind: "lapsed", card };
453
+ let top = -1;
454
+ let again = [];
455
+ for (const r of workflowRunsBelow(tree, runId)) {
456
+ for (const p of r.parks ?? []) {
457
+ if (!isObject(p) || p.callKey !== entry.callKey || p.token === token || p.parkedBy !== r.id || !Number.isSafeInteger(p.generation))
458
+ continue;
459
+ const g = p.generation;
460
+ if (g > top)
461
+ (top = g), (again = [r.id]);
462
+ else if (g === top && !again.includes(r.id))
463
+ again.push(r.id);
464
+ }
465
+ }
466
+ return again.length > 0 ? { kind: "moved_on", runIds: again.sort() } : { kind: "waiting" };
321
467
  }
322
468
  export async function readWorkflowParkWaits(seats, runId, scope) {
323
469
  const within = boundedStoreRead(WORKFLOW_STORE_WAIT_BOUND_MS);
324
- const chain = await readWorkflowRunChain(seats.runStore, runId, scope, within);
325
- if (typeof chain === "string")
326
- return chain;
327
- const records = [chain.root, ...chain.successors];
328
- const tokens = [...new Set((chain.root.parks ?? []).filter((p) => isObject(p) && p.parkedBy === runId && typeof p.token === "string").map((p) => p.token))];
470
+ const tree = await readWorkflowRunTreeWithin(seats.runStore, runId, scope, within);
471
+ if (typeof tree === "string")
472
+ return tree;
473
+ const own = workflowRunInTree(tree, runId);
474
+ const tokens = [...new Set((own.parks ?? []).filter((p) => isObject(p) && p.parkedBy === runId && typeof p.token === "string").map((p) => p.token))];
329
475
  const cardOf = async (token) => {
330
476
  const read = await within(Promise.resolve()
331
477
  .then(() => seats.checkpointStore.get(token))
332
- .then((row) => {
333
- if (row === null)
334
- return "absent";
335
- const status = row.status;
336
- return row.token === token && (status === "pending" || status === "resolved" || status === "expired") ? status : "unread";
337
- }));
478
+ .then((row) => ((s) => (s === "status_unknown" ? "unread" : s))(parkCardStateOf(row, token))));
338
479
  return read.ok ? read.value : "unread";
339
480
  };
340
481
  const cards = await Promise.all(tokens.map(cardOf));
341
- return new Map(tokens.map((token, i) => [token, workflowParkWaitOf(token, runId, records, cards[i])]));
482
+ return new Map(tokens.map((token, i) => [token, workflowParkWaitOf(token, runId, tree, cards[i])]));
342
483
  }
343
484
  const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
485
+ function parkCardStateOf(row, token) {
486
+ if (row === null)
487
+ return "absent";
488
+ if (row.token !== token)
489
+ return "unread";
490
+ const status = row.status;
491
+ return status === "pending" || status === "resolved" || status === "expired" ? status : "status_unknown";
492
+ }
344
493
  const decisionOf = (entry) => ({ token: entry.token, outcome: entry.outcome, decisionId: entry.decisionId, ...(entry.inheritedGate !== undefined ? { inheritedGate: entry.inheritedGate } : {}) });
345
494
  function readDecisions(raw) {
346
495
  const usable = [];
@@ -361,7 +510,7 @@ function readDecisions(raw) {
361
510
  const SETTLE_ATTEMPTS = 3;
362
511
  export function conditionOf(o) {
363
512
  const holder = holderDetailOf(o).holder;
364
- const said = [o.reason, o.code ?? null, o.changed ?? null, o.inputs ?? null, holder === undefined ? null : typeof holder === "string" ? holder : [...holder].sort(), o.why ?? null, o.rowReason ?? null, o.terminal === true];
513
+ const said = [o.reason, o.code ?? null, o.changed ?? null, o.inputs ?? null, holder === undefined ? null : typeof holder === "string" ? holder : [...holder].sort(), o.why ?? null, o.rowReason ?? null, o.terminal === true, ...(o.heldForAnswer === true ? ["held_for_answer"] : [])];
365
514
  return createHash("sha256").update(JSON.stringify(said)).digest("hex").slice(0, 32);
366
515
  }
367
516
  function placeMark(kept, m) {
@@ -385,25 +534,57 @@ function placeMark(kept, m) {
385
534
  export function createWorkflowParkAdopter(seats) {
386
535
  const within = boundedStoreRead(seats.waitBoundMs);
387
536
  const readRun = async (id, scope) => (seats.store === undefined ? "unreadable" : readWorkflowRunIn(seats.store, id, scope, within));
388
- const successorsOf = async (x, scope) => (seats.store === undefined ? "unreadable" : workflowRunSuccessors(seats.store, x.id, scope, within));
389
- const settleOn = async (held, scope, all) => {
537
+ const readTree = async (id, scope) => (seats.store === undefined ? "unreadable" : readWorkflowRunTreeWithin(seats.store, id, scope, within));
538
+ const settleOn = async (tree, scope, all, named) => {
390
539
  const others = new Set();
391
540
  const store = seats.store;
392
541
  if (store === undefined)
393
542
  return others;
543
+ let marks = all.filter((m, i) => all.findIndex((o) => o.token === m.token && o.decisionId === m.decisionId) === i);
544
+ let judged = tree;
545
+ for (let judgment = 0; judgment < 2 && marks.length > 0; judgment++) {
546
+ const byHolder = new Map();
547
+ for (const m of marks) {
548
+ const holder = workflowParkHolderOf(m.token, judged);
549
+ const home = holder.kind === "held" ? holder.runId : holder.kind === "fork" && holder.runIds.includes(named) ? named : undefined;
550
+ if (home !== undefined)
551
+ byHolder.set(home, [...(byHolder.get(home) ?? []), m]);
552
+ }
553
+ const moved = [];
554
+ for (const [holderId, ofHolder] of byHolder) {
555
+ const record = workflowRunInTree(judged, holderId);
556
+ if (record !== undefined)
557
+ moved.push(...(await settleOnHolder(store, record, scope, ofHolder, others)));
558
+ }
559
+ if (moved.length === 0 || judgment === 1)
560
+ break;
561
+ const again = await readTree(tree.root.id, scope);
562
+ if (typeof again === "string")
563
+ break;
564
+ judged = again;
565
+ marks = moved;
566
+ }
567
+ return others;
568
+ };
569
+ const settleOnHolder = async (store, held, scope, marks, others) => {
394
570
  const runId = held.id;
395
- const marks = all.filter((m, i) => all.findIndex((o) => o.token === m.token && o.decisionId === m.decisionId) === i);
396
571
  let mineMayHaveLanded = false;
572
+ const creationId = workflowRunCreationIdOf(held);
397
573
  for (let attempt = 0; attempt < SETTLE_ATTEMPTS; attempt++) {
398
- const now = attempt === 0 ? held : await readRun(runId, scope);
399
- if (now === "unreadable" || now === null || now.status === "running")
400
- return others;
574
+ const now = await readRun(runId, scope);
575
+ if (now === "unreadable" || now === null || now.status === "running" || workflowRunCreationIdOf(now) !== creationId)
576
+ return [];
401
577
  const next = structuredClone(now);
402
578
  let added = false;
579
+ const moved = [];
403
580
  for (const m of marks) {
404
581
  const entry = next.parks?.find((p) => isObject(p) && p.token === m.token && p.parkedBy === runId);
405
582
  if (entry === undefined)
406
583
  continue;
584
+ if (entry.passedTo !== undefined) {
585
+ moved.push(m);
586
+ continue;
587
+ }
407
588
  const placed = placeMark(Array.isArray(entry.settledDecisions) ? entry.settledDecisions.filter((s) => isObject(s)) : [], m);
408
589
  if (placed === "recorded") {
409
590
  if (!mineMayHaveLanded)
@@ -416,112 +597,103 @@ export function createWorkflowParkAdopter(seats) {
416
597
  added = true;
417
598
  }
418
599
  if (!added)
419
- return others;
420
- const won = await within(Promise.resolve().then(() => store.update(runId, scope, next, { rev: now.rev ?? 0 }, { cause: "park_decision_settled" })));
600
+ return moved;
601
+ const won = await within(Promise.resolve().then(() => store.update(runId, scope, next, { rev: now.rev ?? 0, creationId }, { cause: "park_decision_settled" })));
421
602
  if (won.ok && won.value)
422
- return others;
603
+ return moved;
423
604
  if (!won.ok)
424
605
  mineMayHaveLanded = true;
425
606
  }
426
- return others;
607
+ return [];
427
608
  };
428
609
  const cardOf = async (parkStore, token) => {
429
610
  if (parkStore === undefined)
430
- return { kind: "unread" };
431
- const read = await within(Promise.resolve().then(() => parkStore.get(token)));
611
+ return { state: "unread" };
612
+ const read = await within(Promise.resolve().then(() => parkStore.get(token)).then((row) => ({ row, state: parkCardStateOf(row, token) })));
432
613
  if (!read.ok)
433
- return { kind: "unread" };
434
- return read.value === null || read.value.status !== "pending" ? { kind: "gone" } : { kind: "pending", row: read.value };
614
+ return { state: "unread" };
615
+ return read.value.state === "pending" ? { state: "pending", row: read.value.row } : { state: read.value.state };
435
616
  };
436
- const judgeCards = async (x, records, parkStore, entries, unused, settle, quiet) => {
617
+ const judgeCards = async (x, tree, parkStore, entries, settle, quiet) => {
618
+ const records = tree.records;
437
619
  const carried = [];
438
- let first;
620
+ const own = [];
621
+ const ownOf = (entry, reason, more = {}) => void own.push({ kind: "unused", runId: x.id, decisionIds: [entry.decisionId], reason, ...more });
439
622
  let unresumable;
440
623
  for (const entry of entries) {
441
624
  const card = await cardOf(parkStore, entry.token);
442
- if (card.kind === "unread") {
443
- first ??= unused("record_unreadable");
625
+ const was = workflowParkDecisionOf(entry.token, entry.decisionId, tree, card.state === "status_unknown" ? "unread" : card.state);
626
+ if (was.kind === "spent" && was.by === "mark")
627
+ quiet.add(entry.decisionId);
628
+ if (card.state === "unread") {
629
+ ownOf(entry, "record_unreadable", { cardUnread: true });
444
630
  continue;
445
631
  }
446
632
  const key = x.parks?.find((p) => p.token === entry.token);
447
- if (card.kind === "gone") {
448
- const continuedAs = key === undefined ? undefined : runThatDrove(records, key.callKey)?.id;
449
- first ??= unused("not_pending", continuedAs !== undefined ? { continuedAs } : {});
633
+ if (card.state !== "pending") {
634
+ const continuedAs = key === undefined ? undefined : runThatDrove(records, entry.token, key.callKey)?.id;
635
+ ownOf(entry, "not_pending", continuedAs !== undefined ? { continuedAs } : {});
450
636
  continue;
451
637
  }
452
- const holder = workflowParkHolderOf(entry.token, records);
453
- if (holder.kind !== "held" || holder.runId !== x.id) {
454
- first ??= unused("not_holder", holder.kind === "held" ? { holder: holder.runId } : holder.kind === "fork" ? { holder: holder.runIds } : {});
638
+ const holder = workflowParkHolderOf(entry.token, tree);
639
+ if (holder.kind === "held" ? holder.runId !== x.id : holder.kind === "fork" ? !holder.runIds.includes(x.id) : true) {
640
+ ownOf(entry, "not_holder", holder.kind === "held" ? { holder: holder.runId } : holder.kind === "fork" ? { holder: holder.runIds } : {});
455
641
  continue;
456
642
  }
457
643
  const row = judgeCheckpointRow(card.row);
458
644
  if (row.kind !== "ok") {
459
- unresumable ??= unused("card_unresumable", { code: row.code, ...(row.reason !== undefined ? { rowReason: row.reason } : {}), rowSentence: row.sentence, ...(row.terminal === true ? { terminal: true } : {}) });
460
- first ??= unresumable;
645
+ const facts = { code: row.code, ...(row.reason !== undefined ? { rowReason: row.reason } : {}), rowSentence: row.sentence };
646
+ unresumable ??= facts;
647
+ ownOf(entry, "card_unresumable", { ...facts, ...(row.terminal === true ? { terminal: true } : {}) });
461
648
  if (row.terminal === true)
462
649
  settle(entry, "card_unresumable", row.code);
463
650
  continue;
464
651
  }
465
- const was = workflowParkDecisionOf(entry.token, entry.decisionId, records);
466
652
  if (was.kind === "spent") {
467
- if (was.reason !== "decision_spent" || quiet.has(entry.decisionId))
468
- quiet.add(entry.decisionId);
469
- else {
470
- first ??= unused("decision_spent", was.code !== undefined ? { code: was.code } : {});
471
- settle(entry, "decision_spent", was.code);
472
- }
653
+ if (quiet.has(entry.decisionId))
654
+ continue;
655
+ ownOf(entry, "decision_spent", was.code !== undefined ? { code: was.code } : {});
656
+ settle(entry, "decision_spent", was.code);
473
657
  continue;
474
658
  }
475
659
  carried.push({ entry, state: card.row.state });
476
660
  }
477
- return { carried, ...(first !== undefined ? { first } : {}), ...(unresumable !== undefined ? { unresumable } : {}) };
661
+ return { carried, own, ...(unresumable !== undefined ? { unresumable } : {}) };
478
662
  };
479
- const adoptOne = async (runId, entries, leg, quiet, approvedCall) => {
480
- const unused = (reason, more = {}) => ({ kind: "unused", runId, decisionIds: entries.map((e) => e.decisionId), reason, ...more });
663
+ const adoptOne = async (runId, entries, leg, quiet, asides, approvedCall) => {
664
+ const own = [];
481
665
  const toolCallId = leg.mintCallId();
482
666
  const ctx = leg.ctxOf(toolCallId);
483
667
  const scope = seats.scopeOf(ctx);
484
- const x = await readRun(runId, scope);
668
+ const tree = await readTree(runId, scope);
669
+ const x = typeof tree === "string" ? tree : workflowRunInTree(tree, runId);
485
670
  const parkStore = seats.parkStoreOf(ctx);
486
671
  const cardsFirst = async (reason) => {
487
- let first;
488
- const waiting = [];
489
672
  for (const entry of entries) {
490
673
  const card = await cardOf(parkStore, entry.token);
491
- if (card.kind === "pending")
492
- waiting.push(entry.decisionId);
493
- else
494
- first ??= unused(card.kind === "gone" ? "not_pending" : "record_unreadable");
674
+ own.push({ kind: "unused", runId, decisionIds: [entry.decisionId], ...(card.state === "pending" ? { reason } : card.state === "unread" ? { reason: "record_unreadable", cardUnread: true } : { reason: "not_pending" }) });
495
675
  }
496
- return waiting.length > 0 ? { kind: "unused", runId, decisionIds: waiting, reason } : (first ?? unused(reason));
676
+ for (const o of groupedByAnswer(own))
677
+ asides.push(o);
678
+ return "settled_before";
497
679
  };
498
- if (x === "unreadable" || x === null || x.resumeAdmissionIncomplete === true)
680
+ if (typeof tree === "string" || typeof x === "string" || x.resumeAdmissionIncomplete === true)
499
681
  return cardsFirst("record_unreadable");
500
- if (approvedCall === undefined)
501
- for (const e of entries)
502
- if (settledMarkOf(e.token, e.decisionId, [x]) !== undefined)
503
- quiet.add(e.decisionId);
504
- if (entries.every((e) => quiet.has(e.decisionId)))
505
- return "settled_before";
506
682
  if (x.status === "running")
507
683
  return cardsFirst("run_not_ended");
508
- const successors = await successorsOf(x, scope);
509
- if (typeof successors === "string")
510
- return cardsFirst("record_unreadable");
511
- const records = [x, ...successors];
512
684
  const settling = [];
513
- let lineRecords = [];
514
685
  const settle = (entry, reason, code) => {
515
686
  if (approvedCall === undefined && !quiet.has(entry.decisionId))
516
687
  settling.push({ token: entry.token, decisionId: entry.decisionId, reason, ...(code !== undefined ? { code } : {}) });
517
688
  };
689
+ let judgedTree = tree;
518
690
  const told = async (o) => {
519
691
  if (o.kind !== "unused" || approvedCall !== undefined)
520
692
  return o;
521
693
  if (settlesDecision(o)) {
522
694
  const marks = settling.filter((m) => m.reason === o.reason && m.code === o.code && o.decisionIds.includes(m.decisionId));
523
695
  if (marks.length > 0)
524
- for (const id of await settleOn(x, scope, marks))
696
+ for (const id of await settleOn(judgedTree, scope, marks, runId))
525
697
  quiet.add(id);
526
698
  return o;
527
699
  }
@@ -533,151 +705,194 @@ export function createWorkflowParkAdopter(seats) {
533
705
  const entry = entries.find((e) => e.decisionId === id);
534
706
  if (entry === undefined || quiet.has(id))
535
707
  continue;
536
- if (blockedMarkOf(entry.token, id, [...records, ...lineRecords])?.condition === condition) {
537
- quiet.add(id);
538
- continue;
539
- }
540
708
  marks.push({ token: entry.token, decisionId: id, reason: o.reason, ...(o.code !== undefined ? { code: o.code } : {}), ...(o.inputs !== undefined ? { inputs: o.inputs } : {}), condition });
541
709
  }
542
710
  if (marks.length > 0)
543
- for (const id of await settleOn(x, scope, marks))
711
+ for (const id of await settleOn(judgedTree, scope, marks, runId))
544
712
  quiet.add(id);
545
713
  return o;
546
714
  };
547
- const judged = await judgeCards(x, records, parkStore, entries, unused, settle, quiet);
548
- if (judged.unresumable !== undefined)
549
- return told(judged.unresumable);
550
- if (judged.carried.length === 0)
551
- return told(judged.first ?? unused("record_unreadable"));
552
- const walked = seats.store === undefined ? "unreadable" : await workflowLineOf(seats.store, x.id, scope, within);
553
- const unrecordedOn = (w, of) => {
554
- if (typeof w === "string")
555
- return of;
556
- lineRecords = w.records;
557
- return of.filter((c) => {
558
- const recorded = workflowParkDecisionOf(c.entry.token, c.entry.decisionId, w.records).kind === "spent";
559
- if (recorded)
560
- quiet.add(c.entry.decisionId);
561
- return !recorded;
562
- });
563
- };
564
- let carried = unrecordedOn(walked, judged.carried);
565
- if (carried.length === 0)
566
- return judged.first !== undefined ? told(judged.first) : "settled_before";
567
- const carriedIdsOf = () => carried.map((c) => c.entry.decisionId);
568
- const unusedCarried = (reason, more = {}) => ({ kind: "unused", runId, decisionIds: carriedIdsOf(), reason, ...more });
569
- const settledCarried = (reason, more = {}) => {
570
- for (const { entry } of carried)
571
- settle(entry, reason, more.code);
572
- return told(unusedCarried(reason, more));
573
- };
574
- const lineOf = async (walked) => {
575
- const line = seats.store === undefined ? { kind: "unreadable" } : await otherWaitingLine(seats.store, parkStore, x.id, scope, within, walked);
576
- return line.kind === "unreadable" || line.kind === "over_bound" ? unusedCarried("record_unreadable") : line.kind === "waiting" ? unusedCarried("waiting_elsewhere", { waiting: line.lines }) : line.root;
577
- };
578
- const treeOf = (w) => (typeof w === "string" ? w : { root: w.root, line: w.line, recorded: w.recorded });
579
- const claimKey = await lineOf(treeOf(walked));
580
- if (typeof claimKey !== "string")
581
- return told(claimKey);
582
- if (x.errorCode !== WORKFLOW_AGENT_PARKED_ERROR_CODE)
583
- return unusedCarried("record_unreadable");
584
- let launch;
585
- if (journalKeepsLaunches(seats.journalStore)) {
586
- const launchRead = await readKeptLaunch(seats.journalStore, runId, scope, seats.waitBoundMs);
587
- if (launchRead.kind === "failed") {
588
- if (launchRead.cause !== undefined)
589
- seats.reportStoreFault?.(`the launch record of workflow run ${JSON.stringify(runId)} could not be read by the engine's continuation`, launchRead.cause.err);
715
+ const answer = await (async () => {
716
+ const judged = await judgeCards(x, tree, parkStore, entries, settle, quiet);
717
+ own.push(...judged.own);
718
+ if (judged.carried.length === 0)
719
+ return "settled_before";
720
+ let carried = judged.carried;
721
+ const carriedIdsOf = () => carried.map((c) => c.entry.decisionId);
722
+ const unusedCarried = (reason, more = {}) => ({ kind: "unused", runId, decisionIds: carriedIdsOf(), reason, ...more });
723
+ if (judged.unresumable !== undefined)
724
+ return told(unusedCarried("card_unresumable", { ...judged.unresumable, otherCard: true }));
725
+ const settledCarried = (reason, more = {}) => {
726
+ for (const { entry } of carried)
727
+ settle(entry, reason, more.code);
728
+ return told(unusedCarried(reason, more));
729
+ };
730
+ const lineOf = async (over) => {
731
+ const line = await otherWaitingLine(over, parkStore, x.id, within);
732
+ return line.kind === "unreadable" ? unusedCarried("record_unreadable") : line.kind === "waiting" ? unusedCarried("waiting_elsewhere", { waiting: line.lines }) : line.root;
733
+ };
734
+ const claimKey = await lineOf(tree);
735
+ if (typeof claimKey !== "string")
736
+ return told(claimKey);
737
+ if (x.errorCode !== WORKFLOW_AGENT_PARKED_ERROR_CODE)
590
738
  return unusedCarried("record_unreadable");
739
+ let launch;
740
+ if (journalKeepsLaunches(seats.journalStore)) {
741
+ const launchRead = await readKeptLaunch(seats.journalStore, runId, scope, seats.waitBoundMs);
742
+ if (launchRead.kind === "failed") {
743
+ if (launchRead.cause !== undefined)
744
+ seats.reportStoreFault?.(`the launch record of workflow run ${JSON.stringify(runId)} could not be read by the engine's continuation`, launchRead.cause.err);
745
+ return unusedCarried("record_unreadable");
746
+ }
747
+ if (launchRead.kind === "defect")
748
+ return settledCarried("launch_unreadable", { code: launchRead.member });
749
+ if (launchRead.kind === "record")
750
+ launch = launchRead.record;
591
751
  }
592
- if (launchRead.kind === "defect")
593
- return settledCarried("launch_unreadable", { code: launchRead.member });
594
- if (launchRead.kind === "record")
595
- launch = launchRead.record;
596
- }
597
- if (launch !== undefined || x.hostFoldDigest !== undefined) {
598
- let fold;
599
- try {
600
- fold = seats.hostFoldDigest(ctx, launch);
752
+ if (launch !== undefined || x.hostFoldDigest !== undefined) {
753
+ let fold;
754
+ try {
755
+ fold = seats.hostFoldDigest(ctx, launch);
756
+ }
757
+ catch {
758
+ fold = undefined;
759
+ }
760
+ if (fold === undefined || x.hostFoldDigest === undefined || fold !== x.hostFoldDigest) {
761
+ const inputs = fold === undefined || x.hostFoldDigest === undefined ? undefined : hostFoldChanges(x.hostFoldDigest, fold);
762
+ return told(unusedCarried("host_changed", { changed: "identity", ...(inputs !== undefined && inputs.length > 0 ? { inputs } : {}) }));
763
+ }
601
764
  }
602
- catch {
603
- fold = undefined;
765
+ for (const { entry, state } of carried) {
766
+ const verdict = parentConstraintChainVerdict(state, entry.inheritedGate?.parentConstraints ?? seats.chainToHand(ctx));
767
+ if (verdict !== undefined)
768
+ return told(unusedCarried("host_changed", { changed: "parent_chain", code: verdict.code }));
604
769
  }
605
- if (fold === undefined || x.hostFoldDigest === undefined || fold !== x.hostFoldDigest) {
606
- const inputs = fold === undefined || x.hostFoldDigest === undefined ? undefined : hostFoldChanges(x.hostFoldDigest, fold);
607
- return told(unusedCarried("host_changed", { changed: "identity", ...(inputs !== undefined && inputs.length > 0 ? { inputs } : {}) }));
770
+ if (approvedCall !== undefined) {
771
+ seats.holdForCall(runId, approvedCall, { decisions: carried.map(({ entry }) => decisionOf(entry)) });
772
+ return "carried";
608
773
  }
609
- }
610
- for (const { entry, state } of carried) {
611
- const verdict = parentConstraintChainVerdict(state, entry.inheritedGate?.parentConstraints ?? seats.chainToHand(ctx));
612
- if (verdict !== undefined)
613
- return told(unusedCarried("host_changed", { changed: "parent_chain", code: verdict.code }));
614
- }
615
- if (approvedCall !== undefined) {
616
- seats.holdForCall(runId, approvedCall, { decisions: carried.map(({ entry }) => decisionOf(entry)) });
617
- return "carried";
618
- }
619
- if (launch === undefined)
620
- return told(unusedCarried("launch_unrecorded"));
621
- const name = launch.callArgs.name;
622
- const input = { script: launch.script, ...(launch.effectiveArgs !== undefined ? { args: launch.effectiveArgs } : {}), ...(typeof name === "string" ? { name } : {}), resumeFromRunId: runId };
623
- const byPerson = carried.every((c) => isObject(c.entry.outcome) && isObject(c.entry.outcome.hostDecision) && c.entry.outcome.hostDecision.decidedBy === "person");
624
- if (leg.gate !== undefined) {
625
- let judged;
626
- try {
627
- judged = await leg.gate.judge({ toolCallId, toolName: seats.toolName, input }, byPerson ? "person" : "none");
774
+ if (launch === undefined)
775
+ return told(unusedCarried("launch_unrecorded"));
776
+ let superseded;
777
+ const rejudge = async () => {
778
+ const now = await readTree(runId, scope);
779
+ const xNow = typeof now === "string" ? undefined : workflowRunInTree(now, runId);
780
+ if (typeof now === "string" || xNow === undefined || xNow.status === "running" || xNow.resumeAdmissionIncomplete === true) {
781
+ superseded = unusedCarried("record_unreadable");
782
+ return false;
783
+ }
784
+ judgedTree = now;
785
+ const again = await judgeCards(xNow, now, parkStore, carried.map((c) => c.entry), settle, quiet);
786
+ own.push(...again.own);
787
+ const lost = carried.filter((c) => !again.carried.some((a) => a.entry === c.entry) && !quiet.has(c.entry.decisionId)).length;
788
+ carried = again.carried;
789
+ if (carried.length === 0)
790
+ superseded = "settled_before";
791
+ return { lost, ...(again.unresumable !== undefined ? { unresumable: again.unresumable } : {}) };
792
+ };
793
+ const confirm = async () => {
794
+ const again = await rejudge();
795
+ if (again === false || carried.length === 0)
796
+ return false;
797
+ if (again.unresumable !== undefined || again.lost > 0) {
798
+ superseded = again.unresumable !== undefined ? unusedCarried("card_unresumable", { ...again.unresumable, otherCard: true }) : unusedCarried("record_unreadable");
799
+ return false;
800
+ }
801
+ const line = await lineOf(judgedTree);
802
+ if (typeof line !== "string")
803
+ superseded = line;
804
+ else if (line !== claimKey)
805
+ superseded = unusedCarried("record_unreadable");
806
+ return superseded === undefined ? carried.map(({ entry }) => decisionOf(entry)) : false;
807
+ };
808
+ const deniedUnderClaim = async (layer) => {
809
+ if ((await rejudge()) === false || carried.length === 0)
810
+ return undefined;
811
+ if (judgedTree.root.id !== claimKey) {
812
+ superseded = unusedCarried("record_unreadable");
813
+ return undefined;
814
+ }
815
+ const o = await settledCarried("denied", { code: layer, explicit: true });
816
+ if (o.kind !== "unused")
817
+ return o;
818
+ const after = await readTree(runId, scope);
819
+ const stands = (id) => {
820
+ const entry = carried.find((c) => c.entry.decisionId === id)?.entry;
821
+ if (typeof after === "string" || entry === undefined)
822
+ return false;
823
+ const was = workflowParkDecisionOf(entry.token, id, after);
824
+ return was.kind === "spent" && was.by === "mark" && was.reason === "denied" && was.code === layer;
825
+ };
826
+ const unrecorded = o.decisionIds.filter((id) => !stands(id));
827
+ if (unrecorded.length === 0)
828
+ return o;
829
+ own.push({ kind: "unused", runId, decisionIds: unrecorded, reason: "record_unreadable", answerUnrecorded: true });
830
+ const recorded = o.decisionIds.filter((id) => !unrecorded.includes(id));
831
+ return recorded.length > 0 ? { ...o, decisionIds: recorded } : "settled_before";
832
+ };
833
+ const supersededAnswer = () => (superseded === "settled_before" ? superseded : told(superseded ?? unusedCarried("record_unreadable")));
834
+ const name = launch.callArgs.name;
835
+ const input = { script: launch.script, ...(launch.effectiveArgs !== undefined ? { args: launch.effectiveArgs } : {}), ...(typeof name === "string" ? { name } : {}), resumeFromRunId: runId };
836
+ const byPerson = carried.every((c) => isObject(c.entry.outcome) && isObject(c.entry.outcome.hostDecision) && c.entry.outcome.hostDecision.decidedBy === "person");
837
+ if (leg.gate !== undefined) {
838
+ let judged;
839
+ try {
840
+ judged = await leg.gate.judge({ toolCallId, toolName: seats.toolName, input }, byPerson ? "person" : "none");
841
+ }
842
+ catch {
843
+ judged = { kind: "ask_unanswerable" };
844
+ }
845
+ if (judged.kind === "denied" && judged.explicit) {
846
+ const layer = judged.layer;
847
+ const under = await seats.underClaim(claimKey, scope, () => deniedUnderClaim(layer));
848
+ if ("claimHeld" in under)
849
+ return unusedCarried("continuing_elsewhere", { ...under.claimHeld, answerUnrecorded: true });
850
+ if ("refused" in under)
851
+ return unusedCarried("record_unreadable", { answerUnrecorded: true });
852
+ return under.value ?? supersededAnswer();
853
+ }
854
+ if (judged.kind === "denied")
855
+ return settledCarried("denied", { code: judged.layer });
856
+ if (judged.kind === "ask_unanswerable")
857
+ return told(unusedCarried("ask_unanswerable"));
858
+ if (judged.kind === "call_changed")
859
+ return told(unusedCarried("call_changed"));
628
860
  }
629
- catch {
630
- judged = { kind: "ask_unanswerable" };
861
+ let started;
862
+ try {
863
+ started = await seats.launch({ fromRunId: runId, launch, decisions: carried.map(({ entry }) => decisionOf(entry)), claimKey }, ctx, confirm);
631
864
  }
632
- if (judged.kind === "denied")
633
- return settledCarried("denied", { code: judged.layer, ...(judged.explicit ? { explicit: true } : {}) });
634
- if (judged.kind === "ask_unanswerable")
635
- return told(unusedCarried("ask_unanswerable"));
636
- }
637
- let superseded;
638
- const confirm = async () => {
639
- const lineNow = seats.store === undefined ? "unreadable" : await workflowLineOf(seats.store, x.id, scope, within);
640
- carried = unrecordedOn(lineNow, carried);
641
- if (carried.length === 0) {
642
- superseded = "settled_before";
643
- return false;
865
+ catch (e) {
866
+ started = { refused: `the continuation's launch threw ${storeErrorClassOf(e)}` };
867
+ seats.reportStoreFault?.(`the continuation's launch of workflow run ${JSON.stringify(runId)} threw`, e);
644
868
  }
645
- const now = await successorsOf(x, scope);
646
- const again = typeof now === "string" ? undefined : await judgeCards(x, [x, ...now], parkStore, carried.map((c) => c.entry), unusedCarried, settle, quiet);
647
- superseded = again === undefined ? unusedCarried("record_unreadable") : (again.unresumable ?? (again.carried.length < carried.length ? (again.first ?? unusedCarried("record_unreadable")) : undefined));
648
- if (superseded !== undefined)
649
- return false;
650
- const line = await lineOf(treeOf(lineNow));
651
- if (typeof line !== "string")
652
- superseded = line;
653
- return superseded === undefined ? carried.map(({ entry }) => decisionOf(entry)) : false;
654
- };
655
- let started;
656
- try {
657
- started = await seats.launch({ fromRunId: runId, launch, decisions: carried.map(({ entry }) => decisionOf(entry)), claimKey }, ctx, confirm);
658
- }
659
- catch (e) {
660
- started = { refused: `the continuation's launch threw ${storeErrorClassOf(e)}` };
661
- seats.reportStoreFault?.(`the continuation's launch of workflow run ${JSON.stringify(runId)} threw`, e);
662
- }
663
- if ("refused" in started)
664
- return told(unusedCarried("launch_refused", { why: neutral(started.refused, WHY_ECHO_MAX) }));
665
- if ("claimHeld" in started)
666
- return told(unusedCarried("continuing_elsewhere", started.claimHeld));
667
- if ("superseded" in started)
668
- return superseded === "settled_before" ? superseded : told(superseded ?? unusedCarried("record_unreadable"));
669
- const stepDenied = carried.some((c) => isObject(c.entry.outcome) && c.entry.outcome.decision === "deny");
670
- return { kind: "started", runId, decisionIds: carriedIdsOf(), continuedAs: started.runId, ...(stepDenied ? { stepDenied: true } : {}) };
869
+ if ("refused" in started)
870
+ return told(unusedCarried("launch_refused", { why: neutral(started.refused, WHY_ECHO_MAX) }));
871
+ if ("claimHeld" in started)
872
+ return told(unusedCarried("continuing_elsewhere", started.claimHeld));
873
+ if ("superseded" in started)
874
+ return supersededAnswer();
875
+ const stepDenied = carried.some((c) => isObject(c.entry.outcome) && c.entry.outcome.decision === "deny");
876
+ return { kind: "started", runId, decisionIds: carriedIdsOf(), continuedAs: started.runId, ...(stepDenied ? { stepDenied: true } : {}) };
877
+ })();
878
+ for (const o of groupedByAnswer(own))
879
+ asides.push(await told(o));
880
+ return answer;
671
881
  };
672
882
  return async (leg) => {
673
883
  const { usable, unreadable } = readDecisions(seats.decisions);
674
884
  const out = [];
675
885
  const byRun = new Map();
676
- for (const e of usable)
677
- byRun.set(e.runId, [...(byRun.get(e.runId) ?? []), e]);
886
+ for (const e of usable) {
887
+ const was = byRun.get(e.runId) ?? [];
888
+ if (!was.some((s) => s.token === e.token && s.decisionId === e.decisionId))
889
+ byRun.set(e.runId, [...was, e]);
890
+ }
678
891
  const unreadableRuns = new Map();
679
- for (const u of unreadable)
680
- unreadableRuns.set(u.runId, [...(unreadableRuns.get(u.runId) ?? []), ...(u.decisionId !== undefined ? [u.decisionId] : [])]);
892
+ for (const u of unreadable) {
893
+ const was = unreadableRuns.get(u.runId) ?? [];
894
+ unreadableRuns.set(u.runId, u.decisionId !== undefined && !was.includes(u.decisionId) ? [...was, u.decisionId] : was);
895
+ }
681
896
  for (const [runId, ids] of unreadableRuns)
682
897
  if (!byRun.has(runId))
683
898
  out.push({ kind: "unused", runId, decisionIds: ids, reason: "entry_unreadable" });
@@ -686,8 +901,10 @@ export function createWorkflowParkAdopter(seats) {
686
901
  if (resumed !== undefined) {
687
902
  if (resumed.approved) {
688
903
  try {
689
- const adopted = await adoptOne(runId, entries, leg, new Set(), resumed.toolCallId);
690
- const refusal = adopted === "carried" || adopted === "settled_before" ? undefined : resumedCallRefusalOf(adopted);
904
+ const own = [];
905
+ const adopted = await adoptOne(runId, entries, leg, new Set(), own, resumed.toolCallId);
906
+ const answered = own.find((o) => o.kind === "unused" && o.reason === "card_unresumable") ?? (adopted === "settled_before" ? own[0] : adopted);
907
+ const refusal = answered === undefined || answered === "carried" ? undefined : resumedCallRefusalOf(answered);
691
908
  if (refusal !== undefined)
692
909
  seats.holdForCall(runId, resumed.toolCallId, { refusal });
693
910
  }
@@ -698,14 +915,15 @@ export function createWorkflowParkAdopter(seats) {
698
915
  }
699
916
  try {
700
917
  const quiet = new Set();
701
- const adopted = await adoptOne(runId, entries, leg, quiet);
702
- if (adopted === "carried" || adopted === "settled_before")
703
- continue;
704
- const kept = adopted.kind === "unused" ? adopted.decisionIds.filter((id) => !quiet.has(id)) : [];
705
- if (adopted.kind !== "unused" || kept.length === adopted.decisionIds.length)
706
- out.push(adopted);
707
- else if (kept.length > 0)
708
- out.push({ ...adopted, decisionIds: kept });
918
+ const asides = [];
919
+ const adopted = await adoptOne(runId, entries, leg, quiet, asides);
920
+ for (const o of adopted === "carried" || adopted === "settled_before" ? asides : [adopted, ...asides]) {
921
+ const kept = o.kind === "unused" ? o.decisionIds.filter((id) => !quiet.has(id)) : [];
922
+ if (o.kind !== "unused" || kept.length === o.decisionIds.length)
923
+ out.push(o);
924
+ else if (kept.length > 0)
925
+ out.push({ ...o, decisionIds: kept });
926
+ }
709
927
  }
710
928
  catch {
711
929
  out.push({ kind: "unused", runId, decisionIds: entries.map((e) => e.decisionId), reason: "record_unreadable" });
@@ -739,6 +957,10 @@ export function workflowParkUnusedSentence(o) {
739
957
  case "entry_unreadable":
740
958
  return `the deployment handed the decision over without its decision id or its outcome. ${waiting}; decide it again, and report the defect to the deployment if this repeats`;
741
959
  case "record_unreadable":
960
+ if (o.cardUnread === true)
961
+ return `the approval card could not be read right now, so whether it is still waiting is not known; the next run of this session tries again`;
962
+ if (o.answerUnrecorded === true)
963
+ return `a person answered no when asked to continue the workflow, and the engine could not confirm that it recorded that answer, so nothing was started and the same decision may be asked about again. If the approval card is still waiting, decide it again (a new decision) to continue the run, or start the workflow again`;
742
964
  return `the workflow run's record could not be read right now, or the run did not stop on an approval. ${waiting}; the next run of this session tries again. If the answer stays the same, the workflow may have more runs than the ${WORKFLOW_TREE_RUNS_MAX} the engine reads to judge a continuation (every continuation of a run adds one): then start the workflow again — it runs from its first step`;
743
965
  case "run_not_ended":
744
966
  return `the run that holds the approval card has not written down how it ended — its record still says it is running — so the engine cannot continue it from this decision and nothing was started. ${waiting}; if that run is still running, decide again once it has ended, and if it stopped without writing its end, nothing continues it from this card: start the workflow again — it runs from its first step`;
@@ -752,12 +974,26 @@ export function workflowParkUnusedSentence(o) {
752
974
  : "the approval card is no longer waiting for a decision (it was decided elsewhere, it expired, or it was removed). Nothing is left to do for this decision";
753
975
  case "continuing_elsewhere": {
754
976
  const self = typeof o.holder === "string" && o.holder === o.runId;
755
- const who = self ? `run ${echo(o.runId)} itself holds the claim to continue this workflow right now (it is still running, or has just stopped and not yet given the claim back)` : `another run${o.holder !== undefined && typeof o.holder === "string" ? ` (run ${echo(o.holder)})` : ""} holds the claim to continue this workflow right now`;
756
- const at = claimLapseInstant(o.claimExpiresAt);
757
- const lapse = `or once the claim lapses${at !== undefined ? ` (at ${at} at the latest)` : ""} if its process stopped without giving it back`;
758
977
  const holderRun = typeof o.holder === "string" ? `run ${echo(o.holder)}` : undefined;
978
+ const recording = "another leg of this workflow, recording a person's answer to continuing it";
979
+ const at = claimLapseInstant(o.claimExpiresAt);
980
+ const when = at !== undefined ? `at ${at} at the latest` : o.claimLapseUnreadable === true ? CLAIM_REMAINING_UNREADABLE_NOTE : undefined;
981
+ const lapse = `or once the claim lapses${when !== undefined ? ` (${when})` : ""} if its process stopped without giving it back`;
982
+ const mayHaveUsed = o.heldForAnswer !== true && !self;
983
+ const whatCame = `${mayHaveUsed && holderRun !== undefined ? `If ${holderRun} was started, its completion notification and record tell what came of it. ` : ""}The workflow's run records tell whether the run was continued, and the approval card tells whether it still waits for a decision`;
984
+ if (o.answerUnrecorded === true) {
985
+ const holderSaid = o.heldForAnswer === true ? `${recording},` : self ? `run ${echo(o.runId)} itself (it is still running, or has just stopped and not yet given the claim back)` : holderRun ?? "another leg of this workflow";
986
+ return `a person answered no when asked to continue the workflow, and that answer was not recorded: ${holderSaid} held the workflow's resume claim at that moment${mayHaveUsed ? " and may have continued the run with this same decision" : ""}, so this leg started nothing. ${whatCame}`;
987
+ }
988
+ const who = o.heldForAnswer === true ? `${recording}, holds the claim to continue this workflow` : self ? `run ${echo(o.runId)} itself holds the claim to continue this workflow right now (it is still running, or has just stopped and not yet given the claim back)` : `another run${holderRun !== undefined ? ` (${holderRun})` : ""} holds the claim to continue this workflow right now`;
989
+ if (o.heldForAnswer === true) {
990
+ const back = `The claim comes free when that leg gives it back, ${lapse}`;
991
+ return `${who}, so ${o.decisionIds.length > 0
992
+ ? `this leg did not use this decision; what that leg records about it is read the next time the decision is handed over. ${back}`
993
+ : `nothing was started. ${back}; the run's approval card then tells whether the run waits for a decision`}`;
994
+ }
759
995
  return `${who}, so ${o.decisionIds.length > 0
760
- ? `this decision was not used; once that run has ended${at !== undefined ? ` (the claim lapses at ${at} at the latest)` : ""}, deciding the card again continues the workflow`
996
+ ? `this decision was not used this time${mayHaveUsed ? "; that run may be continuing the run with this same decision" : ""}. ${whatCame}. The claim comes free when that run gives it back, ${lapse}`
761
997
  : self
762
998
  ? `nothing was started; it can be continued once it has ended and given the claim back, ${lapse}`
763
999
  : `nothing was started. If you were told that the engine continues this run${holderRun !== undefined ? ` as ${holderRun}` : ""}, do not call again: ${holderRun !== undefined ? `${holderRun}'s` : "that continuation's"} completion notification tells what came of it. If you were not told that, ${holderRun ?? "the run that holds the claim"} is another continuation of this workflow, and this run cannot be continued while that run holds the claim, which comes free when that run gives it back, ${lapse}`}`;
@@ -784,6 +1020,8 @@ export function workflowParkUnusedSentence(o) {
784
1020
  return `other lines of this workflow are waiting: ${list}, and a workflow runs or waits on one line at a time. ${kept ? `${waiting}; ${wayOut} — each moves its own line —, then decide this card again once none of them waits` : `Nothing was started; ${wayOut}`}`;
785
1021
  }
786
1022
  case "card_unresumable":
1023
+ if (o.otherCard === true)
1024
+ return `another approval card of this workflow run is one this engine cannot resume${unresumableCode(o)}: ${o.rowSentence ?? ""} A continuation would stop on that card, so none was started. ${waiting}: handed over again without that card's decision, this decision continues the run (which then stops on that card once more)`;
787
1025
  return o.terminal === true
788
1026
  ? `the approval card's checkpoint is one no engine release resumes${unresumableCode(o)}: ${o.rowSentence ?? ""} The workflow run cannot be continued from this card; start the workflow again`
789
1027
  : `this engine cannot resume the approval card's checkpoint${unresumableCode(o)}: ${o.rowSentence ?? ""} This engine cannot continue the workflow run from this card. If the deployment still runs a worker whose engine release reads the card, the decision can continue the run there; otherwise cancel the run and start the workflow again`;
@@ -803,13 +1041,15 @@ export function workflowParkUnusedSentence(o) {
803
1041
  return o.explicit === true
804
1042
  ? `a person answered no when asked to continue the workflow. ${waiting}; decide the card again (a new decision) to continue the run, or start the workflow again`
805
1043
  : `this session's permission settings now refuse to run the workflow${o.code !== undefined ? ` (${neutral(o.code)})` : ""}. ${waiting}: once ${o.code === "persisted_rule" ? "that deny rule for the Workflow tool is removed" : o.code === "mode" ? "the session is out of that permission mode" : "the Workflow tool is allowed again"}, deciding the card again continues the run — or start the workflow again`;
1044
+ case "call_changed":
1045
+ return `the Workflow call that continues the run came back changed when it was judged (an approver's edit, or a policy's or a hook's rewrite of its arguments), and the engine's continuation runs only what the workflow was started with, so nothing was started. ${waiting}: the session's model can call the Workflow tool with resumeFromRunId itself — that call is judged on its own card, where the change can be made again; it runs as approved and stops on the same approval step once more, under a new run, and deciding that step's card continues it`;
806
1046
  case "ask_unanswerable":
807
1047
  return `continuing the workflow needs a person's approval that nobody can give in this session right now. ${waiting}: the session's model can ask for that approval as a new card, or the card can be decided again where a person can approve`;
808
1048
  case "launch_refused":
809
1049
  return `the workflow could not be started${o.why !== undefined ? `: ${neutral(o.why, WHY_ECHO_MAX)}` : ""}. ${waiting}: once the cause clears, deciding the card again continues the run; if it does not clear, start the workflow again`;
810
1050
  }
811
1051
  }
812
- const settledForGood = (o) => o.reason === "not_pending" || settlesDecision(o);
1052
+ const settledForGood = (o) => workflowParkUnusedClassOf(o.reason, settlesDecision(o)) !== "deliverable";
813
1053
  export function notContinuedRefusalOf(runId, reason, more = {}) {
814
1054
  const { decisionIds = [], ...rest } = more;
815
1055
  return `workflow run "${neutral(runId)}" is not continued: ${workflowParkUnusedSentence({ kind: "unused", runId, decisionIds, reason, ...rest })}.`;
@@ -833,6 +1073,9 @@ const ECHO_MAX = 64;
833
1073
  const WAITING_LINES_NAMED_MAX = 3;
834
1074
  const WHY_ECHO_MAX = 160;
835
1075
  const neutral = (s, max = ECHO_MAX) => inlineUntrusted(s, max);
1076
+ function decisionKeyOf(runId, decisionIds) {
1077
+ return createHash("sha256").update(JSON.stringify([runId, [...new Set(decisionIds)].sort()])).digest("hex").slice(0, 32);
1078
+ }
836
1079
  export function workflowParksContributor(input) {
837
1080
  const decisions = input.decisions;
838
1081
  if (decisions === undefined || decisions.length === 0)
@@ -840,13 +1083,23 @@ export function workflowParksContributor(input) {
840
1083
  return async () => {
841
1084
  const outcomes = input.adopter !== undefined ? await input.adopter({ gate: input.gate, mintCallId: input.mintCallId, ctxOf: input.ctxOf, ...(input.resumedCall !== undefined ? { resumedCall: input.resumedCall } : {}) }) : unmountedWorkflowParkAdoptions(decisions);
842
1085
  for (const o of outcomes) {
843
- if (o.kind !== "unused")
1086
+ if (o.kind === "started") {
1087
+ try {
1088
+ input.deliver({
1089
+ code: "workflow.parked_decision_used",
1090
+ message: `the approval decision for workflow run "${neutral(o.runId)}" was used to continue it, as run "${neutral(o.continuedAs)}".`,
1091
+ detail: { runId: o.runId, decisionIds: [...o.decisionIds], decisionKey: decisionKeyOf(o.runId, o.decisionIds), continuedAs: o.continuedAs },
1092
+ });
1093
+ }
1094
+ catch {
1095
+ }
844
1096
  continue;
1097
+ }
845
1098
  try {
846
1099
  input.deliver({
847
1100
  code: "workflow.parked_decision_unused",
848
1101
  message: `the approval decision for workflow run "${neutral(o.runId)}" was not used to continue it: ${workflowParkUnusedSentence(o)}.`,
849
- detail: { runId: o.runId, decisionIds: [...o.decisionIds], reason: o.reason, ...holderDetailOf(o), ...(o.code !== undefined ? { code: o.code } : {}), ...(o.changed !== undefined ? { changed: o.changed } : {}), ...(o.inputs !== undefined ? { inputs: [...o.inputs] } : {}), ...(o.why !== undefined ? { why: o.why } : {}), ...(o.rowReason !== undefined ? { rowReason: o.rowReason } : {}), ...(o.terminal === true ? { terminal: true } : {}), ...(o.continuedAs !== undefined ? { continuedAs: o.continuedAs } : {}) },
1102
+ detail: { runId: o.runId, decisionIds: [...o.decisionIds], decisionKey: decisionKeyOf(o.runId, o.decisionIds), reason: o.reason, ...holderDetailOf(o), ...(o.code !== undefined ? { code: o.code } : {}), ...(o.changed !== undefined ? { changed: o.changed } : {}), ...(o.inputs !== undefined ? { inputs: [...o.inputs] } : {}), ...(o.why !== undefined ? { why: o.why } : {}), ...(o.rowReason !== undefined ? { rowReason: o.rowReason } : {}), ...(o.terminal === true ? { terminal: true } : {}), ...(o.continuedAs !== undefined ? { continuedAs: o.continuedAs } : {}), spent: settlesDecision(o) },
850
1103
  });
851
1104
  }
852
1105
  catch {
@@ -855,6 +1108,18 @@ export function workflowParksContributor(input) {
855
1108
  return workflowContinuationFrameBody(outcomes, input.toolName, input.say);
856
1109
  };
857
1110
  }
1111
+ function groupedByAnswer(answers) {
1112
+ const groups = new Map();
1113
+ for (const o of answers) {
1114
+ if (o.kind !== "unused")
1115
+ continue;
1116
+ const { decisionIds, ...rest } = o;
1117
+ const key = JSON.stringify(Object.entries(rest).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
1118
+ const g = groups.get(key);
1119
+ groups.set(key, g === undefined ? o : { ...g, decisionIds: [...g.decisionIds, ...decisionIds] });
1120
+ }
1121
+ return [...groups.values()];
1122
+ }
858
1123
  function holderDetailOf(o) {
859
1124
  const holder = o.waiting !== undefined && o.waiting.length > 0 ? (o.waiting.length === 1 ? o.waiting[0].runId : o.waiting.map((l) => l.runId)) : o.holder;
860
1125
  return holder === undefined ? {} : { holder: typeof holder === "string" ? holder : [...holder] };