@proofoftech/flowsafe 0.20.0 → 0.22.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 (238) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +55 -10
  3. package/deployment-identity-protocol.d.mts +28 -3
  4. package/deployment-identity-protocol.mjs +275 -21
  5. package/dist/agent-host/router.d.ts.map +1 -1
  6. package/dist/agent-host/router.js +11 -2
  7. package/dist/agent-host/router.js.map +1 -1
  8. package/dist/agent-host/thread-host.d.ts +3 -1
  9. package/dist/agent-host/thread-host.d.ts.map +1 -1
  10. package/dist/agent-host/thread-host.js +858 -351
  11. package/dist/agent-host/thread-host.js.map +1 -1
  12. package/dist/agent-host/thread-topology.d.ts +8 -0
  13. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  14. package/dist/agent-host/thread-topology.js +243 -64
  15. package/dist/agent-host/thread-topology.js.map +1 -1
  16. package/dist/agent-runner/durable-agent-runner.d.ts +89 -14
  17. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  18. package/dist/agent-runner/durable-agent-runner.js +369 -44
  19. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  20. package/dist/agent-runner/index.d.ts +1 -1
  21. package/dist/agent-runner/index.d.ts.map +1 -1
  22. package/dist/agent-runner/index.js.map +1 -1
  23. package/dist/approval-api/actor-context.d.ts +4 -0
  24. package/dist/approval-api/actor-context.d.ts.map +1 -1
  25. package/dist/approval-api/actor-context.js +53 -5
  26. package/dist/approval-api/actor-context.js.map +1 -1
  27. package/dist/approval-api/principal.d.ts +1 -1
  28. package/dist/approval-api/principal.js +1 -1
  29. package/dist/approval-api/retention.d.ts +1 -2
  30. package/dist/approval-api/retention.d.ts.map +1 -1
  31. package/dist/approval-api/retention.js.map +1 -1
  32. package/dist/approval-api/service.d.ts +13 -20
  33. package/dist/approval-api/service.d.ts.map +1 -1
  34. package/dist/approval-api/service.js +52 -28
  35. package/dist/approval-api/service.js.map +1 -1
  36. package/dist/audit-export/index.d.ts +2 -2
  37. package/dist/audit-export/index.js +2 -2
  38. package/dist/background-tasks/d1-storage.d.ts +4 -3
  39. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  40. package/dist/background-tasks/d1-storage.js +8 -14
  41. package/dist/background-tasks/d1-storage.js.map +1 -1
  42. package/dist/background-tasks/host.d.ts.map +1 -1
  43. package/dist/background-tasks/host.js +3 -2
  44. package/dist/background-tasks/host.js.map +1 -1
  45. package/dist/do-runner/constants.d.ts +3 -0
  46. package/dist/do-runner/constants.d.ts.map +1 -0
  47. package/dist/do-runner/constants.js +3 -0
  48. package/dist/do-runner/constants.js.map +1 -0
  49. package/dist/do-runner/d1-storage.d.ts +34 -158
  50. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  51. package/dist/do-runner/d1-storage.js +935 -402
  52. package/dist/do-runner/d1-storage.js.map +1 -1
  53. package/dist/do-runner/durable-object.d.ts.map +1 -1
  54. package/dist/do-runner/durable-object.js +472 -185
  55. package/dist/do-runner/durable-object.js.map +1 -1
  56. package/dist/do-runner/execution-admission.d.ts +114 -0
  57. package/dist/do-runner/execution-admission.d.ts.map +1 -0
  58. package/dist/do-runner/execution-admission.js +206 -0
  59. package/dist/do-runner/execution-admission.js.map +1 -0
  60. package/dist/do-runner/execution-context.d.ts +5 -1
  61. package/dist/do-runner/execution-context.d.ts.map +1 -1
  62. package/dist/do-runner/execution-context.js +6 -1
  63. package/dist/do-runner/execution-context.js.map +1 -1
  64. package/dist/do-runner/execution-fence.d.ts +74 -30
  65. package/dist/do-runner/execution-fence.d.ts.map +1 -1
  66. package/dist/do-runner/execution-fence.js +684 -120
  67. package/dist/do-runner/execution-fence.js.map +1 -1
  68. package/dist/do-runner/fenced-workflow-capability.d.ts +64 -0
  69. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -0
  70. package/dist/do-runner/fenced-workflow-capability.js +3 -0
  71. package/dist/do-runner/fenced-workflow-capability.js.map +1 -0
  72. package/dist/do-runner/fenced-workflows-d1.d.ts +15 -0
  73. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -0
  74. package/dist/do-runner/fenced-workflows-d1.js +894 -0
  75. package/dist/do-runner/fenced-workflows-d1.js.map +1 -0
  76. package/dist/do-runner/index.d.ts +13 -8
  77. package/dist/do-runner/index.d.ts.map +1 -1
  78. package/dist/do-runner/index.js +6 -2
  79. package/dist/do-runner/index.js.map +1 -1
  80. package/dist/do-runner/initial-admission-refusal.d.ts +7 -0
  81. package/dist/do-runner/initial-admission-refusal.d.ts.map +1 -0
  82. package/dist/do-runner/initial-admission-refusal.js +41 -0
  83. package/dist/do-runner/initial-admission-refusal.js.map +1 -0
  84. package/dist/do-runner/inventory.d.ts +2 -1
  85. package/dist/do-runner/inventory.d.ts.map +1 -1
  86. package/dist/do-runner/inventory.js +28 -39
  87. package/dist/do-runner/inventory.js.map +1 -1
  88. package/dist/do-runner/notification-predicate.d.ts +7 -7
  89. package/dist/do-runner/notification-predicate.d.ts.map +1 -1
  90. package/dist/do-runner/notification-predicate.js +134 -7
  91. package/dist/do-runner/notification-predicate.js.map +1 -1
  92. package/dist/do-runner/run-lifecycle.d.ts +20 -1
  93. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  94. package/dist/do-runner/run-lifecycle.js +69 -15
  95. package/dist/do-runner/run-lifecycle.js.map +1 -1
  96. package/dist/do-runner/run-provenance.d.ts +38 -0
  97. package/dist/do-runner/run-provenance.d.ts.map +1 -0
  98. package/dist/do-runner/run-provenance.js +152 -0
  99. package/dist/do-runner/run-provenance.js.map +1 -0
  100. package/dist/do-runner/run-storage-tables.d.ts +2 -0
  101. package/dist/do-runner/run-storage-tables.d.ts.map +1 -0
  102. package/dist/do-runner/run-storage-tables.js +4 -0
  103. package/dist/do-runner/run-storage-tables.js.map +1 -0
  104. package/dist/do-runner/run-terminal-state.d.ts +29 -0
  105. package/dist/do-runner/run-terminal-state.d.ts.map +1 -0
  106. package/dist/do-runner/run-terminal-state.js +105 -0
  107. package/dist/do-runner/run-terminal-state.js.map +1 -0
  108. package/dist/do-runner/runtime.d.ts +108 -46
  109. package/dist/do-runner/runtime.d.ts.map +1 -1
  110. package/dist/do-runner/runtime.js +927 -438
  111. package/dist/do-runner/runtime.js.map +1 -1
  112. package/dist/do-runner/start-idempotency.d.ts +35 -258
  113. package/dist/do-runner/start-idempotency.d.ts.map +1 -1
  114. package/dist/do-runner/start-idempotency.js +606 -498
  115. package/dist/do-runner/start-idempotency.js.map +1 -1
  116. package/dist/do-runner/start-reservation-contract.d.ts +103 -0
  117. package/dist/do-runner/start-reservation-contract.d.ts.map +1 -0
  118. package/dist/do-runner/start-reservation-contract.js +338 -0
  119. package/dist/do-runner/start-reservation-contract.js.map +1 -0
  120. package/dist/do-runner/suspension-deadline.d.ts +4 -11
  121. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  122. package/dist/do-runner/suspension-deadline.js +8 -12
  123. package/dist/do-runner/suspension-deadline.js.map +1 -1
  124. package/dist/do-runner/table-prefix.d.ts.map +1 -1
  125. package/dist/do-runner/table-prefix.js +2 -1
  126. package/dist/do-runner/table-prefix.js.map +1 -1
  127. package/dist/do-runner/testing.d.ts +3 -0
  128. package/dist/do-runner/testing.d.ts.map +1 -0
  129. package/dist/do-runner/testing.js +3 -0
  130. package/dist/do-runner/testing.js.map +1 -0
  131. package/dist/do-runner/thread-do.d.ts +2 -1
  132. package/dist/do-runner/thread-do.d.ts.map +1 -1
  133. package/dist/do-runner/thread-do.js +14 -10
  134. package/dist/do-runner/thread-do.js.map +1 -1
  135. package/dist/do-runner/workflow-snapshot-row.d.ts +49 -0
  136. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -0
  137. package/dist/do-runner/workflow-snapshot-row.js +97 -0
  138. package/dist/do-runner/workflow-snapshot-row.js.map +1 -0
  139. package/dist/goals/objective-routes.d.ts +1 -5
  140. package/dist/goals/objective-routes.d.ts.map +1 -1
  141. package/dist/goals/objective-routes.js +32 -53
  142. package/dist/goals/objective-routes.js.map +1 -1
  143. package/dist/host-kit/approval-bridge.d.ts +8 -8
  144. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  145. package/dist/host-kit/approval-bridge.js +18 -15
  146. package/dist/host-kit/approval-bridge.js.map +1 -1
  147. package/dist/host-kit/do-response.d.ts +16 -0
  148. package/dist/host-kit/do-response.d.ts.map +1 -1
  149. package/dist/host-kit/do-response.js +181 -0
  150. package/dist/host-kit/do-response.js.map +1 -1
  151. package/dist/host-kit/do-run-topology.d.ts +2 -14
  152. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  153. package/dist/host-kit/do-run-topology.js +31 -24
  154. package/dist/host-kit/do-run-topology.js.map +1 -1
  155. package/dist/host-kit/env-vars.d.ts.map +1 -1
  156. package/dist/host-kit/env-vars.js +5 -6
  157. package/dist/host-kit/env-vars.js.map +1 -1
  158. package/dist/host-kit/flowsafe-worker.d.ts +38 -6
  159. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  160. package/dist/host-kit/flowsafe-worker.js +115 -93
  161. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  162. package/dist/host-kit/host-approval-service.d.ts +4 -14
  163. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  164. package/dist/host-kit/host-approval-service.js +23 -40
  165. package/dist/host-kit/host-approval-service.js.map +1 -1
  166. package/dist/host-kit/index.d.ts +7 -1
  167. package/dist/host-kit/index.d.ts.map +1 -1
  168. package/dist/host-kit/index.js +4 -0
  169. package/dist/host-kit/index.js.map +1 -1
  170. package/dist/host-kit/run-route-error.d.ts +3 -17
  171. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  172. package/dist/host-kit/run-route-error.js +4 -24
  173. package/dist/host-kit/run-route-error.js.map +1 -1
  174. package/dist/host-kit/run-router.d.ts +6 -2
  175. package/dist/host-kit/run-router.d.ts.map +1 -1
  176. package/dist/host-kit/run-router.js +93 -80
  177. package/dist/host-kit/run-router.js.map +1 -1
  178. package/dist/host-kit/thread-topology.d.ts +1 -1
  179. package/dist/host-kit/thread-topology.d.ts.map +1 -1
  180. package/dist/host-kit/thread-topology.js +7 -3
  181. package/dist/host-kit/thread-topology.js.map +1 -1
  182. package/dist/internal-error-response.d.ts.map +1 -1
  183. package/dist/internal-error-response.js +16 -6
  184. package/dist/internal-error-response.js.map +1 -1
  185. package/dist/schedules/index.d.ts +1 -0
  186. package/dist/schedules/index.d.ts.map +1 -1
  187. package/dist/schedules/index.js +1 -7
  188. package/dist/schedules/index.js.map +1 -1
  189. package/dist/schedules/mutation-contract.d.ts +38 -0
  190. package/dist/schedules/mutation-contract.d.ts.map +1 -0
  191. package/dist/schedules/mutation-contract.js +21 -0
  192. package/dist/schedules/mutation-contract.js.map +1 -0
  193. package/dist/schedules/router.d.ts +11 -19
  194. package/dist/schedules/router.d.ts.map +1 -1
  195. package/dist/schedules/router.js +130 -49
  196. package/dist/schedules/router.js.map +1 -1
  197. package/dist/schedules/schedules-d1.d.ts +11 -5
  198. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  199. package/dist/schedules/schedules-d1.js +571 -144
  200. package/dist/schedules/schedules-d1.js.map +1 -1
  201. package/dist/schedules/storage.d.ts +0 -7
  202. package/dist/schedules/storage.d.ts.map +1 -1
  203. package/dist/schedules/storage.js +0 -27
  204. package/dist/schedules/storage.js.map +1 -1
  205. package/dist/schedules/tick.d.ts +1 -8
  206. package/dist/schedules/tick.d.ts.map +1 -1
  207. package/dist/schedules/tick.js +15 -20
  208. package/dist/schedules/tick.js.map +1 -1
  209. package/dist/signal-providers/webhook-route.d.ts +1 -1
  210. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  211. package/dist/signal-providers/webhook-route.js +99 -109
  212. package/dist/signal-providers/webhook-route.js.map +1 -1
  213. package/dist/signals/d1-shared.d.ts +11 -8
  214. package/dist/signals/d1-shared.d.ts.map +1 -1
  215. package/dist/signals/d1-shared.js +2 -7
  216. package/dist/signals/d1-shared.js.map +1 -1
  217. package/dist/signals/index.d.ts +1 -1
  218. package/dist/signals/index.d.ts.map +1 -1
  219. package/dist/signals/index.js +1 -1
  220. package/dist/signals/index.js.map +1 -1
  221. package/dist/signals/notification-dispatch.d.ts +84 -4
  222. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  223. package/dist/signals/notification-dispatch.js +365 -53
  224. package/dist/signals/notification-dispatch.js.map +1 -1
  225. package/dist/signals/notifications-d1.d.ts +6 -1
  226. package/dist/signals/notifications-d1.d.ts.map +1 -1
  227. package/dist/signals/notifications-d1.js +215 -10
  228. package/dist/signals/notifications-d1.js.map +1 -1
  229. package/dist/signals/router.d.ts +6 -4
  230. package/dist/signals/router.d.ts.map +1 -1
  231. package/dist/signals/router.js +49 -84
  232. package/dist/signals/router.js.map +1 -1
  233. package/dist/signals/thread-do-routes.d.ts +2 -0
  234. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  235. package/dist/signals/thread-do-routes.js +250 -81
  236. package/dist/signals/thread-do-routes.js.map +1 -1
  237. package/package.json +9 -7
  238. package/scripts/seed-deployment-identity.mjs +27 -6
