@proofoftech/flowsafe 0.4.0 → 0.7.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 (271) hide show
  1. package/CHANGELOG.md +327 -0
  2. package/README.md +295 -251
  3. package/dist/agent-runner/approval-shapes.d.ts +36 -0
  4. package/dist/agent-runner/approval-shapes.d.ts.map +1 -0
  5. package/dist/agent-runner/approval-shapes.js +101 -0
  6. package/dist/agent-runner/approval-shapes.js.map +1 -0
  7. package/dist/agent-runner/durable-agent-runner.d.ts +158 -0
  8. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -0
  9. package/dist/agent-runner/durable-agent-runner.js +295 -0
  10. package/dist/agent-runner/durable-agent-runner.js.map +1 -0
  11. package/dist/agent-runner/index.d.ts +3 -0
  12. package/dist/agent-runner/index.d.ts.map +1 -0
  13. package/dist/agent-runner/index.js +10 -0
  14. package/dist/agent-runner/index.js.map +1 -0
  15. package/dist/approval-api/contract.d.ts +2 -2
  16. package/dist/approval-api/d1-store.d.ts.map +1 -1
  17. package/dist/approval-api/d1-store.js +87 -19
  18. package/dist/approval-api/d1-store.js.map +1 -1
  19. package/dist/approval-api/grants.d.ts +1 -1
  20. package/dist/approval-api/grants.js +1 -1
  21. package/dist/approval-api/index.d.ts +1 -1
  22. package/dist/approval-api/index.d.ts.map +1 -1
  23. package/dist/approval-api/index.js.map +1 -1
  24. package/dist/approval-api/router.d.ts +2 -2
  25. package/dist/approval-api/router.d.ts.map +1 -1
  26. package/dist/approval-api/router.js +1 -0
  27. package/dist/approval-api/router.js.map +1 -1
  28. package/dist/approval-api/service.d.ts +10 -11
  29. package/dist/approval-api/service.d.ts.map +1 -1
  30. package/dist/approval-api/service.js +22 -9
  31. package/dist/approval-api/service.js.map +1 -1
  32. package/dist/approval-api/store.d.ts +27 -22
  33. package/dist/approval-api/store.d.ts.map +1 -1
  34. package/dist/approval-api/store.js +25 -9
  35. package/dist/approval-api/store.js.map +1 -1
  36. package/dist/approval-api/tenant-context.d.ts +6 -6
  37. package/dist/approval-api/tenant-context.d.ts.map +1 -1
  38. package/dist/approval-api/tenant-context.js +15 -0
  39. package/dist/approval-api/tenant-context.js.map +1 -1
  40. package/dist/approval-api/tenant-store.d.ts +1 -1
  41. package/dist/approval-api/tenant-store.d.ts.map +1 -1
  42. package/dist/approval-api/types.d.ts +13 -4
  43. package/dist/approval-api/types.d.ts.map +1 -1
  44. package/dist/approval-api/types.js +2 -1
  45. package/dist/approval-api/types.js.map +1 -1
  46. package/dist/approval-ui/App.d.ts +2 -2
  47. package/dist/approval-ui/FilterBar.d.ts +3 -3
  48. package/dist/approval-ui/FilterBar.js +3 -3
  49. package/dist/approval-ui/client.d.ts +1 -1
  50. package/dist/approval-ui/components.d.ts +1 -1
  51. package/dist/approval-ui/stream.d.ts +3 -3
  52. package/dist/approval-ui/stream.js +2 -2
  53. package/dist/approval-ui/use-approval-dashboard.d.ts +9 -12
  54. package/dist/approval-ui/use-approval-dashboard.d.ts.map +1 -1
  55. package/dist/approval-ui/use-approval-dashboard.js +6 -9
  56. package/dist/approval-ui/use-approval-dashboard.js.map +1 -1
  57. package/dist/approval-ui/use-web-socket-transport.d.ts +1 -1
  58. package/dist/approval-ui/use-web-socket-transport.js +1 -1
  59. package/dist/background-tasks/d1-storage.d.ts +66 -0
  60. package/dist/background-tasks/d1-storage.d.ts.map +1 -0
  61. package/dist/background-tasks/d1-storage.js +196 -0
  62. package/dist/background-tasks/d1-storage.js.map +1 -0
  63. package/dist/background-tasks/host.d.ts +82 -0
  64. package/dist/background-tasks/host.d.ts.map +1 -0
  65. package/dist/background-tasks/host.js +275 -0
  66. package/dist/background-tasks/host.js.map +1 -0
  67. package/dist/background-tasks/index.d.ts +7 -0
  68. package/dist/background-tasks/index.d.ts.map +1 -0
  69. package/dist/background-tasks/index.js +10 -0
  70. package/dist/background-tasks/index.js.map +1 -0
  71. package/dist/background-tasks/routes.d.ts +15 -0
  72. package/dist/background-tasks/routes.d.ts.map +1 -0
  73. package/dist/background-tasks/routes.js +144 -0
  74. package/dist/background-tasks/routes.js.map +1 -0
  75. package/dist/do-runner/breakwater-keys.d.ts +1 -1
  76. package/dist/do-runner/breakwater-keys.js +1 -1
  77. package/dist/do-runner/cf-types.d.ts +1 -1
  78. package/dist/do-runner/d1-storage.d.ts +347 -5
  79. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  80. package/dist/do-runner/d1-storage.js +571 -17
  81. package/dist/do-runner/d1-storage.js.map +1 -1
  82. package/dist/do-runner/do-error-response.d.ts +29 -0
  83. package/dist/do-runner/do-error-response.d.ts.map +1 -0
  84. package/dist/do-runner/do-error-response.js +73 -0
  85. package/dist/do-runner/do-error-response.js.map +1 -0
  86. package/dist/do-runner/durable-object.d.ts +3 -3
  87. package/dist/do-runner/durable-object.d.ts.map +1 -1
  88. package/dist/do-runner/durable-object.js +7 -21
  89. package/dist/do-runner/durable-object.js.map +1 -1
  90. package/dist/do-runner/hub-do.d.ts +2 -2
  91. package/dist/do-runner/index.d.ts +9 -3
  92. package/dist/do-runner/index.d.ts.map +1 -1
  93. package/dist/do-runner/index.js +8 -2
  94. package/dist/do-runner/index.js.map +1 -1
  95. package/dist/do-runner/init.d.ts +20 -0
  96. package/dist/do-runner/init.d.ts.map +1 -1
  97. package/dist/do-runner/init.js +12 -1
  98. package/dist/do-runner/init.js.map +1 -1
  99. package/dist/do-runner/memory-id.d.ts +3 -3
  100. package/dist/do-runner/memory-id.js +3 -3
  101. package/dist/do-runner/path-safe-id.d.ts +6 -6
  102. package/dist/do-runner/path-safe-id.js +6 -6
  103. package/dist/do-runner/pubsub.d.ts +18 -0
  104. package/dist/do-runner/pubsub.d.ts.map +1 -0
  105. package/dist/do-runner/pubsub.js +42 -0
  106. package/dist/do-runner/pubsub.js.map +1 -0
  107. package/dist/do-runner/runtime.d.ts +24 -1
  108. package/dist/do-runner/runtime.d.ts.map +1 -1
  109. package/dist/do-runner/runtime.js +28 -2
  110. package/dist/do-runner/runtime.js.map +1 -1
  111. package/dist/do-runner/thread-do.d.ts +74 -0
  112. package/dist/do-runner/thread-do.d.ts.map +1 -0
  113. package/dist/do-runner/thread-do.js +156 -0
  114. package/dist/do-runner/thread-do.js.map +1 -0
  115. package/dist/do-runner/thread-header.d.ts +16 -0
  116. package/dist/do-runner/thread-header.d.ts.map +1 -0
  117. package/dist/do-runner/thread-header.js +24 -0
  118. package/dist/do-runner/thread-header.js.map +1 -0
  119. package/dist/goals/index.d.ts +2 -0
  120. package/dist/goals/index.d.ts.map +1 -0
  121. package/dist/goals/index.js +7 -0
  122. package/dist/goals/index.js.map +1 -0
  123. package/dist/goals/objective-routes.d.ts +87 -0
  124. package/dist/goals/objective-routes.d.ts.map +1 -0
  125. package/dist/goals/objective-routes.js +375 -0
  126. package/dist/goals/objective-routes.js.map +1 -0
  127. package/dist/host-kit/approval-bridge.d.ts +28 -8
  128. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  129. package/dist/host-kit/approval-bridge.js +37 -15
  130. package/dist/host-kit/approval-bridge.js.map +1 -1
  131. package/dist/host-kit/bearer-auth.d.ts +1 -1
  132. package/dist/host-kit/bearer-auth.js +1 -1
  133. package/dist/host-kit/env-vars.d.ts +20 -0
  134. package/dist/host-kit/env-vars.d.ts.map +1 -1
  135. package/dist/host-kit/env-vars.js +30 -0
  136. package/dist/host-kit/env-vars.js.map +1 -1
  137. package/dist/host-kit/flowsafe-worker.d.ts +113 -6
  138. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  139. package/dist/host-kit/flowsafe-worker.js +253 -63
  140. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  141. package/dist/host-kit/host-approval-service.d.ts +13 -13
  142. package/dist/host-kit/host-approval-service.js +10 -10
  143. package/dist/host-kit/index.d.ts +3 -1
  144. package/dist/host-kit/index.d.ts.map +1 -1
  145. package/dist/host-kit/index.js +7 -0
  146. package/dist/host-kit/index.js.map +1 -1
  147. package/dist/host-kit/memory-boundary.d.ts +64 -0
  148. package/dist/host-kit/memory-boundary.d.ts.map +1 -0
  149. package/dist/host-kit/memory-boundary.js +109 -0
  150. package/dist/host-kit/memory-boundary.js.map +1 -0
  151. package/dist/host-kit/route-path.d.ts +17 -0
  152. package/dist/host-kit/route-path.d.ts.map +1 -0
  153. package/dist/host-kit/route-path.js +35 -0
  154. package/dist/host-kit/route-path.js.map +1 -0
  155. package/dist/host-kit/run-router.d.ts +10 -11
  156. package/dist/host-kit/run-router.d.ts.map +1 -1
  157. package/dist/host-kit/run-router.js.map +1 -1
  158. package/dist/host-kit/stream-router.d.ts +1 -1
  159. package/dist/host-kit/stream-router.d.ts.map +1 -1
  160. package/dist/host-kit/stream-ticket.d.ts +3 -3
  161. package/dist/host-kit/stream-ticket.d.ts.map +1 -1
  162. package/dist/host-kit/stream-ticket.js +1 -1
  163. package/dist/host-kit/tenant-registry.d.ts +1 -1
  164. package/dist/host-kit/tenant-registry.js +1 -1
  165. package/dist/host-kit/thread-topology.d.ts +44 -0
  166. package/dist/host-kit/thread-topology.d.ts.map +1 -0
  167. package/dist/host-kit/thread-topology.js +76 -0
  168. package/dist/host-kit/thread-topology.js.map +1 -0
  169. package/dist/host-kit/verifier.d.ts +1 -1
  170. package/dist/host-kit/verifier.js +1 -1
  171. package/dist/index.d.ts +4 -8
  172. package/dist/index.d.ts.map +1 -1
  173. package/dist/index.js +4 -4
  174. package/dist/index.js.map +1 -1
  175. package/dist/internal-error-response.d.ts +3 -0
  176. package/dist/internal-error-response.d.ts.map +1 -0
  177. package/dist/internal-error-response.js +20 -0
  178. package/dist/internal-error-response.js.map +1 -0
  179. package/dist/numeric-config.d.ts +4 -0
  180. package/dist/numeric-config.d.ts.map +1 -0
  181. package/dist/numeric-config.js +23 -0
  182. package/dist/numeric-config.js.map +1 -0
  183. package/dist/schedules/index.d.ts +5 -0
  184. package/dist/schedules/index.d.ts.map +1 -0
  185. package/dist/schedules/index.js +13 -0
  186. package/dist/schedules/index.js.map +1 -0
  187. package/dist/schedules/router.d.ts +66 -0
  188. package/dist/schedules/router.d.ts.map +1 -0
  189. package/dist/schedules/router.js +827 -0
  190. package/dist/schedules/router.js.map +1 -0
  191. package/dist/schedules/schedules-d1.d.ts +30 -0
  192. package/dist/schedules/schedules-d1.d.ts.map +1 -0
  193. package/dist/schedules/schedules-d1.js +374 -0
  194. package/dist/schedules/schedules-d1.js.map +1 -0
  195. package/dist/schedules/storage.d.ts +11 -0
  196. package/dist/schedules/storage.d.ts.map +1 -0
  197. package/dist/schedules/storage.js +34 -0
  198. package/dist/schedules/storage.js.map +1 -0
  199. package/dist/schedules/tick.d.ts +132 -0
  200. package/dist/schedules/tick.d.ts.map +1 -0
  201. package/dist/schedules/tick.js +598 -0
  202. package/dist/schedules/tick.js.map +1 -0
  203. package/dist/signal-providers/delivery.d.ts +24 -0
  204. package/dist/signal-providers/delivery.d.ts.map +1 -0
  205. package/dist/signal-providers/delivery.js +62 -0
  206. package/dist/signal-providers/delivery.js.map +1 -0
  207. package/dist/signal-providers/github-provider.d.ts +33 -0
  208. package/dist/signal-providers/github-provider.d.ts.map +1 -0
  209. package/dist/signal-providers/github-provider.js +116 -0
  210. package/dist/signal-providers/github-provider.js.map +1 -0
  211. package/dist/signal-providers/host-do.d.ts +81 -0
  212. package/dist/signal-providers/host-do.d.ts.map +1 -0
  213. package/dist/signal-providers/host-do.js +229 -0
  214. package/dist/signal-providers/host-do.js.map +1 -0
  215. package/dist/signal-providers/host-topology.d.ts +27 -0
  216. package/dist/signal-providers/host-topology.d.ts.map +1 -0
  217. package/dist/signal-providers/host-topology.js +36 -0
  218. package/dist/signal-providers/host-topology.js.map +1 -0
  219. package/dist/signal-providers/index.d.ts +8 -0
  220. package/dist/signal-providers/index.d.ts.map +1 -0
  221. package/dist/signal-providers/index.js +21 -0
  222. package/dist/signal-providers/index.js.map +1 -0
  223. package/dist/signal-providers/provider.d.ts +93 -0
  224. package/dist/signal-providers/provider.d.ts.map +1 -0
  225. package/dist/signal-providers/provider.js +89 -0
  226. package/dist/signal-providers/provider.js.map +1 -0
  227. package/dist/signal-providers/subscription-d1.d.ts +88 -0
  228. package/dist/signal-providers/subscription-d1.d.ts.map +1 -0
  229. package/dist/signal-providers/subscription-d1.js +259 -0
  230. package/dist/signal-providers/subscription-d1.js.map +1 -0
  231. package/dist/signal-providers/webhook-route.d.ts +96 -0
  232. package/dist/signal-providers/webhook-route.d.ts.map +1 -0
  233. package/dist/signal-providers/webhook-route.js +444 -0
  234. package/dist/signal-providers/webhook-route.js.map +1 -0
  235. package/dist/signals/client.d.ts +72 -0
  236. package/dist/signals/client.d.ts.map +1 -0
  237. package/dist/signals/client.js +87 -0
  238. package/dist/signals/client.js.map +1 -0
  239. package/dist/signals/d1-shared.d.ts +43 -0
  240. package/dist/signals/d1-shared.d.ts.map +1 -0
  241. package/dist/signals/d1-shared.js +46 -0
  242. package/dist/signals/d1-shared.js.map +1 -0
  243. package/dist/signals/index.d.ts +9 -0
  244. package/dist/signals/index.d.ts.map +1 -0
  245. package/dist/signals/index.js +15 -0
  246. package/dist/signals/index.js.map +1 -0
  247. package/dist/signals/notification-dispatch.d.ts +52 -0
  248. package/dist/signals/notification-dispatch.d.ts.map +1 -0
  249. package/dist/signals/notification-dispatch.js +198 -0
  250. package/dist/signals/notification-dispatch.js.map +1 -0
  251. package/dist/signals/notifications-d1.d.ts +27 -0
  252. package/dist/signals/notifications-d1.d.ts.map +1 -0
  253. package/dist/signals/notifications-d1.js +703 -0
  254. package/dist/signals/notifications-d1.js.map +1 -0
  255. package/dist/signals/router.d.ts +73 -0
  256. package/dist/signals/router.d.ts.map +1 -0
  257. package/dist/signals/router.js +240 -0
  258. package/dist/signals/router.js.map +1 -0
  259. package/dist/signals/storage.d.ts +11 -0
  260. package/dist/signals/storage.d.ts.map +1 -0
  261. package/dist/signals/storage.js +27 -0
  262. package/dist/signals/storage.js.map +1 -0
  263. package/dist/signals/thread-do-routes.d.ts +82 -0
  264. package/dist/signals/thread-do-routes.d.ts.map +1 -0
  265. package/dist/signals/thread-do-routes.js +660 -0
  266. package/dist/signals/thread-do-routes.js.map +1 -0
  267. package/dist/signals/thread-state-d1.d.ts +22 -0
  268. package/dist/signals/thread-state-d1.d.ts.map +1 -0
  269. package/dist/signals/thread-state-d1.js +83 -0
  270. package/dist/signals/thread-state-d1.js.map +1 -0
  271. package/package.json +11 -2
