@classytic/arc 2.45.2 → 2.47.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 (333) hide show
  1. package/README.md +1 -1
  2. package/dist/{EventTransport-DHb1tpu-.mjs → EventTransport-BHKy4_Bi.mjs} +5 -6
  3. package/dist/{EventTransport-CiicKz2Z.d.mts → EventTransport-CYEoCJGe.d.mts} +0 -2
  4. package/dist/{HookSystem-C1u0EUnt.mjs → HookSystem-CAIDVoKC.mjs} +3 -4
  5. package/dist/{QueryCache--5uAuYPW.d.mts → QueryCache-DdvrGG8Q.d.mts} +1 -3
  6. package/dist/{ResourceRegistry-D2jXWVN_.mjs → ResourceRegistry-23Ml6FNe.mjs} +15 -4
  7. package/dist/{acquire-DTkA8Lme.mjs → acquire-DoFX06fm.mjs} +2 -3
  8. package/dist/{actionPermissions-DRVk6m7x.mjs → actionPermissions-DXrlWHHK.mjs} +37 -42
  9. package/dist/audit/index.d.mts +2 -10
  10. package/dist/audit/index.mjs +8 -12
  11. package/dist/auth/audit.d.mts +0 -2
  12. package/dist/auth/audit.mjs +2 -3
  13. package/dist/auth/index.d.mts +9 -17
  14. package/dist/auth/index.mjs +26 -29
  15. package/dist/auth/redis-session.d.mts +2 -4
  16. package/dist/auth/redis-session.mjs +2 -3
  17. package/dist/{authorizationDecision-D48fUJv1.mjs → authorizationDecision-DYiubkYw.mjs} +5 -6
  18. package/dist/{base-CZyixEQR.d.mts → base-HXNgPQww.d.mts} +1 -7
  19. package/dist/{boundedMap-DkKiPifd.mjs → boundedMap-CtdzpJ3X.mjs} +2 -3
  20. package/dist/{buildHandler-BiZ4VATS.mjs → buildHandler-CARdmPNo.mjs} +5 -6
  21. package/dist/cache/index.d.mts +4 -10
  22. package/dist/cache/index.mjs +5 -6
  23. package/dist/{caching-Cj0as-P1.mjs → caching-QRiryDLs.mjs} +3 -4
  24. package/dist/{claimed-ChI13rUR.mjs → claimed-BLecr1j3.mjs} +2 -3
  25. package/dist/cleanup/index.d.mts +4 -18
  26. package/dist/cleanup/index.mjs +12 -20
  27. package/dist/cli/commands/describe.d.mts +1 -3
  28. package/dist/cli/commands/describe.mjs +4 -5
  29. package/dist/cli/commands/docs.d.mts +1 -3
  30. package/dist/cli/commands/docs.mjs +4 -5
  31. package/dist/cli/commands/doctor.d.mts +1 -3
  32. package/dist/cli/commands/doctor.mjs +2 -3
  33. package/dist/cli/commands/generate.d.mts +1 -1
  34. package/dist/cli/commands/generate.mjs +2 -2
  35. package/dist/cli/commands/init.d.mts +1 -1
  36. package/dist/cli/commands/init.mjs +2 -2
  37. package/dist/cli/commands/introspect.d.mts +1 -3
  38. package/dist/cli/commands/introspect.mjs +3 -4
  39. package/dist/cli/index.d.mts +2 -2
  40. package/dist/cli/index.mjs +3 -3
  41. package/dist/{constants-D_aiew34.mjs → constants-Cx7BcnHT.mjs} +2 -3
  42. package/dist/context/index.d.mts +0 -8
  43. package/dist/context/index.mjs +6 -7
  44. package/dist/core/index.d.mts +3 -3
  45. package/dist/core/index.mjs +8 -8
  46. package/dist/{core-QIZ2560Y.mjs → core-0WyMuo0f.mjs} +9 -12
  47. package/dist/{createActionRouter-CvH84dyx.mjs → createActionRouter-mLAGbpDV.mjs} +7 -8
  48. package/dist/{createAggregationRouter-DGyK2Hp6.mjs → createAggregationRouter-BEAjn3dA.mjs} +9 -10
  49. package/dist/{createApp-CKjZpmq9.mjs → createApp-QDP4vYWH.mjs} +49 -62
  50. package/dist/{createMcpServer-DSztofa9.d.mts → createMcpServer-DzXHX0SO.d.mts} +1 -3
  51. package/dist/{defineAggregation-BLza7Ca4.mjs → defineAggregation-CFNfvz-C.mjs} +2 -3
  52. package/dist/{defineResource-CEo0gDCb.mjs → defineResource-BROJmhzJ.mjs} +80 -29
  53. package/dist/discovery/index.d.mts +1 -3
  54. package/dist/discovery/index.mjs +2 -3
  55. package/dist/docs/index.d.mts +8 -8
  56. package/dist/docs/index.mjs +4 -5
  57. package/dist/{elevation-BW2J3tNj.d.mts → elevation-DPD0hcU-.d.mts} +0 -2
  58. package/dist/{elevation-BJTsSnke.mjs → elevation-DrXeEWWk.mjs} +9 -10
  59. package/dist/encryption/index.d.mts +1 -7
  60. package/dist/encryption/index.mjs +8 -13
  61. package/dist/{errorHandler--4rSMMvq.d.mts → errorHandler-B9r88jZV.d.mts} +8 -3
  62. package/dist/{errorHandler-2p4SL5zm.mjs → errorHandler-BiBXtxj4.mjs} +16 -6
  63. package/dist/{errors-JYc9vwqE.d.mts → errors-DTo0me1o.d.mts} +0 -2
  64. package/dist/{errors-grZkIA8N.mjs → errors-DnrUChAy.mjs} +2 -3
  65. package/dist/{eventPlugin-BtmA4-3P.d.mts → eventPlugin-BY38F6yK.d.mts} +1 -7
  66. package/dist/{eventPlugin-ItcYBGUs.mjs → eventPlugin-BhKLUe7H.mjs} +10 -12
  67. package/dist/{eventTypes-Ck6fD3ne.mjs → eventTypes-CCIRGakw.mjs} +5 -8
  68. package/dist/events/index.d.mts +5 -17
  69. package/dist/events/index.mjs +9 -9
  70. package/dist/events/transports/redis-stream-entry.d.mts +1 -1
  71. package/dist/events/transports/redis-stream-entry.mjs +5 -6
  72. package/dist/events/transports/redis.d.mts +2 -4
  73. package/dist/events/transports/redis.mjs +3 -4
  74. package/dist/{externalPaths-CmGOxOtD.d.mts → externalPaths-BOqdq5wr.d.mts} +0 -2
  75. package/dist/factory/index.d.mts +4 -14
  76. package/dist/factory/index.mjs +12 -18
  77. package/dist/{fastify-augmentation-DRlCIWE9.d.mts → fastify-augmentation-bzkWPt1f.d.mts} +4 -10
  78. package/dist/{fields-BRX0Krcj.mjs → fields-CYdpcV73.mjs} +2 -3
  79. package/dist/{fields-BBSpf8pS.d.mts → fields-JTkrtO-r.d.mts} +0 -2
  80. package/dist/{filter-merge-CDc7YMwX.mjs → filter-merge-6kasezRH.mjs} +2 -3
  81. package/dist/{generate-DCGuEbqI.d.mts → generate-C-g_KOkV.d.mts} +0 -4
  82. package/dist/{generate-hvg7V2g1.mjs → generate-DUkcbc4r.mjs} +7 -12
  83. package/dist/{headers-Cqkg4LzI.mjs → headers-KxhrKevA.mjs} +3 -4
  84. package/dist/{health-PVt0VjOx.mjs → health-CRJg3IIq.mjs} +2 -3
  85. package/dist/{health-DyeP3mTW.mjs → health-jkYNdobJ.mjs} +4 -7
  86. package/dist/hooks/index.d.mts +1 -1
  87. package/dist/hooks/index.mjs +2 -2
  88. package/dist/http-cache/index.d.mts +211 -0
  89. package/dist/http-cache/index.mjs +605 -0
  90. package/dist/http-cache/purgers/cloudflare.d.mts +13 -0
  91. package/dist/http-cache/purgers/cloudflare.mjs +46 -0
  92. package/dist/http-cache/purgers/fastly.d.mts +12 -0
  93. package/dist/http-cache/purgers/fastly.mjs +47 -0
  94. package/dist/http-cache/testing/index.d.mts +68 -0
  95. package/dist/http-cache/testing/index.mjs +168 -0
  96. package/dist/idempotency/index.d.mts +3 -9
  97. package/dist/idempotency/index.mjs +11 -14
  98. package/dist/idempotency/redis.d.mts +1 -1
  99. package/dist/idempotency/redis.mjs +3 -4
  100. package/dist/{index-Bxriq3so.d.mts → index-B5i9-vuP.d.mts} +4 -26
  101. package/dist/{index-Chgz3d0i.d.mts → index-BAXDo5eE.d.mts} +1 -7
  102. package/dist/{index-Beg3aNnK.d.mts → index-BxZS-8So.d.mts} +67 -25
  103. package/dist/{index-WH7xgvxS.d.mts → index-Cy2-QffW.d.mts} +40 -92
  104. package/dist/{index-uhkUA5-U.d.mts → index-D1X_C_qz.d.mts} +13 -23
  105. package/dist/{index-CUJvoyw3.d.mts → index-DFCCQ9AE.d.mts} +2 -24
  106. package/dist/index.d.mts +7 -9
  107. package/dist/index.mjs +12 -13
  108. package/dist/{init-jC3rMPzb.mjs → init-CACwpktI.mjs} +18 -35
  109. package/dist/{init-Cscs4lab.d.mts → init-CV2_Fw3H.d.mts} +0 -4
  110. package/dist/integrations/event-gateway.d.mts +3 -5
  111. package/dist/integrations/event-gateway.mjs +3 -4
  112. package/dist/integrations/index.d.mts +3 -3
  113. package/dist/integrations/index.mjs +1 -1
  114. package/dist/integrations/jobs/index.d.mts +1 -1
  115. package/dist/integrations/jobs/index.mjs +7 -11
  116. package/dist/integrations/mcp/index.d.mts +7 -39
  117. package/dist/integrations/mcp/index.mjs +8 -14
  118. package/dist/integrations/mcp/testing.d.mts +3 -5
  119. package/dist/integrations/mcp/testing.mjs +3 -4
  120. package/dist/integrations/streamline.d.mts +1 -3
  121. package/dist/integrations/streamline.mjs +4 -5
  122. package/dist/integrations/webhooks.d.mts +2 -4
  123. package/dist/integrations/webhooks.mjs +5 -5
  124. package/dist/integrations/websocket-pushref-redis.d.mts +2 -4
  125. package/dist/integrations/websocket-pushref-redis.mjs +2 -3
  126. package/dist/integrations/websocket-redis.d.mts +2 -4
  127. package/dist/integrations/websocket-redis.mjs +2 -3
  128. package/dist/integrations/websocket.d.mts +2 -2
  129. package/dist/integrations/websocket.mjs +13 -24
  130. package/dist/{interface-JJzwH4Ro.d.mts → interface-BmExzQRD.d.mts} +0 -2
  131. package/dist/{interface-BOk3YnTz.d.mts → interface-WR1U0K7t.d.mts} +0 -2
  132. package/dist/{jsonBody-ptwyzZQ-.mjs → jsonBody-CzDBkCme.mjs} +3 -4
  133. package/dist/{keys-C1vFuSbv.mjs → keys-Cbwf6r1B.mjs} +2 -3
  134. package/dist/{loadResources-CHPDyIPn.mjs → loadResources-Kr6vuljv.mjs} +4 -5
  135. package/dist/{loadResourcesFromEntry-BkHHTu_B.mjs → loadResourcesFromEntry-D2e0qoDR.mjs} +3 -4
  136. package/dist/logger/index.d.mts +1 -3
  137. package/dist/logger/index.mjs +2 -2
  138. package/dist/{logger-C5bvCiAK.mjs → logger-C110X5Yz.mjs} +3 -5
  139. package/dist/{mcpPlugin-C9qohJCF.mjs → mcpPlugin-4lIPr9OJ.mjs} +41 -60
  140. package/dist/{memory-CxiTwT0j.mjs → memory-D9qkhXiB.mjs} +4 -5
  141. package/dist/{metrics-Ckp2zRy-.mjs → metrics-B-qrrWfI.mjs} +4 -5
  142. package/dist/middleware/index.d.mts +1 -5
  143. package/dist/middleware/index.mjs +4 -5
  144. package/dist/migrations/index.d.mts +0 -2
  145. package/dist/migrations/index.mjs +3 -4
  146. package/dist/{module-CfnKuIuH.mjs → module-BD8xHgrz.mjs} +2 -3
  147. package/dist/{multiTenant-CAtYlW6H.d.mts → multiTenant-KZj8j1uJ.d.mts} +1 -5
  148. package/dist/{multipartBody-BFasGtP9.mjs → multipartBody-qU7KCn1l.mjs} +2 -3
  149. package/dist/observeSend-BnPtTotW.mjs +20 -0
  150. package/dist/{openapi-DAPxjYHX.mjs → openapi-DoVa5SVP.mjs} +18 -28
  151. package/dist/outbox-admin/index.d.mts +2 -4
  152. package/dist/outbox-admin/index.mjs +6 -7
  153. package/dist/{outbox-module-gZCHoE4H.d.mts → outbox-module-5Mnwcycy.d.mts} +3 -9
  154. package/dist/outbox-module-DyITEIop.mjs +297 -0
  155. package/dist/permissions/index.d.mts +4 -4
  156. package/dist/permissions/index.mjs +7 -7
  157. package/dist/{permissions-B14c3OMp.mjs → permissions-BBy4bOGi.mjs} +19 -29
  158. package/dist/{pipe-CQv7PsAK.mjs → pipe-BOm2o4UA.mjs} +3 -4
  159. package/dist/pipeline/index.d.mts +1 -9
  160. package/dist/pipeline/index.mjs +5 -8
  161. package/dist/{plan-CpnTykjb.mjs → plan-DDIGwuxr.mjs} +5 -9
  162. package/dist/{plugin-DXTjVg_Q.mjs → plugin-Bn4D_0XK.mjs} +156 -64
  163. package/dist/plugins/index.d.mts +8 -16
  164. package/dist/plugins/index.mjs +22 -26
  165. package/dist/plugins/response-cache.d.mts +2 -4
  166. package/dist/plugins/response-cache.mjs +10 -10
  167. package/dist/plugins/tracing-entry.d.mts +1 -1
  168. package/dist/plugins/tracing-entry.mjs +3 -4
  169. package/dist/{pluralize-C3VJKRGp.mjs → pluralize-ClEjcKlG.mjs} +2 -3
  170. package/dist/policy.types-DPqToKG1.d.mts +50 -0
  171. package/dist/presets/filesUpload.d.mts +4 -6
  172. package/dist/presets/filesUpload.mjs +6 -7
  173. package/dist/presets/index.d.mts +3 -19
  174. package/dist/presets/index.mjs +2 -2
  175. package/dist/presets/multiTenant.d.mts +1 -1
  176. package/dist/presets/multiTenant.mjs +7 -7
  177. package/dist/presets/search.d.mts +3 -5
  178. package/dist/presets/search.mjs +3 -4
  179. package/dist/{presets-CquqYJPy.mjs → presets-DK2jh5YR.mjs} +11 -18
  180. package/dist/{projection-CgfSLOSM.mjs → projection-BHH-sXyS.mjs} +3 -4
  181. package/dist/purger.types-2wNJK_89.mjs +24 -0
  182. package/dist/purger.types-DvPp4-yd.d.mts +26 -0
  183. package/dist/{pushref-registry-UxCkoA4C.d.mts → pushref-registry-d86QUaSq.d.mts} +0 -6
  184. package/dist/{queryCachePlugin-D0HUISHJ.mjs → queryCachePlugin-Ckqe98AM.mjs} +8 -10
  185. package/dist/{queryCachePlugin-C2lZjTxk.d.mts → queryCachePlugin-DYQUyeJ9.d.mts} +2 -4
  186. package/dist/{rateLimitKey-AvkBOMkl.mjs → rateLimitKey-CWAjlqcN.mjs} +2 -3
  187. package/dist/{realtime-CbWtVbqK.mjs → realtime-BIJi9USY.mjs} +17 -19
  188. package/dist/{redis-BDgv9Glw.d.mts → redis-RpDMemdm.d.mts} +2 -4
  189. package/dist/{redis-stream-BMk-bpQS.d.mts → redis-stream-CS1N9dwM.d.mts} +1 -3
  190. package/dist/{redisShapes-CQksY67q.d.mts → redisShapes-CqBXTn_s.d.mts} +0 -2
  191. package/dist/registry/index.d.mts +2 -12
  192. package/dist/registry/index.mjs +3 -3
  193. package/dist/{registry-BVwpAuFI.mjs → registry-y9ZA-R_J.mjs} +7 -12
  194. package/dist/{outbox-module-B4FAkx3A.mjs → relay-BNrC1CEP.mjs} +8 -306
  195. package/dist/{renewingLease-CykpeNcQ.mjs → renewingLease-CS43br5E.mjs} +2 -3
  196. package/dist/{replyHelpers-DA51IZio.mjs → replyHelpers-oZDzakGb.mjs} +3 -4
  197. package/dist/{requestContext-DIWHKDtQ.mjs → requestContext-fWb_YaV2.mjs} +2 -3
  198. package/dist/{requirement-Cp_fsMDL.mjs → requirement--2hWyyHi.mjs} +2 -3
  199. package/dist/{requirement-CbiLdQ1n.d.mts → requirement-CTRQjjQx.d.mts} +0 -2
  200. package/dist/{resourceRateLimit-BFuluodF.mjs → resourceRateLimit-1WbcyMZY.mjs} +3 -4
  201. package/dist/{resourceRateLimit-Wf6d6FL9.d.mts → resourceRateLimit-DCWglD7V.d.mts} +1 -3
  202. package/dist/{rolldown-runtime-D_lMdYOd.mjs → rolldown-runtime-yH2lHMo_.mjs} +2 -3
  203. package/dist/{routeValidator-DuLonYwr.mjs → routeValidator-BSlRIA5c.mjs} +2 -3
  204. package/dist/{runtimeCapabilities-CydRfm0i.mjs → runtimeCapabilities-CYCEtU1W.mjs} +2 -3
  205. package/dist/{schedules-B693KXxa.mjs → schedules-B5WGlYIT.mjs} +132 -9
  206. package/dist/{schemaConverter-DNvZWTV6.mjs → schemaConverter-DtNvts-6.mjs} +3 -4
  207. package/dist/{schemaIR-REV2y7Wd.mjs → schemaIR-uS_RHqa3.mjs} +3 -4
  208. package/dist/schemas/index.d.mts +0 -2
  209. package/dist/schemas/index.mjs +2 -3
  210. package/dist/scim/index.d.mts +0 -12
  211. package/dist/scim/index.mjs +10 -18
  212. package/dist/scope/index.d.mts +2 -6
  213. package/dist/scope/index.mjs +5 -5
  214. package/dist/{scope-Bevxy_ST.mjs → scope-BwVLSyNG.mjs} +5 -6
  215. package/dist/{sessionManager-qimlKV0P.d.mts → sessionManager-CdvDF04x.d.mts} +2 -4
  216. package/dist/{shutdown-CfrqPR7A.mjs → shutdown-BJiJN7FT.mjs} +2 -3
  217. package/dist/{simpleEqualityMatcher-BJwfuRKP.mjs → simpleEqualityMatcher-DGRLq-1k.mjs} +2 -3
  218. package/dist/{sse-CuNNWr2z.mjs → sse-B_50llZu.mjs} +8 -9
  219. package/dist/{sseStream-C_2ujAVY.mjs → sseStream-BjSo9Ult.mjs} +3 -4
  220. package/dist/{storage-Cx9Sz3Ou.d.mts → storage-odC5MNKN.d.mts} +0 -2
  221. package/dist/{store-helpers-C8uBGCbb.mjs → store-helpers-D-n5cwy5.mjs} +2 -3
  222. package/dist/{streaming-Bdq_M4d5.mjs → streaming-Dcgqa-hH.mjs} +2 -3
  223. package/dist/{subscriberIdentity-B-KpZkdl.mjs → subscriberIdentity-C9KhIXTF.mjs} +2 -3
  224. package/dist/{tenancy-C5PCvm1h.mjs → tenancy-COrhjPRZ.mjs} +3 -4
  225. package/dist/{tenantPreparation-dYvWrgNa.mjs → tenantPreparation-BElWHytd.mjs} +5 -6
  226. package/dist/testing/cleanupStoreContract.d.mts +2 -4
  227. package/dist/testing/cleanupStoreContract.mjs +2 -3
  228. package/dist/testing/index.d.mts +6 -32
  229. package/dist/testing/index.mjs +24 -37
  230. package/dist/testing/outboxStoreContract.d.mts +1 -3
  231. package/dist/testing/outboxStoreContract.mjs +3 -4
  232. package/dist/testing/requiredPorts.d.mts +2 -4
  233. package/dist/testing/requiredPorts.mjs +3 -4
  234. package/dist/testing/storageContract.d.mts +2 -4
  235. package/dist/testing/storageContract.mjs +2 -3
  236. package/dist/{timing-DCqsezX8.mjs → timing-CaxKbRk_.mjs} +3 -5
  237. package/dist/{tracing-Dro5eH6j.d.mts → tracing-JSFiBl5r.d.mts} +0 -2
  238. package/dist/{transactionContext-DrcNyjpv.mjs → transactionContext-8qKON0Nk.mjs} +2 -3
  239. package/dist/{typeGuards-CEl10KPy.mjs → typeGuards-DVjVSsXO.mjs} +2 -3
  240. package/dist/types/index.d.mts +4 -4
  241. package/dist/types/index.mjs +1 -1
  242. package/dist/types/storage.d.mts +1 -1
  243. package/dist/types/storage.mjs +1 -1
  244. package/dist/{types-ByHn9rEO.d.mts → types-0Dqlbgn8.d.mts} +0 -2
  245. package/dist/{types-BJ-2XqVF.d.mts → types-BeEJm-DV.d.mts} +114 -14
  246. package/dist/{types-DVLddu2q.d.mts → types-C0YJAiL0.d.mts} +0 -2
  247. package/dist/{types-D9NWjpYc.mjs → types-DZHqOuJE.mjs} +5 -6
  248. package/dist/{types-D3Ixsh00.d.mts → types-DeLiuaNv.d.mts} +2 -4
  249. package/dist/{types-Ddl9OjmE.d.mts → types-DnkIALZ8.d.mts} +0 -4
  250. package/dist/usage/index.d.mts +2 -10
  251. package/dist/usage/index.mjs +8 -12
  252. package/dist/{userHelpers-BHig1kHq.mjs → userHelpers-_eGj6kf0.mjs} +2 -3
  253. package/dist/utils/index.d.mts +5 -39
  254. package/dist/utils/index.mjs +12 -12
  255. package/dist/{utils-BG5P7_Vb.mjs → utils-Dd6MWpye.mjs} +20 -30
  256. package/dist/{validate-D_mdOCir.mjs → validate-BaF5wd0x.mjs} +5 -7
  257. package/dist/{versioning-DBGHjPh7.mjs → versioning-DyV7mwtK.mjs} +4 -5
  258. package/dist/{versioning-Bqm_57Qt.d.mts → versioning-S18y2-0C.d.mts} +1 -15
  259. package/dist/{websocket-Cs4awVyD.d.mts → websocket-BGuc-WVZ.d.mts} +1 -15
  260. package/dist/{workScope-DPPfM4m6.mjs → workScope-CmCBUmPR.mjs} +3 -4
  261. package/llms.txt +37 -30
  262. package/package.json +51 -22
  263. package/skills/arc/SKILL.md +65 -844
  264. package/skills/arc/references/agent-auth.md +82 -193
  265. package/skills/arc/references/api-reference.md +41 -245
  266. package/skills/arc/references/auth-api-keys.md +99 -0
  267. package/skills/arc/references/auth-better-auth-overlay.md +87 -0
  268. package/skills/arc/references/auth-better-auth.md +78 -0
  269. package/skills/arc/references/auth-permissions.md +100 -0
  270. package/skills/arc/references/auth-strategies.md +122 -0
  271. package/skills/arc/references/boot.md +80 -0
  272. package/skills/arc/references/enterprise-auth.md +65 -81
  273. package/skills/arc/references/events-outbox.md +90 -0
  274. package/skills/arc/references/events.md +75 -440
  275. package/skills/arc/references/integrations-jobs.md +74 -0
  276. package/skills/arc/references/integrations-realtime.md +84 -0
  277. package/skills/arc/references/integrations-webhooks.md +71 -0
  278. package/skills/arc/references/integrations-workflows.md +47 -0
  279. package/skills/arc/references/mcp-auth.md +83 -0
  280. package/skills/arc/references/mcp-custom-tools.md +125 -0
  281. package/skills/arc/references/mcp-setup.md +115 -0
  282. package/skills/arc/references/mcp-testing.md +63 -0
  283. package/skills/arc/references/multi-tenancy.md +56 -230
  284. package/skills/arc/references/permissions-scope.md +81 -0
  285. package/skills/arc/references/production-api.md +119 -0
  286. package/skills/arc/references/production-audit.md +101 -0
  287. package/skills/arc/references/production-boot.md +91 -0
  288. package/skills/arc/references/production-caching.md +63 -0
  289. package/skills/arc/references/production-distributed.md +75 -0
  290. package/skills/arc/references/production-idempotency.md +83 -0
  291. package/skills/arc/references/production-observability.md +83 -0
  292. package/skills/arc/references/production-realtime.md +70 -0
  293. package/skills/arc/references/production-reliability.md +100 -0
  294. package/skills/arc/references/production-shutdown.md +43 -0
  295. package/skills/arc/references/querying.md +76 -0
  296. package/skills/arc/references/resources.md +97 -0
  297. package/skills/arc/references/schedules.md +79 -0
  298. package/skills/arc/references/scim.md +61 -208
  299. package/skills/arc/references/tenancy-scope-install.md +82 -0
  300. package/skills/arc/references/testing.md +101 -144
  301. package/skills/arc/references/usage-cleanup-capabilities.md +45 -0
  302. package/skills/arc/references/validation.md +91 -0
  303. package/skills/arc/references/writes-hooks-errors.md +80 -0
  304. package/skills/arc-code-review/SKILL.md +67 -114
  305. package/skills/arc-code-review/references/arc-cheatsheet.md +68 -167
  306. package/skills/arc-code-review/references/mongokit-repositories.md +104 -0
  307. package/skills/arc-code-review/references/recipe-events-cache-jobs.md +112 -0
  308. package/skills/arc-code-review/references/recipe-resource.md +100 -0
  309. package/skills/arc-code-review/references/recipe-schemas-fields.md +93 -0
  310. package/skills/arc-code-review/references/recipe-scope-permissions.md +82 -0
  311. package/skills/arc-code-review/references/scaffolding.md +61 -198
  312. package/skills/arc-code-review/references/severity.md +49 -102
  313. package/skills/arc-code-review/references/smells-auth-scope.md +80 -0
  314. package/skills/arc-code-review/references/smells-data-events.md +66 -0
  315. package/skills/arc-code-review/references/smells-imports-style.md +59 -0
  316. package/skills/arc-code-review/references/smells-platform.md +89 -0
  317. package/skills/arc-code-review/references/smells-routes-schemas.md +66 -0
  318. package/skills/arc-module-publishing/SKILL.md +82 -208
  319. package/skills/arc-module-publishing/references/action-presets-and-plugins.md +87 -0
  320. package/skills/arc-module-publishing/references/build-and-types.md +73 -0
  321. package/skills/arc-module-publishing/references/module-lifecycle.md +101 -0
  322. package/skills/arc-module-publishing/references/package-manifest.md +34 -122
  323. package/skills/arc-module-publishing/references/publishing-workflow.md +44 -140
  324. package/skills/arc-module-publishing/references/resource-assembly.md +102 -0
  325. package/skills/arc-module-publishing/references/testing-packages.md +82 -0
  326. package/skills/arc/references/auth.md +0 -729
  327. package/skills/arc/references/integrations.md +0 -452
  328. package/skills/arc/references/mcp.md +0 -691
  329. package/skills/arc/references/production.md +0 -835
  330. package/skills/arc-code-review/references/anti-patterns.md +0 -1008
  331. package/skills/arc-code-review/references/migration-recipes.md +0 -649
  332. package/skills/arc-code-review/references/mongokit-migration.md +0 -360
  333. package/skills/arc-module-publishing/references/authoring-modules.md +0 -327
