@proofoftech/flowsafe 0.6.0 → 0.8.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 (211) hide show
  1. package/CHANGELOG.md +31 -1
  2. package/README.md +305 -251
  3. package/dist/agent-host/approval-resumer.d.ts +13 -0
  4. package/dist/agent-host/approval-resumer.d.ts.map +1 -0
  5. package/dist/agent-host/approval-resumer.js +43 -0
  6. package/dist/agent-host/approval-resumer.js.map +1 -0
  7. package/dist/agent-host/catalog.d.ts +6 -0
  8. package/dist/agent-host/catalog.d.ts.map +1 -0
  9. package/dist/agent-host/catalog.js +98 -0
  10. package/dist/agent-host/catalog.js.map +1 -0
  11. package/dist/agent-host/index.d.ts +9 -0
  12. package/dist/agent-host/index.d.ts.map +1 -0
  13. package/dist/agent-host/index.js +11 -0
  14. package/dist/agent-host/index.js.map +1 -0
  15. package/dist/agent-host/router.d.ts +11 -0
  16. package/dist/agent-host/router.d.ts.map +1 -0
  17. package/dist/agent-host/router.js +240 -0
  18. package/dist/agent-host/router.js.map +1 -0
  19. package/dist/agent-host/thread-host.d.ts +55 -0
  20. package/dist/agent-host/thread-host.d.ts.map +1 -0
  21. package/dist/agent-host/thread-host.js +636 -0
  22. package/dist/agent-host/thread-host.js.map +1 -0
  23. package/dist/agent-host/thread-topology.d.ts +39 -0
  24. package/dist/agent-host/thread-topology.d.ts.map +1 -0
  25. package/dist/agent-host/thread-topology.js +127 -0
  26. package/dist/agent-host/thread-topology.js.map +1 -0
  27. package/dist/agent-host/trusted-context.d.ts +9 -0
  28. package/dist/agent-host/trusted-context.d.ts.map +1 -0
  29. package/dist/agent-host/trusted-context.js +40 -0
  30. package/dist/agent-host/trusted-context.js.map +1 -0
  31. package/dist/agent-host/types.d.ts +49 -0
  32. package/dist/agent-host/types.d.ts.map +1 -0
  33. package/dist/agent-host/types.js +3 -0
  34. package/dist/agent-host/types.js.map +1 -0
  35. package/dist/agent-runner/agent-run-state.d.ts +30 -0
  36. package/dist/agent-runner/agent-run-state.d.ts.map +1 -0
  37. package/dist/agent-runner/agent-run-state.js +128 -0
  38. package/dist/agent-runner/agent-run-state.js.map +1 -0
  39. package/dist/agent-runner/approval-shapes.d.ts +1 -1
  40. package/dist/agent-runner/approval-shapes.js +1 -1
  41. package/dist/agent-runner/durable-agent-runner.d.ts +32 -16
  42. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  43. package/dist/agent-runner/durable-agent-runner.js +149 -28
  44. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  45. package/dist/agent-runner/index.d.ts +2 -0
  46. package/dist/agent-runner/index.d.ts.map +1 -1
  47. package/dist/agent-runner/index.js +1 -0
  48. package/dist/agent-runner/index.js.map +1 -1
  49. package/dist/approval-api/contract.d.ts +2 -2
  50. package/dist/approval-api/d1-store.d.ts.map +1 -1
  51. package/dist/approval-api/d1-store.js +27 -11
  52. package/dist/approval-api/d1-store.js.map +1 -1
  53. package/dist/approval-api/grants.d.ts +1 -1
  54. package/dist/approval-api/grants.js +1 -1
  55. package/dist/approval-api/router.d.ts +1 -1
  56. package/dist/approval-api/service.d.ts +8 -9
  57. package/dist/approval-api/service.d.ts.map +1 -1
  58. package/dist/approval-api/service.js +37 -16
  59. package/dist/approval-api/service.js.map +1 -1
  60. package/dist/approval-api/store.d.ts +17 -16
  61. package/dist/approval-api/store.d.ts.map +1 -1
  62. package/dist/approval-api/store.js +10 -9
  63. package/dist/approval-api/store.js.map +1 -1
  64. package/dist/approval-api/tenant-context.d.ts +6 -6
  65. package/dist/approval-api/tenant-context.d.ts.map +1 -1
  66. package/dist/approval-api/tenant-context.js +20 -3
  67. package/dist/approval-api/tenant-context.js.map +1 -1
  68. package/dist/approval-api/tenant-store.d.ts +1 -1
  69. package/dist/approval-api/tenant-store.d.ts.map +1 -1
  70. package/dist/approval-api/types.d.ts +14 -7
  71. package/dist/approval-api/types.d.ts.map +1 -1
  72. package/dist/approval-api/types.js +2 -1
  73. package/dist/approval-api/types.js.map +1 -1
  74. package/dist/approval-ui/App.d.ts +2 -2
  75. package/dist/approval-ui/FilterBar.d.ts +3 -3
  76. package/dist/approval-ui/FilterBar.js +3 -3
  77. package/dist/approval-ui/client.d.ts +1 -1
  78. package/dist/approval-ui/components.d.ts +1 -1
  79. package/dist/approval-ui/stream.d.ts +3 -3
  80. package/dist/approval-ui/stream.js +2 -2
  81. package/dist/approval-ui/use-approval-dashboard.d.ts +9 -12
  82. package/dist/approval-ui/use-approval-dashboard.d.ts.map +1 -1
  83. package/dist/approval-ui/use-approval-dashboard.js +6 -9
  84. package/dist/approval-ui/use-approval-dashboard.js.map +1 -1
  85. package/dist/approval-ui/use-web-socket-transport.d.ts +1 -1
  86. package/dist/approval-ui/use-web-socket-transport.js +1 -1
  87. package/dist/background-tasks/d1-storage.d.ts +3 -3
  88. package/dist/background-tasks/d1-storage.js +3 -3
  89. package/dist/background-tasks/host.d.ts +4 -4
  90. package/dist/background-tasks/host.js +2 -2
  91. package/dist/background-tasks/routes.js +3 -3
  92. package/dist/do-runner/breakwater-keys.d.ts +1 -1
  93. package/dist/do-runner/breakwater-keys.js +1 -1
  94. package/dist/do-runner/cf-types.d.ts +1 -1
  95. package/dist/do-runner/d1-storage.d.ts +37 -36
  96. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  97. package/dist/do-runner/d1-storage.js +24 -23
  98. package/dist/do-runner/d1-storage.js.map +1 -1
  99. package/dist/do-runner/durable-object.d.ts +2 -2
  100. package/dist/do-runner/durable-object.d.ts.map +1 -1
  101. package/dist/do-runner/durable-object.js +5 -5
  102. package/dist/do-runner/durable-object.js.map +1 -1
  103. package/dist/do-runner/execution-context.d.ts +19 -0
  104. package/dist/do-runner/execution-context.d.ts.map +1 -0
  105. package/dist/do-runner/execution-context.js +70 -0
  106. package/dist/do-runner/execution-context.js.map +1 -0
  107. package/dist/do-runner/hub-do.d.ts +2 -2
  108. package/dist/do-runner/index.d.ts +2 -1
  109. package/dist/do-runner/index.d.ts.map +1 -1
  110. package/dist/do-runner/index.js +2 -1
  111. package/dist/do-runner/index.js.map +1 -1
  112. package/dist/do-runner/init.d.ts +1 -1
  113. package/dist/do-runner/memory-id.d.ts +3 -3
  114. package/dist/do-runner/memory-id.js +3 -3
  115. package/dist/do-runner/path-safe-id.d.ts +6 -6
  116. package/dist/do-runner/path-safe-id.js +6 -6
  117. package/dist/do-runner/runtime.d.ts +12 -5
  118. package/dist/do-runner/runtime.d.ts.map +1 -1
  119. package/dist/do-runner/runtime.js +158 -21
  120. package/dist/do-runner/runtime.js.map +1 -1
  121. package/dist/do-runner/thread-do.d.ts +8 -5
  122. package/dist/do-runner/thread-do.d.ts.map +1 -1
  123. package/dist/do-runner/thread-do.js +23 -6
  124. package/dist/do-runner/thread-do.js.map +1 -1
  125. package/dist/do-runner/thread-header.d.ts +2 -0
  126. package/dist/do-runner/thread-header.d.ts.map +1 -1
  127. package/dist/do-runner/thread-header.js +2 -0
  128. package/dist/do-runner/thread-header.js.map +1 -1
  129. package/dist/goals/objective-routes.d.ts +6 -6
  130. package/dist/goals/objective-routes.d.ts.map +1 -1
  131. package/dist/goals/objective-routes.js +3 -3
  132. package/dist/host-kit/approval-bridge.d.ts +14 -17
  133. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  134. package/dist/host-kit/approval-bridge.js +20 -20
  135. package/dist/host-kit/approval-bridge.js.map +1 -1
  136. package/dist/host-kit/bearer-auth.d.ts +1 -1
  137. package/dist/host-kit/bearer-auth.js +1 -1
  138. package/dist/host-kit/flowsafe-worker.d.ts +27 -14
  139. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  140. package/dist/host-kit/flowsafe-worker.js +9 -1
  141. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  142. package/dist/host-kit/host-approval-service.d.ts +13 -13
  143. package/dist/host-kit/host-approval-service.js +10 -10
  144. package/dist/host-kit/index.d.ts +1 -1
  145. package/dist/host-kit/index.d.ts.map +1 -1
  146. package/dist/host-kit/index.js.map +1 -1
  147. package/dist/host-kit/memory-boundary.d.ts +1 -1
  148. package/dist/host-kit/memory-boundary.js +1 -1
  149. package/dist/host-kit/run-router.d.ts +10 -11
  150. package/dist/host-kit/run-router.d.ts.map +1 -1
  151. package/dist/host-kit/run-router.js.map +1 -1
  152. package/dist/host-kit/stream-router.d.ts +1 -1
  153. package/dist/host-kit/stream-router.d.ts.map +1 -1
  154. package/dist/host-kit/stream-ticket.d.ts +3 -3
  155. package/dist/host-kit/stream-ticket.d.ts.map +1 -1
  156. package/dist/host-kit/stream-ticket.js +1 -1
  157. package/dist/host-kit/tenant-registry.d.ts +1 -1
  158. package/dist/host-kit/tenant-registry.js +1 -1
  159. package/dist/host-kit/thread-topology.d.ts.map +1 -1
  160. package/dist/host-kit/thread-topology.js +3 -1
  161. package/dist/host-kit/thread-topology.js.map +1 -1
  162. package/dist/host-kit/verifier.d.ts +1 -1
  163. package/dist/host-kit/verifier.js +1 -1
  164. package/dist/index.d.ts +4 -8
  165. package/dist/index.d.ts.map +1 -1
  166. package/dist/index.js +7 -6
  167. package/dist/index.js.map +1 -1
  168. package/dist/schedules/router.d.ts +3 -3
  169. package/dist/schedules/router.d.ts.map +1 -1
  170. package/dist/schedules/router.js +2 -2
  171. package/dist/schedules/tick.d.ts +8 -11
  172. package/dist/schedules/tick.d.ts.map +1 -1
  173. package/dist/schedules/tick.js +11 -45
  174. package/dist/schedules/tick.js.map +1 -1
  175. package/dist/signal-providers/delivery.d.ts +1 -1
  176. package/dist/signal-providers/delivery.js +1 -1
  177. package/dist/signal-providers/host-do.d.ts +9 -7
  178. package/dist/signal-providers/host-do.d.ts.map +1 -1
  179. package/dist/signal-providers/host-do.js +28 -15
  180. package/dist/signal-providers/host-do.js.map +1 -1
  181. package/dist/signal-providers/host-topology.d.ts +27 -0
  182. package/dist/signal-providers/host-topology.d.ts.map +1 -0
  183. package/dist/signal-providers/host-topology.js +36 -0
  184. package/dist/signal-providers/host-topology.js.map +1 -0
  185. package/dist/signal-providers/index.d.ts +1 -0
  186. package/dist/signal-providers/index.d.ts.map +1 -1
  187. package/dist/signal-providers/index.js +2 -0
  188. package/dist/signal-providers/index.js.map +1 -1
  189. package/dist/signal-providers/provider.d.ts +8 -7
  190. package/dist/signal-providers/provider.d.ts.map +1 -1
  191. package/dist/signal-providers/provider.js +11 -9
  192. package/dist/signal-providers/provider.js.map +1 -1
  193. package/dist/signal-providers/subscription-d1.d.ts +3 -3
  194. package/dist/signal-providers/subscription-d1.d.ts.map +1 -1
  195. package/dist/signal-providers/subscription-d1.js +1 -1
  196. package/dist/signal-providers/subscription-d1.js.map +1 -1
  197. package/dist/signal-providers/webhook-route.d.ts +10 -2
  198. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  199. package/dist/signal-providers/webhook-route.js +55 -2
  200. package/dist/signal-providers/webhook-route.js.map +1 -1
  201. package/dist/signals/notifications-d1.d.ts +3 -4
  202. package/dist/signals/notifications-d1.d.ts.map +1 -1
  203. package/dist/signals/notifications-d1.js +3 -4
  204. package/dist/signals/notifications-d1.js.map +1 -1
  205. package/dist/signals/router.d.ts +1 -1
  206. package/dist/signals/router.d.ts.map +1 -1
  207. package/dist/signals/thread-do-routes.d.ts +10 -5
  208. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  209. package/dist/signals/thread-do-routes.js +54 -18
  210. package/dist/signals/thread-do-routes.js.map +1 -1
  211. package/package.json +6 -3