@@ -1,108 +1,47 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
- // Owner-bound idempotent start — the reservation that makes "start this once"
3
- // mean once, across retries, isolates, and deployments.
4
- //
5
- // WHY it exists: a run start is the moment a deployment commits to spending
6
- // money. The first step of a workflow can wire funds, file an order, or call a
7
- // paid API, and every layer between a caller and that step is allowed to lose a
8
- // RESPONSE without losing the WORK — a Worker eviction, a client timeout, a
9
- // load balancer retry, an operator re-running a script. Without a reservation
10
- // the only honest answer to "did my start land?" is "retry and find out", and
11
- // that answer charges the card twice.
12
- //
13
- // The reservation is what a key BUYS: a durable row, written before anything
14
- // executes, that says which run this key already means. A retry carrying the
15
- // same key does not start a second run — it finds the first one and is told
16
- // what happened to it.
17
- //
18
- // THE TAXONOMY IS THE CONTRACT. Eight structured reason codes say what flowsafe
19
- // KNOWS, because the caller's next action differs for each and a collapsed code
20
- // would make them all "retry". Five are reservation-decision refusals:
21
- //
22
- // IDEMPOTENT_START_OWNER_MISMATCH (403) this key is somebody else's. Keys are
23
- // owner-scoped, so one tenant principal
24
- // cannot probe, hijack, or collide with
25
- // another's — and never learns more than
26
- // "not yours".
27
- // IDEMPOTENT_START_TARGET_MISMATCH (409) the key is yours but names a
28
- // different workflow/agent than last time.
29
- // Reusing a key across targets is a caller
30
- // bug, and silently honouring it would make
31
- // one key mean two different charges.
32
- // IDEMPOTENT_START_PENDING (503) the run this key names is RUNNING right
33
- // now. Retryable, and legitimately unbounded:
34
- // the first persisted summary lands at the
35
- // first suspend or terminal state, so a long
36
- // live run has no summary yet and is not lost.
37
- // `pendingSince` lets a caller reason about
38
- // how long, without this package pretending a
39
- // timeout would be safe.
40
- // IDEMPOTENT_START_UNRESOLVABLE (409) the claim was taken, nothing persisted,
41
- // and nothing is running. Whether a side
42
- // effect fired before the crash is UNKNOWABLE
43
- // to flowsafe. So it refuses, and says so, and
44
- // never re-executes on its own. A host that
45
- // investigates and decides to re-run does it
46
- // with a FRESH key — a deliberate second
47
- // charge, not one this package invented.
48
- // IDEMPOTENT_START_ALREADY_SETTLED (409) the run finished and its summary has
49
- // aged out. The reservation deliberately
50
- // OUTLIVES the snapshot so this answer exists
51
- // at all; the alternative is a purged run
52
- // looking exactly like a fresh key.
53
- //
54
- // Three complete the public keyed-start taxonomy:
55
- //
56
- // IDEMPOTENT_START_UNSUPPORTED (503) a keyed start reached a deployment whose
57
- // host did not wire a reservation store.
58
- // INVALID_START_IDEMPOTENCY_REQUEST (400) the keyed input was malformed.
59
- // IDEMPOTENT_START_UNREADABLE (503) the reservation store could not be read
60
- // or contained a row this build cannot parse.
61
- //
62
- // The seven-member `StartReservationRefusal` union recognized by
63
- // `isStartReservationRefusal` includes everything above except UNREADABLE,
64
- // which propagates separately as an integrity or availability failure.
65
- //
66
- // NO TIMER ANYWHERE. Two of those branches are separated by a LIVENESS PROBE,
67
- // never by elapsed time. A timer would have to guess a bound on legitimate
68
- // in-flight work, and every guess is wrong in the expensive direction: too
69
- // short and a long live run is declared dead, inviting a fresh key and a second
70
- // charge; too long and a genuinely crashed start wedges its key. The probe asks
71
- // the run's own host whether it is executing, which is the question a timer was
72
- // only ever approximating.
73
- //
74
- // THE CLAIM IS THE SERIALIZER. `reserve()` decides which runId a key means;
75
- // `claim()` decides who gets to START it. The claim is one conditional UPDATE,
76
- // so exactly one caller changes a row and every other caller reads the outcome
77
- // instead of racing it. That matters most where Durable Object serialization
78
- // cannot help: agent runs live in thread objects keyed by threadId, so two
79
- // same-key starts naming different threads are two different objects with no
80
- // shared lock at all. This CAS is the only thing between them.
81
- //
82
- // RUN IDS ARE NEVER MINTED HERE. Run ids are server-minted, at the host's own
83
- // existing mint sites; the reservation STORES one and hands the same id back to
84
- // every later caller. A store that generated ids would be a second minting
85
- // authority, and the whole rule is that there is exactly one.
86
- import { EXECUTION_PRINCIPAL_KINDS, isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal-identity.js';
2
+ // A missing result cannot establish whether a claimed start had effects.
3
+ import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal-identity.js';
87
4
  import { missingTableReadsEmpty } from './cause-chain.js';
88
5
  import { DoStatusError } from './do-status-error.js';
89
- import { isExecutionFenceRefusal } from './execution-fence.js';
6
+ import { InvalidExecutionIdentityError, normalizeMutationEpoch, normalizeStartExecutionIdentity, RunAdmissionConflictError, } from './execution-admission.js';
90
7
  import { isPathSafeId } from './path-safe-id.js';
91
- /**
92
- * The reservation table — flowsafe-owned, so outside the `mastra_%` schema
93
- * guard, and created lazily by the first `reserve()` rather than by the
94
- * provisioning protocol. Unlike the execution fence (whose ABSENCE has to read
95
- * as a state, so provisioning writes an explicit row), an absent reservation
96
- * table simply means no key has ever been used on this deployment, which is
97
- * indistinguishable from an empty one.
98
- */
99
- export const START_IDEMPOTENCY_TABLE = 'flowsafe_start_idempotency';
100
- export const START_RESERVATION_STATES = [
101
- 'reserved',
102
- 'started',
103
- 'terminal',
104
- ];
105
- export const START_TARGET_KINDS = ['workflow', 'agent'];
8
+ import { admissionReservationFromRow, captureReservation, decodeStartReservationAdmissionResult, isStartTargetKind, ReservationSchemaError, reservationFromRow, reservationResultRows, reservationSchemaStage, START_IDEMPOTENCY_ADDITIONS, START_IDEMPOTENCY_COLUMNS, START_IDEMPOTENCY_DDL, START_IDEMPOTENCY_RUN_INDEX_DDL, START_IDEMPOTENCY_STATE_INDEX_DDL, START_IDEMPOTENCY_TABLE, START_TARGET_KINDS, sameReservationIdentity, validateStartReservationAdmissionSchema, } from './start-reservation-contract.js';
9
+ export { decodeStartReservationAdmissionResult, START_IDEMPOTENCY_DDL, START_IDEMPOTENCY_RUN_INDEX_DDL, START_IDEMPOTENCY_STATE_INDEX_DDL, START_IDEMPOTENCY_TABLE, START_RESERVATION_STATES, START_TARGET_KINDS, validateStartReservationAdmissionSchema, } from './start-reservation-contract.js';
10
+ function captureStartRequest(request) {
11
+ const key = assertKey(request.key);
12
+ const owner = assertOwner(request.owner);
13
+ const { targetKind, targetId, threadId, mintRunId } = request;
14
+ if (!isStartTargetKind(targetKind)) {
15
+ throw new InvalidStartIdempotencyRequestError(`target kind must be one of ${START_TARGET_KINDS.join(', ')}`);
16
+ }
17
+ if (!isPathSafeId(targetId)) {
18
+ throw new InvalidStartIdempotencyRequestError('target id must be a URL-path-safe identifier');
19
+ }
20
+ // The thread is the agent run's ADDRESS, so requiring it for agents and
21
+ // rejecting it for workflows is not tidiness: an agent reservation without
22
+ // one is a run a retry can never reach, and a workflow reservation WITH one
23
+ // is a second, silently divergent copy of an address that is already
24
+ // derivable from (workflowId, runId).
25
+ if (targetKind === 'agent') {
26
+ if (!isPathSafeId(threadId)) {
27
+ throw new InvalidStartIdempotencyRequestError('an agent start reservation requires a URL-path-safe threadId');
28
+ }
29
+ }
30
+ else if (threadId !== undefined) {
31
+ throw new InvalidStartIdempotencyRequestError('threadId applies only to agent start reservations');
32
+ }
33
+ if (typeof mintRunId !== 'function') {
34
+ throw new InvalidStartIdempotencyRequestError('mintRunId must be a function');
35
+ }
36
+ return Object.freeze({
37
+ key,
38
+ owner,
39
+ targetKind,
40
+ targetId,
41
+ threadId,
42
+ mintRunId: () => Reflect.apply(mintRunId, request, []),
43
+ });
44
+ }
106
45
  /**
107
46
  * The key names a reservation owned by a different principal.
108
47
  *
@@ -142,12 +81,6 @@ export class StartReservationTargetMismatchError extends DoStatusError {
142
81
  };
143
82
  }
144
83
  }
145
- /**
146
- * The key's run is executing right now. 503 for the same reason every
147
- * operator-transient refusal in this package is: the condition is real, it is
148
- * nobody's mistake, and it clears on its own — so a client that honours
149
- * retry semantics converges instead of giving up.
150
- */
151
84
  export class IdempotentStartPendingError extends DoStatusError {
152
85
  status = 503;
153
86
  reason;
@@ -267,9 +200,8 @@ export function isStartReservationRefusal(error) {
267
200
  * the D1 storage adapter (and @mastra/cloudflare-d1 with it) into its bundle.
268
201
  *
269
202
  * That bundle rule is why the imports at the top of this file are what they
270
- * are. Four are import-free leaves (principal-identity, cause-chain,
271
- * do-status-error, path-safe-id) and the fifth, execution-fence, imports only
272
- * leaves and the shared provisioning protocol. Nothing on that graph can cycle
203
+ * are: lightweight identity/error leaves and the execution-fence store, whose
204
+ * dependencies never reach the adapter. Nothing on that graph can cycle
273
205
  * back here, which matters more than usual: the eight DoStatusError subclasses
274
206
  * in this module are evaluated at module load, so an import edge that came
275
207
  * back around would meet a class expression still in its temporal dead zone.
@@ -295,104 +227,6 @@ export function startIdempotencyFor(db) {
295
227
  startIdempotencyStores.set(db, store);
296
228
  return store;
297
229
  }
298
- const STATE_CHECK = START_RESERVATION_STATES.map((state) => `'${state}'`).join(', ');
299
- const TARGET_CHECK = START_TARGET_KINDS.map((kind) => `'${kind}'`).join(', ');
300
- /**
301
- * Built from the principal vocabulary rather than hand-written, so a kind added
302
- * to `EXECUTION_PRINCIPAL_KINDS` cannot leave this constraint behind. The
303
- * failure a stale literal would cause is not a compile error and not a rejected
304
- * write on an existing deployment: `CREATE TABLE IF NOT EXISTS` is a no-op
305
- * against a table that already exists, so the drift would show up only as an
306
- * INSERT refused on whichever database happened to be created after the new
307
- * kind shipped.
308
- */
309
- const OWNER_KIND_CHECK = EXECUTION_PRINCIPAL_KINDS.map((kind) => `'${kind}'`).join(', ');
310
- /**
311
- * The reservation schema.
312
- *
313
- * The CHECK constraints are load-bearing, not decoration: every compare-and-set
314
- * below is stated as `WHERE ... AND state = '<literal>'`, which is only a TOTAL
315
- * decision while the column cannot hold a fourth value. A row hand-edited into
316
- * an unknown state would otherwise be a reservation no CAS can advance and no
317
- * purge can reap — a permanently wedged key.
318
- */
319
- export const START_IDEMPOTENCY_DDL = `CREATE TABLE IF NOT EXISTS ${START_IDEMPOTENCY_TABLE} (
320
- key TEXT PRIMARY KEY,
321
- owner_kind TEXT NOT NULL CHECK (owner_kind IN (${OWNER_KIND_CHECK})),
322
- owner_id TEXT NOT NULL,
323
- target_kind TEXT NOT NULL CHECK (target_kind IN (${TARGET_CHECK})),
324
- target_id TEXT NOT NULL,
325
- run_id TEXT NOT NULL,
326
- thread_id TEXT,
327
- state TEXT NOT NULL CHECK (state IN (${STATE_CHECK})),
328
- created_at INTEGER NOT NULL,
329
- updated_at INTEGER NOT NULL
330
- )`;
331
- /**
332
- * `run_id` is how the RUNTIME finds a reservation (terminal reconcile knows the
333
- * run, never the key) and how the purge pairs a reservation with the snapshot
334
- * it outlived. Without the index both degrade to a table scan on every terminal
335
- * run.
336
- */
337
- export const START_IDEMPOTENCY_RUN_INDEX_DDL = `CREATE INDEX IF NOT EXISTS ${START_IDEMPOTENCY_TABLE}_run
338
- ON ${START_IDEMPOTENCY_TABLE} (run_id)`;
339
- /** The purge's own access path: terminal rows past the key-validity horizon. */
340
- export const START_IDEMPOTENCY_STATE_INDEX_DDL = `CREATE INDEX IF NOT EXISTS ${START_IDEMPOTENCY_TABLE}_state
341
- ON ${START_IDEMPOTENCY_TABLE} (state, updated_at)`;
342
- function isStartReservationState(value) {
343
- return (typeof value === 'string' &&
344
- START_RESERVATION_STATES.includes(value));
345
- }
346
- function isStartTargetKind(value) {
347
- return (typeof value === 'string' &&
348
- START_TARGET_KINDS.includes(value));
349
- }
350
- function isEpochMs(value) {
351
- return typeof value === 'number' && Number.isFinite(value);
352
- }
353
- /**
354
- * Project a stored row, or refuse it.
355
- *
356
- * A malformed row throws rather than reading as absent, and that direction is
357
- * deliberate: "there is no reservation" is the answer that STARTS A RUN, so it
358
- * must never be reachable from a row this build cannot parse. The CHECK
359
- * constraints make this unreachable on a database this package created; it
360
- * exists for the one that was hand-edited.
361
- *
362
- * The TIMESTAMPS are in that strict set too, rather than coerced to 0 as an
363
- * unparseable number once was. Neither column is decoration: `updated_at` is
364
- * the horizon the purge measures from, so a corrupt one on a terminal row reads
365
- * as epoch 0 and makes the reservation immediately reapable — which deletes a
366
- * spent key early and turns the next retry of it into a fresh start. It is also
367
- * `pendingSince` on a live claim, where 0 tells an operator a run has been
368
- * starting since 1970. Refusing the row keeps both faults visible as the 503
369
- * they are.
370
- */
371
- function reservationFromRow(row) {
372
- const { key, owner_kind: ownerKind, owner_id: ownerId, target_kind: targetKind, target_id: targetId, run_id: runId, thread_id: threadId, state, created_at: createdAt, updated_at: updatedAt, } = row;
373
- if (typeof key !== 'string' ||
374
- !isExecutionPrincipalKind(ownerKind) ||
375
- !isExecutionPrincipalId(ownerId) ||
376
- !isStartTargetKind(targetKind) ||
377
- typeof targetId !== 'string' ||
378
- !isPathSafeId(runId) ||
379
- !isStartReservationState(state) ||
380
- !isEpochMs(createdAt) ||
381
- !isEpochMs(updatedAt)) {
382
- throw new StartReservationUnreadableError(typeof key === 'string' ? key : '(unknown)');
383
- }
384
- return {
385
- key,
386
- owner: { kind: ownerKind, id: ownerId },
387
- targetKind,
388
- targetId,
389
- runId,
390
- ...(isPathSafeId(threadId) ? { threadId } : {}),
391
- state,
392
- createdAt,
393
- updatedAt,
394
- };
395
- }
396
230
  /**
397
231
  * A reservation exists but cannot be understood, or the table could not be
398
232
  * read. 503 and never "no reservation": the absent answer is the one that
@@ -442,6 +276,50 @@ function assertOwner(owner) {
442
276
  }
443
277
  return { kind, id };
444
278
  }
279
+ function assertReservationStartIdentity(reservation, execution) {
280
+ if (reservation.owner.kind !== execution.owner.kind ||
281
+ reservation.owner.id !== execution.owner.id)
282
+ throw new StartReservationOwnerMismatchError(reservation.key);
283
+ if (reservation.targetKind !== execution.target.kind ||
284
+ reservation.targetId !== execution.target.id)
285
+ throw new StartReservationTargetMismatchError(reservation.key, reservation);
286
+ if (reservation.runId !== execution.runId ||
287
+ reservation.threadId !==
288
+ (execution.target.kind === 'agent'
289
+ ? execution.target.threadId
290
+ : undefined) ||
291
+ (execution.target.kind === 'workflow' &&
292
+ execution.workflowId !== execution.target.id))
293
+ throw new InvalidExecutionIdentityError('admission');
294
+ }
295
+ function sameReservationExecution(reservation, execution) {
296
+ return (reservation.runId === execution.runId &&
297
+ reservation.owner.kind === execution.owner.kind &&
298
+ reservation.owner.id === execution.owner.id &&
299
+ reservation.targetKind === execution.target.kind &&
300
+ reservation.targetId === execution.target.id &&
301
+ reservation.threadId ===
302
+ (execution.target.kind === 'agent'
303
+ ? execution.target.threadId
304
+ : undefined) &&
305
+ reservation.binding.kind === 'bound' &&
306
+ reservation.binding.execution.runId === execution.runId &&
307
+ reservation.binding.execution.startToken === execution.startToken &&
308
+ reservation.binding.execution.tablePrefix === execution.tablePrefix &&
309
+ reservation.binding.execution.workflowId === execution.workflowId);
310
+ }
311
+ function reservationMutationResult(result, observed, state, updatedAt, execution) {
312
+ const row = decodeStartReservationAdmissionResult(result);
313
+ if (row !== undefined &&
314
+ (!sameReservationIdentity(row, observed) ||
315
+ row.state !== state ||
316
+ row.updatedAt !== updatedAt ||
317
+ (execution === undefined
318
+ ? row.binding.kind !== 'unbound'
319
+ : !sameReservationExecution(row, execution))))
320
+ throw new Error('reservation mutation returned an unexpected row');
321
+ return row;
322
+ }
445
323
  /**
446
324
  * The deployment's start reservations, over the SAME D1 database its snapshots,
447
325
  * its resource owners, and its execution fence live in — so a reservation
@@ -454,17 +332,22 @@ export class StartIdempotencyStore {
454
332
  constructor(db, options = {}) {
455
333
  this.#db = db;
456
334
  this.#now = options.now ?? Date.now;
457
- if (options.ready) {
458
- this.#ready = options.ready;
335
+ const ready = options.ready;
336
+ if (ready) {
337
+ this.#ready = async () => {
338
+ await Reflect.apply(ready, this, []);
339
+ if ((await this.#schemaStage()) !== 3)
340
+ throw new ReservationSchemaError('host readiness did not reach the current schema');
341
+ };
459
342
  }
460
343
  else {
461
- let ready;
344
+ let storageReady;
462
345
  this.#ready = () => {
463
- ready ??= this.#createSchema().catch((error) => {
464
- ready = undefined;
346
+ storageReady ??= this.#createSchema().catch((error) => {
347
+ storageReady = undefined;
465
348
  throw error;
466
349
  });
467
- return ready;
350
+ return storageReady;
468
351
  };
469
352
  }
470
353
  }
@@ -484,29 +367,14 @@ export class StartIdempotencyStore {
484
367
  * deployment's read-only drain inventory into a write.
485
368
  */
486
369
  async reserve(request) {
487
- const key = assertKey(request.key);
488
- const owner = assertOwner(request.owner);
489
- if (!isStartTargetKind(request.targetKind)) {
490
- throw new InvalidStartIdempotencyRequestError(`target kind must be one of ${START_TARGET_KINDS.join(', ')}`);
491
- }
492
- if (!isPathSafeId(request.targetId)) {
493
- throw new InvalidStartIdempotencyRequestError('target id must be a URL-path-safe identifier');
494
- }
495
- // The thread is the agent run's ADDRESS, so requiring it for agents and
496
- // rejecting it for workflows is not tidiness: an agent reservation without
497
- // one is a run a retry can never reach, and a workflow reservation WITH one
498
- // is a second, silently divergent copy of an address that is already
499
- // derivable from (workflowId, runId).
500
- if (request.targetKind === 'agent') {
501
- if (!isPathSafeId(request.threadId)) {
502
- throw new InvalidStartIdempotencyRequestError('an agent start reservation requires a URL-path-safe threadId');
503
- }
370
+ const { key, owner, targetKind, targetId, threadId, mintRunId } = captureStartRequest(request);
371
+ try {
372
+ await this.#ready();
504
373
  }
505
- else if (request.threadId !== undefined) {
506
- throw new InvalidStartIdempotencyRequestError('threadId applies only to agent start reservations');
374
+ catch (error) {
375
+ throw new StartReservationUnreadableError(key, { cause: error });
507
376
  }
508
- await this.#ready();
509
- const candidateRunId = request.mintRunId();
377
+ const candidateRunId = Reflect.apply(mintRunId, request, []);
510
378
  if (!isPathSafeId(candidateRunId)) {
511
379
  throw new InvalidStartIdempotencyRequestError('the host minted a runId that is not URL-path-safe');
512
380
  }
@@ -514,9 +382,9 @@ export class StartIdempotencyStore {
514
382
  const inserted = changesOf(await this.#db
515
383
  .prepare(`INSERT OR IGNORE INTO ${START_IDEMPOTENCY_TABLE}
516
384
  (key, owner_kind, owner_id, target_kind, target_id, run_id,
517
- thread_id, state, created_at, updated_at)
518
- VALUES (?, ?, ?, ?, ?, ?, ?, 'reserved', ?, ?)`)
519
- .bind(key, owner.kind, owner.id, request.targetKind, request.targetId, candidateRunId, request.threadId ?? null, now, now)
385
+ thread_id, state, created_at, updated_at, start_token, start_table_prefix, start_workflow_id)
386
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'reserved', ?, ?, '', NULL, NULL)`)
387
+ .bind(key, owner.kind, owner.id, targetKind, targetId, candidateRunId, threadId ?? null, now, now)
520
388
  .run());
521
389
  const stored = await this.read(key);
522
390
  if (stored === undefined) {
@@ -530,8 +398,7 @@ export class StartIdempotencyStore {
530
398
  if (stored.owner.kind !== owner.kind || stored.owner.id !== owner.id) {
531
399
  throw new StartReservationOwnerMismatchError(key);
532
400
  }
533
- if (stored.targetKind !== request.targetKind ||
534
- stored.targetId !== request.targetId) {
401
+ if (stored.targetKind !== targetKind || stored.targetId !== targetId) {
535
402
  throw new StartReservationTargetMismatchError(key, stored);
536
403
  }
537
404
  // Both signals must agree before this caller believes it created the row.
@@ -544,69 +411,255 @@ export class StartIdempotencyStore {
544
411
  created: inserted > 0 && stored.runId === candidateRunId,
545
412
  };
546
413
  }
547
- /**
548
- * Take the claim: `reserved` -> `started`, for this exact run.
549
- *
550
- * ONE conditional UPDATE, and the whole cross-isolate serialization of the
551
- * feature. Exactly one caller changes a row; every other caller sees zero
552
- * changes and must go and find out what the winner did rather than starting
553
- * anything. The `run_id` predicate rides along so a claim can never land on a
554
- * row that was rewritten underneath it.
555
- *
556
- * Never creates the table: a claim can only ever follow a reserve, which did.
557
- */
558
- async claim(key, runId) {
559
- return this.#casState(key, runId, 'reserved', 'started');
414
+ /** Claim only this observed modern-unbound reservation. */
415
+ async claimReservation(observed) {
416
+ const reservation = captureReservation(observed, 'reserved');
417
+ const next = this.#nextReservationStamp(reservation);
418
+ await this.#requireReservationSchema(reservation.key);
419
+ let result;
420
+ try {
421
+ result = await this.#db
422
+ .prepare(`UPDATE ${START_IDEMPOTENCY_TABLE} SET state = 'started', updated_at = ?
423
+ WHERE key = ? AND run_id = ?
424
+ AND owner_kind = ? AND owner_id = ?
425
+ AND target_kind = ? AND target_id = ? AND thread_id IS ?
426
+ AND created_at = ? AND updated_at = ? AND state = ?
427
+ AND state = 'reserved'
428
+ AND start_token = '' AND start_table_prefix IS NULL AND start_workflow_id IS NULL
429
+ RETURNING *`)
430
+ .bind(next, reservation.key, reservation.runId, reservation.owner.kind, reservation.owner.id, reservation.targetKind, reservation.targetId, reservation.threadId ?? null, reservation.createdAt, reservation.updatedAt, reservation.state)
431
+ .all();
432
+ }
433
+ catch (error) {
434
+ throw new StartReservationUnreadableError(reservation.key, {
435
+ cause: error,
436
+ });
437
+ }
438
+ try {
439
+ return reservationMutationResult(result, reservation, 'started', next);
440
+ }
441
+ catch (error) {
442
+ throw new StartReservationUnreadableError(reservation.key, {
443
+ cause: error,
444
+ });
445
+ }
560
446
  }
561
- /**
562
- * Give the claim back: `started` -> `reserved`, for this exact run.
563
- *
564
- * The ONLY backwards transition, and it exists for exactly one caller: a
565
- * start the EXECUTION FENCE refused. That refusal is special because it is
566
- * provably pre-execution — the fence is read before the run lock and before
567
- * any storage write — so the claim it consumed bought nothing and holding on
568
- * to it would manufacture an UNRESOLVABLE reservation out of an operator
569
- * action. Leaving the claim taken would mean a deployment that drained,
570
- * migrated, and reopened had permanently poisoned every key that happened to
571
- * be in flight.
572
- *
573
- * It is deliberately NOT used for other start failures. Anything that reached
574
- * the runtime's execution path may have taken effect, and a rollback there
575
- * would hand the next retry a fresh run — the exact double-charge this whole
576
- * module exists to prevent.
577
- */
578
- async release(key, runId) {
579
- return this.#casState(key, runId, 'started', 'reserved');
447
+ /** Release only the exact unbound claim, without readback recovery. */
448
+ async releaseReservation(observed) {
449
+ const reservation = captureReservation(observed, 'started');
450
+ const next = this.#nextReservationStamp(reservation);
451
+ await this.#requireReservationSchema(reservation.key);
452
+ let result;
453
+ try {
454
+ result = await this.#db
455
+ .prepare(`UPDATE ${START_IDEMPOTENCY_TABLE} SET state = 'reserved', updated_at = ?
456
+ WHERE key = ? AND run_id = ?
457
+ AND owner_kind = ? AND owner_id = ?
458
+ AND target_kind = ? AND target_id = ? AND thread_id IS ?
459
+ AND created_at = ? AND updated_at = ? AND state = ?
460
+ AND state = 'started'
461
+ AND start_token = '' AND start_table_prefix IS NULL AND start_workflow_id IS NULL
462
+ RETURNING *`)
463
+ .bind(next, reservation.key, reservation.runId, reservation.owner.kind, reservation.owner.id, reservation.targetKind, reservation.targetId, reservation.threadId ?? null, reservation.createdAt, reservation.updatedAt, reservation.state)
464
+ .all();
465
+ }
466
+ catch (error) {
467
+ throw new StartReservationUnreadableError(reservation.key, {
468
+ cause: error,
469
+ });
470
+ }
471
+ try {
472
+ return (reservationMutationResult(result, reservation, 'reserved', next) !==
473
+ undefined);
474
+ }
475
+ catch (error) {
476
+ throw new StartReservationUnreadableError(reservation.key, {
477
+ cause: error,
478
+ });
479
+ }
580
480
  }
581
- /**
582
- * Terminal reconcile, keyed by RUN rather than by key: the runtime observes a
583
- * run reaching a terminal state and has no idea which key (if any) named it.
584
- *
585
- * Idempotent by construction (`state <> 'terminal'`), so the several places a
586
- * run can reach terminal — completing, failing, being cancelled, timing out —
587
- * can all call it without coordinating, and a re-entry after a crash is a
588
- * no-op rather than a conflict.
589
- *
590
- * Returns the number of reservations settled, which is 0 for the overwhelming
591
- * majority of runs (nobody used a key) and 1 for the rest.
592
- */
593
- async settleRun(runId) {
594
- if (!isPathSafeId(runId))
595
- return 0;
481
+ /** Associate an alias with an already-observed nonpending execution. */
482
+ async associateReservation(observed, execution) {
483
+ const reservation = captureReservation(observed, 'nonterminal');
484
+ const identity = normalizeStartExecutionIdentity(execution);
485
+ assertReservationStartIdentity(reservation, identity);
486
+ await this.#requireReservationSchema(reservation.key);
487
+ let result;
488
+ let failed = false;
489
+ let writeCause;
490
+ try {
491
+ result = await this.#db
492
+ .prepare(`UPDATE ${START_IDEMPOTENCY_TABLE}
493
+ SET start_token = ?, start_table_prefix = ?, start_workflow_id = ?
494
+ WHERE key = ? AND run_id = ?
495
+ AND owner_kind = ? AND owner_id = ?
496
+ AND target_kind = ? AND target_id = ? AND thread_id IS ?
497
+ AND created_at = ? AND updated_at = ? AND state = ?
498
+ AND state <> 'terminal'
499
+ AND start_token = '' AND start_table_prefix IS NULL AND start_workflow_id IS NULL
500
+ RETURNING *`)
501
+ .bind(identity.startToken, identity.tablePrefix, identity.workflowId, reservation.key, reservation.runId, reservation.owner.kind, reservation.owner.id, reservation.targetKind, reservation.targetId, reservation.threadId ?? null, reservation.createdAt, reservation.updatedAt, reservation.state)
502
+ .all();
503
+ }
504
+ catch (error) {
505
+ failed = true;
506
+ writeCause = error;
507
+ }
508
+ if (!failed) {
509
+ try {
510
+ const row = reservationMutationResult(result, reservation, reservation.state, reservation.updatedAt, identity);
511
+ if (row)
512
+ return row;
513
+ }
514
+ catch (error) {
515
+ throw new StartReservationUnreadableError(reservation.key, {
516
+ cause: error,
517
+ });
518
+ }
519
+ }
520
+ let current;
521
+ try {
522
+ current = await this.readForAdmission(reservation.key);
523
+ }
524
+ catch (error) {
525
+ if (!failed)
526
+ throw error;
527
+ }
528
+ if (current &&
529
+ sameReservationIdentity(current, reservation) &&
530
+ sameReservationExecution(current, identity))
531
+ return current;
532
+ if (failed)
533
+ throw new StartReservationUnreadableError(reservation.key, {
534
+ cause: writeCause,
535
+ });
536
+ throw new RunAdmissionConflictError('reservation-changed');
537
+ }
538
+ /** Bind a prepared start; only exact lost-write readback can recover. */
539
+ async bindPreparedStart(observed, execution) {
540
+ const reservation = captureReservation(observed, 'started');
541
+ const identity = normalizeStartExecutionIdentity(execution);
542
+ assertReservationStartIdentity(reservation, identity);
543
+ await this.#requireReservationSchema(reservation.key);
544
+ let result;
596
545
  try {
597
- return changesOf(await this.#db
546
+ result = await this.#db
598
547
  .prepare(`UPDATE ${START_IDEMPOTENCY_TABLE}
599
- SET state = 'terminal', updated_at = ?
600
- WHERE run_id = ? AND state <> 'terminal'`)
601
- .bind(this.#now(), runId)
602
- .run());
548
+ SET start_token = ?, start_table_prefix = ?, start_workflow_id = ?
549
+ WHERE key = ? AND run_id = ?
550
+ AND owner_kind = ? AND owner_id = ?
551
+ AND target_kind = ? AND target_id = ? AND thread_id IS ?
552
+ AND created_at = ? AND updated_at = ? AND state = ?
553
+ AND state = 'started'
554
+ AND start_token = '' AND start_table_prefix IS NULL AND start_workflow_id IS NULL
555
+ RETURNING *`)
556
+ .bind(identity.startToken, identity.tablePrefix, identity.workflowId, reservation.key, reservation.runId, reservation.owner.kind, reservation.owner.id, reservation.targetKind, reservation.targetId, reservation.threadId ?? null, reservation.createdAt, reservation.updatedAt, reservation.state)
557
+ .all();
558
+ }
559
+ catch (error) {
560
+ let current;
561
+ try {
562
+ current = await this.readForAdmission(reservation.key);
563
+ }
564
+ catch {
565
+ // Preserve the write uncertainty even when its one readback also fails.
566
+ }
567
+ if (current &&
568
+ sameReservationIdentity(current, reservation) &&
569
+ current.state === reservation.state &&
570
+ current.updatedAt === reservation.updatedAt &&
571
+ sameReservationExecution(current, identity))
572
+ return current;
573
+ throw new StartReservationUnreadableError(reservation.key, {
574
+ cause: error,
575
+ });
576
+ }
577
+ let row;
578
+ try {
579
+ row = reservationMutationResult(result, reservation, reservation.state, reservation.updatedAt, identity);
580
+ }
581
+ catch (error) {
582
+ throw new StartReservationUnreadableError(reservation.key, {
583
+ cause: error,
584
+ });
585
+ }
586
+ if (row)
587
+ return row;
588
+ throw new RunAdmissionConflictError('reservation-changed');
589
+ }
590
+ /** Settle every alias of this complete physical/logical execution. */
591
+ async settleExecution(execution) {
592
+ const identity = normalizeStartExecutionIdentity(execution);
593
+ const clock = this.#reservationClock(identity.runId);
594
+ let result;
595
+ try {
596
+ const stage = await this.#schemaStage();
597
+ if (stage === undefined)
598
+ return 0;
599
+ if (stage !== 3)
600
+ throw new ReservationSchemaError('settlement requires current schema');
601
+ result = await this.#db
602
+ .prepare(`UPDATE ${START_IDEMPOTENCY_TABLE} SET state = 'terminal', updated_at = ?
603
+ WHERE run_id = ? AND start_token = ? AND start_table_prefix IS ?
604
+ AND start_workflow_id = ? AND owner_kind = ? AND owner_id = ?
605
+ AND target_kind = ? AND target_id = ? AND thread_id IS ?
606
+ AND state <> 'terminal' RETURNING *`)
607
+ .bind(clock, identity.runId, identity.startToken, identity.tablePrefix, identity.workflowId, identity.owner.kind, identity.owner.id, identity.target.kind, identity.target.id, identity.target.kind === 'agent' ? identity.target.threadId : null)
608
+ .all();
603
609
  }
604
610
  catch (error) {
605
- // A database with no reservation table has no reservation to settle. Any
606
- // other fault is real and must not be mistaken for "nothing to do".
607
611
  if (isMissingReservationTable(error))
608
612
  return 0;
609
- throw new StartReservationUnreadableError(runId, { cause: error });
613
+ throw new StartReservationUnreadableError(identity.runId, {
614
+ cause: error,
615
+ });
616
+ }
617
+ try {
618
+ const keys = new Set();
619
+ for (const raw of reservationResultRows(result)) {
620
+ const row = admissionReservationFromRow(raw, 3);
621
+ if (keys.has(row.key) ||
622
+ row.state !== 'terminal' ||
623
+ row.updatedAt !== clock ||
624
+ !sameReservationExecution(row, identity))
625
+ throw new Error('settlement returned an unexpected reservation');
626
+ keys.add(row.key);
627
+ }
628
+ return keys.size;
629
+ }
630
+ catch (error) {
631
+ throw new StartReservationUnreadableError(identity.runId, {
632
+ cause: error,
633
+ });
634
+ }
635
+ }
636
+ #reservationClock(key) {
637
+ try {
638
+ const clock = this.#now();
639
+ if (!Number.isFinite(clock))
640
+ throw new Error('reservation clock is not finite');
641
+ return clock;
642
+ }
643
+ catch (error) {
644
+ throw new StartReservationUnreadableError(key, { cause: error });
645
+ }
646
+ }
647
+ #nextReservationStamp(reservation) {
648
+ const clock = this.#reservationClock(reservation.key);
649
+ const next = Math.max(clock, reservation.updatedAt + 1);
650
+ if (!Number.isFinite(next) || next <= reservation.updatedAt)
651
+ throw new StartReservationUnreadableError(reservation.key, {
652
+ cause: new Error('reservation update stamp is exhausted'),
653
+ });
654
+ return next;
655
+ }
656
+ async #requireReservationSchema(key) {
657
+ try {
658
+ if ((await this.#schemaStage()) !== 3)
659
+ throw new ReservationSchemaError('mutation requires current schema');
660
+ }
661
+ catch (error) {
662
+ throw new StartReservationUnreadableError(key, { cause: error });
610
663
  }
611
664
  }
612
665
  /**
@@ -621,26 +674,120 @@ export class StartIdempotencyStore {
621
674
  */
622
675
  async read(key) {
623
676
  const safeKey = assertKey(key);
624
- let rows;
677
+ const rows = await this.#readReservations(`SELECT * FROM ${START_IDEMPOTENCY_TABLE} WHERE key = ? LIMIT 2`, [safeKey], safeKey);
678
+ if (rows.length > 1 || (rows[0] !== undefined && rows[0].key !== safeKey)) {
679
+ throw new StartReservationUnreadableError(safeKey, {
680
+ cause: new Error('reservation query did not return the requested singleton key'),
681
+ });
682
+ }
683
+ const row = rows[0];
684
+ return row;
685
+ }
686
+ usesDatabase(binding) {
687
+ return this.#db === binding;
688
+ }
689
+ /** @internal Pure current-stage read, including for an absent key. */
690
+ async readForAdmission(key) {
691
+ const safeKey = assertKey(key);
625
692
  try {
626
- rows = (await this.#db
627
- .prepare(`SELECT key, owner_kind, owner_id, target_kind, target_id, run_id,
628
- thread_id, state, created_at, updated_at
629
- FROM ${START_IDEMPOTENCY_TABLE} WHERE key = ?`)
693
+ const result = await this.#db
694
+ .prepare(`SELECT * FROM ${START_IDEMPOTENCY_TABLE} WHERE key = ? LIMIT 2`)
630
695
  .bind(safeKey)
631
- .all()).results;
696
+ .all();
697
+ const row = decodeStartReservationAdmissionResult(result);
698
+ validateStartReservationAdmissionSchema(await this.#db
699
+ .prepare(`PRAGMA table_xinfo(${START_IDEMPOTENCY_TABLE})`)
700
+ .all());
701
+ if (row !== undefined && row.key !== safeKey)
702
+ throw new ReservationSchemaError('admission returned another key');
703
+ return row;
632
704
  }
633
705
  catch (error) {
634
- if (isMissingReservationTable(error))
635
- return undefined;
636
706
  throw new StartReservationUnreadableError(safeKey, { cause: error });
637
707
  }
638
- const row = rows[0];
639
- return row === undefined ? undefined : reservationFromRow(row);
708
+ }
709
+ async #schemaStage() {
710
+ return reservationSchemaStage(await this.#db
711
+ .prepare(`PRAGMA table_xinfo(${START_IDEMPOTENCY_TABLE})`)
712
+ .all());
713
+ }
714
+ async #readReservations(sql, bindings, key) {
715
+ try {
716
+ let result;
717
+ try {
718
+ result = await this.#db
719
+ .prepare(sql)
720
+ .bind(...bindings)
721
+ .all();
722
+ }
723
+ catch (error) {
724
+ if (isMissingReservationTable(error))
725
+ return [];
726
+ throw error;
727
+ }
728
+ const rows = reservationResultRows(result);
729
+ const stage = await this.#schemaStage();
730
+ if (stage === undefined)
731
+ throw new ReservationSchemaError('row observation has no schema');
732
+ return rows.map((row) => reservationFromRow(row, stage));
733
+ }
734
+ catch (error) {
735
+ throw new StartReservationUnreadableError(key, { cause: error });
736
+ }
737
+ }
738
+ async #migrationStage() {
739
+ const stage = await this.#schemaStage();
740
+ if (stage === undefined)
741
+ throw new ReservationSchemaError('table is missing during initialization');
742
+ if (stage === 0 || stage === 3)
743
+ return stage;
744
+ const predicate = START_IDEMPOTENCY_COLUMNS.slice(10, 10 + stage)
745
+ .map(([name]) => `${name} IS NOT NULL`)
746
+ .join(' OR ');
747
+ const rows = reservationResultRows(await this.#db
748
+ .prepare(`SELECT * FROM ${START_IDEMPOTENCY_TABLE} WHERE ${predicate} LIMIT 1`)
749
+ .all());
750
+ const observed = await this.#schemaStage();
751
+ if (observed === undefined || observed < stage)
752
+ throw new ReservationSchemaError('schema regressed during initialization');
753
+ if (rows.length > 1)
754
+ throw new ReservationSchemaError('partial binding query returned multiple rows');
755
+ for (const row of rows)
756
+ reservationFromRow(row, observed);
757
+ return observed;
640
758
  }