@@ -1,878 +1,99 @@
1
1
  ---
2
2
  name: arc
3
- description: |
4
- @classytic/arc — Resource-oriented backend framework for Fastify.
5
- Use when building REST APIs with Fastify, resource CRUD, defineResource, createApp,
6
- permissions, presets, database adapters, hooks, events, QueryCache, authentication,
7
- multi-tenant SaaS, OpenAPI, job queues, WebSocket, MCP tools, or production deployment.
8
- Triggers: arc, fastify resource, defineResource, createApp, BaseController, arc preset,
9
- arc auth, arc events, arc jobs, arc websocket, arc mcp, arc plugin, arc testing, arc cli,
10
- arc permissions, arc hooks, arc factory, arc cache.
3
+ description: "@classytic/arc: resource-oriented Fastify backend framework. Use for defineResource CRUD, createApp, permissions, presets, route/action validation (zod v4), scheduled and daily jobs, events/outbox, auth (JWT, Better Auth), multi-tenancy, OpenAPI, MCP tools, testing. Triggers: arc, defineResource, createApp, routeInput, scheduledJobs, arc preset, arc permissions."
11
4
  license: MIT
12
5
  metadata:
13
6
  author: Classytic
14
- tags:
15
- - fastify
16
- - rest-api
17
- - resource-framework
18
- - crud
19
- - permissions
20
- - multi-tenant
21
- - presets
22
- - typescript
23
- - cache
24
- - events
25
- - openapi
7
+ minVersion: "2.46.0"
26
8
  ---
