@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,17 +1,9 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
- // createFlowsafeWorker — the whole production-Worker skeleton the deploy
3
- // template and the showcase host previously carried as near-byte copies:
4
- // the /healthz → routers → 404 fetch pipeline over one actor resolver, the
5
- // alarm-driven maintenance (deadline, sweep, purge, and optional schedule tick
6
- // never share an invocation). Hosts stay thin shells: they supply workflows,
7
- // their identity seam (buildVerifier), and their deployment-specific hooks —
8
- // preRoutes (extra unauthenticated/authenticated mounts), beforeStart/
9
- // beforeResume (e.g. a budget charge), notify (reviewer-facing transport), and
10
- // extraPurgeDuties (e.g. a host-specific purge). Everything here is structural:
11
- // host-kit never imports @cloudflare/workers-types.
12
2
  import { APPROVAL_ROLES, createActorResolver, createApprovalRouter, createResourceOwnershipSchema, RESOURCE_OWNERSHIP_TABLE, trustAutomationPrincipal, } from '../approval-api/index.js';
13
3
  import { createAuditProxyDurableObjectBinding, createAuditProxyQueue, } from '../audit-export/index.js';
4
+ import { parseRunRetentionCursor } from '../do-runner/d1-storage.js';
14
5
  import { credentialsMatch } from '../do-runner/deployment-identity.js';
6
+ import { InvalidMutationEpochError, normalizeMutationEpoch, } from '../do-runner/execution-admission.js';
15
7
  import { assertExecutionFenceState, DEPLOYMENT_IDENTITY_HEADER, DeploymentIdentityError, DeploymentInventory, DoStatusError, deploymentIdentityHeaders, ensureDeploymentIdentityBindings, executionFenceFor, executionFenceReadingPayload, InvalidInventoryRequestError, isInventoryCategory, purgeExpiredBackgroundTasks, purgeExpiredNotifications, purgeExpiredScheduleTriggers, purgeExpiredThreadState, purgeExpiredThreads, purgeExpiredWorkflowRuns, START_IDEMPOTENCY_TABLE, startIdempotencyFor, sweepExpiredRunDeadlines, verifyDurableObjectDeploymentIdentity, verifyDurableObjectDeploymentRequest, } from '../do-runner/index.js';
16
8
  import { validateTablePrefix } from '../do-runner/table-prefix.js';
17
9
  import { readBoundedBody } from '../http-body.js';
@@ -19,7 +11,7 @@ import { abandonApprovalsForRun } from './approval-bridge.js';
19
11
  import { bearerActorAuthenticator } from './bearer-auth.js';
20
12
  import { createDoRunTopology, } from './do-run-topology.js';
21
13
  import { numberVar, optionalNumberVar, selfDecisionPolicyVar, } from './env-vars.js';
22
- import { approvalStoreFactoryFor, buildHostApprovalService, maintenancePrincipal, reconcileApprovalsOnStatusDetached, runApprovalRetentionPurge, runSlaSweepMaintenance, } from './host-approval-service.js';
14
+ import { approvalStoreFactoryFor, buildHostApprovalService, hostErrorText, maintenancePrincipal, reconcileApprovalsOnStatusDetached, runApprovalRetentionPurge, runSlaSweepMaintenance, } from './host-approval-service.js';
23
15
  import { createHubTopology } from './hub-topology.js';
24
16
  import { MAINTENANCE_RECEIPT_HEADER, mintMaintenanceReceipt, verifyAsymmetricMaintenanceCapability, verifyMaintenanceCapability, } from './maintenance-capability.js';
25
17
  import { createRunRouter } from './run-router.js';
@@ -41,6 +33,7 @@ function buildConfiguredApprovalService(config, env, topology, options) {
41
33
  allowSelfDecision: options.allowSelfDecision,
42
34
  stream: options.stream,
43
35
  executionFence: options.executionFence,
36
+ workflowTablePrefix: options.workflowTablePrefix,
44
37
  });
45
38
  }
