@proofoftech/flowsafe 0.19.0 → 0.21.0

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 (297) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/README.md +68 -6
  3. package/deployment-identity-protocol.d.mts +70 -1
  4. package/deployment-identity-protocol.mjs +423 -5
  5. package/dist/agent-host/index.d.ts +1 -1
  6. package/dist/agent-host/index.d.ts.map +1 -1
  7. package/dist/agent-host/index.js.map +1 -1
  8. package/dist/agent-host/router.d.ts.map +1 -1
  9. package/dist/agent-host/router.js +17 -4
  10. package/dist/agent-host/router.js.map +1 -1
  11. package/dist/agent-host/thread-host.d.ts +14 -1
  12. package/dist/agent-host/thread-host.d.ts.map +1 -1
  13. package/dist/agent-host/thread-host.js +865 -308
  14. package/dist/agent-host/thread-host.js.map +1 -1
  15. package/dist/agent-host/thread-topology.d.ts +43 -1
  16. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  17. package/dist/agent-host/thread-topology.js +301 -28
  18. package/dist/agent-host/thread-topology.js.map +1 -1
  19. package/dist/agent-runner/durable-agent-runner.d.ts +107 -8
  20. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  21. package/dist/agent-runner/durable-agent-runner.js +427 -55
  22. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  23. package/dist/agent-runner/index.d.ts +1 -1
  24. package/dist/agent-runner/index.d.ts.map +1 -1
  25. package/dist/agent-runner/index.js.map +1 -1
  26. package/dist/approval-api/actor-context.d.ts +4 -0
  27. package/dist/approval-api/actor-context.d.ts.map +1 -1
  28. package/dist/approval-api/actor-context.js +53 -5
  29. package/dist/approval-api/actor-context.js.map +1 -1
  30. package/dist/approval-api/d1-store.d.ts.map +1 -1
  31. package/dist/approval-api/d1-store.js +6 -3
  32. package/dist/approval-api/d1-store.js.map +1 -1
  33. package/dist/approval-api/principal-identity.d.ts +32 -0
  34. package/dist/approval-api/principal-identity.d.ts.map +1 -0
  35. package/dist/approval-api/principal-identity.js +69 -0
  36. package/dist/approval-api/principal-identity.js.map +1 -0
  37. package/dist/approval-api/principal.d.ts +10 -13
  38. package/dist/approval-api/principal.d.ts.map +1 -1
  39. package/dist/approval-api/principal.js +10 -46
  40. package/dist/approval-api/principal.js.map +1 -1
  41. package/dist/approval-api/retention.d.ts +1 -2
  42. package/dist/approval-api/retention.d.ts.map +1 -1
  43. package/dist/approval-api/retention.js.map +1 -1
  44. package/dist/approval-api/router.d.ts.map +1 -1
  45. package/dist/approval-api/router.js +9 -1
  46. package/dist/approval-api/router.js.map +1 -1
  47. package/dist/approval-api/service.d.ts +29 -14
  48. package/dist/approval-api/service.d.ts.map +1 -1
  49. package/dist/approval-api/service.js +83 -25
  50. package/dist/approval-api/service.js.map +1 -1
  51. package/dist/approval-api/types.d.ts +12 -0
  52. package/dist/approval-api/types.d.ts.map +1 -1
  53. package/dist/approval-api/types.js +12 -0
  54. package/dist/approval-api/types.js.map +1 -1
  55. package/dist/audit-export/index.d.ts +2 -2
  56. package/dist/audit-export/index.js +2 -2
  57. package/dist/background-tasks/d1-storage.d.ts +4 -3
  58. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  59. package/dist/background-tasks/d1-storage.js +7 -13
  60. package/dist/background-tasks/d1-storage.js.map +1 -1
  61. package/dist/background-tasks/host.d.ts +127 -14
  62. package/dist/background-tasks/host.d.ts.map +1 -1
  63. package/dist/background-tasks/host.js +579 -50
  64. package/dist/background-tasks/host.js.map +1 -1
  65. package/dist/background-tasks/index.d.ts +2 -2
  66. package/dist/background-tasks/index.d.ts.map +1 -1
  67. package/dist/background-tasks/index.js +11 -6
  68. package/dist/background-tasks/index.js.map +1 -1
  69. package/dist/background-tasks/routes.d.ts +19 -2
  70. package/dist/background-tasks/routes.d.ts.map +1 -1
  71. package/dist/background-tasks/routes.js +4 -4
  72. package/dist/background-tasks/routes.js.map +1 -1
  73. package/dist/deployment-identity-protocol.d.ts +2 -2
  74. package/dist/deployment-identity-protocol.d.ts.map +1 -1
  75. package/dist/deployment-identity-protocol.js +1 -1
  76. package/dist/deployment-identity-protocol.js.map +1 -1
  77. package/dist/do-runner/cause-chain.d.ts +53 -0
  78. package/dist/do-runner/cause-chain.d.ts.map +1 -0
  79. package/dist/do-runner/cause-chain.js +96 -0
  80. package/dist/do-runner/cause-chain.js.map +1 -0
  81. package/dist/do-runner/constants.d.ts +3 -0
  82. package/dist/do-runner/constants.d.ts.map +1 -0
  83. package/dist/do-runner/constants.js +3 -0
  84. package/dist/do-runner/constants.js.map +1 -0
  85. package/dist/do-runner/d1-storage.d.ts +47 -69
  86. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  87. package/dist/do-runner/d1-storage.js +972 -196
  88. package/dist/do-runner/d1-storage.js.map +1 -1
  89. package/dist/do-runner/deployment-identity.d.ts +29 -5
  90. package/dist/do-runner/deployment-identity.d.ts.map +1 -1
  91. package/dist/do-runner/deployment-identity.js +23 -6
  92. package/dist/do-runner/deployment-identity.js.map +1 -1
  93. package/dist/do-runner/do-error-response.d.ts +4 -23
  94. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  95. package/dist/do-runner/do-error-response.js +19 -24
  96. package/dist/do-runner/do-error-response.js.map +1 -1
  97. package/dist/do-runner/do-status-error.d.ts +37 -0
  98. package/dist/do-runner/do-status-error.d.ts.map +1 -0
  99. package/dist/do-runner/do-status-error.js +42 -0
  100. package/dist/do-runner/do-status-error.js.map +1 -0
  101. package/dist/do-runner/durable-object.d.ts +2 -1
  102. package/dist/do-runner/durable-object.d.ts.map +1 -1
  103. package/dist/do-runner/durable-object.js +617 -144
  104. package/dist/do-runner/durable-object.js.map +1 -1
  105. package/dist/do-runner/execution-admission.d.ts +114 -0
  106. package/dist/do-runner/execution-admission.d.ts.map +1 -0
  107. package/dist/do-runner/execution-admission.js +206 -0
  108. package/dist/do-runner/execution-admission.js.map +1 -0
  109. package/dist/do-runner/execution-context.d.ts.map +1 -1
  110. package/dist/do-runner/execution-context.js +1 -0
  111. package/dist/do-runner/execution-context.js.map +1 -1
  112. package/dist/do-runner/execution-fence.d.ts +379 -0
  113. package/dist/do-runner/execution-fence.d.ts.map +1 -0
  114. package/dist/do-runner/execution-fence.js +1098 -0
  115. package/dist/do-runner/execution-fence.js.map +1 -0
  116. package/dist/do-runner/fenced-workflow-capability.d.ts +64 -0
  117. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -0
  118. package/dist/do-runner/fenced-workflow-capability.js +3 -0
  119. package/dist/do-runner/fenced-workflow-capability.js.map +1 -0
  120. package/dist/do-runner/fenced-workflows-d1.d.ts +15 -0
  121. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -0
  122. package/dist/do-runner/fenced-workflows-d1.js +894 -0
  123. package/dist/do-runner/fenced-workflows-d1.js.map +1 -0
  124. package/dist/do-runner/index.d.ts +20 -8
  125. package/dist/do-runner/index.d.ts.map +1 -1
  126. package/dist/do-runner/index.js +21 -4
  127. package/dist/do-runner/index.js.map +1 -1
  128. package/dist/do-runner/init.d.ts +82 -1
  129. package/dist/do-runner/init.d.ts.map +1 -1
  130. package/dist/do-runner/init.js +58 -3
  131. package/dist/do-runner/init.js.map +1 -1
  132. package/dist/do-runner/initial-admission-refusal.d.ts +7 -0
  133. package/dist/do-runner/initial-admission-refusal.d.ts.map +1 -0
  134. package/dist/do-runner/initial-admission-refusal.js +41 -0
  135. package/dist/do-runner/initial-admission-refusal.js.map +1 -0
  136. package/dist/do-runner/inventory.d.ts +295 -0
  137. package/dist/do-runner/inventory.d.ts.map +1 -0
  138. package/dist/do-runner/inventory.js +800 -0
  139. package/dist/do-runner/inventory.js.map +1 -0
  140. package/dist/do-runner/notification-predicate.d.ts +8 -0
  141. package/dist/do-runner/notification-predicate.d.ts.map +1 -0
  142. package/dist/do-runner/notification-predicate.js +136 -0
  143. package/dist/do-runner/notification-predicate.js.map +1 -0
  144. package/dist/do-runner/run-lifecycle.d.ts +20 -1
  145. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  146. package/dist/do-runner/run-lifecycle.js +67 -13
  147. package/dist/do-runner/run-lifecycle.js.map +1 -1
  148. package/dist/do-runner/run-provenance.d.ts +38 -0
  149. package/dist/do-runner/run-provenance.d.ts.map +1 -0
  150. package/dist/do-runner/run-provenance.js +152 -0
  151. package/dist/do-runner/run-provenance.js.map +1 -0
  152. package/dist/do-runner/run-storage-tables.d.ts +2 -0
  153. package/dist/do-runner/run-storage-tables.d.ts.map +1 -0
  154. package/dist/do-runner/run-storage-tables.js +4 -0
  155. package/dist/do-runner/run-storage-tables.js.map +1 -0
  156. package/dist/do-runner/run-terminal-state.d.ts +29 -0
  157. package/dist/do-runner/run-terminal-state.d.ts.map +1 -0
  158. package/dist/do-runner/run-terminal-state.js +105 -0
  159. package/dist/do-runner/run-terminal-state.js.map +1 -0
  160. package/dist/do-runner/runtime.d.ts +191 -46
  161. package/dist/do-runner/runtime.d.ts.map +1 -1
  162. package/dist/do-runner/runtime.js +994 -378
  163. package/dist/do-runner/runtime.js.map +1 -1
  164. package/dist/do-runner/start-idempotency.d.ts +285 -0
  165. package/dist/do-runner/start-idempotency.d.ts.map +1 -0
  166. package/dist/do-runner/start-idempotency.js +994 -0
  167. package/dist/do-runner/start-idempotency.js.map +1 -0
  168. package/dist/do-runner/start-reservation-contract.d.ts +103 -0
  169. package/dist/do-runner/start-reservation-contract.d.ts.map +1 -0
  170. package/dist/do-runner/start-reservation-contract.js +338 -0
  171. package/dist/do-runner/start-reservation-contract.js.map +1 -0
  172. package/dist/do-runner/suspension-deadline.d.ts +4 -11
  173. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  174. package/dist/do-runner/suspension-deadline.js +8 -12
  175. package/dist/do-runner/suspension-deadline.js.map +1 -1
  176. package/dist/do-runner/table-prefix.d.ts.map +1 -1
  177. package/dist/do-runner/table-prefix.js +2 -1
  178. package/dist/do-runner/table-prefix.js.map +1 -1
  179. package/dist/do-runner/testing.d.ts +3 -0
  180. package/dist/do-runner/testing.d.ts.map +1 -0
  181. package/dist/do-runner/testing.js +3 -0
  182. package/dist/do-runner/testing.js.map +1 -0
  183. package/dist/do-runner/thread-do.d.ts +2 -1
  184. package/dist/do-runner/thread-do.d.ts.map +1 -1
  185. package/dist/do-runner/thread-do.js +14 -10
  186. package/dist/do-runner/thread-do.js.map +1 -1
  187. package/dist/do-runner/workflow-snapshot-row.d.ts +49 -0
  188. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -0
  189. package/dist/do-runner/workflow-snapshot-row.js +97 -0
  190. package/dist/do-runner/workflow-snapshot-row.js.map +1 -0
  191. package/dist/goals/objective-routes.d.ts +15 -5
  192. package/dist/goals/objective-routes.d.ts.map +1 -1
  193. package/dist/goals/objective-routes.js +64 -64
  194. package/dist/goals/objective-routes.js.map +1 -1
  195. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  196. package/dist/host-kit/approval-bridge.js +10 -7
  197. package/dist/host-kit/approval-bridge.js.map +1 -1
  198. package/dist/host-kit/do-response.d.ts +16 -0
  199. package/dist/host-kit/do-response.d.ts.map +1 -1
  200. package/dist/host-kit/do-response.js +181 -0
  201. package/dist/host-kit/do-response.js.map +1 -1
  202. package/dist/host-kit/do-run-topology.d.ts +3 -0
  203. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  204. package/dist/host-kit/do-run-topology.js +36 -8
  205. package/dist/host-kit/do-run-topology.js.map +1 -1
  206. package/dist/host-kit/env-vars.d.ts.map +1 -1
  207. package/dist/host-kit/env-vars.js +5 -6
  208. package/dist/host-kit/env-vars.js.map +1 -1
  209. package/dist/host-kit/flowsafe-worker.d.ts +49 -6
  210. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  211. package/dist/host-kit/flowsafe-worker.js +409 -111
  212. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  213. package/dist/host-kit/host-approval-service.d.ts +24 -14
  214. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  215. package/dist/host-kit/host-approval-service.js +29 -40
  216. package/dist/host-kit/host-approval-service.js.map +1 -1
  217. package/dist/host-kit/index.d.ts +9 -3
  218. package/dist/host-kit/index.d.ts.map +1 -1
  219. package/dist/host-kit/index.js +5 -1
  220. package/dist/host-kit/index.js.map +1 -1
  221. package/dist/host-kit/run-route-error.d.ts +8 -4
  222. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  223. package/dist/host-kit/run-route-error.js +14 -11
  224. package/dist/host-kit/run-route-error.js.map +1 -1
  225. package/dist/host-kit/run-router.d.ts +63 -2
  226. package/dist/host-kit/run-router.d.ts.map +1 -1
  227. package/dist/host-kit/run-router.js +167 -45
  228. package/dist/host-kit/run-router.js.map +1 -1
  229. package/dist/host-kit/stream-router.d.ts.map +1 -1
  230. package/dist/host-kit/stream-router.js +18 -9
  231. package/dist/host-kit/stream-router.js.map +1 -1
  232. package/dist/host-kit/thread-topology.d.ts +1 -1
  233. package/dist/host-kit/thread-topology.d.ts.map +1 -1
  234. package/dist/host-kit/thread-topology.js +7 -3
  235. package/dist/host-kit/thread-topology.js.map +1 -1
  236. package/dist/internal-error-response.d.ts.map +1 -1
  237. package/dist/internal-error-response.js +16 -6
  238. package/dist/internal-error-response.js.map +1 -1
  239. package/dist/schedules/index.d.ts +1 -0
  240. package/dist/schedules/index.d.ts.map +1 -1
  241. package/dist/schedules/index.js +1 -7
  242. package/dist/schedules/index.js.map +1 -1
  243. package/dist/schedules/mutation-contract.d.ts +38 -0
  244. package/dist/schedules/mutation-contract.d.ts.map +1 -0
  245. package/dist/schedules/mutation-contract.js +21 -0
  246. package/dist/schedules/mutation-contract.js.map +1 -0
  247. package/dist/schedules/router.d.ts +15 -8
  248. package/dist/schedules/router.d.ts.map +1 -1
  249. package/dist/schedules/router.js +170 -59
  250. package/dist/schedules/router.js.map +1 -1
  251. package/dist/schedules/schedules-d1.d.ts +11 -5
  252. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  253. package/dist/schedules/schedules-d1.js +570 -143
  254. package/dist/schedules/schedules-d1.js.map +1 -1
  255. package/dist/schedules/storage.d.ts +0 -7
  256. package/dist/schedules/storage.d.ts.map +1 -1
  257. package/dist/schedules/storage.js +0 -27
  258. package/dist/schedules/storage.js.map +1 -1
  259. package/dist/schedules/tick.d.ts +13 -0
  260. package/dist/schedules/tick.d.ts.map +1 -1
  261. package/dist/schedules/tick.js +66 -40
  262. package/dist/schedules/tick.js.map +1 -1
  263. package/dist/signal-providers/host-do.d.ts +12 -1
  264. package/dist/signal-providers/host-do.d.ts.map +1 -1
  265. package/dist/signal-providers/host-do.js +28 -3
  266. package/dist/signal-providers/host-do.js.map +1 -1
  267. package/dist/signal-providers/webhook-route.d.ts +15 -1
  268. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  269. package/dist/signal-providers/webhook-route.js +126 -113
  270. package/dist/signal-providers/webhook-route.js.map +1 -1
  271. package/dist/signals/d1-shared.d.ts +11 -8
  272. package/dist/signals/d1-shared.d.ts.map +1 -1
  273. package/dist/signals/d1-shared.js +1 -6
  274. package/dist/signals/d1-shared.js.map +1 -1
  275. package/dist/signals/index.d.ts +1 -1
  276. package/dist/signals/index.d.ts.map +1 -1
  277. package/dist/signals/index.js +1 -1
  278. package/dist/signals/index.js.map +1 -1
  279. package/dist/signals/notification-dispatch.d.ts +109 -5
  280. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  281. package/dist/signals/notification-dispatch.js +430 -46
  282. package/dist/signals/notification-dispatch.js.map +1 -1
  283. package/dist/signals/notifications-d1.d.ts +14 -1
  284. package/dist/signals/notifications-d1.d.ts.map +1 -1
  285. package/dist/signals/notifications-d1.js +229 -18
  286. package/dist/signals/notifications-d1.js.map +1 -1
  287. package/dist/signals/router.d.ts +6 -4
  288. package/dist/signals/router.d.ts.map +1 -1
  289. package/dist/signals/router.js +49 -84
  290. package/dist/signals/router.js.map +1 -1
  291. package/dist/signals/thread-do-routes.d.ts +2 -0
  292. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  293. package/dist/signals/thread-do-routes.js +330 -83
  294. package/dist/signals/thread-do-routes.js.map +1 -1
  295. package/package.json +6 -3
  296. package/patches/@mastra__core@1.53.0.patch +54 -0
  297. package/scripts/seed-deployment-identity.mjs +34 -9