641
759
  /** Create the table and its two access paths. Only `reserve()` reaches this. */
642
760
  async #createSchema() {
643
- await this.#db.prepare(START_IDEMPOTENCY_DDL).run();
761
+ if ((await this.#schemaStage()) === undefined) {
762
+ await this.#db.prepare(START_IDEMPOTENCY_DDL).run();
763
+ }
764
+ for (let index = await this.#migrationStage(); index < START_IDEMPOTENCY_ADDITIONS.length; index += 1) {
765
+ const stage = await this.#migrationStage();
766
+ if (stage < index)
767
+ throw new ReservationSchemaError('schema regressed during initialization');
768
+ if (stage > index)
769
+ continue;
770
+ try {
771
+ await this.#db
772
+ .prepare(`ALTER TABLE ${START_IDEMPOTENCY_TABLE} ADD COLUMN ${START_IDEMPOTENCY_ADDITIONS[index]}`)
773
+ .run();
774
+ }
775
+ catch (error) {
776
+ let observed;
777
+ try {
778
+ observed = await this.#schemaStage();
779
+ }
780
+ catch (readError) {
781
+ if (readError instanceof ReservationSchemaError)
782
+ throw readError;
783
+ throw error;
784
+ }
785
+ if (observed === undefined || observed <= index)
786
+ throw error;
787
+ }
788
+ }
789
+ if ((await this.#schemaStage()) !== 3)
790
+ throw new ReservationSchemaError('initialization did not reach the current schema');
644
791
  await this.#db.prepare(START_IDEMPOTENCY_RUN_INDEX_DDL).run();
645
792
  await this.#db.prepare(START_IDEMPOTENCY_STATE_INDEX_DDL).run();
646
793
  }
@@ -654,217 +801,178 @@ export class StartIdempotencyStore {
654
801
  if (safeRunIds.length === 0)
655
802
  return [];
656
803
  const placeholders = safeRunIds.map(() => '?').join(', ');
657
- let rows;
658
- try {
659
- rows = (await this.#db
660
- .prepare(`SELECT key, owner_kind, owner_id, target_kind, target_id, run_id,
661
- thread_id, state, created_at, updated_at
662
- FROM ${START_IDEMPOTENCY_TABLE} WHERE run_id IN (${placeholders})`)
663
- .bind(...safeRunIds)
664
- .all()).results;
665
- }
666
- catch (error) {
667
- if (isMissingReservationTable(error))
668
- return [];
804
+ const rows = await this.#readReservations(`SELECT * FROM ${START_IDEMPOTENCY_TABLE} WHERE run_id IN (${placeholders})`, safeRunIds, '(run lookup)');
805
+ const requested = new Set(safeRunIds);
806
+ if (rows.some((row) => !requested.has(row.runId))) {
669
807
  throw new StartReservationUnreadableError('(run lookup)', {
670
- cause: error,
808
+ cause: new Error('reservation lookup returned an unrequested run'),
671
809
  });
672
810
  }
673
- return rows.map((row) => reservationFromRow(row));
811
+ return rows;
674
812
  }
675
- async #casState(key, runId, from, to) {
676
- const safeKey = assertKey(key);
677
- if (!isPathSafeId(runId)) {
678
- throw new InvalidStartIdempotencyRequestError('reservation runId must be a URL-path-safe identifier');
679
- }
813
+ }
814
+ export async function beginIdempotentStart(store, request, surface, fence, mutationEpoch) {
815
+ const capturedRequest = captureStartRequest(request);
816
+ const epoch = normalizeMutationEpoch(mutationEpoch);
817
+ const { persisted, live } = surface;
818
+ const capturedSurface = {
819
+ persisted: (row) => Reflect.apply(persisted, surface, [row]),
820
+ live: (row) => Reflect.apply(live, surface, [row]),
821
+ };
822
+ let proof;
823
+ if (fence !== undefined && fence !== 'none') {
680
824
  try {
681
- return (changesOf(await this.#db
682
- .prepare(`UPDATE ${START_IDEMPOTENCY_TABLE}
683
- SET state = ?, updated_at = ?
684
- WHERE key = ? AND run_id = ? AND state = ?`)
685
- .bind(to, this.#now(), safeKey, runId, from)
686
- .run()) > 0);
825
+ const reading = await fence.read();
826
+ if (reading.state === 'proof-only' &&
827
+ reading.proofKey === capturedRequest.key)
828
+ proof = Object.freeze({
829
+ key: capturedRequest.key,
830
+ mutationEpoch: reading.mutationEpoch,
831
+ transitionRevision: reading.transitionRevision,
832
+ });
687
833
  }
688
- catch (error) {
689
- // No table means no reservation, so no transition happened — which is
690
- // exactly what `false` says, and the caller's replay path handles it.
691
- if (isMissingReservationTable(error))
692
- return false;
693
- throw new StartReservationUnreadableError(safeKey, { cause: error });
834
+ catch {
835
+ /* A failed observation cannot authorize nomination. */
694
836
  }
695
837
  }
696
- }
697
- /**
698
- * Resolve an idempotency key into "start this run" or "replay that one".
699
- *
700
- * The order of the checks below IS the semantics:
701
- *
702
- * 1. Reserve. A brand-new key that also wins the claim is the only path that
703
- * starts anything.
704
- * 2. Persisted state, BEFORE the reservation's own state. A run that persisted
705
- * is answerable whatever the reservation says, and reading the row's state
706
- * first would let a stale `started` refuse a retry whose run is sitting
707
- * right there, finished.
708
- * 3. `reserved` with nothing persisted means the first caller died between the
709
- * insert and the claim, having executed nothing — so this caller may take
710
- * the claim and proceed with the SAME runId. That convergence is what makes
711
- * a crashed reservation self-healing instead of a wedged key.
712
- * 4. `started` with nothing persisted is the only ambiguous state in the
713
- * system, and the liveness probe is what resolves it.
714
- * 5. `terminal` with nothing persisted is a completed run whose summary aged
715
- * out. Spent, never re-run.
716
- *
717
- * Throws the applicable structured taxonomy errors; a surface renders them
718
- * through `doErrorResponse` (or its router's equivalent) with no re-mapping.
719
- * Across the public keyed-start surface the eight codes are the five decision
720
- * refusals — IDEMPOTENT_START_OWNER_MISMATCH (403),
721
- * IDEMPOTENT_START_TARGET_MISMATCH (409), IDEMPOTENT_START_PENDING
722
- * (503), IDEMPOTENT_START_UNRESOLVABLE (409), and
723
- * IDEMPOTENT_START_ALREADY_SETTLED (409) — plus IDEMPOTENT_START_UNSUPPORTED
724
- * (503), INVALID_START_IDEMPOTENCY_REQUEST (400), and
725
- * IDEMPOTENT_START_UNREADABLE (503).
726
- */
727
- export async function beginIdempotentStart(store, request, surface, fence) {
728
- const { reservation, created } = await store.reserve(request);
729
- if (created && (await store.claim(reservation.key, reservation.runId))) {
730
- return { kind: 'start', reservation };
838
+ const { reservation, created } = await store.reserve(capturedRequest);
839
+ let decision;
840
+ // A creator can read back another caller's released reservation.
841
+ if (created &&
842
+ reservation.binding.kind === 'unbound' &&
843
+ reservation.state === 'reserved' &&
844
+ reservation.updatedAt === reservation.createdAt) {
845
+ const claimed = await store.claimReservation(reservation);
846
+ if (claimed !== undefined)
847
+ return { kind: 'start', reservation: claimed };
848
+ decision = await resolveLostClaim(store, reservation, capturedSurface);
731
849
  }
732
- const decision = await resolveExistingReservation(store, reservation, surface);
733
- if (decision.kind === 'replay') {
734
- await rebindProofRun(fence, decision.reservation);
850
+ else
851
+ decision = await resolveExistingReservation(store, reservation, capturedSurface, true);
852
+ if (decision.kind === 'replay' &&
853
+ proof !== undefined &&
854
+ fence !== undefined &&
855
+ fence !== 'none') {
856
+ const row = decision.reservation;
857
+ if (row.binding.kind === 'bound' &&
858
+ row.binding.execution.tablePrefix !== null) {
859
+ try {
860
+ if (row.targetKind === 'agent' && row.threadId === undefined)
861
+ throw new InvalidExecutionIdentityError('admission');
862
+ await fence.rebindProofRun({
863
+ reservation: row,
864
+ execution: {
865
+ ...row.binding.execution,
866
+ tablePrefix: row.binding.execution.tablePrefix,
867
+ owner: row.owner,
868
+ target: row.targetKind === 'agent'
869
+ ? {
870
+ kind: 'agent',
871
+ id: row.targetId,
872
+ threadId: row.threadId,
873
+ }
874
+ : { kind: 'workflow', id: row.targetId },
875
+ },
876
+ proof,
877
+ mutationEpoch: epoch,
878
+ reservationStore: store,
879
+ });
880
+ }
881
+ catch (error) {
882
+ console.error(JSON.stringify({
883
+ type: 'start-reservation-proof-rebind-failed',
884
+ key: row.key,
885
+ runId: row.runId,
886
+ error: error instanceof Error ? error.message : String(error),
887
+ }));
888
+ }
889
+ }
735
890
  }
736
891
  return decision;
737
892
  }
738
- /**
739
- * Re-assert a proof-only fence's binding to the run this key already made.
740
- *
741
- * The binding is written by `RunnerRuntime.start`, which a REPLAY never
742
- * reaches — so without this, a proof run whose fence lost its `proof_run_id`
743
- * (the fence was moved away and back onto the same key while its run survived)
744
- * would be a run the deployment can read but can no longer RESUME: proof-only
745
- * admits existing work only for `proof_run_id`, and there would be none.
746
- *
747
- * Every guard lives in `recordProofRun`'s own CAS, which is why this can be
748
- * unconditional and best-effort: it changes nothing unless the fence is in
749
- * proof-only under EXACTLY this key with the slot empty or already holding this
750
- * run. A different key, a different state, a different proof run — all are zero
751
- * rows and no harm. A failure is swallowed rather than raised, because the
752
- * caller is being handed the persisted state of a run that already happened,
753
- * and refusing that read would answer a successful retry with an error while
754
- * changing nothing about the run.
755
- */
756
- async function rebindProofRun(fence, reservation) {
757
- if (fence === undefined || fence === 'none')
758
- return;
893
+ function decodePersistedStart(value, row) {
759
894
  try {
760
- // The reservation KEY is passed as the fence's PROOF KEY: proof-only
761
- // nominates one idempotency key, and `admitsRunStart` admits the start
762
- // carrying it — so the two identifiers are the same string by construction,
763
- // and a rebind for any other key is the zero-row no-op described above.
764
- await fence.recordProofRun(reservation.key, reservation.runId);
765
- }
766
- catch (error) {
767
- console.error(JSON.stringify({
768
- type: 'start-reservation-proof-rebind-failed',
769
- key: reservation.key,
770
- runId: reservation.runId,
771
- error: error instanceof Error ? error.message : String(error),
772
- }));
773
- }
774
- }
775
- async function resolveExistingReservation(store, observed, surface) {
776
- const persisted = await surface.persisted(observed);
777
- if (persisted !== undefined) {
778
- return { kind: 'replay', reservation: observed, persisted };
779
- }
780
- if (observed.state === 'reserved') {
781
- if (await store.claim(observed.key, observed.runId)) {
782
- return { kind: 'start', reservation: observed };
783
- }
784
- // The claim was taken between the read and here. Re-read rather than
785
- // assuming: the winner may already have persisted, in which case the right
786
- // answer is its outcome and not a refusal.
787
- const current = await store.read(observed.key);
788
- if (current === undefined || current.runId !== observed.runId) {
789
- // The reservation vanished or was replaced under us. Refusing is the only
790
- // safe answer — a caller that retries gets a clean reserve, while
791
- // silently starting here would start a run under an id nothing reserved.
792
- throw new StartReservationUnreadableError(observed.key);
793
- }
794
- return resolveClaimedReservation(current, surface);
795
- }
796
- return resolveClaimedReservation(observed, surface);
797
- }
798
- async function resolveClaimedReservation(reservation, surface) {
799
- if (reservation.state === 'terminal') {
800
- throw new IdempotentStartAlreadySettledError(reservation);
895
+ if (value === null ||
896
+ typeof value !== 'object' ||
897
+ Array.isArray(value) ||
898
+ !Object.hasOwn(value, 'kind') ||
899
+ !Object.hasOwn(value, 'execution'))
900
+ throw new Error('persisted start result is malformed');
901
+ const { kind, execution: raw } = value;
902
+ if ((kind !== 'initial' && kind !== 'result') ||
903
+ (kind === 'initial'
904
+ ? Object.hasOwn(value, 'value')
905
+ : !Object.hasOwn(value, 'value')))
906
+ throw new Error('persisted start result is malformed');
907
+ const { tablePrefix, workflowId, runId, startToken, owner, target } = raw;
908
+ const execution = normalizeStartExecutionIdentity({
909
+ tablePrefix,
910
+ workflowId,
911
+ runId,
912
+ startToken,
913
+ owner,
914
+ target,
915
+ });
916
+ if (execution.tablePrefix !== tablePrefix)
917
+ throw new Error('persisted start prefix is not canonical');
918
+ assertReservationStartIdentity(row, execution);
919
+ return kind === 'initial'
920
+ ? { kind, execution }
921
+ : { kind, execution, value: value.value };
801
922
  }
802
- if (await surface.live(reservation)) {
803
- throw new IdempotentStartPendingError(reservation);
923
+ catch (cause) {
924
+ throw new StartReservationUnreadableError(row.key, { cause });
804
925
  }
805
- throw new IdempotentStartUnresolvableError(reservation);
806
926
  }
807
- /**
808
- * Give back a claim that the EXECUTION FENCE refused, then re-throw.
809
- *
810
- * Homed here, beside the state machine, rather than written out at each start
811
- * site: the rollback is only correct for this one error family, and a copy that
812
- * widened its catch — to "any start failure", say — would hand the next retry a
813
- * fresh run after a start that may well have executed. Keeping the predicate
814
- * and the CAS in one function is what stops that widening from being a one-line
815
- * edit somebody makes in a hurry.
816
- *
817
- * THE CLASS INVARIANT THIS RELIES ON. Giving a claim back is only sound for a
818
- * failure that provably executed NOTHING, and that is a property of the two
819
- * fence refusal codes rather than of the JavaScript class carrying them:
820
- *
821
- * EXECUTION_FENCED is authored at a gate — the run object's start
822
- * route, before any of its own reads or writes,
823
- * and `RunnerRuntime.#assertStartFence`, before
824
- * the run lock and before core mints anything.
825
- * EXECUTION_FENCE_UNREADABLE is authored by the fence READ that fronts those
826
- * same gates, which is even earlier.
827
- *
828
- * Neither code is reachable from anywhere past the point of execution, so a
829
- * refusal carrying one is pre-execution wherever it was observed.
830
- *
831
- * Which is why the predicate is `isExecutionFenceRefusal` — the widened one,
832
- * which admits the wire rebuild — and NOT `instanceof ExecutionFencedError`.
833
- * Both of this function's callers sit on the far side of a Durable Object
834
- * boundary in every DO-backed host: the run object throws, `doErrorResponse`
835
- * renders, and `doSummary` (or the agent topology's `errorFrom`) rebuilds a
836
- * `RunRouteError` carrying the same status and the same structured reason but
837
- * not the same class. An instanceof-only test would answer "not a fence
838
- * refusal" for exactly the deployments this rollback exists to protect, and a
839
- * drained-then-reopened deployment would find every key that was in flight
840
- * permanently stuck at UNRESOLVABLE. In-process hosts (a `{ storage }` runtime
841
- * wired straight into the router) do throw the class, so both shapes are live
842
- * and one predicate has to cover them.
843
- *
844
- * The rollback itself is best-effort: it runs while the deployment is already
845
- * refusing to execute, so its own failure must not replace the fence's refusal
846
- * with a storage error the caller cannot act on. A rollback that does not land
847
- * leaves an UNRESOLVABLE reservation — recoverable by investigation — while a
848
- * swallowed fence refusal would leave the caller believing the deployment is
849
- * broken rather than fenced.
850
- */
851
- export async function rollbackFencedStart(store, key, runId, error) {
852
- if (isExecutionFenceRefusal(error)) {
853
- try {
854
- await store.release(key, runId);
927
+ async function resolveExistingReservation(store, observed, surface, mayClaim) {
928
+ if (observed.binding.kind === 'legacy') {
929
+ if (observed.state === 'terminal')
930
+ throw new IdempotentStartAlreadySettledError(observed);
931
+ throw new IdempotentStartUnresolvableError(observed);
932
+ }
933
+ const value = await surface.persisted(observed);
934
+ if (value !== undefined) {
935
+ const persisted = decodePersistedStart(value, observed);
936
+ if (observed.binding.kind === 'bound' &&
937
+ !sameReservationExecution(observed, persisted.execution)) {
938
+ if (observed.state === 'terminal')
939
+ throw new IdempotentStartAlreadySettledError(observed);
940
+ throw new IdempotentStartUnresolvableError(observed);
855
941
  }
856
- catch (rollbackError) {
857
- console.error(JSON.stringify({
858
- type: 'start-reservation-rollback-failed',
859
- key,
860
- runId,
861
- error: rollbackError instanceof Error
862
- ? rollbackError.message
863
- : String(rollbackError),
864
- }));
942
+ if (persisted.kind === 'result') {
943
+ if (observed.binding.kind === 'bound')
944
+ return {
945
+ kind: 'replay',
946
+ reservation: observed,
947
+ persisted: persisted.value,
948
+ };
949
+ if (observed.state === 'terminal')
950
+ throw new IdempotentStartAlreadySettledError(observed);
951
+ const reservation = await store.associateReservation(observed, persisted.execution);
952
+ return { kind: 'replay', reservation, persisted: persisted.value };
865
953
  }
866
954
  }
867
- throw error;
955
+ else if (mayClaim &&
956
+ observed.state === 'reserved' &&
957
+ observed.binding.kind === 'unbound') {
958
+ if (await surface.live(observed))
959
+ throw new IdempotentStartPendingError(observed);
960
+ const claimed = await store.claimReservation(observed);
961
+ if (claimed !== undefined)
962
+ return { kind: 'start', reservation: claimed };
963
+ return resolveLostClaim(store, observed, surface);
964
+ }
965
+ if (observed.state === 'terminal')
966
+ throw new IdempotentStartAlreadySettledError(observed);
967
+ if (await surface.live(observed))
968
+ throw new IdempotentStartPendingError(observed);
969
+ throw new IdempotentStartUnresolvableError(observed);
970
+ }
971
+ async function resolveLostClaim(store, observed, surface) {
972
+ const current = await store.readForAdmission(observed.key);
973
+ if (current === undefined || !sameReservationIdentity(current, observed))
974
+ throw new StartReservationUnreadableError(observed.key);
975
+ return resolveExistingReservation(store, current, surface, false);
868
976
  }
869
977
  /**
870
978
  * Resolve a surface's reservation wiring, refusing a key the host cannot