46
39
  /**
@@ -58,6 +51,7 @@ export function createFlowsafeRunnerLifecycle(config, env, options = {}) {
58
51
  const service = buildConfiguredApprovalService(config, env, topology, {
59
52
  store: approvalStoreFactoryFor(env.DB, storageTablePrefix).store(),
60
53
  executionFence: executionFenceForEnv(env),
54
+ workflowTablePrefix: (storageTablePrefix ?? '').toLowerCase(),
61
55
  waitUntil: options.waitUntil,
62
56
  notify: config.notify?.(env),
63
57
  allowSelfDecision,
@@ -137,6 +131,10 @@ async function validateFleetChannelTopology(env) {
137
131
  throw new Error('external fleet release has a direct audit queue binding');
138
132
  }
139
133
  }
134
+ const RETENTION_CURSOR_SEAM_REASON = 'retention purge requires advanceRetentionCursor';
135
+ function hasRetentionCursorSeam(context) {
136
+ return typeof context?.advanceRetentionCursor === 'function';
137
+ }
140
138
  function json(payload, status = 200) {
141
139
  return new Response(JSON.stringify(payload), {
142
140
  status,
@@ -145,26 +143,6 @@ function json(payload, status = 200) {
145
143
  }
146
144
  const MAINTENANCE_ADMIN_SECRET_PATTERN = /^[\x21-\x7e]{32,256}$/;
147
145
  const FLEET_SPEC_DIGEST_PATTERN = /^[a-f0-9]{64}$/;
148
- /**
149
- * The credential preamble EVERY /admin surface runs before it does anything.
150
- *
151
- * One function rather than a copy per route because this is the trust boundary
152
- * itself (docs/security-threat-model.md, "The provisioning boundary"): it
153
- * proves MAINTENANCE_ADMIN_SECRET is configured, proves it is DISTINCT from the
154
- * deployment identity secret (sharing them would let a Worker-to-DO credential
155
- * move the fence, and vice versa), and constant-time compares the request's
156
- * Bearer token against it. A second copy is a second place for one of those
157
- * three to be dropped in a hurry, and the inventory route lands here next.
158
- *
159
- * The surfaces differ in exactly ONE thing, which is why it is a parameter
160
- * rather than a fork: what an ABSENT secret means. `/admin/execution-fence`
161
- * always refuses — the fence is the control that stops a deployment executing,
162
- * so an unauthenticated caller must never reach it. The maintenance routes
163
- * delegate instead when the fleet requires capability tokens, because there the
164
- * Durable Object verifies a signed capability and this Worker is only a relay;
165
- * the longer credential cap applies to that path alone, since a capability
166
- * token is not a shared secret.
167
- */
168
146
  async function authorizeAdminCredential(request, env, options) {
169
147
  const { surface } = options;
170
148
  const unavailable = (reason) => {
@@ -183,10 +161,13 @@ async function authorizeAdminCredential(request, env, options) {
183
161
  response: json({ error: 'authentication required' }, 401),
184
162
  });
185
163
  const expected = env.MAINTENANCE_ADMIN_SECRET;
186
- const delegating = expected === undefined && options.delegateWhenUnconfigured;
187
- if (!delegating) {
188
- if (expected === undefined ||
189
- !MAINTENANCE_ADMIN_SECRET_PATTERN.test(expected)) {
164
+ const delegating = options.delegateCapability;
165
+ if (expected === undefined) {
166
+ if (!delegating)
167
+ return unavailable(`${surface} is not configured`);
168
+ }
169
+ else {
170
+ if (!MAINTENANCE_ADMIN_SECRET_PATTERN.test(expected)) {
190
171
  return unavailable(`${surface} is not configured`);
191
172
  }
192
173
  if (await credentialsMatch(expected, env.DEPLOYMENT_IDENTITY_SECRET)) {
@@ -198,7 +179,13 @@ async function authorizeAdminCredential(request, env, options) {
198
179
  if (!credential || credential.length > maximumCredentialLength) {
199
180
  return unauthenticated();
200
181
  }
201
- if (expected !== undefined &&
182
+ // When maintenance routes delegate a fleet capability
183
+ // (FLEET_MAINTENANCE_CAPABILITIES=required), the Maintenance object verifies
184
+ // it; a raw maintenance secret cannot substitute for the capability.
185
+ // Delegation skips the Bearer comparison here. Without delegation, the
186
+ // Bearer must match MAINTENANCE_ADMIN_SECRET when it is configured.
187
+ if (!delegating &&
188
+ expected !== undefined &&
202
189
  !(await credentialsMatch(credential, expected))) {
203
190
  return unauthenticated();
204
191
  }
@@ -223,10 +210,7 @@ async function maintenanceAdminResponse(request, env) {
223
210
  }
224
211
  const gate = await authorizeAdminCredential(request, env, {
225
212
  surface: 'maintenance administration',
226
- // An unconfigured secret is survivable HERE and only here: a fleet that
227
- // requires capability tokens authenticates at the maintenance DO, which
228
- // verifies a signed capability this Worker only relays.
229
- delegateWhenUnconfigured: env.FLEET_MAINTENANCE_CAPABILITIES === 'required',
213
+ delegateCapability: env.FLEET_MAINTENANCE_CAPABILITIES === 'required',
230
214
  });
231
215
  if (!gate.authorized)
232
216
  return gate.response;
@@ -319,7 +303,7 @@ async function executionFenceAdminResponse(request, env) {
319
303
  // Unconfigured is 503, never open: the fence is the control that stops a
320
304
  // deployment executing, so an unauthenticated caller must never move it.
321
305
  // There is no capability-token relay behind this route to delegate to.
322
- delegateWhenUnconfigured: false,
306
+ delegateCapability: false,
323
307
  });
324
308
  if (!gate.authorized)
325
309
  return gate.response;
@@ -349,8 +333,11 @@ async function executionFenceAdminResponse(request, env) {
349
333
  expected: assertExecutionFenceState(body.expected, 'expected'),
350
334
  next: assertExecutionFenceState(body.next, 'next'),
351
335
  ...(body.proofKey === undefined ? {} : { proofKey: body.proofKey }),
336
+ expectedMutationEpoch: body.expectedMutationEpoch,
337
+ expectedRevision: body.expectedRevision,
338
+ advanceMutationEpoch: body.advanceMutationEpoch,
352
339
  });
353
- return json({ state: reading.state });
340
+ return json(executionFenceReadingPayload(reading));
354
341
  }
355
342
  catch (error) {
356
343
  if (error instanceof DoStatusError) {
@@ -361,7 +348,7 @@ async function executionFenceAdminResponse(request, env) {
361
348
  }
362
349
  console.error(JSON.stringify({
363
350
  type: 'execution-fence-admin-error',
364
- reason: error instanceof Error ? error.message : String(error),
351
+ reason: hostErrorText(error, true),
365
352
  }));
366
353
  return json({ error: 'execution fence administration failed' }, 500);
367
354
  }
@@ -420,7 +407,7 @@ async function inventoryAdminResponse(request, env, storageTablePrefix) {
420
407
  // Unconfigured is 503, never open: this read enumerates every outstanding
421
408
  // run, approval, and reservation on the deployment. There is no capability
422
409
  // relay behind it to delegate to, either.
423
- delegateWhenUnconfigured: false,
410
+ delegateCapability: false,
424
411
  });
425
412
  if (!gate.authorized)
426
413
  return gate.response;
@@ -459,22 +446,27 @@ async function inventoryAdminResponse(request, env, storageTablePrefix) {
459
446
  }
460
447
  console.error(JSON.stringify({
461
448
  type: 'inventory-admin-error',
462
- reason: error instanceof Error ? error.message : String(error),
449
+ reason: hostErrorText(error, true),
463
450
  }));
464
451
  return json({ error: 'deployment inventory failed' }, 500);
465
452
  }
466
453
  }
467
454
  export function createFlowsafeWorker(config) {
455
+ const epochSource = config.mutationEpoch;
456
+ if (typeof epochSource !== 'function')
457
+ normalizeMutationEpoch(epochSource);
468
458
  const storageTablePrefix = validateTablePrefix(config.storageTablePrefix, 'storageTablePrefix');
469
459
  // Authenticate before constructing request-scoped services.
470
- const buildResolve = (env, topology, waitUntil, notify, selfDecision, stream) => {
460
+ const buildResolve = (env, topology, waitUntil, notify, selfDecision, stream, mutationEpoch) => {
471
461
  const base = createActorResolver({
462
+ mutationEpoch,
472
463
  authenticate: bearerActorAuthenticator(config.buildVerifier(env)),
473
464
  storeFactory: approvalStoreFactoryFor(env.DB, storageTablePrefix),
474
465
  deploymentTag: env.DEPLOYMENT_TENANT,
475
466
  buildService: (store) => buildConfiguredApprovalService(config, env, topology, {
476
467
  store,
477
468
  executionFence: executionFenceForEnv(env),
469
+ workflowTablePrefix: (storageTablePrefix ?? '').toLowerCase(),
478
470
  waitUntil,
479
471
  notify,
480
472
  stream,
@@ -508,10 +500,10 @@ export function createFlowsafeWorker(config) {
508
500
  selfDecisionCache.set(raw, policy);
509
501
  return policy;
510
502
  };
511
- async function runPurgeMaintenance(env, trigger) {
503
+ async function runPurgeMaintenance(env, trigger, context) {
512
504
  const failures = [];
513
505
  const recordFailure = (surface, error) => {
514
- const failure = String(error);
506
+ const failure = hostErrorText(error).slice(0, 256);
515
507
  failures.push(`${surface}: ${failure}`);
516
508
  console.error(JSON.stringify({
517
509
  type: 'maintenance-error',
@@ -522,12 +514,31 @@ export function createFlowsafeWorker(config) {
522
514
  };
523
515
  let purged;
524
516
  try {
517
+ const advanceCursor = context.advanceRetentionCursor;
518
+ const db = env.DB;
519
+ const prepare = db.prepare;
520
+ const batch = db.batch;
521
+ if (typeof prepare !== 'function' || typeof batch !== 'function') {
522
+ throw new Error('retention purge requires database.prepare() and batch()');
523
+ }
524
+ const retentionDb = {
525
+ prepare: prepare.bind(db),
526
+ batch: batch.bind(db),
527
+ };
528
+ const storedCursor = parseRunRetentionCursor(context.retentionCursor);
529
+ const cursor = storedCursor?.tablePrefix ===
530
+ (storageTablePrefix?.toLowerCase() ?? '') &&
531
+ storedCursor.startIdempotencyTable === START_IDEMPOTENCY_TABLE
532
+ ? storedCursor
533
+ : undefined;
525
534
  const artifactStore = config.artifactStore?.(env);
526
535
  // The resource registry is lazy like Mastra's snapshot table. Retention
527
536
  // may be the first resource-aware operation in a fresh deployment, so
528
537
  // initialize it before asking the atomic purge to reference it.
529
- await createResourceOwnershipSchema(env.DB);
530
- purged = await purgeExpiredWorkflowRuns(env.DB, {
538
+ await createResourceOwnershipSchema(retentionDb);
539
+ purged = await purgeExpiredWorkflowRuns(retentionDb, {
540
+ cursor,
541
+ advanceCursor,
531
542
  // allowZero: RUN_RETENTION_DAYS=0 means "purge terminal runs now".
532
543
  ttlMs: numberVar(env.RUN_RETENTION_DAYS, 30, 'RUN_RETENTION_DAYS', {
533
544
  allowZero: true,
@@ -536,21 +547,9 @@ export function createFlowsafeWorker(config) {
536
547
  60 *
537
548
  60 *
538
549
  1000,
539
- // Pairs each expired run's R2 artifacts with its snapshot-row deletion
540
- // (artifacts BEFORE the row — the row is the only record of their keys).
541
- // Undefined on hosts that wire no R2, so the purge stays byte-identical.
542
550
  artifactStore,
543
551
  tablePrefix: storageTablePrefix,
544
- // Snapshot + owner release share one D1 transaction, so retention
545
- // cannot leave unbounded run-ownership tombstones or expose a live row
546
- // without its authorization record.
547
552
  resourceOwnerTable: RESOURCE_OWNERSHIP_TABLE,
548
- // Start reservations join the same transaction, for the same reason:
549
- // an idempotency key must never be reaped while the run it names is
550
- // still readable, or the next retry of that key would start a second
551
- // run beside the live one. The horizon defaults to run retention —
552
- // START_IDEMPOTENCY_RETENTION_DAYS is what a host sets when its callers
553
- // retry for longer than it keeps run summaries.
554
553
  startIdempotencyTable: START_IDEMPOTENCY_TABLE,
555
554
  ...(env.START_IDEMPOTENCY_RETENTION_DAYS === undefined
556
555
  ? {}
@@ -566,9 +565,6 @@ export function createFlowsafeWorker(config) {
566
565
  catch (error) {
567
566
  recordFailure('retention-purge', error);
568
567
  }
569
- // Own containment (inside runApprovalRetentionPurge), same isolation as
570
- // the snapshot purge above: a failure in any one purge duty must never
571
- // stop the others.
572
568
  const approvalPurge = await runApprovalRetentionPurge({
573
569
  store: approvalStoreFactoryFor(env.DB, storageTablePrefix).store(),
574
570
  retentionDays: env.APPROVAL_RETENTION_DAYS,
@@ -578,11 +574,6 @@ export function createFlowsafeWorker(config) {
578
574
  failures.push(`approval-retention-purge: ${approvalPurge.error}`);
579
575
  }
580
576
  const approvalsPurged = approvalPurge.ok ? approvalPurge.value : undefined;
581
- // Agent-memory thread TTL, opt-in.
582
- // Its OWN try/catch, like every sibling duty above and below: isolating one
583
- // loop while a sibling shares its failure is a defect this codebase has
584
- // already shipped once — a wedged thread purge must cost the run-snapshot
585
- // purge, the approval purge, and the extra duties nothing.
586
577
  let threadsPurged;
587
578
  let threadMessagesPurged;
588
579
  // optionalNumberVar, not numberVar: this var GATES the duty rather than
@@ -604,9 +595,6 @@ export function createFlowsafeWorker(config) {
604
595
  recordFailure('thread-retention-purge', error);
605
596
  }
606
597
  }
607
- // Background-task TTL cleanup (opt-in). Its OWN try/catch, like
608
- // every sibling duty: a wedged background-task purge must cost the
609
- // run-snapshot, approval, and thread purges nothing.
610
598
  let backgroundTasksPurged;
611
599
  if (config.backgroundTasks) {
612
600
  try {
@@ -620,8 +608,6 @@ export function createFlowsafeWorker(config) {
620
608
  recordFailure('background-task-purge', error);
621
609
  }
622
610
  }
623
- // Notification TTL cleanup (opt-in). Its OWN try/catch, like every sibling
624
- // duty. optionalNumberVar (GATES the duty; unset/garbage => do not delete).
625
611
  let notificationsPurged;
626
612
  const notificationRetentionDays = optionalNumberVar(env.NOTIFICATION_RETENTION_DAYS, 'NOTIFICATION_RETENTION_DAYS', { allowZero: true });
627
613
  if (notificationRetentionDays !== undefined) {
@@ -635,7 +621,6 @@ export function createFlowsafeWorker(config) {
635
621
  recordFailure('notification-purge', error);
636
622
  }
637
623
  }
638
- // Thread-state TTL cleanup (opt-in). Same isolation + opt-in posture.
639
624
  let threadStatePurged;
640
625
  const threadStateRetentionDays = optionalNumberVar(env.THREAD_STATE_RETENTION_DAYS, 'THREAD_STATE_RETENTION_DAYS', { allowZero: true });
641
626
  if (threadStateRetentionDays !== undefined) {
@@ -649,9 +634,6 @@ export function createFlowsafeWorker(config) {
649
634
  recordFailure('thread-state-purge', error);
650
635
  }
651
636
  }
652
- // Schedule-trigger history TTL cleanup (opt-in). Same isolation + opt-in
653
- // posture. Only the fire HISTORY expires; schedule config rows are reaped
654
- // only at deployment teardown.
655
637
  let scheduleTriggersPurged;
656
638
  const scheduleTriggerRetentionDays = optionalNumberVar(env.SCHEDULE_TRIGGER_RETENTION_DAYS, 'SCHEDULE_TRIGGER_RETENTION_DAYS', { allowZero: true });
657
639
  if (scheduleTriggerRetentionDays !== undefined) {
@@ -717,7 +699,7 @@ export function createFlowsafeWorker(config) {
717
699
  return { ok: true, value: undefined };
718
700
  }
719
701
  catch (error) {
720
- const failure = String(error);
702
+ const failure = hostErrorText(error);
721
703
  console.error(JSON.stringify({
722
704
  type: 'schedule-tick-error',
723
705
  trigger,
@@ -756,7 +738,7 @@ export function createFlowsafeWorker(config) {
756
738
  return { ok: true, value: undefined };
757
739
  }
758
740
  catch (error) {
759
- const failure = String(error);
741
+ const failure = hostErrorText(error);
760
742
  console.error(JSON.stringify({
761
743
  type: 'deadline-sweep-error',
762
744
  trigger,
@@ -768,6 +750,7 @@ export function createFlowsafeWorker(config) {
768
750
  return {
769
751
  async fetch(request, env, ctx) {
770
752
  try {
753
+ const mutationEpoch = normalizeMutationEpoch(typeof epochSource === 'function' ? epochSource(env) : epochSource);
771
754
  await ensureDeploymentIdentityBindings(env);
772
755
  await validateFleetChannelTopology(env);
773
756
  const url = new URL(request.url);
@@ -803,10 +786,10 @@ export function createFlowsafeWorker(config) {
803
786
  const hubTopology = createHubTopology(hub, env.DEPLOYMENT_IDENTITY_SECRET);
804
787
  streamSink = (event) => waitUntil(hubTopology.publish(event).catch((error) => console.error(JSON.stringify({
805
788
  type: 'stream-publish-error',
806
- reason: error instanceof Error ? error.message : String(error),
789
+ reason: hostErrorText(error, true),
807
790
  }))));
808
791
  }
809
- const resolve = buildResolve(env, topology, waitUntil, notify, selfDecision, streamSink);
792
+ const resolve = buildResolve(env, topology, waitUntil, notify, selfDecision, streamSink, mutationEpoch);
810
793
  if (config.preRoutes) {
811
794
  const preResponse = await config.preRoutes(request, env, ctx, {
812
795
  resolve,
@@ -887,10 +870,11 @@ export function createFlowsafeWorker(config) {
887
870
  startIdempotency: {
888
871
  store: startIdempotencyForEnv(env),
889
872
  live: topology.startLiveness,
873
+ persistedStart: topology.persistedStart,
890
874
  executionFence: executionFenceForEnv(env),
891
875
  },
892
876
  beforeStart: beforeStart
893
- ? (context, workflowId, inputData) => beforeStart(context, env, workflowId, inputData)
877
+ ? (context, workflowId, inputData, requestContext) => beforeStart(context, env, workflowId, inputData, requestContext)
894
878
  : undefined,
895
879
  beforeResume: beforeResume
896
880
  ? (context, workflowId, runId, body) => beforeResume(context, env, workflowId, runId, body)
@@ -907,17 +891,20 @@ export function createFlowsafeWorker(config) {
907
891
  if (error instanceof DeploymentIdentityError) {
908
892
  console.error(JSON.stringify({
909
893
  type: 'deployment-identity-error',
910
- reason: error.message,
894
+ reason: hostErrorText(error, true),
911
895
  }));
912
896
  return json({ error: 'deployment unavailable' }, 503);
913
897
  }
898
+ if (error instanceof InvalidMutationEpochError) {
899
+ return json({ error: error.message, reason: error.reason }, error.status);
900
+ }
914
901
  // Backstop: a mounted router (or any handler fault) that THROWS before
915
902
  // returning a Response — e.g. a future unguarded path decode — is
916
903
  // contained as a generic 500 here rather than rejecting out of fetch()
917
904
  // as an unhandled promise. Never surface error.message to the client.
918
905
  console.error(JSON.stringify({
919
906
  type: 'worker-fetch-error',
920
- reason: error instanceof Error ? error.message : String(error),
907
+ reason: hostErrorText(error, true),
921
908
  }));
922
909
  return json({ error: 'internal error' }, 500);
923
910
  }
@@ -947,12 +934,28 @@ export function createFlowsafeWorker(config) {
947
934
  });
948
935
  }
949
936
  if (duty === 'purge') {
950
- return await runPurgeMaintenance(env, duty);
937
+ if (!hasRetentionCursorSeam(context)) {
938
+ // The same refusal the tick duty makes below for an unwired
939
+ // builder: the cursor seam is part of the purge's wiring, not one
940
+ // of its surfaces, so a host that omits it gets the misconfig
941
+ // named rather than its remaining surfaces purged and the run
942
+ // retention reported as failed. MaintenancePurgeDutyContext
943
+ // requires the seam; this is the check for hosts types do not
944
+ // reach.
945
+ console.error(JSON.stringify({
946
+ type: 'config-error',
947
+ var: 'maintenance.purge.advanceRetentionCursor',
948
+ trigger: duty,
949
+ reason: RETENTION_CURSOR_SEAM_REASON,
950
+ }));
951
+ return { ok: false, error: RETENTION_CURSOR_SEAM_REASON };
952
+ }
953
+ return await runPurgeMaintenance(env, duty, context);
951
954
  }
952
955
  return await runScheduleTickDuty(env, duty);
953
956
  }
954
957
  catch (error) {
955
- const failure = String(error);
958
+ const failure = hostErrorText(error);
956
959
  console.error(JSON.stringify({
957
960
  type: 'maintenance-error',
958
961
  surface: `${duty}-duty`,
@@ -967,6 +970,7 @@ export function createFlowsafeWorker(config) {
967
970
  const MAINTENANCE_HEALTH_KEY = 'flowsafe:maintenance-health:v1';
968
971
  const MAINTENANCE_NONCES_KEY = 'flowsafe:maintenance-nonces:v1';
969
972
  const MAINTENANCE_DEADLINE_CURSOR_KEY = 'flowsafe:maintenance-deadline-cursor:v1';
973
+ const MAINTENANCE_RUN_RETENTION_CURSOR_KEY = 'flowsafe:maintenance-run-retention-cursor:v1';
970
974
  const DUTY_ORDER = ['deadline', 'sweep', 'purge', 'tick'];
971
975
  /** Build the fixed-name maintenance Durable Object class for one host. */
972
976
  export function createFlowsafeMaintenanceDurableObject(config) {
@@ -1110,6 +1114,10 @@ export function createFlowsafeMaintenanceDurableObject(config) {
1110
1114
  }
1111
1115
  if (!capability)
1112
1116
  return undefined;
1117
+ if (this.#env.FLEET_RESOURCE_ROLE === 'platform-catalog' &&
1118
+ (capability.scriptName !== this.#env.FLEET_DEPLOYMENT_SCRIPT ||
1119
+ capability.specDigest !== this.#env.FLEET_SPEC_DIGEST))
1120
+ return undefined;
1113
1121
  if (operation === 'maintenance-status')
1114
1122
  return capability;
1115
1123
  const nowSeconds = Math.floor(Date.now() / 1_000);
@@ -1178,7 +1186,7 @@ export function createFlowsafeMaintenanceDurableObject(config) {
1178
1186
  }
1179
1187
  console.error(JSON.stringify({
1180
1188
  type: 'maintenance-do-error',
1181
- reason: error instanceof Error ? error.message : String(error),
1189
+ reason: hostErrorText(error, true),
1182
1190
  }));
1183
1191
  return json({ error: 'internal error' }, 500);
1184
1192
  }
@@ -1206,17 +1214,31 @@ export function createFlowsafeMaintenanceDurableObject(config) {
1206
1214
  setNextAt(health, duty, advancePast(dueAt, interval, now));
1207
1215
  const followUpAt = nextAlarmAt(health, intervals);
1208
1216
  await this.#persistAndArm(health, hasDueDuty(health, intervals, now) ? now : followUpAt);
1209
- let context;
1217
+ // Each duty carries the cursor pair it owns, so the call sits inside the
1218
+ // branch that builds it: the purge seam is required by its context type,
1219
+ // which a single call over the whole duty union cannot satisfy.
1220
+ let outcome;
1210
1221
  if (duty === 'deadline') {
1211
1222
  const deadlineCursor = await this.#state.storage.get(MAINTENANCE_DEADLINE_CURSOR_KEY);
1212
- context = {
1223
+ outcome = await worker.runMaintenanceDuty(duty, this.#env, {
1213
1224
  ...(deadlineCursor ? { deadlineCursor } : {}),
1214
1225
  advanceDeadlineCursor: (cursor) => this.#state.storage.transaction(async (transaction) => {
1215
1226
  await transaction.put(MAINTENANCE_DEADLINE_CURSOR_KEY, cursor);
1216
1227
  }),
1217
- };
1228
+ });
1229
+ }
1230
+ else if (duty === 'purge') {
1231
+ const retentionCursor = await this.#state.storage.get(MAINTENANCE_RUN_RETENTION_CURSOR_KEY);
1232
+ outcome = await worker.runMaintenanceDuty(duty, this.#env, {
1233
+ ...(retentionCursor === undefined ? {} : { retentionCursor }),
1234
+ advanceRetentionCursor: (cursor) => this.#state.storage.transaction(async (transaction) => {
1235
+ await transaction.put(MAINTENANCE_RUN_RETENTION_CURSOR_KEY, cursor);
1236
+ }),
1237
+ });
1238
+ }
1239
+ else {
1240
+ outcome = await worker.runMaintenanceDuty(duty, this.#env);
1218
1241
  }
1219
- const outcome = await worker.runMaintenanceDuty(duty, this.#env, context);
1220
1242
  await this.#recordOutcome(duty, Date.now(), outcome);
1221
1243
  }
1222
1244
  };