@@ -20,12 +20,22 @@
20
20
  // (see durable-object.ts).
21
21
  import { Mastra } from '@mastra/core/mastra';
22
22
  import { RequestContext } from '@mastra/core/request-context';
23
+ import { cleanStepResult, } from '@mastra/core/workflows';
23
24
  import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal.js';
24
25
  import { BREAKWATER_ACTOR_KEY, BREAKWATER_CONNECTOR_EXECUTION_KEY, BREAKWATER_ISOLATION_SCOPE_KEY, BREAKWATER_WORKFLOW_SCOPE_KEY, } from './breakwater-keys.js';
26
+ import { assertMutationEpoch, ExecutionFenceUnreadableError, normalizeD1RunExecutionIdentity, normalizeMutationEpoch, normalizeStartIdentity, RunStartPendingError, } from './execution-admission.js';
25
27
  import { isReservedExecutionContextKey, RUN_PROVENANCE_CONTEXT_KEY, stripReservedExecutionContext, } from './execution-context.js';
28
+ import { admitsExistingRun, admitsRunStart, ExecutionFencedError, } from './execution-fence.js';
29
+ import { FENCED_WORKFLOW_STORAGE, } from './fenced-workflow-capability.js';
30
+ import { isDefinitiveInitialAdmissionRefusal } from './initial-admission-refusal.js';
26
31
  import { mastraRegistryEntries } from './mastra-registry.js';
27
32
  import { isPathSafeId } from './path-safe-id.js';