package/CHANGELOG.md CHANGED
@@ -1,7 +1,34 @@
1
1
  # @proofoftech/flowsafe
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 09a4406: Add guarded Breakwater agents and Flowsafe's authenticated, catalog-driven agent host. Agent starts now derive trusted identity and execution context, agent resumes require an approval-bound capability, and status and NDJSON observation remain tenant-bound.
8
+
9
+ ### Patch Changes
10
+
11
+ - 6670285: Prevent approval resume after isolate eviction from rerunning application input processors or input policy evaluation. Durable-agent recovery now reauthorizes the stored principal, restores both Mastra run registries with complete runtime processor chains, and fails before resumed tool execution when authorization is denied.
12
+
13
+ ## 0.7.0
14
+
15
+ ### Minor Changes
16
+
17
+ - def3b37: Complete and document the public flowsafe surface. The root entry point now
18
+ re-exports the approval API, Durable Object runner, artifacts, and audit export
19
+ surfaces with parity tests. Signal-provider hosts gain a tenant-safe topology,
20
+ stable polling alarms, and automatic post-mutation polling reconciliation.
21
+ Publish comprehensive package, deployment, approval, durable-agent, operations,
22
+ and API-reference documentation, plus a full advanced starter host.
23
+
3
24
  ## 0.6.0
