@proofoftech/flowsafe 0.11.0 → 0.12.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 (384) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +65 -43
  3. package/deployment-identity-protocol.d.mts +52 -0
  4. package/deployment-identity-protocol.mjs +231 -0
  5. package/dist/agent-host/approval-resumer.d.ts +3 -3
  6. package/dist/agent-host/approval-resumer.d.ts.map +1 -1
  7. package/dist/agent-host/approval-resumer.js +6 -7
  8. package/dist/agent-host/approval-resumer.js.map +1 -1
  9. package/dist/agent-host/catalog.js +2 -2
  10. package/dist/agent-host/catalog.js.map +1 -1
  11. package/dist/agent-host/index.d.ts +2 -2
  12. package/dist/agent-host/index.d.ts.map +1 -1
  13. package/dist/agent-host/index.js.map +1 -1
  14. package/dist/agent-host/router.d.ts +2 -2
  15. package/dist/agent-host/router.d.ts.map +1 -1
  16. package/dist/agent-host/router.js +22 -54
  17. package/dist/agent-host/router.js.map +1 -1
  18. package/dist/agent-host/thread-host.d.ts +42 -8
  19. package/dist/agent-host/thread-host.d.ts.map +1 -1
  20. package/dist/agent-host/thread-host.js +533 -106
  21. package/dist/agent-host/thread-host.js.map +1 -1
  22. package/dist/agent-host/thread-topology.d.ts +28 -7
  23. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  24. package/dist/agent-host/thread-topology.js +97 -39
  25. package/dist/agent-host/thread-topology.js.map +1 -1
  26. package/dist/agent-host/trusted-context.d.ts.map +1 -1
  27. package/dist/agent-host/trusted-context.js +3 -1
  28. package/dist/agent-host/trusted-context.js.map +1 -1
  29. package/dist/agent-host/types.d.ts +2 -0
  30. package/dist/agent-host/types.d.ts.map +1 -1
  31. package/dist/agent-runner/agent-run-state.d.ts +9 -8
  32. package/dist/agent-runner/agent-run-state.d.ts.map +1 -1
  33. package/dist/agent-runner/agent-run-state.js +78 -40
  34. package/dist/agent-runner/agent-run-state.js.map +1 -1
  35. package/dist/agent-runner/durable-agent-runner.d.ts +18 -16
  36. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  37. package/dist/agent-runner/durable-agent-runner.js +120 -43
  38. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  39. package/dist/agent-runner/index.d.ts +1 -1
  40. package/dist/agent-runner/index.d.ts.map +1 -1
  41. package/dist/agent-runner/index.js +1 -1
  42. package/dist/agent-runner/index.js.map +1 -1
  43. package/dist/approval-api/actor-context.d.ts +67 -0
  44. package/dist/approval-api/actor-context.d.ts.map +1 -0
  45. package/dist/approval-api/actor-context.js +120 -0
  46. package/dist/approval-api/actor-context.js.map +1 -0
  47. package/dist/approval-api/contract.d.ts +12 -23
  48. package/dist/approval-api/contract.d.ts.map +1 -1
  49. package/dist/approval-api/d1-store.d.ts +7 -15
  50. package/dist/approval-api/d1-store.d.ts.map +1 -1
  51. package/dist/approval-api/d1-store.js +83 -159
  52. package/dist/approval-api/d1-store.js.map +1 -1
  53. package/dist/approval-api/grants.d.ts +3 -17
  54. package/dist/approval-api/grants.d.ts.map +1 -1
  55. package/dist/approval-api/grants.js +19 -39
  56. package/dist/approval-api/grants.js.map +1 -1
  57. package/dist/approval-api/index.d.ts +8 -8
  58. package/dist/approval-api/index.d.ts.map +1 -1
  59. package/dist/approval-api/index.js +5 -5
  60. package/dist/approval-api/index.js.map +1 -1
  61. package/dist/approval-api/principal.d.ts +29 -30
  62. package/dist/approval-api/principal.d.ts.map +1 -1
  63. package/dist/approval-api/principal.js +73 -54
  64. package/dist/approval-api/principal.js.map +1 -1
  65. package/dist/approval-api/resource-ownership.d.ts +64 -0
  66. package/dist/approval-api/resource-ownership.d.ts.map +1 -0
  67. package/dist/approval-api/resource-ownership.js +329 -0
  68. package/dist/approval-api/resource-ownership.js.map +1 -0
  69. package/dist/approval-api/retention.d.ts +6 -11
  70. package/dist/approval-api/retention.d.ts.map +1 -1
  71. package/dist/approval-api/retention.js +7 -12
  72. package/dist/approval-api/retention.js.map +1 -1
  73. package/dist/approval-api/router.d.ts +9 -8
  74. package/dist/approval-api/router.d.ts.map +1 -1
  75. package/dist/approval-api/router.js +50 -18
  76. package/dist/approval-api/router.js.map +1 -1
  77. package/dist/approval-api/service.d.ts +26 -36
  78. package/dist/approval-api/service.d.ts.map +1 -1
  79. package/dist/approval-api/service.js +104 -166
  80. package/dist/approval-api/service.js.map +1 -1
  81. package/dist/approval-api/store-factory.d.ts +19 -0
  82. package/dist/approval-api/store-factory.d.ts.map +1 -0
  83. package/dist/approval-api/store-factory.js +49 -0
  84. package/dist/approval-api/store-factory.js.map +1 -0
  85. package/dist/approval-api/store.d.ts +22 -36
  86. package/dist/approval-api/store.d.ts.map +1 -1
  87. package/dist/approval-api/store.js +48 -66
  88. package/dist/approval-api/store.js.map +1 -1
  89. package/dist/approval-api/types.d.ts +28 -22
  90. package/dist/approval-api/types.d.ts.map +1 -1
  91. package/dist/approval-api/types.js +51 -3
  92. package/dist/approval-api/types.js.map +1 -1
  93. package/dist/approval-ui/client.js +3 -3
  94. package/dist/approval-ui/client.js.map +1 -1
  95. package/dist/approval-ui/stream.d.ts +4 -4
  96. package/dist/approval-ui/stream.d.ts.map +1 -1
  97. package/dist/approval-ui/stream.js +2 -2
  98. package/dist/approval-ui/tips.d.ts +1 -1
  99. package/dist/approval-ui/tips.js +1 -1
  100. package/dist/approval-ui/tips.js.map +1 -1
  101. package/dist/approval-ui/use-approval-dashboard.d.ts +3 -3
  102. package/dist/approval-ui/use-approval-dashboard.js +1 -1
  103. package/dist/artifacts/index.d.ts +2 -3
  104. package/dist/artifacts/index.d.ts.map +1 -1
  105. package/dist/artifacts/index.js +9 -8
  106. package/dist/artifacts/index.js.map +1 -1
  107. package/dist/audit-export/audit-proxy.d.ts +71 -0
  108. package/dist/audit-export/audit-proxy.d.ts.map +1 -0
  109. package/dist/audit-export/audit-proxy.js +142 -0
  110. package/dist/audit-export/audit-proxy.js.map +1 -0
  111. package/dist/audit-export/index.d.ts +4 -7
  112. package/dist/audit-export/index.d.ts.map +1 -1
  113. package/dist/audit-export/index.js +1 -4
  114. package/dist/audit-export/index.js.map +1 -1
  115. package/dist/audit-export/queue-types.d.ts +5 -0
  116. package/dist/audit-export/queue-types.d.ts.map +1 -0
  117. package/dist/audit-export/queue-types.js +3 -0
  118. package/dist/audit-export/queue-types.js.map +1 -0
  119. package/dist/background-tasks/d1-storage.d.ts +9 -19
  120. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  121. package/dist/background-tasks/d1-storage.js +22 -52
  122. package/dist/background-tasks/d1-storage.js.map +1 -1
  123. package/dist/background-tasks/host.d.ts +4 -6
  124. package/dist/background-tasks/host.d.ts.map +1 -1
  125. package/dist/background-tasks/host.js +14 -17
  126. package/dist/background-tasks/host.js.map +1 -1
  127. package/dist/background-tasks/index.d.ts +1 -1
  128. package/dist/background-tasks/index.d.ts.map +1 -1
  129. package/dist/background-tasks/index.js +3 -3
  130. package/dist/background-tasks/index.js.map +1 -1
  131. package/dist/background-tasks/routes.d.ts +8 -4
  132. package/dist/background-tasks/routes.d.ts.map +1 -1
  133. package/dist/background-tasks/routes.js +33 -31
  134. package/dist/background-tasks/routes.js.map +1 -1
  135. package/dist/deployment-identity-protocol.d.ts +3 -0
  136. package/dist/deployment-identity-protocol.d.ts.map +1 -0
  137. package/dist/deployment-identity-protocol.js +3 -0
  138. package/dist/deployment-identity-protocol.js.map +1 -0
  139. package/dist/do-runner/breakwater-keys.d.ts +7 -5
  140. package/dist/do-runner/breakwater-keys.d.ts.map +1 -1
  141. package/dist/do-runner/breakwater-keys.js +7 -5
  142. package/dist/do-runner/breakwater-keys.js.map +1 -1
  143. package/dist/do-runner/cf-types.d.ts +18 -12
  144. package/dist/do-runner/cf-types.d.ts.map +1 -1
  145. package/dist/do-runner/cf-types.js.map +1 -1
  146. package/dist/do-runner/d1-storage.d.ts +44 -182
  147. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  148. package/dist/do-runner/d1-storage.js +102 -353
  149. package/dist/do-runner/d1-storage.js.map +1 -1
  150. package/dist/do-runner/deployment-identity.d.ts +121 -0
  151. package/dist/do-runner/deployment-identity.d.ts.map +1 -0
  152. package/dist/do-runner/deployment-identity.js +272 -0
  153. package/dist/do-runner/deployment-identity.js.map +1 -0
  154. package/dist/do-runner/do-error-response.d.ts +1 -1
  155. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  156. package/dist/do-runner/do-error-response.js +7 -1
  157. package/dist/do-runner/do-error-response.js.map +1 -1
  158. package/dist/do-runner/durable-object.d.ts +23 -16
  159. package/dist/do-runner/durable-object.d.ts.map +1 -1
  160. package/dist/do-runner/durable-object.js +303 -70
  161. package/dist/do-runner/durable-object.js.map +1 -1
  162. package/dist/do-runner/execution-context.d.ts +1 -0
  163. package/dist/do-runner/execution-context.d.ts.map +1 -1
  164. package/dist/do-runner/execution-context.js +4 -7
  165. package/dist/do-runner/execution-context.js.map +1 -1
  166. package/dist/do-runner/execution-principal-header.d.ts +16 -0
  167. package/dist/do-runner/execution-principal-header.d.ts.map +1 -0
  168. package/dist/do-runner/execution-principal-header.js +20 -0
  169. package/dist/do-runner/execution-principal-header.js.map +1 -0
  170. package/dist/do-runner/hub-do.d.ts +17 -25
  171. package/dist/do-runner/hub-do.d.ts.map +1 -1
  172. package/dist/do-runner/hub-do.js +63 -59
  173. package/dist/do-runner/hub-do.js.map +1 -1
  174. package/dist/do-runner/index.d.ts +12 -10
  175. package/dist/do-runner/index.d.ts.map +1 -1
  176. package/dist/do-runner/index.js +10 -9
  177. package/dist/do-runner/index.js.map +1 -1
  178. package/dist/do-runner/init.d.ts +0 -7
  179. package/dist/do-runner/init.d.ts.map +1 -1
  180. package/dist/do-runner/init.js +1 -2
  181. package/dist/do-runner/init.js.map +1 -1
  182. package/dist/do-runner/memory-id.d.ts +8 -25
  183. package/dist/do-runner/memory-id.d.ts.map +1 -1
  184. package/dist/do-runner/memory-id.js +25 -52
  185. package/dist/do-runner/memory-id.js.map +1 -1
  186. package/dist/do-runner/path-safe-id.d.ts +2 -48
  187. package/dist/do-runner/path-safe-id.d.ts.map +1 -1
  188. package/dist/do-runner/path-safe-id.js +3 -93
  189. package/dist/do-runner/path-safe-id.js.map +1 -1
  190. package/dist/do-runner/pubsub.d.ts +1 -1
  191. package/dist/do-runner/pubsub.js +1 -1
  192. package/dist/do-runner/runtime.d.ts +47 -34
  193. package/dist/do-runner/runtime.d.ts.map +1 -1
  194. package/dist/do-runner/runtime.js +281 -143
  195. package/dist/do-runner/runtime.js.map +1 -1
  196. package/dist/do-runner/schedule-source.d.ts +81 -0
  197. package/dist/do-runner/schedule-source.d.ts.map +1 -0
  198. package/dist/do-runner/schedule-source.js +64 -0
  199. package/dist/do-runner/schedule-source.js.map +1 -0
  200. package/dist/do-runner/thread-do.d.ts +18 -32
  201. package/dist/do-runner/thread-do.d.ts.map +1 -1
  202. package/dist/do-runner/thread-do.js +52 -74
  203. package/dist/do-runner/thread-do.js.map +1 -1
  204. package/dist/goals/objective-routes.d.ts +7 -4
  205. package/dist/goals/objective-routes.d.ts.map +1 -1
  206. package/dist/goals/objective-routes.js +58 -43
  207. package/dist/goals/objective-routes.js.map +1 -1
  208. package/dist/host-kit/approval-bridge.d.ts +18 -21
  209. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  210. package/dist/host-kit/approval-bridge.js +37 -37
  211. package/dist/host-kit/approval-bridge.js.map +1 -1
  212. package/dist/host-kit/bearer-auth.d.ts +3 -4
  213. package/dist/host-kit/bearer-auth.d.ts.map +1 -1
  214. package/dist/host-kit/bearer-auth.js +7 -11
  215. package/dist/host-kit/bearer-auth.js.map +1 -1
  216. package/dist/host-kit/do-run-topology.d.ts +14 -5
  217. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  218. package/dist/host-kit/do-run-topology.js +47 -15
  219. package/dist/host-kit/do-run-topology.js.map +1 -1
  220. package/dist/host-kit/env-vars.d.ts +1 -1
  221. package/dist/host-kit/env-vars.js +1 -1
  222. package/dist/host-kit/flowsafe-worker.d.ts +149 -73
  223. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  224. package/dist/host-kit/flowsafe-worker.js +619 -141
  225. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  226. package/dist/host-kit/host-approval-service.d.ts +62 -54
  227. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  228. package/dist/host-kit/host-approval-service.js +90 -61
  229. package/dist/host-kit/host-approval-service.js.map +1 -1
  230. package/dist/host-kit/hub-topology.d.ts +6 -7
  231. package/dist/host-kit/hub-topology.d.ts.map +1 -1
  232. package/dist/host-kit/hub-topology.js +16 -12
  233. package/dist/host-kit/hub-topology.js.map +1 -1
  234. package/dist/host-kit/index.d.ts +13 -11
  235. package/dist/host-kit/index.d.ts.map +1 -1
  236. package/dist/host-kit/index.js +9 -12
  237. package/dist/host-kit/index.js.map +1 -1
  238. package/dist/host-kit/maintenance-capability.d.ts +58 -0
  239. package/dist/host-kit/maintenance-capability.d.ts.map +1 -0
  240. package/dist/host-kit/maintenance-capability.js +268 -0
  241. package/dist/host-kit/maintenance-capability.js.map +1 -0
  242. package/dist/host-kit/memory-boundary.d.ts +4 -19
  243. package/dist/host-kit/memory-boundary.d.ts.map +1 -1
  244. package/dist/host-kit/memory-boundary.js +12 -27
  245. package/dist/host-kit/memory-boundary.js.map +1 -1
  246. package/dist/host-kit/resource-access.d.ts +4 -0
  247. package/dist/host-kit/resource-access.d.ts.map +1 -0
  248. package/dist/host-kit/resource-access.js +12 -0
  249. package/dist/host-kit/resource-access.js.map +1 -0
  250. package/dist/host-kit/run-router.d.ts +25 -15
  251. package/dist/host-kit/run-router.d.ts.map +1 -1
  252. package/dist/host-kit/run-router.js +61 -46
  253. package/dist/host-kit/run-router.js.map +1 -1
  254. package/dist/host-kit/state-egress.d.ts +51 -0
  255. package/dist/host-kit/state-egress.d.ts.map +1 -0
  256. package/dist/host-kit/state-egress.js +120 -0
  257. package/dist/host-kit/state-egress.js.map +1 -0
  258. package/dist/host-kit/stream-router.d.ts +9 -4
  259. package/dist/host-kit/stream-router.d.ts.map +1 -1
  260. package/dist/host-kit/stream-router.js +45 -38
  261. package/dist/host-kit/stream-router.js.map +1 -1
  262. package/dist/host-kit/stream-ticket.d.ts +10 -10
  263. package/dist/host-kit/stream-ticket.d.ts.map +1 -1
  264. package/dist/host-kit/stream-ticket.js +60 -90
  265. package/dist/host-kit/stream-ticket.js.map +1 -1
  266. package/dist/host-kit/thread-topology.d.ts +17 -11
  267. package/dist/host-kit/thread-topology.d.ts.map +1 -1
  268. package/dist/host-kit/thread-topology.js +33 -59
  269. package/dist/host-kit/thread-topology.js.map +1 -1
  270. package/dist/host-kit/verifier.d.ts +6 -6
  271. package/dist/host-kit/verifier.d.ts.map +1 -1
  272. package/dist/host-kit/verifier.js +51 -119
  273. package/dist/host-kit/verifier.js.map +1 -1
  274. package/dist/http-body.d.ts +20 -0
  275. package/dist/http-body.d.ts.map +1 -0
  276. package/dist/http-body.js +67 -0
  277. package/dist/http-body.js.map +1 -0
  278. package/dist/schedules/index.d.ts +3 -2
  279. package/dist/schedules/index.d.ts.map +1 -1
  280. package/dist/schedules/index.js +5 -4
  281. package/dist/schedules/index.js.map +1 -1
  282. package/dist/schedules/router.d.ts +16 -10
  283. package/dist/schedules/router.d.ts.map +1 -1
  284. package/dist/schedules/router.js +153 -91
  285. package/dist/schedules/router.js.map +1 -1
  286. package/dist/schedules/schedules-d1.d.ts +88 -0
  287. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  288. package/dist/schedules/schedules-d1.js +411 -50
  289. package/dist/schedules/schedules-d1.js.map +1 -1
  290. package/dist/schedules/target-policy.d.ts +29 -0
  291. package/dist/schedules/target-policy.d.ts.map +1 -0
  292. package/dist/schedules/target-policy.js +70 -0
  293. package/dist/schedules/target-policy.js.map +1 -0
  294. package/dist/schedules/tick.d.ts +125 -21
  295. package/dist/schedules/tick.d.ts.map +1 -1
  296. package/dist/schedules/tick.js +637 -160
  297. package/dist/schedules/tick.js.map +1 -1
  298. package/dist/signal-providers/delivery.d.ts +0 -19
  299. package/dist/signal-providers/delivery.d.ts.map +1 -1
  300. package/dist/signal-providers/delivery.js +5 -54
  301. package/dist/signal-providers/delivery.js.map +1 -1
  302. package/dist/signal-providers/github-provider.d.ts.map +1 -1
  303. package/dist/signal-providers/github-provider.js +9 -16
  304. package/dist/signal-providers/github-provider.js.map +1 -1
  305. package/dist/signal-providers/host-do.d.ts +3 -45
  306. package/dist/signal-providers/host-do.d.ts.map +1 -1
  307. package/dist/signal-providers/host-do.js +86 -106
  308. package/dist/signal-providers/host-do.js.map +1 -1
  309. package/dist/signal-providers/host-topology.d.ts +5 -14
  310. package/dist/signal-providers/host-topology.d.ts.map +1 -1
  311. package/dist/signal-providers/host-topology.js +11 -25
  312. package/dist/signal-providers/host-topology.js.map +1 -1
  313. package/dist/signal-providers/index.d.ts +3 -3
  314. package/dist/signal-providers/index.d.ts.map +1 -1
  315. package/dist/signal-providers/index.js +3 -3
  316. package/dist/signal-providers/index.js.map +1 -1
  317. package/dist/signal-providers/provider.d.ts +4 -5
  318. package/dist/signal-providers/provider.d.ts.map +1 -1
  319. package/dist/signal-providers/provider.js +5 -6
  320. package/dist/signal-providers/provider.js.map +1 -1
  321. package/dist/signal-providers/subscription-d1.d.ts +10 -57
  322. package/dist/signal-providers/subscription-d1.d.ts.map +1 -1
  323. package/dist/signal-providers/subscription-d1.js +208 -155
  324. package/dist/signal-providers/subscription-d1.js.map +1 -1
  325. package/dist/signal-providers/webhook-route.d.ts +28 -14
  326. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  327. package/dist/signal-providers/webhook-route.js +117 -88
  328. package/dist/signal-providers/webhook-route.js.map +1 -1
  329. package/dist/signals/client.js +8 -8
  330. package/dist/signals/client.js.map +1 -1
  331. package/dist/signals/d1-shared.js +1 -1
  332. package/dist/signals/d1-shared.js.map +1 -1
  333. package/dist/signals/index.d.ts +1 -1
  334. package/dist/signals/index.d.ts.map +1 -1
  335. package/dist/signals/index.js.map +1 -1
  336. package/dist/signals/notification-dispatch.d.ts +12 -6
  337. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  338. package/dist/signals/notification-dispatch.js +37 -21
  339. package/dist/signals/notification-dispatch.js.map +1 -1
  340. package/dist/signals/notifications-d1.d.ts +5 -8
  341. package/dist/signals/notifications-d1.d.ts.map +1 -1
  342. package/dist/signals/notifications-d1.js +8 -13
  343. package/dist/signals/notifications-d1.js.map +1 -1
  344. package/dist/signals/router.d.ts +10 -10
  345. package/dist/signals/router.d.ts.map +1 -1
  346. package/dist/signals/router.js +49 -51
  347. package/dist/signals/router.js.map +1 -1
  348. package/dist/signals/thread-do-routes.d.ts +74 -15
  349. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  350. package/dist/signals/thread-do-routes.js +484 -41
  351. package/dist/signals/thread-do-routes.js.map +1 -1
  352. package/dist/signals/thread-state-d1.d.ts.map +1 -1
  353. package/dist/signals/thread-state-d1.js +2 -3
  354. package/dist/signals/thread-state-d1.js.map +1 -1
  355. package/package.json +29 -6
  356. package/scripts/seed-deployment-identity.mjs +252 -0
  357. package/dist/approval-api/tenant-brand.d.ts +0 -35
  358. package/dist/approval-api/tenant-brand.d.ts.map +0 -1
  359. package/dist/approval-api/tenant-brand.js +0 -19
  360. package/dist/approval-api/tenant-brand.js.map +0 -1
  361. package/dist/approval-api/tenant-context.d.ts +0 -84
  362. package/dist/approval-api/tenant-context.d.ts.map +0 -1
  363. package/dist/approval-api/tenant-context.js +0 -112
  364. package/dist/approval-api/tenant-context.js.map +0 -1
  365. package/dist/approval-api/tenant-store.d.ts +0 -36
  366. package/dist/approval-api/tenant-store.d.ts.map +0 -1
  367. package/dist/approval-api/tenant-store.js +0 -129
  368. package/dist/approval-api/tenant-store.js.map +0 -1
  369. package/dist/do-runner/resume-ledger.d.ts +0 -48
  370. package/dist/do-runner/resume-ledger.d.ts.map +0 -1
  371. package/dist/do-runner/resume-ledger.js +0 -60
  372. package/dist/do-runner/resume-ledger.js.map +0 -1
  373. package/dist/do-runner/thread-header.d.ts +0 -31
  374. package/dist/do-runner/thread-header.d.ts.map +0 -1
  375. package/dist/do-runner/thread-header.js +0 -39
  376. package/dist/do-runner/thread-header.js.map +0 -1
  377. package/dist/host-kit/subdomain-check.d.ts +0 -23
  378. package/dist/host-kit/subdomain-check.d.ts.map +0 -1
  379. package/dist/host-kit/subdomain-check.js +0 -61
  380. package/dist/host-kit/subdomain-check.js.map +0 -1
  381. package/dist/host-kit/tenant-registry.d.ts +0 -51
  382. package/dist/host-kit/tenant-registry.d.ts.map +0 -1
  383. package/dist/host-kit/tenant-registry.js +0 -88
  384. package/dist/host-kit/tenant-registry.js.map +0 -1
