@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
@@ -0,0 +1,275 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Track B (M-003): host a Mastra BackgroundTaskManager on a Durable Object, and
3
+ // survive DO eviction BY CONSTRUCTION (DL-015).
4
+ //
5
+ // THE RECOVERY SEAM (spike B-S2, pinned against @mastra/core 1.50.0 dist —
6
+ // validation finding R-002). `recoverStaleTasks()` and `handleResume` are
7
+ // PRIVATE and `getStorage()` is async, so the alarm CANNOT call
8
+ // `recoverStaleTasks()` directly. But it does not need to: the PUBLIC async
9
+ // `manager.init(pubsub)` fires `recoverStaleTasks()` internally (manager.d.ts:21
10
+ // -> chunk .init -> `await this.recoverStaleTasks()`), guarded by its own
11
+ // initPromise so it runs once per manager INSTANCE. A DO evicted mid-task leaves
12
+ // its task row 'running'/'pending' in D1; when the DO is next instantiated (a
13
+ // FRESH manager), `boot()` re-registers the static tool executors, starts the
14
+ // workflow workers, and only then calls `init(pubsub)`. Init's recovery resets a
15
+ // stranded 'running' task (maxRetries > 0) to 'pending' and re-dispatches it;
16
+ // starting workers first guarantees that the workflow event published by that
17
+ // dispatch has a subscriber. Its workflow step resolves the executor by tool
18
+ // name via the re-registered static registry (the cross-process path core ships
19
+ // `registerStaticExecutor` for). The DO ALARM is what WAKES an evicted DO so
20
+ // this happens without waiting for a request. No private method is ever called;
21
+ // the seam is `registerStaticExecutor` + `startWorkers()` + `init(pubsub)`, all
22
+ // public.
23
+ //
24
+ // v1 policy (DL-005/P8): connectors are foreground-only, so approval-carrying
25
+ // tools never enter this suspend/resume topology. Background suspend/resume
26
+ // stays available for NON-gated tools (e.g. a long research tool awaiting an
27
+ // external webhook); such a task's resume mints no capability.
28
+ //
29
+ // Execution is opt-in. The host accepts it only with the serialized D1 workflow
30
+ // adapter and a task domain bound to the same tenant. One DO isolate owns that
31
+ // manager and both domains, so core's tenant-blind recovery sees only that
32
+ // tenant's rows. `boot()` then starts Mastra's public evented workers on the
33
+ // raw pubsub instance the caller passed to Mastra. Persistence-only hosts retain
34
+ // the earlier warning.
35
+ //
36
+ // Core still keys an internal `__background-task` workflow by the unsalted task
37
+ // ID. The tenant-scoped store, TTL purge, and offboarding paths therefore delete
38
+ // the internal snapshot before deleting the task row that supplies its tenant
39
+ // association.
40
+ import { BackgroundTaskManager, } from '@mastra/core/background-tasks';
41
+ import { finiteNonnegativeNumber, nonnegativeSafeInteger, positiveSafeInteger, } from '../numeric-config.js';
42
+ import { backgroundTasksStore, SERIALIZED_WORKFLOWS_D1, TENANT_SCOPED_BACKGROUND_TASKS_D1, } from './d1-storage.js';
43
+ function validateManagerConfig(config) {
44
+ if (!config)
45
+ return;
46
+ if (config.globalConcurrency !== undefined) {
47
+ nonnegativeSafeInteger(config.globalConcurrency, 'backgroundTasks.manager.globalConcurrency');
48
+ }
49
+ if (config.perAgentConcurrency !== undefined) {
50
+ nonnegativeSafeInteger(config.perAgentConcurrency, 'backgroundTasks.manager.perAgentConcurrency');
51
+ }
52
+ if (config.defaultTimeoutMs !== undefined) {
53
+ positiveSafeInteger(config.defaultTimeoutMs, 'backgroundTasks.manager.defaultTimeoutMs');
54
+ }
55
+ if (config.progressThrottleMs !== undefined) {
56
+ nonnegativeSafeInteger(config.progressThrottleMs, 'backgroundTasks.manager.progressThrottleMs');
57
+ }
58
+ if (config.waitTimeoutMs !== undefined) {
59
+ positiveSafeInteger(config.waitTimeoutMs, 'backgroundTasks.manager.waitTimeoutMs');
60
+ }
61
+ const retries = config.defaultRetries;
62
+ if (retries?.maxRetries !== undefined) {
63
+ nonnegativeSafeInteger(retries.maxRetries, 'backgroundTasks.manager.defaultRetries.maxRetries');
64
+ }
65
+ if (retries?.retryDelayMs !== undefined) {
66
+ nonnegativeSafeInteger(retries.retryDelayMs, 'backgroundTasks.manager.defaultRetries.retryDelayMs');
67
+ }
68
+ if (retries?.maxRetryDelayMs !== undefined) {
69
+ nonnegativeSafeInteger(retries.maxRetryDelayMs, 'backgroundTasks.manager.defaultRetries.maxRetryDelayMs');
70
+ }
71
+ if (retries?.backoffMultiplier !== undefined) {
72
+ finiteNonnegativeNumber(retries.backoffMultiplier, 'backgroundTasks.manager.defaultRetries.backoffMultiplier');
73
+ }
74
+ const cleanup = config.cleanup;
75
+ if (cleanup?.completedTtlMs !== undefined) {
76
+ nonnegativeSafeInteger(cleanup.completedTtlMs, 'backgroundTasks.manager.cleanup.completedTtlMs');
77
+ }
78
+ if (cleanup?.failedTtlMs !== undefined) {
79
+ nonnegativeSafeInteger(cleanup.failedTtlMs, 'backgroundTasks.manager.cleanup.failedTtlMs');
80
+ }
81
+ if (cleanup?.cleanupIntervalMs !== undefined) {
82
+ positiveSafeInteger(cleanup.cleanupIntervalMs, 'backgroundTasks.manager.cleanup.cleanupIntervalMs');
83
+ }
84
+ }
85
+ /**
86
+ * A BackgroundTaskManager bound to a hosting DO's Mastra + pubsub, with the
87
+ * boot/alarm lifecycle that makes DO eviction survivable. The hosting DO owns
88
+ * alarm arming (it needs `ctx.storage.setAlarm`); this class owns the manager
89
+ * wiring, the recovery-firing `boot()`, and the alarm `cleanup()` duty. The raw
90
+ * manager is reachable as `.manager` for the tenant-bound routes to wrap — never
91
+ * expose it directly over HTTP.
92
+ */
93
+ export class BackgroundTaskHost {
94
+ manager;
95
+ #mastra;
96
+ #pubsub;
97
+ #executors;
98
+ #execution;
99
+ #booted;
100
+ #bootSettled = false;
101
+ #managerNeedsShutdown = false;
102
+ #workersNeedStop = false;
103
+ #shutdownRequested = false;
104
+ #shutdown;
105
+ constructor(options) {
106
+ validateManagerConfig(options.manager);
107
+ this.#mastra = options.mastra;
108
+ this.#pubsub = options.pubsub;
109
+ this.#executors = options.executors;
110
+ this.#execution = options.execution;
111
+ this.manager = new BackgroundTaskManager({
112
+ enabled: true,
113
+ ...options.manager,
114
+ });
115
+ // Must precede init(): the manager reads its Mastra for storage, the
116
+ // internal background-task workflow registration, and id generation.
117
+ this.manager.__registerMastra(options.mastra);
118
+ }
119
+ /**
120
+ * Durable-Object boot wiring. Fail fast if the backgroundTasks storage domain is
121
+ * missing, re-register the static executors, start execution-mode workflow
122
+ * workers, THEN call `init(pubsub)` — whose internal `recoverStaleTasks()`
123
+ * re-drives any task the evicted instance left mid-flight. Executors and the
124
+ * workflow subscriber both go in BEFORE recovery publishes work. A failed
125
+ * startup unwinds attempted components in reverse order. Memoized per
126
+ * instance: `init` is itself idempotent (initPromise), and `boot()` from both
127
+ * `fetch()` and `alarm()` must not double-register.
128
+ */
129
+ boot() {
130
+ if (this.#shutdownRequested) {
131
+ return Promise.reject(new Error('background-tasks: host is shutting down'));
132
+ }
133
+ if (!this.#booted) {
134
+ this.#booted = this.#doBoot().finally(() => {
135
+ this.#bootSettled = true;
136
+ });
137
+ }
138
+ return this.#booted;
139
+ }
140
+ async #doBoot() {
141
+ // Fail-fast with a clear message before any dispatch could surface core's
142
+ // terser error deep in a lifecycle callback.
143
+ const tasks = await backgroundTasksStore(this.#mastra);
144
+ // Execution mode validates every required ownership and concurrency seam.
145
+ if (this.#execution) {
146
+ const workflows = await this.#mastra.getStorage()?.getStore('workflows');
147
+ if (!workflows ||
148
+ workflows[SERIALIZED_WORKFLOWS_D1] !== true) {
149
+ throw new Error('background-tasks: execution requires DurableObjectWorkflowsStorageD1');
150
+ }
151
+ const tenantTasks = tasks;
152
+ if (tenantTasks[TENANT_SCOPED_BACKGROUND_TASKS_D1] !== true ||
153
+ tenantTasks.tenantId !== this.#execution.tenantId) {
154
+ throw new Error('background-tasks: execution requires a task store branded for the same tenant');
155
+ }
156
+ }
157
+ else {
158
+ await this.#warnIfBodiesCannotExecute();
159
+ }
160
+ for (const [toolName, executor] of Object.entries(this.#executors)) {
161
+ this.manager.registerStaticExecutor(toolName, executor);
162
+ }
163
+ try {
164
+ if (this.#execution) {
165
+ this.#workersNeedStop = true;
166
+ await this.#mastra.startWorkers();
167
+ }
168
+ this.#managerNeedsShutdown = true;
169
+ await this.manager.init(this.#pubsub);
170
+ }
171
+ catch (primary) {
172
+ const cleanupErrors = [];
173
+ if (this.#managerNeedsShutdown) {
174
+ try {
175
+ await this.manager.shutdown();
176
+ this.#managerNeedsShutdown = false;
177
+ }
178
+ catch (error) {
179
+ cleanupErrors.push(error);
180
+ }
181
+ }
182
+ if (this.#workersNeedStop) {
183
+ try {
184
+ await this.#mastra.stopWorkers();
185
+ this.#workersNeedStop = false;
186
+ }
187
+ catch (error) {
188
+ cleanupErrors.push(error);
189
+ }
190
+ }
191
+ if (cleanupErrors.length === 0)
192
+ throw primary;
193
+ throw new AggregateError([primary, ...cleanupErrors], 'background-tasks: boot failed and cleanup also failed', { cause: primary });
194
+ }
195
+ }
196
+ async #warnIfBodiesCannotExecute() {
197
+ const workflows = await this.#mastra.getStorage()?.getStore('workflows');
198
+ // Optional-chained: a store that predates the capability method reads as
199
+ // "cannot" (fail loud, never silently assume support).
200
+ const supports = workflows?.supportsConcurrentUpdates?.() ?? false;
201
+ if (!supports) {
202
+ console.warn('background-tasks: persistence-only mode cannot execute task bodies because the workflows domain does not support concurrent updates; configure createBackgroundTaskD1Domains and execution.tenantId on one single-tenant Durable Object to enable execution');
203
+ }
204
+ }
205
+ /**
206
+ * DO-alarm duty: ensure the DO is booted (a FRESH post-eviction instance
207
+ * recovers HERE, since the alarm is what woke it — see the recovery seam
208
+ * above), then run the manager's TTL cleanup. The hosting DO re-arms the alarm
209
+ * after this returns. Cleanup is core's own `cleanup()` — the belt to the
210
+ * storage-layer `purgeExpiredBackgroundTasks` cron braces (that one needs no
211
+ * live manager); running both is harmless (each only deletes rows past the
212
+ * TTL).
213
+ */
214
+ async onAlarm() {
215
+ await this.boot();
216
+ await this.manager.cleanup();
217
+ }
218
+ /**
219
+ * Graceful teardown. Stop the manager first: its shutdown flag rejects new
220
+ * enqueues synchronously before the workflow consumers disappear. Worker
221
+ * teardown is still attempted if manager teardown fails.
222
+ */
223
+ async #doShutdown() {
224
+ if (this.#booted && !this.#bootSettled) {
225
+ try {
226
+ await this.#booted;
227
+ }
228
+ catch {
229
+ // #doBoot already unwound every component it managed to stop. Any
230
+ // component whose cleanup failed remains flagged for the retry below.
231
+ }
232
+ }
233
+ const errors = [];
234
+ if (this.#managerNeedsShutdown) {
235
+ try {
236
+ await this.manager.shutdown();
237
+ this.#managerNeedsShutdown = false;
238
+ }
239
+ catch (error) {
240
+ errors.push(error);
241
+ }
242
+ }
243
+ if (this.#workersNeedStop) {
244
+ try {
245
+ await this.#mastra.stopWorkers();
246
+ this.#workersNeedStop = false;
247
+ }
248
+ catch (error) {
249
+ errors.push(error);
250
+ }
251
+ }
252
+ if (errors.length === 1)
253
+ throw errors[0];
254
+ if (errors.length > 1) {
255
+ throw new AggregateError(errors, 'background-tasks: shutdown failed', {
256
+ cause: errors[0],
257
+ });
258
+ }
259
+ }
260
+ async shutdown() {
261
+ this.#shutdownRequested = true;
262
+ if (this.#shutdown)
263
+ return this.#shutdown;
264
+ const pending = this.#doShutdown();
265
+ this.#shutdown = pending;
266
+ try {
267
+ await pending;
268
+ }
269
+ finally {
270
+ if (this.#shutdown === pending)
271
+ this.#shutdown = undefined;
272
+ }
273
+ }
274
+ }
275
+ //# sourceMappingURL=host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.js","sourceRoot":"","sources":["../../src/background-tasks/host.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,gFAAgF;AAChF,gDAAgD;AAChD,EAAE;AACF,2EAA2E;AAC3E,0EAA0E;AAC1E,gEAAgE;AAChE,4EAA4E;AAC5E,iFAAiF;AACjF,0EAA0E;AAC1E,iFAAiF;AACjF,8EAA8E;AAC9E,8EAA8E;AAC9E,iFAAiF;AACjF,8EAA8E;AAC9E,8EAA8E;AAC9E,6EAA6E;AAC7E,gFAAgF;AAChF,6E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AC;QAC1C,MAAM,OAAO,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QACnC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC;QACzB,IAAI,CAAC;YACH,MAAM,OAAO,CAAC;QAChB,CAAC;gBAAS,CAAC;YACT,IAAI,IAAI,CAAC,SAAS,KAAK,OAAO;gBAAE,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC7D,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,7 @@
1
+ export type { CreateBackgroundTaskD1DomainsOptions, PurgeExpiredBackgroundTasksOptions, PurgeExpiredBackgroundTasksResult, } from './d1-storage.js';
2
+ export { BACKGROUND_TASK_TTL_PURGE_TABLES, backgroundTasksStore, createBackgroundTaskD1Domains, DurableObjectWorkflowsStorageD1, purgeExpiredBackgroundTasks, SERIALIZED_WORKFLOWS_D1, TENANT_SCOPED_BACKGROUND_TASKS_D1, TenantScopedBackgroundTasksStorageD1, } from './d1-storage.js';
3
+ export type { BackgroundTaskHostOptions } from './host.js';
4
+ export { BackgroundTaskHost } from './host.js';
5
+ export type { BackgroundTaskRouter, BackgroundTaskRoutesOptions, } from './routes.js';
6
+ export { createBackgroundTaskRoutes } from './routes.js';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/background-tasks/index.ts"],"names":[],"mappings":"AAOA,YAAY,EACV,oCAAoC,EACpC,kCAAkC,EAClC,iCAAiC,GAClC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,gCAAgC,EAChC,oBAAoB,EACpB,6BAA6B,EAC7B,+BAA+B,EAC/B,2BAA2B,EAC3B,uBAAuB,EACvB,iCAAiC,EACjC,oCAAoC,GACrC,MAAM,iBAAiB,CAAC;AACzB,YAAY,EAAE,yBAAyB,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAC/C,YAAY,EACV,oBAAoB,EACpB,2BAA2B,GAC5B,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,10 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Track B (M-003) — background tasks. Subpath-only (`@proofoftech/flowsafe/
3
+ // background-tasks`), like agent-runner: host-side wiring a consumer opts into,
4
+ // not part of the root barrel. The tenant-range purge coverage + the completedAt
5
+ // TTL cleanup live in do-runner (coupled there to the schema guard) and are
6
+ // re-exported here for a single import surface.
7
+ export { BACKGROUND_TASK_TTL_PURGE_TABLES, backgroundTasksStore, createBackgroundTaskD1Domains, DurableObjectWorkflowsStorageD1, purgeExpiredBackgroundTasks, SERIALIZED_WORKFLOWS_D1, TENANT_SCOPED_BACKGROUND_TASKS_D1, TenantScopedBackgroundTasksStorageD1, } from './d1-storage.js';
8
+ export { BackgroundTaskHost } from './host.js';
9
+ export { createBackgroundTaskRoutes } from './routes.js';
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/background-tasks/index.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,4EAA4E;AAC5E,gFAAgF;AAChF,iFAAiF;AACjF,4EAA4E;AAC5E,gDAAgD;AAOhD,OAAO,EACL,gCAAgC,EAChC,oBAAoB,EACpB,6BAA6B,EAC7B,+BAA+B,EAC/B,2BAA2B,EAC3B,uBAAuB,EACvB,iCAAiC,EACjC,oCAAoC,GACrC,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAK/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,15 @@
1
+ import type { BackgroundTaskManager } from '@mastra/core/background-tasks';
2
+ export interface BackgroundTaskRoutesOptions {
3
+ /** The manager to read through — WRAPPED, never exposed over the wire. */
4
+ manager: BackgroundTaskManager;
5
+ /** Route prefix. Default '/background-tasks'. */
6
+ basePath?: string;
7
+ }
8
+ /**
9
+ * A router `(request, tenantId) => Response | null`. `null` means the path is
10
+ * not one of ours (the DO falls through). `tenantId` is the DO's own asserted
11
+ * tenant — never read from the request.
12
+ */
13
+ export type BackgroundTaskRouter = (request: Request, tenantId: string) => Promise<Response | null>;
14
+ export declare function createBackgroundTaskRoutes(options: BackgroundTaskRoutesOptions): BackgroundTaskRouter;
15
+ //# sourceMappingURL=routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/background-tasks/routes.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EACV,qBAAqB,EAEtB,MAAM,+BAA+B,CAAC;AAKvC,MAAM,WAAW,2BAA2B;IAC1C,0EAA0E;IAC1E,OAAO,EAAE,qBAAqB,CAAC;IAC/B,iDAAiD;IACjD,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;GAIG;AACH,MAAM,MAAM,oBAAoB,GAAG,CACjC,OAAO,EAAE,OAAO,EAChB,QAAQ,EAAE,MAAM,KACb,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC;AAsD9B,wBAAgB,0BAA0B,CACxC,OAAO,EAAE,2BAA2B,GACnC,oBAAoB,CAkDtB"}
@@ -0,0 +1,144 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Track B (M-003): the READ-ONLY, tenant-bound HTTP surface over background
3
+ // tasks (DL-014). Background-task rows carry tenant-prefixed run_id / threadId /
4
+ // resourceId (INV-1 + minted memory ids), but core's `listTasks` / `getTask` /
5
+ // `stream` are NOT tenant-bound — exposing the raw manager would be a
6
+ // cross-tenant existence/content oracle. So this router:
7
+ // - REQUIRES a `runId` or `threadId` filter on list AND stream, and validates
8
+ // its salted prefix against the authenticated tenant (400 if absent, 404 if
9
+ // foreign — no oracle);
10
+ // - loads a task for `getTask` and 404s if its `runId` is not tenant-owned,
11
+ // whether the task is missing or another tenant's (one response, no oracle);
12
+ // - never returns or accepts the raw BackgroundTaskManager.
13
+ //
14
+ // The hosting DO passes the already-authenticated tenant (its own idFromName
15
+ // identity), exactly as the run/thread DOs recover theirs. Mutating the queue
16
+ // (dispatch/cancel/resume) is NOT here: v1 keeps background dispatch server-side
17
+ // (an agent's tool call), and a suspended non-gated task's resume, if ever
18
+ // exposed, is a separate role-gated route that mints no capability (P8).
19
+ import { tenantOwnsSaltedId } from '../do-runner/index.js';
20
+ import { safeDecodeSegment } from '../host-kit/route-path.js';
21
+ function json(payload, status = 200) {
22
+ return new Response(JSON.stringify(payload), {
23
+ status,
24
+ headers: { 'content-type': 'application/json' },
25
+ });
26
+ }
27
+ /**
28
+ * Resolve the tenant-scoped filter (runId XOR threadId) from the query, or a
29
+ * fail-closed Response. Both ids are salted `${tenantId}_...`, so
30
+ * `tenantOwnsSaltedId` is exact for either. Absent means 400; foreign means
31
+ * 404 (no oracle — a foreign id gets the same answer as a nonexistent one).
32
+ */
33
+ function resolveScopedFilter(url, tenantId) {
34
+ const runId = url.searchParams.get('runId') ?? undefined;
35
+ const threadId = url.searchParams.get('threadId') ?? undefined;
36
+ if (runId === undefined && threadId === undefined) {
37
+ return json({
38
+ error: 'a runId or threadId filter is required (background-task queries are tenant-scoped)',
39
+ }, 400);
40
+ }
41
+ const scopeValue = runId ?? threadId;
42
+ if (!tenantOwnsSaltedId(tenantId, scopeValue)) {
43
+ return json({ error: 'not found' }, 404);
44
+ }
45
+ return {
46
+ filter: runId !== undefined ? { runId } : { threadId },
47
+ scopeValue,
48
+ };
49
+ }
50
+ /**
51
+ * The scope-ownership predicate shared by list and stream: a row is in
52
+ * scope iff its runId or threadId equals the validated, tenant-owned scope value
53
+ * the request was filtered by. Defense-in-depth OVER core's own filter — a future
54
+ * regression in core's `listTasks`/`stream` scoping cannot leak a foreign or
55
+ * out-of-scope row past this. One predicate so list and stream can never drift.
56
+ */
57
+ function ownsScope(row, scopeValue) {
58
+ return row.runId === scopeValue || row.threadId === scopeValue;
59
+ }
60
+ export function createBackgroundTaskRoutes(options) {
61
+ const { manager } = options;
62
+ const base = options.basePath ?? '/background-tasks';
63
+ return async (request, tenantId) => {
64
+ if (request.method !== 'GET')
65
+ return null;
66
+ const url = new URL(request.url);
67
+ const path = url.pathname;
68
+ if (path !== base && !path.startsWith(`${base}/`))
69
+ return null;
70
+ // GET {base}/stream — SSE of lifecycle events for one tenant-owned run/thread.
71
+ if (path === `${base}/stream`) {
72
+ const resolved = resolveScopedFilter(url, tenantId);
73
+ if (resolved instanceof Response)
74
+ return resolved;
75
+ return streamResponse(manager, resolved, request.signal);
76
+ }
77
+ // GET {base}/task/:taskId — one task, 404 on missing OR foreign (no oracle).
78
+ if (path.startsWith(`${base}/task/`)) {
79
+ // Malformed percent-encoding in the taskId is not a real task — 404 (the
80
+ // no-oracle response), never a decodeURIComponent throw out of the DO
81
+ // handler (this route is post-auth, but the same fail-shut posture).
82
+ const taskId = safeDecodeSegment(path.slice(`${base}/task/`.length));
83
+ if (taskId === undefined || taskId === '' || taskId.includes('/'))
84
+ return json({ error: 'not found' }, 404);
85
+ const task = await manager.getTask(taskId);
86
+ if (!task || !tenantOwnsSaltedId(tenantId, task.runId)) {
87
+ return json({ error: 'not found' }, 404);
88
+ }
89
+ return json({ task });
90
+ }
91
+ // GET {base} — list, filtered to one tenant-owned run/thread.
92
+ if (path === base) {
93
+ const resolved = resolveScopedFilter(url, tenantId);
94
+ if (resolved instanceof Response)
95
+ return resolved;
96
+ const result = await manager.listTasks(resolved.filter);
97
+ // Per-row parity with the stream guard (DL-014): re-check every returned
98
+ // row against the requested scope, so a future regression in core's
99
+ // listTasks filter cannot leak a foreign or out-of-scope task. `total` is
100
+ // recomputed from the surviving rows — never report a count that includes
101
+ // a row we would not return.
102
+ const tasks = result.tasks.filter((t) => ownsScope(t, resolved.scopeValue));
103
+ return json({ tasks, total: tasks.length });
104
+ }
105
+ return null;
106
+ };
107
+ }
108
+ /**
109
+ * Wrap `manager.stream(options)` (an object-chunk ReadableStream) as an SSE
110
+ * Response. The stream is passed the validated filter so core scopes both its
111
+ * on-connect snapshot and its live events; a second exact-match guard in the
112
+ * transform drops any chunk whose runId/threadId is not the requested one, so a
113
+ * cross-tenant leak is impossible even if core's filter ever loosened
114
+ * as defense in depth. `abortSignal` is the request's own, so a client
115
+ * disconnect closes the upstream subscription.
116
+ */
117
+ function streamResponse(manager, scoped, abortSignal) {
118
+ const { filter, scopeValue } = scoped;
119
+ const source = manager.stream({ ...filter, abortSignal });
120
+ const encoder = new TextEncoder();
121
+ const guarded = source.pipeThrough(new TransformStream({
122
+ transform(chunk, controller) {
123
+ // Same per-row scope guard the list route applies — one predicate so the
124
+ // two surfaces never drift (DL-014, defense-in-depth over core's filter).
125
+ const payload = typeof chunk.payload === 'object' &&
126
+ chunk.payload !== null &&
127
+ !Array.isArray(chunk.payload)
128
+ ? chunk.payload
129
+ : undefined;
130
+ if (!payload || !ownsScope(payload, scopeValue))
131
+ return;
132
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));
133
+ },
134
+ }));
135
+ return new Response(guarded, {
136
+ status: 200,
137
+ headers: {
138
+ 'content-type': 'text/event-stream',
139
+ 'cache-control': 'no-cache',
140
+ connection: 'keep-alive',
141
+ },
142
+ });
143
+ }
144
+ //# sourceMappingURL=routes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.js","sourceRoot":"","sources":["../../src/background-tasks/routes.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,4EAA4E;AAC5E,iFAAiF;AACjF,+EAA+E;AAC/E,sEAAsE;AACtE,yDAAyD;AACzD,gFAAgF;AAChF,gFAAgF;AAChF,4BAA4B;AAC5B,8EAA8E;AAC9E,iFAAiF;AACjF,8DAA8D;AAC9D,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,iFAAiF;AACjF,2EAA2E;AAC3E,yEAAyE;AAOzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3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ClC,MAAM,OAAO,GAAG,MAAM,CAAC,WAAW,CAChC,IAAI,eAAe,CAAsC;QACvD,SAAS,CAAC,KAAK,EAAE,UAAU;YACzB,yEAAyE;YACzE,0EAA0E;YAC1E,MAAM,OAAO,GACX,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ;gBACjC,KAAK,CAAC,OAAO,KAAK,IAAI;gBACtB,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC;gBAC3B,CAAC,CAAE,KAAK,CAAC,OAAmC;gBAC5C,CAAC,CAAC,SAAS,CAAC;YAChB,IAAI,CAAC,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,UAAU,CAAC;gBAAE,OAAO;YACxD,UAAU,CAAC,OAAO,CAChB,OAAO,CAAC,MAAM,CAAC,SAAS,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CACrD,CAAC;QACJ,CAAC;KACF,CAAC,CACH,CAAC;IACF,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE;QAC3B,MAAM,EAAE,GAAG;QACX,OAAO,EAAE;YACP,cAAc,EAAE,mBAAmB;YACnC,eAAe,EAAE,UAAU;YAC3B,UAAU,EAAE,YAAY;SACzB;KACF,CAAC,CAAC;AACL,CAAC"}
@@ -15,7 +15,7 @@ export declare const BREAKWATER_WORKFLOW_SCOPE_KEY = "breakwater.workflowScope";
15
15
  /**
16
16
  * requestContext key breakwater's tenantIsolation evaluator and connector
17
17
  * key-scoping read: the caller's OPAQUE isolation scope. RunnerRuntime mints
18
- * the runId's tenant prefix here on every leg of a tenant-salted run (INV-1),
18
+ * the runId's tenant prefix here on every leg of a tenant-salted run,
19
19
  * so connector idempotency + rate-limit keys segment per tenant. Absent on
20
20
  * non-tenant runs — breakwater then preserves its single-tenant keys.
21
21
  */
