@proofoftech/flowsafe 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (297) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/README.md +68 -6
  3. package/deployment-identity-protocol.d.mts +70 -1
  4. package/deployment-identity-protocol.mjs +423 -5
  5. package/dist/agent-host/index.d.ts +1 -1
  6. package/dist/agent-host/index.d.ts.map +1 -1
  7. package/dist/agent-host/index.js.map +1 -1
  8. package/dist/agent-host/router.d.ts.map +1 -1
  9. package/dist/agent-host/router.js +17 -4
  10. package/dist/agent-host/router.js.map +1 -1
  11. package/dist/agent-host/thread-host.d.ts +14 -1
  12. package/dist/agent-host/thread-host.d.ts.map +1 -1
  13. package/dist/agent-host/thread-host.js +865 -308
  14. package/dist/agent-host/thread-host.js.map +1 -1
  15. package/dist/agent-host/thread-topology.d.ts +43 -1
  16. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  17. package/dist/agent-host/thread-topology.js +301 -28
  18. package/dist/agent-host/thread-topology.js.map +1 -1
  19. package/dist/agent-runner/durable-agent-runner.d.ts +107 -8
  20. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  21. package/dist/agent-runner/durable-agent-runner.js +427 -55
  22. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  23. package/dist/agent-runner/index.d.ts +1 -1
  24. package/dist/agent-runner/index.d.ts.map +1 -1
  25. package/dist/agent-runner/index.js.map +1 -1
  26. package/dist/approval-api/actor-context.d.ts +4 -0
  27. package/dist/approval-api/actor-context.d.ts.map +1 -1
  28. package/dist/approval-api/actor-context.js +53 -5
  29. package/dist/approval-api/actor-context.js.map +1 -1
  30. package/dist/approval-api/d1-store.d.ts.map +1 -1
  31. package/dist/approval-api/d1-store.js +6 -3
  32. package/dist/approval-api/d1-store.js.map +1 -1
  33. package/dist/approval-api/principal-identity.d.ts +32 -0
  34. package/dist/approval-api/principal-identity.d.ts.map +1 -0
  35. package/dist/approval-api/principal-identity.js +69 -0
  36. package/dist/approval-api/principal-identity.js.map +1 -0
  37. package/dist/approval-api/principal.d.ts +10 -13
  38. package/dist/approval-api/principal.d.ts.map +1 -1
  39. package/dist/approval-api/principal.js +10 -46
  40. package/dist/approval-api/principal.js.map +1 -1
  41. package/dist/approval-api/retention.d.ts +1 -2
  42. package/dist/approval-api/retention.d.ts.map +1 -1
  43. package/dist/approval-api/retention.js.map +1 -1
  44. package/dist/approval-api/router.d.ts.map +1 -1
  45. package/dist/approval-api/router.js +9 -1
  46. package/dist/approval-api/router.js.map +1 -1
  47. package/dist/approval-api/service.d.ts +29 -14
  48. package/dist/approval-api/service.d.ts.map +1 -1
  49. package/dist/approval-api/service.js +83 -25
  50. package/dist/approval-api/service.js.map +1 -1
  51. package/dist/approval-api/types.d.ts +12 -0
  52. package/dist/approval-api/types.d.ts.map +1 -1
  53. package/dist/approval-api/types.js +12 -0
  54. package/dist/approval-api/types.js.map +1 -1
  55. package/dist/audit-export/index.d.ts +2 -2
  56. package/dist/audit-export/index.js +2 -2
  57. package/dist/background-tasks/d1-storage.d.ts +4 -3
  58. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  59. package/dist/background-tasks/d1-storage.js +7 -13
  60. package/dist/background-tasks/d1-storage.js.map +1 -1
  61. package/dist/background-tasks/host.d.ts +127 -14
  62. package/dist/background-tasks/host.d.ts.map +1 -1
  63. package/dist/background-tasks/host.js +579 -50
  64. package/dist/background-tasks/host.js.map +1 -1
  65. package/dist/background-tasks/index.d.ts +2 -2
  66. package/dist/background-tasks/index.d.ts.map +1 -1
  67. package/dist/background-tasks/index.js +11 -6
  68. package/dist/background-tasks/index.js.map +1 -1
  69. package/dist/background-tasks/routes.d.ts +19 -2
  70. package/dist/background-tasks/routes.d.ts.map +1 -1
  71. package/dist/background-tasks/routes.js +4 -4
  72. package/dist/background-tasks/routes.js.map +1 -1
  73. package/dist/deployment-identity-protocol.d.ts +2 -2
  74. package/dist/deployment-identity-protocol.d.ts.map +1 -1
  75. package/dist/deployment-identity-protocol.js +1 -1
  76. package/dist/deployment-identity-protocol.js.map +1 -1
  77. package/dist/do-runner/cause-chain.d.ts +53 -0
  78. package/dist/do-runner/cause-chain.d.ts.map +1 -0
  79. package/dist/do-runner/cause-chain.js +96 -0
  80. package/dist/do-runner/cause-chain.js.map +1 -0
  81. package/dist/do-runner/constants.d.ts +3 -0
  82. package/dist/do-runner/constants.d.ts.map +1 -0
  83. package/dist/do-runner/constants.js +3 -0
  84. package/dist/do-runner/constants.js.map +1 -0
  85. package/dist/do-runner/d1-storage.d.ts +47 -69
  86. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  87. package/dist/do-runner/d1-storage.js +972 -196
  88. package/dist/do-runner/d1-storage.js.map +1 -1
  89. package/dist/do-runner/deployment-identity.d.ts +29 -5
  90. package/dist/do-runner/deployment-identity.d.ts.map +1 -1
  91. package/dist/do-runner/deployment-identity.js +23 -6
  92. package/dist/do-runner/deployment-identity.js.map +1 -1
  93. package/dist/do-runner/do-error-response.d.ts +4 -23
  94. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  95. package/dist/do-runner/do-error-response.js +19 -24
  96. package/dist/do-runner/do-error-response.js.map +1 -1
  97. package/dist/do-runner/do-status-error.d.ts +37 -0
  98. package/dist/do-runner/do-status-error.d.ts.map +1 -0
  99. package/dist/do-runner/do-status-error.js +42 -0
  100. package/dist/do-runner/do-status-error.js.map +1 -0
  101. package/dist/do-runner/durable-object.d.ts +2 -1
  102. package/dist/do-runner/durable-object.d.ts.map +1 -1
  103. package/dist/do-runner/durable-object.js +617 -144
  104. package/dist/do-runner/durable-object.js.map +1 -1
  105. package/dist/do-runner/execution-admission.d.ts +114 -0
  106. package/dist/do-runner/execution-admission.d.ts.map +1 -0
  107. package/dist/do-runner/execution-admission.js +206 -0
  108. package/dist/do-runner/execution-admission.js.map +1 -0
  109. package/dist/do-runner/execution-context.d.ts.map +1 -1
  110. package/dist/do-runner/execution-context.js +1 -0
  111. package/dist/do-runner/execution-context.js.map +1 -1
  112. package/dist/do-runner/execution-fence.d.ts +379 -0
  113. package/dist/do-runner/execution-fence.d.ts.map +1 -0
  114. package/dist/do-runner/execution-fence.js +1098 -0
  115. package/dist/do-runner/execution-fence.js.map +1 -0
  116. package/dist/do-runner/fenced-workflow-capability.d.ts +64 -0
  117. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -0
  118. package/dist/do-runner/fenced-workflow-capability.js +3 -0
  119. package/dist/do-runner/fenced-workflow-capability.js.map +1 -0
  120. package/dist/do-runner/fenced-workflows-d1.d.ts +15 -0
  121. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -0
  122. package/dist/do-runner/fenced-workflows-d1.js +894 -0
  123. package/dist/do-runner/fenced-workflows-d1.js.map +1 -0
  124. package/dist/do-runner/index.d.ts +20 -8
  125. package/dist/do-runner/index.d.ts.map +1 -1
  126. package/dist/do-runner/index.js +21 -4
  127. package/dist/do-runner/index.js.map +1 -1
  128. package/dist/do-runner/init.d.ts +82 -1
  129. package/dist/do-runner/init.d.ts.map +1 -1
  130. package/dist/do-runner/init.js +58 -3
  131. package/dist/do-runner/init.js.map +1 -1
  132. package/dist/do-runner/initial-admission-refusal.d.ts +7 -0
  133. package/dist/do-runner/initial-admission-refusal.d.ts.map +1 -0
  134. package/dist/do-runner/initial-admission-refusal.js +41 -0
  135. package/dist/do-runner/initial-admission-refusal.js.map +1 -0
  136. package/dist/do-runner/inventory.d.ts +295 -0
  137. package/dist/do-runner/inventory.d.ts.map +1 -0
  138. package/dist/do-runner/inventory.js +800 -0
  139. package/dist/do-runner/inventory.js.map +1 -0
  140. package/dist/do-runner/notification-predicate.d.ts +8 -0
  141. package/dist/do-runner/notification-predicate.d.ts.map +1 -0
  142. package/dist/do-runner/notification-predicate.js +136 -0
  143. package/dist/do-runner/notification-predicate.js.map +1 -0
  144. package/dist/do-runner/run-lifecycle.d.ts +20 -1
  145. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  146. package/dist/do-runner/run-lifecycle.js +67 -13
  147. package/dist/do-runner/run-lifecycle.js.map +1 -1
  148. package/dist/do-runner/run-provenance.d.ts +38 -0
  149. package/dist/do-runner/run-provenance.d.ts.map +1 -0
  150. package/dist/do-runner/run-provenance.js +152 -0
  151. package/dist/do-runner/run-provenance.js.map +1 -0
  152. package/dist/do-runner/run-storage-tables.d.ts +2 -0
  153. package/dist/do-runner/run-storage-tables.d.ts.map +1 -0
  154. package/dist/do-runner/run-storage-tables.js +4 -0
  155. package/dist/do-runner/run-storage-tables.js.map +1 -0
  156. package/dist/do-runner/run-terminal-state.d.ts +29 -0
  157. package/dist/do-runner/run-terminal-state.d.ts.map +1 -0
  158. package/dist/do-runner/run-terminal-state.js +105 -0
  159. package/dist/do-runner/run-terminal-state.js.map +1 -0
  160. package/dist/do-runner/runtime.d.ts +191 -46
  161. package/dist/do-runner/runtime.d.ts.map +1 -1
  162. package/dist/do-runner/runtime.js +994 -378
  163. package/dist/do-runner/runtime.js.map +1 -1
  164. package/dist/do-runner/start-idempotency.d.ts +285 -0
  165. package/dist/do-runner/start-idempotency.d.ts.map +1 -0
  166. package/dist/do-runner/start-idempotency.js +994 -0
  167. package/dist/do-runner/start-idempotency.js.map +1 -0
  168. package/dist/do-runner/start-reservation-contract.d.ts +103 -0
  169. package/dist/do-runner/start-reservation-contract.d.ts.map +1 -0
  170. package/dist/do-runner/start-reservation-contract.js +338 -0
  171. package/dist/do-runner/start-reservation-contract.js.map +1 -0
  172. package/dist/do-runner/suspension-deadline.d.ts +4 -11
  173. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  174. package/dist/do-runner/suspension-deadline.js +8 -12
  175. package/dist/do-runner/suspension-deadline.js.map +1 -1
  176. package/dist/do-runner/table-prefix.d.ts.map +1 -1
  177. package/dist/do-runner/table-prefix.js +2 -1
  178. package/dist/do-runner/table-prefix.js.map +1 -1
  179. package/dist/do-runner/testing.d.ts +3 -0
  180. package/dist/do-runner/testing.d.ts.map +1 -0
  181. package/dist/do-runner/testing.js +3 -0
  182. package/dist/do-runner/testing.js.map +1 -0
  183. package/dist/do-runner/thread-do.d.ts +2 -1
  184. package/dist/do-runner/thread-do.d.ts.map +1 -1
  185. package/dist/do-runner/thread-do.js +14 -10
  186. package/dist/do-runner/thread-do.js.map +1 -1
  187. package/dist/do-runner/workflow-snapshot-row.d.ts +49 -0
  188. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -0
  189. package/dist/do-runner/workflow-snapshot-row.js +97 -0
  190. package/dist/do-runner/workflow-snapshot-row.js.map +1 -0
  191. package/dist/goals/objective-routes.d.ts +15 -5
  192. package/dist/goals/objective-routes.d.ts.map +1 -1
  193. package/dist/goals/objective-routes.js +64 -64
  194. package/dist/goals/objective-routes.js.map +1 -1
  195. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  196. package/dist/host-kit/approval-bridge.js +10 -7
  197. package/dist/host-kit/approval-bridge.js.map +1 -1
  198. package/dist/host-kit/do-response.d.ts +16 -0
  199. package/dist/host-kit/do-response.d.ts.map +1 -1
  200. package/dist/host-kit/do-response.js +181 -0
  201. package/dist/host-kit/do-response.js.map +1 -1
  202. package/dist/host-kit/do-run-topology.d.ts +3 -0
  203. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  204. package/dist/host-kit/do-run-topology.js +36 -8
  205. package/dist/host-kit/do-run-topology.js.map +1 -1
  206. package/dist/host-kit/env-vars.d.ts.map +1 -1
  207. package/dist/host-kit/env-vars.js +5 -6
  208. package/dist/host-kit/env-vars.js.map +1 -1
  209. package/dist/host-kit/flowsafe-worker.d.ts +49 -6
  210. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  211. package/dist/host-kit/flowsafe-worker.js +409 -111
  212. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  213. package/dist/host-kit/host-approval-service.d.ts +24 -14
  214. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  215. package/dist/host-kit/host-approval-service.js +29 -40
  216. package/dist/host-kit/host-approval-service.js.map +1 -1
  217. package/dist/host-kit/index.d.ts +9 -3
  218. package/dist/host-kit/index.d.ts.map +1 -1
  219. package/dist/host-kit/index.js +5 -1
  220. package/dist/host-kit/index.js.map +1 -1
  221. package/dist/host-kit/run-route-error.d.ts +8 -4
  222. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  223. package/dist/host-kit/run-route-error.js +14 -11
  224. package/dist/host-kit/run-route-error.js.map +1 -1
  225. package/dist/host-kit/run-router.d.ts +63 -2
  226. package/dist/host-kit/run-router.d.ts.map +1 -1
  227. package/dist/host-kit/run-router.js +167 -45
  228. package/dist/host-kit/run-router.js.map +1 -1
  229. package/dist/host-kit/stream-router.d.ts.map +1 -1
  230. package/dist/host-kit/stream-router.js +18 -9
  231. package/dist/host-kit/stream-router.js.map +1 -1
  232. package/dist/host-kit/thread-topology.d.ts +1 -1
  233. package/dist/host-kit/thread-topology.d.ts.map +1 -1
  234. package/dist/host-kit/thread-topology.js +7 -3
  235. package/dist/host-kit/thread-topology.js.map +1 -1
  236. package/dist/internal-error-response.d.ts.map +1 -1
  237. package/dist/internal-error-response.js +16 -6
  238. package/dist/internal-error-response.js.map +1 -1
  239. package/dist/schedules/index.d.ts +1 -0
  240. package/dist/schedules/index.d.ts.map +1 -1
  241. package/dist/schedules/index.js +1 -7
  242. package/dist/schedules/index.js.map +1 -1
  243. package/dist/schedules/mutation-contract.d.ts +38 -0
  244. package/dist/schedules/mutation-contract.d.ts.map +1 -0
  245. package/dist/schedules/mutation-contract.js +21 -0
  246. package/dist/schedules/mutation-contract.js.map +1 -0
  247. package/dist/schedules/router.d.ts +15 -8
  248. package/dist/schedules/router.d.ts.map +1 -1
  249. package/dist/schedules/router.js +170 -59
  250. package/dist/schedules/router.js.map +1 -1
  251. package/dist/schedules/schedules-d1.d.ts +11 -5
  252. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  253. package/dist/schedules/schedules-d1.js +570 -143
  254. package/dist/schedules/schedules-d1.js.map +1 -1
  255. package/dist/schedules/storage.d.ts +0 -7
  256. package/dist/schedules/storage.d.ts.map +1 -1
  257. package/dist/schedules/storage.js +0 -27
  258. package/dist/schedules/storage.js.map +1 -1
  259. package/dist/schedules/tick.d.ts +13 -0
  260. package/dist/schedules/tick.d.ts.map +1 -1
  261. package/dist/schedules/tick.js +66 -40
  262. package/dist/schedules/tick.js.map +1 -1
  263. package/dist/signal-providers/host-do.d.ts +12 -1
  264. package/dist/signal-providers/host-do.d.ts.map +1 -1
  265. package/dist/signal-providers/host-do.js +28 -3
  266. package/dist/signal-providers/host-do.js.map +1 -1
  267. package/dist/signal-providers/webhook-route.d.ts +15 -1
  268. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  269. package/dist/signal-providers/webhook-route.js +126 -113
  270. package/dist/signal-providers/webhook-route.js.map +1 -1
  271. package/dist/signals/d1-shared.d.ts +11 -8
  272. package/dist/signals/d1-shared.d.ts.map +1 -1
  273. package/dist/signals/d1-shared.js +1 -6
  274. package/dist/signals/d1-shared.js.map +1 -1
  275. package/dist/signals/index.d.ts +1 -1
  276. package/dist/signals/index.d.ts.map +1 -1
  277. package/dist/signals/index.js +1 -1
  278. package/dist/signals/index.js.map +1 -1
  279. package/dist/signals/notification-dispatch.d.ts +109 -5
  280. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  281. package/dist/signals/notification-dispatch.js +430 -46
  282. package/dist/signals/notification-dispatch.js.map +1 -1
  283. package/dist/signals/notifications-d1.d.ts +14 -1
  284. package/dist/signals/notifications-d1.d.ts.map +1 -1
  285. package/dist/signals/notifications-d1.js +229 -18
  286. package/dist/signals/notifications-d1.js.map +1 -1
  287. package/dist/signals/router.d.ts +6 -4
  288. package/dist/signals/router.d.ts.map +1 -1
  289. package/dist/signals/router.js +49 -84
  290. package/dist/signals/router.js.map +1 -1
  291. package/dist/signals/thread-do-routes.d.ts +2 -0
  292. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  293. package/dist/signals/thread-do-routes.js +330 -83
  294. package/dist/signals/thread-do-routes.js.map +1 -1
  295. package/package.json +6 -3
  296. package/patches/@mastra__core@1.53.0.patch +54 -0
  297. package/scripts/seed-deployment-identity.mjs +34 -9