27
9
 
28
10
  # @classytic/arc
29
11
 
30
- Resource-oriented backend framework for Fastify. **Fastify ≥5.8 · Node ≥22 · ESM only.**
12
+ One `defineResource()` = REST + validation + permissions + events + cache + OpenAPI + MCP. Fastify >=5.12, Node >=22, ESM. DB through kits (`@classytic/mongokit`, `sqlitekit`, `prismakit`) over `@classytic/repo-core`.
31
13
 
32
- One `defineResource()` call → REST + auth + permissions + events + cache + OpenAPI + MCP. Database-agnostic (Mongoose, Drizzle/sqlite, Prisma, custom).
14
+ ## Do not hand-roll
33
15
 
34
- ## Install
35
-
36
- ```bash
37
- # Scaffold
38
- npx @classytic/arc@latest init my-api --mongokit --better-auth --single --ts
39
-
40
- # Or add to an existing project
41
- npm install @classytic/arc fastify
42
- npm install @fastify/cors @fastify/helmet @fastify/rate-limit @fastify/sensible @fastify/under-pressure
43
- npm install @classytic/mongokit mongoose # or sqlitekit / prismakit / custom
44
- ```
45
-
46
- `init` flags: `--mongokit | --custom`, `--better-auth | --jwt`, `--single | --multi`, `--ts | --js`, `--edge`, `--force`, `--skip-install`.
47
-
48
- ## Boot
49
-
50
- ```typescript
16
+ | Need | Use |
17
+ |---|---|
18
+ | CRUD, OpenAPI, MCP tools | `defineResource({ name, adapter, permissions })` |
19
+ | Role, ownership, row policy | `@classytic/arc/permissions`: `requireRoles`, `requireOwnership`, `allowPublic({ policy })`, `anyOf` |
20
+ | Tenant or user id in a handler | `@classytic/arc/scope`: `requireOrgId`, `getUserId` (never read scope fields) |
21
+ | Route body/query/params schema | `routeInput({ body })` from `@classytic/arc/core` |
22
+ | CRUD write schema | `crudInput({ create, update })` |
23
+ | Action body schema | `actions.x.schema` is the schema itself; `defineAction({ schema, parse: true })`; `noPayloadSchema` |
24
+ | Filter, sort, page | resource `queryParser` allow-list, keyset `after` |
25
+ | Soft delete, slug, tree, bulk, files | `presets: [...]` |
26
+ | Recurring job | module `scheduledJobs` + `lock` or `singleReplica` |
27
+ | Once per local day | `scheduledJobs` with `daily: { hour, minute, zone, ledger }` |
28
+ | Durable queue | `@classytic/arc/integrations/jobs` |
29
+ | Headless worker | `createWorker(sameOptions)` from `@classytic/arc/factory` |
30
+ | Counters, quotas | `@classytic/arc/usage`: `usagePlugin`, `requireQuota`; `rateLimit.plan` |
31
+ | Events, outbox, webhooks | `@classytic/arc/events`: `createOutboxModule` |
32
+ | 404 for unknown routes | built in: `arc.not_found` ErrorContract |
33
+ | Tests | `createTestApp`, `expectArc` from `@classytic/arc/testing` |
34
+
35
+ ## Golden path
36
+
37
+ ```typescript
38
+ import { defineResource } from '@classytic/arc';
51
39
  import { createApp, loadResources } from '@classytic/arc/factory';