28
- import { canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, hasDisputedSettlement, lifecycleFromRequestContext, RUN_LIFECYCLE_CONTEXT_KEY, } from './run-lifecycle.js';
33
+ import { canonicalEconomicOperations, canonicalReplayPrincipals, canonicalScheduleDispatch, hasDisputedSettlement, lifecycleFromRequestContext, nextLifecycleRevision, projectTerminalLifecycle, RUN_LIFECYCLE_CONTEXT_KEY, RunLifecycleBlockedError, terminalCleanupFor, } from './run-lifecycle.js';
34
+ import { decodeProgressRunProvenance, decodeResumeCounts, nextResumeCount, runExecutionIdentityFor, } from './run-provenance.js';
35
+ import { errorText, isRunStatus, isTerminalRunStatus, terminalStateFields, terminalStateUpdate, } from './run-terminal-state.js';
36
+ import { captureReservation, } from './start-reservation-contract.js';
37
+ import { validateTablePrefix } from './table-prefix.js';
38
+ export { RunLifecycleBlockedError, } from './run-lifecycle.js';
29
39
  export class UnknownWorkflowError extends Error {
30
40
  constructor(workflowId) {
31
41
  super(`unknown workflow '${workflowId}'`);
@@ -73,14 +83,6 @@ export class RunTerminalConflictError extends Error {
73
83
  this.name = 'RunTerminalConflictError';
74
84
  }
75
85
  }
76
- export class RunLifecycleBlockedError extends Error {
77
- reason;
78
- constructor(reason) {
79
- super(reason.message);
80
- this.name = 'RunLifecycleBlockedError';
81
- this.reason = reason;
82
- }
83
- }
84
86
  /** A request the caller can fix: bad input/resume data or step selection. */
85
87
  export class InvalidRunRequestError extends Error {
86
88
  constructor(message) {
@@ -123,6 +125,8 @@ function runProvenance(state) {
123
125
  if (value === null || typeof value !== 'object') {
124
126
  throw new Error('stored run provenance is malformed');
125
127
  }
128
+ if (value.version === 2)
129
+ return decodeProgressRunProvenance(value);
126
130
  const candidate = value;
127
131
  if (candidate.version !== 1 ||
128
132
  (candidate.requestedBy !== undefined &&
@@ -137,17 +141,7 @@ function runProvenance(state) {
137
141
  !Array.isArray(candidate.resumeCounts)) {
138
142
  throw new Error('stored run provenance is malformed');
139
143
  }
140
- const counts = [];
141
- for (const entry of candidate.resumeCounts) {
142
- if (!Array.isArray(entry) ||
143
- entry.length !== 2 ||
144
- typeof entry[0] !== 'string' ||
145
- !Number.isSafeInteger(entry[1]) ||
146
- entry[1] < 1) {
147
- throw new Error('stored run provenance is malformed');
148
- }
149
- counts.push([entry[0], entry[1]]);
150
- }
144
+ const counts = decodeResumeCounts(candidate.resumeCounts);
151
145
  return {
152
146
  version: 1,
153
147
  ...(candidate.requestedBy === undefined
@@ -161,78 +155,6 @@ function runProvenance(state) {
161
155
  resumeCounts: counts,
162
156
  };
163
157
  }
164
- const NONTERMINAL_RUN_STATUSES = new Set([
165
- 'running',
166
- 'suspended',
167
- 'waiting',
168
- 'pending',
169
- 'paused',
170
- ]);
171
- function terminalStateUpdate(result) {
172
- if (NONTERMINAL_RUN_STATUSES.has(result.status))
173
- return undefined;
174
- const common = {
175
- status: result.status,
176
- result: undefined,
177
- error: undefined,
178
- suspendedPaths: {},
179
- waitingPaths: {},
180
- resumeLabels: {},
181
- activePaths: [],
182
- activeStepsPath: {},
183
- };
184
- if (result.status === 'success') {
185
- return {
186
- ...common,
187
- result: result.result,
188
- };
189
- }
190
- if (result.status === 'failed') {
191
- const error = result.error;
192
- const name = error instanceof Error
193
- ? error.name
194
- : error !== null &&
195
- typeof error === 'object' &&
196
- 'name' in error &&
197
- typeof error.name === 'string'
198
- ? error.name
199
- : 'Error';
200
- const stack = error instanceof Error
201
- ? error.stack
202
- : error !== null &&
203
- typeof error === 'object' &&
204
- 'stack' in error &&
205
- typeof error.stack === 'string'
206
- ? error.stack
207
- : undefined;
208
- return {
209
- ...common,
210
- error: {
211
- name,
212
- message: errorText(error),
213
- ...(stack !== undefined ? { stack } : {}),
214
- },
215
- };
216
- }
217
- return common;
218
- }
219
- // Failed runs carry the step's thrown error as an Error instance, a string,
220
- // or — once it crossed an engine/persistence boundary — a serialized
221
- // { name, message, stack } object; String() on the last reads
222
- // '[object Object]', so extract the message wherever it lives.
223
- function errorText(error) {
224
- if (error instanceof Error)
225
- return error.message;
226
- if (typeof error === 'string')
227
- return error;
228
- if (error !== null &&
229
- typeof error === 'object' &&
230
- 'message' in error &&
231
- typeof error.message === 'string') {
232
- return error.message;
233
- }
234
- return String(error);
235
- }
236
158
  function summarize(runId, result, counts, requestedBy, requestedByKind, deadlineAt) {
237
159
  let summary;
238
160
  switch (result.status) {
@@ -348,15 +270,6 @@ function byStep(suspendedKeys, lookup) {
348
270
  }
349
271
  return size > 0 ? map : undefined;
350
272
  }
351
- // Projection of the persisted WorkflowState for status(). Unlike summarize()
352
- // (which shapes a just-finished WorkflowResult), this reads the stored
353
- // snapshot: suspended paths come from suspendedPaths keys (dot-joined for
354
- // nested steps) and suspend payloads from per-step results — the same keyed
355
- // shape start/resume return. A tripwire status carries no reason here (the
356
- // snapshot does not persist it). When the state is an in-memory approximation
357
- // (isFromInMemory), steps are empty and timestamps are current-time; the
358
- // projection truthfully degrades to status-only rather than fabricating
359
- // detail.
360
273
  function summarizeState(runId, state, counts, requestedBy, requestedByKind) {
361
274
  const lifecycle = lifecycleFromRequestContext(state.requestContext);
362
275
  const summary = {
@@ -398,6 +311,20 @@ function summarizeState(runId, state, counts, requestedBy, requestedByKind) {
398
311
  }
399
312
  return summary;
400
313
  }
314
+ function summaryFromSelectedSnapshot(runId, snapshot, timestamps, provenance) {
315
+ const steps = Object.fromEntries(Object.entries(snapshot.context ?? {})
316
+ .filter(([key]) => key !== 'input' && key !== '__state')
317
+ .map(([key, value]) => [key, cleanStepResult(value)]));
318
+ return summarizeState(runId, {
319
+ status: snapshot.status,
320
+ result: snapshot.result,
321
+ error: snapshot.error,
322
+ requestContext: snapshot.requestContext,
323
+ suspendedPaths: snapshot.suspendedPaths,
324
+ steps,
325
+ ...timestamps,
326
+ }, provenance ? new Map(provenance.resumeCounts) : undefined, provenance?.requestedBy, provenance?.requestedByKind);
327
+ }
401
328
  function summaryWithRequester(summary, requestedBy, requestedByKind) {
402
329
  if (requestedBy !== undefined)
403
330
  summary.requestedBy = requestedBy;
@@ -465,6 +392,130 @@ function relativeDeadline(deadlineMs, now = Date.now()) {
465
392
  }
466
393
  return deadlineAt;
467
394
  }
395
+ function captureStartRunOptions(source) {
396
+ const { runId, inputData, initialState, storedRequestContext, attemptToken, deadlineMs, economicOperations: rawOperations, scheduleDispatch: rawDispatch, idempotencyKey, requestedBy, requestedByKind, mutationEpoch: rawEpoch, startIdentity: rawIdentity, agentStart: rawAgentStart, onPreparedStartIdentity, runOwnerGuard: rawGuard, startReservation: rawReservation, } = source;
397
+ if (requestedBy !== undefined && !isExecutionPrincipalId(requestedBy)) {
398
+ throw new InvalidRunRequestError('requestedBy is malformed');
399
+ }
400
+ if (requestedByKind !== undefined &&
401
+ !isExecutionPrincipalKind(requestedByKind)) {
402
+ throw new InvalidRunRequestError('requestedByKind is malformed');
403
+ }
404
+ if ((requestedBy === undefined) !== (requestedByKind === undefined)) {
405
+ throw new InvalidRunRequestError('requestedBy and requestedByKind must be provided together');
406
+ }
407
+ const mutationEpoch = normalizeMutationEpoch(rawEpoch);
408
+ const startIdentity = rawIdentity === undefined ? undefined : normalizeStartIdentity(rawIdentity);
409
+ const startReservation = rawReservation === undefined
410
+ ? undefined
411
+ : captureReservation(rawReservation, 'started');
412
+ let agentStart;
413
+ if (rawAgentStart !== undefined) {
414
+ if (rawAgentStart === null ||
415
+ typeof rawAgentStart !== 'object' ||
416
+ Array.isArray(rawAgentStart)) {
417
+ throw new InvalidRunRequestError('agentStart is malformed');
418
+ }
419
+ const { threaded } = rawAgentStart;
420
+ if (typeof threaded !== 'boolean') {
421
+ throw new InvalidRunRequestError('agentStart is malformed');
422
+ }
423
+ agentStart = Object.freeze({ threaded });
424
+ }
425
+ if (agentStart !== undefined && startIdentity?.target.kind !== 'agent')
426
+ throw new InvalidRunRequestError('agentStart has no agent target');
427
+ if (startIdentity?.target.kind === 'agent' && agentStart === undefined) {
428
+ throw new InvalidRunRequestError('agentStart is required for an agent target');
429
+ }
430
+ if (startIdentity &&
431
+ (startIdentity.owner.id !== requestedBy ||
432
+ startIdentity.owner.kind !== requestedByKind)) {
433
+ throw new InvalidRunRequestError('startIdentity owner does not match requester');
434
+ }
435
+ if (onPreparedStartIdentity !== undefined &&
436
+ typeof onPreparedStartIdentity !== 'function') {
437
+ throw new InvalidRunRequestError('onPreparedStartIdentity is malformed');
438
+ }
439
+ let runOwnerGuard;
440
+ if (rawGuard !== undefined) {
441
+ if (rawGuard === null ||
442
+ typeof rawGuard !== 'object' ||
443
+ Array.isArray(rawGuard)) {
444
+ throw new InvalidRunRequestError('runOwnerGuard is malformed');
445
+ }
446
+ const { owner: rawOwner, reservationToken } = rawGuard;
447
+ if (rawOwner === null ||
448
+ typeof rawOwner !== 'object' ||
449
+ Array.isArray(rawOwner)) {
450
+ throw new InvalidRunRequestError('runOwnerGuard is malformed');
451
+ }
452
+ const { kind, id } = rawOwner;
453
+ if (!isExecutionPrincipalKind(kind) ||
454
+ !isExecutionPrincipalId(id) ||
455
+ !isPathSafeId(reservationToken)) {
456
+ throw new InvalidRunRequestError('runOwnerGuard is malformed');
457
+ }
458
+ runOwnerGuard = Object.freeze({
459
+ owner: Object.freeze({ kind, id }),
460
+ reservationToken,
461
+ });
462
+ }
463
+ if (deadlineMs !== undefined &&
464
+ (!Number.isSafeInteger(deadlineMs) || deadlineMs < 0)) {
465
+ throw new InvalidRunRequestError('deadlineMs must be a nonnegative safe integer');
466
+ }
467
+ let dispatch;
468
+ if (rawDispatch !== undefined) {
469
+ if (rawDispatch === null ||
470
+ typeof rawDispatch !== 'object' ||
471
+ Array.isArray(rawDispatch)) {
472
+ throw new Error('stored run lifecycle is malformed');
473
+ }
474
+ const { scheduleId, dispatchId } = rawDispatch;
475
+ dispatch = { scheduleId, dispatchId };
476
+ }
477
+ let operations;
478
+ if (rawOperations !== undefined) {
479
+ if (!Array.isArray(rawOperations)) {
480
+ throw new Error('stored run lifecycle is malformed');
481
+ }
482
+ const length = rawOperations.length;
483
+ if (!Number.isSafeInteger(length) || length < 0 || length > 0xffff_ffff) {
484
+ throw new Error('stored run lifecycle is malformed');
485
+ }
486
+ operations = new Array(length);
487
+ for (let index = 0; index < length; index++) {
488
+ if (!(index in rawOperations))
489
+ throw new Error('stored run lifecycle is malformed');
490
+ const entry = rawOperations[index];
491
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
492
+ throw new Error('stored run lifecycle is malformed');
493
+ }
494
+ const { id, settlementState } = entry;
495
+ operations[index] = { id, settlementState };
496
+ }
497
+ }
498
+ const captured = {
499
+ runId,
500
+ inputData,
501
+ initialState,
502
+ storedRequestContext,
503
+ attemptToken,
504
+ deadlineMs,
505
+ economicOperations: canonicalEconomicOperations(operations),
506
+ scheduleDispatch: canonicalScheduleDispatch(dispatch),
507
+ idempotencyKey,
508
+ mutationEpoch,
509
+ startIdentity,
510
+ agentStart,
511
+ onPreparedStartIdentity,
512
+ runOwnerGuard,
513
+ startReservation,
514
+ };
515
+ return Object.freeze(requestedBy !== undefined && requestedByKind !== undefined
516
+ ? { ...captured, requestedBy, requestedByKind }
517
+ : captured);
518
+ }
468
519
  function lifecycleForStart(options) {
469
520
  const deadlineAt = relativeDeadline(options.deadlineMs);
470
521
  const economicOperations = canonicalEconomicOperations(options.economicOperations);
@@ -504,6 +555,26 @@ function effectiveLifecycle(persisted, active) {
504
555
  : {}),
505
556
  };
506
557
  }
558
+ function sameExecution(a, b) {
559
+ return (a.tablePrefix === b.tablePrefix &&
560
+ a.workflowId === b.workflowId &&
561
+ a.runId === b.runId &&
562
+ a.startToken === b.startToken);
563
+ }
564
+ function assertClaimIdentity(claim, execution, key = claim.key) {
565
+ if (claim.key !== key ||
566
+ claim.runId !== execution.runId ||
567
+ claim.owner.id !== execution.owner.id ||
568
+ claim.owner.kind !== execution.owner.kind ||
569
+ claim.targetKind !== execution.target.kind ||
570
+ claim.targetId !== execution.target.id ||
571
+ claim.threadId !==
572
+ (execution.target.kind === 'agent'
573
+ ? execution.target.threadId
574
+ : undefined)) {
575
+ throw new InvalidRunRequestError('start reservation disagrees with execution identity');
576
+ }
577
+ }
507
578
  export class RunnerRuntime {
508
579
  #storage;
509
580
  #logger;
@@ -515,16 +586,60 @@ export class RunnerRuntime {
515
586
  #terminalAbortIntents = new Map();
516
587
  #lifecycleLocks = new Map();
517
588
  // The host DO's pubsub identity (RunnerRuntimeOptions.pubsub), threaded into
518
- // both createRun sites below (CI-M-002-002) so a configured host publishes and
589
+ // both createRun sites below so a configured host publishes and
519
590
  // replays on ONE shared feed. Undefined ⇒ core defaults a fresh emitter per
520
591
  // run ⇒ byte-identical to before this seam existed.
521
592
  #pubsub;
593
+ #executionFence;
594
+ #startIdempotency;
522
595
  #mastra;
523
596
  constructor(options) {
524
597
  this.#storage = options.storage;
525
598
  this.#logger = options.logger ?? false;
526
599
  this.#requestContextForRun = options.requestContextForRun;
527
600
  this.#pubsub = options.pubsub;
601
+ this.#executionFence = options.executionFence;
602
+ this.#startIdempotency = options.startIdempotency;
603
+ }
604
+ /**
605
+ * The deployment execution fence this runtime enforces, or undefined when
606
+ * the host built an unfenced runtime. Exposed so the surfaces ABOVE the
607
+ * runtime — the run object's routes, the thread DO's signal routes — gate on
608
+ * the same store rather than constructing a second one, and so
609
+ * DurableObjectRunner can assert that a runtime built against a bound
610
+ * database is never fence-less.
611
+ */
612
+ get executionFence() {
613
+ return this.#executionFence;
614
+ }
615
+ /**
616
+ * The deployment's start reservations, or undefined for a host with no
617
+ * database to reserve against. Exposed for the same reason the fence is: the
618
+ * surfaces ABOVE this runtime reserve and claim against it, and two stores
619
+ * over two bindings would be two different tables answering the same key.
620
+ */
621
+ get startIdempotency() {
622
+ return this.#startIdempotency;
623
+ }
624
+ /**
625
+ * Is this run EXECUTING in this isolate right now?
626
+ *
627
+ * The liveness half of the idempotent-start replay decision, answered from
628
+ * the same `#activeRuns` map the cancel path uses — the runtime's own record
629
+ * of runs it is currently driving. It is in-memory ON PURPOSE: liveness is a
630
+ * property of an isolate that is running code, and any durable proxy for it
631
+ * (a journal, a heartbeat, a timestamp) would keep saying "live" after the
632
+ * isolate that wrote it was evicted, which is precisely the case the probe
633
+ * exists to detect.
634
+ *
635
+ * A `false` here therefore means "not running HERE", which is authoritative
636
+ * only where the run has exactly one possible host — a run Durable Object
637
+ * addressed by `idFromName(workflowId:runId)`, or the thread object an agent
638
+ * run is bound to. Callers that probe across an object boundary must ask the
639
+ * object that owns the run, never their own runtime.
640
+ */
641
+ isRunActive(workflowId, runId) {
642
+ return this.#activeRuns.has(this.#runKey(workflowId, runId));
528
643
  }
529
644
  /**
530
645
  * The host pubsub identity this runtime was built with, or undefined when the
@@ -566,107 +681,269 @@ export class RunnerRuntime {
566
681
  workflowIds() {
567
682
  return [...this.#workflows.keys()];
568
683
  }
569
- async start(workflowId, options) {
570
- const workflow = this.#getWorkflow(workflowId);
571
- // Reject non-path-safe ids at the mint boundary so the runId is unambiguous
572
- // everywhere it addresses the run (D1 key, DO name, URL path) — see
573
- // PATH_SAFE_ID_PATTERN. Fail fast, before the lock and any createRun work.
574
- // The typeof guard is load-bearing, not redundant with the string type:
575
- // this value can arrive from JSON.parse through an unchecked `as` cast
576
- // (durable-object.ts readJson), and RegExp.test() coerces its argument to a
577
- // String — so a numeric runId like 123 would pass the pattern as "123" yet
578
- // mint a run keyed by the number 123, unreachable by the string "123" the
579
- // URL path later carries. There is NO generation fallback (INV-1): a
580
- // missing/null runId is a client error, not a request for one.
581
- if (!isPathSafeId(options.runId)) {
582
- throw new InvalidRunRequestError("runId is required and must be URL-path-safe (letters, digits, '.', '_', '~', '-'; 1–200 chars)");
583
- }
584
- const runId = options.runId;
585
- if (options.requestedBy !== undefined &&
586
- !isExecutionPrincipalId(options.requestedBy)) {
587
- throw new InvalidRunRequestError('requestedBy is malformed');
684
+ async #assertStartFence(idempotencyKey, mutationEpoch) {
685
+ const fence = this.#executionFence;
686
+ if (!fence)
687
+ return;
688
+ const reading = await fence.read();
689
+ assertMutationEpoch(reading, mutationEpoch);
690
+ if (!admitsRunStart(reading, idempotencyKey))
691
+ throw new ExecutionFencedError(reading.state, 'run start');
692
+ if (reading.state === 'proof-only' && reading.proofKey !== undefined)
693
+ return Object.freeze({
694
+ key: reading.proofKey,
695
+ mutationEpoch: reading.mutationEpoch,
696
+ transitionRevision: reading.transitionRevision,
697
+ });
698
+ }
699
+ async #settleStartReservation(state) {
700
+ if (state.kind !== 'result' || !isTerminalRunStatus(state.summary.status))
701
+ return;
702
+ try {
703
+ await this.settleStartExecution(state);
588
704
  }
589
- if (options.requestedByKind !== undefined &&
590
- !isExecutionPrincipalKind(options.requestedByKind)) {
591
- throw new InvalidRunRequestError('requestedByKind is malformed');
705
+ catch (error) {
706
+ console.error(JSON.stringify({
707
+ type: 'start-reservation-settle-failed',
708
+ runId: state.execution.runId,
709
+ error: error instanceof Error ? error.message : String(error),
710
+ }));
592
711
  }
593
- if ((options.requestedBy === undefined) !==
594
- (options.requestedByKind === undefined)) {
595
- throw new InvalidRunRequestError('requestedBy and requestedByKind must be provided together');
712
+ }
713
+ async #assertResumeFence(workflowId, runId) {
714
+ const fence = this.#executionFence;
715
+ if (!fence)
716
+ return;
717
+ const reading = await fence.read();
718
+ if (reading.state === 'open' || reading.state === 'draining')
719
+ return;
720
+ if (reading.state === 'migration-locked')
721
+ throw new ExecutionFencedError(reading.state, 'run resume');
722
+ const state = await this.authoritativeStartState(workflowId, runId);
723
+ if (state?.storage !== 'd1' || !admitsExistingRun(reading, state.execution))
724
+ throw new ExecutionFencedError(reading.state, 'run resume');
725
+ return state.execution;
726
+ }
727
+ /** @internal Retain this physical proof expectation across preparation waits. */
728
+ assertExistingRunAllowed(workflowId, runId) {
729
+ return this.#assertResumeFence(workflowId, runId);
730
+ }
731
+ async #assertRetainedResume(source, workflowId, runId, expected, proof) {
732
+ const reading = this.#executionFence
733
+ ? await this.#executionFence.read()
734
+ : undefined;
735
+ const snapshot = await source.load.call(source.workflows, {
736
+ workflowName: workflowId,
737
+ runId,
738
+ });
739
+ if (!snapshot)
740
+ throw new UnknownRunError(workflowId, runId);
741
+ if (snapshot.runId !== runId)
742
+ throw new RunStateUnreadableError(workflowId, runId);
743
+ const current = runProvenance(snapshot);
744
+ if (expected?.version === 2 &&
745
+ (current?.version !== 2 || current.startToken !== expected.startToken))
746
+ throw new RunStateUnreadableError(workflowId, runId);
747
+ if (proof &&
748
+ (source.tablePrefix !== proof.tablePrefix ||
749
+ current?.version !== 2 ||
750
+ current.startToken !== proof.startToken))
751
+ throw new RunStateUnreadableError(workflowId, runId);
752
+ if (reading) {
753
+ const execution = current?.version === 2
754
+ ? runExecutionIdentityFor({ tablePrefix: source.tablePrefix, workflowId, runId }, current)
755
+ : undefined;
756
+ if (!admitsExistingRun(reading, execution) ||
757
+ (proof && (!execution || !sameExecution(proof, execution))))
758
+ throw new ExecutionFencedError(reading.state, 'run resume');
596
759
  }
760
+ return snapshot;
761
+ }
762
+ async #completedStartState(source, execution, expected) {
763
+ const state = await this.#readStartState(source, execution.workflowId, execution.runId);
764
+ if (!state ||
765
+ state.kind === 'legacy' ||
766
+ !sameExecution(state.execution, execution) ||
767
+ state.provenance.version !== expected.version ||
768
+ state.provenance.attemptToken !== expected.attemptToken)
769
+ throw new RunStateUnreadableError(execution.workflowId, execution.runId);
770
+ if (state.kind === 'initial')
771
+ throw new RunStartPendingError();
772
+ return state;
773
+ }
774
+ async start(workflowId, sourceOptions) {
775
+ const options = captureStartRunOptions(sourceOptions);
776
+ const runId = options.runId;
777
+ if (!isPathSafeId(runId))
778
+ throw new InvalidRunRequestError('runId is required and must be URL-path-safe');
597
779
  if (options.attemptToken !== undefined &&
598
- !isPathSafeId(options.attemptToken)) {
780
+ !isPathSafeId(options.attemptToken))
599
781
  throw new InvalidRunRequestError('attemptToken is malformed');
782
+ const startIdentity = options.startIdentity ??
783
+ (options.requestedBy === undefined
784
+ ? undefined
785
+ : normalizeStartIdentity({
786
+ owner: { id: options.requestedBy, kind: options.requestedByKind },
787
+ target: { kind: 'workflow', id: workflowId },
788
+ }));
789
+ const claim = options.startReservation;
790
+ if (claim) {
791
+ if (!startIdentity || !this.#startIdempotency)
792
+ throw new InvalidRunRequestError('start reservation requires configured store and identity');
793
+ if (options.idempotencyKey !== claim.key)
794
+ throw new InvalidRunRequestError('start reservation key disagrees with execution');
795
+ assertClaimIdentity(claim, { ...startIdentity, runId }, options.idempotencyKey);
600
796
  }
601
- return this.#withRunLock(workflowId, runId, async () => {
602
- // Supplied ids can collide with an existing run; starting it
603
- // again would re-execute already-executed steps.
604
- const existing = await workflow.getWorkflowRunById(runId);
605
- if (existing) {
606
- throw new RunAlreadyExistsError(workflowId, runId, existing.status);
607
- }
608
- // Resolve the leg's context BEFORE createRun: createRun persists the
609
- // initial snapshot, so a provider failure after it would strand a
610
- // pending-but-never-started run (a supplied runId would then be locked
611
- // out by RunAlreadyExistsError on retry). Failing here leaves no state.
612
- const startAttemptToken = options.attemptToken ?? crypto.randomUUID();
613
- const provenance = {
614
- version: 1,
615
- ...(options.requestedBy === undefined
616
- ? {}
617
- : {
618
- requestedBy: options.requestedBy,
619
- requestedByKind: options.requestedByKind,
620
- }),
621
- startToken: startAttemptToken,
622
- attemptToken: startAttemptToken,
623
- resumeCounts: [],
624
- };
625
- const lifecycle = lifecycleForStart(options);
626
- const requestContext = await this.#requestContextFor(workflowId, runId, { kind: 'start' }, provenance, options.storedRequestContext, lifecycle);
627
- // Thread the host DO's pubsub identity into the run (CI-M-002-002). Core
628
- // accepts `createRun({ runId, pubsub })` at every one of its OWN call
629
- // sites (agent/durable index.js:5224/5541) and stamps it straight onto
630
- // `new Run({ ..., pubsub: options?.pubsub })`, defaulting a FRESH
631
- // EventEmitterPubSub when it is undefined. So an unconfigured host
632
- // (#pubsub undefined) reaches the identical `new Run({ pubsub: undefined })`
633
- // the prior `createRun({ runId })` produced — byte-identical, polling
634
- // stays the fallback. A configured host gets ONE shared feed so publish
635
- // and observe()/replay agree (do-runner/pubsub.ts).
636
- const run = await workflow.createRun({ runId, pubsub: this.#pubsub });
637
- let result;
638
- const activeKey = this.#runKey(workflowId, runId);
639
- const active = { run, lifecycle, requestContext };
640
- this.#activeRuns.set(activeKey, active);
641
- try {
642
- result = await run.start({
643
- inputData: options.inputData,
644
- initialState: options.initialState,
645
- requestContext,
646
- });
647
- }
648
- catch (error) {
649
- const recovered = await this.#summaryForAttempt(workflow, runId, provenance.attemptToken);
650
- if (recovered)
651
- return recovered;
652
- throw asClientError(error) ?? error;
653
- }
654
- finally {
655
- if (this.#activeRuns.get(activeKey) === active) {
656
- this.#activeRuns.delete(activeKey);
797
+ let preflight = true;
798
+ const releasePreflight = async () => {
799
+ if (preflight && claim && this.#startIdempotency)
800
+ await this.#startIdempotency.releaseReservation(claim);
801
+ };
802
+ try {
803
+ const workflow = this.#getWorkflow(workflowId);
804
+ if (startIdentity?.target.kind === 'workflow' &&
805
+ startIdentity.target.id !== workflow.id)
806
+ throw new InvalidRunRequestError('startIdentity target does not match workflow');
807
+ const proof = await this.#assertStartFence(options.idempotencyKey, options.mutationEpoch);
808
+ return await this.#withRunLock(workflowId, runId, async () => {
809
+ const activeKey = this.#runKey(workflowId, runId);
810
+ const active = {};
811
+ if (this.#activeRuns.has(activeKey))
812
+ throw new RunAlreadyExistsError(workflowId, runId, 'running');
813
+ this.#activeRuns.set(activeKey, active);
814
+ let execution;
815
+ let engineEntered = false;
816
+ let outcomeReadStarted = false;
817
+ let admissionEntered = false;
818
+ let candidate;
819
+ const originalCached = workflow.runs.get(runId);
820
+ let provenance;
821
+ try {
822
+ const existing = await workflow.getWorkflowRunById(runId);
823
+ if (existing || originalCached)
824
+ throw new RunAlreadyExistsError(workflowId, runId, existing?.status ?? 'pending');
825
+ const source = await this.#captureWorkflowStorage(workflow);
826
+ active.source = source;
827
+ provenance = {
828
+ version: 2,
829
+ startToken: crypto.randomUUID(),
830
+ attemptToken: options.attemptToken ?? crypto.randomUUID(),
831
+ resumeCounts: [],
832
+ ...(options.requestedBy === undefined
833
+ ? {}
834
+ : {
835
+ requestedBy: options.requestedBy,
836
+ requestedByKind: options.requestedByKind,
837
+ }),
838
+ ...(startIdentity ? { startIdentity } : {}),
839
+ ...(options.agentStart ? { agentStart: options.agentStart } : {}),
840
+ ...(options.mutationEpoch === undefined
841
+ ? {}
842
+ : { mutationEpoch: options.mutationEpoch }),
843
+ };
844
+ execution = runExecutionIdentityFor({ tablePrefix: source.tablePrefix, workflowId, runId }, provenance);
845
+ const lifecycle = lifecycleForStart(options);
846
+ active.lifecycle = lifecycle;
847
+ preflight = false;
848
+ const requestContext = await this.#requestContextFor(workflowId, runId, { kind: 'start' }, provenance, options.storedRequestContext, lifecycle);
849
+ active.requestContext = requestContext;
850
+ if (options.onPreparedStartIdentity)
851
+ await Reflect.apply(options.onPreparedStartIdentity, undefined, [
852
+ execution,
853
+ ]);
854
+ const capturedExecution = execution;
855
+ const capturedProvenance = provenance;
856
+ const { executionPromise } = await this.#withLifecycleLock(workflowId, runId, async () => {
857
+ let run;
858
+ if (this.#executionFence) {
859
+ if (source.storage !== 'd1')
860
+ throw new Error('fenced workflow storage capability is unavailable');
861
+ const d1Execution = normalizeD1RunExecutionIdentity(capturedExecution);
862
+ admissionEntered = true;
863
+ const admitted = await source.admit.call(source.capability, {
864
+ execution: d1Execution,
865
+ attemptToken: capturedProvenance.attemptToken,
866
+ mutationEpoch: options.mutationEpoch,
867
+ startIdentity,
868
+ requestContext: Object.fromEntries(requestContext.entries()),
869
+ fence: this.#executionFence,
870
+ reservationStore: claim
871
+ ? this.#startIdempotency
872
+ : undefined,
873
+ reservation: claim,
874
+ proof,
875
+ runOwnerGuard: options.runOwnerGuard,
876
+ onInitialWriteAttempt: () => {
877
+ candidate = workflow.runs.get(runId);
878
+ },
879
+ }, () => workflow.createRun({ runId, pubsub: this.#pubsub }));
880
+ if (!admitted?.witness ||
881
+ !sameExecution(admitted.witness.execution, d1Execution))
882
+ throw new RunStateUnreadableError(workflowId, runId);
883
+ const witnessed = this.#projectD1StartState(source, workflowId, runId, admitted.witness.row);
884
+ if (witnessed.kind !== 'initial' ||
885
+ !sameExecution(witnessed.execution, d1Execution) ||
886
+ witnessed.provenance.initialAdmission !== true ||
887
+ witnessed.provenance.attemptToken !==
888
+ capturedProvenance.attemptToken)
889
+ throw new RunStateUnreadableError(workflowId, runId);
890
+ run = admitted.value;
891
+ }
892
+ else {
893
+ if (claim && startIdentity && this.#startIdempotency)
894
+ await this.#startIdempotency.bindPreparedStart(claim, {
895
+ ...capturedExecution,
896
+ ...startIdentity,
897
+ });
898
+ run = await workflow.createRun({ runId, pubsub: this.#pubsub });
899
+ }
900
+ active.run = run;
901
+ engineEntered = true;
902
+ return {
903
+ executionPromise: run.start({
904
+ inputData: options.inputData,
905
+ initialState: options.initialState,
906
+ requestContext,
907
+ }),
908
+ };
909
+ });
910
+ const result = await executionPromise;
911
+ await this.#reconcileTerminalState(workflowId, runId, result, requestContext, source);
912
+ outcomeReadStarted = true;
913
+ const selected = await this.#completedStartState(source, capturedExecution, provenance);
914
+ await this.#settleStartReservation(selected);
915
+ return selected.summary;
657
916
  }
658
- }
659
- try {
660
- await this.#reconcileTerminalState(workflowId, run.runId, result, requestContext);
661
- }
662
- catch (error) {
663
- const recovered = await this.#summaryForAttempt(workflow, runId, provenance.attemptToken);
664
- if (recovered)
665
- return recovered;
666
- throw error;
667
- }
668
- return summarize(run.runId, result, undefined, provenance.requestedBy, provenance.requestedByKind, lifecycle?.deadlineAt);
669
- });
917
+ catch (error) {
918
+ if (admissionEntered &&
919
+ !engineEntered &&
920
+ execution?.tablePrefix !== null &&
921
+ execution !== undefined &&
922
+ isDefinitiveInitialAdmissionRefusal(error, normalizeD1RunExecutionIdentity(execution))) {
923
+ if (candidate &&
924
+ candidate !== originalCached &&
925
+ workflow.runs.get(runId) === candidate)
926
+ workflow.runs.delete(runId);
927
+ if (claim && this.#startIdempotency)
928
+ await this.#startIdempotency.releaseReservation(claim);
929
+ }
930
+ if (engineEntered && provenance && !outcomeReadStarted) {
931
+ const recovered = await this.#summaryForAttempt(workflow, runId, provenance);
932
+ if (recovered)
933
+ return recovered;
934
+ }
935
+ throw asClientError(error) ?? error;
936
+ }
937
+ finally {
938
+ if (this.#activeRuns.get(activeKey) === active)
939
+ this.#activeRuns.delete(activeKey);
940
+ }
941
+ });
942
+ }
943
+ catch (error) {
944
+ await releasePreflight();
945
+ throw error;
946
+ }
670
947
  }
671
948
  /**
672
949
  * Reattach to a suspended run — the designed fresh-process pattern:
@@ -675,85 +952,88 @@ export class RunnerRuntime {
675
952
  */
676
953
  async resume(workflowId, runId, options = {}) {
677
954
  const workflow = this.#getWorkflow(workflowId);
955
+ const proof = await this.#assertResumeFence(workflowId, runId);
678
956
  return this.#withRunLock(workflowId, runId, async () => {
679
- const state = await this.#workflowState(workflow, runId);
680
- if (!state)
681
- throw new UnknownRunError(workflowId, runId);
682
- if (state.status !== 'suspended') {
683
- throw new RunNotSuspendedError(workflowId, runId, state.status);
684
- }
685
- // Provider before createRun for symmetry with start(): a resume-time
686
- // createRun only reattaches (no snapshot write), but failing before it
687
- // still does the least work and keeps the ordering invariant uniform.
688
- const { nextCounts, provenance, requestContext, lifecycle } = await this.#trustedResumePreparation(workflowId, runId, state, options.step, options.requestedBy, options.requestedByKind, options.deadlineMs, options.economicOperations);
689
957
  const activeKey = this.#runKey(workflowId, runId);
690
- const active = { lifecycle, requestContext };
691
- await this.#withLifecycleLock(workflowId, runId, async () => {
692
- const current = await this.#loadSnapshot(workflowId, runId);
693
- if (!current)
694
- throw new UnknownRunError(workflowId, runId);
695
- const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
696
- if (currentLifecycle?.terminal || currentLifecycle?.transitionIntent) {
697
- throw new RunTerminalConflictError(workflowId, runId, current.status);
698
- }
699
- active.lifecycle = effectiveLifecycle(currentLifecycle, lifecycle);
700
- this.#activeRuns.set(activeKey, active);
701
- });
702
- let run;
703
- let result;
958
+ const active = {};
959
+ if (this.#activeRuns.has(activeKey))
960
+ throw new RunTerminalConflictError(workflowId, runId, 'running');
961
+ this.#activeRuns.set(activeKey, active);
962
+ let provenance;
963
+ let engineEntered = false;
964
+ let outcomeReadStarted = false;
704
965
  try {
705
- if (options.prepareExecution) {
706
- const preparationValues = structuredClone(Object.fromEntries(requestContext.entries()));
707
- await options.prepareExecution(new RequestContext(Object.entries(preparationValues)));
708
- }
709
- // Same host pubsub identity as start() (CI-M-002-002) — see the note
710
- // there; undefined stays byte-identical to `createRun({ runId })`.
711
- run = await workflow.createRun({ runId, pubsub: this.#pubsub });
712
- await this.#withLifecycleLock(workflowId, runId, async () => {
713
- const current = await this.#loadSnapshot(workflowId, runId);
714
- if (!current)
715
- throw new UnknownRunError(workflowId, runId);
966
+ const source = await this.#captureWorkflowStorage(workflow);
967
+ active.source = source;
968
+ const state = await this.#workflowState(workflow, runId, true);
969
+ if (!state)
970
+ throw new UnknownRunError(workflowId, runId);
971
+ if (state.isFromInMemory)
972
+ throw new RunStateUnreadableError(workflowId, runId);
973
+ const prior = runProvenance(state);
974
+ if (proof &&
975
+ (prior?.version !== 2 ||
976
+ prior.startToken !== proof.startToken ||
977
+ source.tablePrefix !== proof.tablePrefix))
978
+ throw new RunStateUnreadableError(workflowId, runId);
979
+ if (state.status !== 'suspended')
980
+ throw new RunNotSuspendedError(workflowId, runId, state.status);
981
+ const prepared = await this.#trustedResumePreparation(workflowId, runId, state, options.step, options.requestedBy, options.requestedByKind, options.deadlineMs, options.economicOperations);
982
+ provenance = prepared.provenance;
983
+ const { requestContext, lifecycle, nextCounts } = prepared;
984
+ active.requestContext = requestContext;
985
+ active.lifecycle = lifecycle;
986
+ const check = async () => {
987
+ const current = await this.#assertRetainedResume(source, workflowId, runId, prior, proof);
716
988
  const currentLifecycle = lifecycleFromRequestContext(current.requestContext);
717
989
  if (currentLifecycle?.terminal ||
718
990
  currentLifecycle?.transitionIntent ||
719
- this.#activeRuns.get(activeKey) !== active) {
991
+ this.#activeRuns.get(activeKey) !== active)
720
992
  throw new RunTerminalConflictError(workflowId, runId, current.status);
721
- }
722
993
  active.lifecycle = effectiveLifecycle(currentLifecycle, active.lifecycle);
994
+ };
995
+ await this.#withLifecycleLock(workflowId, runId, check);
996
+ if (options.prepareExecution) {
997
+ const values = structuredClone(Object.fromEntries(requestContext.entries()));
998
+ await options.prepareExecution(new RequestContext(Object.entries(values)));
999
+ await this.#withLifecycleLock(workflowId, runId, check);
1000
+ }
1001
+ const run = await workflow.createRun({ runId, pubsub: this.#pubsub });
1002
+ const { executionPromise } = await this.#withLifecycleLock(workflowId, runId, async () => {
1003
+ await check();
723
1004
  active.run = run;
1005
+ engineEntered = true;
1006
+ return {
1007
+ executionPromise: run.resume({
1008
+ step: options.step,
1009
+ resumeData: options.resumeData,
1010
+ requestContext,
1011
+ }),
1012
+ };
724
1013
  });
725
- result = await run.resume({
726
- step: options.step,
727
- resumeData: options.resumeData,
728
- requestContext,
729
- });
1014
+ const result = await executionPromise;
1015
+ await this.#reconcileTerminalState(workflowId, runId, result, requestContext, source, proof);
1016
+ if (provenance.version === 2) {
1017
+ const execution = runExecutionIdentityFor({ tablePrefix: source.tablePrefix, workflowId, runId }, provenance);
1018
+ outcomeReadStarted = true;
1019
+ const selected = await this.#completedStartState(source, execution, provenance);
1020
+ await this.#settleStartReservation(selected);
1021
+ return selected.summary;
1022
+ }
1023
+ return summarize(runId, result, nextCounts, provenance.requestedBy, provenance.requestedByKind, lifecycle?.deadlineAt);
730
1024
  }
731
1025
  catch (error) {
732
- const recovered = await this.#summaryForAttempt(workflow, runId, provenance.attemptToken);
733
- if (recovered)
734
- return recovered;
735
- // No authoritative snapshot carries this attempt token: the run stayed
736
- // on its prior suspension, so neither requester nor ordinal advances.
1026
+ if (engineEntered && provenance && !outcomeReadStarted) {
1027
+ const recovered = await this.#summaryForAttempt(workflow, runId, provenance);
1028
+ if (recovered)
1029
+ return recovered;
1030
+ }
737
1031
  throw asClientError(error) ?? error;
738
1032
  }
739
1033
  finally {
740
- if (this.#activeRuns.get(activeKey) === active) {
1034
+ if (this.#activeRuns.get(activeKey) === active)
741
1035
  this.#activeRuns.delete(activeKey);
742
- }
743
- }
744
- // A re-suspension produced by this resume carries the incremented ordinal
745
- // in the same authoritative snapshot as the new workflow state.
746
- const summary = summarize(run.runId, result, nextCounts, provenance.requestedBy, provenance.requestedByKind, lifecycle?.deadlineAt);
747
- try {
748
- await this.#reconcileTerminalState(workflowId, run.runId, result, requestContext);
749
1036
  }
750
- catch (error) {
751
- const recovered = await this.#summaryForAttempt(workflow, runId, provenance.attemptToken);
752
- if (recovered)
753
- return recovered;
754
- throw error;
755
- }
756
- return summary;
757
1037
  });
758
1038
  }
759
1039
  /** Idempotently cancel a live run from its persisted snapshot. */
@@ -768,9 +1048,16 @@ export class RunnerRuntime {
768
1048
  async cancelActiveExecution(workflowId, runId, intendedStatus, replayPrincipals, cas, now = Date.now()) {
769
1049
  this.#getWorkflow(workflowId);
770
1050
  const prepared = await this.#withLifecycleLock(workflowId, runId, async () => {
771
- const state = await this.#loadSnapshot(workflowId, runId);
1051
+ const source = this.#activeRuns.get(this.#runKey(workflowId, runId))?.source ??
1052
+ (await this.#captureWorkflowStorage(this.#getWorkflow(workflowId)));
1053
+ const state = await source.load.call(source.workflows, {
1054
+ workflowName: workflowId,
1055
+ runId,
1056
+ });
772
1057
  if (!state)
773
1058
  throw new UnknownRunError(workflowId, runId);
1059
+ if (state.runId !== runId)
1060
+ throw new RunStateUnreadableError(workflowId, runId);
774
1061
  const key = this.#runKey(workflowId, runId);
775
1062
  const active = this.#activeRuns.get(key);
776
1063
  const lifecycle = effectiveLifecycle(lifecycleFromRequestContext(state.requestContext), active?.lifecycle);
@@ -811,7 +1098,7 @@ export class RunnerRuntime {
811
1098
  const principals = canonicalReplayPrincipals(replayPrincipals);
812
1099
  const intent = {
813
1100
  ...(lifecycle ?? { version: 1, revision: 0 }),
814
- revision: (lifecycle?.revision ?? 0) + 1,
1101
+ revision: nextLifecycleRevision(lifecycle?.revision ?? 0),
815
1102
  transitionIntent: {
816
1103
  status: intendedStatus,
817
1104
  requestedAt: now,
@@ -824,7 +1111,7 @@ export class RunnerRuntime {
824
1111
  : {}),
825
1112
  },
826
1113
  };
827
- await this.#persistLifecycle(workflowId, runId, state, intent, now);
1114
+ await this.#persistLifecycle(workflowId, runId, state, intent, now, source);
828
1115
  if (active) {
829
1116
  active.lifecycle = intent;
830
1117
  active.requestContext?.set(RUN_LIFECYCLE_CONTEXT_KEY, intent);
@@ -869,9 +1156,15 @@ export class RunnerRuntime {
869
1156
  async #transitionTerminal(workflowId, runId, status, now, cas, replayPrincipals, replayingPrincipal) {
870
1157
  this.#getWorkflow(workflowId);
871
1158
  return this.#withRunLock(workflowId, runId, async () => {
872
- const state = await this.#loadSnapshot(workflowId, runId);
1159
+ const source = await this.#captureWorkflowStorage(this.#getWorkflow(workflowId));
1160
+ const state = await source.load.call(source.workflows, {
1161
+ workflowName: workflowId,
1162
+ runId,
1163
+ });
873
1164
  if (!state)
874
1165
  throw new UnknownRunError(workflowId, runId);
1166
+ if (state.runId !== runId)
1167
+ throw new RunStateUnreadableError(workflowId, runId);
875
1168
  const lifecycle = lifecycleFromRequestContext(state.requestContext);
876
1169
  if (lifecycle?.terminal) {
877
1170
  if (replayingPrincipal &&
@@ -880,19 +1173,12 @@ export class RunnerRuntime {
880
1173
  throw new UnknownRunError(workflowId, runId);
881
1174
  }
882
1175
  return {
883
- summary: await this.#summaryAfterPersist(workflowId, runId),
1176
+ summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
884
1177
  transitioned: false,
885
1178
  casMatched: cas === undefined ||
886
1179
  (lifecycle.terminal.status === 'timed_out' &&
887
1180
  lifecycle.deadlineAt === cas.expectedDeadlineAt),
888
- cleanup: {
889
- revision: lifecycle.revision,
890
- status: lifecycle.terminal.status,
891
- cleanupCompleted: lifecycle.terminal.cleanupCompletedAt !== undefined,
892
- ...(lifecycle.scheduleDispatch
893
- ? { scheduleDispatch: lifecycle.scheduleDispatch }
894
- : {}),
895
- },
1181
+ cleanup: terminalCleanupFor(lifecycle),
896
1182
  };
897
1183
  }
898
1184
  const transitionIntent = lifecycle?.transitionIntent;
@@ -908,7 +1194,7 @@ export class RunnerRuntime {
908
1194
  lifecycle.deadlineAt === undefined ||
909
1195
  lifecycle.deadlineAt > now)) {
910
1196
  return {
911
- summary: await this.#summaryAfterPersist(workflowId, runId),
1197
+ summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
912
1198
  transitioned: false,
913
1199
  casMatched: false,
914
1200
  cleanup: {
@@ -934,9 +1220,6 @@ export class RunnerRuntime {
934
1220
  !(currentStatus === 'canceled' && abortIntent === status)) {
935
1221
  throw new RunTerminalConflictError(workflowId, runId, currentStatus);
936
1222
  }
937
- const error = status === 'cancelled'
938
- ? { code: 'CANCELLED', message: 'run was cancelled' }
939
- : { code: 'TIMED_OUT', message: 'run deadline expired' };
940
1223
  const provenance = runProvenance(state);
941
1224
  const fallbackPrincipal = provenance?.requestedBy && provenance.requestedByKind
942
1225
  ? {
@@ -946,48 +1229,22 @@ export class RunnerRuntime {
946
1229
  : { kind: 'system', id: 'flowsafe-system' };
947
1230
  const principals = canonicalReplayPrincipals(replayPrincipals ??
948
1231
  transitionIntent?.replayPrincipals ?? [fallbackPrincipal]);
949
- const lifecycleBase = lifecycle
950
- ? Object.fromEntries(Object.entries(lifecycle).filter(([key]) => key !== 'transitionIntent'))
951
- : { version: 1, revision: 0 };
952
- const next = {
953
- ...lifecycleBase,
954
- version: 1,
955
- revision: (lifecycle?.revision ?? 0) + 1,
956
- terminal: {
957
- status,
958
- error,
959
- transitionedAt: now,
960
- replayPrincipals: principals,
961
- },
962
- };
1232
+ const next = projectTerminalLifecycle(lifecycle, status, now, principals);
963
1233
  await this.#persistLifecycle(workflowId, runId, {
964
1234
  ...state,
965
- status: status,
966
- result: undefined,
1235
+ ...terminalStateFields(status),
967
1236
  error: {
968
1237
  name: status === 'cancelled' ? 'RunCancelledError' : 'RunTimedOutError',
969
- message: error.message,
1238
+ message: next.terminal.error.message,
970
1239
  },
971
- suspendedPaths: {},
972
- waitingPaths: {},
973
- resumeLabels: {},
974
- activePaths: [],
975
- activeStepsPath: {},
976
1240
  timestamp: now,
977
- }, next, now);
1241
+ }, next, now, source);
978
1242
  this.#terminalAbortIntents.delete(this.#runKey(workflowId, runId));
979
1243
  return {
980
- summary: await this.#summaryAfterPersist(workflowId, runId),
1244
+ summary: await this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state)),
981
1245
  transitioned: true,
982
1246
  casMatched: true,
983
- cleanup: {
984
- revision: next.revision,
985
- status,
986
- cleanupCompleted: false,
987
- ...(next.scheduleDispatch
988
- ? { scheduleDispatch: next.scheduleDispatch }
989
- : {}),
990
- },
1247
+ cleanup: terminalCleanupFor(next),
991
1248
  };
992
1249
  });
993
1250
  }
@@ -995,29 +1252,35 @@ export class RunnerRuntime {
995
1252
  async completeTerminalCleanup(workflowId, runId, expectedRevision, now = Date.now()) {
996
1253
  this.#getWorkflow(workflowId);
997
1254
  return this.#withRunLock(workflowId, runId, async () => {
998
- const state = await this.#loadSnapshot(workflowId, runId);
1255
+ const source = await this.#captureWorkflowStorage(this.#getWorkflow(workflowId));
1256
+ const state = await source.load.call(source.workflows, {
1257
+ workflowName: workflowId,
1258
+ runId,
1259
+ });
999
1260
  if (!state)
1000
1261
  throw new UnknownRunError(workflowId, runId);
1262
+ if (state.runId !== runId)
1263
+ throw new RunStateUnreadableError(workflowId, runId);
1001
1264
  const lifecycle = lifecycleFromRequestContext(state.requestContext);
1002
1265
  if (!lifecycle?.terminal) {
1003
1266
  throw new RunTerminalConflictError(workflowId, runId, state.status);
1004
1267
  }
1005
1268
  if (lifecycle.terminal.cleanupCompletedAt !== undefined) {
1006
- return this.#summaryAfterPersist(workflowId, runId);
1269
+ return this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state));
1007
1270
  }
1008
1271
  if (lifecycle.revision !== expectedRevision) {
1009
1272
  throw new Error('run terminal cleanup CAS no longer matches');
1010
1273
  }
1011
1274
  const next = {
1012
1275
  ...lifecycle,
1013
- revision: lifecycle.revision + 1,
1276
+ revision: nextLifecycleRevision(lifecycle.revision),
1014
1277
  terminal: {
1015
1278
  ...lifecycle.terminal,
1016
1279
  cleanupCompletedAt: now,
1017
1280
  },
1018
1281
  };
1019
- await this.#persistLifecycle(workflowId, runId, state, next, now);
1020
- return this.#summaryAfterPersist(workflowId, runId);
1282
+ await this.#persistLifecycle(workflowId, runId, state, next, now, source);
1283
+ return this.#summaryAfterPersist(workflowId, runId, source, runProvenance(state));
1021
1284
  });
1022
1285
  }
1023
1286
  /**
@@ -1052,8 +1315,8 @@ export class RunnerRuntime {
1052
1315
  * that did not reach storage. `null` still means the read SUCCEEDED and
1053
1316
  * found nothing.
1054
1317
  *
1055
- * status() stays the projection read, unchanged for every existing caller:
1056
- * a summary is still the best answer an HTTP status route can give.
1318
+ * Both status readers refuse a valid v2 pending row before lifecycle
1319
+ * projection; it has no durable execution outcome yet.
1057
1320
  */
1058
1321
  async authoritativeStatus(workflowId, runId) {
1059
1322
  const workflow = this.#getWorkflow(workflowId);
@@ -1065,42 +1328,360 @@ export class RunnerRuntime {
1065
1328
  }
1066
1329
  return this.#summaryFromState(runId, state);
1067
1330
  }
1068
- /**
1069
- * Reconcile an interrupted start against the token stored in the
1070
- * authoritative workflow snapshot. Mastra's `createRun()` first persists a
1071
- * tokenless pending shell; if no executed snapshot replaced it, the shell is
1072
- * abandoned and must not become a successful FlowSafe run.
1073
- */
1074
- async recoverStartAttempt(workflowId, runId, attemptToken) {
1075
- if (!isPathSafeId(attemptToken)) {
1076
- throw new InvalidRunRequestError('attemptToken is malformed');
1331
+ async authoritativeStartState(workflowId, runId, options) {
1332
+ const includeLegacy = options?.includeLegacy === true;
1333
+ const { state } = await this.#observeStartState(workflowId, runId);
1334
+ if (state?.kind === 'legacy' && !includeLegacy)
1335
+ throw new RunStateUnreadableError(workflowId, runId);
1336
+ return state;
1337
+ }
1338
+ async #captureWorkflowStorage(workflow) {
1339
+ const workflows = await workflow.mastra
1340
+ ?.getStorage()
1341
+ ?.getStore('workflows');
1342
+ if (!workflows)
1343
+ throw new Error('workflow storage is unavailable');
1344
+ const methods = {
1345
+ workflows,
1346
+ read: workflows.getWorkflowRunById,
1347
+ load: workflows.loadWorkflowSnapshot,
1348
+ persist: workflows.persistWorkflowSnapshot,
1349
+ };
1350
+ const capability = workflows[FENCED_WORKFLOW_STORAGE];
1351
+ if (capability === undefined) {
1352
+ if (this.#executionFence)
1353
+ throw new Error('fenced workflow storage capability is unavailable');
1354
+ return { ...methods, storage: 'unfenced', tablePrefix: null };
1077
1355
  }
1356
+ if (capability === null || typeof capability !== 'object')
1357
+ throw new Error('workflow capability is malformed');
1358
+ const { database, tablePrefix: prefix, readSnapshot, withInitialAdmission: admit, terminalizeInitialAdmission: terminalize, } = capability;
1359
+ if (typeof prefix !== 'string' ||
1360
+ typeof readSnapshot !== 'function' ||
1361
+ typeof admit !== 'function' ||
1362
+ typeof terminalize !== 'function' ||
1363
+ !database ||
1364
+ typeof database.prepare !== 'function' ||
1365
+ typeof database.batch !== 'function')
1366
+ throw new Error('workflow capability is malformed');
1367
+ validateTablePrefix(prefix);
1368
+ if ((this.#executionFence && !this.#executionFence.usesDatabase(database)) ||
1369
+ (this.#startIdempotency && !this.#startIdempotency.usesDatabase(database)))
1370
+ throw new Error('workflow storage binding disagrees with runtime stores');
1371
+ return {
1372
+ ...methods,
1373
+ storage: 'd1',
1374
+ tablePrefix: prefix.toLowerCase(),
1375
+ capability,
1376
+ database,
1377
+ readSnapshot,
1378
+ admit,
1379
+ terminalize,
1380
+ };
1381
+ }
1382
+ async #observeStartState(workflowId, runId) {
1383
+ if (!isPathSafeId(workflowId))
1384
+ throw new InvalidRunRequestError('workflowId is malformed');
1385
+ if (!isPathSafeId(runId))
1386
+ throw new InvalidRunRequestError('runId is malformed');
1078
1387
  const workflow = this.#getWorkflow(workflowId);
1079
- return this.#withRunLock(workflowId, runId, async () => {
1080
- const state = await this.#workflowState(workflow, runId);
1081
- if (!state)
1082
- return null;
1083
- // A read that did not reach storage cannot settle an interrupted start.
1084
- // The in-memory fallback carries no requestContext, so the token below
1085
- // can never match, and the 'pending' status it reports for a run that
1086
- // has not been resumed falls straight into the delete branch — which
1087
- // would destroy a live row and its snapshot behind a lagging read. The
1088
- // throw defers only a no-op: under the marker either the row exists, and
1089
- // deleting it destroys live state, or it does not, and the delete does
1090
- // nothing. A genuinely abandoned shell on an isolate that holds no Run
1091
- // carries no marker and converges here exactly as before.
1092
- if (state.isFromInMemory === true) {
1093
- throw new RunStateUnreadableError(workflowId, runId);
1388
+ try {
1389
+ const source = await this.#captureWorkflowStorage(workflow);
1390
+ return {
1391
+ source,
1392
+ state: await this.#readStartState(source, workflowId, runId),
1393
+ };
1394
+ }
1395
+ catch (cause) {
1396
+ if (cause instanceof RunStateUnreadableError)
1397
+ throw cause;
1398
+ throw new RunStateUnreadableError(workflowId, runId, { cause });
1399
+ }
1400
+ }
1401
+ #projectD1StartState(source, workflowId, runId, observed) {
1402
+ for (const key of [
1403
+ 'tablePrefix',
1404
+ 'workflowId',
1405
+ 'runId',
1406
+ 'resourceId',
1407
+ 'snapshot',
1408
+ 'createdAt',
1409
+ 'updatedAt',
1410
+ ]) {
1411
+ if (!Object.hasOwn(observed, key))
1412
+ throw new Error('workflow snapshot field is missing');
1413
+ }
1414
+ const { tablePrefix, workflowId: storedWorkflow, runId: storedRun, resourceId, snapshot, createdAt, updatedAt, } = observed;
1415
+ if (tablePrefix !== source.tablePrefix ||
1416
+ storedWorkflow !== workflowId ||
1417
+ storedRun !== runId ||
1418
+ (resourceId !== null && typeof resourceId !== 'string') ||
1419
+ typeof snapshot !== 'string' ||
1420
+ typeof createdAt !== 'string' ||
1421
+ typeof updatedAt !== 'string')
1422
+ throw new Error('workflow snapshot fields are malformed');
1423
+ const raw = Object.freeze({
1424
+ tablePrefix,
1425
+ workflowId,
1426
+ runId,
1427
+ resourceId,
1428
+ snapshot,
1429
+ createdAt,
1430
+ updatedAt,
1431
+ });
1432
+ return this.#projectStartState({ storage: 'd1', tablePrefix, raw }, workflowId, runId, JSON.parse(snapshot), createdAt, updatedAt);
1433
+ }
1434
+ async #readStartState(source, workflowId, runId) {
1435
+ try {
1436
+ let state;
1437
+ if (source.storage === 'd1') {
1438
+ const row = await source.readSnapshot.call(source.capability, {
1439
+ workflowId,
1440
+ runId,
1441
+ });
1442
+ state =
1443
+ row === undefined
1444
+ ? null
1445
+ : this.#projectD1StartState(source, workflowId, runId, row);
1094
1446
  }
1095
- const provenance = runProvenance(state);
1096
- if (provenance?.startToken === attemptToken) {
1097
- return summarizeState(runId, state, new Map(provenance.resumeCounts), provenance.requestedBy, provenance.requestedByKind);
1447
+ else {
1448
+ const row = await source.read.call(source.workflows, {
1449
+ workflowName: workflowId,
1450
+ runId,
1451
+ });
1452
+ if (row === null)
1453
+ return null;
1454
+ const { workflowName, runId: storedRun, snapshot, createdAt, updatedAt, } = row;
1455
+ if (workflowName !== workflowId || storedRun !== runId)
1456
+ throw new Error('workflow snapshot selector disagrees with the request');
1457
+ state = this.#projectStartState(source, workflowId, runId, typeof snapshot === 'string'
1458
+ ? JSON.parse(snapshot)
1459
+ : structuredClone(snapshot), createdAt, updatedAt);
1098
1460
  }
1099
- if (state.status === 'pending' && provenance === undefined) {
1100
- await workflow.deleteWorkflowRunById(runId);
1101
- return null;
1461
+ return state;
1462
+ }
1463
+ catch (cause) {
1464
+ throw new RunStateUnreadableError(workflowId, runId, { cause });
1465
+ }
1466
+ }
1467
+ #projectStartState(physical, workflowId, runId, decoded, createdAt, updatedAt) {
1468
+ if (decoded === null ||
1469
+ typeof decoded !== 'object' ||
1470
+ Array.isArray(decoded))
1471
+ throw new Error('workflow snapshot is malformed');
1472
+ const snapshot = decoded;
1473
+ if (snapshot.runId !== runId || !isRunStatus(snapshot.status))
1474
+ throw new Error('workflow snapshot identity or status is malformed');
1475
+ for (const value of [
1476
+ snapshot.requestContext,
1477
+ snapshot.context,
1478
+ snapshot.suspendedPaths,
1479
+ ]) {
1480
+ if (value !== undefined &&
1481
+ (value === null || typeof value !== 'object' || Array.isArray(value)))
1482
+ throw new Error('workflow snapshot container is malformed');
1483
+ }
1484
+ const provenance = runProvenance(snapshot);
1485
+ lifecycleFromRequestContext(snapshot.requestContext);
1486
+ for (const value of [createdAt, updatedAt]) {
1487
+ if (!(value instanceof Date) && typeof value !== 'string')
1488
+ throw new Error('workflow snapshot timestamp is malformed');
1489
+ if (!Number.isFinite(new Date(value).getTime()))
1490
+ throw new Error('workflow snapshot timestamp is malformed');
1491
+ }
1492
+ if (provenance?.version !== 2)
1493
+ return {
1494
+ kind: 'legacy',
1495
+ provenanceVersion: provenance?.version,
1496
+ address: Object.freeze({
1497
+ tablePrefix: physical.tablePrefix,
1498
+ workflowId,
1499
+ runId,
1500
+ }),
1501
+ snapshot,
1502
+ summary: summaryFromSelectedSnapshot(runId, snapshot, { createdAt: toIso(createdAt), updatedAt: toIso(updatedAt) }, provenance),
1503
+ };
1504
+ const execution = runExecutionIdentityFor({ tablePrefix: physical.tablePrefix, workflowId, runId }, provenance);
1505
+ const state = snapshot.status === 'pending'
1506
+ ? { kind: 'initial', snapshot, provenance }
1507
+ : {
1508
+ kind: 'result',
1509
+ snapshot,
1510
+ provenance,
1511
+ summary: summaryFromSelectedSnapshot(runId, snapshot, { createdAt: toIso(createdAt), updatedAt: toIso(updatedAt) }, provenance),
1512
+ };
1513
+ return physical.storage === 'd1'
1514
+ ? {
1515
+ ...state,
1516
+ storage: 'd1',
1517
+ execution: Object.freeze({
1518
+ ...execution,
1519
+ tablePrefix: physical.tablePrefix,
1520
+ }),
1521
+ raw: physical.raw,
1102
1522
  }
1103
- throw new Error(`run '${runId}' snapshot belongs to another start attempt`);
1523
+ : {
1524
+ ...state,
1525
+ storage: 'unfenced',
1526
+ execution: Object.freeze({ ...execution, tablePrefix: null }),
1527
+ };
1528
+ }
1529
+ /** @internal Recover only after the exact owning execution has unwound. */
1530
+ async recoverStartAttempt(value, recovery) {
1531
+ const execution = normalizeD1RunExecutionIdentity(value);
1532
+ const { attemptToken, isOwnerQuiescent, startReservation: suppliedClaim, expectedTarget: suppliedTarget, } = recovery;
1533
+ let expectedTarget;
1534
+ if (suppliedTarget !== undefined) {
1535
+ if (suppliedTarget === null ||
1536
+ typeof suppliedTarget !== 'object' ||
1537
+ Array.isArray(suppliedTarget))
1538
+ throw new InvalidRunRequestError('start recovery target is malformed');
1539
+ const { kind } = suppliedTarget;
1540
+ if (kind === 'workflow')
1541
+ expectedTarget = Object.freeze({ kind });
1542
+ else if (kind === 'agent') {
1543
+ const { owner, id, threadId, threaded } = suppliedTarget;
1544
+ const identity = normalizeStartIdentity({
1545
+ owner,
1546
+ target: { kind, id, threadId },
1547
+ });
1548
+ if (typeof threaded !== 'boolean')
1549
+ throw new InvalidRunRequestError('start recovery target is malformed');
1550
+ expectedTarget = Object.freeze({
1551
+ kind,
1552
+ id: identity.target.id,
1553
+ threadId,
1554
+ owner: identity.owner,
1555
+ threaded,
1556
+ });
1557
+ }
1558
+ else
1559
+ throw new InvalidRunRequestError('start recovery target is malformed');
1560
+ }
1561
+ const assertExpectedTarget = (state) => {
1562
+ if (!expectedTarget)
1563
+ return;
1564
+ const { startIdentity, agentStart } = state.provenance;
1565
+ if (expectedTarget.kind === 'workflow') {
1566
+ if (startIdentity?.target.kind !== 'workflow' ||
1567
+ startIdentity.target.id !== state.execution.workflowId ||
1568
+ agentStart !== undefined)
1569
+ throw new Error('recovery workflow target disagrees with execution');
1570
+ }
1571
+ else if (startIdentity?.target.kind !== 'agent' ||
1572
+ startIdentity.target.id !== expectedTarget.id ||
1573
+ startIdentity.target.threadId !== expectedTarget.threadId ||
1574
+ startIdentity.owner.kind !== expectedTarget.owner.kind ||
1575
+ startIdentity.owner.id !== expectedTarget.owner.id ||
1576
+ agentStart?.threaded !== expectedTarget.threaded)
1577
+ throw new Error('recovery agent target disagrees with execution');
1578
+ };
1579
+ const claim = suppliedClaim === undefined
1580
+ ? undefined
1581
+ : captureReservation(suppliedClaim, 'started');
1582
+ if (!isPathSafeId(attemptToken) || typeof isOwnerQuiescent !== 'function')
1583
+ throw new InvalidRunRequestError('start recovery authority is malformed');
1584
+ if (claim && !this.#startIdempotency)
1585
+ throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
1586
+ const { workflowId, runId } = execution;
1587
+ const workflow = this.#getWorkflow(workflowId);
1588
+ return this.#withRunLock(workflowId, runId, () => this.#withLifecycleLock(workflowId, runId, async () => {
1589
+ try {
1590
+ if (this.isRunActive(workflowId, runId))
1591
+ throw new Error('run owner is not quiescent');
1592
+ const source = await this.#captureWorkflowStorage(workflow);
1593
+ if (this.isRunActive(workflowId, runId) ||
1594
+ (await Reflect.apply(isOwnerQuiescent, undefined, [])) !== true ||
1595
+ this.isRunActive(workflowId, runId))
1596
+ throw new Error('run owner is not quiescent');
1597
+ const state = await this.#readStartState(source, workflowId, runId);
1598
+ if (state?.kind === 'legacy')
1599
+ throw new RunStateUnreadableError(workflowId, runId);
1600
+ if (source.storage !== 'd1' ||
1601
+ source.tablePrefix !== execution.tablePrefix)
1602
+ throw new Error('recovery source disagrees with execution');
1603
+ if (!state)
1604
+ return null;
1605
+ if (!sameExecution(state.execution, execution))
1606
+ throw new Error('recovery generation disagrees with execution');
1607
+ assertExpectedTarget(state);
1608
+ if (claim) {
1609
+ if (!state.provenance.startIdentity)
1610
+ throw new Error('recovery lacks logical identity');
1611
+ assertClaimIdentity(claim, {
1612
+ ...state.provenance.startIdentity,
1613
+ runId,
1614
+ });
1615
+ }
1616
+ let selected = state;
1617
+ let transitioned = false;
1618
+ let cleanup = terminalCleanupFor(lifecycleFromRequestContext(state.snapshot.requestContext));
1619
+ if (state.kind === 'initial') {
1620
+ if (!this.#executionFence ||
1621
+ state.storage !== 'd1' ||
1622
+ state.provenance.initialAdmission !== true ||
1623
+ state.provenance.attemptToken !== attemptToken ||
1624
+ state.provenance.resumeCounts.length !== 0)
1625
+ throw new RunStartPendingError();
1626
+ const result = await source.terminalize.call(source.capability, {
1627
+ expected: state.raw,
1628
+ execution,
1629
+ attemptToken,
1630
+ nowMs: Date.now(),
1631
+ });
1632
+ if (result.kind === 'conflict')
1633
+ throw new Error('initial terminalization conflicts');
1634
+ const projected = this.#projectD1StartState(source, workflowId, runId, result.row);
1635
+ if (projected.kind !== 'result' ||
1636
+ !sameExecution(projected.execution, execution))
1637
+ throw new Error('terminalization result is unresolved');
1638
+ selected = projected;
1639
+ assertExpectedTarget(selected);
1640
+ transitioned = result.kind === 'terminalized';
1641
+ cleanup = result.cleanup;
1642
+ }
1643
+ if (selected.kind !== 'result')
1644
+ throw new RunStartPendingError();
1645
+ if (isTerminalRunStatus(selected.summary.status))
1646
+ await this.settleStartExecution(selected, claim);
1647
+ return cleanup
1648
+ ? {
1649
+ kind: 'lifecycle',
1650
+ transition: {
1651
+ summary: selected.summary,
1652
+ transitioned,
1653
+ casMatched: true,
1654
+ cleanup,
1655
+ },
1656
+ }
1657
+ : { kind: 'ordinary', summary: selected.summary };
1658
+ }
1659
+ catch (cause) {
1660
+ if (cause instanceof RunStartPendingError ||
1661
+ cause instanceof RunStateUnreadableError)
1662
+ throw cause;
1663
+ throw new ExecutionFenceUnreadableError('run start recovery is unresolved', { cause });
1664
+ }
1665
+ }));
1666
+ }
1667
+ /** @internal Settle the exact selected terminal generation before managed cleanup. */
1668
+ async settleStartExecution(state, originalClaim) {
1669
+ const claim = originalClaim === undefined
1670
+ ? undefined
1671
+ : captureReservation(originalClaim, 'started');
1672
+ if (state.kind !== 'result' || !isTerminalRunStatus(state.summary.status))
1673
+ throw new RunStartPendingError();
1674
+ const identity = state.provenance.startIdentity;
1675
+ if (claim) {
1676
+ if (!identity || !this.#startIdempotency)
1677
+ throw new ExecutionFenceUnreadableError('run start settlement is unresolved');
1678
+ assertClaimIdentity(claim, { ...identity, runId: state.execution.runId });
1679
+ }
1680
+ if (!identity || !this.#startIdempotency)
1681
+ return;
1682
+ await this.#startIdempotency.settleExecution({
1683
+ ...state.execution,
1684
+ ...identity,
1104
1685
  });
1105
1686
  }
1106
1687
  // A provider crash propagates (fail loud): silently starting the leg with
@@ -1190,10 +1771,12 @@ export class RunnerRuntime {
1190
1771
  const priorCounts = new Map(storedProvenance?.resumeCounts ?? []);
1191
1772
  const nextCounts = new Map(priorCounts);
1192
1773
  if (stepKey !== undefined) {
1193
- nextCounts.set(stepKey, (nextCounts.get(stepKey) ?? 0) + 1);
1774
+ nextCounts.set(stepKey, nextResumeCount(nextCounts.get(stepKey) ?? 0));
1194
1775
  }
1195
1776
  const provenance = {
1196
- version: 1,
1777
+ ...(storedProvenance?.version === 2
1778
+ ? storedProvenance
1779
+ : { version: 1 }),
1197
1780
  ...(requester === undefined
1198
1781
  ? {}
1199
1782
  : { requestedBy: requester, requestedByKind: requesterKind }),
@@ -1208,7 +1791,7 @@ export class RunnerRuntime {
1208
1791
  ? storedLifecycle
1209
1792
  : {
1210
1793
  ...(storedLifecycle ?? { version: 1, revision: 0 }),
1211
- revision: (storedLifecycle?.revision ?? 0) + 1,
1794
+ revision: nextLifecycleRevision(storedLifecycle?.revision ?? 0),
1212
1795
  ...(replacementDeadline === undefined
1213
1796
  ? {}
1214
1797
  : { deadlineAt: replacementDeadline }),
@@ -1231,21 +1814,14 @@ export class RunnerRuntime {
1231
1814
  lifecycle,
1232
1815
  };
1233
1816
  }
1234
- #workflowState(workflow, runId) {
1235
- return workflow.getWorkflowRunById(runId, { fields: RUN_STATE_FIELDS });
1236
- }
1237
- async #loadSnapshot(workflowId, runId) {
1238
- const workflows = await this.#storage.getStore('workflows');
1239
- if (!workflows) {
1240
- throw new Error('RunnerRuntime: workflows storage is unavailable');
1241
- }
1242
- return workflows.loadWorkflowSnapshot({ workflowName: workflowId, runId });
1817
+ #workflowState(workflow, runId, withNestedWorkflows = false) {
1818
+ return workflow.getWorkflowRunById(runId, {
1819
+ fields: RUN_STATE_FIELDS,
1820
+ withNestedWorkflows,
1821
+ });
1243
1822
  }
1244
- async #persistLifecycle(workflowId, runId, state, lifecycle, now) {
1245
- const workflows = await this.#storage.getStore('workflows');
1246
- if (!workflows) {
1247
- throw new Error('RunnerRuntime: workflows storage is unavailable');
1248
- }
1823
+ async #persistLifecycle(workflowId, runId, state, lifecycle, now, source) {
1824
+ const workflows = source.workflows;
1249
1825
  const persisted = {
1250
1826
  ...state,
1251
1827
  requestContext: {
@@ -1254,7 +1830,7 @@ export class RunnerRuntime {
1254
1830
  },
1255
1831
  timestamp: now,
1256
1832
  };
1257
- await workflows.persistWorkflowSnapshot({
1833
+ await source.persist.call(workflows, {
1258
1834
  workflowName: workflowId,
1259
1835
  runId,
1260
1836
  snapshot: persisted,
@@ -1262,7 +1838,13 @@ export class RunnerRuntime {
1262
1838
  });
1263
1839
  return persisted;
1264
1840
  }
1265
- async #summaryAfterPersist(workflowId, runId) {
1841
+ async #summaryAfterPersist(workflowId, runId, source, expected) {
1842
+ if (expected?.version === 2) {
1843
+ const selected = await this.#completedStartState(source, runExecutionIdentityFor({ tablePrefix: source.tablePrefix, workflowId, runId }, expected), expected);
1844
+ if (isTerminalRunStatus(selected.summary.status))
1845
+ await this.settleStartExecution(selected);
1846
+ return selected.summary;
1847
+ }
1266
1848
  const state = await this.#workflowState(this.#getWorkflow(workflowId), runId);
1267
1849
  if (!state)
1268
1850
  throw new UnknownRunError(workflowId, runId);
@@ -1270,33 +1852,67 @@ export class RunnerRuntime {
1270
1852
  }
1271
1853
  #summaryFromState(runId, state) {
1272
1854
  const provenance = runProvenance(state);
1855
+ if (state.status === 'pending' && provenance?.version === 2)
1856
+ throw new RunStartPendingError();
1273
1857
  return summarizeState(runId, state, provenance ? new Map(provenance.resumeCounts) : undefined, provenance?.requestedBy, provenance?.requestedByKind);
1274
1858
  }
1275
- async #summaryForAttempt(workflow, runId, attemptToken) {
1276
- const persisted = await this.#workflowState(workflow, runId);
1277
- if (!persisted)
1278
- return undefined;
1279
- const provenance = runProvenance(persisted);
1280
- if (provenance?.attemptToken !== attemptToken)
1859
+ async #summaryForAttempt(workflow, runId, expected) {
1860
+ try {
1861
+ if (expected.version === 2) {
1862
+ const source = this.#activeRuns.get(this.#runKey(workflow.id, runId))?.source;
1863
+ if (!source)
1864
+ return undefined;
1865
+ const state = await this.#completedStartState(source, {
1866
+ tablePrefix: source.tablePrefix,
1867
+ workflowId: workflow.id,
1868
+ runId,
1869
+ startToken: expected.startToken,
1870
+ }, expected);
1871
+ await this.#settleStartReservation(state);
1872
+ return state.summary;
1873
+ }
1874
+ const persisted = await this.#workflowState(workflow, runId);
1875
+ if (!persisted ||
1876
+ persisted.isFromInMemory ||
1877
+ persisted.status === 'pending')
1878
+ return undefined;
1879
+ const provenance = runProvenance(persisted);
1880
+ if (provenance?.version !== expected.version ||
1881
+ provenance.attemptToken !== expected.attemptToken)
1882
+ return undefined;
1883
+ return summarizeState(runId, persisted, new Map(provenance.resumeCounts), provenance.requestedBy, provenance.requestedByKind);
1884
+ }
1885
+ catch {
1281
1886
  return undefined;
1282
- return summarizeState(runId, persisted, new Map(provenance.resumeCounts), provenance.requestedBy, provenance.requestedByKind);
1887
+ }
1283
1888
  }
1284
- async #reconcileTerminalState(workflowId, runId, result, requestContext) {
1889
+ async #reconcileTerminalState(workflowId, runId, result, requestContext, source, proof) {
1285
1890
  const opts = terminalStateUpdate(result);
1286
1891
  if (!opts)
1287
1892
  return;
1288
1893
  await this.#withLifecycleLock(workflowId, runId, async () => {
1289
- const workflows = await this.#storage.getStore('workflows');
1290
- if (!workflows) {
1291
- throw new Error('RunnerRuntime: workflows storage is unavailable while persisting terminal state');
1292
- }
1293
- const snapshot = await workflows.loadWorkflowSnapshot({
1894
+ const workflows = source.workflows;
1895
+ const snapshot = await source.load.call(workflows, {
1294
1896
  workflowName: workflowId,
1295
1897
  runId,
1296
1898
  });
1297
1899
  if (!snapshot) {
1298
1900
  throw new Error(`RunnerRuntime: run '${runId}' of workflow '${workflowId}' completed without a durable snapshot`);
1299
1901
  }
1902
+ if (snapshot.runId !== runId)
1903
+ throw new RunStateUnreadableError(workflowId, runId);
1904
+ const expected = runProvenance({
1905
+ requestContext: Object.fromEntries(requestContext.entries()),
1906
+ });
1907
+ const persisted = runProvenance(snapshot);
1908
+ if (expected?.version === 2 &&
1909
+ ((persisted !== undefined &&
1910
+ (persisted.version !== 2 ||
1911
+ persisted.startToken !== expected.startToken)) ||
1912
+ (this.#executionFence && persisted?.version !== 2)))
1913
+ throw new RunStateUnreadableError(workflowId, runId);
1914
+ if (proof)
1915
+ await this.#assertRetainedResume(source, workflowId, runId, expected, proof);
1300
1916
  const persistedContext = snapshot.requestContext !== null &&
1301
1917
  typeof snapshot.requestContext === 'object' &&
1302
1918
  !Array.isArray(snapshot.requestContext)
@@ -1329,7 +1945,7 @@ export class RunnerRuntime {
1329
1945
  persistedCoversLifecycle) {
1330
1946
  return;
1331
1947
  }
1332
- await workflows.persistWorkflowSnapshot({
1948
+ await source.persist.call(workflows, {
1333
1949
  workflowName: workflowId,
1334
1950
  runId,
1335
1951
  snapshot: {