@@ -1,11 +1,10 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
- // Track C (M-004) — the signal routes hosted ON the thread DO (CI-M-004-001,
3
- // DL-002). A thread's agent loop and every signal for that thread both address
4
- // `idFromName(threadId)`, so the platform serializes them onto ONE isolate — the
5
- // DO IS the serialization lease Mastra otherwise wants Redis for (DL-002). These
6
- // routes run AFTER ThreadDurableObject.fetch has already verified the deployment
7
- // identity and decoded the server-stamped principal, so `scope.threadId` and
8
- // `scope.principal` are trusted here; the P6 ingestion gate (allowlist / size
2
+ // The signal routes hosted ON the thread DO. A thread's agent loop and every
3
+ // signal both address `idFromName(threadId)`, so the platform serializes them
4
+ // onto ONE isolate. The DO IS the serialization lease Mastra otherwise wants
5
+ // Redis for. These routes run AFTER ThreadDurableObject.fetch verifies the
6
+ // deployment identity and decodes the server-stamped principal. The scope's
7
+ // threadId and principal are trusted here; the ingestion gate (allowlist / size
9
8
  // cap / rate cap / audit) is the Worker-side createSignalRouter's job, the same
10
9
  // split createRunRouter (Worker gate) → DurableObjectRunner (execution) uses.
