@proofoftech/flowsafe 0.18.0 → 0.20.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 (196) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/README.md +79 -5
  3. package/deployment-identity-protocol.d.mts +62 -1
  4. package/deployment-identity-protocol.mjs +201 -5
  5. package/dist/agent-host/catalog.js +1 -1
  6. package/dist/agent-host/catalog.js.map +1 -1
  7. package/dist/agent-host/index.d.ts +1 -1
  8. package/dist/agent-host/index.d.ts.map +1 -1
  9. package/dist/agent-host/index.js.map +1 -1
  10. package/dist/agent-host/router.d.ts.map +1 -1
  11. package/dist/agent-host/router.js +6 -2
  12. package/dist/agent-host/router.js.map +1 -1
  13. package/dist/agent-host/thread-host.d.ts +11 -0
  14. package/dist/agent-host/thread-host.d.ts.map +1 -1
  15. package/dist/agent-host/thread-host.js +53 -1
  16. package/dist/agent-host/thread-host.js.map +1 -1
  17. package/dist/agent-host/thread-topology.d.ts +35 -1
  18. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  19. package/dist/agent-host/thread-topology.js +103 -7
  20. package/dist/agent-host/thread-topology.js.map +1 -1
  21. package/dist/agent-runner/durable-agent-runner.d.ts +267 -21
  22. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  23. package/dist/agent-runner/durable-agent-runner.js +706 -76
  24. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  25. package/dist/approval-api/d1-store.d.ts.map +1 -1
  26. package/dist/approval-api/d1-store.js +6 -3
  27. package/dist/approval-api/d1-store.js.map +1 -1
  28. package/dist/approval-api/principal-identity.d.ts +32 -0
  29. package/dist/approval-api/principal-identity.d.ts.map +1 -0
  30. package/dist/approval-api/principal-identity.js +69 -0
  31. package/dist/approval-api/principal-identity.js.map +1 -0
  32. package/dist/approval-api/principal.d.ts +9 -12
  33. package/dist/approval-api/principal.d.ts.map +1 -1
  34. package/dist/approval-api/principal.js +9 -45
  35. package/dist/approval-api/principal.js.map +1 -1
  36. package/dist/approval-api/router.d.ts.map +1 -1
  37. package/dist/approval-api/router.js +9 -1
  38. package/dist/approval-api/router.js.map +1 -1
  39. package/dist/approval-api/service.d.ts +19 -0
  40. package/dist/approval-api/service.d.ts.map +1 -1
  41. package/dist/approval-api/service.js +41 -10
  42. package/dist/approval-api/service.js.map +1 -1
  43. package/dist/approval-api/types.d.ts +12 -0
  44. package/dist/approval-api/types.d.ts.map +1 -1
  45. package/dist/approval-api/types.js +12 -0
  46. package/dist/approval-api/types.js.map +1 -1
  47. package/dist/background-tasks/host.d.ts +127 -14
  48. package/dist/background-tasks/host.d.ts.map +1 -1
  49. package/dist/background-tasks/host.js +579 -50
  50. package/dist/background-tasks/host.js.map +1 -1
  51. package/dist/background-tasks/index.d.ts +2 -2
  52. package/dist/background-tasks/index.d.ts.map +1 -1
  53. package/dist/background-tasks/index.js +11 -6
  54. package/dist/background-tasks/index.js.map +1 -1
  55. package/dist/background-tasks/routes.d.ts +19 -2
  56. package/dist/background-tasks/routes.d.ts.map +1 -1
  57. package/dist/background-tasks/routes.js +4 -4
  58. package/dist/background-tasks/routes.js.map +1 -1
  59. package/dist/deployment-identity-protocol.d.ts +2 -2
  60. package/dist/deployment-identity-protocol.d.ts.map +1 -1
  61. package/dist/deployment-identity-protocol.js +1 -1
  62. package/dist/deployment-identity-protocol.js.map +1 -1
  63. package/dist/do-runner/cause-chain.d.ts +53 -0
  64. package/dist/do-runner/cause-chain.d.ts.map +1 -0
  65. package/dist/do-runner/cause-chain.js +96 -0
  66. package/dist/do-runner/cause-chain.js.map +1 -0
  67. package/dist/do-runner/d1-storage.d.ts +109 -5
  68. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  69. package/dist/do-runner/d1-storage.js +289 -44
  70. package/dist/do-runner/d1-storage.js.map +1 -1
  71. package/dist/do-runner/deployment-identity.d.ts +28 -13
  72. package/dist/do-runner/deployment-identity.d.ts.map +1 -1
  73. package/dist/do-runner/deployment-identity.js +25 -35
  74. package/dist/do-runner/deployment-identity.js.map +1 -1
  75. package/dist/do-runner/do-error-response.d.ts +4 -23
  76. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  77. package/dist/do-runner/do-error-response.js +19 -24
  78. package/dist/do-runner/do-error-response.js.map +1 -1
  79. package/dist/do-runner/do-status-error.d.ts +37 -0
  80. package/dist/do-runner/do-status-error.d.ts.map +1 -0
  81. package/dist/do-runner/do-status-error.js +42 -0
  82. package/dist/do-runner/do-status-error.js.map +1 -0
  83. package/dist/do-runner/durable-object.d.ts +2 -1
  84. package/dist/do-runner/durable-object.d.ts.map +1 -1
  85. package/dist/do-runner/durable-object.js +205 -19
  86. package/dist/do-runner/durable-object.js.map +1 -1
  87. package/dist/do-runner/execution-fence.d.ts +335 -0
  88. package/dist/do-runner/execution-fence.d.ts.map +1 -0
  89. package/dist/do-runner/execution-fence.js +534 -0
  90. package/dist/do-runner/execution-fence.js.map +1 -0
  91. package/dist/do-runner/index.d.ts +10 -3
  92. package/dist/do-runner/index.d.ts.map +1 -1
  93. package/dist/do-runner/index.js +16 -3
  94. package/dist/do-runner/index.js.map +1 -1
  95. package/dist/do-runner/init.d.ts +82 -1
  96. package/dist/do-runner/init.d.ts.map +1 -1
  97. package/dist/do-runner/init.js +58 -3
  98. package/dist/do-runner/init.js.map +1 -1
  99. package/dist/do-runner/inventory.d.ts +294 -0
  100. package/dist/do-runner/inventory.d.ts.map +1 -0
  101. package/dist/do-runner/inventory.js +811 -0
  102. package/dist/do-runner/inventory.js.map +1 -0
  103. package/dist/do-runner/notification-predicate.d.ts +8 -0
  104. package/dist/do-runner/notification-predicate.d.ts.map +1 -0
  105. package/dist/do-runner/notification-predicate.js +9 -0
  106. package/dist/do-runner/notification-predicate.js.map +1 -0
  107. package/dist/do-runner/runtime.d.ts +83 -0
  108. package/dist/do-runner/runtime.d.ts.map +1 -1
  109. package/dist/do-runner/runtime.js +131 -4
  110. package/dist/do-runner/runtime.js.map +1 -1
  111. package/dist/do-runner/start-idempotency.d.ts +508 -0
  112. package/dist/do-runner/start-idempotency.d.ts.map +1 -0
  113. package/dist/do-runner/start-idempotency.js +886 -0
  114. package/dist/do-runner/start-idempotency.js.map +1 -0
  115. package/dist/do-runner/suspension-deadline.d.ts +3 -2
  116. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  117. package/dist/do-runner/suspension-deadline.js +3 -2
  118. package/dist/do-runner/suspension-deadline.js.map +1 -1
  119. package/dist/goals/objective-routes.d.ts +14 -0
  120. package/dist/goals/objective-routes.d.ts.map +1 -1
  121. package/dist/goals/objective-routes.js +45 -24
  122. package/dist/goals/objective-routes.js.map +1 -1
  123. package/dist/host-kit/do-run-topology.d.ts +15 -0
  124. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  125. package/dist/host-kit/do-run-topology.js +22 -1
  126. package/dist/host-kit/do-run-topology.js.map +1 -1
  127. package/dist/host-kit/flowsafe-worker.d.ts +11 -0
  128. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  129. package/dist/host-kit/flowsafe-worker.js +343 -62
  130. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  131. package/dist/host-kit/host-approval-service.d.ts +20 -0
  132. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  133. package/dist/host-kit/host-approval-service.js +6 -0
  134. package/dist/host-kit/host-approval-service.js.map +1 -1
  135. package/dist/host-kit/index.d.ts +2 -2
  136. package/dist/host-kit/index.d.ts.map +1 -1
  137. package/dist/host-kit/index.js +1 -1
  138. package/dist/host-kit/index.js.map +1 -1
  139. package/dist/host-kit/run-route-error.d.ts +18 -0
  140. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  141. package/dist/host-kit/run-route-error.js +23 -0
  142. package/dist/host-kit/run-route-error.js.map +1 -1
  143. package/dist/host-kit/run-router.d.ts +58 -1
  144. package/dist/host-kit/run-router.d.ts.map +1 -1
  145. package/dist/host-kit/run-router.js +120 -11
  146. package/dist/host-kit/run-router.js.map +1 -1
  147. package/dist/host-kit/stream-router.d.ts.map +1 -1
  148. package/dist/host-kit/stream-router.js +18 -9
  149. package/dist/host-kit/stream-router.js.map +1 -1
  150. package/dist/schedules/router.d.ts +15 -0
  151. package/dist/schedules/router.d.ts.map +1 -1
  152. package/dist/schedules/router.js +47 -17
  153. package/dist/schedules/router.js.map +1 -1
  154. package/dist/schedules/tick.d.ts +13 -0
  155. package/dist/schedules/tick.d.ts.map +1 -1
  156. package/dist/schedules/tick.js +59 -39
  157. package/dist/schedules/tick.js.map +1 -1
  158. package/dist/signal-providers/delivery.d.ts +32 -0
  159. package/dist/signal-providers/delivery.d.ts.map +1 -1
  160. package/dist/signal-providers/delivery.js +45 -0
  161. package/dist/signal-providers/delivery.js.map +1 -1
  162. package/dist/signal-providers/host-do.d.ts +23 -1
  163. package/dist/signal-providers/host-do.d.ts.map +1 -1
  164. package/dist/signal-providers/host-do.js +76 -17
  165. package/dist/signal-providers/host-do.js.map +1 -1
  166. package/dist/signal-providers/provider.d.ts +8 -0
  167. package/dist/signal-providers/provider.d.ts.map +1 -1
  168. package/dist/signal-providers/provider.js.map +1 -1
  169. package/dist/signal-providers/webhook-route.d.ts +20 -0
  170. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  171. package/dist/signal-providers/webhook-route.js +137 -26
  172. package/dist/signal-providers/webhook-route.js.map +1 -1
  173. package/dist/signals/client.d.ts +19 -5
  174. package/dist/signals/client.d.ts.map +1 -1
  175. package/dist/signals/client.js +25 -17
  176. package/dist/signals/client.js.map +1 -1
  177. package/dist/signals/index.d.ts +1 -1
  178. package/dist/signals/index.d.ts.map +1 -1
  179. package/dist/signals/index.js.map +1 -1
  180. package/dist/signals/notification-dispatch.d.ts +15 -0
  181. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  182. package/dist/signals/notification-dispatch.js +23 -1
  183. package/dist/signals/notification-dispatch.js.map +1 -1
  184. package/dist/signals/notifications-d1.d.ts +8 -0
  185. package/dist/signals/notifications-d1.d.ts.map +1 -1
  186. package/dist/signals/notifications-d1.js +15 -9
  187. package/dist/signals/notifications-d1.js.map +1 -1
  188. package/dist/signals/router.d.ts.map +1 -1
  189. package/dist/signals/router.js +3 -2
  190. package/dist/signals/router.js.map +1 -1
  191. package/dist/signals/thread-do-routes.d.ts +48 -10
  192. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  193. package/dist/signals/thread-do-routes.js +710 -136
  194. package/dist/signals/thread-do-routes.js.map +1 -1
  195. package/package.json +8 -6
  196. package/scripts/seed-deployment-identity.mjs +22 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,119 @@