@@ -6,7 +6,6 @@
6
6
  // to `new Mastra({ storage })` — no migration step needed for the runner.
7
7
  import { D1Store } from '@mastra/cloudflare-d1';
8
8
  import { MastraCompositeStore, } from '@mastra/core/storage';
9
- import { TENANT_ID_PATTERN } from './path-safe-id.js';
10
9
  export function createD1Storage(options) {
11
10
  const d1 = new D1Store({
12
11
  id: options.id ?? 'flowsafe',
@@ -47,12 +46,9 @@ const TERMINAL_STATUSES = [
47
46
  /**
48
47
  * The tables `purgeExpiredWorkflowRuns` deletes from under the run TTL — the
49
48
  * production anchor the schema guard cross-checks every `run-ttl` retention
50
- * declaration against, the retention counterpart of
51
- * TENANT_RANGE_PURGE_TABLES for the offboarding leg. One table, because the run
52
- * TTL rides a `run_id` range paired with artifact deletion and an app-owned
53
- * index (its own block below), not the tenant-range map. The guard reads THIS,
54
- * not a literal copied into the test, so a purge that changes what it targets
55
- * and a guard that still blesses the old set cannot drift apart silently.
49
+ * declaration against. The guard reads THIS, not a literal copied into the
50
+ * test, so a purge that changes what it targets and a guard that still
51
+ * blesses the old set cannot drift apart silently.
56
52
  */
57
53
  export const RUN_TTL_PURGE_TABLES = [
58
54
  'mastra_workflow_snapshot',
@@ -65,8 +61,8 @@ export const RUN_TTL_PURGE_TABLES = [
65
61
  * pending/paused) are never touched — expiring a suspended run would kill a
66
62
  * pending approval. A missing snapshot table reads as zero purgeable runs
67
63
  * (Mastra creates it lazily with the first persisted run). TTL enforcement
68
- * is a storage-layer property, so it lives here; scheduling (Worker cron /
69
- * DO alarm) stays with the caller. Returns the number of deleted rows.
64
+ * is a storage-layer property, so it lives here; alarm scheduling stays with
65
+ * the caller. Returns the number of deleted rows.
70
66
  */
71
67
  export async function purgeExpiredWorkflowRuns(db, options) {
72
68
  const now = options.now ?? Date.now;
@@ -88,6 +84,15 @@ export async function purgeExpiredWorkflowRuns(db, options) {
88
84
  WHEN json_valid(snapshot)
89
85
  THEN json_extract(snapshot, '$.status')
90
86
  END IN (${placeholders})`;
87
+ const resourceOwnerTable = options.resourceOwnerTable;
88
+ if (resourceOwnerTable !== undefined &&
89
+ !/^[A-Za-z_][A-Za-z0-9_]*$/.test(resourceOwnerTable)) {
90
+ throw new Error('resourceOwnerTable must be a safe SQL identifier');
91
+ }
92
+ const batch = resourceOwnerTable ? db.batch?.bind(db) : undefined;
93
+ if (resourceOwnerTable && !batch) {
94
+ throw new Error('purgeExpiredWorkflowRuns requires database.batch() for atomic owner cleanup');
95
+ }
91
96
  if (options.artifactStore) {
92
97
  // Artifact-paired path, run by run: artifacts BEFORE the row, because
93
98
  // the row is the only record of the run's artifact keys — dying between
@@ -107,7 +112,7 @@ export async function purgeExpiredWorkflowRuns(db, options) {
107
112
  .all());
108
113
  }
109
114
  catch (error) {
110
- if (!isMissingTable(error))
115
+ if (!isMissingTable(error, `${prefix}mastra_workflow_snapshot`))
111
116
  throw error;
112
117
  return 0;
113
118
  }
@@ -118,11 +123,11 @@ export async function purgeExpiredWorkflowRuns(db, options) {
118
123
  await options.artifactStore.deleteRun(row.workflow_name, row.run_id);
119
124
  }
120
125
  catch (error) {
121
- // Isolate per run, same as the demo-tenant reaper: aborting the
126
+ // Isolate per run: aborting the
122
127
  // loop would re-hit this run at the same scan position every firing
123
128
  // and stall every eligible row behind it forever. Its row survives
124
129
  // as its own retry cursor; the aggregate throw below keeps the
125
- // cron's error surface firing. A wedged run does occupy a batch
130
+ // purge duty's error surface firing. A wedged run does occupy a batch
126
131
  // slot until fixed, so isolation holds while wedged runs number
127
132
  // fewer than `limit`.
128
133
  failures.push({
@@ -133,11 +138,27 @@ export async function purgeExpiredWorkflowRuns(db, options) {
133
138
  }
134
139
  // Re-checking eligibility keys the delete to the row the SELECT saw;
135
140
  // terminal is absorbing, so this is belt-and-braces, not a race fix.
136
- deleted += d1Changes(await db
141
+ const deleteSnapshot = db
137
142
  .prepare(`DELETE FROM ${prefix}mastra_workflow_snapshot
138
- WHERE workflow_name = ? AND run_id = ? AND ${eligible}`)
139
- .bind(row.workflow_name, row.run_id, cutoff, ...TERMINAL_STATUSES)
140
- .run());
143
+ WHERE workflow_name = ? AND run_id = ? AND ${eligible}`)
144
+ .bind(row.workflow_name, row.run_id, cutoff, ...TERMINAL_STATUSES);
145
+ if (resourceOwnerTable && batch) {
146
+ const [result] = await batch([
147
+ deleteSnapshot,
148
+ db
149
+ .prepare(`DELETE FROM ${resourceOwnerTable}
150
+ WHERE resource_kind = 'run' AND resource_id = ?
151
+ AND NOT EXISTS (
152
+ SELECT 1 FROM ${prefix}mastra_workflow_snapshot
153
+ WHERE run_id = ?
154
+ )`)
155
+ .bind(row.run_id, row.run_id),
156
+ ]);
157
+ deleted += d1Changes(result);
158
+ }
159
+ else {
160
+ deleted += d1Changes(await deleteSnapshot.run());
161
+ }
141
162
  }
142
163
  if (failures.length > 0) {
143
164
  throw new Error(`purgeExpiredWorkflowRuns: artifact deletion failed for ${failures.length} of ${rows.length} eligible run(s), the rest were purged (${failures
@@ -151,9 +172,43 @@ export async function purgeExpiredWorkflowRuns(db, options) {
151
172
  // per firing whatever the batch size, hence the larger default). An
152
173
  // unbounded DELETE over a huge first backlog can exceed the per-query
153
174
  // limits and then fail the same way on EVERY firing — retention silently
154
- // unenforced, the exact wedge the cron split exists to avoid. The
175
+ // unenforced, the exact wedge the one-duty-per-alarm split exists to avoid. The
155
176
  // shrinking eligible set is the cursor: a backlog drains across firings.
156
177
  try {
178
+ if (resourceOwnerTable && batch) {
179
+ // D1 accepts at most 100 bound parameters per statement. Keep the exact
180
+ // rowid + owner-id transaction below under that limit even when a caller
181
+ // requests a larger generic purge batch.
182
+ const limit = Math.min(options.limit ?? 1000, 90);
183
+ const selected = await db
184
+ .prepare(`SELECT rowid, run_id
185
+ FROM ${prefix}mastra_workflow_snapshot
186
+ WHERE ${eligible}
187
+ LIMIT ?`)
188
+ .bind(cutoff, ...TERMINAL_STATUSES, limit)
189
+ .all();
190
+ if (selected.results.length === 0)
191
+ return 0;
192
+ const rowIds = selected.results.map((row) => row.rowid);
193
+ const runIds = [...new Set(selected.results.map((row) => row.run_id))];
194
+ const rowPlaceholders = rowIds.map(() => '?').join(', ');
195
+ const runPlaceholders = runIds.map(() => '?').join(', ');
196
+ const [result] = await batch([
197
+ db
198
+ .prepare(`DELETE FROM ${prefix}mastra_workflow_snapshot
199
+ WHERE rowid IN (${rowPlaceholders}) AND ${eligible}`)
200
+ .bind(...rowIds, cutoff, ...TERMINAL_STATUSES),
201
+ db
202
+ .prepare(`DELETE FROM ${resourceOwnerTable}
203
+ WHERE resource_kind = 'run'
204
+ AND resource_id IN (${runPlaceholders})
205
+ AND resource_id NOT IN (
206
+ SELECT run_id FROM ${prefix}mastra_workflow_snapshot
207
+ )`)
208
+ .bind(...runIds),
209
+ ]);
210
+ return d1Changes(result);
211
+ }
157
212
  return d1Changes(await db
158
213
  .prepare(`DELETE FROM ${prefix}mastra_workflow_snapshot
159
214
  WHERE rowid IN (
@@ -165,7 +220,7 @@ export async function purgeExpiredWorkflowRuns(db, options) {
165
220
  .run());
166
221
  }
167
222
  catch (error) {
168
- if (!isMissingTable(error))
223
+ if (!isMissingTable(error, `${prefix}mastra_workflow_snapshot`))
169
224
  throw error;
170
225
  return 0;
171
226
  }
@@ -199,7 +254,7 @@ export const THREAD_TTL_PURGE_TABLES = [
199
254
  'mastra_messages',
200
255
  ];
201
256
  /**
202
- * Thread-level retention (docs/agent-memory-tenancy.md item 7): deletes agent
257
+ * Thread-level retention (docs/agent-memory-isolation.md#thread-retention): deletes agent
203
258
  * memory threads whose `updatedAt` is older than the TTL, each with its
204
259
  * messages. The terminal-status shape `purgeExpiredWorkflowRuns` uses does not
205
260
  * transfer — threads are not per-run and have no status, so there is nothing to
@@ -211,7 +266,7 @@ export const THREAD_TTL_PURGE_TABLES = [
211
266
  * so there is no per-message IDLENESS signal — a message's lifetime is its
212
267
  * thread's, and its rows are reachable only through it. Deleting a thread first
213
268
  * would strand its messages beyond every later firing of this purge (only
214
- * purgeTenant, at offboarding, still ranges over their salted `thread_id`).
269
+ * decommissioning the deployment's database would still reap them).
215
270
  *
216
271
  * EVERY statement re-checks the CURRENT row rather than trusting the SELECT's id
217
272
  * list, and that is load-bearing here in a way it is not for
@@ -246,13 +301,12 @@ export const THREAD_TTL_PURGE_TABLES = [
246
301
  * milliseconds away. (2) A message inserted AFTER its thread's row is already
247
302
  * gone is orphaned by the writer, not by this purge; D1 offers no cross-statement
248
303
  * transaction through this seam to close it. An orphan is unreachable by recall
249
- * (nothing lists a thread that does not exist), stays tenant-salted on its
250
- * `thread_id`, and is reaped by purgeTenant at offboarding — a hygiene cost, not
251
- * a leak.
304
+ * (nothing lists a thread that does not exist) and vanishes with the
305
+ * deployment's database at decommission — a hygiene cost, not a leak.
252
306
  *
253
307
  * `mastra_resources` (working memory) is deliberately untouched: a resource is
254
308
  * the OWNER's, shared across every thread they have, so one thread aging out
255
- * says nothing about it. It is reaped at offboarding (purgeTenant).
309
+ * says nothing about it. It lives until the deployment is decommissioned.
256
310
  *
257
311
  * Missing tables read as zero (a deployment with no agent memory never created
258
312
  * them). Scheduling stays with the caller — see createFlowsafeWorker's
@@ -303,7 +357,7 @@ export async function purgeExpiredThreads(db, options) {
303
357
  catch (error) {
304
358
  // A host whose memory domain never initialized has threads but no
305
359
  // messages table; anything else is a real failure and must reach the
306
- // cron's error surface rather than silently orphan a thread's history.
360
+ // purge duty's error surface rather than silently orphan a thread's history.
307
361
  if (!isMissingTable(error))
308
362
  throw error;
309
363
  hasMessagesTable = false;
@@ -349,9 +403,9 @@ const BACKGROUND_TASK_FAILED_STATUSES = [
349
403
  * Background-task TTL cleanup: deletes terminal task
350
404
  * rows from `mastra_background_tasks` once their `completedAt` is older than the
351
405
  * TTL, mirroring core `BackgroundTaskManager.cleanup()` at the storage layer so
352
- * a purge cron can reap them WITHOUT a live manager — the same posture as
406
+ * a maintenance purge can reap them WITHOUT a live manager: the same posture as
353
407
  * purgeExpiredWorkflowRuns/purgeExpiredThreads (raw D1 binding, failure-isolated
354
- * as a cron duty). Two windows, exactly as core: completed rows expire fast
408
+ * as a purge duty). Two windows, exactly as core: completed rows expire fast
355
409
  * (default 1h), failed/cancelled/timed_out slowly (default 24h) so a failure
356
410
  * stays inspectable.
357
411
  *
@@ -372,7 +426,7 @@ export async function purgeExpiredBackgroundTasks(db, options = {}) {
372
426
  const failedPlaceholders = BACKGROUND_TASK_FAILED_STATUSES.map(() => '?').join(', ');
373
427
  try {
374
428
  // Internal evented-engine snapshots use the UNSALTED task id. Consume that
375
- // association before deleting the task rows that make tenant/retention
429
+ // association before deleting the task rows that make retention
376
430
  // ownership discoverable.
377
431
  try {
378
432
  await db
@@ -442,8 +496,8 @@ const NOTIFICATION_TERMINAL_STATUSES = [
442
496
  /**
443
497
  * Notification TTL cleanup: deletes terminal agent-inbox
444
498
  * rows from `mastra_notifications` once their `updatedAt` is older than the TTL,
445
- * at the storage layer so a cron reaps them without a live agent — the same
446
- * posture as the other purges (raw D1 binding, failure-isolated as a cron duty).
499
+ * at the storage layer so alarm maintenance reaps them without a live agent —
500
+ * the same posture as the other purges (raw D1 binding, failure-isolated duty).
447
501
  * `updatedAt` is ISO-8601 TEXT, so lexicographic `<` is a correct timestamp
448
502
  * comparison. A missing table reads as zero (notifications may never have been
449
503
  * sent). Scheduling stays with the caller.
@@ -480,9 +534,9 @@ export const THREAD_STATE_TTL_PURGE_TABLES = [
480
534
  * on `updatedAt` for the same reason `purgeExpiredThreads` does — thread state
481
535
  * has no terminal status, so time-since-last-write is the only "done" signal.
482
536
  * ISO-8601 TEXT encoding; missing table reads as zero; scheduling stays with the
483
- * caller. Independent of the thread TTL (an orphan row is reaped here or at
484
- * offboarding by purgeTenant), so it self-bounds without touching the delicate
485
- * messages-before-threads ordering of purgeExpiredThreads.
537
+ * caller. Independent of the thread TTL (an orphan row is reaped here or when
538
+ * the deployment is decommissioned), so it self-bounds without touching the
539
+ * delicate messages-before-threads ordering of purgeExpiredThreads.
486
540
  */
487
541
  export async function purgeExpiredThreadState(db, options) {
488
542
  const now = options.now ?? Date.now;
@@ -506,24 +560,26 @@ export async function purgeExpiredThreadState(db, options) {
506
560
  * declaration against. It is the schedule-trigger counterpart to
507
561
  * THREAD_STATE_TTL_PURGE_TABLES.
508
562
  * Only the trigger HISTORY expires; the schedule rows themselves are standing
509
- * config (retention 'none', reaped at offboarding by purgeTenant).
563
+ * config (retention 'none' — they live until deleted over the schedule
564
+ * surface or the deployment is decommissioned).
510
565
  */
511
566
  export const SCHEDULE_TRIGGER_TTL_PURGE_TABLES = [
512
567
  'mastra_schedule_triggers',
513
568
  ];
514
569
  /**
515
- * Schedule-trigger TTL cleanup: deletes trigger-history
570
+ * Schedule-trigger TTL cleanup: deletes terminal trigger-history
516
571
  * rows from `mastra_schedule_triggers` once their `actualFireAt` is older than the
517
- * TTL, at the storage layer so a cron reaps them without a live tick — the same
518
- * posture as the other purges (raw D1 binding, failure-isolated as a cron duty).
572
+ * TTL, at the storage layer so alarm maintenance reaps them without a live tick —
573
+ * the same posture as the other purges (raw D1 binding, failure-isolated duty).
519
574
  *
520
575
  * `actualFireAt` is stored as INTEGER ms-epoch (core types
521
576
  * `ScheduleTrigger.actualFireAt` as `number`, unlike the ISO-TEXT timestamp
522
577
  * columns the other domains use), so the comparison is a NUMERIC `<` against a
523
578
  * numeric cutoff — a correct timestamp comparison over integers. A missing table
524
579
  * reads as zero (schedules may never have fired). Scheduling stays with the
525
- * caller. Deleting trigger history never touches a live schedule (its own row is
526
- * in `mastra_schedules`), so there is no ordering constraint.
580
+ * caller. Deferred rows are live dispatch/reconciliation state and are never
581
+ * TTL-purged; their eventual settlement also finalizes any pending schedule
582
+ * deletion.
527
583
  */
528
584
  export async function purgeExpiredScheduleTriggers(db, options) {
529
585
  const now = options.now ?? Date.now;
@@ -531,7 +587,8 @@ export async function purgeExpiredScheduleTriggers(db, options) {
531
587
  const cutoff = now() - options.ttlMs;
532
588
  try {
533
589
  return d1Changes(await db
534
- .prepare(`DELETE FROM ${prefix}mastra_schedule_triggers WHERE actualFireAt < ?`)
590
+ .prepare(`DELETE FROM ${prefix}mastra_schedule_triggers
591
+ WHERE actualFireAt < ? AND outcome <> 'deferred'`)
535
592
  .bind(cutoff)
536
593
  .run());
537
594
  }
@@ -541,317 +598,6 @@ export async function purgeExpiredScheduleTriggers(db, options) {
541
598
  return 0;
542
599
  }
543
600
  }
544
- // One CREATE INDEX per (database, prefix) per isolate: purgeTenant runs this,
545
- // and the demo reaper invokes purgeTenant in a LIMIT-batched loop — without
546
- // the memo that is one DDL round-trip to the D1 primary per tenant per cron
547
- // firing (24 no-ops out of 25), plus one on every expired-sandbox re-auth.
548
- // Same clear-on-failure promise memo as D1ApprovalStoreFactory's
549
- // #schemaReady: only SUCCESS memoizes, so a missing snapshot table (this call
550
- // doubles as purgeTenant's table probe) or a transient error retries on the
551
- // next call instead of pinning the database to a dead promise.
552
- const snapshotIndexReady = new WeakMap();
553
- /**
554
- * Additive, app-owned index for the tenant range predicate. It couples us to
555
- * Mastra's snapshot column name (`run_id`, snake_case — its timestamps are
556
- * camelCase) — the schema-guard test pins that name so a @mastra/core bump
557
- * that renames it fails CI, not a purge.
558
- */
559
- export async function ensureSnapshotRunIdIndex(db, tablePrefix = '') {
560
- let prefixes = snapshotIndexReady.get(db);
561
- if (!prefixes) {
562
- prefixes = new Map();
563
- snapshotIndexReady.set(db, prefixes);
564
- }
565
- const memo = prefixes;
566
- let ready = memo.get(tablePrefix);
567
- if (!ready) {
568
- ready = Promise.resolve(db
569
- .prepare(`CREATE INDEX IF NOT EXISTS idx_${tablePrefix}snapshot_run_id
570
- ON ${tablePrefix}mastra_workflow_snapshot (run_id)`)
571
- .run()).then(() => undefined, (error) => {
572
- memo.delete(tablePrefix);
573
- throw error;
574
- });
575
- memo.set(tablePrefix, ready);
576
- }
577
- await ready;
578
- }
579
- /**
580
- * The tenant-range purge inventory, extensible by construction: each
581
- * later feature appends its adopted table here instead of editing purgeTenant's
582
- * body, so adoption is one additive row plus the counter/result pair the types
583
- * force alongside it. Ordering is not load-bearing (the deletes run
584
- * concurrently; see purgeTenant).
585
- *
586
- * `mastra_workflow_snapshot` is deliberately absent: it rides the same range but
587
- * over `run_id`, paired with artifact deletion and an app-owned index, so it
588
- * keeps its own block. `mastra_background_tasks` rides the range over
589
- * its own `run_id` — the originating run's tenant-salted id, always present on a
590
- * task row — without artifacts or an app index, so it lives here. Tables no
591
- * feature writes yet (`mastra_scorers`) are absent because nothing salts their
592
- * ids yet — the schema-guard's inventory pin is what forces that decision when a
593
- * feature adopts one.
594
- */
595
- export const TENANT_RANGE_PURGE_TABLES = [
596
- { counter: 'messages', table: 'mastra_messages', column: 'thread_id' },
597
- { counter: 'threads', table: 'mastra_threads', column: 'id' },
598
- { counter: 'resources', table: 'mastra_resources', column: 'id' },
599
- {
600
- counter: 'backgroundTasks',
601
- table: 'mastra_background_tasks',
602
- column: 'run_id',
603
- },
604
- // Track C — both thread-keyed: their `thread_id` holds the salted memory
605
- // threadId (`${tenantId}_${uuid}`), so the same exact range applies.
606
- {
607
- counter: 'notifications',
608
- table: 'mastra_notifications',
609
- column: 'thread_id',
610
- },
611
- {
612
- counter: 'threadState',
613
- table: 'mastra_thread_state',
614
- column: 'thread_id',
615
- },
616
- ];
617
- /**
618
- * The metadata-filtered purge inventory — the offboarding coverage for
619
- * tables whose tenant is a JSON `metadata.tenantId` (stamped by the schedules
620
- * facade at create + the tick on every trigger), not a salted id column. Both
621
- * schedule tables are here: schedule rows and their trigger history. The DELETE is
622
- * `WHERE json_extract(metadata, '$.tenantId') = ?` (the same SQLite json_extract
623
- * the run-snapshot purge already uses on `snapshot`), so a NULL/absent metadata
624
- * never matches — every row our facade/tick writes carries it, so this reaps them
625
- * all. Ordering is not load-bearing (deletes run concurrently; see purgeTenant).
626
- */
627
- export const TENANT_METADATA_PURGE_TABLES = [
628
- { counter: 'schedules', table: 'mastra_schedules' },
629
- { counter: 'scheduleTriggers', table: 'mastra_schedule_triggers' },
630
- ];
631
- /**
632
- * Complete tenant offboarding: reaps EVERY tenant-keyed store — snapshot
633
- * rows of ANY status (a tenant's suspended-and-abandoned runs are never
634
- * eligible for the terminal-only retention purge at any age), the tenant's
635
- * agent-memory rows (threads/messages/resources — salted per
636
- * docs/agent-memory-tenancy.md, so the same range predicate is exact), the
637
- * tenant's approval records (titles, summaries, payloads, decider
638
- * identities), and its R2 artifacts.
639
- *
640
- * The snapshot predicate is a range over the tenant-salted runId:
641
- * `run_id >= '<tid>_' AND run_id < '<tid>' || CHAR(0x60)`. tenantId is
642
- * revalidated against the tenant-ID pattern here — not for injection safety (every query is
643
- * parameter-bound) but for RANGE-EXACTNESS: the predicate selects exactly one
644
- * tenant only because the charset excludes every character in [0x5F, 0x60]
645
- * ('_' is 0x5F; its successor 0x60, backtick, closes the range under BINARY
646
- * collation). 'abc' can never sweep 'abcdefg'.
647
- *
648
- * PURGE POLICY (the race): this deletes SUSPENDED rows, and a reviewer
649
- * approving at that moment would resume against a vanishing row (absorbed:
650
- * the runtime's pre-check throws before any step re-executes — pinned by the
651
- * purge-race regression test). Only purge tenants whose tokens have already
652
- * expired, so no live caller can be mid-resume by construction — or purge at
653
- * the tenant's own explicit request (the showcase's self-service /demo/reset).
654
- * That caller, uniquely, can race ITSELF: a run started between the artifact
655
- * SELECT and the snapshot DELETE is reaped by the DELETE (which re-reads the
656
- * range) with its artifacts unenumerated, and the three statements are not one
657
- * transaction — an R2 delete can never join a SQL one — so a mid-purge failure
658
- * leaves it partially applied. Both are pinned in d1-storage.test.ts. Neither
659
- * can escape the requester's own tenant: the range predicate is exact.
660
- */
661
- export async function purgeTenant(db, options) {
662
- const { tenantId } = options;
663
- if (typeof tenantId !== 'string' || !TENANT_ID_PATTERN.test(tenantId)) {
664
- throw new Error(`purgeTenant: tenantId '${tenantId}' violates INV-3 (^[a-z0-9]{3,32}$) — refusing (the range predicate is only exact over that charset)`);
665
- }
666
- const prefix = options.tablePrefix ?? '';
667
- const lower = `${tenantId}_`;
668
- const upper = `${tenantId}\x60`;
669
- let backgroundTaskIds = [];
670
- try {
671
- const { results } = await db
672
- .prepare(`SELECT id FROM ${prefix}mastra_background_tasks
673
- WHERE run_id >= ? AND run_id < ?`)
674
- .bind(lower, upper)
675
- .all();
676
- backgroundTaskIds = results.map((row) => row.id);
677
- }
678
- catch (error) {
679
- if (!isMissingTable(error))
680
- throw error;
681
- }
682
- // The snapshot table exists only once Mastra lazily creates it for the
683
- // first persisted run. A tenant that never started one — routine for an
684
- // expired demo sandbox — has zero snapshots and artifacts, and its
685
- // approvals below MUST still be reaped: throwing here would wedge every
686
- // offboarding (the purge cron AND the demo re-auth's inline purge) until
687
- // some unrelated run initializes the schema.
688
- let hasSnapshotTable = true;
689
- try {
690
- await ensureSnapshotRunIdIndex(db, prefix);
691
- }
692
- catch (error) {
693
- if (!isMissingTable(error))
694
- throw error;
695
- hasSnapshotTable = false;
696
- }
697
- let artifacts = 0;
698
- let snapshots = 0;
699
- if (hasSnapshotTable) {
700
- // 1. Artifacts first — deleteRun needs the run list the snapshot DELETE
701
- // would destroy.
702
- if (options.artifactStore) {
703
- const { results } = await db
704
- .prepare(`SELECT workflow_name, run_id FROM ${prefix}mastra_workflow_snapshot
705
- WHERE run_id >= ? AND run_id < ?`)
706
- .bind(lower, upper)
707
- .all();
708
- const artifactRows = [...results];
709
- for (const ids of chunked(backgroundTaskIds, D1_BIND_CHUNK)) {
710
- if (ids.length === 0)
711
- continue;
712
- const associated = await db
713
- .prepare(`SELECT workflow_name, run_id
714
- FROM ${prefix}mastra_workflow_snapshot
715
- WHERE workflow_name = '__background-task'
716
- AND run_id IN (${ids.map(() => '?').join(', ')})`)
717
- .bind(...ids)
718
- .all();
719
- artifactRows.push(...associated.results);
720
- }
721
- const seen = new Set();
722
- for (const row of artifactRows) {
723
- const key = `${row.workflow_name}\0${row.run_id}`;
724
- if (seen.has(key))
725
- continue;
726
- seen.add(key);
727
- artifacts += await options.artifactStore.deleteRun(row.workflow_name, row.run_id);
728
- }
729
- }
730
- // 2. Snapshots — ANY status.
731
- snapshots = d1Changes(await db
732
- .prepare(`DELETE FROM ${prefix}mastra_workflow_snapshot
733
- WHERE run_id >= ? AND run_id < ?`)
734
- .bind(lower, upper)
735
- .run());
736
- for (const ids of chunked(backgroundTaskIds, D1_BIND_CHUNK)) {
737
- if (ids.length === 0)
738
- continue;
739
- snapshots += d1Changes(await db
740
- .prepare(`DELETE FROM ${prefix}mastra_workflow_snapshot
741
- WHERE workflow_name = '__background-task'
742
- AND run_id IN (${ids.map(() => '?').join(', ')})`)
743
- .bind(...ids)
744
- .run());
745
- }
746
- }
747
- // 3. Every tenant-range table (TENANT_RANGE_PURGE_TABLES — today the
748
- // agent-memory rows) — the SAME exact range, over the salted ids the
749
- // memory-id chokepoint mints (threads/resources by id, messages by their
750
- // NOT-NULL thread_id; message ids themselves are unsalted by design). The
751
- // DELETEs run concurrently via Promise.all — child-before-parent order is
752
- // non-load-bearing (messages range on their own thread_id column, Mastra
753
- // declares no FK, every table independently re-sweepable after a mid-purge
754
- // failure in any order), the memory[counter] writes hit distinct keys so
755
- // there is no shared-state race, each statement keeps its own missing-table
756
- // tolerance, and a first non-missing-table error still rejects. A missing
757
- // table reads as empty — the tables exist wherever createD1Storage ran
758
- // (eager creation), but crafted test databases and non-D1Store hosts may
759
- // not have them.
760
- const memory = {
761
- threads: 0,
762
- messages: 0,
763
- resources: 0,
764
- backgroundTasks: 0,
765
- notifications: 0,
766
- threadState: 0,
767
- };
768
- await Promise.all(TENANT_RANGE_PURGE_TABLES.filter(({ counter }) => counter !== 'backgroundTasks').map(async ({ counter, table, column }) => {
769
- try {
770
- memory[counter] = d1Changes(await db
771
- .prepare(`DELETE FROM ${prefix}${table} WHERE ${column} >= ? AND ${column} < ?`)
772
- .bind(lower, upper)
773
- .run());
774
- }
775
- catch (error) {
776
- if (!isMissingTable(error))
777
- throw error;
778
- }
779
- }));
780
- // The task row is the only durable association between its salted parent run
781
- // and the unsalted __background-task snapshot. Delete it only after the
782
- // associated snapshots/artifacts above have been consumed.
783
- try {
784
- memory.backgroundTasks = d1Changes(await db
785
- .prepare(`DELETE FROM ${prefix}mastra_background_tasks
786
- WHERE run_id >= ? AND run_id < ?`)
787
- .bind(lower, upper)
788
- .run());
789
- }
790
- catch (error) {
791
- if (!isMissingTable(error))
792
- throw error;
793
- }
794
- // 3b. Metadata-filtered tables (Track D schedules + triggers): their tenant is
795
- // a JSON metadata.tenantId, not a salted id, so they cannot ride the range
796
- // above. Same posture — concurrent deletes, per-table missing-table tolerance,
797
- // a first real error still rejects. json_extract on a NULL metadata yields NULL
798
- // and matches nothing (a row our facade/tick never wrote).
799
- const metadataCounts = {
800
- schedules: 0,
801
- scheduleTriggers: 0,
802
- };
803
- await Promise.all(TENANT_METADATA_PURGE_TABLES.map(async ({ counter, table }) => {
804
- try {
805
- metadataCounts[counter] = d1Changes(await db
806
- .prepare(`DELETE FROM ${prefix}${table} WHERE json_extract(metadata, '$.tenantId') = ?`)
807
- .bind(tenantId)
808
- .run());
809
- }
810
- catch (error) {
811
- if (!isMissingTable(error))
812
- throw error;
813
- }
814
- }));
815
- // 4. Approvals — by the tenant_id column. Hosts without the approval queue
816
- // have no such table; a missing table is the only tolerated failure.
817
- let approvals = 0;
818
- try {
819
- approvals = d1Changes(await db
820
- .prepare('DELETE FROM flowsafe_approvals WHERE tenant_id = ?')
821
- .bind(tenantId)
822
- .run());
823
- }
824
- catch (error) {
825
- if (!isMissingTable(error))
826
- throw error;
827
- }
828
- // 5. Signal subscriptions (Track E) — the same flowsafe-owned tenant_id-column
829
- // delete as approvals (NOT a mastra_* table, so not in the ranged/metadata
830
- // inventories above; retention is 'none' — standing config reaped only here).
831
- // The table name is the literal signal-providers/subscription-d1.ts owns
832
- // (SIGNAL_SUBSCRIPTIONS_TABLE); a do-runner import of signals/signal-providers
833
- // would cycle, so it is hardcoded like flowsafe_approvals. Missing table (a
834
- // host with no signal providers) is the only tolerated failure.
835
- let subscriptions = 0;
836
- try {
837
- subscriptions = d1Changes(await db
838
- .prepare('DELETE FROM flowsafe_signal_subscriptions WHERE tenant_id = ?')
839
- .bind(tenantId)
840
- .run());
841
- }
842
- catch (error) {
843
- if (!isMissingTable(error))
844
- throw error;
845
- }
846
- return {
847
- snapshots,
848
- ...memory,
849
- ...metadataCounts,
850
- approvals,
851
- subscriptions,
852
- artifacts,
853
- };
854
- }
855
601
  /** Rows affected by a D1 write, read from its `{ meta: { changes } }` envelope. */
856
602
  export function d1Changes(result) {
857
603
  const changes = result?.meta
@@ -869,7 +615,10 @@ function errorMessageOf(error) {
869
615
  * structural SnapshotDatabase seam carries no error codes (D1 wraps the
870
616
  * SQLite text but preserves it).
871
617
  */
872
- function isMissingTable(error) {
873
- return /no such table/i.test(errorMessageOf(error));
618
+ function isMissingTable(error, expectedTable) {
619
+ const message = errorMessageOf(error);
620
+ if (!/no such table/i.test(message))
621
+ return false;
622
+ return expectedTable === undefined || message.includes(expectedTable);
874
623
  }
875
624
  //# sourceMappingURL=d1-storage.js.map