11
10
  //
@@ -14,24 +13,26 @@
14
13
  // module-level `defaultAgentThreadPubSub`), so a send only drains into an active
15
14
  // loop when BOTH run in one isolate (the DO gives this) AND both use the SAME
16
15
  // pubsub. The agent resolves its pubsub from `agent.getPubSub()`, so these routes
17
- // stamp the DO's ONE identity (`scope.init.pubsub`, Track 0 / DL-001) onto the
18
- // agent before every call — the exact reason Track A threads that same identity
19
- // into createRun. Absent (host opted out) ⇒ core's module default, still one per
16
+ // stamp the DO's ONE identity (`scope.init.pubsub`) onto the agent before every
17
+ // call — the exact reason durable-agent execution threads that identity into
18
+ // createRun. Absent (host opted out) ⇒ core's module default, still one per
20
19
  // isolate, so affinity holds either way; a wired pubsub additionally makes
21
20
  // observe()/replay align (pubsub.ts).
22
21
  //
23
22
  // core's `agentThreadStreamRuntime` is NOT on the package exports map, so these
24
- // routes drive the PUBLIC Agent methods only (never a deep dist import — R-001).
23
+ // routes drive only the PUBLIC Agent methods, never a deep dist import across
24
+ // the export boundary.
25
25
  import { createMessageSignal, createSignal, resolveDeliveryAttributes, signalToXmlMarkup, } from '@mastra/core/agent';
26
26
  import { createNotificationSignal, createNotificationSummarySignal, summarizeNotifications, } from '@mastra/core/notifications';
27
27
  import { RequestContext } from '@mastra/core/request-context';
28
28
  import { FLOWSAFE_PERSISTENCE_FORBIDDEN } from '../agent-runner/durable-agent-runner.js';
29
29
  import { isRuntimeDrivenAgent, } from '../agent-runner/index.js';
30
30
  import { samePrincipal, } from '../approval-api/index.js';
31
- import { DoStatusError, isPathSafeId, } from '../do-runner/index.js';
31
+ import { admitsExistingRun, DoStatusError, ExecutionFencedError, executionFencedResponse, isExecutionFenceRefusal, isPathSafeId, readExecutionFence, } from '../do-runner/index.js';
32
32
  import { internalErrorResponse } from '../internal-error-response.js';
33
+ import { positiveSafeInteger } from '../numeric-config.js';
33
34
  import { createScheduleAgentDispatchReceipt, } from '../schedules/schedules-d1.js';