1
1
  # @proofoftech/flowsafe
2
2
 
3
+ ## 0.20.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 1212ba5: Flowsafe now exposes deployment-wide execution fencing, owner-bound idempotent starts, and a read-only drain inventory for physical deployment migrations.
8
+
9
+ This changes the public runtime and host contract:
10
+
11
+ - The execution fence has `open`, `draining`, `migration-locked`, and `proof-only` states. Transitions use compare-and-set through `POST /admin/execution-fence`; a stale expected state returns `409` with `FENCE_CAS_CONFLICT`, and invalid state or proof-key values return `400` with `INVALID_EXECUTION_FENCE_REQUEST`. `GET /admin/execution-fence` reads the current state. Both routes require `MAINTENANCE_ADMIN_SECRET`.
12
+ - Fence refusals return `503` with `EXECUTION_FENCED`. `open` admits every entry. `draining` refuses new run mints and future-work authoring, but admits work on existing runs, dispatch of queued background tasks, and new background-task enqueues. `migration-locked` refuses every execution entry, including background-task enqueue, dispatch, and stale-task re-drive. `proof-only` admits only the start carrying the nominated proof key and later work addressed to its bound proof run; it also refuses background-task enqueue, dispatch, and stale-task re-drive. Reads, termination, cancellation, timeout, objective clear, and schedule pause or delete remain available. In-flight compute is not preempted.
13
+ - The new `flowsafe_execution_fence` table stores one deployment-wide row. The deployment-identity protocol treats it as protocol-owned state during ownership checks. A database created before this release reads an absent table or row as `open`.
14
+ - **BREAKING:** `ExecutionFenceWiring` is required on the non-`'none'` `RunRouterStartIdempotency` arm of `RunRouterOptions.startIdempotency`, and on `HostApprovalServiceOptions`, `ScheduleTickOptions`, `ScheduleRouterOptions`, `SignalProviderHostWiring`, `WebhookRouterOptions`, `ApprovalServiceOptions`, `NotificationDispatchTickOptions`, `StorageInitOptions`, `AgentThreadTopologyOptions`, `ObjectiveRouterOptions`, and `BackgroundTaskHostOptions`.
15
+ - **BREAKING:** `provisionDeploymentIdentityProtocol()`, `seedDeploymentIdentity()`, and the `flowsafe-provision --initial-fence-state` CLI require an initial state. Provisioning accepts only `open` or `migration-locked`; there is no default.
16
+ - **BREAKING:** `BackgroundTaskHost.manager` is removed. Use `enqueue()`, `getTask()`, `listTasks()`, and `stream()`, and type read-only consumers with `BackgroundTaskReads`.
17
+ - **BEHAVIOR CHANGE:** the agent-host and host-kit stream routers preserve structured Durable Object refusals. Clients now receive the original `503` or `409` and a `reason` body instead of a bare `500` for structured server-side refusals.
18
+ - Refusal and denial message text no longer exposes internal plan identifiers. Reason codes and statuses are unchanged.
19
+ - `idempotencyKey` makes `POST /runs`, trusted agent-host starts, and `streamUntilPersisted()` converge on the same server-minted run. Callers still cannot supply `runId` to `POST /runs`; doing so returns `400`.
20
+ - Idempotent-start decisions return `IDEMPOTENT_START_OWNER_MISMATCH` (`403`), `IDEMPOTENT_START_TARGET_MISMATCH` (`409`), `IDEMPOTENT_START_PENDING` (`503`), `IDEMPOTENT_START_UNRESOLVABLE` (`409`), or `IDEMPOTENT_START_ALREADY_SETTLED` (`409`). Operational failures return `IDEMPOTENT_START_UNSUPPORTED` (`503`) or `IDEMPOTENT_START_UNREADABLE` (`503`), and malformed input returns `INVALID_START_IDEMPOTENCY_REQUEST` (`400`). `isStartReservationRefusal()` recognizes the five decision refusals, unsupported wiring, and malformed input; unreadable storage propagates separately.
21
+ - A replay returns the original run's persisted state. `IDEMPOTENT_START_PENDING` includes `pendingSince`. `IDEMPOTENT_START_UNRESOLVABLE` is a point-in-time answer, so re-probe before acting. A replayed suspended start omits the start response's `approval` and `approvals` fields. The `flowsafe_start_idempotency` row remains valid for the configured reservation-retention horizon.
22
+ - **BREAKING:** `RunRouterOptions`, `AgentThreadTopologyOptions`, and `StorageInitOptions` require `startIdempotency` wiring. `START_IDEMPOTENCY_RETENTION_DAYS` controls how long spent keys remain valid and defaults to run retention.
23
+ - `GET /admin/inventory` reports work categories `runs`, `approvals-waiting`, `schedule-deferred-dispatches`, `pending-notifications`, `background-tasks`, `resource-owners`, and `start-reservations`, plus standing categories `schedules` and `signal-subscriptions`. Standing categories are never required to empty.
24
+ - `INVENTORY_DRAIN_PROOF` requires every work category to be empty across two consecutive full sweeps at least one 60-second alarm cadence apart, while the fence remains `draining`. Inventory readings are point-in-time observations rather than snapshots and can move in either direction while draining admits work. Empty results cannot over-count, and keyset pagination never skips a row that existed before the sweep began. A host that needs a hard guarantee can re-sweep once after transitioning to `migration-locked`: an empty post-lock sweep is conclusive, while a non-empty one means work is still outstanding, either because it entered after the proof or because the lock parked it before it finished. Return to `draining` and repeat the proof. An inventory read taken under `migration-locked` measures what the fence parked rather than what the deployment would otherwise be doing. `INVENTORY_UNENUMERABLE` declares the run-owner recovery journal and persisted idle signals; the latter deliberately survive migration. `FLOWSAFE_TABLES` keeps every Flowsafe-owned table accounted for.
25
+
26
+ When upgrading, pass `'none'` only for leaf hosts with no database, select `open` or `migration-locked` during provisioning, replace `host.manager` reads with the host methods, preserve structured `503` and `409` refusal bodies, and re-probe `IDEMPOTENT_START_UNRESOLVABLE` before deciding whether to use a fresh key.
27
+
28
+ ## 0.19.0
29
+
30
+ ### Minor Changes
31
+
32
+ - fa0d11d: Add an optional content-policy boundary for agent signals. Breakwater exposes `createContentPolicyGate()`, a reusable opaque input-policy gate for host code outside Mastra's processor chain, and FlowSafe's thread signal routes accept a structural `contentPolicy` callback that inspects Mastra's canonical escaped XML before delivery, persistence, wake, or run start — covering direct ingestion, providers, schedules, and notification dispatch. Denial is terminal and evaluator failure stays recoverable on every lane; neither exposes policy names, reasons, content, or causes.
33
+
34
+ Signal attributes whose keys are not XML names are now dropped when a signal is ingested, and a schedule whose stored target cannot be rendered settles a terminal discard receipt instead of failing every later tick with the same broken target.
35
+
36
+ Provider deliveries now distinguish a terminal refusal from one the deployment could not decide: an undecided webhook is answered with 503 so the sender redelivers, and every delivery carries a dedupe key derived from the signed bytes and the subscription so a redelivery coalesces into a still-pending notification instead of duplicating it. Webhook and poll results report `denied`, `failed`, and `deferred` counts.
37
+
38
+ - 0447466: Signal delivery through a Flowsafe durable agent no longer starts an unowned
39
+ run below the host seam; an unbranded agent on an active thread keeps core's own
40
+ behavior as a degraded configuration.
41
+
42
+ This changes the public signal contract:
43
+
44
+ - `/signal/queue` persists in both active and idle states. Success now returns
45
+ `decision.action: 'persist'` without a `runId`; active-thread auto-drain is
46
+ removed, so the message surfaces on the next host-started turn.
47
+ - `/signal/state` now applies the queue route's owner gates and can return
48
+ `principal-mismatch` or `persistence-forbidden`.
49
+ - `/signal/notification` creates the notification record for every accepted
50
+ provider delivery. Owners receive core's `{ record, decision, ... }` result
51
+ under the top-level `record` field, with the signal-routing decision exposed
52
+ separately as `delivery` when core returns one. Non-owners receive a flat
53
+ `NotificationRecord` under `record` plus
54
+ `delivery: { action: 'deferred', reason: 'dispatcher' }`; they never send a
55
+ signal directly. Low-priority owner notifications use summarize-later and
56
+ have no immediate `delivery`.
57
+ - Unbranded agents return `degraded: 'not-runtime-driven'` from successful,
58
+ non-skipped state and owner-notification responses, regardless of thread state.
59
+ Skipped state and an early `memory-unavailable` state response carry no marker.
60
+ - `/signal/message`, `/signal`, `/signal/schedule`, and
61
+ `/signal/notifications/dispatch` now persist on a stale-active-id fall-through
62
+ instead of waking. A forbidden fallback returns `persistence-forbidden`; a
63
+ memory-less fallback returns `memory-unavailable`. The notification dispatch
64
+ lane counts either discard as failed and performs no persisted write. A
65
+ non-owner `/signal` request for `ifActive: 'persist'` degrades to `discard`
66
+ for active delivery: when the thread was active, the response is
67
+ `persistence-forbidden` without a `signalId` because the gate refused and
68
+ nothing was delivered; when the thread was idle, the caller's own `ifIdle`
69
+ outcome is returned unchanged with `signalId`. Owners still forward
70
+ `persist`. Non-owner active deliveries carry non-rendered metadata so a
71
+ completion drain cannot preserve a leftover through the terminal path.
72
+ - Persist outcomes return a `memory-unavailable` discard decision when the
73
+ resolved agent has no memory, after the content gate. A default or
74
+ `ifIdle: 'persist'` message or signal is delivered into an active run without
75
+ memory; an active persist that no memory could write answers
76
+ `memory-unavailable`. A persist-behavior `/signal/schedule` fire instead
77
+ settles a canonical `discard` receipt with `outcome: 'discarded'` and no
78
+ reason, where it previously settled `persisted`.
79
+ Owner `/signal/notification` is the other exception: its model-visible memory
80
+ write is best-effort because the inbox record is already durable. The shipped
81
+ starter host does not configure agent memory, so its other persist outcomes
82
+ return `memory-unavailable` until the host adds memory configuration.
83
+ - Non-owner `/signal/notification` ingestion now requires notification storage
84
+ and returns `409` without it. Those rows bypass the agent's delivery policy and
85
+ readiness hook; the host must run `createNotificationDispatchTick()` to
86
+ deliver them. The starter runs it every 60 seconds, giving up to one tick of
87
+ latency. A host without the tick records but never delivers them; the spike
88
+ has no tick and its provider probes assert only the inbox row.
89
+ - The durable-agent runner terminally fails every run that was not registered
90
+ through `streamUntilPersisted()`. Direct `stream()` resolves to a failed
91
+ output; direct `generate()` rejects. `stream()`, `generate()`, `prepare()`, and
92
+ `streamUntilPersisted()` synchronously refuse a live id, and `prepare(X)`
93
+ keeps `X` live until cleanup. `streamUntilPersisted()` also refuses
94
+ `untilIdle`. If the runner's two terminal-publication attempts and core's own
95
+ fire-and-forget attempt all fail, the output never closes and the thread stays
96
+ active until eviction or a new host start.
97
+ - The public `signals/router.ts` state and notification channels carry these new
98
+ response shapes.
99
+
100
+ Migrate run starts to the host routes or `streamUntilPersisted()`. Treat queue
101
+ success as `{ action: 'persist' }` without a `runId`, and read queued messages on
102
+ the next host-started turn.
103
+
104
+ - 8f4daae: Require `@mastra/core` 1.53.0 exactly (previously 1.50.0). The peer is exact, so every consumer must move to 1.53.0 as well; this is breaking for consumers pinned to 1.50.0. 1.53.0 is the newest release whose published output still bundles for Cloudflare Workers and Vite: 1.54.0 through 1.60.0 inline Node-only dynamic imports (`execa`, `@ast-grep/napi`) that fail to bundle (mastra-ai/mastra#20638). `@mastra/cloudflare-d1` stays at 1.1.1. FlowSafe's `@proofoftech/breakwater` peer floor rises to `>=0.13.0` in step, that being the first Breakwater release built against the same core.
105
+
106
+ FlowSafe's durable agent runner now refuses every inherited entry point that can drive execution outside `RunnerRuntime`, mint a run id below the caller, or hand back runs the caller does not own: the run-recovery entry points 1.53.0 adds to `DurableAgent` (`recover`, `recoverActiveRuns`, `listActiveRuns`); the resume family (`resume`, `resumeStream`, `resumeGenerate`, `approveToolCall`, `declineToolCall`, `approveToolCallGenerate`, `declineToolCallGenerate`), which since 1.53.0 rehydrate from snapshot storage on a run-registry miss; the agent-level discovery member `listSuspendedRuns`; the network family (`network`, `resumeNetwork`, `approveNetworkToolCall`, `declineNetworkToolCall`), which drives the multi-agent loop's own workflow on the default engine; the AI SDK v4 legacy pair (`generateLegacy`, `streamLegacy`), which runs the agent's tools while skipping the authorization check every supported entry point calls; and `sendToolApproval`, whose continuation branch starts a run under a generated run id rather than resuming. `deleteRunSnapshots` is refused on a separate ground: the snapshot rows it deletes belong to deployment-scoped retention rather than to any caller. Nineteen entry points in all. That leaves `resumeViaRuntime` as the only resume path and the guarded `stream`/`generate`/`prepare` as the only execution entry points. Surface tripwires now classify every `DurableAgent` prototype member and every inherited `Agent` member, so a future peer bump surfaces new entry points on either.
107
+
108
+ This is a behavior change for any consumer that called those methods on a FlowSafe durable agent: they now throw instead of executing. Their TYPE signatures narrow too — the overridden members return `Promise<never>`, and the generic overloads several of them carried (`network`, `generateLegacy`, `streamLegacy`, `sendToolApproval`) collapse to a single refusing signature, so a call that no longer type-checks is the intended signal rather than a regression. Nothing in the supported agent-host surface reaches them — route clients through the agent-host run routes.
109
+
110
+ ### Patch Changes
111
+
112
+ - 80a801c: Signal-provider delivery-error log events now carry the same `terminal` flag as their delivery-rejected siblings, so a dropped-forever throw is distinguishable from a deferred one without re-deriving the classification.
113
+ - da6a0aa: Export deployment identity headers from the protocol leaf so external candidates do not import the Durable Object runner barrel.
114
+ - 66c19f1: Clean generated output at the packaging boundary so deleted source modules cannot remain in published tarballs.
115
+ - 5cbe01d: Align the package and documented Node.js runtime floor with the required `@mastra/core` peer dependency.
116
+
3
117
  ## 0.18.0
4
118
 
5
119
  ### Minor Changes
package/README.md CHANGED
@@ -9,7 +9,7 @@ Flowsafe runs Mastra workflows and agents through Cloudflare Durable Objects, st
9
9
  ## Install
10
10
 
11
11
  ```bash
12
- npm install @mastra/core@1.50.0 @proofoftech/flowsafe
12
+ npm install @mastra/core@1.53.0 @proofoftech/flowsafe
13
13
  ```
14
14
 
15
15
  Install `@proofoftech/breakwater` when resumed steps call approval-protected connectors:
@@ -22,12 +22,12 @@ Install React and React DOM only when you import `@proofoftech/flowsafe/approval
22
22
 
23
23
  Compatibility:
24
24
 
25
- - Node.js 22 or later (engine range `>=22`)
25
+ - Node.js 22.13.0 or later (engine range `>=22.13.0`)
26
26
  - ESM only
27
27
  - TypeScript `moduleResolution: "NodeNext"`, `"Node16"`, or `"Bundler"`
28
- - `@mastra/core` `1.50.0`
28
+ - `@mastra/core` `1.53.0`
29
29
  - `react` and `react-dom` `>=18 <20` (React 18 or 19) for the optional approval UI
30
- - `@proofoftech/breakwater` `>=0.12.0 <1.0.0` when used
30
+ - `@proofoftech/breakwater` `>=0.13.0 <1.0.0` when used
31
31
  - host-provided Wrangler `>=4.118 <5` for the optional `flowsafe-provision` CLI
32
32
 
33
33
  ## Choose an export
@@ -101,7 +101,7 @@ export class AppRunner extends DurableObjectRunner<Env> {
101
101
  }
102
102
  ```
103
103
 
104
- `init()` creates D1-backed Mastra storage from the conventional `DB` binding unless you inject storage. Workflow definitions use the same `createWorkflow()` and `createStep()` shape as Mastra. Flowsafe pins `@mastra/cloudflare-d1` 1.1.1 so the minimum supported `@mastra/core` 1.50.0 peer can import and bundle without a consumer override.
104
+ `init()` creates D1-backed Mastra storage from the conventional `DB` binding unless you inject storage. Workflow definitions use the same `createWorkflow()` and `createStep()` shape as Mastra. Flowsafe pins `@mastra/cloudflare-d1` 1.1.1 because the shipped D1 storage is written against that release's domain surface: it subclasses the adapter's background-tasks domain to apply the `TaskFilter.resourceId` predicate the adapter declares but omits from its SQL builder, and hand-writes the schedules, notifications, and thread-state domains the adapter does not ship at all. The pin also holds the adapter on its `@cloudflare/workers-types` v4 peer, which is the major Flowsafe and Agent Starter still build against.
105
105
 
106
106
  If the deployment uses a table prefix, pass one shared constant to storage and host maintenance:
107
107
 
@@ -291,16 +291,27 @@ npm install --save-dev "wrangler@>=4.118 <5"
291
291
  npx flowsafe-provision \
292
292
  --database <database> \
293
293
  --tag <tag> \
294
+ --initial-fence-state open \
294
295
  --remote \
295
296
  --config wrangler.jsonc
296
297
  ```
297
298
 
298
299
  Fleet control planes can import the same fail-closed sentinel implementation from `@proofoftech/flowsafe/deployment-identity-protocol` instead of duplicating its schema or race handling.
299
300
 
301
+ ### Fence and drain a deployment
302
+
303
+ One Flowsafe deployment is one tenant, so the execution fence controls the complete deployment. `open` admits all work. `draining` refuses new run mints and future-work authoring while existing runs and deliveries finish. It still accepts new background-task enqueues and dispatches queued tasks because both are drainable work. Background-task enqueue, dispatch, and stale-task re-drive are refused in `migration-locked` and `proof-only`. Signal wakes that would mint a run persist instead. `migration-locked` refuses execution, and `proof-only` admits only the nominated start and its bound run. The fence never preempts compute already in flight.
304
+
305
+ Provisioning requires `--initial-fence-state open` or `--initial-fence-state migration-locked`; it never chooses a default. A pre-0.20 database without a fence row reads as `open`. For locked-at-birth provisioning, read `GET /admin/execution-fence` afterward and fail unless it reports `migration-locked`.
306
+
307
+ Use `GET /admin/inventory` while the fence remains `draining`. A drain is proven only after every work category is empty across two complete sweeps at least 60 seconds apart. Readings are point-in-time observations rather than snapshots and can move in either direction while draining admits work. Empty results cannot over-count, and keyset pagination never skips a row that existed before the sweep began. If you need a hard guarantee, re-sweep once after transitioning to `migration-locked`: an empty post-lock sweep is conclusive; a non-empty one means work is still outstanding, either because it entered after the proof or because the lock parked it before it finished. Return to `draining` and repeat the proof. An inventory read taken under `migration-locked` measures what the fence parked rather than what the deployment would otherwise be doing. Schedules and signal subscriptions are standing configuration and need not empty. Persisted idle signals are deliberately unenumerable and carry into the replacement deployment.
308
+
300
309
  ### Runtime ids are opaque
301
310
 
302
311
  The host mints opaque, path-safe run and thread ids. `RunnerRuntime.start()` requires a host-owned run id and has no generation fallback. The id scopes the snapshot, Durable Object, approval lookup, stream address, and artifact path, but it carries no customer identity.
303
312
 
313
+ Callers that need exactly-once start behavior supply an `idempotencyKey`, never a run ID. The key is available on `POST /runs`, trusted agent-host starts, and `streamUntilPersisted()`. A retry returns the same persisted run. `IDEMPOTENT_START_PENDING` includes `pendingSince`; re-probe the point-in-time `IDEMPOTENT_START_UNRESOLVABLE` result before acting. A key remains valid until its reservation-retention horizon expires.
314
+
304
315
  ### Stores are deployment-wide
305
316
 
306
317
  `D1ApprovalStoreFactory.store()` and `D1SubscriptionStoreFactory.store()` return the store for the bound database. Tables and indexes contain no tenant column. Legacy pooled schemas require a fresh database.
@@ -397,6 +408,65 @@ Agent event replay lasts only as long as the configured Mastra cache. The defaul
397
408
 
398
409
  `createThreadSignalRoutes()` hosts message, queue, signal, state, and notification delivery in the thread Durable Object. `createSignalRouter()` is the Worker trust boundary: authenticate, authorize, ownership-check, cap, parse, reject memory ids, allowlist attributes, rate-limit, audit, then forward.
399
410
 
411
+ The thread routes reject a signal whose `tagName` is not an XML name, and drop an attributes object carrying a value Mastra cannot render or a key that is not an XML name. Both are what core would otherwise throw on while rendering the signal inside the agent turn.
412
+
413
+ Configure `ThreadSignalRoutesOptions.contentPolicy` when signal content needs a domain policy before it becomes model input. The Thread Durable Object invokes this structural callback for direct ingestion, provider delivery, schedule fires, and notification dispatch. Its `text` is Mastra's canonical escaped XML representation. A denial stops direct delivery with 422, settles a scheduled fire as discarded, or terminally discards the affected notification.
414
+
415
+ A policy failure is opaque, and each lane recovers the way it already recovers from any other failure: direct delivery returns 503, schedule state is left unsettled so the lease expires and a later tick retries, and notification dispatch uses its existing backoff. A webhook whose matched deliveries the deployment could not decide is answered with 503 so the provider's own at-least-once redelivery recovers it; each delivery carries a dedupe key derived from the signed bytes and the subscription, so a redelivery coalesces into a still-pending row rather than duplicating it. A content denial is terminal and answers 2xx, because redelivering the identical bytes would only be denied again. Poll deliveries report the same three outcomes and depend on the adapter re-reporting state it has not seen accepted. Give a network-backed policy its own timeout and failure budget inside the callback; FlowSafe imposes neither.
416
+
417
+ Adapt Breakwater without adding a FlowSafe runtime dependency on it:
418
+
419
+ ```typescript
420
+ import { RequestContext } from '@mastra/core/request-context';
421
+ import {
422
+ ACTOR_CONTEXT_KEY,
423
+ AGENT_AUDIT_CONTEXT_KEY,
424
+ createContentPolicyGate,
425
+ } from '@proofoftech/breakwater';
426
+ import {
427
+ breakwaterActorFor,
428
+ principalAuditFields,
429
+ } from '@proofoftech/flowsafe/approval-api';
430
+ import {
431
+ createThreadSignalRoutes,
432
+ type SignalContentPolicyInput,
433
+ } from '@proofoftech/flowsafe/signals';
434
+
435
+ const inspectContent = createContentPolicyGate({ policies });
436
+
437
+ function signalPolicyContext(input: SignalContentPolicyInput): RequestContext {
438
+ const requestContext = new RequestContext();
439
+ requestContext.set(ACTOR_CONTEXT_KEY, breakwaterActorFor(input.principal));
440
+ requestContext.set(AGENT_AUDIT_CONTEXT_KEY, {
441
+ agentId: input.agentId,
442
+ ...(input.deploymentTag === undefined
443
+ ? {}
444
+ : { tenantId: input.deploymentTag }),
445
+ ...(input.runId === undefined ? {} : { runId: input.runId }),
446
+ threadId: input.threadId,
447
+ ...(input.resourceId === undefined
448
+ ? {}
449
+ : { resourceId: input.resourceId }),
450
+ entryPath: input.entryPath,
451
+ ...principalAuditFields(input.principal),
452
+ });
453
+ return requestContext;
454
+ }
455
+
456
+ const signalRoutes = createThreadSignalRoutes({
457
+ // Existing server-owned resolvers and dispatch seams.
458
+ contentPolicy: (input) =>
459
+ inspectContent({
460
+ text: input.text,
461
+ requestContext: signalPolicyContext(input),
462
+ }),
463
+ });
464
+ ```
465
+
466
+ Build the request context only from the callback input. FlowSafe derives those fields from the asserted Thread Durable Object scope and server-owned metadata; never merge HTTP body context or caller-supplied identity into it.
467
+
468
+ Notification ingestion is checked before persistence, and that check is authoritative rather than advisory: Mastra's default delivery decision sends an urgent notification — and an idle-thread high or medium one — straight out of `sendNotificationSignal`, so those records never reach the dispatcher. Storage owns the id, the timestamps and any coalescing, so ingestion inspects a canonical prospective notification carrying every untrusted model-visible field, in both renderings Mastra can choose between: the individual signal and the single-record summary. Dispatch then checks the exact persisted individual or summary signal for every record that was deferred or batched to the tick.
469
+
400
470
  `D1NotificationsStorage` and `D1ThreadStateStorage` mirror Mastra's in-memory domains on D1. `SignalClient` is available from the browser-safe `signals/client` export.
401
471
 
402
472
  ### Goals
@@ -425,6 +495,10 @@ Complete wiring is in the [durable-agents guide](https://github.com/ProofOfTechO
425
495
 
426
496
  The composed `createFlowsafeWorker()` owns the shared route and maintenance-duty pipeline. Hosts inject workflows, identity verification, topology-backed optional routers, budget wrappers, notification transport, an invocation-scoped artifact-store factory, the storage table prefix, schedule tick, and extra purge duties.
427
497
 
498
+ Protect `GET` and `POST /admin/execution-fence` plus `GET /admin/inventory` with a distinct `MAINTENANCE_ADMIN_SECRET`. Fence transitions use CAS and return `409` with `FENCE_CAS_CONFLICT` when the expected state is stale. Fenced execution returns `503` with an `EXECUTION_FENCED` reason. The agent-host and stream routers preserve structured `503` and `409` refusals instead of collapsing them to a generic `500`.
499
+
500
+ Every leaf option that accepts `ExecutionFenceWiring` requires an explicit store or `'none'`. Run-router, agent-thread-topology, and storage initialization also require explicit start-idempotency wiring. Use `'none'` only when no database exists. `BackgroundTaskHost` no longer exposes its manager; call `enqueue()`, `getTask()`, `listTasks()`, or `stream()` on the host and use `BackgroundTaskReads` for read-only route composition.
501
+
428
502
  `createFlowsafeMaintenanceDurableObject()` runs deadline expiry, approval service-level agreement (SLA) sweep, retention purge, and optional schedule fire as separate alarm invocations. Provider polling and background recovery use their own Durable Object alarms.
429
503
 
430
504
  Read:
@@ -15,6 +15,12 @@ export type DeploymentIdentityProtocolExecutor = (
15
15
  export const DEPLOYMENT_TAG_PATTERN: RegExp;
16
16
  export const DEPLOYMENT_ENVIRONMENT_PATTERN: RegExp;
17
17
  export const DEPLOYMENT_SENTINEL_TABLE: 'flowsafe_deployment';
18
+ /**
19
+ * Internal Worker-to-Durable-Object credential header. Topology helpers always
20
+ * overwrite it, and public request resolvers reject it. The value is a
21
+ * deployment secret rather than the public deployment tag.
22
+ */
23
+ export const DEPLOYMENT_IDENTITY_HEADER: 'x-flowsafe-deployment-identity';
18
24
  export const DEPLOYMENT_SENTINEL_DDL: string;
19
25
  export const DEPLOYMENT_SENTINEL_COLUMNS: readonly Readonly<{
20
26
  name: string;
@@ -23,8 +29,55 @@ export const DEPLOYMENT_SENTINEL_COLUMNS: readonly Readonly<{
23
29
  pk: number;
24
30
  }>[];
25
31
 
32
+ /** The table the single deployment execution fence row lives in. */
33
+ export const EXECUTION_FENCE_TABLE: 'flowsafe_execution_fence';
34
+ /** The fence row's fixed primary key — one deployment, one database, one row. */
35
+ export const EXECUTION_FENCE_ROW_ID: 'deployment';
36
+ /** Every fence state, ordered from most to least permissive. */
37
+ export const EXECUTION_FENCE_STATES: readonly [
38
+ 'open',
39
+ 'draining',
40
+ 'migration-locked',
41
+ 'proof-only',
42
+ ];
43
+ /** The states a deployment may be BORN in. */
44
+ export const INITIAL_EXECUTION_FENCE_STATES: readonly [
45
+ 'open',
46
+ 'migration-locked',
47
+ ];
48
+ /**
49
+ * The fence table's schema. `do-runner/execution-fence.ts` issues this exact
50
+ * string, so the store and the provisioning protocol cannot create differently
51
+ * shaped tables.
52
+ */
53
+ export const EXECUTION_FENCE_DDL: string;
54
+
55
+ /** The fence state a deployment is provisioned into. Required; no default. */
56
+ export type InitialExecutionFenceState =
57
+ (typeof INITIAL_EXECUTION_FENCE_STATES)[number];
58
+
26
59
  export class DeploymentIdentityError extends Error {}
27
60
 
61
+ /**
62
+ * Validate the fence state a deployment is to be born in, throwing
63
+ * DeploymentIdentityError on anything else.
64
+ */
65
+ export function assertInitialExecutionFenceState(
66
+ state: unknown,
67
+ caller: string,
68
+ ): InitialExecutionFenceState;
69
+
70
+ export function assertDeploymentIdentitySecret(
71
+ secret: unknown,
72
+ caller?: string,
73
+ ): asserts secret is string;
74
+
75
+ /** Stamp the internal credential onto an ordinary topology request. */
76
+ export function deploymentIdentityHeaders(
77
+ secret: string,
78
+ initial?: HeadersInit,
79
+ ): Record<string, string>;
80
+
28
81
  export function isDeploymentEnvironment(value: unknown): value is string;
29
82
 
30
83
  export function assertValidDeploymentTag(
@@ -45,8 +98,16 @@ export function readDeploymentIdentityProtocol(
45
98
  export function provisionDeploymentIdentityProtocol(
46
99
  execute: DeploymentIdentityProtocolExecutor,
47
100
  tag: string,
48
- options?: {
101
+ options: {
49
102
  caller?: string;
50
103
  provisionedAt?: string;
104
+ /** Injectable clock (epoch milliseconds) for the seeded rows. */
105
+ now?: () => number;
106
+ /**
107
+ * The fence state the deployment is born in. REQUIRED and without a
108
+ * default: a migration host that forgot to ask for 'migration-locked'
109
+ * would otherwise silently get an executing deployment.
110
+ */
111
+ initialExecutionFenceState: InitialExecutionFenceState;
51
112
  },
52
113
  ): Promise<void>;
@@ -4,6 +4,12 @@ export const DEPLOYMENT_TAG_PATTERN = /^[a-z0-9]{3,32}$/;
4
4
  export const DEPLOYMENT_ENVIRONMENT_PATTERN =
5
5
  /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
6
6
  export const DEPLOYMENT_SENTINEL_TABLE = 'flowsafe_deployment';
7
+ /**
8
+ * Internal Worker-to-Durable-Object credential header. Topology helpers always
9
+ * overwrite it, and public request resolvers reject it. The value is a
10
+ * deployment secret rather than the public deployment tag.
11
+ */
12
+ export const DEPLOYMENT_IDENTITY_HEADER = 'x-flowsafe-deployment-identity';
7
13
  export const DEPLOYMENT_SENTINEL_DDL = `CREATE TABLE IF NOT EXISTS ${DEPLOYMENT_SENTINEL_TABLE} (
8
14
  id INTEGER PRIMARY KEY CHECK (id = 1),
9
15
  tenant_tag TEXT NOT NULL,
@@ -20,10 +26,82 @@ export const DEPLOYMENT_SENTINEL_COLUMNS = Object.freeze([
20
26
  }),
21
27
  ]);