4
25
 
26
+ > **Final 0.6.0 state:** The `eca3b6e` closeout entry below supersedes earlier
27
+ > statements in this release section that agent schedule targets and durable D1
28
+ > background-task execution were deferred. Both are supported in 0.6.0 when
29
+ > their opt-in host wiring is configured. Durable-agent restart resume and
30
+ > notification dispatch are also closed and verified.
31
+
5
32
  ### Minor Changes
6
33
 
7
34
  - eca3b6e: Close the durable-agent, agent-schedule, notification-dispatch, and D1 background-task execution residuals with tenant-safe thread routing and eviction-safe approval resume. Harden stored schedule context and core schedule-contract validation; make D1 notification creation preserve explicit-id coalescing, insertion-order targets, rollback-safe atomic migration, and concurrent partial updates; priority-plan summary and individual delivery across state-stable 100-id batches; accept Mastra's raw constructor pubsub with rollback-safe workers and a synchronous enqueue shutdown gate; close failed resume streams; validate public numeric configuration synchronously; preserve nested Mastra background-task SSE events; and require a proven process shutdown before spike restart.
@@ -99,7 +126,10 @@
99
126
  a malformed taskId returns the no-oracle 404 instead of throwing. Additive and
100
127
  behavior-preserving for all valid paths.
101
128
 
102
- ## 0.5.0
129
+ ## Unpublished 0.5.0 draft (included in 0.6.0)
130
+
131
+ No `@proofoftech/flowsafe@0.5.0` package was published. These changes shipped in
132
+ 0.6.0 and remain here as their original generated release notes.
103
133
 
104
134
  ### Minor Changes
105
135
 
package/README.md CHANGED
@@ -1,287 +1,341 @@
1
- # flowsafe
1
+ # @proofoftech/flowsafe
2
2
 
3
- Approval UX and durable execution for Mastra workflows, running on Cloudflare
4
- Workers and Durable Objects.
3
+ Durable approvals and tenant-safe long-running execution for Mastra on Cloudflare.
5
4
 
6
- ## Purpose
5
+ Flowsafe runs Mastra workflows and agents through Cloudflare Durable Objects, stores their snapshots in D1, turns suspensions into human approval requests, and derives connector grants from stored decisions when a run resumes.
7
6
 