52
-
53
- const app = await createApp({
54
- preset: 'production', // production | development | testing | edge
55
- runtime: 'memory', // memory | distributed
56
- resourcePrefix: '/api/v1',
57
- auth: { type: 'jwt', jwt: { secret: process.env.JWT_SECRET } },
58
- cors: { origin: process.env.ALLOWED_ORIGINS!.split(','), credentials: true },
59
- resources: await loadResources(import.meta.url), // auto-discovers *.resource.ts
60
- arcPlugins: { events: true, queryCache: false, sse: false, caching: true },
61
- stores: { // required when runtime: 'distributed'
62
- events: new RedisEventTransport({ client: redis }),
63
- queryCache: new RedisCacheStore({ client: redis }),
64
- },
65
- });
66
-
67
- await app.listen({ port: 8040, host: '0.0.0.0' });
68
- ```
69
-
70
- **Boot order (fixed):** `beforeBoot` → modules resolve → `plugins` → `bootstrap[]` → `resources` → `afterResources` → `onReady`.
71
-
72
- **`role` — one image, N deployments (2.33).** `createApp({ role })` declares what a process is FOR, so the same codebase ships as api / worker / relay / scheduler without per-deployment builds:
73
-
74
- ```typescript
75
- createApp({ role: process.env.ARC_ROLE as 'api' | 'worker' | 'relay' | 'scheduler' | 'all' })
76
- ```
77
-
78
- `api` and `worker` mount NO module schedule arms; `relay` mounts only `kind: 'relay'` arms (the outbox relay, durable webhook delivery); `scheduler` mounts all of them. Declaring `relay`/`scheduler` together with `resources`/`resourceDir` is BOOT-FATAL — a relay process must not serve routes. Default `all` is the pre-2.33 behaviour, unchanged. `createWorker()` forwards `role`; without one it still runs everything non-HTTP.
79
-
80
- `beforeBoot()` (2.21) runs before Fastify exists and before module thunks / resource files import — connect the DB there instead of dynamic-import ordering hacks. Return a disposer (`() => mongoose.disconnect()`) and arc runs it on close and on a failed boot. A bridge declared as `{ kind: 'bridge', name, dependsOn, load }` is never imported when inactive.
81
-
82
- For async-booted engines, pass `resources` as a factory so it runs after `bootstrap[]`:
83
-
84
- ```typescript
85
- resources: async (fastify) => {
86
- const engine = await ensureCatalogEngine();
87
- return [buildProductResource(engine)];
88
- }
89
- ```
90
-
91
- `loadResources(import.meta.url)` resolves `src/` in dev and `dist/` in prod. Use `loadResources(import.meta.url, { context: { engine } })` to thread engine handles into `(ctx) => defineResource(...)` default exports. `{ filter: (absPath) => boolean }` (2.21) gates files BEFORE they're imported — feature-flag manifests become one callback.
92
-
93
- ## defineResource()
94
-
95
- ```typescript
96
- import { defineResource, allowPublic, requireRoles, requireAuth } from '@classytic/arc';
40
+ import { allowPublic, requireRoles } from '@classytic/arc/permissions';
97
41
  import { createMongooseAdapter } from '@classytic/mongokit/adapter';
98
42
 