22
28
 
29
+ // --- Deployment execution fence (F1) ---------------------------------------
30
+ //
31
+ // The fence table and its single row are created BY THIS PROTOCOL, so every
32
+ // database provisioned from 0.20 on is born carrying an EXPLICIT fence state
33
+ // instead of leaning on the absent-row-reads-open upgrade rule.
34
+ //
35
+ // The vocabulary and the DDL live HERE rather than beside the store that reads
36
+ // them (src/do-runner/execution-fence.ts, which imports them from this module)
37
+ // for one reason: this file is the only place both sides can share. It ships at
38
+ // the package root and is loaded by the provisioning CLI, by fleet-control's
39
+ // backends, and by the runtime — none of which can import the package's
40
+ // TypeScript sources. And the two MUST be one string: the store's own
41
+ // `CREATE TABLE IF NOT EXISTS` silently accepts a differently-shaped table this
42
+ // protocol created, so a drifted copy would not fail, it would quietly drop the
43
+ // CHECK constraints that make the store's compare-and-sets total.
44
+
45
+ /** The table the single fence row lives in — flowsafe-owned, outside `mastra_%`. */
46
+ export const EXECUTION_FENCE_TABLE = 'flowsafe_execution_fence';
47
+
48
+ /**
49
+ * The fence row's fixed primary key. The fence is a property of the DEPLOYMENT
50
+ * and a deployment is one database, so there is exactly one row and its key is
51
+ * a constant.
52
+ */
53
+ export const EXECUTION_FENCE_ROW_ID = 'deployment';
54
+
55
+ /** Every fence state, ordered from most to least permissive. */
56
+ export const EXECUTION_FENCE_STATES = Object.freeze([
57
+ 'open',
58
+ 'draining',
59
+ 'migration-locked',
60
+ 'proof-only',
61
+ ]);
62
+
63
+ /**
64
+ * The states a deployment may be BORN in. `draining` and `proof-only` are
65
+ * transitions out of a state that already exists — draining finishes work a
66
+ * fresh database has none of, and proof-only nominates a run nothing has yet
67
+ * started — so neither is a coherent initial condition.
68
+ */
69
+ export const INITIAL_EXECUTION_FENCE_STATES = Object.freeze([
70
+ 'open',
71
+ 'migration-locked',
72
+ ]);
73
+
74
+ export const EXECUTION_FENCE_DDL = `CREATE TABLE IF NOT EXISTS ${EXECUTION_FENCE_TABLE} (
75
+ id TEXT PRIMARY KEY CHECK (id = '${EXECUTION_FENCE_ROW_ID}'),
76
+ state TEXT NOT NULL CHECK (state IN (${EXECUTION_FENCE_STATES.map((state) => `'${state}'`).join(', ')})),
77
+ proof_key TEXT,
78
+ proof_run_id TEXT,
79
+ updated_at INTEGER NOT NULL
80
+ )`;
81
+
23
82
  const SENTINEL_SQL_PATTERN =