@@ -1,13 +1,14 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
- // Roadmap Phase 1: "D1 storage adapter (wrap Mastra's)". The wrap pins
3
- // flowsafe defaults and is the seam where audit export / Queues hooks
4
- // attach in later phases. Table auto-creation (CREATE TABLE IF NOT EXISTS)
2
+ // The D1 adapter wraps Mastra's store to pin flowsafe defaults and provide the
3
+ // seam where audit export and Queues hooks attach. Table auto-creation
4
+ // (CREATE TABLE IF NOT EXISTS)
5
5
  // happens lazily via Mastra's storage-init proxy once the store is handed
6
6
  // to `new Mastra({ storage })` — no migration step needed for the runner.
7
7
  import { D1Store } from '@mastra/cloudflare-d1';
8
+ import { MastraCompositeStore, } from '@mastra/core/storage';
8
9
  import { TENANT_ID_PATTERN } from './path-safe-id.js';
9
10
  export function createD1Storage(options) {
10
- return new D1Store({
11
+ const d1 = new D1Store({
11
12
  id: options.id ?? 'flowsafe',
12
13
  // @mastra/cloudflare-d1's own D1Store signature wants the real
13
14
  // D1Database; D1DatabaseBinding is the structural subset this package
@@ -18,6 +19,19 @@ export function createD1Storage(options) {
18
19
  ? { tablePrefix: options.tablePrefix }
19
20
  : {}),
20
21
  });
22
+ // No extra domains ⇒ return the D1Store itself (it IS a MastraCompositeStore),
23
+ // preserving byte-identical behavior for every host that does not opt into
24
+ // signals. With domains, compose them OVER d1 as the default: its own init()
25
+ // (all adapter tables, DDL ordering, coalesced callers) runs first via the
26
+ // parentDefault path, THEN each override domain's init() — the composite never
27
+ // double-inits a parent's domain (validated: chunk #runInit).
28
+ if (!options.domains)
29
+ return d1;
30
+ return new MastraCompositeStore({
31
+ id: options.id ?? 'flowsafe',
32
+ default: d1,
33
+ domains: options.domains,
34
+ });
21
35
  }
22
36
  // Terminal statuses per WorkflowRunStatus (@mastra/core workflows/types).
23
37
  // Deleting a live run (running/suspended/waiting/pending/paused) would kill
@@ -30,6 +44,19 @@ const TERMINAL_STATUSES = [
30
44
  'bailed',
31
45
  'skipped',
32
46
  ];
47
+ /**
48
+ * The tables `purgeExpiredWorkflowRuns` deletes from under the run TTL — the
49
+ * 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.
56
+ */
57
+ export const RUN_TTL_PURGE_TABLES = [
58
+ 'mastra_workflow_snapshot',
59
+ ];
33
60
  /**
34
61
  * Data-retention purge: deletes TERMINAL runs (success/failed/tripwire/
35
62
  * canceled/bailed/skipped) whose updatedAt is older than the TTL from
@@ -143,6 +170,377 @@ export async function purgeExpiredWorkflowRuns(db, options) {
143
170
  return 0;
144
171
  }
145
172
  }
173
+ // D1 binds at most 100 parameters per query. Each id chunk below shares its
174
+ // statement with the cutoff bind of the eligibility re-check, so the chunk
175
+ // ceiling must leave room for it — 90 keeps comfortable headroom without
176
+ // making the batch loop meaningfully longer.
177
+ const D1_BIND_CHUNK = 90;
178
+ function chunked(values, size) {
179
+ const chunks = [];
180
+ for (let index = 0; index < values.length; index += size) {
181
+ chunks.push(values.slice(index, index + size));
182
+ }
183
+ return chunks;
184
+ }
185
+ /**
186
+ * The tables `purgeExpiredThreads` deletes from under the thread TTL — the
187
+ * production anchor the schema guard cross-checks the `thread-ttl` retention
188
+ * declaration against, AND the target set a `cascade` child must appear in to be
189
+ * believed. Both tables are here because the purge reaps a thread and
190
+ * its messages together: `mastra_threads` by its own `updatedAt`,
191
+ * `mastra_messages` by cascade (a message has no idleness signal of its own — see
192
+ * the purge doc). So the inventory's `mastra_messages: { retention: cascade with
193
+ * mastra_threads }` is only legal because `mastra_messages` is genuinely a delete
194
+ * target here; a cascade naming a parent whose purge never touches the child is
195
+ * the lie the guard now catches.
196
+ */
197
+ export const THREAD_TTL_PURGE_TABLES = [
198
+ 'mastra_threads',
199
+ 'mastra_messages',
200
+ ];
201
+ /**
202
+ * Thread-level retention (docs/agent-memory-tenancy.md item 7): deletes agent
203
+ * memory threads whose `updatedAt` is older than the TTL, each with its
204
+ * messages. The terminal-status shape `purgeExpiredWorkflowRuns` uses does not
205
+ * transfer — threads are not per-run and have no status, so there is nothing to
206
+ * prove "finished" about one. Time since last write IS the only signal a thread
207
+ * is done, which is why the TTL keys on `updatedAt` (the D1 memory domain stamps
208
+ * it on every saveThread, so an active conversation never ages out).
209
+ *
210
+ * MESSAGES BEFORE THREADS: a message carries a `createdAt` but no `updatedAt`,
211
+ * so there is no per-message IDLENESS signal — a message's lifetime is its
212
+ * thread's, and its rows are reachable only through it. Deleting a thread first
213
+ * would strand its messages beyond every later firing of this purge (only
214
+ * purgeTenant, at offboarding, still ranges over their salted `thread_id`).
215
+ *
216
+ * EVERY statement re-checks the CURRENT row rather than trusting the SELECT's id
217
+ * list, and that is load-bearing here in a way it is not for
218
+ * purgeExpiredWorkflowRuns (where terminal status is absorbing, so its re-check
219
+ * is belt-and-braces). "Idle" is precisely NOT absorbing — a thread can come
220
+ * back to life mid-purge — and the writer is not atomic either: the memory
221
+ * domain's saveMessages issues its message insert and its `UPDATE mastra_threads
222
+ * SET updatedAt` as two INDEPENDENT calls under one Promise.all, so a send's
223
+ * message can be visible while its thread still reads idle. That TORN state is
224
+ * what each guard answers:
225
+ *
226
+ * - The message DELETE re-reads the thread's current `updatedAt` (subquery) AND
227
+ * bounds itself to `createdAt < cutoff`. The subquery alone would sweep a
228
+ * just-arrived message into the same statement as the genuinely old ones —
229
+ * it keys on the THREAD's staleness, and the bump has not landed — silently
230
+ * destroying the message the user just sent. `createdAt` is the message's own
231
+ * evidence of recency, and the only guard that survives a torn write.
232
+ * - The thread DELETE re-checks `updatedAt < cutoff` AND fires only when `NOT
233
+ * EXISTS` any message for it. Sequence alone cannot carry "messages before
234
+ * threads": a message landing after the message DELETE leaves an idle-looking
235
+ * thread whose row would go out from under it. The NOT EXISTS makes the
236
+ * invariant — never delete a thread a message points at — a property of the
237
+ * statement rather than of timing.
238
+ *
239
+ * Together: a torn or concurrent send at ANY point in the sequence keeps both
240
+ * its message and its thread; the thread's next firing (by then bumped, or by
241
+ * then genuinely idle again) decides its fate on fresh evidence.
242
+ *
243
+ * Residuals, both accepted, neither reachable by a read path: (1) a send landing
244
+ * between the two DELETEs loses the already-expiring history while the thread
245
+ * and the new message survive — strictly better than the deletion that was
246
+ * milliseconds away. (2) A message inserted AFTER its thread's row is already
247
+ * gone is orphaned by the writer, not by this purge; D1 offers no cross-statement
248
+ * 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.
252
+ *
253
+ * `mastra_resources` (working memory) is deliberately untouched: a resource is
254
+ * 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).
256
+ *
257
+ * Missing tables read as zero (a deployment with no agent memory never created
258
+ * them). Scheduling stays with the caller — see createFlowsafeWorker's
259
+ * THREAD_RETENTION_DAYS duty.
260
+ */
261
+ export async function purgeExpiredThreads(db, options) {
262
+ const now = options.now ?? Date.now;
263
+ const prefix = options.tablePrefix ?? '';
264
+ // @mastra/cloudflare-d1 stores the memory tables' TIMESTAMP columns as
265
+ // ISO-8601 TEXT (the same serialization the snapshot rows use), so a
266
+ // lexicographic < against an ISO cutoff is a correct timestamp comparison.
267
+ const cutoff = new Date(now() - options.ttlMs).toISOString();
268
+ let expired;
269
+ try {
270
+ ({ results: expired } = await db
271
+ .prepare(`SELECT id FROM ${prefix}mastra_threads
272
+ WHERE updatedAt < ?
273
+ ORDER BY updatedAt
274
+ LIMIT ?`)
275
+ .bind(cutoff, options.limit ?? 100)
276
+ .all());
277
+ }
278
+ catch (error) {
279
+ if (!isMissingTable(error))
280
+ throw error;
281
+ return { threads: 0, messages: 0 };
282
+ }
283
+ const ids = expired.map((row) => row.id);
284
+ if (ids.length === 0)
285
+ return { threads: 0, messages: 0 };
286
+ const batches = chunked(ids, D1_BIND_CHUNK);
287
+ const placeholders = (chunk) => chunk.map(() => '?').join(', ');
288
+ // The eligibility re-check, as a subquery so the message delete rides the
289
+ // thread's CURRENT updatedAt rather than the SELECT's stale membership.
290
+ const stillExpired = (chunk) => `SELECT id FROM ${prefix}mastra_threads
291
+ WHERE id IN (${placeholders(chunk)}) AND updatedAt < ?`;
292
+ let messages = 0;
293
+ let hasMessagesTable = true;
294
+ for (const chunk of batches) {
295
+ try {
296
+ messages += d1Changes(await db
297
+ .prepare(`DELETE FROM ${prefix}mastra_messages
298
+ WHERE thread_id IN (${stillExpired(chunk)})
299
+ AND createdAt < ?`)
300
+ .bind(...chunk, cutoff, cutoff)
301
+ .run());
302
+ }
303
+ catch (error) {
304
+ // A host whose memory domain never initialized has threads but no
305
+ // 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.
307
+ if (!isMissingTable(error))
308
+ throw error;
309
+ hasMessagesTable = false;
310
+ break;
311
+ }
312
+ }
313
+ // The structural invariant: never delete a thread a message still points at
314
+ // (see the header — the writer's insert and its updatedAt bump are not atomic,
315
+ // so updatedAt alone cannot carry this). Dropped only when the table does not
316
+ // exist, where "no message points at it" is vacuously true and the subquery
317
+ // would throw instead.
318
+ const noMessagesLeft = hasMessagesTable
319
+ ? ` AND NOT EXISTS (SELECT 1 FROM ${prefix}mastra_messages
320
+ WHERE thread_id = ${prefix}mastra_threads.id)`
321
+ : '';
322
+ let threads = 0;
323
+ for (const chunk of batches) {
324
+ threads += d1Changes(await db
325
+ .prepare(`DELETE FROM ${prefix}mastra_threads
326
+ WHERE id IN (${placeholders(chunk)}) AND updatedAt < ?${noMessagesLeft}`)
327
+ .bind(...chunk, cutoff)
328
+ .run());
329
+ }
330
+ return { threads, messages };
331
+ }
332
+ /**
333
+ * The table `purgeExpiredBackgroundTasks` deletes from under the background-task
334
+ * TTL — the production anchor the schema guard cross-checks the
335
+ * `background-task-ttl` retention declaration against. It is the background-task
336
+ * counterpart to RUN_TTL_PURGE_TABLES. One table: the TTL rides `completedAt` on
337
+ * `mastra_background_tasks` alone, no cascade.
338
+ */
339
+ export const BACKGROUND_TASK_TTL_PURGE_TABLES = [
340
+ 'mastra_background_tasks',
341
+ ];
342
+ /** Terminal statuses the failed-class TTL reaps together (core cleanup mirrors this set). */
343
+ const BACKGROUND_TASK_FAILED_STATUSES = [
344
+ 'failed',
345
+ 'cancelled',
346
+ 'timed_out',
347
+ ];
348
+ /**
349
+ * Background-task TTL cleanup: deletes terminal task
350
+ * rows from `mastra_background_tasks` once their `completedAt` is older than the
351
+ * 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
353
+ * purgeExpiredWorkflowRuns/purgeExpiredThreads (raw D1 binding, failure-isolated
354
+ * as a cron duty). Two windows, exactly as core: completed rows expire fast
355
+ * (default 1h), failed/cancelled/timed_out slowly (default 24h) so a failure
356
+ * stays inspectable.
357
+ *
358
+ * `completedAt` is stored as ISO-8601 TEXT (`toISOString()`), so lexicographic
359
+ * `<` against an ISO cutoff is a correct timestamp comparison — the same bet the
360
+ * other purges take. `completedAt IS NOT NULL` is load-bearing: a row without a
361
+ * completion stamp cannot be proven old, so it survives (fail safe). Live rows
362
+ * (pending / running / suspended) are never matched — deleting a suspended task
363
+ * mid-flight would strand its resume. A missing table reads as zero (background
364
+ * tasks may never have run). Scheduling stays with the caller.
365
+ */
366
+ export async function purgeExpiredBackgroundTasks(db, options = {}) {
367
+ const now = options.now ?? Date.now;
368
+ const prefix = options.tablePrefix ?? '';
369
+ const table = `${prefix}mastra_background_tasks`;
370
+ const completedCutoff = new Date(now() - (options.completedTtlMs ?? 3_600_000)).toISOString();
371
+ const failedCutoff = new Date(now() - (options.failedTtlMs ?? 86_400_000)).toISOString();
372
+ const failedPlaceholders = BACKGROUND_TASK_FAILED_STATUSES.map(() => '?').join(', ');
373
+ try {
374
+ // Internal evented-engine snapshots use the UNSALTED task id. Consume that
375
+ // association before deleting the task rows that make tenant/retention
376
+ // ownership discoverable.
377
+ try {
378
+ await db
379
+ .prepare(`DELETE FROM ${prefix}mastra_workflow_snapshot
380
+ WHERE workflow_name = '__background-task'
381
+ AND run_id IN (
382
+ SELECT id FROM ${table}
383
+ WHERE status = 'completed'
384
+ AND completedAt IS NOT NULL AND completedAt < ?
385
+ )`)
386
+ .bind(completedCutoff)
387
+ .run();
388
+ await db
389
+ .prepare(`DELETE FROM ${prefix}mastra_workflow_snapshot
390
+ WHERE workflow_name = '__background-task'
391
+ AND run_id IN (
392
+ SELECT id FROM ${table}
393
+ WHERE status IN (${failedPlaceholders})
394
+ AND completedAt IS NOT NULL AND completedAt < ?
395
+ )`)
396
+ .bind(...BACKGROUND_TASK_FAILED_STATUSES, failedCutoff)
397
+ .run();
398
+ }
399
+ catch (error) {
400
+ // A deployment may have task rows before its workflow table is created;
401
+ // no associated snapshots can exist in that case.
402
+ if (!isMissingTable(error))
403
+ throw error;
404
+ }
405
+ const completed = d1Changes(await db
406
+ .prepare(`DELETE FROM ${table}
407
+ WHERE status = 'completed'
408
+ AND completedAt IS NOT NULL AND completedAt < ?`)
409
+ .bind(completedCutoff)
410
+ .run());
411
+ const failed = d1Changes(await db
412
+ .prepare(`DELETE FROM ${table}
413
+ WHERE status IN (${failedPlaceholders})
414
+ AND completedAt IS NOT NULL AND completedAt < ?`)
415
+ .bind(...BACKGROUND_TASK_FAILED_STATUSES, failedCutoff)
416
+ .run());
417
+ return { completed, failed };
418
+ }
419
+ catch (error) {
420
+ if (!isMissingTable(error))
421
+ throw error;
422
+ return { completed: 0, failed: 0 };
423
+ }
424
+ }
425
+ /**
426
+ * The table `purgeExpiredNotifications` deletes from under the notification TTL
427
+ * — the anchor the schema guard cross-checks the `notification-ttl` retention
428
+ * declaration against. It is the notification counterpart to
429
+ * BACKGROUND_TASK_TTL_PURGE_TABLES.
430
+ */
431
+ export const NOTIFICATION_TTL_PURGE_TABLES = [
432
+ 'mastra_notifications',
433
+ ];
434
+ /** Terminal notification statuses the TTL reaps (a delivered/seen/… inbox item is done). */
435
+ const NOTIFICATION_TERMINAL_STATUSES = [
436
+ 'delivered',
437
+ 'seen',
438
+ 'dismissed',
439
+ 'archived',
440
+ 'discarded',
441
+ ];
442
+ /**
443
+ * Notification TTL cleanup: deletes terminal agent-inbox
444
+ * 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).
447
+ * `updatedAt` is ISO-8601 TEXT, so lexicographic `<` is a correct timestamp
448
+ * comparison. A missing table reads as zero (notifications may never have been
449
+ * sent). Scheduling stays with the caller.
450
+ */
451
+ export async function purgeExpiredNotifications(db, options) {
452
+ const now = options.now ?? Date.now;
453
+ const prefix = options.tablePrefix ?? '';
454
+ const cutoff = new Date(now() - options.ttlMs).toISOString();
455
+ const placeholders = NOTIFICATION_TERMINAL_STATUSES.map(() => '?').join(', ');
456
+ try {
457
+ return d1Changes(await db
458
+ .prepare(`DELETE FROM ${prefix}mastra_notifications
459
+ WHERE status IN (${placeholders}) AND updatedAt < ?`)
460
+ .bind(...NOTIFICATION_TERMINAL_STATUSES, cutoff)
461
+ .run());
462
+ }
463
+ catch (error) {
464
+ if (!isMissingTable(error))
465
+ throw error;
466
+ return 0;
467
+ }
468
+ }
469
+ /**
470
+ * The table `purgeExpiredThreadState` deletes from under the thread-state TTL —
471
+ * the anchor the schema guard cross-checks the `thread-state-ttl` retention
472
+ * declaration against.
473
+ */
474
+ export const THREAD_STATE_TTL_PURGE_TABLES = [
475
+ 'mastra_thread_state',
476
+ ];
477
+ /**
478
+ * Thread-state TTL cleanup: deletes thread-state rows
479
+ * from `mastra_thread_state` once their `updatedAt` is older than the TTL. Keys
480
+ * on `updatedAt` for the same reason `purgeExpiredThreads` does — thread state
481
+ * has no terminal status, so time-since-last-write is the only "done" signal.
482
+ * 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.
486
+ */
487
+ export async function purgeExpiredThreadState(db, options) {
488
+ const now = options.now ?? Date.now;
489
+ const prefix = options.tablePrefix ?? '';
490
+ const cutoff = new Date(now() - options.ttlMs).toISOString();
491
+ try {
492
+ return d1Changes(await db
493
+ .prepare(`DELETE FROM ${prefix}mastra_thread_state WHERE updatedAt < ?`)
494
+ .bind(cutoff)
495
+ .run());
496
+ }
497
+ catch (error) {
498
+ if (!isMissingTable(error))
499
+ throw error;
500
+ return 0;
501
+ }
502
+ }
503
+ /**
504
+ * The table `purgeExpiredScheduleTriggers` deletes from under the trigger-row TTL
505
+ * — the anchor the schema guard cross-checks the `schedule-trigger-ttl` retention
506
+ * declaration against. It is the schedule-trigger counterpart to
507
+ * THREAD_STATE_TTL_PURGE_TABLES.
508
+ * Only the trigger HISTORY expires; the schedule rows themselves are standing
509
+ * config (retention 'none', reaped at offboarding by purgeTenant).
510
+ */
511
+ export const SCHEDULE_TRIGGER_TTL_PURGE_TABLES = [
512
+ 'mastra_schedule_triggers',
513
+ ];
514
+ /**
515
+ * Schedule-trigger TTL cleanup: deletes trigger-history
516
+ * 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).
519
+ *
520
+ * `actualFireAt` is stored as INTEGER ms-epoch (core types
521
+ * `ScheduleTrigger.actualFireAt` as `number`, unlike the ISO-TEXT timestamp
522
+ * columns the other domains use), so the comparison is a NUMERIC `<` against a
523
+ * numeric cutoff — a correct timestamp comparison over integers. A missing table
524
+ * 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.
527
+ */
528
+ export async function purgeExpiredScheduleTriggers(db, options) {
529
+ const now = options.now ?? Date.now;
530
+ const prefix = options.tablePrefix ?? '';
531
+ const cutoff = now() - options.ttlMs;
532
+ try {
533
+ return d1Changes(await db
534
+ .prepare(`DELETE FROM ${prefix}mastra_schedule_triggers WHERE actualFireAt < ?`)
535
+ .bind(cutoff)
536
+ .run());
537
+ }
538
+ catch (error) {
539
+ if (!isMissingTable(error))
540
+ throw error;
541
+ return 0;
542
+ }
543
+ }
146
544
  // One CREATE INDEX per (database, prefix) per isolate: purgeTenant runs this,
147
545
  // and the demo reaper invokes purgeTenant in a LIMIT-batched loop — without
148
546
  // the memo that is one DDL round-trip to the D1 primary per tenant per cron
@@ -178,6 +576,58 @@ export async function ensureSnapshotRunIdIndex(db, tablePrefix = '') {
178
576
  }
179
577
  await ready;
180
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
+ ];
181
631
  /**
182
632
  * Complete tenant offboarding: reaps EVERY tenant-keyed store — snapshot
183
633
  * rows of ANY status (a tenant's suspended-and-abandoned runs are never
@@ -187,9 +637,9 @@ export async function ensureSnapshotRunIdIndex(db, tablePrefix = '') {
187
637
  * tenant's approval records (titles, summaries, payloads, decider
188
638
  * identities), and its R2 artifacts.
189
639
  *
190
- * The snapshot predicate is a RANGE over the INV-1 salted runId:
640
+ * The snapshot predicate is a range over the tenant-salted runId:
191
641
  * `run_id >= '<tid>_' AND run_id < '<tid>' || CHAR(0x60)`. tenantId is
192
- * re-validated against INV-3 here — not for injection safety (every query is
642
+ * revalidated against the tenant-ID pattern here — not for injection safety (every query is
193
643
  * parameter-bound) but for RANGE-EXACTNESS: the predicate selects exactly one
194
644
  * tenant only because the charset excludes every character in [0x5F, 0x60]
195
645
  * ('_' is 0x5F; its successor 0x60, backtick, closes the range under BINARY
@@ -216,6 +666,19 @@ export async function purgeTenant(db, options) {
216
666
  const prefix = options.tablePrefix ?? '';
217
667
  const lower = `${tenantId}_`;
218
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
+ }
219
682
  // The snapshot table exists only once Mastra lazily creates it for the
220
683
  // first persisted run. A tenant that never started one — routine for an
221
684
  // expired demo sandbox — has zero snapshots and artifacts, and its
@@ -242,7 +705,25 @@ export async function purgeTenant(db, options) {
242
705
  WHERE run_id >= ? AND run_id < ?`)
243
706
  .bind(lower, upper)
244
707
  .all();
245
- for (const row of results) {
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);
246
727
  artifacts += await options.artifactStore.deleteRun(row.workflow_name, row.run_id);
247
728
  }
248
729
  }
@@ -252,11 +733,22 @@ export async function purgeTenant(db, options) {
252
733
  WHERE run_id >= ? AND run_id < ?`)
253
734
  .bind(lower, upper)
254
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
+ }
255
746
  }
256
- // 3. Agent-memory rows — the SAME exact range, over the salted ids the
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
257
749
  // memory-id chokepoint mints (threads/resources by id, messages by their
258
750
  // NOT-NULL thread_id; message ids themselves are unsalted by design). The
259
- // three DELETEs run concurrently via Promise.all — child-before-parent order is
751
+ // DELETEs run concurrently via Promise.all — child-before-parent order is
260
752
  // non-load-bearing (messages range on their own thread_id column, Mastra
261
753
  // declares no FK, every table independently re-sweepable after a mid-purge
262
754
  // failure in any order), the memory[counter] writes hit distinct keys so
@@ -265,13 +757,15 @@ export async function purgeTenant(db, options) {
265
757
  // table reads as empty — the tables exist wherever createD1Storage ran
266
758
  // (eager creation), but crafted test databases and non-D1Store hosts may
267
759
  // not have them.
268
- const memoryPurges = [
269
- ['messages', 'mastra_messages', 'thread_id'],
270
- ['threads', 'mastra_threads', 'id'],
271
- ['resources', 'mastra_resources', 'id'],
272
- ];
273
- const memory = { threads: 0, messages: 0, resources: 0 };
274
- await Promise.all(memoryPurges.map(async ([counter, table, column]) => {
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 }) => {
275
769
  try {
276
770
  memory[counter] = d1Changes(await db
277
771
  .prepare(`DELETE FROM ${prefix}${table} WHERE ${column} >= ? AND ${column} < ?`)
@@ -283,6 +777,41 @@ export async function purgeTenant(db, options) {
283
777
  throw error;
284
778
  }
285
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
+ }));
286
815
  // 4. Approvals — by the tenant_id column. Hosts without the approval queue
287
816
  // have no such table; a missing table is the only tolerated failure.
288
817
  let approvals = 0;
@@ -296,7 +825,32 @@ export async function purgeTenant(db, options) {
296
825
  if (!isMissingTable(error))
297
826
  throw error;
298
827
  }
299
- return { snapshots, ...memory, approvals, artifacts };
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
+ };
300
854
  }
301
855
  /** Rows affected by a D1 write, read from its `{ meta: { changes } }` envelope. */
302
856
  export function d1Changes(result) {