@@ -31,7 +31,7 @@ export const BREAKWATER_WORKFLOW_SCOPE_KEY = 'breakwater.workflowScope';
31
31
  /**
32
32
  * requestContext key breakwater's tenantIsolation evaluator and connector
33
33
  * key-scoping read: the caller's OPAQUE isolation scope. RunnerRuntime mints
34
- * the runId's tenant prefix here on every leg of a tenant-salted run (INV-1),
34
+ * the runId's tenant prefix here on every leg of a tenant-salted run,
35
35
  * so connector idempotency + rate-limit keys segment per tenant. Absent on
36
36
  * non-tenant runs — breakwater then preserves its single-tenant keys.
37
37
  */
@@ -59,7 +59,7 @@ export declare function safeSend(ws: WebSocketLike, frame: string): void;
59
59
  /**
60
60
  * Structural subset of DurableObjectState — the shape DurableObjectRunner
61
61
  * reads from. `id.name` (tenant/run identity recovery off the DO's own
62
- * idFromName address, INV-1) and `storage` (the ctx.storage-backed resume
62
+ * tenant-scoped idFromName address) and `storage` (the ctx.storage-backed resume
63
63
  * ledger — DurableStorageResumeLedger in resume-ledger.ts) are always touched;
64
64
  * the Hibernatable-WebSocket members are OPTIONAL so node/vitest stubs that
65
65
  * set only id.name/storage still satisfy the type and the per-run WS stream