24
83
  /^create table (?:if not exists )?flowsafe_deployment\s*\(\s*id integer primary key check\s*\(\s*id\s*=\s*1\s*\)\s*,\s*tenant_tag text not null\s*,\s*provisioned_at text not null\s*\)$/i;
25
84
  const D1_OWNED_INTERNAL_TABLES = Object.freeze(['_cf_KV', '_cf_METADATA']);
26
- const D1_OWNED_TABLE_EXCLUSIONS = D1_OWNED_INTERNAL_TABLES.map(
85
+ /**
86
+ * Tables whose presence does NOT make a database "unowned application state":
87
+ * D1's own internal tables plus every table this protocol creates itself.
88
+ *
89
+ * The fence table belongs here because it can legitimately exist BEFORE the
90
+ * ownership row does — a previous provisioning attempt that died between the
91
+ * fence DDL and the sentinel insert leaves exactly that residue, and the
92
+ * runtime store also materializes the table on its first control-plane
93
+ * transition. Without the exclusion the next provisioning pass would read its
94
+ * own leftovers as somebody else's application data and refuse the database
95
+ * forever (`unownedDatabaseError`), and the conditional ownership insert below
96
+ * would never fire.
97
+ */
98
+ const NON_APPLICATION_TABLES = Object.freeze([
99
+ ...D1_OWNED_INTERNAL_TABLES,
100
+ EXECUTION_FENCE_TABLE,
101
+ ]);
102
+ const MIN_DEPLOYMENT_CREDENTIAL_LENGTH = 32;
103
+ const MAX_DEPLOYMENT_CREDENTIAL_LENGTH = 256;
104
+ const NON_APPLICATION_TABLE_EXCLUSIONS = NON_APPLICATION_TABLES.map(
27
105
  (name) => ` AND name <> '${name}'`,
28
106
  ).join('\n');
29
107
 
@@ -52,6 +130,11 @@ const CREATE_SENTINEL = Object.freeze({
52
130
  sql: DEPLOYMENT_SENTINEL_DDL,
53
131
  bindings: Object.freeze([]),
54
132
  });
133
+ const CREATE_EXECUTION_FENCE = Object.freeze({
134
+ mode: 'write',
135
+ sql: EXECUTION_FENCE_DDL,
136
+ bindings: Object.freeze([]),
137
+ });
55
138
 
56
139
  export class DeploymentIdentityError extends Error {
57
140
  constructor(message) {
@@ -60,6 +143,30 @@ export class DeploymentIdentityError extends Error {
60
143
  }
61
144
  }
62
145
 
146
+ export function assertDeploymentIdentitySecret(
147
+ secret,
148
+ caller = 'deployment identity',
149
+ ) {
150
+ if (
151
+ typeof secret !== 'string' ||
152
+ secret.length < MIN_DEPLOYMENT_CREDENTIAL_LENGTH ||
153
+ secret.length > MAX_DEPLOYMENT_CREDENTIAL_LENGTH ||
154
+ !/^[\x21-\x7e]+$/.test(secret)
155
+ ) {
156
+ throw new DeploymentIdentityError(
157
+ `${caller}: DEPLOYMENT_IDENTITY_SECRET must contain ${MIN_DEPLOYMENT_CREDENTIAL_LENGTH}-${MAX_DEPLOYMENT_CREDENTIAL_LENGTH} visible ASCII characters`,
158
+ );
159
+ }
160
+ }
161
+
162
+ /** Stamp the internal credential onto an ordinary topology request. */
163
+ export function deploymentIdentityHeaders(secret, initial) {
164
+ assertDeploymentIdentitySecret(secret, 'deploymentIdentityHeaders');
165
+ const merged = new Headers(initial);
166
+ merged.set(DEPLOYMENT_IDENTITY_HEADER, secret);
167
+ return Object.fromEntries(merged.entries());
168
+ }
169
+
63
170
  export function isDeploymentEnvironment(value) {
64
171
  return (
65
172
  typeof value === 'string' && DEPLOYMENT_ENVIRONMENT_PATTERN.test(value)
@@ -74,6 +181,28 @@ export function assertValidDeploymentTag(tag, caller) {
74
181
  }
75
182
  }
76
183
 
184
+ /**
185
+ * Validate the fence state a deployment is to be born in.
186
+ *
187
+ * Loud on anything else, and with NO default anywhere above it: the failure
188
+ * this closes is a migration host forgetting to ask for 'migration-locked' and
189
+ * silently getting an executing deployment, which is exactly the condition a
190
+ * migration exists to prevent. Making the argument required turns that into an
191
+ * obligation the caller cannot skip, while still letting a host that wants an
192
+ * open deployment say so.
193
+ */
194
+ export function assertInitialExecutionFenceState(state, caller) {
195
+ if (
196
+ typeof state !== 'string' ||
197
+ !INITIAL_EXECUTION_FENCE_STATES.includes(state)
198
+ ) {
199
+ throw new DeploymentIdentityError(
200
+ `${caller}: initialExecutionFenceState must be one of ${INITIAL_EXECUTION_FENCE_STATES.join(', ')} (got '${String(state)}') — it has no default on purpose`,
201
+ );
202
+ }
203
+ return state;
204
+ }
205
+
77
206
  export function normalizeDeploymentSentinelSql(sql) {
78
207
  return sql.replace(/\s+/g, ' ').trim();
79
208
  }
@@ -86,7 +215,7 @@ export function deploymentIdentityApplicationTables(rows) {
86
215
  typeof name === 'string' &&
87
216
  name !== DEPLOYMENT_SENTINEL_TABLE &&
88
217
  !name.startsWith('sqlite_') &&
89
- !D1_OWNED_INTERNAL_TABLES.includes(name),
218
+ !NON_APPLICATION_TABLES.includes(name),
90
219
  )
91
220
  .sort();
92
221
  }
@@ -138,13 +267,48 @@ function conditionalOwnershipInsert(tag, provisionedAt) {
138
267
  SELECT 1 FROM sqlite_schema
139
268
  WHERE type = 'table'
140
269
  AND name <> '${DEPLOYMENT_SENTINEL_TABLE}'
141
- ${D1_OWNED_TABLE_EXCLUSIONS}
270
+ ${NON_APPLICATION_TABLE_EXCLUSIONS}
142
271
  AND name NOT GLOB 'sqlite_*'
143
272
  )`,
144
273
  bindings: [tag, provisionedAt],
145
274
  };
146
275
  }
147
276
 
277
+ function seedExecutionFenceRow(state, seededAt) {
278
+ return {
279
+ mode: 'write',
280
+ sql: `INSERT OR IGNORE INTO ${EXECUTION_FENCE_TABLE}
281
+ (id, state, proof_key, proof_run_id, updated_at)
282
+ VALUES (?, ?, NULL, NULL, ?)`,
283
+ // INSERT OR IGNORE, never an upsert: seeding runs on every provisioning
284
+ // pass, and a re-provision of a LIVE deployment must not silently reopen a
285
+ // fence an operator closed.
286
+ //
287
+ // `updated_at` is an INTEGER column bound as TEXT because D1's REST query
288
+ // API takes every parameter as a string (fleet-control's
289
+ // d1RestParameters rejects anything else). SQLite's INTEGER affinity
290
+ // converts a well-formed integer literal on write, so the column still
291
+ // holds a number.
292
+ bindings: [EXECUTION_FENCE_ROW_ID, state, String(seededAt)],
293
+ };
294
+ }
295
+
296
+ /**
297
+ * Write the deployment's initial fence row, if it has none.
298
+ *
299
+ * Two statements rather than one request: every executor this protocol is
300
+ * driven through — the runtime's `db.prepare()`, the CLI's
301
+ * `wrangler d1 execute --command`, and both fleet-control backends' REST
302
+ * `/query` with bound parameters — carries exactly ONE statement per call, so
303
+ * there is no seam here through which a batch could be sent. The DDL therefore
304
+ * runs first and the row second; a crash between them leaves an empty fence
305
+ * table, which reads as `open` and is healed by the next invocation.
306
+ */
307
+ async function seedExecutionFence(execute, state, seededAt) {
308
+ await execute(CREATE_EXECUTION_FENCE);
309
+ await execute(seedExecutionFenceRow(state, seededAt));
310
+ }
311
+
148
312
  async function scanTables(execute) {
149
313
  return execute(SCAN_TABLES);
150
314
  }
@@ -182,9 +346,24 @@ function differentOwnerError(caller, stored, tag) {
182
346
  export async function provisionDeploymentIdentityProtocol(
183
347
  execute,
184
348
  tag,
185
- { caller = 'seedDeploymentIdentity', provisionedAt } = {},
349
+ {
350
+ caller = 'seedDeploymentIdentity',
351
+ provisionedAt,
352
+ now = Date.now,
353
+ initialExecutionFenceState,
354
+ } = {},
186
355
  ) {
187
356
  assertValidDeploymentTag(tag, caller);
357
+ // Validated BEFORE the first statement: a caller that omitted the fence state
358
+ // must learn so without having stamped ownership onto a database first.
359
+ const fenceState = assertInitialExecutionFenceState(
360
+ initialExecutionFenceState,
361
+ caller,
362
+ );
363
+ // One instant for both rows. The sentinel stores it as ISO TEXT and the fence
364
+ // as epoch-milliseconds INTEGER because that is what each column already is;
365
+ // an explicit `provisionedAt` still wins for the sentinel, as before.
366
+ const seededAt = now();
188
367
  const tables = await scanTables(execute);
189
368
  const applicationTables = deploymentIdentityApplicationTables(tables);
190
369
  const sentinelExists = tables.some(
@@ -195,6 +374,13 @@ export async function provisionDeploymentIdentityProtocol(
195
374
  if (storedBeforeCreate !== tag) {
196
375
  throw differentOwnerError(caller, storedBeforeCreate, tag);
197
376
  }
377
+ // The already-owned early return still seeds the fence. A previous pass
378
+ // that died between the ownership insert and the fence row left a
379
+ // deployment with an owner and NO explicit fence — permanently implicit-open
380
+ // residue, on the one deployment a migration most needs to be able to lock.
381
+ // Seeding here is what heals it, and INSERT-if-absent is what makes
382
+ // repeating it safe on a deployment whose fence has since been moved.
383
+ await seedExecutionFence(execute, fenceState, seededAt);
198
384
  return;
199
385
  }
200
386
  if (applicationTables.length > 0) {
@@ -207,11 +393,15 @@ export async function provisionDeploymentIdentityProtocol(
207
393
  if (storedAfterCreate !== tag) {
208
394
  throw differentOwnerError(caller, storedAfterCreate, tag);
209
395
  }
396
+ await seedExecutionFence(execute, fenceState, seededAt);
210
397
  return;
211
398
  }
212
399
 
213
400
  await execute(
214
- conditionalOwnershipInsert(tag, provisionedAt ?? new Date().toISOString()),
401
+ conditionalOwnershipInsert(
402
+ tag,
403
+ provisionedAt ?? new Date(seededAt).toISOString(),
404
+ ),
215
405
  );
216
406
  const seeded = await readDeploymentIdentityProtocol(execute);
217
407
  if (seeded === undefined) {
@@ -228,4 +418,10 @@ export async function provisionDeploymentIdentityProtocol(
228
418
  if (seeded !== tag) {
229
419
  throw differentOwnerError(caller, seeded, tag);
230
420
  }
421
+ // Last, never first: the fence DDL is the one statement that could add a
422
+ // table to an as-yet-unowned database, and running it only after ownership is
423
+ // PROVEN keeps it out of the window where `unownedDatabaseError` and the
424
+ // conditional ownership insert are still deciding whether this database is
425
+ // ours to write to at all.
426
+ await seedExecutionFence(execute, fenceState, seededAt);
231
427
  }
@@ -169,7 +169,7 @@ export function validateAgentModule(module) {
169
169
  fail(`agent '${meta.id}' must be created by createGuardedAgent`);
170
170
  }
171
171
  if (breakwaterGuardedAgentHostProtocol(module.agent) === undefined) {
172
- fail(`agent '${meta.id}' was built by a @proofoftech/breakwater without the durable-host protocol; >=0.12.0 is required`);
172
+ fail(`agent '${meta.id}' was built by a @proofoftech/breakwater release without the durable-host protocol (added in 0.12.0); install a release inside the declared peer range`);
173
173
  }
174
174
  if (module.agent.id !== meta.id) {
175
175
  fail(`metadata id '${meta.id}' does not match guarded agent id '${module.agent.id}'`);