34
- import { deferNotificationAfterFailure, MAX_NOTIFICATION_DISPATCH_IDS, planNotificationDispatch, } from './notification-dispatch.js';
35
+ import { assertNotificationDeliveryPolicyPatched, assertNotificationSourceKeysPatched, captureNotificationDeliverySelection, captureNotificationDeliveryStorage, DEFAULT_MAX_NOTIFICATION_DELIVERY_ATTEMPTS, MAX_NOTIFICATION_DISPATCH_IDS, planNotificationDispatch, recordNotificationDeliveryFailure, reportNotificationDeliveryError, } from './notification-dispatch.js';
35
36
  /**
36
37
  * The idle-thread delivery behavior a send may ask for. `wake` starts a run
37
38
  * after consulting the run cap; `persist` writes the signal to the durable
@@ -190,6 +191,7 @@ function signalContentPolicyResponse(inspection) {
190
191
  : json({ error: 'signal content policy unavailable' }, 503);
191
192
  }
192
193
  export function createThreadSignalRoutes(options) {
194
+ const maxDeliveryAttempts = positiveSafeInteger(options.maxDeliveryAttempts ?? DEFAULT_MAX_NOTIFICATION_DELIVERY_ATTEMPTS, 'notification maximum delivery attempts');
193
195
  const { resolveAgent, resolveResourceId, consultRunCap, startIdleRun, resolveBlockingRun, serializeDispatch, resolveScheduleRunStatus, resolveScheduleTarget, canPersist, canPersistSchedule, resolveNotificationsStorage, resolveScheduleDispatchStore, contentPolicy, } = options;
194
196
  if (resolveBlockingRun && !serializeDispatch) {
195
197
  throw new Error('signal routes require serializeDispatch with resolveBlockingRun');
@@ -221,6 +223,18 @@ export function createThreadSignalRoutes(options) {
221
223
  if (!body)
222
224
  return json({ error: 'a JSON body is required' }, 400);
223
225
  try {
226
+ // The execution fence, read ONCE for this request and before any store
227
+ // lookup. `migration-locked` refuses every signal route outright — the
228
+ // persist lanes included, because their thread-state write is part of
229
+ // what the migration is copying. `proof-only` is decided further down,
230
+ // once the thread's active run is knowable.
231
+ //
232
+ // A read that fails throws ExecutionFenceUnreadableError, which the
233
+ // catch below answers as a 503 — degrade closed, never a silent open.
234
+ const executionFence = await readExecutionFence(scope.init.executionFence);
235
+ if (executionFence.state === 'migration-locked') {
236
+ return executionFencedResponse(executionFence.state, entryPath);
237
+ }
224
238
  let scheduleTarget;
225
239
  if (path === '/signal/schedule') {
226
240
  if (!resolveScheduleTarget) {
@@ -266,6 +280,50 @@ export function createThreadSignalRoutes(options) {
266
280
  agent.__setPubSub(pubsub);
267
281
  const resourceId = resolveResourceId?.(scope);
268
282
  const threadId = scope.threadId;
283
+ // proof-only admits work on ONE run, so the gate lives here — the first
284
+ // point where the run a signal would reach is knowable, and the only one
285
+ // every route passes through. Deciding it inside handleWake would leave
286
+ // the lanes that never reach it (the persist routes, and a default
287
+ // non-wake delivery) ungated; handleWake keeps its own check for the
288
+ // wake path it owns.
289
+ let proof;
290
+ if (executionFence.state === 'proof-only') {
291
+ const runtime = scope.init.runtime;
292
+ const reader = agent.proofExecutionFor;
293
+ if (!runtimeDriven ||
294
+ typeof reader !== 'function' ||
295
+ runtime.executionFence !== scope.init.executionFence)
296
+ throw new ExecutionFencedError(executionFence.state, entryPath);
297
+ const capture = async (runId) => {
298
+ if (runId === undefined)
299
+ throw new ExecutionFencedError(executionFence.state, entryPath);
300
+ const execution = await Reflect.apply(reader, agent, [
301
+ runtime,
302
+ threadId,
303
+ runId,
304
+ ]);
305
+ if (execution === undefined ||
306
+ !admitsExistingRun(executionFence, execution))
307
+ throw new ExecutionFencedError(executionFence.state, entryPath);
308
+ return Object.freeze({ ...execution });
309
+ };
310
+ const admitted = await capture(activeThreadRunIdOf(agent, threadId, resourceId ?? ''));
311
+ const assertActive = (expected = admitted) => {
312
+ if (activeThreadRunIdOf(agent, threadId, resourceId ?? '') !==
313
+ expected.runId)
314
+ throw new ExecutionFencedError(executionFence.state, entryPath);
315
+ };
316
+ proof = {
317
+ capture,
318
+ async check(expected = admitted) {
319
+ const current = await capture(expected.runId);
320
+ if (!admitsExistingRun({ state: 'proof-only', proofExecution: expected }, current))
321
+ throw new ExecutionFencedError(executionFence.state, entryPath);
322
+ },
323
+ assertActive,
324
+ };
325
+ assertActive();
326
+ }
269
327
  let memoryResolution;
270
328
  const memoryAvailable = () => {
271
329
  memoryResolution ??= (async () => {
@@ -274,10 +332,15 @@ export function createThreadSignalRoutes(options) {
274
332
  Boolean(await agent.getMemory()));
275
333
  }
276
334
  catch {
277
- console.error(JSON.stringify({
278
- type: 'signal-memory-resolution-failed',
279
- threadId,
280
- }));
335
+ try {
336
+ console.error(JSON.stringify({
337
+ type: 'signal-memory-resolution-failed',
338
+ threadId,
339
+ }));
340
+ }
341
+ catch {
342
+ // Diagnostics cannot change the memory fallback.
343
+ }
281
344
  return false;
282
345
  }
283
346
  })();
@@ -315,6 +378,8 @@ export function createThreadSignalRoutes(options) {
315
378
  persistenceAllowed,
316
379
  memoryAvailable,
317
380
  inspectContent,
381
+ proof,
382
+ executionFence,
318
383
  });
319
384
  }
320
385
  // POST /signal/queue — persisted for the next host-started turn; never
@@ -326,6 +391,7 @@ export function createThreadSignalRoutes(options) {
326
391
  persistenceAllowed,
327
392
  memoryAvailable,
328
393
  inspectContent,
394
+ proof,
329
395
  });
330
396
  }
331
397
  // POST /signal — a system signal (ifActive/ifIdle deliver/persist/discard/wake).
@@ -337,6 +403,8 @@ export function createThreadSignalRoutes(options) {
337
403
  persistenceAllowed,
338
404
  memoryAvailable,
339
405
  inspectContent,
406
+ proof,
407
+ executionFence,
340
408
  });
341
409
  }
342
410
  if (path === '/signal/schedule') {
@@ -349,6 +417,7 @@ export function createThreadSignalRoutes(options) {
349
417
  return await handleScheduleSignal({
350
418
  agent,
351
419
  body,
420
+ executionFence,
352
421
  target: scheduleTarget,
353
422
  threadId,
354
423
  resourceId,
@@ -370,6 +439,7 @@ export function createThreadSignalRoutes(options) {
370
439
  store: await resolveScheduleDispatchStore(scope),
371
440
  completed: completedScheduleDispatches,
372
441
  inspectContent,
442
+ proof,
373
443
  });
374
444
  }
375
445
  // POST /signal/state — a durable thread-state lane (snapshot/delta).
@@ -381,6 +451,7 @@ export function createThreadSignalRoutes(options) {
381
451
  runtimeDriven,
382
452
  memoryAvailable,
383
453
  inspectContent,
454
+ proof,
384
455
  });
385
456
  }
386
457
  if (requestedAgentId !== undefined) {
@@ -390,6 +461,7 @@ export function createThreadSignalRoutes(options) {
390
461
  return await serializeNotification(async () => handleNotificationDispatch({
391
462
  agent,
392
463
  body,
464
+ executionFence,
393
465
  threadId,
394
466
  resourceId,
395
467
  deploymentTag: scope.deploymentTag,
@@ -403,19 +475,28 @@ export function createThreadSignalRoutes(options) {
403
475
  persistenceAllowed,
404
476
  memoryAvailable,
405
477
  storage: await resolveNotificationsStorage(scope),
478
+ maxDeliveryAttempts,
406
479
  agentId: requestedAgentId,
407
480
  inspectContent,
481
+ proof,
408
482
  }));
409
483
  }
410
484
  // POST /signal/notification — the durable AGENT inbox (mastra_notifications).
411
485
  if (path === '/signal/notification') {
412
486
  return await serializeNotification(async () => handleNotification(agent, body, threadId, resourceId, resolveNotificationsStorage
413
487
  ? () => resolveNotificationsStorage(scope)
414
- : undefined, { persistenceAllowed, runtimeDriven, inspectContent }));
488
+ : undefined, { persistenceAllowed, runtimeDriven, inspectContent, proof }));
415
489
  }
416
490
  return json({ error: 'not found' }, 404);
417
491
  }
418
492
  catch (error) {
493
+ // The fence refusing, or failing to answer. Surfaced with its own 503 and
494
+ // reason rather than the 502 below: a caller must be able to tell "this
495
+ // deployment is deliberately not executing" (retry after the migration)
496
+ // from "the model or a route is broken".
497
+ if (isExecutionFenceRefusal(error)) {
498
+ return json({ error: error.message, reason: error.reason }, error.status);
499
+ }
419
500
  if (error instanceof DoStatusError &&
420
501
  (error.status === 403 || error.status === 404 || error.status === 409)) {
421
502
  const message = error.status === 403
@@ -473,6 +554,7 @@ async function handleNotificationDispatch(options) {
473
554
  if (Number.isNaN(now.getTime())) {
474
555
  return json({ error: 'now must be an ISO timestamp' }, 400);
475
556
  }
557
+ const nowMs = now.getTime();
476
558
  const carriesBatchThreadState = Object.hasOwn(options.body, 'batchThreadState');
477
559
  const requestedBatchThreadState = options.body.batchThreadState;
478
560
  if (carriesBatchThreadState &&
@@ -481,30 +563,61 @@ async function handleNotificationDispatch(options) {
481
563
  requestedBatchThreadState !== 'idle') {
482
564
  return json({ error: 'batchThreadState must be null, active, or idle' }, 400);
483
565
  }
484
- const records = [];
566
+ assertNotificationSourceKeysPatched();
567
+ const deliveryStorage = captureNotificationDeliveryStorage(options.storage);
568
+ const selections = [];
569
+ // A record settles once: an already-discarded record must not be counted
570
+ // twice, nor have its content-policy reason overwritten by an unrelated
571
+ // storage error. `recordFailure` returns early for the same reason.
572
+ const settled = new Set();
573
+ let delivered = 0;
574
+ let failed = 0;
575
+ let discarded = 0;
485
576
  let skipped = 0;
577
+ const settle = (id, outcome) => {
578
+ if (settled.has(id))
579
+ return;
580
+ settled.add(id);
581
+ if (outcome === 'delivered')
582
+ delivered += 1;
583
+ else if (outcome === 'failed')
584
+ failed += 1;
585
+ else if (outcome === 'discarded')
586
+ discarded += 1;
587
+ else
588
+ skipped += 1;
589
+ };
486
590
  for (const id of uniqueIds) {
487
- const current = await options.storage.getNotification({
591
+ const current = await deliveryStorage.getNotification({
488
592
  threadId: options.threadId,
489
593
  id,
490
594
  });
491
595
  if (current?.status !== 'pending' || current.deliveredSignalId) {
492
- skipped += 1;
596
+ settle(id, 'skipped');
493
597
  continue;
494
598
  }
495
- if (current.resourceId !== options.resourceId ||
599
+ if (current.id !== id ||
600
+ current.threadId !== options.threadId ||
601
+ current.resourceId !== options.resourceId ||
496
602
  current.agentId !== options.agentId) {
497
603
  return json({ error: 'notification binding does not match' }, 404);
498
604
  }
499
- const due = (current.deliverAt !== undefined &&
500
- current.deliverAt.getTime() <= now.getTime()) ||
501
- (current.summaryAt !== undefined &&
502
- current.summaryAt.getTime() <= now.getTime());
503
- if (!due) {
504
- skipped += 1;
505
- continue;
605
+ try {
606
+ const selection = captureNotificationDeliverySelection(current);
607
+ const { record } = selection;
608
+ const due = (record.deliverAt !== undefined &&
609
+ record.deliverAt.getTime() <= nowMs) ||
610
+ (record.summaryAt !== undefined && record.summaryAt.getTime() <= nowMs);
611
+ if (!due) {
612
+ settle(id, 'skipped');
613
+ continue;
614
+ }
615
+ selections.push(selection);
616
+ }
617
+ catch (error) {
618
+ settle(id, 'failed');
619
+ reportNotificationDeliveryError(error);
506
620
  }
507
- records.push(current);
508
621
  }
509
622
  const batchThreadState = requestedBatchThreadState === 'active' ||
510
623
  requestedBatchThreadState === 'idle'
@@ -513,30 +626,29 @@ async function handleNotificationDispatch(options) {
513
626
  activeThreadRunIdOf(options.agent, options.threadId, resourceId)
514
627
  ? 'active'
515
628
  : 'idle';
516
- let delivered = 0;
517
- let failed = 0;
518
- let discarded = 0;
519
- // Records whose terminal discard is already durable. A later throw in the
520
- // same group funnels the group into `updateFailure`; without this, an
521
- // already-discarded record would be counted twice and have its
522
- // content-policy reason overwritten by an unrelated storage error.
523
- const settledDiscards = new Set();
524
- const updateFailure = async (record, error) => {
525
- if (settledDiscards.has(record.id))
629
+ const recordFailure = async (expected, action) => {
630
+ if (action.type === 'failure' && isExecutionFenceRefusal(action.error))
631
+ throw action.error;
632
+ if (!expected)
633
+ throw new Error('notification observation is unavailable');
634
+ if (settled.has(expected.id))
526
635
  return;
527
- failed += 1;
528
- await deferNotificationAfterFailure(options.storage, record, now, error);
636
+ await options.proof?.check();
637
+ options.proof?.assertActive();
638
+ const outcome = await recordNotificationDeliveryFailure(deliveryStorage, expected, new Date(nowMs), options.maxDeliveryAttempts, action);
639
+ settle(expected.id, outcome === 'discarded' ? 'discarded' : 'failed');
529
640
  };
530
641
  const discardAfterDenial = async (record) => {
642
+ await options.proof?.check();
643
+ options.proof?.assertActive();
531
644
  await options.storage.updateNotification({
532
645
  id: record.id,
533
646
  threadId: record.threadId,
534
647
  status: 'discarded',
535
648
  deliveryReason: 'content-policy-denied',
536
- lastDeliveryAttemptAt: now,
649
+ lastDeliveryAttemptAt: new Date(nowMs),
537
650
  });
538
- settledDiscards.add(record.id);
539
- discarded += 1;
651
+ settle(record.id, 'discarded');
540
652
  };
541
653
  const inspect = async (signal) => {
542
654
  if (!options.inspectContent)
@@ -559,6 +671,8 @@ async function handleNotificationDispatch(options) {
559
671
  consultRunCap: options.consultRunCap,
560
672
  startIdleRun: options.startIdleRun,
561
673
  serializeWake: options.serializeWake,
674
+ executionFence: options.executionFence,
675
+ proof: options.proof,
562
676
  blockingRun: durableBlockingRun
563
677
  ? () => durableBlockingRun
564
678
  : options.blockingRun,
@@ -582,8 +696,11 @@ async function handleNotificationDispatch(options) {
582
696
  ifIdle: { behavior: 'persist' },
583
697
  }),
584
698
  });
585
- if (!response.ok)
699
+ if (!response.ok) {
700
+ if (options.executionFence.state === 'proof-only')
701
+ throw new ExecutionFencedError('proof-only', 'notification signal');
586
702
  throw new Error(`notification signal returned ${response.status}`);
703
+ }
587
704
  const result = (await response.json());
588
705
  const action = recordValue(result.decision)?.action;
589
706
  // A stale active id can fall through to idle. Persistence-forbidden and
@@ -604,6 +721,8 @@ async function handleNotificationDispatch(options) {
604
721
  if (!(await options.memoryAvailable())) {
605
722
  throw new Error('signal persistence requires agent memory');
606
723
  }
724
+ await options.proof?.check();
725
+ options.proof?.assertActive();
607
726
  const result = options.agent.sendSignal(signal, {
608
727
  threadId: options.threadId,
609
728
  resourceId,
@@ -615,12 +734,21 @@ async function handleNotificationDispatch(options) {
615
734
  await result.persisted;
616
735
  return result.signal.id;
617
736
  };
737
+ const records = [];
738
+ const observations = new Map();
739
+ for (const { record, expected } of selections) {
740
+ if (expected.deliveryAttempts >= options.maxDeliveryAttempts) {
741
+ await recordFailure(expected, { type: 'exhausted' });
742
+ continue;
743
+ }
744
+ records.push(record);
745
+ observations.set(record.id, expected);
746
+ }
618
747
  for (const item of planNotificationDispatch(records, now)) {
619
748
  if (item.type === 'summary') {
620
- // Everything from rendering onward stays inside this try: a storage
621
- // failure in the discard/failure bookkeeping below must be contained to
622
- // this group, exactly as the individual branch contains its own, rather
623
- // than escaping and abandoning the rest of the plan.
749
+ // A summary group's failure, from rendering through bookkeeping, is
750
+ // contained to this group rather than escaping and abandoning the rest
751
+ // of the plan.
624
752
  try {
625
753
  const signal = createNotificationSummarySignal(summarizeNotifications(item.records));
626
754
  const inspection = await inspect(signal);
@@ -631,7 +759,10 @@ async function handleNotificationDispatch(options) {
631
759
  }
632
760
  if (inspection === 'error') {
633
761
  for (const record of item.records) {
634
- await updateFailure(record, new Error('signal content policy failed'));
762
+ await recordFailure(observations.get(record.id), {
763
+ type: 'failure',
764
+ error: new Error('signal content policy failed'),
765
+ });
635
766
  }
636
767
  continue;
637
768
  }
@@ -640,49 +771,70 @@ async function handleNotificationDispatch(options) {
640
771
  ? await persistWithoutWake(signal)
641
772
  : await send(signal);
642
773
  for (const record of item.records) {
774
+ await options.proof?.check();
775
+ options.proof?.assertActive();
643
776
  await options.storage.updateNotification({
644
777
  id: record.id,
645
778
  threadId: record.threadId,
646
779
  summaryAt: null,
647
780
  summarySignalId: signalId,
648
- lastDeliveryAttemptAt: now,
781
+ lastDeliveryAttemptAt: new Date(nowMs),
649
782
  });
650
- delivered += 1;
783
+ settle(record.id, 'delivered');
651
784
  }
652
785
  }
653
786
  catch (error) {
654
- for (const record of item.records)
655
- await updateFailure(record, error);
787
+ for (const record of item.records) {
788
+ await recordFailure(observations.get(record.id), {
789
+ type: 'failure',
790
+ error,
791
+ });
792
+ }
656
793
  }
657
794
  continue;
658
795
  }
659
796
  const selected = item.record;
797
+ let expected = observations.get(selected.id);
660
798
  try {
661
- const record = await options.storage.getNotification({
799
+ const current = await deliveryStorage.getNotification({
662
800
  threadId: selected.threadId,
663
801
  id: selected.id,
664
802
  });
665
- const summaryDue = Boolean(record?.summaryAt && record.summaryAt.getTime() <= now.getTime());
666
- const deliveryDue = Boolean(record?.deliverAt && record.deliverAt.getTime() <= now.getTime());
667
- if (record?.status !== 'pending' ||
668
- record.deliveredSignalId ||
669
- record.resourceId !== resourceId ||
670
- record.agentId !== options.agentId ||
671
- summaryDue ||
672
- !deliveryDue) {
673
- skipped += 1;
803
+ if (current?.status !== 'pending' ||
804
+ current.deliveredSignalId ||
805
+ current.id !== selected.id ||
806
+ current.threadId !== options.threadId ||
807
+ current.resourceId !== resourceId ||
808
+ current.agentId !== options.agentId) {
809
+ settle(selected.id, 'skipped');
810
+ continue;
811
+ }
812
+ // Clearing the pre-read observation keeps a failure between here and the
813
+ // re-capture from being recorded against stale state.
814
+ expected = undefined;
815
+ const selection = captureNotificationDeliverySelection(current);
816
+ const { record } = selection;
817
+ expected = selection.expected;
818
+ const summaryDue = Boolean(record.summaryAt && record.summaryAt.getTime() <= nowMs);
819
+ const deliveryDue = Boolean(record.deliverAt && record.deliverAt.getTime() <= nowMs);
820
+ if (summaryDue || !deliveryDue) {
821
+ settle(selected.id, 'skipped');
822
+ continue;
823
+ }
824
+ if (expected.deliveryAttempts >= options.maxDeliveryAttempts) {
825
+ await recordFailure(expected, { type: 'exhausted' });
674
826
  continue;
675
827
  }
676
828
  if (record.priority === 'high' &&
677
829
  record.summarySignalId &&
678
830
  batchThreadState === 'active') {
679
- skipped += 1;
831
+ settle(selected.id, 'skipped');
680
832
  continue;
681
833
  }
682
834
  const signal = createNotificationSignal({
683
835
  ...record,
684
836
  status: 'delivered',
685
- deliveredAt: now,
837
+ deliveredAt: new Date(nowMs),
686
838
  });
687
839
  const inspection = await inspect(signal);
688
840
  if (inspection === 'denied') {
@@ -690,21 +842,33 @@ async function handleNotificationDispatch(options) {
690
842
  continue;
691
843
  }
692
844
  if (inspection === 'error') {
693
- await updateFailure(record, new Error('signal content policy failed'));
845
+ await recordFailure(expected, {
846
+ type: 'failure',
847
+ error: new Error('signal content policy failed'),
848
+ });
694
849
  continue;
695
850
  }
696
851
  const signalId = await send(signal);
852
+ await options.proof?.check();
853
+ options.proof?.assertActive();
697
854
  await options.storage.updateNotification({
698
855
  id: record.id,
699
856
  threadId: record.threadId,
700
857
  status: 'delivered',
701
858
  deliveredSignalId: signalId,
702
- lastDeliveryAttemptAt: now,
859
+ lastDeliveryAttemptAt: new Date(nowMs),
703
860
  });
704
- delivered += 1;
861
+ settle(record.id, 'delivered');
705
862
  }
706
863
  catch (error) {
707
- await updateFailure(selected, error);
864
+ if (isExecutionFenceRefusal(error))
865
+ throw error;
866
+ if (expected)
867
+ await recordFailure(expected, { type: 'failure', error });
868
+ else {
869
+ settle(selected.id, 'failed');
870
+ reportNotificationDeliveryError(error);
871
+ }
708
872
  }
709
873
  }
710
874
  return json({
@@ -784,12 +948,22 @@ function persistenceForbiddenResponse(options) {
784
948
  }
785
949
  async function handleWake(options) {
786
950
  return options.serializeWake(async () => {
951
+ const fence = options.executionFence;
787
952
  const durableBlockingRun = await options.blockingRun?.();
788
953
  const activeRunId = activeThreadRunIdOf(options.agent, options.threadId, options.resourceId);
789
954
  if (durableBlockingRun &&
790
955
  !samePrincipal(durableBlockingRun.principal, options.principal)) {
791
956
  return principalMismatchResponse(durableBlockingRun.runId);
792
957
  }
958
+ // Delivery into a run that ALREADY exists survives a drain — the run is
959
+ // what the drain is waiting for — and in proof-only it is admitted only
960
+ // for the nominated run. The check sits after the principal gate so a
961
+ // fenced deployment leaks nothing a permitted caller could not see.
962
+ const admitted = fence.state === 'proof-only'
963
+ ? await options.proof?.capture(activeRunId)
964
+ : undefined;
965
+ if (fence.state === 'proof-only' && admitted === undefined)
966
+ throw new ExecutionFencedError(fence.state, 'signal delivery');
793
967
  if (activeRunId) {
794
968
  if (durableBlockingRun && durableBlockingRun.runId !== activeRunId) {
795
969
  return json({
@@ -802,6 +976,8 @@ async function handleWake(options) {
802
976
  });
803
977
  }
804
978
  const memoryAvailable = await options.memoryAvailable();
979
+ await options.proof?.check(admitted);
980
+ options.proof?.assertActive(admitted);
805
981
  const delivered = options.deliverActive(activeRunId, memoryAvailable);
806
982
  const decision = await delivered.accepted;
807
983
  if (delivered.persisted)
@@ -834,16 +1010,37 @@ async function handleWake(options) {
834
1010
  : {}),
835
1011
  });
836
1012
  }
1013
+ // An idle thread has no run to deliver into, so from here on the only way
1014
+ // to serve the signal is to MINT one. `migration-locked` and `proof-only`
1015
+ // forbid that outright and have no lossless alternative to offer (the
1016
+ // proof run is a specific run, not this thread's next one), so they refuse
1017
+ // and the caller retries after the migration. `draining` degrades to the
1018
+ // persist branch below instead — see WakeRefusal.
1019
+ if (fence.state === 'migration-locked' || fence.state === 'proof-only') {
1020
+ return executionFencedResponse(fence.state, 'signal wake');
1021
+ }
837
1022
  const startIdleRun = options.startIdleRun;
838
- const refusal = !options.runtimeDriven
839
- ? 'not-runtime-driven'
840
- : !startIdleRun
841
- ? 'no-start-idle-run'
842
- : undefined;
1023
+ const refusal = fence.state === 'draining'
1024
+ ? 'execution-draining'
1025
+ : !options.runtimeDriven
1026
+ ? 'not-runtime-driven'
1027
+ : !startIdleRun
1028
+ ? 'no-start-idle-run'
1029
+ : undefined;
843
1030
  const capped = options.runtimeDriven && options.consultRunCap
844
1031
  ? !(await options.consultRunCap())
845
1032
  : false;
846
1033
  if (refusal || capped) {
1034
+ // The one place a drain can lose a signal, and it is the CALLER'S choice,
1035
+ // not the fence's. `execution-draining` degrades a wake into a persist so
1036
+ // nothing is lost while a deployment finishes its work — but a caller who
1037
+ // said persistence is forbidden has already declared it does not want its
1038
+ // signal parked, and honouring the fence by parking it anyway would
1039
+ // override an authorization decision with an operational one. So it is
1040
+ // discarded, deliberately, and the response SAYS SO: `wakeRefused:
1041
+ // 'execution-draining'` alongside `action: 'discard'` tells the caller
1042
+ // exactly which condition dropped it, so a sender that would rather wait
1043
+ // out the migration can retry instead of assuming delivery.
847
1044
  if (!options.persistenceAllowed) {
848
1045
  return persistenceForbiddenResponse({
849
1046
  capped,
@@ -961,6 +1158,8 @@ async function handleScheduleSignal(options) {
961
1158
  const receipt = createScheduleAgentDispatchReceipt('discard', {
962
1159
  signalId: dispatchId,
963
1160
  });
1161
+ await options.proof?.check();
1162
+ options.proof?.assertActive();
964
1163
  options.completed.set(dispatchId, receipt);
965
1164
  await options.store.settle(scheduleId, dispatchId, receipt);
966
1165
  options.completed.delete(dispatchId);
@@ -968,10 +1167,14 @@ async function handleScheduleSignal(options) {
968
1167
  };
969
1168
  const completed = options.completed.get(dispatchId);
970
1169
  if (completed) {
1170
+ await options.proof?.check();
1171
+ options.proof?.assertActive();
971
1172
  await options.store.settle(scheduleId, dispatchId, completed);
972
1173
  options.completed.delete(dispatchId);
973
1174
  return json({ receipt: completed });
974
1175
  }
1176
+ await options.proof?.check();
1177
+ options.proof?.assertActive();
975
1178
  const state = await options.store.begin(scheduleId, dispatchId);
976
1179
  if (state.state === 'missing') {
977
1180
  return json({ error: 'schedule dispatch not found' }, 404);
@@ -994,6 +1197,8 @@ async function handleScheduleSignal(options) {
994
1197
  runId: recoveredRun.runId,
995
1198
  signalId: dispatchId,
996
1199
  };
1200
+ await options.proof?.check();
1201
+ options.proof?.assertActive();
997
1202
  options.completed.set(dispatchId, receipt);
998
1203
  await options.store.settle(scheduleId, dispatchId, receipt);
999
1204
  options.completed.delete(dispatchId);
@@ -1008,6 +1213,8 @@ async function handleScheduleSignal(options) {
1008
1213
  runId: durableBlockingRun.runId,
1009
1214
  signalId: dispatchId,
1010
1215
  };
1216
+ await options.proof?.check();
1217
+ options.proof?.assertActive();
1011
1218
  options.completed.set(dispatchId, receipt);
1012
1219
  await options.store.settle(scheduleId, dispatchId, receipt);
1013
1220
  options.completed.delete(dispatchId);
@@ -1026,12 +1233,17 @@ async function handleScheduleSignal(options) {
1026
1233
  !renderableAttributes(target.ifIdle?.attributes)) {
1027
1234
  // The operator has to be able to find the broken schedule; the offending
1028
1235
  // name itself stays out of the log.
1029
- console.error(JSON.stringify({
1030
- type: 'schedule-target-unrenderable',
1031
- scheduleId,
1032
- dispatchId,
1033
- agentId: target.agentId,
1034
- }));
1236
+ try {
1237
+ console.error(JSON.stringify({
1238
+ type: 'schedule-target-unrenderable',
1239
+ scheduleId,
1240
+ dispatchId,
1241
+ agentId: target.agentId,
1242
+ }));
1243
+ }
1244
+ catch {
1245
+ // Diagnostics cannot prevent terminal settlement.
1246
+ }
1035
1247
  return await settleDiscard();
1036
1248
  }
1037
1249
  const baseProviderOptions = target.providerOptions ?? {};
@@ -1154,6 +1366,8 @@ async function handleScheduleSignal(options) {
1154
1366
  consultRunCap: options.consultRunCap,
1155
1367
  startIdleRun: options.startIdleRun,
1156
1368
  serializeWake: options.serializeWake,
1369
+ executionFence: options.executionFence,
1370
+ proof: options.proof,
1157
1371
  blockingRun: durableBlockingRun
1158
1372
  ? () => durableBlockingRun
1159
1373
  : options.blockingRun,
@@ -1189,6 +1403,8 @@ async function handleScheduleSignal(options) {
1189
1403
  typeof payload.signalId === 'string' ? payload.signalId : undefined;
1190
1404
  }
1191
1405
  else {
1406
+ await options.proof?.check();
1407
+ options.proof?.assertActive();
1192
1408
  const sent = options.agent.sendSignal(deliverableSignal, signalTarget);
1193
1409
  decision = await sent.accepted;
1194
1410
  const action = recordValue(decision)?.action;
@@ -1208,6 +1424,8 @@ async function handleScheduleSignal(options) {
1208
1424
  if (!receipt) {
1209
1425
  throw new Error('agent schedule returned an invalid signal decision');
1210
1426
  }
1427
+ await options.proof?.check();
1428
+ options.proof?.assertActive();
1211
1429
  options.completed.set(dispatchId, receipt);
1212
1430
  await options.store.settle(scheduleId, dispatchId, receipt);
1213
1431
  options.completed.delete(dispatchId);
@@ -1260,6 +1478,8 @@ async function handleMessage(agent, body, threadId, resourceId, consultRunCap, d
1260
1478
  consultRunCap,
1261
1479
  startIdleRun,
1262
1480
  serializeWake,
1481
+ executionFence: options.executionFence,
1482
+ proof: options.proof,
1263
1483
  blockingRun: durableBlockingRun
1264
1484
  ? () => durableBlockingRun
1265
1485
  : options.blockingRun,
@@ -1290,6 +1510,8 @@ async function handleMessage(agent, body, threadId, resourceId, consultRunCap, d
1290
1510
  return persistenceForbiddenResponse({ capped: false });
1291
1511
  }
1292
1512
  const memoryAvailable = await options.memoryAvailable();
1513
+ await options.proof?.check();
1514
+ options.proof?.assertActive();
1293
1515
  const result = agent.sendMessage(message, {
1294
1516
  threadId,
1295
1517
  resourceId,
@@ -1333,6 +1555,8 @@ async function handleQueue(agent, body, threadId, resourceId, options) {
1333
1555
  return policyRefusal;
1334
1556
  if (!(await options.memoryAvailable()))
1335
1557
  return memoryUnavailableResponse();
1558
+ await options.proof?.check();
1559
+ options.proof?.assertActive();
1336
1560
  const result = agent.sendMessage(message, {
1337
1561
  threadId,
1338
1562
  resourceId,
@@ -1348,7 +1572,7 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
1348
1572
  if (!isContents(body.contents)) {
1349
1573
  return json({ error: 'contents (string) is required' }, 400);
1350
1574
  }
1351
- // Route-level tagName defense (C-S5): reject a non-XML-name tagName HERE with a
1575
+ // Route-level tagName defense: reject a non-XML-name tagName HERE with a
1352
1576
  // 400, rather than letting core's signalToXmlMarkup throw at render time inside
1353
1577
  // the agent turn. Core still escapes contents/attribute values and re-validates
1354
1578
  // names; this is the ingest-time half the plan calls "route-level defense".
@@ -1387,6 +1611,8 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
1387
1611
  if (!isPathSafeId(runId)) {
1388
1612
  throw new Error('thread signal generated a non-path-safe run id');
1389
1613
  }
1614
+ await options.proof?.check();
1615
+ options.proof?.assertActive();
1390
1616
  const result = agent.sendSignal(signal, {
1391
1617
  threadId,
1392
1618
  runId,
@@ -1408,6 +1634,8 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
1408
1634
  consultRunCap,
1409
1635
  startIdleRun,
1410
1636
  serializeWake,
1637
+ executionFence: options.executionFence,
1638
+ proof: options.proof,
1411
1639
  blockingRun: durableBlockingRun
1412
1640
  ? () => durableBlockingRun
1413
1641
  : options.blockingRun,
@@ -1439,6 +1667,8 @@ async function handleSignal(agent, body, threadId, resourceId, consultRunCap, de
1439
1667
  }
1440
1668
  const memoryAvailable = await options.memoryAvailable();
1441
1669
  const wasActive = activeThreadRunIdOf(agent, threadId, resourceId) !== undefined;
1670
+ await options.proof?.check();
1671
+ options.proof?.assertActive();
1442
1672
  const result = agent.sendSignal(signal, {
1443
1673
  threadId,
1444
1674
  resourceId,
@@ -1512,6 +1742,8 @@ async function handleState(agent, body, threadId, resourceId, options) {
1512
1742
  return policyRefusal;
1513
1743
  if (!(await options.memoryAvailable()))
1514
1744
  return memoryUnavailableResponse();
1745
+ await options.proof?.check();
1746
+ options.proof?.assertActive();
1515
1747
  const result = await agent.sendStateSignal(state, {
1516
1748
  threadId,
1517
1749
  resourceId,
@@ -1579,6 +1811,17 @@ async function handleNotification(agent, body, threadId, resourceId, resolveNoti
1579
1811
  if (resourceId === undefined) {
1580
1812
  return json({ error: 'this thread has no resourceId wired; notifications need one' }, 409);
1581
1813
  }
1814
+ // Ingestion reaches core's patched functions below — the content-policy gate
1815
+ // renders a prospective summary through summarizeNotifications, and core's
1816
+ // inline sender resolves the configured source delivery policy — so the
1817
+ // refusal sits above the branches rather than beside a single reach. It
1818
+ // refuses the record-only branch as well, which a deployment that ingests
1819
+ // here and delegates dispatch elsewhere pays. The route's catch answers 502
1820
+ // with the message on the server log. Each subject has its own probe: the
1821
+ // synchronous call covers summarizeNotifications, and the awaited one covers
1822
+ // the source delivery policy lookup, which resolves asynchronously.
1823
+ assertNotificationSourceKeysPatched();
1824
+ await assertNotificationDeliveryPolicyPatched();
1582
1825
  // This gate is AUTHORITATIVE, not a preview: core can send an individual or
1583
1826
  // summary signal before the record reaches the dispatcher's second gate.
1584
1827
  // Storage owns the id, timestamps, and coalescing, so inspect a prospective
@@ -1620,6 +1863,8 @@ async function handleNotification(agent, body, threadId, resourceId, resolveNoti
1620
1863
  if (!storage) {
1621
1864
  return json({ error: 'notifications storage unavailable' }, 409);
1622
1865
  }
1866
+ await options.proof?.check();
1867
+ options.proof?.assertActive();
1623
1868
  const record = await storage.createNotification({
1624
1869
  ...notification,
1625
1870
  threadId,
@@ -1632,6 +1877,8 @@ async function handleNotification(agent, body, threadId, resourceId, resolveNoti
1632
1877
  delivery: { action: 'deferred', reason: 'dispatcher' },
1633
1878
  });
1634
1879
  }
1880
+ await options.proof?.check();
1881
+ options.proof?.assertActive();
1635
1882
  const result = await agent.sendNotificationSignal(notification, {
1636
1883
  threadId,
1637
1884
  resourceId,