@powerhousedao/switchboard 6.2.3-dev.9 → 6.2.3-dev.90

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 (306) hide show
  1. package/.tsbuild/test/ai-gateway.test.d.ts +2 -0
  2. package/.tsbuild/test/ai-gateway.test.d.ts.map +1 -0
  3. package/.tsbuild/test/attachments/byte-grants.test.d.ts +2 -0
  4. package/.tsbuild/test/attachments/byte-grants.test.d.ts.map +1 -0
  5. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts +2 -0
  6. package/.tsbuild/test/attachments/byte-routes-read-gate.integration.test.d.ts.map +1 -0
  7. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts +2 -0
  8. package/.tsbuild/test/attachments/reserve-metadata-parity.test.d.ts.map +1 -0
  9. package/.tsbuild/test/attachments/url-signer.test.d.ts +2 -0
  10. package/.tsbuild/test/attachments/url-signer.test.d.ts.map +1 -0
  11. package/.tsbuild/test/boot-auth-config.test.d.ts +2 -0
  12. package/.tsbuild/test/boot-auth-config.test.d.ts.map +1 -0
  13. package/.tsbuild/test/boot-create-signature-policy.test.d.ts +2 -0
  14. package/.tsbuild/test/boot-create-signature-policy.test.d.ts.map +1 -0
  15. package/.tsbuild/test/boot-desktop-auth.test.d.ts +2 -0
  16. package/.tsbuild/test/boot-desktop-auth.test.d.ts.map +1 -0
  17. package/.tsbuild/test/boot-env-isolation.test.d.ts +2 -0
  18. package/.tsbuild/test/boot-env-isolation.test.d.ts.map +1 -0
  19. package/.tsbuild/test/boot-helpers.d.ts +5 -0
  20. package/.tsbuild/test/boot-helpers.d.ts.map +1 -0
  21. package/.tsbuild/test/boot-inspection-enabled.test.d.ts +2 -0
  22. package/.tsbuild/test/boot-inspection-enabled.test.d.ts.map +1 -0
  23. package/.tsbuild/test/boot-mcp-auth.test.d.ts +2 -0
  24. package/.tsbuild/test/boot-mcp-auth.test.d.ts.map +1 -0
  25. package/.tsbuild/test/boot-mcp-enabled.test.d.ts +2 -0
  26. package/.tsbuild/test/boot-mcp-enabled.test.d.ts.map +1 -0
  27. package/.tsbuild/test/boot-port-zero.test.d.ts +2 -0
  28. package/.tsbuild/test/boot-port-zero.test.d.ts.map +1 -0
  29. package/.tsbuild/test/boot-preconditions.test.d.ts +2 -0
  30. package/.tsbuild/test/boot-preconditions.test.d.ts.map +1 -0
  31. package/.tsbuild/test/boot-privacy.test.d.ts +2 -0
  32. package/.tsbuild/test/boot-privacy.test.d.ts.map +1 -0
  33. package/.tsbuild/test/boot-ready-drives.test.d.ts +2 -0
  34. package/.tsbuild/test/boot-ready-drives.test.d.ts.map +1 -0
  35. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts +2 -0
  36. package/.tsbuild/test/boot-unsupported-stored-documents.test.d.ts.map +1 -0
  37. package/.tsbuild/test/boot-without-renown.test.d.ts +2 -0
  38. package/.tsbuild/test/boot-without-renown.test.d.ts.map +1 -0
  39. package/.tsbuild/test/boot-without-require-signatures.test.d.ts +2 -0
  40. package/.tsbuild/test/boot-without-require-signatures.test.d.ts.map +1 -0
  41. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts +2 -0
  42. package/.tsbuild/test/boot-worker-trust-policy.test.d.ts.map +1 -0
  43. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts +2 -0
  44. package/.tsbuild/test/boot-workflow-singleton-conflict.test.d.ts.map +1 -0
  45. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts +2 -0
  46. package/.tsbuild/test/boot-workflow-singleton-retry.test.d.ts.map +1 -0
  47. package/.tsbuild/test/builder-defaults.test.d.ts +2 -0
  48. package/.tsbuild/test/builder-defaults.test.d.ts.map +1 -0
  49. package/.tsbuild/test/config-from-env.test.d.ts +2 -0
  50. package/.tsbuild/test/config-from-env.test.d.ts.map +1 -0
  51. package/.tsbuild/test/config-merge.test.d.ts +2 -0
  52. package/.tsbuild/test/config-merge.test.d.ts.map +1 -0
  53. package/.tsbuild/test/config-schema.test.d.ts +2 -0
  54. package/.tsbuild/test/config-schema.test.d.ts.map +1 -0
  55. package/.tsbuild/test/create-signature-policy.test.d.ts +2 -0
  56. package/.tsbuild/test/create-signature-policy.test.d.ts.map +1 -0
  57. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts +2 -0
  58. package/.tsbuild/test/default-drive-protocol-versions.test.d.ts.map +1 -0
  59. package/.tsbuild/test/default-drive-slug.test.d.ts +2 -0
  60. package/.tsbuild/test/default-drive-slug.test.d.ts.map +1 -0
  61. package/.tsbuild/test/delegated-publish.test.d.ts +2 -0
  62. package/.tsbuild/test/delegated-publish.test.d.ts.map +1 -0
  63. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts +2 -0
  64. package/.tsbuild/test/durable-node-fs-pg16.test.d.ts.map +1 -0
  65. package/.tsbuild/test/fatal-shutdown.test.d.ts +2 -0
  66. package/.tsbuild/test/fatal-shutdown.test.d.ts.map +1 -0
  67. package/.tsbuild/test/inspection-throttle.test.d.ts +2 -0
  68. package/.tsbuild/test/inspection-throttle.test.d.ts.map +1 -0
  69. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts +2 -0
  70. package/.tsbuild/test/keyframe-reclaim-store.test.d.ts.map +1 -0
  71. package/.tsbuild/test/observability-signals.test.d.ts +2 -0
  72. package/.tsbuild/test/observability-signals.test.d.ts.map +1 -0
  73. package/.tsbuild/test/permissions-backfill.test.d.ts +2 -0
  74. package/.tsbuild/test/permissions-backfill.test.d.ts.map +1 -0
  75. package/.tsbuild/test/pglite-preflight.test.d.ts +2 -0
  76. package/.tsbuild/test/pglite-preflight.test.d.ts.map +1 -0
  77. package/.tsbuild/test/pglite-storage-dirs.test.d.ts +2 -0
  78. package/.tsbuild/test/pglite-storage-dirs.test.d.ts.map +1 -0
  79. package/.tsbuild/test/pglite-store.test.d.ts +2 -0
  80. package/.tsbuild/test/pglite-store.test.d.ts.map +1 -0
  81. package/.tsbuild/test/plugin-config-schemas.test.d.ts +2 -0
  82. package/.tsbuild/test/plugin-config-schemas.test.d.ts.map +1 -0
  83. package/.tsbuild/test/plugin-presence.test.d.ts +2 -0
  84. package/.tsbuild/test/plugin-presence.test.d.ts.map +1 -0
  85. package/.tsbuild/test/port-probe.test.d.ts +2 -0
  86. package/.tsbuild/test/port-probe.test.d.ts.map +1 -0
  87. package/.tsbuild/test/processor-timing-log.test.d.ts +2 -0
  88. package/.tsbuild/test/processor-timing-log.test.d.ts.map +1 -0
  89. package/.tsbuild/test/renown-storage-path.test.d.ts +2 -0
  90. package/.tsbuild/test/renown-storage-path.test.d.ts.map +1 -0
  91. package/.tsbuild/test/renown-trust-policy.test.d.ts +2 -0
  92. package/.tsbuild/test/renown-trust-policy.test.d.ts.map +1 -0
  93. package/.tsbuild/test/served-schemas.test.d.ts +2 -0
  94. package/.tsbuild/test/served-schemas.test.d.ts.map +1 -0
  95. package/.tsbuild/test/shutdown.test.d.ts +2 -0
  96. package/.tsbuild/test/shutdown.test.d.ts.map +1 -0
  97. package/.tsbuild/test/snapshot-writer.d.ts +18 -0
  98. package/.tsbuild/test/snapshot-writer.d.ts.map +1 -0
  99. package/.tsbuild/test/store-lock.test.d.ts +2 -0
  100. package/.tsbuild/test/store-lock.test.d.ts.map +1 -0
  101. package/.tsbuild/test/two-switchboards.test.d.ts +2 -0
  102. package/.tsbuild/test/two-switchboards.test.d.ts.map +1 -0
  103. package/.tsbuild/test/unsupported-stored-documents.test.d.ts +2 -0
  104. package/.tsbuild/test/unsupported-stored-documents.test.d.ts.map +1 -0
  105. package/.tsbuild/test/workflow/harness.d.ts +56 -0
  106. package/.tsbuild/test/workflow/harness.d.ts.map +1 -0
  107. package/.tsbuild/test/workflow/oauth-apps-config.test.d.ts +2 -0
  108. package/.tsbuild/test/workflow/oauth-apps-config.test.d.ts.map +1 -0
  109. package/.tsbuild/test/workflow/oauth.test.d.ts +2 -0
  110. package/.tsbuild/test/workflow/oauth.test.d.ts.map +1 -0
  111. package/.tsbuild/test/workflow/resolvers.test.d.ts +2 -0
  112. package/.tsbuild/test/workflow/resolvers.test.d.ts.map +1 -0
  113. package/.tsbuild/test/workflow/runtime-host.test.d.ts +2 -0
  114. package/.tsbuild/test/workflow/runtime-host.test.d.ts.map +1 -0
  115. package/.tsbuild/test/workflow/waitpoint-routes.test.d.ts +2 -0
  116. package/.tsbuild/test/workflow/waitpoint-routes.test.d.ts.map +1 -0
  117. package/.tsbuild/test/workflow/waitpoint-runtime.test.d.ts +2 -0
  118. package/.tsbuild/test/workflow/waitpoint-runtime.test.d.ts.map +1 -0
  119. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts +2 -0
  120. package/.tsbuild/test/workflow/webhook-dedupe.test.d.ts.map +1 -0
  121. package/.tsbuild/test/workflow/webhook-signed.test.d.ts +2 -0
  122. package/.tsbuild/test/workflow/webhook-signed.test.d.ts.map +1 -0
  123. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts +2 -0
  124. package/.tsbuild/test/workflow/webhook-trigger-test.test.d.ts.map +1 -0
  125. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts +2 -0
  126. package/.tsbuild/test/workflow/webhook-unsigned.test.d.ts.map +1 -0
  127. package/.tsbuild/test/workflow-reactor-access.test.d.ts +2 -0
  128. package/.tsbuild/test/workflow-reactor-access.test.d.ts.map +1 -0
  129. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts +2 -0
  130. package/.tsbuild/test/workflow-reactor-enforcement.test.d.ts.map +1 -0
  131. package/.tsbuild/test/workflow-read-gate.test.d.ts +2 -0
  132. package/.tsbuild/test/workflow-read-gate.test.d.ts.map +1 -0
  133. package/.tsbuild/test/workflow-runtime.test.d.ts +2 -0
  134. package/.tsbuild/test/workflow-runtime.test.d.ts.map +1 -0
  135. package/.tsbuild/test/workflows-plugin-config.test.d.ts +2 -0
  136. package/.tsbuild/test/workflows-plugin-config.test.d.ts.map +1 -0
  137. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  138. package/.tsbuild/tsdown.config.d.ts.map +1 -1
  139. package/.tsbuild/vitest.config.d.ts.map +1 -1
  140. package/Auth.md +144 -2
  141. package/CHANGELOG.md +1206 -0
  142. package/README.md +88 -14
  143. package/dist/boot.d.mts +46 -0
  144. package/dist/boot.d.mts.map +1 -0
  145. package/dist/boot.mjs +67 -0
  146. package/dist/boot.mjs.map +1 -0
  147. package/dist/config/from-env.d.mts +15 -0
  148. package/dist/config/from-env.d.mts.map +1 -0
  149. package/dist/config/from-env.mjs +4 -0
  150. package/dist/config/schema.d.mts +3 -0
  151. package/dist/config/schema.mjs +4 -0
  152. package/dist/from-env-DJ4iQ3QZ.mjs +473 -0
  153. package/dist/from-env-DJ4iQ3QZ.mjs.map +1 -0
  154. package/dist/index.d.mts +2 -1
  155. package/dist/index.mjs +84 -84
  156. package/dist/index.mjs.map +1 -1
  157. package/dist/install-packages.d.mts +2 -1
  158. package/dist/install-packages.mjs +2 -2
  159. package/dist/install-packages.mjs.map +1 -1
  160. package/dist/mcp-SsBK14Jm.mjs +32 -0
  161. package/dist/mcp-SsBK14Jm.mjs.map +1 -0
  162. package/dist/migrate.d.mts +2 -1
  163. package/dist/migrate.mjs +7 -5
  164. package/dist/migrate.mjs.map +1 -1
  165. package/dist/plugin-host-BHEUSn9G.d.mts +46 -0
  166. package/dist/plugin-host-BHEUSn9G.d.mts.map +1 -0
  167. package/dist/plugins/ai.d.mts +37 -0
  168. package/dist/plugins/ai.d.mts.map +1 -0
  169. package/dist/plugins/ai.mjs +400 -0
  170. package/dist/plugins/ai.mjs.map +1 -0
  171. package/dist/plugins/attachments.d.mts +33 -0
  172. package/dist/plugins/attachments.d.mts.map +1 -0
  173. package/dist/plugins/attachments.mjs +4 -0
  174. package/dist/plugins/mcp.d.mts +31 -0
  175. package/dist/plugins/mcp.d.mts.map +1 -0
  176. package/dist/plugins/mcp.mjs +4 -0
  177. package/dist/plugins/privacy.d.mts +22 -0
  178. package/dist/plugins/privacy.d.mts.map +1 -0
  179. package/dist/plugins/privacy.mjs +4 -0
  180. package/dist/plugins/workflows.d.mts +79 -0
  181. package/dist/plugins/workflows.d.mts.map +1 -0
  182. package/dist/plugins/workflows.mjs +4 -0
  183. package/dist/postgres-url-DTDhBjXX.mjs +11 -0
  184. package/dist/postgres-url-DTDhBjXX.mjs.map +1 -0
  185. package/dist/privacy-BO8Q25xI.mjs +44 -0
  186. package/dist/privacy-BO8Q25xI.mjs.map +1 -0
  187. package/dist/privacy-DxIJGH4P.mjs +91 -0
  188. package/dist/privacy-DxIJGH4P.mjs.map +1 -0
  189. package/dist/renown-layers-COZsrGQT.mjs +40 -0
  190. package/dist/renown-layers-COZsrGQT.mjs.map +1 -0
  191. package/dist/schema-1yj85yQD.mjs +326 -0
  192. package/dist/schema-1yj85yQD.mjs.map +1 -0
  193. package/dist/schema-ugrJupVH.d.mts +246 -0
  194. package/dist/schema-ugrJupVH.d.mts.map +1 -0
  195. package/dist/server-CgDvrUqE.mjs +2729 -0
  196. package/dist/server-CgDvrUqE.mjs.map +1 -0
  197. package/dist/server.d.mts +129 -189
  198. package/dist/server.d.mts.map +1 -1
  199. package/dist/server.mjs +5 -5
  200. package/dist/types-DzO3_320.d.mts +308 -0
  201. package/dist/types-DzO3_320.d.mts.map +1 -0
  202. package/dist/utils-Cm0TE6dP.mjs +148 -0
  203. package/dist/utils-Cm0TE6dP.mjs.map +1 -0
  204. package/dist/utils.d.mts +30 -5
  205. package/dist/utils.d.mts.map +1 -1
  206. package/dist/utils.mjs +5 -4
  207. package/dist/worker-pool-gyxJnCxA.mjs +304 -0
  208. package/dist/worker-pool-gyxJnCxA.mjs.map +1 -0
  209. package/dist/workflow-runtime-CF5pc8mt.d.mts +33 -0
  210. package/dist/workflow-runtime-CF5pc8mt.d.mts.map +1 -0
  211. package/dist/workflows-C9BQlyT0.mjs +1943 -0
  212. package/dist/workflows-C9BQlyT0.mjs.map +1 -0
  213. package/package.json +85 -24
  214. package/scripts/install-packages.sh +0 -0
  215. package/test/ai-gateway.test.ts +612 -0
  216. package/test/attachment-reference-read-model.test.ts +28 -20
  217. package/test/attachments/auth.test.ts +85 -0
  218. package/test/attachments/byte-grants.test.ts +290 -0
  219. package/test/attachments/byte-routes-read-gate.integration.test.ts +314 -0
  220. package/test/attachments/download-target.test.ts +211 -32
  221. package/test/attachments/index.test.ts +47 -4
  222. package/test/attachments/reserve-metadata-parity.test.ts +96 -0
  223. package/test/attachments/routes-integration.test.ts +60 -4
  224. package/test/attachments/routes.test.ts +297 -35
  225. package/test/attachments/service-config.test.ts +41 -19
  226. package/test/attachments/url-signer.test.ts +105 -0
  227. package/test/boot-auth-config.test.ts +109 -0
  228. package/test/boot-create-signature-policy.test.ts +110 -0
  229. package/test/boot-desktop-auth.test.ts +278 -0
  230. package/test/boot-env-isolation.test.ts +26 -0
  231. package/test/boot-helpers.ts +19 -0
  232. package/test/boot-inspection-enabled.test.ts +140 -0
  233. package/test/boot-mcp-auth.test.ts +449 -0
  234. package/test/boot-mcp-enabled.test.ts +119 -0
  235. package/test/boot-port-zero.test.ts +101 -0
  236. package/test/boot-preconditions.test.ts +213 -0
  237. package/test/boot-privacy.test.ts +232 -0
  238. package/test/boot-ready-drives.test.ts +141 -0
  239. package/test/boot-unsupported-stored-documents.test.ts +214 -0
  240. package/test/boot-without-renown.test.ts +83 -0
  241. package/test/boot-without-require-signatures.test.ts +76 -0
  242. package/test/boot-worker-trust-policy.test.ts +91 -0
  243. package/test/boot-workflow-singleton-conflict.test.ts +109 -0
  244. package/test/boot-workflow-singleton-retry.test.ts +122 -0
  245. package/test/builder-defaults.test.ts +80 -0
  246. package/test/config-from-env.test.ts +942 -0
  247. package/test/config-merge.test.ts +226 -0
  248. package/test/config-schema.test.ts +156 -0
  249. package/test/create-signature-policy.test.ts +69 -0
  250. package/test/default-drive-protocol-versions.test.ts +79 -0
  251. package/test/default-drive-slug.test.ts +265 -0
  252. package/test/delegated-publish.test.ts +435 -0
  253. package/test/durable-node-fs-pg16.test.ts +80 -0
  254. package/test/fatal-shutdown.test.ts +205 -0
  255. package/test/goldens/packages.graphql +797 -0
  256. package/test/goldens/privacy.graphql +853 -0
  257. package/test/goldens/reactor-drive-nodes.graphql +827 -0
  258. package/test/goldens/resolvers.json +327 -0
  259. package/test/goldens/supergraph.graphql +5918 -0
  260. package/test/goldens/workflow-runtime.graphql +1548 -0
  261. package/test/inspection-throttle.test.ts +23 -0
  262. package/test/keyframe-reclaim-store.test.ts +156 -0
  263. package/test/observability-signals.test.ts +131 -0
  264. package/test/permissions-backfill.test.ts +486 -0
  265. package/test/pglite-dialect.test.ts +237 -2
  266. package/test/pglite-preflight.test.ts +313 -0
  267. package/test/pglite-storage-dirs.test.ts +113 -0
  268. package/test/pglite-store.test.ts +441 -0
  269. package/test/pglite-version.test.ts +9 -1
  270. package/test/plugin-config-schemas.test.ts +83 -0
  271. package/test/plugin-presence.test.ts +262 -0
  272. package/test/port-probe.test.ts +45 -0
  273. package/test/processor-timing-log.test.ts +109 -0
  274. package/test/redact-webhook-path.test.ts +9 -0
  275. package/test/renown-storage-path.test.ts +40 -0
  276. package/test/renown-trust-policy.test.ts +313 -0
  277. package/test/served-schemas.test.ts +134 -0
  278. package/test/shutdown.test.ts +278 -0
  279. package/test/snapshot-writer.ts +94 -0
  280. package/test/store-lock.test.ts +65 -0
  281. package/test/two-switchboards.test.ts +146 -0
  282. package/test/unsupported-stored-documents.test.ts +72 -0
  283. package/test/worker-pool.test.ts +27 -1
  284. package/test/workflow/harness.ts +289 -0
  285. package/test/workflow/oauth-apps-config.test.ts +66 -0
  286. package/test/workflow/oauth.test.ts +286 -0
  287. package/test/workflow/resolvers.test.ts +488 -0
  288. package/test/workflow/runtime-host.test.ts +19 -0
  289. package/test/workflow/waitpoint-routes.test.ts +306 -0
  290. package/test/workflow/waitpoint-runtime.test.ts +204 -0
  291. package/test/workflow/webhook-dedupe.test.ts +295 -0
  292. package/test/workflow/webhook-signed.test.ts +509 -0
  293. package/test/workflow/webhook-trigger-test.test.ts +82 -0
  294. package/test/workflow/webhook-unsigned.test.ts +345 -0
  295. package/test/workflow-reactor-access.test.ts +384 -0
  296. package/test/workflow-reactor-enforcement.test.ts +808 -0
  297. package/test/workflow-read-gate.test.ts +213 -0
  298. package/test/workflow-runtime.test.ts +1254 -0
  299. package/test/workflows-plugin-config.test.ts +77 -0
  300. package/tsconfig.json +11 -2
  301. package/tsdown.config.ts +13 -1
  302. package/vitest.config.ts +65 -0
  303. package/dist/server-CiKkVE6g.mjs +0 -1555
  304. package/dist/server-CiKkVE6g.mjs.map +0 -1
  305. package/dist/utils-Baw7rThP.mjs +0 -80
  306. package/dist/utils-Baw7rThP.mjs.map +0 -1