99
43
  export default defineResource({
100
44
  name: 'product',
101
- // mongokit >=3.21 defaults schemaGenerator to buildCrudSchemasFromModel;
102
- // pass `schemaGenerator: false` to opt out.
103
45
  adapter: createMongooseAdapter({ model: ProductModel, repository: productRepo }),
104
-
105
- presets: ['softDelete', 'slugLookup', { name: 'multiTenant', tenantField: 'organizationId' }],
106
-
107
- permissions: {
108
- list: allowPublic(),
109
- get: allowPublic(),
110
- create: requireRoles(['admin']),
111
- update: requireRoles(['admin']),
112
- delete: requireRoles(['admin']),
113
- },
114
-
115
- schemaOptions: {
116
- fieldRules: {
117
- name: { minLength: 2, maxLength: 200 },
118
- sku: { pattern: '^[A-Z]{3}-\\d{3}$' },
119
- status: { enum: ['draft', 'active', 'archived'] },
120
- deletedAt: { systemManaged: true }, // framework stamps; strip from body
121
- priceMode: { nullable: true }, // accept null
122
- organizationId: { systemManaged: true, preserveForElevated: true },
123
- },
124
- query: {
125
- allowedPopulate: ['category', 'createdBy'],
126
- filterableFields: { status: { type: 'string' } },
127
- },
128
- },
129
-
130
- cache: { staleTime: 30, gcTime: 300, tags: ['catalog'] },
131
-
132
- routes: [
133
- { method: 'GET', path: '/featured', handler: 'getFeatured', permissions: allowPublic() },
134
- { method: 'POST', path: '/webhook', rawHandler: webhookFn, permissions: requireAuth() },
135
- ],
136
- actions: {
137
- approve: { handler: approveOrder, permissions: requireRoles(['admin']) },
138
- },
139
- });
140
- ```
141
-
142
- **Auto-generated:** `GET /`, `GET /:id`, `POST /`, `PATCH /:id`, `DELETE /:id`. Presets add their own routes (see table below).
143
-
144
- ### Custom routes: `handler` vs `rawHandler`
145
-
146
- A route declares its execution model by WHICH FIELD it fills — there is no `raw` flag (removed in 2.31).
147
-
148
- | Field | Signature | Behaviour |
149
- |---|---|---|
150
- | `handler` | `(ctx: IRequestContext)` or a controller-method name | Arc pipeline: envelope shaping, field-write permissions, MCP tool by default |
151
- | `rawHandler` | `(request, reply)` or a controller-method name | Fastify-native: owns the response, no pipeline, no MCP unless `mcpHandler` is set |
152
- | `controllerMethod` | `(c: MyController) => c.method` | Typed ref for the pipeline — TS catches typos |
153
-
154
- Declaring both `handler` and `rawHandler` throws at boot. `streamResponse: true` requires `rawHandler` (the handler is invoked with `(request, reply)` and owns the socket).
155
-
156
- Inline `rawHandler` parameters infer — no `req: FastifyRequest` annotation — and typed generics (`FastifyRequest<{ Body: CreateBody }>`) assign without a cast.
157
-
158
- **Resource shorthands:**
159
-
160
- ```typescript
161
- // "fetch-all" reference data — read-only crud (list+get), defaultLimit/maxLimit=1000,
162
- // cache { staleTime: 300, gcTime: 600 }. Explicit narrow flags still win.
163
- defineResource({ name: 'currency', adapter, referenceData: true });
164
-
165
- // Service resource — no adapter, no auto-CRUD, no validation, no registry entry.
166
- // Equivalent to disableDefaultRoutes + skipValidation + skipRegistry.
167
- defineResource({ name: 'health', customRoutesOnly: true, routes: [...] });
168
-
169
- // Resource-level pagination knobs (no custom queryParser needed):
170
- defineResource({ name: 'pipeline', adapter, defaultLimit: 200, maxLimit: 500 });
171
- ```
172
-
173
- A `?limit=` above the cap is **clamped to it**, not rejected (2.33 — see Query parsing). The effective cap rides in the OpenAPI parameter description.
174
-
175
- ## fieldRules
176
-
177
- | Flag | Effect |
178
- |---|---|
179
- | `systemManaged` | Strip from body, drop from `required[]`. Framework stamps the value. |
180
- | `preserveForElevated` | Elevated admins keep the field on ingest (cross-tenant writes). |
181
- | `immutable` / `immutableAfterCreate` | Omit from update body. |
182
- | `optional` | Strip from `required[]` without touching `properties`. |
183
- | `nullable` | Widen JSON-Schema `type` to include null. |
184
- | `hidden` | Block from response projection + OpenAPI. |
185
- | `minLength` · `maxLength` · `min` · `max` · `pattern` · `enum` · `description` | Map to AJV + OpenAPI. |
186
-
187
- Mongoose model constraints take precedence; `fieldRules` supplements what the model doesn't declare.
188
-
189
- ## Presets
190
-
191
- | Preset | Routes added | Config |
192
- |---|---|---|
193
- | `softDelete` | `GET /deleted`, `POST /:id/restore` | `{ deletedField }` |
194
- | `slugLookup` | `GET /slug/:slug` | `{ slugField }` |
195
- | `tree` | `GET /tree`, `GET /:parent/children` | `{ parentField }` |
196
- | `ownedByUser` | (middleware only) | `{ ownerField }` |
197
- | `multiTenant` | (middleware only) | `{ tenantField }` or `{ tenantFields: [...] }` |
198
- | `audited` | (middleware only) | — |
199
- | `bulk` | `POST/PATCH/DELETE /bulk` | `{ operations?, maxCreateItems? }` |
200
- | `filesUpload` | `POST /upload`, `GET /:id`, `DELETE /:id` | `{ storage, sanitizeFilename?, allowedMimeTypes?, maxFileSize? }` |
201
- | `search` | `POST /search`, `/search-similar`, `/embed` | `{ repository?, search?, similar?, embed? }` |
202
-
203
- ```typescript
204
- presets: ['softDelete', { name: 'multiTenant', tenantField: 'organizationId' }]
205
- ```
206
-
207
- **`tenantField: false`** disables the silent org filter — use it for lookup tables, platform settings, cross-org reports.
208
-
209
- **`idField`** picks the lookup column for `:id` (default `_id`). URL segment is always `:id`. A 404 on `PATCH /agents/foo` when `GET` works is usually a permission `filters` clause excluding the row — not an `idField` bug.
210
-
211
- ## Permissions
212
-
213
- A `PermissionCheck` returns `boolean | AuthorizationDecision` — build one with `allow({ policy?, scope? })` / `deny(reason?)`. `policy` is ANDed into the repo query (row-level ABAC); `scope` stamps attributes downstream. The pre-2.30 `{ granted, filters }` shape THROWS — never emit it.
214
-
215
- **Public but row-filtered** — use `allowPublic({ policy })`, not a hand-written `allow({ policy })`: a hand-written check lacks the `_isPublic` flag, so anonymous callers get 401.
216
-
217
- ```typescript
218
- list: allowPublic({ policy: { status: 'published' } }), // strangers: published only
219
- list: allowPublic({ policy: (ctx) => isElevated(scopeOf(ctx)) ? {} : { status: 'published' } }), // {} = unrestricted
220
- ```
221
-
222
- ```typescript
223
- import {
224
- allowPublic, requireAuth, requireRoles, requireOwnership,
225
- requireOrgMembership, requireOrgRole, requireTeamMembership,
226
- requireServiceScope, requireScopeContext, requireOrgInScope,
227
- allOf, anyOf, when, denyAll,
228
- createDynamicPermissionMatrix,
229
- } from '@classytic/arc/permissions';
230
-
231
- permissions: {
232
- list: allowPublic(),
233
- create: requireRoles(['admin', 'editor']),
234
- update: anyOf(requireOwnership('userId'), requireRoles(['admin'])),
235
- delete: allOf(requireAuth(), requireRoles(['admin'])),
236
- bulkImport: anyOf(requireOrgRole('admin'), requireServiceScope('jobs:bulk-write')),
237
- }
238
- ```
239
-
240
- **Custom check:**
241
-
242
- ```typescript
243
- import { allow, deny, type PermissionCheck } from '@classytic/arc/permissions';
244
-
245
- const requirePro = (): PermissionCheck => async (ctx) => {
246
- if (!ctx.user) return deny('Auth required');
247
- return ctx.user.plan === 'pro' ? allow() : deny('Pro plan required');
248
- };
249
- ```
250
-
251
- **Field-level:**
252
-
253
- ```typescript
254
- import { fields } from '@classytic/arc/permissions';
255
- fields: {
256
- password: fields.hidden(),
257
- salary: fields.visibleTo(['admin', 'hr']),
258
- role: fields.writableBy(['admin']),
259
- email: fields.redactFor(['viewer'], '***'),
260
- }
261
- ```
262
-
263
- **Dynamic ACL (DB-backed):**
264
-
265
- ```typescript
266
- const acl = createDynamicPermissionMatrix({
267
- resolveRolePermissions: (ctx) => aclService.getRoleMatrix(ctx.user.orgId),
268
- cacheStore: new RedisCacheStore({ client: redis, prefix: 'acl:' }),
269
- });
270
- permissions: { list: acl.canAction('product', 'read') }
271
- ```
272
-
273
- `requireRoles()` checks BOTH platform roles (`user.role`) and org roles (`scope.orgRoles`). For mixed human + machine routes, combine with `requireServiceScope(...)` via `anyOf(...)`.
274
-
275
- ## RequestScope
276
-
277
- Five kinds, populated by your auth function. **Always read via accessors from `@classytic/arc/scope`** — never direct property access.
278
-
279
- ```typescript
280
- type RequestScope =
281
- | { kind: 'public' }
282
- | { kind: 'authenticated'; userId?; userRoles? }
283
- | { kind: 'member'; userId?; userRoles; organizationId; orgRoles; teamId?; context?; ancestorOrgIds? }
284
- | { kind: 'service'; clientId; organizationId; scopes?; context?; ancestorOrgIds?; mandate?; dpopJkt? }
285
- | { kind: 'elevated'; userId?; organizationId?; elevatedBy; context?; ancestorOrgIds? };
286
-
287
- import {
288
- isMember, isService, isElevated, hasOrgAccess,
289
- getOrgId, getUserId, getUserRoles, getOrgRoles, getServiceScopes,
290
- getScopeContext, getAncestorOrgIds, isOrgInScope,
291
- requireOrgId, requireUserId, // throwing accessors for handler boundaries
292
- } from '@classytic/arc/scope';
293
- ```
294
-
295
- | Helper | `member` | `service` | `elevated` |
296
- |---|---|---|---|
297
- | `requireOrgMembership()` | ✅ | ✅ | ✅ |
298
- | `requireOrgRole(roles)` | role match | ❌ | bypass |
299
- | `requireServiceScope(scopes)` | ❌ | scope match | bypass |
300
- | `requireTeamMembership()` | `teamId` set | n/a | bypass |
301
- | `requireOrgInScope(target)` | target in chain | target in chain | bypass |
302
-
303
- Populate `scope.context` / `scope.ancestorOrgIds` in your auth function for branch/region scoping and parent-child org chains. Then `multiTenantPreset({ tenantFields: [...] })` auto-filters by every dimension. → [references/multi-tenancy.md](references/multi-tenancy.md)
304
-
305
- ## Authentication
306
-
307
- Discriminated union on `type`:
308
-
309
- ```typescript
310
- auth: { type: 'jwt', jwt: { secret, expiresIn: '15m' } } // arc JWT
311
- auth: { type: 'betterAuth', betterAuth: createBetterAuthAdapter({ auth }) } // Better Auth
312
- auth: { type: 'custom', plugin: myAuthPlugin } // any Fastify plugin
313
- auth: { type: 'authenticator', authenticate: async (req, reply) => { … } } // ad-hoc fn
314
- auth: false // internal services
315
- ```
316
-
317
- Decorates `app.authenticate` / `app.optionalAuthenticate` / `app.authorize`.
318
-
319
- **Better Auth** is arc's recommended path for SaaS with orgs. Kit overlays read whatever BA plugins you enabled (`organization`, `twoFactor`, `admin`, `bearer`, `apiKey` from `@better-auth/api-key`). Bulk-stub populate models with `registerBetterAuthStubs(mongoose, { plugins, extraCollections })`; per-resource overlay with `createBetterAuthOverlay({ auth, mongoose, collection })`. Sqlitekit is symmetric. Full recipes (multi-plugin matrix, API-key flow, write path) → [references/auth.md](references/auth.md).
320
-
321
- ## Authoritative gotchas
322
-
323
- - **Field-write reject (default).** Requests carrying non-writable fields → 403 with denied list. Opt into silent strip: `defineResource({ onFieldWriteDenied: 'strip' })`.
324
- - **Immutable writes are STRIPPED, not refused (default).** `PATCH {"type":"rent"}` on an `immutable` field returns 200 with the value unchanged. Opt into 403: `defineResource({ onImmutableWrite: 'reject' })`, or `ARC_STRICT_IMMUTABLE_WRITES=true`. Separate from `onFieldWriteDenied` because a full-object PATCH echoing an immutable field back UNCHANGED is legitimate, and the sanitizer has no stored document to tell that from a real change — turn it on if you send partial patches.
325
- - **Log redaction is REPLACED, not merged.** Setting `logger.redact` makes yours the whole policy; arc's defaults stop applying. Superset them: `import { DEFAULT_LOGGER_REDACT_PATHS } from '@classytic/arc/factory'` and spread it into your list, rather than hand-copying (a copy drifts — one host's had lost `*.passwordHash`).
326
- - **Error disclosure derives from `preset`, falling back to the environment.** `includeStack` and `exposeInternalMessages` are both derived, and host keys MERGE over them — stating one no longer resets the other. Direct `errorHandlerPlugin` registration skips the preset derivation entirely.
327
- - **multiTenant injects org on UPDATE.** Body `organizationId` is overwritten with caller's scope (closes tenant-hop).
328
- - **`request.user`** is `Record<string, unknown> | undefined`. Guard with `if (req.user)` on public routes.
329
- - **Arc reads singular `user.role`** (string, comma-separated, or array). Don't put a plural `roles` field on the model.
330
- - **`verifySignature(body, …)`** throws on parsed body — pass `req.rawBody`.
331
- - **MCP tools fail-closed.** A resource action without per-action perm + no `actionPermissions` + no `permissions.update` fallback → throws at tool generation. Declare `allowPublic()` to opt into unauthenticated.
332
- - **Better Auth roles.** BA stores `member.role = "admin,recruiter"` (comma-separated). Arc splits into `scope.orgRoles = ['admin', 'recruiter']`; `?role=admin` won't match — use `role[like]=admin`.
333
- - **Read-only repositories refuse write ROUTES at boot (2.33).** Kits' Better Auth overlays are sealed by default (`capabilities.readOnly`) — BA owns hashing, session revocation, org cascades. Mounting `create`/`update`/`delete` over one is boot-fatal: disable those routes, or pass the kit's `unsafeWritable: true` for administrative repair only. Normal identity mutations go through `auth.api`.
334
- - **Arc closes only stores/transports it BUILT (2.33).** One you hand to `idempotencyPlugin` / `eventPlugin` / `queryCachePlugin` stays yours to close — arc used to close every one, which wiped a co-resident app's live idempotency records.
335
- - **Idempotency self-checks its store at boot (2.33).** A probe write must read back under its own key and NOT under another; registration throws otherwise. Catches a filter-stripping repository (a pathless Mongoose schema under `strictQuery: true` strips filters to `{}`), which otherwise replays cached responses across keys AND users. `selfCheck: false` to disable; the adapter's per-read identity checks remain.
336
-
337
- ## routeGuards + defineGuard
338
-
339
- Apply guards to **every** route on a resource (CRUD + custom + preset):
340
-
341
- ```typescript
342
- import { defineGuard } from '@classytic/arc/utils';
343
-
344
- const tenantGuard = defineGuard({
345
- name: 'tenant',
346
- resolve: (req) => {
347
- const orgId = req.headers['x-org-id'] as string;
348
- if (!orgId) throw new Error('Missing x-org-id');
349
- return { orgId, actorId: req.user?.id ?? 'system' };
350
- },
351
- });
352
-
353
- defineResource({
354
- name: 'procurement',
355
- routeGuards: [tenantGuard.preHandler],
356
- routes: [{
357
- method: 'GET', path: '/summary', permissions: requireAuth(),
358
- rawHandler: async (req, reply) => {
359
- const { orgId } = tenantGuard.from(req);
360
- reply.send({ orgId });
361
- },
362
- }],
363
- });
364
- ```
365
-
366
- **Order:** auth → permissions → cache/idempotency → `routeGuards` → per-route `preHandler`.
367
-
368
- ## Query parsing
369
-
370
- ```
371
- GET /products?page=2&limit=20&sort=-createdAt&select=name,price
372
- GET /products?price[gte]=100&status[in]=active,featured&search=keyword
373
- GET /products?after=<cursor_id>&limit=20 # keyset
374
- GET /products?populate[category][select]=name,slug
375
- GET /products?filter[status]=active&filter[price][gte]=100 # bracket envelope (2.16)
376
- ```
377
-
378
- Operators: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`, `like`, `regex`, `exists`.
379
-
380
- **Whitelisted parser (MCP filter auto-derive):**
381
-
382
- ```typescript
383
- import { QueryParser } from '@classytic/mongokit';
384
-
385
- defineResource({
386
- queryParser: new QueryParser({
387
- allowedFilterFields: ['status', 'category', 'orgId'],
388
- allowedSortFields: ['createdAt', 'price'],
389
- allowedOperators: ['eq', 'gte', 'lte', 'in'],
390
- }),
391
- schemaOptions: { query: { allowedPopulate: ['category'], allowedLookups: ['categories'] } },
392
- });
393
- ```
394
-
395
- **An unknown filter key is DROPPED by default, and dropping WIDENS.** `?filters[status]=pending`
396
- against a parser that does not whitelist `status` returns 200 with every row unfiltered — the
397
- caller asked to narrow and got a broader set. Refuse instead:
398
-
399
- ```typescript
400
- new QueryParser({ allowedFilterFields: [...], strictFilterFields: true }) // 400 ValidationError
401
- ```
402
-
403
- Off by default (an unconditional throw would reject requests that work today). Fleet-wide via
404
- `ARC_STRICT_QUERY_PARAMS=true`; an explicit `false` beats the env. Only the FILTER whitelist —
405
- a dropped sort or operator degrades ordering, it does not widen the row set.
406
-
407
- **`?limit` above the cap CLAMPS, it does not 400** (2.33). The parser and `QueryResolver` both
408
- clamp, and the querystring schema no longer emits `maximum` — it used to reject first, making the
409
- documented clamp unreachable and turning a benign over-ask into a 400 that callers render as an
410
- empty list. The cap is in the parameter description instead, so OpenAPI still shows it.
411
-
412
- **One cap, one owner.** Page size is capped by the parser, the repository's pagination engine and
413
- arc — lowest wins silently. Arc defers to the parser's `maxLimit` when the host states none, and
414
- WARNS at boot when the parser allows more than the repository (`pagination-cap-mismatch`).
415
- Configure both to the same number.
416
-
417
- ## Aggregations
418
-
419
- `GET /:prefix/aggregations/:name` per entry. Portable `$match → $group → $project → $sort → $limit` against `repo.aggregate(req, options)` — same shape across kits.
420
-
421
- ```typescript
422
- import { defineResource, defineAggregation } from '@classytic/arc';
423
-
424
- defineResource({
425
- name: 'transaction',
426
- adapter,
427
- presets: [multiTenantPreset({ tenantField: 'organizationId' })],
428
- permissions: { list: canViewRevenue() },
429
- aggregations: {
430
- byPaymentMethod: defineAggregation({
431
- groupBy: 'method',
432
- measures: { total: 'sum:amount', count: 'count' },
433
- sort: { total: -1 },
434
- cache: { staleTime: 60, swr: true, tags: ['revenue'] },
435
- permissions: canViewRevenue(),
436
- }),
437
- byDay: defineAggregation({
438
- dateBuckets: { day: { field: 'createdAt', interval: 'day' } },
439
- groupBy: 'flow',
440
- measures: { total: 'sum:amount', count: 'count' },
441
- requireDateRange: { field: 'createdAt', maxRangeDays: 365 },
442
- permissions: canViewRevenue(),
443
- }),
444
- },
445
- });
446
- ```
447
-
448
- Safety guards on the declaration: `requireFilters`, `requireDateRange { field, maxRangeDays }`, `maxGroups`. Caller query-string filters compose with `groupBy` / measures. SWR + `tags` invalidation tie aggregations to CRUD writes. Every aggregation auto-exports as an MCP tool.
449
-
450
- Tenant scope flows through `options` (second arg), NOT into `aggReq.filter`. The kit's multi-tenant plugin handles type coercion (string → ObjectId, UUID/text, etc.). **Aggregation-only resources** (`disableDefaultRoutes: true` + no controller) work — arc falls back to the adapter's repo. If aggregations exist without a repo AND without `materialized`, `defineResource()` throws at boot.
451
-
452
- ### `materialized` hook — escape hatch + footgun
453
-
454
- When a kit can't express your aggregation in the portable IR (`$graphLookup`, window functions, custom SQL), declare a `materialized` hook to own dispatch yourself:
455
-
456
- ```typescript
457
- defineAggregation({
458
- measures: { count: 'count' },
459
- permissions: canViewRevenue(),
460
- materialized: async (ctx) => {
461
- // ctx = { filter, orgId, userId, requestId, query }
462
- // ⚠️ ctx.filter contains ONLY the declaration filter + caller query string.
463
- // Tenant scope is in ctx.orgId, NOT in ctx.filter. Soft-delete is NOT merged.
464
- // Bypassing repo.aggregate() means bypassing the kit's hook pipeline.
465
-
466
- // ✅ Right (mongokit) — route through repo.aggregatePipeline so the kit's
467
- // multi-tenant + soft-delete + audit hooks all run:
468
- const rows = await orderRepo.aggregatePipeline(
469
- [{ $group: { _id: '$flow', total: { $sum: '$amount' } } }],
470
- { organizationId: ctx.orgId, userId: ctx.userId, requestId: ctx.requestId },
471
- );
472
- return { rows };
473
-
474
- // ❌ Wrong — Model.aggregate(...) bypasses kit plugins; tenant + soft-delete
475
- // leak across orgs. Never call the driver directly in a materialized hook.
476
- },
477
- });
478
- ```
479
-
480
- For sqlitekit / custom adapters without an `aggregatePipeline` equivalent, **you** must inject tenant + soft-delete clauses into the SQL before executing — `ctx.filter` is not sufficient. Prefer the portable `repo.aggregate(req, options)` path whenever the IR can express your shape.
481
-
482
- ## QueryCache
483
-
484
- TanStack-Query-style server cache with SWR + auto-invalidation on mutations:
485
-
486
- ```typescript
487
- const app = await createApp({ arcPlugins: { queryCache: true } });
488
-
489
- defineResource({
490
- cache: {
491
- staleTime: 30, gcTime: 300, tags: ['catalog'],
492
- invalidateOn: { 'category.*': ['catalog'] }, // event pattern → tag targets
493
- list: { staleTime: 60 },
494
- byId: { staleTime: 10 },
495
- },
496
- });
497
- ```
498
-
499
- POST/PATCH/DELETE bumps resource version. Response header: `x-cache: HIT | STALE | MISS`. `runtime: 'distributed'` requires `stores.queryCache: RedisCacheStore`.
500
-
501
- ## Transactional writes (2.33)
502
-
503
- `transactional: true` runs the PERSISTENCE step inside `withTransaction`. Write verbs receive the tx-bound repository plus `ctx.uow` — the join point for work outside the repository:
504
-
505
- ```typescript
506
- defineResource({
507
- name: 'order',
508
- adapter,
509
- transactional: true,
510
- writes: {
511
- create: async (data, ctx) => {
512
- const order = await ctx.repository.create(data); // tx-bound
513
- await outbox.store(event, { session: ctx.uow?.session }); // SAME transaction
514
- return order;
515
- },
516
- },
517
- });
518
- ```
519
-
520
- - Hooks stay OUTSIDE the retry — before/after run once; only persistence re-runs.
521
- - Transient conflicts re-run with jittered backoff; `VersionConflictError` surfaces (409), never retried.
522
- - **Retry authority is the KIT's.** mongokit declares `transactionRetry: 'managed'` (its driver already retries internally) and is called exactly once; sqlitekit declares `'caller'` and gets the envelope's loop. Arc never stacks a second policy.
523
- - **BOOT-FATAL** without `withTransaction`, and at REGISTRATION when the repository reports `capabilities.transactions !== true` (standalone Mongo, D1, unconfirmed topology). The capability is checked at registration, not at `defineResource()`, because that usually runs at module import — before `beforeBoot()` connects.
524
- - `ctx.uow.session` is empty on connection-bound backends (SQLite); the tx-bound repo is the join point there.
525
-
526
- ## Events
527
-
528
- CRUD events auto-emit: `{resource}.created` / `{resource}.updated` / `{resource}.deleted`. Manual publish:
529
-
530
- ```typescript
531
- await app.events.publish('order.created', { orderId: '123' });
532
- await app.events.subscribe('order.*', async (event) => { … });
533
- ```
534
-
535
- Transports: Memory · Redis Pub/Sub (fire-and-forget) · Redis Streams (durable, consumer groups, DLQ). Event types live in `@classytic/primitives/events` (`createEvent`, `createChildEvent`, `matchEventPattern`, …); arc re-exports the runtime `MemoryEventTransport` only.
536
-
537
- **Outbox** (at-least-once via transactional outbox) — prefer the MODULE, so the store is a slot other modules depend on rather than a value threaded by hand:
538
-
539
- ```typescript
540
- createApp({ modules: [createOutboxModule({ store: repositoryAsOutboxStore(outboxRepo) })] });
541
- // Dev: createOutboxModule({ store: new MemoryOutboxStore() })
542
- ```
543
-
544
- The relay arm is `kind: 'relay'`, so `role: 'relay'` deployments drain it. It resolves the RAW transport, never the `fastify.events` facade (the facade fails open, which would acknowledge rows whose publish failed) — no transport is boot-fatal. **Fencing (2.33):** stores that support `claimPendingFenced` mint a token in the claim CAS; a relay that lost its lease mid-batch cannot ack or re-schedule a row a successor already owns. Feature-detected end to end.
545
-
546
- **Durable webhooks (2.33)** — delivery survives crash and deploy, using the outbox machinery rather than a second queue:
547
-
548
- ```typescript
549
- const store = repositoryAsOutboxStore(deliveryRepo);
550
- createApp({
551
- modules: [createDurableWebhookModule({ store })], // relay does the signed POST
552
- plugins: async (f) => f.register(webhookPlugin, { durable: { store } }), // enqueue, don't POST
553
- });
554
- ```
555
-
556
- One row per (event × subscription), deterministic id so an at-least-once upstream enqueues each delivery exactly once. Transient failures (network/timeout/429/5xx) retry with backoff; 4xx dead-letters on the FIRST attempt. `durable` + `retry` together is a registration error.
557
-
558
- Full event recipes (retry, DLQ, dual-publish warnings, idempotency keys) → [references/events.md](references/events.md).
559
-
560
- ## Hooks
561
-
562
- Inline on resource. `ResourceHookContext` = `{ data, user?, meta? }`; `meta` has `id` and `existing` for update/delete.
563
-
564
- ```typescript
565
- hooks: {
566
- beforeCreate: async (ctx) => { ctx.data.slug = slugify(ctx.data.name); },
567
- afterCreate: async (ctx) => { analytics.track('created', { id: ctx.data._id }); },
568
- beforeUpdate: async (ctx) => { /* ctx.meta.existing has the pre-image */ },
569
- beforeDelete: async (ctx) => { if (ctx.data.isProtected) throw new Error('locked'); },
570
- }
571
- ```
572
-
573
- App-level (cross-resource): `createHookSystem()` + `beforeCreate(hooks, 'product', fn)` from `@classytic/arc/hooks`.
574
-
575
- ## Errors
576
-
577
- ```typescript
578
- import { ArcError, NotFoundError, ValidationError, createDomainError } from '@classytic/arc';
579
-
580
- throw new NotFoundError('Product'); // 404
581
- throw createDomainError('SELF_REFERRAL', 'Cannot self-refer', 422, { field });
582
- ```
583
-
584
- Wire envelope: `{ code, message, status, meta?, correlationId? }`. HTTP status is the discriminator — no `success` field. Custom mappers:
585
-
586
- ```typescript
587
- errorHandler: {
588
- errorMappers: [{
589
- type: AccountingError,
590
- toResponse: (err) => ({ status: err.status, code: err.code, message: err.message }),
591
- }],
592
- }
593
- ```
594
-
595
- Modules ship their own via `defineModule({ errorMappers })` (2.21) — merged into the app handler at boot; host-level mappers keep priority.
596
-
597
- ## Testing
598
-
599
- ```typescript
600
- import { createTestApp, expectArc } from '@classytic/arc/testing';
601
-
602
- const ctx = await createTestApp({
603
- resources: [productResource],
604
- authMode: 'jwt', // 'jwt' | 'better-auth' | 'none'
605
- connectMongoose: true, // in-memory Mongo
606
- });
607
- ctx.auth.register('admin', { user: { id: '1', role: 'admin' }, orgId: 'org-1' });
608
-
609
- const res = await ctx.app.inject({
610
- method: 'POST', url: '/products',
611
- headers: ctx.auth.as('admin').headers,
612
- payload: { name: 'Widget' },
613
- });
614
- expectArc(res).ok().hidesField('password');
615
- await ctx.close();
616
- ```
617
-
618
- Three entry points: `createTestApp` (custom), `createHttpTestHarness` (~16 auto-generated CRUD/perm/validation tests per resource), `runStorageContract` (adapter conformance). → [references/testing.md](references/testing.md)
619
-
620
- ## CLI
621
-
622
- ```bash
623
- arc init my-api --mongokit --better-auth --ts # scaffold
624
- arc generate resource product # alias: arc g r product
625
- arc generate resource product --mcp # + MCP tools file
626
- arc generate mcp analytics # standalone MCP file
627
- arc docs ./openapi.json --entry ./dist/index.js # emit OpenAPI
628
- arc introspect --entry ./dist/index.js
629
- arc describe ./dist/resources.js --json # JSON metadata
630
- arc doctor # diagnose env
631
- ```
632
-
633
- Set `"mcp": true` in `.arcrc` to always generate `.mcp.ts` alongside resources.
634
-
635
- ## MCP (AI agent tools)
636
-
637
- Resources auto-generate Model Context Protocol tools — same permissions, same field rules. Stateless by default.
638
-
639
- ```typescript
640
- import { mcpPlugin } from '@classytic/arc/mcp';
641
-
642
- await app.register(mcpPlugin, {
643
- resources: [productResource, orderResource],
644
- auth: false, // or: getAuth() | custom function
645
- exclude: ['credential'],
646
- overrides: { product: { operations: ['list', 'get'] } },
647
- });
648
- ```
649
-
650
- **Per-resource opt-out:** `defineResource({ mcp: false })` — exclude a resource from MCP tool generation entirely. Useful for internal-admin or write-heavy resources where you don't want LLMs poking.
651
-
652
- **Auth modes** — `false` | `getAuth()` (Better Auth OAuth 2.1) | `createMcpAuthFromBetterAuthApiKey(getAuth(), { orgFromMetadata: true })` (BA API-key plugin — handles `referenceId`/`userId` fallback + `metadata.organizationId` extraction) | custom function returning `{ userId, organizationId, roles }` (human) or `{ clientId, organizationId, scopes }` (service). `PermissionResult.filters` flow into MCP tools exactly like REST.
653
-
654
- **Tool-name collisions** — preset vs user (e.g. `softDelete` route vs `actions.restore`) auto-namespace to `softdelete_restore_<resource>`; every other collision shape throws `ArcError('arc.mcp.tool_name_collision')` naming both sources.
655
-
656
- **Custom tools** — co-locate with resources (`order.mcp.ts`), wire via `extraTools`. **AI SDK bridge** — expose AI SDK `tool()` defs via `buildMcpToolsFromBridges([...])`.
657
-
658
- Connect Claude CLI: `claude mcp add --transport http my-api http://localhost:3000/mcp`. Full recipes → [references/mcp.md](references/mcp.md).
659
-
660
- ### AI SDK streaming → Fastify
661
-
662
- `streamResponse: true` routes that return a Web `ReadableStream` (Vercel AI SDK's `result.toUIMessageStream()`, `fetch().body`) auto-pipe through `pipeUIMessageStreamToReply()` — no `JsonToSseTransformStream` boilerplate.
663
-
664
- ```typescript
665
- import { streamText } from 'ai';
666
-
667
- defineResource({
668
- name: 'chat',
669
- customRoutesOnly: true,
670
- routes: [{
671
- method: 'POST', path: '/', streamResponse: true,
672
- permissions: requireAuth(),
673
- rawHandler: async (req) => {
674
- const result = streamText({ model, messages: req.body.messages });
675
- return result.toUIMessageStream(); // arc pipes it for you
676
- },
677
- }],
678
- });
679
- ```
680
-
681
- For manual control: `import { pipeUIMessageStreamToReply, UI_MESSAGE_STREAM_HEADERS } from '@classytic/arc/utils'`. Client disconnect cancels the source stream (no zombie LLM spend).
682
-
683
- ## Tenant cleanup (GDPR / SOX / HIPAA)
684
-
685
- Per-resource strategy + one auth-lifecycle wire-up:
686
-
687
- ```typescript
688
- defineResource({
689
- name: 'invoice',
690
- tenantField: 'organizationId',
691
- onTenantDelete: {
692
- strategy: { type: 'anonymize', fields: { customerName: '[REDACTED]', email: null } },
693
- priority: 50, batchSize: 1000,
694
- },
46
+ presets: ['softDelete', { name: 'multiTenant', tenantField: 'organizationId' }],
47
+ permissions: { list: allowPublic(), get: allowPublic(), create: requireRoles(['admin']),
48
+ update: requireRoles(['admin']), delete: requireRoles(['admin']) },
49
+ schemaOptions: { fieldRules: { organizationId: { systemManaged: true } } },
695
50
  });
696
- defineResource({ name: 'event', onTenantDelete: { strategy: { type: 'hard' } } });
697
- defineResource({ name: 'ledger', onTenantDelete: { strategy: { type: 'skip', reason: 'SOX retention' } } });
698
-
699
- import { cascadeDeleteForOrganization, assertNoTenantData } from '@classytic/arc/registry';
700
-
701
- betterAuth.org.afterDelete = async ({ organizationId }) => {
702
- const report = await cascadeDeleteForOrganization(fastify.arc.registry, {
703
- organizationId, concurrency: 4, logger: fastify.log,
704
- });
705
- if (report.failures.length > 0) await alerting.fire({ report });
706
- };
707
- ```
708
-
709
- Strategies: `hard` · `soft` · `anonymize` (`fields` static or `(doc) => value`) · `skip` (`reason` mandatory). Resources without `onTenantDelete` are never touched. **Index `tenantField`** on every cascading resource or chunked SELECTs run O(n²). Compliance smoke: `assertNoTenantData(registry, { organizationId })`.
710
-
711
- ## Enterprise auth (opt-in)
712
-
713
- | Capability | Surface | Reference |
714
- |---|---|---|
715
- | SCIM 2.0 provisioning (Okta / Azure AD / Google) | `@classytic/arc/scim` — `scimPlugin({ users, groups, bearer })` | [references/scim.md](references/scim.md) |
716
- | Agent mandates + DPoP (AP2 / x402 / MCP authz) | `@classytic/arc/permissions` — `requireAgentScope`, `requireMandate`, `requireDPoP` | [references/agent-auth.md](references/agent-auth.md) |
717
- | Auth-event audit bridge | `@classytic/arc/auth/audit` — `wireBetterAuthAudit({ events })` | [references/enterprise-auth.md](references/enterprise-auth.md) |
718
-
719
- Out of scope: SAML (use BA SAML plugin), session storage (BA `secondaryStorage`), DPoP crypto (one `jose.dpop.verify()` in your `authenticate`), device trust (Castle / Stytch).
720
-
721
- ## Audit per-resource
722
-
723
- ```typescript
724
- await fastify.register(auditPlugin, { autoAudit: { perResource: true } });
725
-
726
- defineResource({ name: 'order', audit: true });
727
- defineResource({ name: 'invoice', history: true }); // 2.22: injects GET /:id/history from audit rows; implies audit: true (gate: update→get→requireAuth; override via { permissions, limit })
728
- defineResource({ name: 'payment', audit: { operations: ['delete'] } });
729
- defineResource({ name: 'product' }); // not audited
730
-
731
- // Manual (MCP tools / read auditing)
732
- await app.audit.custom('order', req.params.id, 'refund', { reason }, { user });
733
- ```
734
-
735
- ## Usage counters + plan limits (2.22)
736
-
737
- `@classytic/arc/usage` — `usagePlugin` decorates `fastify.usage` with per-actor, per-UTC-month counters (`record`/`summary`/`period`/`actorOf`; actor chain org → user → client → ip). Auto-tracks `api.requests` (default on) + `api.egress.bytes` (opt-in); recording is fail-safe (a throwing `UsageStore` never fails a request). Stores: `MemoryUsageStore` (default, single-process) and `RedisUsageStore` (2.41 — `HINCRBY`, the right shape for a hot per-request counter) both from `@classytic/arc/usage`; or a kit's (`@classytic/mongokit/usage`) when counters belong beside domain data. `RedisUsageStore` keeps counters forever by default — `retentionSeconds` is opt-in, because expiring billing history on an unchosen schedule is silent (`summary()` returns `{}` for an expired bucket and a never-written one alike). Pair with `createApp({ rateLimit: { plan: { resolve, limits: { free: { max: 60 }, enterprise: false }, default: 'free' } } })` for per-plan ceilings — `false` = unlimited, unknown/throwing resolvers fall back to `default` then global `max`, and buckets follow the tenant key chain by default. Caveat: the limiter runs before route auth, so `resolve` sees the raw request.
738
51
 
739
- ## Runtime capability registry (2.33)
740
-
741
- Under `runtime: 'distributed'`, subsystems holding process-local state must declare it — the end-of-boot audit FAILS the app on undeclared memory state, naming every violator:
742
-
743
- ```typescript
744
- import { declareRuntimeCapability } from '@classytic/arc/utils';
745
-
746
- declareRuntimeCapability(fastify, {
747
- subsystem: 'billing.sequence-cache',
748
- durability: 'memory', // 'memory' | 'shared'
749
- detail: 'invoice numbering cached per process',
750
- // accepted: true, // ONLY when per-process is intended by design
751
- // // (logged, never fatal). Must be stated by the
752
- // // declarant — the audit never infers it.
52
+ const app = await createApp({
53
+ preset: 'production', beforeBoot: connectDb,
54
+ auth: { type: 'jwt', jwt: { secret: process.env.JWT_SECRET } },
55
+ resources: await loadResources(import.meta.url),
753
56
  });
754
57
  ```
755
58
 
756
- `createApp`'s constructor-time guard only sees what it is passed; state a host wires inside `plugins()` was invisible to it and lived on a checklist. This makes the checklist enforcement. Declare from anywhere a registration reaches — `plugins()`, a module phase, or your own encapsulated `fastify.register()`; all land in the one audit (2.41).
757
-
758
- **Since 2.41 every memory-backed default arc ships declares itself**: `auth.sessions`, `usage.store`, `audit.store`, `cache.query`, `permissions.dynamic-cache` (pass `fastify:` to the matrix — it has no handle of its own), `websocket.adapter`, `websocket.pushref-store`, `webhooks.store`. `http.response-cache` declares `accepted` (per-replica by design). So a distributed app that booted before 2.41 can now fail on a default it was silently running replica-local — the error names each one, and `references/production.md` has the store-by-store fix table.
759
-
760
- ## Adapters
761
-
762
- Cross-framework adapter contract lives in `@classytic/repo-core/adapter`. Every kit-specific adapter ships from its kit's `/adapter` subpath; arc itself has zero kit-bound adapters.
59
+ Validated route, parsed once:
763
60
 
764
61
  ```typescript
765
- import { createMongooseAdapter } from '@classytic/mongokit/adapter';
766
- import { createDrizzleAdapter } from '@classytic/sqlitekit/adapter';
767
- import { createPrismaAdapter } from '@classytic/prismakit/adapter';
768
-
769
- import type { DataAdapter, RepositoryLike, AdapterRepositoryInput }
770
- from '@classytic/repo-core/adapter';
771
- // MinimalRepo<TDoc> — 5-method floor (getAll, getById, create, update, delete)
772
- // StandardRepo<TDoc> — MinimalRepo + optional batch ops, CAS, soft-delete, aggregate, …
773
- // Arc feature-detects optional methods at call sites; missing methods → 501.
62
+ import { parsed, routeInput } from '@classytic/arc/core';
63
+ const body = z.object({ title: z.string().trim().min(2), tags: z.array(z.string()).default([]) });
64
+ routes: [{ method: 'POST', path: '/notes', permissions: requireAuth(), ...routeInput({ body }),
65
+ rawHandler: async (req, reply) => reply.send(await notes.create(parsed(body, req.body))) }]
774
66
  ```
775
67
 
776
- Custom kits implementing `DataAdapter<TDoc>` plug in identically. Kit-native repos plug in **without** `as RepositoryLike` casts.
68
+ Daily job: `scheduledJobs: [{ name: 'sweep', every: 600_000, daily: { hour: 2, zone: 'Asia/Dhaka', ledger }, handler: async (f, ctx) => sweep(ctx?.day) }]`.
777
69
 
778
- ## Controllers
70
+ Test: `const ctx = await createTestApp({ resources: [productResource] }); expectArc(await ctx.app.inject({ method: 'GET', url: '/products' })).ok();`
779
71
 
780
- `BaseController` is mixin-composed. The auto-built controller covers every preset; you only need a custom one to add domain methods.
72
+ ## Gotchas
781
73
 
782
- ```typescript
783
- import { BaseController, type IRequestContext, type IControllerResponse } from '@classytic/arc';
74
+ - `{ body: X }` as an action schema validates nothing (no `type`); pass the schema. `strictSchemas: true` makes it fatal.
75
+ - `.default()` stays optional on the wire (zod input direction); `.refine()` needs `routeInput` or `parse: true`.
76
+ - `request.user` is undefined on public routes: guard it.
77
+ - Public + row filter needs `allowPublic({ policy })`, not `allow({ policy })`.
78
+ - A non-writable field in a body is 403; an `immutable` field is silently stripped.
79
+ - An unknown filter key is dropped (widens results): `strictFilterFields: true`.
80
+ - `distributed` runtime needs shared stores and a schedule `lock` or `singleReplica`.
81
+ - Own `setNotFoundHandler` needs `errorHandler: { notFound: false }`.
82
+ - Refusing hook: `return reply.send(...)` or throw, never a bare send.
784
83
 
785
- class ProductController extends BaseController<Product> {
786
- constructor(opts: { tenantField?: string | false; idField?: string } = {}) {
787
- super(productRepo, { resourceName: 'product', ...opts });
788
- }
789
- async getFeatured(req: IRequestContext): Promise<IControllerResponse<Product[]>> {
790
- return { data: await this.repository.getAll({ filters: { isFeatured: true } }) };
791
- }
792
- }
793
-
794
- defineResource({ name: 'product', controller: new ProductController({ tenantField: '_id' }), tenantField: '_id' });
795
- ```
796
-
797
- When you pass your own controller, arc **cannot** thread `tenantField` / `schemaOptions` / `idField` / `cache` / `onFieldWriteDenied` into it. Forward via `super()` AND pass to `defineResource()`. Presets that inject controller fields (slugLookup, softDelete, tree) only reach arc's auto-built `BaseController` — extend `BaseController` or drop the preset.
798
-
799
- **Slim mixins** (no soft-delete/tree/slug/bulk on by default):
800
-
801
- ```typescript
802
- import { BaseCrudController, SoftDeleteMixin, BulkMixin, SlugMixin, TreeMixin } from '@classytic/arc';
803
- class OrderController extends SoftDeleteMixin(BulkMixin(BaseCrudController)) {}
804
- ```
805
-
806
- ## DX helpers
807
-
808
- ```typescript
809
- import type { ArcRequest } from '@classytic/arc';
810
- import { envelope } from '@classytic/arc';
811
- import { multipartBody } from '@classytic/arc/middleware';
812
-
813
- // Typed request — no `(req as any).user`
814
- rawHandler: async (req: ArcRequest, reply) => { req.user?.id; req.scope; req.signal; }
815
-
816
- // File upload — no-op for JSON requests, safe to always add
817
- defineResource({
818
- name: 'product',
819
- middlewares: { create: [multipartBody({ allowedMimeTypes: ['image/png'], maxFileSize: 5 * 1024 * 1024 })] },
820
- hooks: {
821
- 'before:create': async (data) => {
822
- if (data._files?.image) { data.imageUrl = await uploadToS3(data._files.image); delete data._files; }
823
- return data;
824
- },
825
- },
826
- });
827
-
828
- // SSE — preAuth runs before auth (EventSource can't set headers); rawHandler streams the response
829
- routes: [
830
- { preAuth: [(req) => { req.headers.authorization = `Bearer ${req.query.token}`; }] },
831
- { method: 'GET', path: '/stream', rawHandler: async (req, reply) => reply.send(stream) },
832
- ]
833
-
834
- // Per-route rate limit (2.20) — overrides the resource/app default for ONE endpoint.
835
- // `false` = never throttle, object = tighten, omit = inherit. Custom routes only;
836
- // actions share one POST /:id/action mount, so throttle an action by making it a route.
837
- routes: [
838
- { method: 'POST', path: '/export', handler: 'export', permissions: requireAuth(),
839
- rateLimit: { max: 5, timeWindow: '1 minute' } },
840
- { method: 'GET', path: '/health', handler: 'health', permissions: allowPublic(),
841
- rateLimit: false },
842
- ]
843
-
844
- // Per-resource opt-out of resourcePrefix (webhooks / admin routes)
845
- defineResource({ name: 'webhook', prefix: '/hooks', skipGlobalPrefix: true });
846
-
847
- // Reply helpers — opt-in via createApp({ replyHelpers: true })
848
- return reply.sendList({ method: 'offset', data, total, page, limit, pages, hasNext, hasPrev });
849
- return reply.stream(csvReadable, { contentType: 'text/csv', filename: 'export.csv' });
850
- ```
851
-
852
- ## Subpath imports
853
-
854
- ```typescript
855
- import { defineResource, BaseController, allowPublic } from '@classytic/arc';
856
- import { createApp, loadResources } from '@classytic/arc/factory';
857
- import { createMongooseAdapter } from '@classytic/mongokit/adapter';
858
- import type { DataAdapter, RepositoryLike } from '@classytic/repo-core/adapter';
859
- import { getUserId, getOrgId, requireOrgId } from '@classytic/arc/scope';
860
- import { mcpPlugin } from '@classytic/arc/mcp';
861
- import { createTestApp, expectArc } from '@classytic/arc/testing';
862
- ```
84
+ ## Never
863
85
 
864
- Full subpath map → [references/api-reference.md](references/api-reference.md).
86
+ - Hand-written `.parse()` in every handler, cron or marker-row gates, `setInterval` jobs, manual tenant filters.
87
+ - A bare `fastify.get()` (bypasses auth, OpenAPI, MCP).
88
+ - Reading `node_modules` for the API; deep imports.
865
89
 
866
90
  ## References
867
91
 
868
- - **[api-reference](references/api-reference.md)** — full subpath import map (every plugin, helper, type)
869
- - **[auth](references/auth.md)** — JWT, Better Auth, API key, custom auth, kit overlays
870
- - **[scim](references/scim.md)** — SCIM 2.0 plugin (Okta / Azure AD / Google Workspace)
871
- - **[agent-auth](references/agent-auth.md)** — DPoP + capability mandates (AP2 / x402 / MCP authz)
872
- - **[enterprise-auth](references/enterprise-auth.md)** — what's in vs out of the box
873
- - **[events](references/events.md)** — Transports, retry, outbox, idempotency
874
- - **[integrations](references/integrations.md)** — BullMQ jobs, WebSocket, EventGateway, Streamline, Webhooks
875
- - **[mcp](references/mcp.md)** — Tool generation, custom tools, AI SDK bridges, Better Auth OAuth 2.1
876
- - **[multi-tenancy](references/multi-tenancy.md)** — Scope ladder, `tenantField`, parent-child orgs, API-key auth
877
- - **[production](references/production.md)** — Health, audit, idempotency, tracing, metrics, versioning, SSE, bulk ops
878
- - **[testing](references/testing.md)** — Test app, mocks, fixtures, in-memory Mongo
92
+ - Core: `references/resources.md` defineResource, presets, fieldRules; `references/boot.md` createApp, roles, controllers, CLI; `references/validation.md` zod slots, routeInput; `references/querying.md` parser, aggregations, cache; `references/writes-hooks-errors.md` transactions, hooks, errors, audit
93
+ - Jobs: `references/schedules.md` interval and daily jobs, ledger
94
+ - Access: `references/permissions-scope.md` checks and scope; `references/auth-strategies.md`, `references/auth-better-auth.md`, `references/auth-better-auth-overlay.md`, `references/auth-api-keys.md`, `references/auth-permissions.md` auth setups; `references/multi-tenancy.md`, `references/tenancy-scope-install.md` tenants; `references/scim.md`, `references/agent-auth.md`, `references/enterprise-auth.md` enterprise auth
95
+ - Events: `references/events.md` bus, transports; `references/events-outbox.md` outbox; `references/integrations-jobs.md` BullMQ; `references/integrations-realtime.md` websocket; `references/integrations-webhooks.md`; `references/integrations-workflows.md`
96
+ - MCP: `references/mcp-setup.md`, `references/mcp-auth.md`, `references/mcp-custom-tools.md`, `references/mcp-testing.md`
97
+ - Ops: `references/production-boot.md` runtime, `references/production-distributed.md` stores table, `references/production-observability.md`, `references/production-shutdown.md`, `references/production-idempotency.md`, `references/production-audit.md`, `references/production-realtime.md`, `references/production-caching.md`, `references/production-api.md` versioning and rate limit, `references/production-reliability.md`, `references/usage-cleanup-capabilities.md` usage, tenant cleanup
98
+ - `references/testing.md` test app; `references/api-reference.md` subpath imports
99
+ - Skills: `arc-code-review` audit; `arc-module-publishing` ship a module