8
- flowsafe provides human-in-the-loop approval gates for Mastra workflows and
9
- durable execution via the Durable Object import-swap pattern. It ships as a
10
- standalone service with a React approval UI and a DO-based workflow runner.
7
+ [Documentation](https://github.com/ProofOfTechOrg/anchorage/tree/main/docs) · [Getting started](https://github.com/ProofOfTechOrg/anchorage/blob/main/docs/getting-started.md) · [API reference](https://proofoftechorg.github.io/anchorage/) · [Live demo](https://anchorage.proofoftech.org/)
11
8
 
12
- ## Subpackages
9
+ ## Install
13
10
 
14
- | Subpackage | Role |
15
- |---|---|
16
- | `approval-api` | REST API for submitting and reviewing approval requests: claim/decide/delegate, batch decide, triage filters (requester + age bounds), SLA tracking + escalation, and the `ApprovalNotificationSink` transport seam |
17
- | `approval-ui` | Styling-agnostic React UI surfacing pending approvals and history, with queue triage (filter bar + batch selection/decide) |
18
- | `do-runner` | Durable Object workflow runner (import-swap pattern) |
19
- | `audit-export` | Cloudflare Queues → SIEM audit export (producer sink + batch consumer) |
20
- | `artifacts` | R2-backed workflow artifact storage keyed by run identity |
21
- | `host-kit` | Host-agnostic glue: the identity seam (`TokenVerifier`), the tenant resolver, the shared `/workflows` + `/runs` routes, the tenants registry, the suspension→approval bridge, and `createFlowsafeWorker()` — the composed production Worker hosts consume as thin shells |
22
-
23
- A copy-ready production deployment lives in [`deploy/`](deploy/) — a thin
24
- shell over `createFlowsafeWorker()` with cron-owned SLA enforcement and
25
- retention purge.
11
+ ```bash
12
+ npm install @mastra/core@^1.50.0 @proofoftech/flowsafe
13
+ ```
26
14
 
27
- ## Installation
15
+ Install `@proofoftech/breakwater` when resumed steps call approval-protected connectors:
28
16
 
29
- ```
30
- npm install @proofoftech/flowsafe
17
+ ```bash
18
+ npm install @proofoftech/breakwater
31
19
  ```
32
20
 
33
- Support matrix: Node >= 22, ESM only (TypeScript `moduleResolution`
34
- `node16`/`nodenext`/`bundler`; no CJS build), `@mastra/core` ^1.50.0 as a
35
- peer. React 18 or 19 is an optional peer used only by `./approval-ui`;
36
- `@proofoftech/breakwater` is an optional peer whose types only the
37
- `./host-kit/module` subpath references.
38
-
39
- ## Status
40
-
41
- Implemented, tested, and spike-verified. The do-runner + D1 adapter run a
42
- Mastra workflow on Workers + DO under `wrangler dev`, suspend at an approval
43
- step, survive a full dev-server restart, and resume to completion from the
44
- D1 snapshot — proven as a pass/fail command by
45
- `pnpm --filter @proofoftech/flowsafe spike:verify`.
46
-
47
- The approval queue + dashboard + SLA are implemented, tested, and
48
- spike-verified on workerd: a suspension queues a D1-backed approval request
49
- (CAS-guarded store, one open request per suspended step); a reviewer decision
50
- — role-checked, audited, SLA-tracked, self-approval denied by default —
51
- resumes the run through its Durable Object; and the runtime's
52
- `requestContextForRun` provider derives the breakwater connector grant
53
- (`breakwater.approvedConnectors`) from APPROVED records on every
54
- start/resume, leg-scoped to the resumed step. Grants never travel in HTTP
55
- bodies: a resume that bypasses `decide()` for its step finds no grant and
56
- fails closed at the connector gate — even when the same connector was
57
- approved at an earlier gate of the run.
58
-
59
- flowsafe is **multi-tenant by construction** (see
60
- [Multi-tenancy](#multi-tenancy) below): run ids carry their tenant, approval
61
- stores are bound to one tenant at construction, and the cross-tenant SLA sweep
62
- is cron-only code that a request handler cannot reach — enforced by the type
63
- system, not by convention.
64
-
65
- ## Usage
21
+ Install React and React DOM only when you import `@proofoftech/flowsafe/approval-ui`.
22
+
23
+ Compatibility:
24
+
25
+ - Node.js 22 or later (engine range `>=22`)
26
+ - ESM only
27
+ - TypeScript `moduleResolution: "NodeNext"`, `"Node16"`, or `"Bundler"`
28
+ - `@mastra/core` in the declared `^1.50.0` peer range
29
+ - `react` and `react-dom` `>=18 <20` (React 18 or 19) for the optional approval UI
30
+ - `@proofoftech/breakwater` `>=0.6.0 <1.0.0` when used
31
+
32
+ ## Choose an export
33
+
34
+ | Import | Purpose |
35
+ | --- | --- |
36
+ | `@proofoftech/flowsafe` | Compatibility barrel for approval API, runner, artifacts, and audit export |
37
+ | `@proofoftech/flowsafe/agent-host` | Server-only guarded-agent catalogs, authenticated run routes, thread hosting, NDJSON observation, and approval-only resume |
38
+ | `@proofoftech/flowsafe/approval-api` | Approval records, service, tenant-bound stores, REST router, grants, SLA, retention, notifications, and stream events |
39
+ | `@proofoftech/flowsafe/do-runner` | Durable Object runner, D1 storage, run summaries, identities, pub/sub, resume ledger, retention, and offboarding |
40
+ | `@proofoftech/flowsafe/approval-ui` | Styling-library-agnostic React dashboard, DOM-free API client, headless hook, and live transport |
41
+ | `@proofoftech/flowsafe/host-kit` | Auth seams, tenant resolver, topologies, run/stream routers, approval bridges, and composed Worker |
42
+ | `@proofoftech/flowsafe/host-kit/module` | Import-safe workflow module contract |
43
+ | `@proofoftech/flowsafe/artifacts` | R2 artifact store and in-memory test bucket |
44
+ | `@proofoftech/flowsafe/audit-export` | Cloudflare Queue producer sink and NDJSON SIEM consumer |
45
+ | `@proofoftech/flowsafe/agent-runner` | Runtime-driven Mastra durable agents and restart-safe approval resume |
46
+ | `@proofoftech/flowsafe/signals` | Thread signal routes, ingestion router, D1 notification/state domains, dispatch, and client |
47
+ | `@proofoftech/flowsafe/signals/client` | DOM-free signal client without Worker code |
48
+ | `@proofoftech/flowsafe/goals` | Durable objective router |
49
+ | `@proofoftech/flowsafe/schedules` | D1 schedules, tenant facade, reserved-context controls, and CAS tick |
50
+ | `@proofoftech/flowsafe/background-tasks` | Tenant task host, D1 task domains, routes, and cleanup |
51
+ | `@proofoftech/flowsafe/signal-providers` | Alarm-driven provider host, topology, subscriptions, verified webhooks, and GitHub reference provider |
52
+
53
+ New host-side and React features are subpath-only. This keeps the root import free of Breakwater, durable-agent-host, and UI dependency graphs.
54
+
55
+ ## Start with the baseline Worker
56
+
57
+ Copy the [reference deployment](https://github.com/ProofOfTechOrg/anchorage/tree/main/packages/flowsafe/deploy). It supplies:
58
+
59
+ - one Durable Object per run;
60
+ - D1-backed Mastra snapshots and approvals;
61
+ - bearer-authentication seam and tenant resolver;
62
+ - workflow catalog, start, status, and resume routes;
63
+ - suspension-to-approval bridge;
64
+ - exact suspension-bound breakwater grant derivation;
65
+ - role checks and separation of duties;
66
+ - optional live approval/run WebSockets;
67
+ - cron-owned SLA sweep and retention purge;
68
+ - structured audit and optional Queue-to-SIEM export;
69
+ - a sample gated workflow.
70
+
71
+ Replace the example workflow and identity verifier. Keep the trusted host-kit composition and grant provider.
66
72
 
67
73
  ```typescript
68
- import { z } from 'zod';
69
- import { DurableObjectRunner, init, type RunnerRuntime } from '@proofoftech/flowsafe/do-runner';
70
-
71
- // Inside the Durable Object: init(env) builds D1-backed storage from the
72
- // conventional `DB` binding (or pass { storage } explicitly, e.g. in tests)
73
- // and returns import-swapped factories. Workflow definition code is
74
- // unchanged Mastra code.
75
- export class MyRunner extends DurableObjectRunner<Env> {
74
+ import {
75
+ approvalGrantProvider,
76
+ } from '@proofoftech/flowsafe/approval-api';
77
+ import {
78
+ DurableObjectRunner,
79
+ init,
80
+ type RunnerRuntime,
81
+ } from '@proofoftech/flowsafe/do-runner';
82
+ import { approvalStoreFactoryFor } from '@proofoftech/flowsafe/host-kit';
83
+
84
+ export class AppRunner extends DurableObjectRunner<Env> {
76
85
  protected build(env: Env): RunnerRuntime {
77
- const { createWorkflow, createStep, runtime } = init(env);
78
- const gate = createStep({
79
- id: 'approval',
80
- inputSchema: z.object({ topic: z.string() }),
81
- outputSchema: z.object({ topic: z.string(), approvedBy: z.string() }),
82
- suspendSchema: z.object({ reason: z.string() }),
83
- resumeSchema: z.object({ approvedBy: z.string() }),
84
- execute: async ({ inputData, resumeData, suspend }) => {
85
- if (!resumeData) return suspend({ reason: 'approval required' });
86
- return { topic: inputData.topic, approvedBy: resumeData.approvedBy };
87
- },
86
+ const approvals = approvalStoreFactoryFor(env.DB).forTenant(this.tenantId);
87
+ const { createWorkflow, createStep, runtime } = init(env, {
88
+ requestContextForRun: approvalGrantProvider(approvals),
88
89
  });
89
- createWorkflow({
90
- id: 'gated',
91
- inputSchema: z.object({ topic: z.string() }),
92
- outputSchema: z.object({ topic: z.string(), approvedBy: z.string() }),
93
- })
94
- .then(gate)
95
- .commit();
90
+
91
+ // Define and commit workflows through the import-swapped factories.
92
+
96
93
  return runtime;
97
94
  }
98
95
  }
99
96
  ```
100
97
 
101
- The DO exposes `POST /runs`, `GET /runs/:workflowId/:runId`, and
102
- `POST /runs/:workflowId/:runId/resume`; route one DO instance per run
103
- (`idFromName(workflowId + ':' + runId)`) from your Worker. See
104
- `spike/worker.ts` for a complete Worker, and run the end-to-end spike with
105
- `pnpm spike` (wrangler dev on `spike/wrangler.jsonc`).
98
+ `init()` creates D1-backed Mastra storage from the conventional `DB` binding unless you inject storage. Workflow definitions use the same `createWorkflow()` and `createStep()` shape as Mastra.
99
+
100
+ ## Approval lifecycle
101
+
102
+ When a workflow or durable agent suspends:
103
+
104
+ 1. The authoritative run summary captures `stepPath`, `suspendedAt`, and `resumeCount`.
105
+ 2. The trusted host bridge creates one open approval in a tenant-bound store.
106
+ 3. The record's connector ids come from a server-authored suspend payload.
107
+ 4. A reviewer claims, delegates, approves, or rejects through the service or REST router.
108
+ 5. A compare-and-swap commits the mutation.
109
+ 6. An approval re-enters the owning runtime.
110
+ 7. `approvalGrantProvider()` reads D1 and writes only the matching approved connectors into the resumed leg's request context.
111
+ 8. Another suspension creates a new approval. A completed or failed run ends the loop.
112
+
113
+ Grants never travel in public request bodies. A raw or forged resume finds no stored capability and fails at the breakwater connector gate.
114
+
115
+ ### REST surface
116
+
117
+ The default approval base is `/api/approvals`.
118
+
119
+ ```text
120
+ GET /
121
+ GET /metrics
122
+ GET /:id
123
+ POST /:id/claim
124
+ POST /:id/delegate
125
+ POST /:id/decide
126
+ POST /batch/decide
127
+ ```
128
+
129
+ The create route is disabled by default. If enabled, it rejects capability, attribution, fingerprint, and resume-target fields.
130
+
131
+ Queue filters cover status, workflow, run, claimant, requester, strict creation-time bounds, bounded pagination, and reviewer-priority ordering. Batch decisions contain per-record outcomes and preserve all single-record checks.
132
+
133
+ ### Separation of duties
134
+
135
+ Self-decision is denied by default. A non-exempt actor also cannot approve a later gate after approving an earlier gate that advanced the run. Set a narrow role exemption only for an installation that cannot supply an independent reviewer.
136
+
137
+ ### SLA, notifications, and retention
138
+
139
+ `sweepSLA()` accepts the system-only cross-tenant store and escalates overdue open records. It is intended for a scheduled invocation and is not an HTTP service method.
140
+
141
+ `ApprovalNotificationSink` receives creation and escalation events. Failures are contained and audited. `ApprovalStreamSink` publishes mutations to the optional tenant hub.
106
142
 
107
- ### Approval queue (`@proofoftech/flowsafe/approval-api`)
143
+ `purgeExpiredApprovals()` deletes only approved and rejected records past the configured age. Pending, claimed, and escalated records remain live at any age.
144
+
145
+ Read the [approval-system guide](https://github.com/ProofOfTechOrg/anchorage/blob/main/docs/approval-system.md) for exact grant binding and recovery behavior.
146
+
147
+ ## Approval dashboard
148
+
149
+ The optional UI exports a plain-HTML default and an injected component contract:
108
150
 
109
151
  ```typescript
110
152
  import {
111
- approvalGrantProvider,
112
- ApprovalService,
113
- createApprovalRouter,
114
- createTenantResolver,
115
- D1ApprovalStoreFactory,
116
- resumeViaRuntime,
117
- sweepSLA,
118
- } from '@proofoftech/flowsafe/approval-api';
119
- import { bearerActorAuthenticator, staticTokenVerifier, parseActorTokens }
120
- from '@proofoftech/flowsafe/host-kit';
121
-
122
- // Hoist the factory to module scope: it owns one memoized schema-init pass,
123
- // so rebuilding it per request re-runs the DDL every time.
124
- const factory = new D1ApprovalStoreFactory(env.DB); // shares the runner's D1
125
-
126
- // 1. Grant-minting seam. Inside a Durable Object, bind the store to THIS
127
- // instance's tenant (recovered from its own idFromName identity), so the
128
- // mint can only ever read its own tenant's records.
129
- const { createWorkflow, createStep, runtime } = init(env, {
130
- requestContextForRun: approvalGrantProvider(factory.forTenant(this.tenantId)),
153
+ ApprovalApiClient,
154
+ createApprovalDashboard,
155
+ } from '@proofoftech/flowsafe/approval-ui';
156
+
157
+ const client = new ApprovalApiClient({
158
+ headers: {
159
+ authorization: `Bearer ${token}`,
160
+ },
131
161
  });
132
162
 
133
- // 2. Authenticate FIRST, then construct. The resolver validates the actor's
134
- // tenant and binds the store to it, so there is no pre-auth service for a
135
- // later refactor to reach for.
136
- const resolve = createTenantResolver({
137
- authenticate: bearerActorAuthenticator(
138
- staticTokenVerifier(parseActorTokens(env.APPROVAL_ACTOR_TOKENS)),
139
- ),
140
- storeFactory: factory,
141
- buildService: (store) =>
142
- new ApprovalService({
143
- store, // tenant-bound; required
144
- defaultSlaSeconds: 15 * 60,
145
- resumeRun: resumeViaRuntime(runtime), // or a DO-stub fetch
146
- audit: (event) => auditLogger.record(event),
147
- }),
163
+ createApprovalDashboard(document.getElementById('root')!, {
164
+ client,
148
165
  });
166
+ ```
167
+
168
+ The package includes:
169
+
170
+ - queue, detail, metrics, filter, and batch-decision views;
171
+ - `useApprovalDashboard()` for headless composition;
172
+ - `ApprovalUIProvider` and `ApprovalUIComponents` slots;
173
+ - optional checkbox, select, toast, and presence slots;
174
+ - optimistic decisions with conflict reporting;
175
+ - polling reconciliation;
176
+ - WebSocket live merge and liveness heartbeat;
177
+ - `ApprovalApiClient` without a DOM dependency.
178
+
179
+ Flowsafe has no Astryx or CSS dependency. The repository showcase injects Astryx in the application only.
180
+
181
+ ## Multi-tenancy
182
+
183
+ Flowsafe applies three base invariants.
184
+
185
+ ### The run id carries the tenant
186
+
187
+ The host mints `${tenantId}_${uuid}` from authenticated context. `RunnerRuntime.start()` requires a run id and has no generation fallback. Status and resume return 404 for a foreign run.
188
+
189
+ The run id scopes the snapshot, Durable Object, connector isolation context, approval lookup, and artifact path.
190
+
191
+ ### Stores bind at construction
192
+
193
+ `D1ApprovalStoreFactory.forTenant()` returns a branded tenant-bound store. Request handlers cannot pass an unbound or system store where a tenant store is required.
194
+
195
+ Construct the store after authentication through `createTenantResolver()`. The system store exists only for scheduled cross-tenant maintenance.
196
+
197
+ ### The tenant charset makes prefix ownership exact
198
+
199
+ Tenant ids match `^[a-z0-9]{3,32}$`. This excludes the `_` run and memory delimiter, making prefix ownership and D1 range deletion exact.
200
+
201
+ Provision each named tenant before issuing credentials. Do not infer customer identity from a slug without the registry.
202
+
203
+ ## Memory, retention, and offboarding
204
+
205
+ Mastra memory ids are caller-chosen by default. In a multi-tenant host:
206
+
207
+ - mint threads with `TenantContext.newThreadId()`;
208
+ - mint resources with `TenantContext.newResourceId(key)`;
209
+ - reject client bodies that name memory ids;
210
+ - return 404 for foreign stored ids;
211
+ - reach a thread Durable Object only through `createThreadTopology()`.
149
212
 
150
- // 3. REST surface (list/get/claim/decide/delegate/metrics). The create route
151
- // is off unless you pass allowCreate.
152
- const router = createApprovalRouter({ resolve });
213
+ Retention helpers cover:
214
+
215
+ - terminal workflow snapshots;
216
+ - decided approvals;
217
+ - idle threads and their messages;
218
+ - terminal notifications;
219
+ - thread state and goals;
220
+ - schedule trigger history;
221
+ - terminal background tasks.
222
+
223
+ Schedules, resources/working memory, and provider subscriptions are standing state and delete at offboarding, not by default TTL.
224
+
225
+ `purgeTenant()` deletes every adopted tenant domain. Pass the artifact store so R2 objects delete with their owning run rows.
226
+
227
+ ## Artifacts
228
+
229
+ `R2ArtifactStore` uses keys shaped as:
230
+
231
+ ```text
232
+ [prefix/]workflowId/runId/name
153
233
  ```
154
234
 
155
- Escalation is **cron-only**. There is deliberately no HTTP sweep route: the
156
- sweep is an unfiltered cross-tenant read *and write*, so it lives in a
157
- standalone `sweepSLA(factory.system(), { systemActor, audit, onEscalation })`
158
- that takes a `SystemApprovalStore` — a type a request handler cannot obtain.
159
- Call it from `scheduled()`. Breached open requests transition to `escalated`
160
- (still decidable) and fire `onEscalation`.
161
-
162
- Grant scope: a step-keyed approval unlocks its connectors only for the leg
163
- that resumes that step, and only for the suspension it was decided during —
164
- when the same step suspends again, the earlier approval is spent and the new
165
- suspension needs its own decision. Create a step-less approval for
166
- deliberately run-scoped standing grants. Self-approval (decider ==
167
- requester) is denied unless the service is constructed with
168
- `allowSelfDecision` — `true` exempts every decider, or `{ roles }` exempts
169
- only the listed roles (a single-operator deployment sets e.g.
170
- `{ roles: ['admin'] }`; composed hosts pass `APPROVAL_ALLOW_SELF_DECISION`).
171
- A permitted self-decision is audited with `detail.selfDecision: true`. If a decision's
172
- resume attempt fails (`resume.ok === false`), the decision is already
173
- durable — re-drive the run by POSTing its resume route with the record's
174
- `stepPath` and the `defaultResumeData` shape; grants re-derive from the
175
- store.
176
-
177
- ### Dashboard (`@proofoftech/flowsafe/approval-ui`)
178
-
179
- A React dashboard over the REST API — queue, detail + decision form, metrics.
180
- It is **styling-library agnostic**: the views render through injected slot
181
- components, so you plug in your own design system — or use the built-in unstyled
182
- HTML default. `react`/`react-dom` are optional peers needed only for this
183
- subpath, and it runs on React 18+.
235
+ Workflow and run ids use the runner's path-safe pattern. Artifact names are validated segment by segment. `deleteRun()` pairs with terminal-run retention; tenant purge removes the remaining tenant artifacts.
184
236
 
185
- ```typescript
186
- import { ApprovalApiClient, createApprovalDashboard } from '@proofoftech/flowsafe/approval-ui';
237
+ `InMemoryArtifactBucket` is available for tests and offline demos.
238
+
239
+ ## Audit export
240
+
241
+ `queueAuditSink(queue)` turns the shared audit contract into Cloudflare Queue messages. `createAuditQueueConsumer()` batches records as NDJSON, posts them to the configured collector, acknowledges the batch on 2xx, and retries otherwise.
242
+
243
+ The types are structural and do not require `@cloudflare/workers-types`. A transform seam can map internal events to your SIEM schema.
244
+
245
+ ## Live streaming
246
+
247
+ Live updates are opt-in behind a `HUB` Durable Object binding and `STREAM_TICKET_SECRET`.
248
+
249
+ An authenticated REST request mints a short-lived HMAC ticket. The browser presents it when opening a queue or run WebSocket. The Worker is the only verifier, and each Durable Object rebinds the addressed tenant or run through its own identity.
250
+
251
+ Tickets carry addressing information only. They contain no connector grant or approval decision. Polling remains available as fallback and reconciliation.
252
+
253
+ ## Long-running agents
254
+
255
+ The following surfaces are supported and opt-in: they are tested and covered by package compatibility guarantees, but the host must explicitly wire the required routes, bindings, storage domains, or scheduled duties.
256
+
257
+ ### Durable agents
258
+
259
+ Use `@proofoftech/flowsafe/agent-host` for a public protected surface. `createAgentRouter()` lists server-owned metadata and exposes authenticated start, status, and newline-delimited JSON observation routes. The router mints every id, rejects trusted context and execution overrides, and authorizes mutations against both the global start roles and the selected agent's roles.
260
+
261
+ `createThreadAgentHost()` validates Breakwater's guarded-handle brand before it registers the agent with Mastra. It persists the thread/agent binding and original run principal, so eviction recovery and approval resume cannot switch agents or actors.
262
+
263
+ Agent resume is approval-only. `createAgentApprovalResumer()` rejects legacy agent targets without the original principal, rechecks current catalog roles, and delegates non-agent workflow records to the existing resume function.
264
+
265
+ `createFlowsafeDurableAgent()` remains the lower-level compatibility API. It routes Mastra's durable-agent workflow through `RunnerRuntime`, but it does not guard an arbitrary raw agent. Use `agent-host` when an HTTP surface must enforce catalog and Breakwater invariants.
266
+
267
+ Agent event replay lasts only as long as the configured Mastra cache. The default in-memory cache does not survive process restart. A 409 stream response means the client must read the authoritative status route.
268
+
269
+ ### Signals and notifications
270
+
271
+ `createThreadSignalRoutes()` hosts message, queue, signal, state, and notification delivery in the thread Durable Object. `createSignalRouter()` is the Worker trust boundary: authenticate, authorize, ownership-check, cap, parse, reject memory ids, allowlist attributes, rate-limit, audit, then forward.
187
272
 
188
- const client = new ApprovalApiClient({ headers: { authorization: `Bearer ${token}` } });
273
+ `D1NotificationsStorage` and `D1ThreadStateStorage` mirror Mastra's in-memory domains on D1. `SignalClient` is available from the browser-safe `signals/client` export.
189
274
 
190
- // Unstyled HTML default — zero extra deps; style via the flowsafe-* class hooks.
191
- const dashboard = createApprovalDashboard(document.getElementById('root')!, { client });
275
+ ### Goals
192
276
 
193
- // …or supply a design-system adapter for the ApprovalUIComponents slots:
194
- // createApprovalDashboard(el, { client, components: myAdapter });
277
+ `createObjectiveRouter()` manages one durable objective per thread through Mastra's own goal read/write shape. Writes are role-gated, size- and run-budget-capped, and audited.
278
+
279
+ ### Schedules
280
+
281
+ `D1SchedulesStorage` implements the schedule domain. `createScheduleRouter()` provides tenant-filtered CRUD and read-only trigger history. `createScheduleTick()` claims due fires with CAS, protects reserved context keys, checks unattended-run caps, mints a tenant run id, and starts a workflow or agent through the correct topology.
282
+
283
+ ### Background tasks
284
+
285
+ `createBackgroundTaskD1Domains()` supplies serialized workflow and tenant task storage. `BackgroundTaskHost` owns one manager per tenant Durable Object, while `createBackgroundTaskRoutes()` exposes its host surface. Terminal task cleanup is opt-in through the composed Worker.
286
+
287
+ ### Signal providers
288
+
289
+ Flowsafe providers route polling and webhook deliveries through the thread topology instead of Mastra's in-process registry.
290
+
291
+ `SignalProviderHost` runs one alarm-driven host per tenant. `D1SubscriptionStoreFactory` persists subscriptions. Human-only subscription routes reconcile provider alarms after each committed mutation. Webhook routes verify raw bytes before parsing, derive the tenant from the stored subscription, apply a provider-and-tenant rate cap, and bound forgery audit.
292
+
293
+ `githubSignalProvider()` is the reference provider.
294
+
295
+ Complete wiring is in the [durable-agents guide](https://github.com/ProofOfTechOrg/anchorage/blob/main/docs/durable-agents.md) and [advanced starter](https://github.com/ProofOfTechOrg/anchorage/tree/main/packages/agent-starter).
296
+
297
+ ## Deployment and operations
298
+
299
+ The composed `createFlowsafeWorker()` owns the shared route, scheduled, and Queue pipeline. Hosts inject workflows, identity verification, topology-backed optional routers, budget wrappers, notification transport, artifact pairing, schedule tick, and extra purge duties.
300
+
301
+ Use separate cron expressions for approval SLA sweep, retention purge, and schedule fire. Provider polling uses per-tenant Durable Object alarms.
302
+
303
+ Read:
304
+
305
+ - [Deployment reference](https://github.com/ProofOfTechOrg/anchorage/blob/main/docs/deployment-reference.md)
306
+ - [Operations runbook](https://github.com/ProofOfTechOrg/anchorage/blob/main/docs/operations-runbook.md)
307
+ - [Security threat model](https://github.com/ProofOfTechOrg/anchorage/blob/main/docs/security-threat-model.md)
308
+
309
+ ## Security boundaries
310
+
311
+ Flowsafe does not authenticate users, execute an identity-provider protocol, provide a network sandbox, or decide which business action is safe. It supplies enforcement seams after your host has verified identity and selected policy.
312
+
313
+ Critical host obligations:
314
+
315
+ - derive tenants and actors from verified credentials;
316
+ - mint run, thread, resource, schedule, and subscription identities server-side;
317
+ - keep connector lists and agent resume targets server-authored;
318
+ - persist the original authorized agent requester and resume execution as that principal;
319
+ - expose decisions only through the approval path;
320
+ - configure shared stores for cross-isolate connector budgets;
321
+ - keep raw Durable Object namespaces behind the exported topologies;
322
+ - schedule every enabled domain's retention and offboarding path;
323
+ - protect model, provider, stream-ticket, webhook, and SIEM secrets separately.
324
+
325
+ ## Verification
326
+
327
+ The repository's deterministic workerd spike proves suspend, process restart, resume, forged-resume denial, repeated gates, tenant isolation, live streaming, durable-agent recovery, signals, goals, schedules, providers, notifications, and background-task restart.
328
+
329
+ ```bash
330
+ pnpm --filter @proofoftech/flowsafe spike:verify
195
331
  ```
196
332
 
197
- For a headless integration, drive `useApprovalDashboard(client)` yourself and
198
- render any UI you like. A ready-to-run reference app lives in the repo's
199
- `showcase` package (`packages/showcase/` — `pnpm --filter showcase dev`, or
200
- `pnpm dev` at the root): a full Vite build that injects an
201
- [Astryx](https://astryx.atmeta.com) adapter, bundles that library's CSS, and —
202
- in dev — mounts a live seeded approval-api at `/api/approvals` so
203
- claim/decide/delegate drive real state.
333
+ The optional live-model proof requires `SPIKE_LLM_MODEL_ID` and `SPIKE_LLM_API_KEY`:
204
334
 
205
- ## Multi-tenancy
335
+ ```bash
336
+ pnpm --filter @proofoftech/flowsafe spike:verify:llm
337
+ ```
338
+
339
+ ## License
206
340
 
207
- Three invariants, each enforced at a single chokepoint. Everything else is a
208
- corollary.
209
-
210
- **INV-1 — the run id carries the tenant.** Every `runId` is minted
211
- server-side as `` `${tenantId}_${uuid}` `` from the *authenticated* tenant.
212
- `createRunRouter` rejects a client-supplied `body.runId` with 400,
213
- `RunnerRuntime.start` requires a `runId` (there is no generation fallback),
214
- and the Durable Object refuses any request whose `(workflowId, runId)`
215
- disagrees with its own `ctx.id.name`. Because `runId` is the key everything
216
- else derives from, this makes the Mastra snapshot row, the DO instance, the
217
- per-run lock, the grant-mint predicate, and the R2 key tenant-disjoint with
218
- no schema change and no signature change. Status and resume additionally
219
- check ownership and answer **404** — not 403 — for another tenant's run, so
220
- the route is not an existence oracle.
221
-
222
- **INV-2 — the store is bound to one tenant at construction.** Approval
223
- stores come only from a factory (`D1ApprovalStoreFactory.forTenant()`), and
224
- the bound type carries a `unique symbol` brand: an unbound store, or the
225
- cron-only `SystemApprovalStore`, is a *compile error* wherever a request
226
- handler expects a bound one. `tenantId` is deliberately not a member of
227
- `ApprovalListFilter` — an omissible tenant filter is the canonical fail-open.
228
- Requests flow through a `TenantResolver` (authenticate → validate → bind), so
229
- no pre-auth store exists.
230
-
231
- **INV-3 — the charset makes the prefix exact.** `tenantId` matches
232
- `^[a-z0-9]{3,32}$`. That set contains no character in `[0x5F, 0x60]` —
233
- neither `_` nor `` ` `` — so `runId.startsWith(tenantId + '_')` cannot match
234
- another tenant (`acme` never matches `acmecorp`), and the offboarding range
235
- delete `` run_id >= '<tid>_' AND run_id < '<tid>`' `` selects exactly one
236
- tenant's rows. Loosening the charset silently breaks both; a
237
- character-exhaustive test pins it.
238
-
239
- Consequences worth knowing:
240
-
241
- - **Provision before you issue tokens.** `provisionTenant(db, { tenantId, kind })`
242
- (import from `@proofoftech/flowsafe/host-kit`)
243
- inserts into the `tenants` registry or fails. Nothing else enforces tenant-id
244
- uniqueness, and two clients slugged `acme` would merge entirely.
245
- - **Every actor carries a tenant.** `ApprovalActor` is `{ id, role, tenantId }`;
246
- a bearer-map entry or JWT claim without an INV-3-valid `tenantId` is dropped
247
- and its token 401s. breakwater's own `Actor` stays tenant-agnostic.
248
- - **Connector budgets are per-tenant.** The runtime mints an opaque
249
- `breakwater.isolationScope` on every leg of a tenant-salted run, and
250
- breakwater segments its idempotency and rate-limit keys by it — so one
251
- tenant exhausting a connector's budget cannot throttle another, and two
252
- tenants sharing a business-level idempotency key do not replay each other's
253
- results. Absent scope preserves the single-tenant keys exactly; there is no
254
- flag to forget.
255
- - **Offboarding is one call.** `purgeTenant(db, { tenantId, artifactStore })`
256
- (import from `@proofoftech/flowsafe/do-runner` or the package root)
257
- reaps snapshots of *any* status (a run abandoned at a gate is never eligible
258
- for the terminal-only retention purge), the tenant's agent-memory rows
259
- (threads/messages/resources — salted ids, same exact range predicate), the
260
- tenant's approval records, and its R2 artifacts. Only purge tenants whose
261
- tokens have already expired.
262
- - **Agent-memory ids are tenant-salted.** Mastra memory is keyed by
263
- caller-chosen `threadId`/`resourceId`, which two tenants can legitimately
264
- share. `TenantContext.newThreadId()`/`newResourceId(key)` (and the
265
- underlying `mintThreadId`/`mintResourceId` from
266
- `@proofoftech/flowsafe/do-runner`) are the only constructors: ids are
267
- `${tenantId}_${suffix}`, ownership is an exact prefix check
268
- (`ownsMemoryId`), and hosts never accept a client-supplied memory id. See
269
- `docs/agent-memory-tenancy.md` for the feature-side obligations.
270
-
271
- ### Deployment & ops
272
-
273
- Copy [`deploy/`](deploy/) as a production starting point: a Worker wiring one
274
- DO per run, the D1 approval queue, the tenant resolver over a bearer-token
275
- verifier, an optional subdomain↔tenant cross-check, and a cron trigger that
276
- owns the SLA sweep and snapshot retention purge. `pnpm deploy:dev` runs it on
277
- local workerd (no Cloudflare account); `pnpm deploy:cf` deploys it. Checklist
278
- and configuration table: [`deploy/README.md`](deploy/README.md).
279
-
280
- Audit export ships as a Cloudflare Queues sink + SIEM consumer
281
- (`@proofoftech/flowsafe/audit-export`): `queueAuditSink(env.QUEUE)` plugs into
282
- any breakwater/approval audit sink, and `createAuditQueueConsumer({ endpoint })`
283
- POSTs each batch as NDJSON, acking on 2xx and retrying otherwise. Workflow
284
- artifacts persist to R2 via `R2ArtifactStore`
285
- (`@proofoftech/flowsafe/artifacts`), keyed `workflowId/runId/name`.
286
-
287
- See `docs/flowsafe-architecture.md` and `docs/do-runner-design.md` for design details.
341
+ Apache-2.0.