@@ -0,0 +1,1254 @@
1
+ import { PGlite } from "@electric-sql/pglite";
2
+ import { mkdtemp, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import {
6
+ ReactorBuilder,
7
+ ReactorClientBuilder,
8
+ type AttachmentRef,
9
+ type Database,
10
+ type InProcessReactorClientModule,
11
+ type IReadModelCoordinator,
12
+ } from "@powerhousedao/reactor";
13
+ import {
14
+ AuthorizationPolicy,
15
+ BaseSubgraph,
16
+ type CanonicalDocumentId,
17
+ type GraphQLManager,
18
+ type PackagePieceEntry,
19
+ } from "@powerhousedao/reactor-api";
20
+ import {
21
+ PieceRegistry,
22
+ type WorkflowRuntimeService,
23
+ } from "@powerhousedao/reactor-workflow";
24
+ import {
25
+ createRelationalDb,
26
+ type IRelationalDb,
27
+ type IWebhookScope,
28
+ type WebhookSpec,
29
+ } from "@powerhousedao/shared/processors";
30
+ import type { ILogger } from "document-model";
31
+ import { Kysely } from "kysely";
32
+ import { PGliteDialect } from "kysely-pglite-dialect";
33
+ import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
34
+ import { ReadableDocumentsProjection } from "../../../packages/reactor-api/src/services/readable-documents.js";
35
+ import type { startSwitchboard } from "../src/server.mjs";
36
+ import { bootSwitchboard } from "./boot-helpers.js";
37
+ import {
38
+ bindPackagePieces,
39
+ attachmentReadPolicy,
40
+ composeWorkflowRuntime,
41
+ assertWorkflowPackageLoadable,
42
+ hostPrincipalOf,
43
+ indexQueryFor,
44
+ isWorkflowSingletonConflict,
45
+ retryWorkflowSingleton,
46
+ workflowSingletonLossHandler,
47
+ reactorAccessOf,
48
+ type ComposedWorkflowRuntime,
49
+ } from "../src/workflow-runtime.mjs";
50
+
51
+ function stubLogger(): ILogger & {
52
+ info: ReturnType<typeof vi.fn>;
53
+ error: ReturnType<typeof vi.fn>;
54
+ } {
55
+ const logger = {
56
+ verbose: vi.fn(),
57
+ debug: vi.fn(),
58
+ info: vi.fn(),
59
+ warn: vi.fn(),
60
+ error: vi.fn(),
61
+ child: vi.fn(),
62
+ };
63
+ logger.child.mockReturnValue(logger);
64
+ return logger as unknown as ILogger & {
65
+ info: ReturnType<typeof vi.fn>;
66
+ error: ReturnType<typeof vi.fn>;
67
+ };
68
+ }
69
+
70
+ describe("assertWorkflowPackageLoadable", () => {
71
+ it("passes when the package resolves", async () => {
72
+ await expect(
73
+ assertWorkflowPackageLoadable(() => Promise.resolve({})),
74
+ ).resolves.toBeUndefined();
75
+ });
76
+
77
+ it("names the package a host would have to install when the load fails", async () => {
78
+ const cause = new Error("Cannot find module");
79
+ const failing = assertWorkflowPackageLoadable(() => Promise.reject(cause));
80
+ await expect(failing).rejects.toThrow("@powerhousedao/workflow");
81
+ await expect(failing).rejects.toMatchObject({ cause });
82
+ });
83
+ });
84
+
85
+ // The endpoint family as the host's webhook service holds it, in memory.
86
+ function memoryWebhooks() {
87
+ const families: WebhookSpec[] = [];
88
+ const scope: IWebhookScope = {
89
+ hasPublicOrigin: true,
90
+ register: (spec) => {
91
+ families.push(spec);
92
+ return Promise.resolve({
93
+ endpointFor: (key) =>
94
+ Promise.resolve({
95
+ token: key,
96
+ url: `https://hooks.test/${key}`,
97
+ createdAt: new Date().toISOString(),
98
+ }),
99
+ revoke: () => Promise.resolve(),
100
+ list: () => Promise.resolve([]),
101
+ });
102
+ },
103
+ };
104
+ return { families, scope };
105
+ }
106
+
107
+ describe("composeWorkflowRuntime", () => {
108
+ let databases: Kysely<unknown>[] = [];
109
+ let stores: PGlite[] = [];
110
+ let module: InProcessReactorClientModule | undefined;
111
+ let composed: ComposedWorkflowRuntime | undefined;
112
+ // initdb is most of a store's cost (seconds on Windows): once, then copies.
113
+ let template: Blob | undefined;
114
+
115
+ beforeAll(async () => {
116
+ const pg = new PGlite();
117
+ try {
118
+ template = await pg.dumpDataDir("none");
119
+ } finally {
120
+ await pg.close();
121
+ }
122
+ }, 30_000);
123
+
124
+ afterEach(async () => {
125
+ await composed?.stop();
126
+ await module?.reactor.kill().completed;
127
+ for (const database of databases) await database.destroy();
128
+ // Kysely's destroy leaves the PGlite open.
129
+ for (const store of stores) if (!store.closed) await store.close();
130
+ composed = undefined;
131
+ module = undefined;
132
+ databases = [];
133
+ stores = [];
134
+ });
135
+
136
+ function pglite(): Kysely<unknown> {
137
+ const store = new PGlite({ loadDataDir: template });
138
+ stores.push(store);
139
+ const database = new Kysely<unknown>({
140
+ dialect: new PGliteDialect(store),
141
+ });
142
+ databases.push(database);
143
+ return database;
144
+ }
145
+
146
+ async function buildReactorModule(
147
+ coordinator?: IReadModelCoordinator,
148
+ ): Promise<InProcessReactorClientModule> {
149
+ const builder = new ReactorBuilder().withKysely(
150
+ pglite() as unknown as Kysely<Database>,
151
+ );
152
+ if (coordinator) builder.withReadModelCoordinator(coordinator);
153
+ module = await new ReactorClientBuilder()
154
+ .withReactorBuilder(builder)
155
+ .buildModule();
156
+ return module;
157
+ }
158
+
159
+ // The real engine, loaded as production loads it.
160
+ async function compose(
161
+ clientModule: InProcessReactorClientModule,
162
+ overrides: Partial<Parameters<typeof composeWorkflowRuntime>[0]> = {},
163
+ ): Promise<ComposedWorkflowRuntime> {
164
+ composed = await composeWorkflowRuntime({
165
+ reactorClient: clientModule.client,
166
+ clientModule,
167
+ relationalDb: createRelationalDb(pglite()) as IRelationalDb,
168
+ attachments: {} as never,
169
+ authorizationService: {} as never,
170
+ logger: stubLogger(),
171
+ ...overrides,
172
+ });
173
+ return composed;
174
+ }
175
+
176
+ it("lets a step read a ref only through a document its user may read", async () => {
177
+ const ref = `attachment://v1:${"a".repeat(64)}`;
178
+ const asked: unknown[] = [];
179
+ const policy = attachmentReadPolicy(
180
+ {
181
+ canReadAttachment: (request) => {
182
+ asked.push(request);
183
+ return Promise.resolve(
184
+ request.documentId === "doc-b" && request.userAddress === "0xabc"
185
+ ? {
186
+ kind: "allowed",
187
+ documentId: "doc-b" as CanonicalDocumentId,
188
+ ref: request.attachmentRef as AttachmentRef,
189
+ }
190
+ : { kind: "denied" },
191
+ );
192
+ },
193
+ admitCaller: () => Promise.resolve({ kind: "admitted" }),
194
+ },
195
+ 1,
196
+ );
197
+ const runUser = {
198
+ address: "0xabc",
199
+ subject: { address: "0xabc", key: "did:key:z1" },
200
+ };
201
+ expect(
202
+ await policy({
203
+ workflowId: "wf-1",
204
+ ref,
205
+ documentIds: ["doc-a", "doc-b"],
206
+ runUser,
207
+ }),
208
+ ).toBe(true);
209
+ expect(asked[1]).toEqual({
210
+ documentId: "doc-b",
211
+ attachmentRef: ref,
212
+ userAddress: "0xabc",
213
+ appKey: "did:key:z1",
214
+ });
215
+ // No document to read it through, another user, or not a ref: refused.
216
+ expect(
217
+ await policy({ workflowId: "wf-1", ref, documentIds: [], runUser }),
218
+ ).toBe(false);
219
+ expect(
220
+ await policy({
221
+ workflowId: "wf-1",
222
+ ref,
223
+ documentIds: ["doc-b"],
224
+ runUser: null,
225
+ }),
226
+ ).toBe(false);
227
+ expect(
228
+ await policy({
229
+ workflowId: "wf-1",
230
+ ref: "not-a-ref",
231
+ documentIds: ["doc-b"],
232
+ runUser,
233
+ }),
234
+ ).toBe(false);
235
+ expect(
236
+ await attachmentReadPolicy(undefined)({
237
+ workflowId: "wf-1",
238
+ ref,
239
+ documentIds: ["doc-b"],
240
+ runUser,
241
+ }),
242
+ ).toBe(false);
243
+ });
244
+
245
+ it("waits for the reference index to catch up with the triggering operation", async () => {
246
+ const ref = `attachment://v1:${"b".repeat(64)}`;
247
+ let calls = 0;
248
+ const policy = attachmentReadPolicy(
249
+ {
250
+ canReadAttachment: (request) =>
251
+ Promise.resolve(
252
+ ++calls < 3
253
+ ? { kind: "denied" }
254
+ : {
255
+ kind: "allowed",
256
+ documentId: request.documentId as CanonicalDocumentId,
257
+ ref: request.attachmentRef as AttachmentRef,
258
+ },
259
+ ),
260
+ admitCaller: () => Promise.resolve({ kind: "admitted" }),
261
+ },
262
+ 1,
263
+ );
264
+ expect(
265
+ await policy({ workflowId: "wf-1", ref, documentIds: ["doc-a"] }),
266
+ ).toBe(true);
267
+ expect(calls).toBe(3);
268
+ });
269
+
270
+ it("serves a subgraph the GraphQL manager can construct", async () => {
271
+ const { subgraph } = await compose(await buildReactorModule());
272
+
273
+ expect(subgraph.prototype).toBeInstanceOf(BaseSubgraph);
274
+ });
275
+
276
+ it("registers the trigger read model on the reactor's coordinator", async () => {
277
+ const clientModule = await buildReactorModule();
278
+
279
+ const workflows = await compose(clientModule);
280
+
281
+ expect(workflows.triggers).toEqual({ status: "available" });
282
+ expect(
283
+ clientModule.reactorModule!.readModelCoordinator.readModels.filter(
284
+ ({ name }) => name === "workflow-triggers",
285
+ ),
286
+ ).toHaveLength(1);
287
+ });
288
+
289
+ it("reports the intake unavailable on a coordinator without live registration", async () => {
290
+ const customCoordinator: IReadModelCoordinator = {
291
+ readModels: [],
292
+ start: vi.fn(),
293
+ stop: vi.fn(),
294
+ drain: vi.fn().mockResolvedValue(undefined),
295
+ getChainDepth: vi.fn().mockReturnValue(0),
296
+ };
297
+
298
+ const workflows = await compose(
299
+ await buildReactorModule(customCoordinator),
300
+ );
301
+
302
+ expect(workflows.triggers).toEqual({
303
+ status: "unavailable",
304
+ reason: "live-read-model-registration-unsupported",
305
+ });
306
+ expect(customCoordinator.readModels).toEqual([]);
307
+ });
308
+
309
+ it("reports the intake unavailable without an in-process reactor", async () => {
310
+ const clientModule = await buildReactorModule();
311
+
312
+ const workflows = await compose(clientModule, {
313
+ clientModule: {} as InProcessReactorClientModule,
314
+ });
315
+
316
+ expect(workflows.triggers).toEqual({
317
+ status: "unavailable",
318
+ reason: "in-process-reactor-module-unavailable",
319
+ });
320
+ });
321
+
322
+ it("arms the webhooks and the supervisor on start, and stops them once", async () => {
323
+ const webhooks = memoryWebhooks();
324
+ const clientModule = await buildReactorModule();
325
+ // Intervals only, from here on: the singleton lease's heartbeat and the
326
+ // run-retention sweep from compose, then the supervisor's tick and the
327
+ // PENDING-run sweep.
328
+ vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
329
+ try {
330
+ const workflows = await compose(clientModule, {
331
+ webhooks: webhooks.scope,
332
+ });
333
+ expect(vi.getTimerCount()).toBe(2);
334
+
335
+ await workflows.start();
336
+
337
+ expect(webhooks.families.map(({ name }) => name)).toEqual(["trigger"]);
338
+ // The real runtime answers for it: an unknown workflow is not armed.
339
+ await expect(
340
+ webhooks.families[0]!.policyFor?.("wf-unknown"),
341
+ ).resolves.toBeUndefined();
342
+ expect(vi.getTimerCount()).toBe(4);
343
+
344
+ await workflows.stop();
345
+ await workflows.stop();
346
+
347
+ expect(vi.getTimerCount()).toBe(0);
348
+ } finally {
349
+ vi.useRealTimers();
350
+ }
351
+ });
352
+
353
+ it("names the package a host would have to install when the load fails", async () => {
354
+ const cause = new Error("Cannot find module");
355
+ const failing = compose(await buildReactorModule(), {
356
+ load: () => Promise.reject(cause),
357
+ });
358
+
359
+ await expect(failing).rejects.toThrow("@powerhousedao/reactor-workflow");
360
+ await expect(failing).rejects.toMatchObject({ cause });
361
+ });
362
+
363
+ // Placement (plan agreed decision 3): the claim is taken before the runtime
364
+ // exists and released on the way out. Distinct storage ids give the two
365
+ // composes distinct owner names, as two hosts would have.
366
+ function composeSecond(
367
+ clientModule: InProcessReactorClientModule,
368
+ relationalDb: IRelationalDb,
369
+ ): Promise<ComposedWorkflowRuntime> {
370
+ return composeWorkflowRuntime({
371
+ reactorClient: clientModule.client,
372
+ clientModule: {} as InProcessReactorClientModule,
373
+ relationalDb,
374
+ attachments: {} as never,
375
+ authorizationService: {} as never,
376
+ logger: stubLogger(),
377
+ storageId: "/srv/slot-b",
378
+ });
379
+ }
380
+
381
+ it("claims the workflow singleton and refuses a second owner until it is released", async () => {
382
+ const clientModule = await buildReactorModule();
383
+ const relationalDb = createRelationalDb(pglite()) as IRelationalDb;
384
+ const first = await compose(clientModule, {
385
+ relationalDb,
386
+ storageId: "/srv/slot-a",
387
+ });
388
+ expect(first.singletonOwner).toBeDefined();
389
+
390
+ const refused = await composeSecond(clientModule, relationalDb).catch(
391
+ (error: unknown) => error,
392
+ );
393
+ expect(isWorkflowSingletonConflict(refused)).toBe(true);
394
+
395
+ await first.stop();
396
+ const second = await composeSecond(clientModule, relationalDb);
397
+ try {
398
+ expect(second.singletonOwner).toBeDefined();
399
+ expect(second.singletonOwner).not.toBe(first.singletonOwner);
400
+ } finally {
401
+ await second.stop();
402
+ }
403
+ });
404
+
405
+ it("hands the claim back when composing fails after it", async () => {
406
+ const clientModule = await buildReactorModule();
407
+ const relationalDb = createRelationalDb(pglite()) as IRelationalDb;
408
+ const engine = await import("@powerhousedao/reactor-workflow");
409
+
410
+ await expect(
411
+ compose(clientModule, {
412
+ relationalDb,
413
+ storageId: "/srv/slot-a",
414
+ load: () =>
415
+ Promise.resolve({
416
+ ...engine,
417
+ createWorkflowRuntime: () => {
418
+ throw new Error("the runtime could not be built");
419
+ },
420
+ }),
421
+ }),
422
+ ).rejects.toThrow("the runtime could not be built");
423
+
424
+ const next = await composeSecond(clientModule, relationalDb);
425
+ try {
426
+ expect(next.singletonOwner).toBeDefined();
427
+ } finally {
428
+ await next.stop();
429
+ }
430
+ });
431
+
432
+ // A rolling deploy under one stable owner name: the next pod's claim wins,
433
+ // and this one must stop running workflows rather than become a second
434
+ // writer. There is no re-claim; it stays down until restarted.
435
+ it("shuts the runtime down when a newer claim takes the singleton", async () => {
436
+ const clientModule = await buildReactorModule();
437
+ const relationalDb = createRelationalDb(pglite()) as IRelationalDb;
438
+ const engine = await import("@powerhousedao/reactor-workflow");
439
+ const lost = vi.fn();
440
+ let newer:
441
+ | Awaited<ReturnType<typeof engine.acquireWorkflowSingletonLease>>
442
+ | undefined;
443
+ // The lease measures its silence on performance.now().
444
+ vi.useFakeTimers({
445
+ toFake: ["setInterval", "clearInterval", "performance"],
446
+ });
447
+ try {
448
+ const workflows = await compose(clientModule, {
449
+ relationalDb,
450
+ storageId: "/srv/slot-a",
451
+ onSingletonLost: lost,
452
+ });
453
+ await workflows.start();
454
+ expect(workflows.triggers).toEqual({ status: "available" });
455
+
456
+ // The older holder went quiet, so its own slot may take over.
457
+ const leaseDb = await relationalDb.createNamespace<{
458
+ workflow_singleton: { heartbeat_at: Date };
459
+ }>("workflow_runtime");
460
+ await leaseDb
461
+ .updateTable("workflow_singleton")
462
+ .set({ heartbeat_at: new Date(Date.now() - 3_600_000) })
463
+ .execute();
464
+ newer = await engine.acquireWorkflowSingletonLease({
465
+ relationalDb,
466
+ storageId: "/srv/slot-a",
467
+ logger: stubLogger(),
468
+ });
469
+ expect(newer.owner).toBe(workflows.singletonOwner);
470
+
471
+ await vi.advanceTimersByTimeAsync(engine.SINGLETON_HEARTBEAT_MS);
472
+ await vi.waitFor(() =>
473
+ expect(lost).toHaveBeenCalledWith({
474
+ reason: "taken",
475
+ heldBy: newer!.owner,
476
+ }),
477
+ );
478
+ expect(lost).toHaveBeenCalledTimes(1);
479
+ expect(workflows.triggers).toEqual({
480
+ status: "unavailable",
481
+ reason: "workflow-singleton-lost",
482
+ });
483
+ // Only the newer claim's heartbeat is left running.
484
+ expect(vi.getTimerCount()).toBe(1);
485
+
486
+ await workflows.start();
487
+ expect(vi.getTimerCount()).toBe(1);
488
+
489
+ await workflows.stop();
490
+ expect(await newer.heartbeat()).toBe(true);
491
+ } finally {
492
+ await newer?.release();
493
+ vi.useRealTimers();
494
+ }
495
+ });
496
+
497
+ it("shuts the runtime down before handing the claim back when composing fails", async () => {
498
+ const clientModule = await buildReactorModule();
499
+ const relationalDb = createRelationalDb(pglite()) as IRelationalDb;
500
+ const engine = await import("@powerhousedao/reactor-workflow");
501
+ const shutdowns: ReturnType<typeof vi.fn>[] = [];
502
+
503
+ await expect(
504
+ compose(clientModule, {
505
+ relationalDb,
506
+ storageId: "/srv/slot-a",
507
+ load: () =>
508
+ Promise.resolve({
509
+ ...engine,
510
+ createWorkflowRuntime: (host) => {
511
+ const runtime = engine.createWorkflowRuntime(host);
512
+ shutdowns.push(vi.spyOn(runtime, "shutdown"));
513
+ return runtime;
514
+ },
515
+ WorkflowTriggersReadModel: class {
516
+ constructor() {
517
+ throw new Error("the read model could not be built");
518
+ }
519
+ } as never,
520
+ }),
521
+ }),
522
+ ).rejects.toThrow("the read model could not be built");
523
+
524
+ expect(shutdowns).toHaveLength(1);
525
+ expect(shutdowns[0]).toHaveBeenCalledOnce();
526
+ const next = await composeSecond(clientModule, relationalDb);
527
+ await next.stop();
528
+ });
529
+
530
+ const triggerModels = (clientModule: InProcessReactorClientModule) =>
531
+ clientModule.reactorModule!.readModelCoordinator.readModels.filter(
532
+ ({ name }) => name === "workflow-triggers",
533
+ );
534
+
535
+ // The retry path composes again in the same process, against the same
536
+ // coordinator: a registration the failed attempt left behind blocks it.
537
+ it("composes again after a compose that failed past registering the trigger read model", async () => {
538
+ const clientModule = await buildReactorModule();
539
+ const relationalDb = createRelationalDb(pglite()) as IRelationalDb;
540
+
541
+ await expect(
542
+ compose(clientModule, {
543
+ relationalDb,
544
+ http: {
545
+ baseUrl: "https://host.test/workflow",
546
+ get: () => {
547
+ throw new Error("the callback route could not be mounted");
548
+ },
549
+ } as never,
550
+ }),
551
+ ).rejects.toThrow("the callback route could not be mounted");
552
+ expect(triggerModels(clientModule)).toHaveLength(0);
553
+
554
+ const again = await compose(clientModule, { relationalDb });
555
+ expect(again.triggers).toEqual({ status: "available" });
556
+ expect(triggerModels(clientModule)).toHaveLength(1);
557
+ });
558
+
559
+ it("registers no trigger read model when the lease is lost while it initialises", async () => {
560
+ const clientModule = await buildReactorModule();
561
+ const relationalDb = createRelationalDb(pglite()) as IRelationalDb;
562
+ const engine = await import("@powerhousedao/reactor-workflow");
563
+ let onLost:
564
+ | ((loss: { reason: "unrenewable"; silentMs: number }) => void)
565
+ | undefined;
566
+ class LosingReadModel extends engine.WorkflowTriggersReadModel {
567
+ override async init(): Promise<void> {
568
+ onLost?.({ reason: "unrenewable", silentMs: 30_000 });
569
+ await super.init();
570
+ }
571
+ }
572
+
573
+ await expect(
574
+ compose(clientModule, {
575
+ relationalDb,
576
+ load: () =>
577
+ Promise.resolve({
578
+ ...engine,
579
+ WorkflowTriggersReadModel: LosingReadModel,
580
+ acquireWorkflowSingletonLease: (options) => {
581
+ onLost = options.onLost as typeof onLost;
582
+ return engine.acquireWorkflowSingletonLease(options);
583
+ },
584
+ }),
585
+ }),
586
+ ).rejects.toMatchObject({ name: "WorkflowSingletonConflictError" });
587
+ expect(triggerModels(clientModule)).toHaveLength(0);
588
+
589
+ const again = await compose(clientModule, { relationalDb });
590
+ expect(triggerModels(clientModule)).toHaveLength(1);
591
+ await again.stop();
592
+ expect(triggerModels(clientModule)).toHaveLength(0);
593
+ });
594
+
595
+ // Embedded PGlite: no other process can open the journal, so the lease must
596
+ // not turn workflows off over a stalled renewal.
597
+ it("lets the lease fence itself only over a journal others can open", async () => {
598
+ const engine = await import("@powerhousedao/reactor-workflow");
599
+ const selfFence: (boolean | undefined)[] = [];
600
+ const exclusive: (boolean | undefined)[] = [];
601
+ const load = () =>
602
+ Promise.resolve({
603
+ ...engine,
604
+ acquireWorkflowSingletonLease: (
605
+ options: Parameters<typeof engine.acquireWorkflowSingletonLease>[0],
606
+ ) => {
607
+ selfFence.push(options.selfFence);
608
+ exclusive.push(options.exclusive);
609
+ return engine.acquireWorkflowSingletonLease(options);
610
+ },
611
+ });
612
+
613
+ for (const exclusiveJournal of [true, false]) {
614
+ const composed = await compose(await buildReactorModule(), {
615
+ relationalDb: createRelationalDb(pglite()) as IRelationalDb,
616
+ exclusiveJournal,
617
+ load,
618
+ });
619
+ await composed.stop();
620
+ }
621
+
622
+ expect(selfFence).toEqual([false, true]);
623
+ expect(exclusive).toEqual([true, false]);
624
+ // Two reactors and two PGlite stores: past 5s on a Windows runner
625
+ }, 30_000);
626
+
627
+ it("opens no journal when the lease is lost before the runtime exists", async () => {
628
+ const clientModule = await buildReactorModule();
629
+ const relationalDb = createRelationalDb(pglite()) as IRelationalDb;
630
+ const engine = await import("@powerhousedao/reactor-workflow");
631
+ const createWorkflowRuntime = vi.fn(engine.createWorkflowRuntime);
632
+
633
+ const composing = compose(clientModule, {
634
+ relationalDb,
635
+ load: () =>
636
+ Promise.resolve({
637
+ ...engine,
638
+ createWorkflowRuntime,
639
+ acquireWorkflowSingletonLease: async (options) => {
640
+ const lease = await engine.acquireWorkflowSingletonLease(options);
641
+ options.onLost?.({ reason: "taken", heldBy: "thief" });
642
+ return lease;
643
+ },
644
+ }),
645
+ });
646
+
647
+ await expect(composing).rejects.toMatchObject({
648
+ name: "WorkflowSingletonConflictError",
649
+ owner: "thief",
650
+ });
651
+ expect(createWorkflowRuntime).not.toHaveBeenCalled();
652
+ });
653
+
654
+ // A rolling deploy whose slots have different owner names: the new pod is
655
+ // refused while the old one holds the lease, and must pick workflows up
656
+ // once the old pod releases it rather than leave nobody running them.
657
+ it("composes a refused host once the holder releases the singleton", async () => {
658
+ const clientModule = await buildReactorModule();
659
+ const relationalDb = createRelationalDb(pglite()) as IRelationalDb;
660
+ const holder = await compose(clientModule, {
661
+ relationalDb,
662
+ storageId: "/srv/slot-a",
663
+ });
664
+ const onComposed = vi.fn(() => Promise.resolve());
665
+ const retry = retryWorkflowSingleton({
666
+ compose: () => composeSecond(clientModule, relationalDb),
667
+ onComposed,
668
+ logger: stubLogger(),
669
+ intervalMs: 20,
670
+ });
671
+ try {
672
+ await new Promise((resolve) => setTimeout(resolve, 150));
673
+ expect(onComposed).not.toHaveBeenCalled();
674
+
675
+ await holder.stop();
676
+
677
+ await vi.waitFor(() => expect(onComposed).toHaveBeenCalledOnce());
678
+ const [taken] = onComposed.mock.calls[0] as unknown as [
679
+ ComposedWorkflowRuntime,
680
+ ];
681
+ expect(taken.singletonOwner).not.toBe(holder.singletonOwner);
682
+ await taken.stop();
683
+ } finally {
684
+ await retry.stop();
685
+ }
686
+ });
687
+
688
+ // Each claim builds its own runtime, so park state seeded under an earlier
689
+ // claim never outlives the gap in which another holder wrote.
690
+ it("reads the parks another holder wrote when it claims again", async () => {
691
+ const clientModule = await buildReactorModule();
692
+ const relationalDb = createRelationalDb(pglite()) as IRelationalDb;
693
+ const engine = await import("@powerhousedao/reactor-workflow");
694
+ const runtimes: WorkflowRuntimeService[] = [];
695
+ const claim = (storageId: string) =>
696
+ composeWorkflowRuntime({
697
+ reactorClient: clientModule.client,
698
+ clientModule: {} as InProcessReactorClientModule,
699
+ relationalDb,
700
+ attachments: {} as never,
701
+ authorizationService: {} as never,
702
+ logger: stubLogger(),
703
+ storageId,
704
+ load: () =>
705
+ Promise.resolve({
706
+ ...engine,
707
+ createWorkflowRuntime: (host) => {
708
+ const runtime = engine.createWorkflowRuntime(host);
709
+ runtimes.push(runtime);
710
+ return runtime;
711
+ },
712
+ }),
713
+ });
714
+ const parkOf = (runtime: WorkflowRuntimeService) =>
715
+ (
716
+ runtime as unknown as {
717
+ parks: { get(id: string): Promise<unknown> };
718
+ }
719
+ ).parks.get("wf-gap");
720
+
721
+ const first = await claim("/srv/slot-a");
722
+ expect(await parkOf(runtimes[0]!)).toBeUndefined();
723
+ await first.stop();
724
+
725
+ const other = await claim("/srv/slot-b");
726
+ await (await runtimes[1]!.store())!.parkWorkflow(
727
+ "wf-gap",
728
+ 1,
729
+ "parked by the other holder",
730
+ );
731
+ await other.stop();
732
+
733
+ const again = await claim("/srv/slot-a");
734
+ try {
735
+ expect(runtimes[2]).not.toBe(runtimes[0]);
736
+ expect(await parkOf(runtimes[2]!)).toMatchObject({
737
+ reason: "parked by the other holder",
738
+ });
739
+ } finally {
740
+ await again.stop();
741
+ }
742
+ });
743
+
744
+ it("stops retrying the claim when the host stops", async () => {
745
+ const clientModule = await buildReactorModule();
746
+ const relationalDb = createRelationalDb(pglite()) as IRelationalDb;
747
+ const holder = await compose(clientModule, {
748
+ relationalDb,
749
+ storageId: "/srv/slot-a",
750
+ });
751
+ const onComposed = vi.fn(() => Promise.resolve());
752
+ const retry = retryWorkflowSingleton({
753
+ compose: () => composeSecond(clientModule, relationalDb),
754
+ onComposed,
755
+ logger: stubLogger(),
756
+ intervalMs: 20,
757
+ });
758
+ await new Promise((resolve) => setTimeout(resolve, 60));
759
+
760
+ await retry.stop();
761
+ await holder.stop();
762
+ await new Promise((resolve) => setTimeout(resolve, 150));
763
+
764
+ expect(onComposed).not.toHaveBeenCalled();
765
+ });
766
+
767
+ it("claims again when starting the composed runtime fails", async () => {
768
+ const unhandled: unknown[] = [];
769
+ const capture = (reason: unknown) => {
770
+ unhandled.push(reason);
771
+ };
772
+ process.on("unhandledRejection", capture);
773
+ const runtimes = [
774
+ { stop: vi.fn() } as unknown as ComposedWorkflowRuntime,
775
+ { stop: vi.fn() } as unknown as ComposedWorkflowRuntime,
776
+ ];
777
+ const compose = vi
778
+ .fn<() => Promise<ComposedWorkflowRuntime>>()
779
+ .mockResolvedValueOnce(runtimes[0]!)
780
+ .mockResolvedValueOnce(runtimes[1]!);
781
+ const onComposed = vi
782
+ .fn<(workflows: ComposedWorkflowRuntime) => Promise<void>>()
783
+ .mockRejectedValueOnce(new Error("start failed"))
784
+ .mockResolvedValueOnce(undefined);
785
+ const logger = stubLogger();
786
+ const retry = retryWorkflowSingleton({
787
+ compose,
788
+ onComposed,
789
+ logger,
790
+ intervalMs: 20,
791
+ });
792
+ try {
793
+ await vi.waitFor(() => expect(onComposed).toHaveBeenCalledTimes(2));
794
+ expect(onComposed).toHaveBeenLastCalledWith(runtimes[1]);
795
+ await new Promise((resolve) => setImmediate(resolve));
796
+ expect(unhandled).toEqual([]);
797
+ expect(logger.error).toHaveBeenCalled();
798
+ } finally {
799
+ await retry.stop();
800
+ process.off("unhandledRejection", capture);
801
+ }
802
+ });
803
+
804
+ it("composes without a claim only when the host opts out", async () => {
805
+ const clientModule = await buildReactorModule();
806
+ const relationalDb = createRelationalDb(pglite()) as IRelationalDb;
807
+
808
+ const unclaimed = await compose(clientModule, {
809
+ relationalDb,
810
+ singletonLease: false,
811
+ });
812
+ expect(unclaimed.singletonOwner).toBeUndefined();
813
+
814
+ // Nothing was claimed, so a host that does claim takes it at once.
815
+ const claimed = await composeSecond(clientModule, relationalDb);
816
+ try {
817
+ expect(claimed.singletonOwner).toBeDefined();
818
+ } finally {
819
+ await claimed.stop();
820
+ }
821
+ });
822
+ });
823
+
824
+ describe("the host's answer to losing the workflow singleton", () => {
825
+ it("stays without workflows, naming the holder, when another claim took it", () => {
826
+ const logger = stubLogger();
827
+ const fatal = vi.fn(() => true);
828
+
829
+ workflowSingletonLossHandler(
830
+ logger,
831
+ fatal,
832
+ )({
833
+ reason: "taken",
834
+ heldBy: "switchboard-1",
835
+ });
836
+
837
+ expect(fatal).not.toHaveBeenCalled();
838
+ const logged = vi
839
+ .mocked(logger.error)
840
+ .mock.calls.map(([line]) => String(line));
841
+ expect(logged.join("\n")).toContain('Another process ("switchboard-1")');
842
+ });
843
+
844
+ // Nobody else runs workflows after a database blip: going down lets the
845
+ // supervisor restart the process, which re-claims at boot.
846
+ it("goes through the fatal shutdown when no takeover was seen", () => {
847
+ const logger = stubLogger();
848
+ const fatal = vi.fn(() => true);
849
+
850
+ workflowSingletonLossHandler(
851
+ logger,
852
+ fatal,
853
+ )({
854
+ reason: "unrenewable",
855
+ silentMs: 30_000,
856
+ });
857
+
858
+ expect(fatal).toHaveBeenCalledOnce();
859
+ const [, error] = fatal.mock.calls[0] as unknown as [string, Error];
860
+ expect(error.message).toContain("no other process was seen");
861
+ expect(error.message).not.toContain("Another process");
862
+ });
863
+
864
+ it("says a restart is needed when no fatal shutdown is installed", () => {
865
+ const logger = stubLogger();
866
+
867
+ workflowSingletonLossHandler(
868
+ logger,
869
+ () => false,
870
+ )({
871
+ reason: "unrenewable",
872
+ silentMs: 30_000,
873
+ });
874
+
875
+ const logged = vi
876
+ .mocked(logger.error)
877
+ .mock.calls.map(([line]) => String(line));
878
+ expect(logged.join("\n")).toContain("until it is restarted");
879
+ expect(logged.join("\n")).not.toContain("Another process");
880
+ });
881
+ });
882
+
883
+ describe("the host's reactor access", () => {
884
+ const signer = { app: { key: "did:key:zHost" }, user: { address: "0xhost" } };
885
+ const moduleWith = (flags?: Record<string, boolean>) =>
886
+ ({
887
+ signer,
888
+ reactorModule: flags ? { featureFlags: flags } : undefined,
889
+ }) as unknown as InProcessReactorClientModule;
890
+
891
+ it("grants the host by key under auth conditions, else by address", () => {
892
+ const byKey = reactorAccessOf(
893
+ moduleWith({ authEnforcement: true, authConditions: true }),
894
+ );
895
+ expect(byKey).toEqual({
896
+ authEnforcement: true,
897
+ authConditions: true,
898
+ identity: { address: "0xhost", key: "did:key:zHost" },
899
+ });
900
+ expect(hostPrincipalOf(byKey)).toEqual({
901
+ match: { eq: [{ attr: "subject.key" }, { lit: "did:key:zHost" }] },
902
+ });
903
+
904
+ const byAddress = reactorAccessOf(
905
+ moduleWith({ authEnforcement: false, authConditions: false }),
906
+ );
907
+ expect(byAddress.authEnforcement).toBe(false);
908
+ expect(hostPrincipalOf(byAddress)).toEqual({ address: "0xhost" });
909
+ });
910
+
911
+ it("reads unknown flags as enforced and a keyless signer as no identity", () => {
912
+ const access = reactorAccessOf({
913
+ signer: {},
914
+ reactorModule: undefined,
915
+ } as unknown as InProcessReactorClientModule);
916
+ expect(access).toEqual({
917
+ authEnforcement: true,
918
+ authConditions: false,
919
+ identity: null,
920
+ });
921
+ expect(hostPrincipalOf(access)).toBeUndefined();
922
+ });
923
+ });
924
+
925
+ describe("a piece's index query through the host", () => {
926
+ const signer = {
927
+ app: { key: "did:key:zHost" },
928
+ user: { address: "0xhost", chainId: 5, networkId: "eip155" },
929
+ };
930
+ const request = {
931
+ subgraph: "key-index",
932
+ query: "{ keyIndex { find { key } } }",
933
+ variables: { k: ["a"] },
934
+ };
935
+ const manager = () => ({
936
+ executeSubgraph: vi.fn().mockResolvedValue({ data: { keyIndex: {} } }),
937
+ });
938
+ const sentUser = (m: ReturnType<typeof manager>) =>
939
+ (m.executeSubgraph.mock.calls[0] as [string, { user?: unknown }])[1].user;
940
+
941
+ it("asks as the run user on the host's chain, with the user's key", async () => {
942
+ const m = manager();
943
+ const query = indexQueryFor(m, {
944
+ signer,
945
+ } as unknown as InProcessReactorClientModule);
946
+ const result = await query(request, {
947
+ address: "0xrun",
948
+ subject: { address: "0xrun", key: "did:key:zRun" },
949
+ });
950
+ expect(result).toEqual({ data: { keyIndex: {} } });
951
+ expect(m.executeSubgraph).toHaveBeenCalledWith("key-index", {
952
+ query: request.query,
953
+ variables: request.variables,
954
+ user: {
955
+ address: "0xrun",
956
+ chainId: 5,
957
+ networkId: "eip155",
958
+ appKey: "did:key:zRun",
959
+ },
960
+ });
961
+ });
962
+
963
+ it("asks as the host itself for a run with no user, and anonymously without an identity", async () => {
964
+ const m = manager();
965
+ await indexQueryFor(m, {
966
+ signer,
967
+ } as unknown as InProcessReactorClientModule)(request, null);
968
+ expect(sentUser(m)).toEqual({
969
+ address: "0xhost",
970
+ chainId: 5,
971
+ networkId: "eip155",
972
+ appKey: "did:key:zHost",
973
+ });
974
+
975
+ const anonymous = manager();
976
+ await indexQueryFor(anonymous, {
977
+ signer: { app: { key: "did:key:zHost" }, user: {} },
978
+ } as unknown as InProcessReactorClientModule)(request, null);
979
+ expect(sentUser(anonymous)).toBeUndefined();
980
+ });
981
+
982
+ describe("a caller the policy gives no rows", () => {
983
+ const adminOnly = (admins: string[]) => ({
984
+ config: {
985
+ admins,
986
+ defaultProtection: false,
987
+ policy: AuthorizationPolicy.ADMIN_ONLY,
988
+ },
989
+ isSupremeAdmin: (address?: string) =>
990
+ address !== undefined && admins.includes(address),
991
+ });
992
+ const runUser = {
993
+ address: "0xrun",
994
+ subject: { address: "0xrun", key: "did:key:zRun" },
995
+ };
996
+ const module = { signer } as unknown as InProcessReactorClientModule;
997
+
998
+ it("refuses a granter who is no longer an admin, rather than answer nothing", async () => {
999
+ const m = manager();
1000
+ const result = await indexQueryFor(
1001
+ m,
1002
+ module,
1003
+ adminOnly(["0xother"]),
1004
+ )(request, runUser);
1005
+ expect(m.executeSubgraph).not.toHaveBeenCalled();
1006
+ expect(result.data).toBeNull();
1007
+ expect(result.errors?.[0].message).toMatch(
1008
+ /0xrun is not an admin of this host/,
1009
+ );
1010
+ });
1011
+
1012
+ it("refuses a run with nobody behind it", async () => {
1013
+ const m = manager();
1014
+ const anonymous = {
1015
+ signer: { app: { key: "did:key:zHost" }, user: {} },
1016
+ } as unknown as InProcessReactorClientModule;
1017
+ const result = await indexQueryFor(
1018
+ m,
1019
+ anonymous,
1020
+ adminOnly(["0xother"]),
1021
+ )(request, null);
1022
+ expect(m.executeSubgraph).not.toHaveBeenCalled();
1023
+ expect(result.errors?.[0].message).toMatch(/no person behind it/);
1024
+ });
1025
+
1026
+ // The real filter an index answers with, over the rows of a store.
1027
+ it("finds an existing document for a delegated run, and refuses once the granter left", async () => {
1028
+ const admins = ["0xrun"];
1029
+ const config = {
1030
+ admins,
1031
+ defaultProtection: false,
1032
+ policy: AuthorizationPolicy.ADMIN_ONLY,
1033
+ };
1034
+ const readable = new ReadableDocumentsProjection({
1035
+ config,
1036
+ } as unknown as ConstructorParameters<
1037
+ typeof ReadableDocumentsProjection
1038
+ >[0]);
1039
+ const executeSubgraph = vi.fn(
1040
+ (
1041
+ _name: string,
1042
+ { user }: { user?: { address: string } },
1043
+ ): Promise<{ data: Record<string, unknown> }> => {
1044
+ const seen = readable.filterFor(user?.address).kind === "all";
1045
+ return Promise.resolve({
1046
+ data: {
1047
+ keyIndex: {
1048
+ find: seen ? [{ key: "gmail:1", documentId: "d1" }] : [],
1049
+ },
1050
+ },
1051
+ });
1052
+ },
1053
+ );
1054
+ const delegated = {
1055
+ address: "0xrun",
1056
+ subject: { address: "0xrun", key: "did:key:zDelegate" },
1057
+ };
1058
+ const query = indexQueryFor({ executeSubgraph }, module, {
1059
+ config,
1060
+ isSupremeAdmin: (address?: string) =>
1061
+ address !== undefined && admins.includes(address),
1062
+ });
1063
+
1064
+ expect(await query(request, delegated)).toEqual({
1065
+ data: { keyIndex: { find: [{ key: "gmail:1", documentId: "d1" }] } },
1066
+ });
1067
+
1068
+ // Removed from ADMINS: an empty answer here would duplicate everything.
1069
+ admins.length = 0;
1070
+ admins.push("0xother");
1071
+ const refused = await query(request, delegated);
1072
+ expect(refused.data).toBeNull();
1073
+ expect(refused.errors).toHaveLength(1);
1074
+ expect(executeSubgraph).toHaveBeenCalledOnce();
1075
+ });
1076
+
1077
+ it("lets an admin read", async () => {
1078
+ const m = manager();
1079
+ await indexQueryFor(m, module, adminOnly(["0xrun"]))(request, runUser);
1080
+ expect(m.executeSubgraph).toHaveBeenCalledOnce();
1081
+ });
1082
+
1083
+ it.each([
1084
+ AuthorizationPolicy.OPEN,
1085
+ AuthorizationPolicy.DOCUMENT_PERMISSIONS,
1086
+ ])("leaves %s to the index's own filter", async (policy) => {
1087
+ const m = manager();
1088
+ await indexQueryFor(m, module, {
1089
+ ...adminOnly([]),
1090
+ config: { admins: [], defaultProtection: false, policy },
1091
+ })(request, runUser);
1092
+ expect(m.executeSubgraph).toHaveBeenCalledOnce();
1093
+ });
1094
+ });
1095
+
1096
+ it("hands the subgraph's errors back as messages", async () => {
1097
+ const m = {
1098
+ executeSubgraph: vi.fn().mockResolvedValue({
1099
+ data: null,
1100
+ errors: [{ message: "nope", extensions: { code: "X" } }],
1101
+ }),
1102
+ };
1103
+ const result = await indexQueryFor(m, undefined)(request, null);
1104
+ expect(result).toEqual({ data: null, errors: [{ message: "nope" }] });
1105
+ });
1106
+ });
1107
+
1108
+ // The GraphQL manager rides on the boot result without being on its public
1109
+ // type, and the subgraph registers late: poll rather than race it.
1110
+ async function pollWorkflowSubgraph(
1111
+ switchboard: Awaited<ReturnType<typeof startSwitchboard>>,
1112
+ ): Promise<{ name: string } | undefined> {
1113
+ const { graphqlManager } = (
1114
+ switchboard as unknown as {
1115
+ api: { graphqlManager: GraphQLManager };
1116
+ }
1117
+ ).api;
1118
+ for (let attempt = 0; attempt < 100; attempt++) {
1119
+ const subgraph = graphqlManager.getSubgraphByName("workflow-runtime");
1120
+ if (subgraph) return subgraph;
1121
+ await new Promise((resolve) => setTimeout(resolve, 50));
1122
+ }
1123
+ return undefined;
1124
+ }
1125
+
1126
+ describe("booting Switchboard with workflows on", () => {
1127
+ it("arms the intake and registers the workflow document models", async () => {
1128
+ const tempRoot = await mkdtemp(join(tmpdir(), "switchboard-workflows-"));
1129
+ const previousReactorDb = process.env.PH_REACTOR_DATABASE_URL;
1130
+ process.env.PH_REACTOR_DATABASE_URL = join(tempRoot, "reactor-storage");
1131
+ let switchboard: Awaited<ReturnType<typeof startSwitchboard>> | undefined;
1132
+
1133
+ try {
1134
+ switchboard = await bootSwitchboard(
1135
+ {
1136
+ server: { port: 0 },
1137
+ storage: { readModel: { url: join(tempRoot, "read-model") } },
1138
+ features: { workflows: true, mcp: false },
1139
+ packages: { disableLocal: true },
1140
+ identity: { keypairPath: join(tempRoot, "identity.json") },
1141
+ },
1142
+ { logger: stubLogger() },
1143
+ );
1144
+
1145
+ expect(switchboard.workflowTriggers).toEqual({ status: "available" });
1146
+ const { results } = await switchboard.reactor.getDocumentModelModules();
1147
+ expect(
1148
+ results.map(({ documentModel }) => documentModel.global.id),
1149
+ ).toContain("powerhouse/workflow");
1150
+ // With no worker pool or projection worker, workflows alone resolve them.
1151
+ expect(
1152
+ switchboard.modelManifest().map((entry) => entry.documentType),
1153
+ ).toEqual(
1154
+ expect.arrayContaining([
1155
+ "powerhouse/workflow",
1156
+ "powerhouse/connection",
1157
+ ]),
1158
+ );
1159
+ // The subgraph is registered late, so the schema it joins arrives after
1160
+ // the boot resolves; poll rather than race it.
1161
+ await expect(pollWorkflowSubgraph(switchboard)).resolves.toMatchObject({
1162
+ name: "workflow-runtime",
1163
+ });
1164
+ // The boot type does not publish `api`; the facts sink lives on it.
1165
+ const { api } = switchboard as unknown as {
1166
+ api: { inspection?: { inspector: { info(): Promise<unknown> } } };
1167
+ };
1168
+ await expect(api.inspection?.inspector.info()).resolves.toMatchObject({
1169
+ workflows: true,
1170
+ });
1171
+
1172
+ await switchboard.shutdown();
1173
+ switchboard = undefined;
1174
+ } finally {
1175
+ await switchboard?.shutdown();
1176
+ if (previousReactorDb === undefined) {
1177
+ delete process.env.PH_REACTOR_DATABASE_URL;
1178
+ } else {
1179
+ process.env.PH_REACTOR_DATABASE_URL = previousReactorDb;
1180
+ }
1181
+ await rm(tempRoot, { recursive: true, force: true });
1182
+ }
1183
+ }, 60_000);
1184
+ });
1185
+
1186
+ describe("bindPackagePieces", () => {
1187
+ // The manager's shape, no more of it than the binding uses.
1188
+ function stubSource(initial: Map<string, PackagePieceEntry[]>) {
1189
+ const handlers: ((pieces: Map<string, PackagePieceEntry[]>) => void)[] = [];
1190
+ return {
1191
+ getPieces: () => initial,
1192
+ onPiecesChange(
1193
+ handler: (pieces: Map<string, PackagePieceEntry[]>) => void,
1194
+ ) {
1195
+ handlers.push(handler);
1196
+ },
1197
+ emit(pieces: Map<string, PackagePieceEntry[]>) {
1198
+ for (const handler of handlers) handler(pieces);
1199
+ },
1200
+ };
1201
+ }
1202
+
1203
+ const entry = (name: string, version: string): PackagePieceEntry => ({
1204
+ name,
1205
+ version,
1206
+ bundleDir: `/pkg/dist/node/pieces/${name}`,
1207
+ });
1208
+
1209
+ it("fills the registry from what the manager already loaded", () => {
1210
+ const registry = new PieceRegistry();
1211
+ const source = stubSource(
1212
+ new Map([
1213
+ ["@acme/pack", [entry("@acme/piece-a", "1.0.0")]],
1214
+ ["/srv/project", [entry("@acme/piece-b", "2.0.0")]],
1215
+ ]),
1216
+ );
1217
+
1218
+ bindPackagePieces(registry, source);
1219
+
1220
+ expect(registry.versions()).toEqual({
1221
+ "@acme/piece-a": "1.0.0",
1222
+ "@acme/piece-b": "2.0.0",
1223
+ });
1224
+ });
1225
+
1226
+ it("refills on every change, so a rebuilt package needs no restart", () => {
1227
+ const registry = new PieceRegistry();
1228
+ const source = stubSource(new Map());
1229
+
1230
+ bindPackagePieces(registry, source);
1231
+ expect(registry.entries()).toEqual([]);
1232
+
1233
+ source.emit(new Map([["/srv/project", [entry("@acme/piece-b", "2.0.0")]]]));
1234
+ expect(registry.versions()).toEqual({ "@acme/piece-b": "2.0.0" });
1235
+
1236
+ // And a package that stops shipping one loses it.
1237
+ source.emit(new Map());
1238
+ expect(registry.entries()).toEqual([]);
1239
+ });
1240
+
1241
+ it("gives a piece two packages ship to the first by package name, whatever the load order", () => {
1242
+ const registry = new PieceRegistry();
1243
+ const source = stubSource(
1244
+ new Map([
1245
+ ["@zeta/pack", [entry("@acme/piece-a", "9.0.0")]],
1246
+ ["@alpha/pack", [entry("@acme/piece-a", "1.0.0")]],
1247
+ ]),
1248
+ );
1249
+
1250
+ bindPackagePieces(registry, source);
1251
+
1252
+ expect(registry.versions()).toEqual({ "@acme/piece-a": "1.0.0" });
1253
+ });
1254
+ });