@classytic/arc 2.45.2 → 2.46.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 (321) hide show
  1. package/README.md +1 -1
  2. package/dist/{EventTransport-CiicKz2Z.d.mts → EventTransport-CYEoCJGe.d.mts} +0 -2
  3. package/dist/{EventTransport-DHb1tpu-.mjs → EventTransport-DNgD9NP4.mjs} +3 -4
  4. package/dist/{HookSystem-C1u0EUnt.mjs → HookSystem-DRbPzEcP.mjs} +3 -4
  5. package/dist/{QueryCache--5uAuYPW.d.mts → QueryCache-DdvrGG8Q.d.mts} +1 -3
  6. package/dist/{ResourceRegistry-D2jXWVN_.mjs → ResourceRegistry-Douk51fa.mjs} +15 -4
  7. package/dist/{acquire-DTkA8Lme.mjs → acquire-RbtvDg9s.mjs} +2 -3
  8. package/dist/{actionPermissions-DRVk6m7x.mjs → actionPermissions-De0AJ7hm.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-DeZMrHcm.mjs} +5 -6
  18. package/dist/{base-CZyixEQR.d.mts → base-HXNgPQww.d.mts} +1 -7
  19. package/dist/{boundedMap-DkKiPifd.mjs → boundedMap-2WBh3gM9.mjs} +2 -3
  20. package/dist/{buildHandler-BiZ4VATS.mjs → buildHandler-DxVOOBpw.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-BYRwYrUo.mjs} +3 -4
  24. package/dist/{claimed-ChI13rUR.mjs → claimed-DYlELdnm.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-CHZMUwBW.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-D9rS2BxO.mjs} +9 -12
  47. package/dist/{createActionRouter-CvH84dyx.mjs → createActionRouter-0qkCRzTL.mjs} +7 -8
  48. package/dist/{createAggregationRouter-DGyK2Hp6.mjs → createAggregationRouter-CUf5Esd9.mjs} +9 -10
  49. package/dist/{createApp-CKjZpmq9.mjs → createApp-DZIXfDKD.mjs} +49 -62
  50. package/dist/{createMcpServer-DSztofa9.d.mts → createMcpServer-DeVpqQF-.d.mts} +1 -3
  51. package/dist/{defineAggregation-BLza7Ca4.mjs → defineAggregation-bmKQ4NmC.mjs} +2 -3
  52. package/dist/{defineResource-CEo0gDCb.mjs → defineResource-CGmdmGwh.mjs} +78 -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-BJTsSnke.mjs → elevation-CzhqAyVN.mjs} +9 -10
  58. package/dist/{elevation-BW2J3tNj.d.mts → elevation-DPD0hcU-.d.mts} +0 -2
  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-dFyGOEoB.mjs} +16 -6
  63. package/dist/{errors-grZkIA8N.mjs → errors-BY8vzlP4.mjs} +2 -3
  64. package/dist/{errors-JYc9vwqE.d.mts → errors-DTo0me1o.d.mts} +0 -2
  65. package/dist/{eventPlugin-BtmA4-3P.d.mts → eventPlugin-BY38F6yK.d.mts} +1 -7
  66. package/dist/{eventPlugin-ItcYBGUs.mjs → eventPlugin-eMhAPtQA.mjs} +10 -12
  67. package/dist/{eventTypes-Ck6fD3ne.mjs → eventTypes-Do2KYeJx.mjs} +5 -8
  68. package/dist/events/index.d.mts +4 -16
  69. package/dist/events/index.mjs +8 -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-Dtn0IIRn.d.mts} +4 -10
  78. package/dist/{fields-BBSpf8pS.d.mts → fields-JTkrtO-r.d.mts} +0 -2
  79. package/dist/{fields-BRX0Krcj.mjs → fields-LnbCcvsw.mjs} +2 -3
  80. package/dist/{filter-merge-CDc7YMwX.mjs → filter-merge-BAWi019Q.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-oXoDnpJf.mjs} +7 -12
  83. package/dist/{headers-Cqkg4LzI.mjs → headers-DBd3Qheo.mjs} +3 -4
  84. package/dist/{health-PVt0VjOx.mjs → health-BlJu9GXS.mjs} +2 -3
  85. package/dist/{health-DyeP3mTW.mjs → health-Dp-3EC9o.mjs} +4 -7
  86. package/dist/hooks/index.d.mts +1 -1
  87. package/dist/hooks/index.mjs +2 -2
  88. package/dist/idempotency/index.d.mts +3 -9
  89. package/dist/idempotency/index.mjs +10 -13
  90. package/dist/idempotency/redis.d.mts +1 -1
  91. package/dist/idempotency/redis.mjs +3 -4
  92. package/dist/{index-Bxriq3so.d.mts → index-B5i9-vuP.d.mts} +4 -26
  93. package/dist/{index-Chgz3d0i.d.mts → index-BAXDo5eE.d.mts} +1 -7
  94. package/dist/{index-Beg3aNnK.d.mts → index-BTxzJ_MN.d.mts} +67 -25
  95. package/dist/{index-CUJvoyw3.d.mts → index-Bqfo8hLz.d.mts} +2 -24
  96. package/dist/{index-uhkUA5-U.d.mts → index-CUdaoCYt.d.mts} +13 -23
  97. package/dist/{index-WH7xgvxS.d.mts → index-DyJFTJLA.d.mts} +31 -92
  98. package/dist/index.d.mts +7 -9
  99. package/dist/index.mjs +12 -13
  100. package/dist/{init-jC3rMPzb.mjs → init-BOaNkLYb.mjs} +18 -35
  101. package/dist/{init-Cscs4lab.d.mts → init-CV2_Fw3H.d.mts} +0 -4
  102. package/dist/integrations/event-gateway.d.mts +3 -5
  103. package/dist/integrations/event-gateway.mjs +3 -4
  104. package/dist/integrations/index.d.mts +3 -3
  105. package/dist/integrations/index.mjs +1 -1
  106. package/dist/integrations/jobs/index.d.mts +1 -1
  107. package/dist/integrations/jobs/index.mjs +7 -11
  108. package/dist/integrations/mcp/index.d.mts +7 -39
  109. package/dist/integrations/mcp/index.mjs +8 -14
  110. package/dist/integrations/mcp/testing.d.mts +3 -5
  111. package/dist/integrations/mcp/testing.mjs +3 -4
  112. package/dist/integrations/streamline.d.mts +1 -3
  113. package/dist/integrations/streamline.mjs +4 -5
  114. package/dist/integrations/webhooks.d.mts +2 -4
  115. package/dist/integrations/webhooks.mjs +4 -5
  116. package/dist/integrations/websocket-pushref-redis.d.mts +2 -4
  117. package/dist/integrations/websocket-pushref-redis.mjs +2 -3
  118. package/dist/integrations/websocket-redis.d.mts +2 -4
  119. package/dist/integrations/websocket-redis.mjs +2 -3
  120. package/dist/integrations/websocket.d.mts +2 -2
  121. package/dist/integrations/websocket.mjs +13 -24
  122. package/dist/{interface-JJzwH4Ro.d.mts → interface-BmExzQRD.d.mts} +0 -2
  123. package/dist/{interface-BOk3YnTz.d.mts → interface-WR1U0K7t.d.mts} +0 -2
  124. package/dist/{jsonBody-ptwyzZQ-.mjs → jsonBody-DpRpKR_K.mjs} +3 -4
  125. package/dist/{keys-C1vFuSbv.mjs → keys-FBz6Ull-.mjs} +2 -3
  126. package/dist/{loadResources-CHPDyIPn.mjs → loadResources-Bx1sKPnF.mjs} +4 -5
  127. package/dist/{loadResourcesFromEntry-BkHHTu_B.mjs → loadResourcesFromEntry-b_jcqbxh.mjs} +3 -4
  128. package/dist/logger/index.d.mts +1 -3
  129. package/dist/logger/index.mjs +2 -2
  130. package/dist/{logger-C5bvCiAK.mjs → logger-CbFcIEBZ.mjs} +3 -5
  131. package/dist/{mcpPlugin-C9qohJCF.mjs → mcpPlugin-yix548XX.mjs} +41 -60
  132. package/dist/{memory-CxiTwT0j.mjs → memory-Bgw5dn8N.mjs} +4 -5
  133. package/dist/{metrics-Ckp2zRy-.mjs → metrics-CZDQWVjS.mjs} +4 -5
  134. package/dist/middleware/index.d.mts +1 -5
  135. package/dist/middleware/index.mjs +4 -5
  136. package/dist/migrations/index.d.mts +0 -2
  137. package/dist/migrations/index.mjs +3 -4
  138. package/dist/{module-CfnKuIuH.mjs → module-Dsc_nKL5.mjs} +2 -3
  139. package/dist/{multiTenant-CAtYlW6H.d.mts → multiTenant-XCxAUlru.d.mts} +1 -5
  140. package/dist/{multipartBody-BFasGtP9.mjs → multipartBody-B85ek8Kj.mjs} +2 -3
  141. package/dist/observeSend-BK-JN1jK.mjs +20 -0
  142. package/dist/{openapi-DAPxjYHX.mjs → openapi-Co7hl073.mjs} +18 -28
  143. package/dist/outbox-admin/index.d.mts +2 -4
  144. package/dist/outbox-admin/index.mjs +6 -7
  145. package/dist/{outbox-module-gZCHoE4H.d.mts → outbox-module-XvUThpqn.d.mts} +2 -8
  146. package/dist/{outbox-module-B4FAkx3A.mjs → outbox-module-mg9kDYkd.mjs} +13 -17
  147. package/dist/permissions/index.d.mts +4 -4
  148. package/dist/permissions/index.mjs +7 -7
  149. package/dist/{permissions-B14c3OMp.mjs → permissions-A1oKtpiC.mjs} +19 -29
  150. package/dist/{pipe-CQv7PsAK.mjs → pipe-Czpw9U2n.mjs} +3 -4
  151. package/dist/pipeline/index.d.mts +1 -9
  152. package/dist/pipeline/index.mjs +5 -8
  153. package/dist/{plan-CpnTykjb.mjs → plan-KVseuBCL.mjs} +5 -9
  154. package/dist/{plugin-DXTjVg_Q.mjs → plugin-DTWt_8C3.mjs} +130 -62
  155. package/dist/plugins/index.d.mts +8 -16
  156. package/dist/plugins/index.mjs +22 -26
  157. package/dist/plugins/response-cache.d.mts +2 -4
  158. package/dist/plugins/response-cache.mjs +10 -10
  159. package/dist/plugins/tracing-entry.d.mts +1 -1
  160. package/dist/plugins/tracing-entry.mjs +3 -4
  161. package/dist/{pluralize-C3VJKRGp.mjs → pluralize-msB9X3yw.mjs} +2 -3
  162. package/dist/presets/filesUpload.d.mts +4 -6
  163. package/dist/presets/filesUpload.mjs +6 -7
  164. package/dist/presets/index.d.mts +3 -19
  165. package/dist/presets/index.mjs +2 -2
  166. package/dist/presets/multiTenant.d.mts +1 -1
  167. package/dist/presets/multiTenant.mjs +7 -7
  168. package/dist/presets/search.d.mts +3 -5
  169. package/dist/presets/search.mjs +3 -4
  170. package/dist/{presets-CquqYJPy.mjs → presets-qKCehiJM.mjs} +11 -18
  171. package/dist/{projection-CgfSLOSM.mjs → projection-ClBqtsIw.mjs} +3 -4
  172. package/dist/{pushref-registry-UxCkoA4C.d.mts → pushref-registry-d86QUaSq.d.mts} +0 -6
  173. package/dist/{queryCachePlugin-D0HUISHJ.mjs → queryCachePlugin-3gJj5Rbz.mjs} +8 -10
  174. package/dist/{queryCachePlugin-C2lZjTxk.d.mts → queryCachePlugin-DYQUyeJ9.d.mts} +2 -4
  175. package/dist/{rateLimitKey-AvkBOMkl.mjs → rateLimitKey-Kro---xl.mjs} +2 -3
  176. package/dist/{realtime-CbWtVbqK.mjs → realtime-Ber8uJN2.mjs} +17 -19
  177. package/dist/{redis-BDgv9Glw.d.mts → redis-RpDMemdm.d.mts} +2 -4
  178. package/dist/{redis-stream-BMk-bpQS.d.mts → redis-stream-CS1N9dwM.d.mts} +1 -3
  179. package/dist/{redisShapes-CQksY67q.d.mts → redisShapes-CqBXTn_s.d.mts} +0 -2
  180. package/dist/registry/index.d.mts +2 -12
  181. package/dist/registry/index.mjs +3 -3
  182. package/dist/{registry-BVwpAuFI.mjs → registry-BA-_vFYk.mjs} +7 -12
  183. package/dist/{renewingLease-CykpeNcQ.mjs → renewingLease-CMY8YOcc.mjs} +2 -3
  184. package/dist/{replyHelpers-DA51IZio.mjs → replyHelpers-DK9P_XSz.mjs} +3 -4
  185. package/dist/{requestContext-DIWHKDtQ.mjs → requestContext-GYO_0gEw.mjs} +2 -3
  186. package/dist/{requirement-CbiLdQ1n.d.mts → requirement-CTRQjjQx.d.mts} +0 -2
  187. package/dist/{requirement-Cp_fsMDL.mjs → requirement-DeNjZIH3.mjs} +2 -3
  188. package/dist/{resourceRateLimit-Wf6d6FL9.d.mts → resourceRateLimit-DCWglD7V.d.mts} +1 -3
  189. package/dist/{resourceRateLimit-BFuluodF.mjs → resourceRateLimit-tHLbrtWc.mjs} +3 -4
  190. package/dist/{rolldown-runtime-D_lMdYOd.mjs → rolldown-runtime-Kv1fZdLg.mjs} +2 -3
  191. package/dist/{routeValidator-DuLonYwr.mjs → routeValidator-C_H5NanI.mjs} +2 -3
  192. package/dist/{runtimeCapabilities-CydRfm0i.mjs → runtimeCapabilities-DWqbxkyw.mjs} +2 -3
  193. package/dist/{schedules-B693KXxa.mjs → schedules-eO_RzhCU.mjs} +132 -9
  194. package/dist/{schemaConverter-DNvZWTV6.mjs → schemaConverter-DBJrPZN4.mjs} +3 -4
  195. package/dist/{schemaIR-REV2y7Wd.mjs → schemaIR-CEScKT2v.mjs} +3 -4
  196. package/dist/schemas/index.d.mts +0 -2
  197. package/dist/schemas/index.mjs +2 -3
  198. package/dist/scim/index.d.mts +0 -12
  199. package/dist/scim/index.mjs +10 -18
  200. package/dist/scope/index.d.mts +2 -6
  201. package/dist/scope/index.mjs +5 -5
  202. package/dist/{scope-Bevxy_ST.mjs → scope-B-Sm9m_E.mjs} +5 -6
  203. package/dist/{sessionManager-qimlKV0P.d.mts → sessionManager-CdvDF04x.d.mts} +2 -4
  204. package/dist/{shutdown-CfrqPR7A.mjs → shutdown-DzLFbe27.mjs} +2 -3
  205. package/dist/{simpleEqualityMatcher-BJwfuRKP.mjs → simpleEqualityMatcher-DOJhwQ8g.mjs} +2 -3
  206. package/dist/{sse-CuNNWr2z.mjs → sse-2972pVwV.mjs} +8 -9
  207. package/dist/{sseStream-C_2ujAVY.mjs → sseStream-AWLEeNV-.mjs} +3 -4
  208. package/dist/{storage-Cx9Sz3Ou.d.mts → storage-odC5MNKN.d.mts} +0 -2
  209. package/dist/{store-helpers-C8uBGCbb.mjs → store-helpers-VzjgVTkM.mjs} +2 -3
  210. package/dist/{streaming-Bdq_M4d5.mjs → streaming-DvraWW6x.mjs} +2 -3
  211. package/dist/{subscriberIdentity-B-KpZkdl.mjs → subscriberIdentity-Bya56jsg.mjs} +2 -3
  212. package/dist/{tenancy-C5PCvm1h.mjs → tenancy-DSa_0hhw.mjs} +3 -4
  213. package/dist/{tenantPreparation-dYvWrgNa.mjs → tenantPreparation-BrpkQre3.mjs} +5 -6
  214. package/dist/testing/cleanupStoreContract.d.mts +2 -4
  215. package/dist/testing/cleanupStoreContract.mjs +2 -3
  216. package/dist/testing/index.d.mts +6 -32
  217. package/dist/testing/index.mjs +24 -37
  218. package/dist/testing/outboxStoreContract.d.mts +1 -3
  219. package/dist/testing/outboxStoreContract.mjs +3 -4
  220. package/dist/testing/requiredPorts.d.mts +2 -4
  221. package/dist/testing/requiredPorts.mjs +3 -4
  222. package/dist/testing/storageContract.d.mts +2 -4
  223. package/dist/testing/storageContract.mjs +2 -3
  224. package/dist/{timing-DCqsezX8.mjs → timing-6rQTuCwg.mjs} +3 -5
  225. package/dist/{tracing-Dro5eH6j.d.mts → tracing-JSFiBl5r.d.mts} +0 -2
  226. package/dist/{transactionContext-DrcNyjpv.mjs → transactionContext-DaxYUEgH.mjs} +2 -3
  227. package/dist/{typeGuards-CEl10KPy.mjs → typeGuards-UKnX8wPX.mjs} +2 -3
  228. package/dist/types/index.d.mts +4 -4
  229. package/dist/types/index.mjs +1 -1
  230. package/dist/types/storage.d.mts +1 -1
  231. package/dist/types/storage.mjs +1 -1
  232. package/dist/{types-ByHn9rEO.d.mts → types-0Dqlbgn8.d.mts} +0 -2
  233. package/dist/{types-D3Ixsh00.d.mts → types-BYEb_dLW.d.mts} +2 -4
  234. package/dist/{types-BJ-2XqVF.d.mts → types-BeEJm-DV.d.mts} +114 -14
  235. package/dist/{types-DVLddu2q.d.mts → types-C0YJAiL0.d.mts} +0 -2
  236. package/dist/{types-D9NWjpYc.mjs → types-CuGjhn83.mjs} +5 -6
  237. package/dist/{types-Ddl9OjmE.d.mts → types-DnkIALZ8.d.mts} +0 -4
  238. package/dist/usage/index.d.mts +2 -10
  239. package/dist/usage/index.mjs +8 -12
  240. package/dist/{userHelpers-BHig1kHq.mjs → userHelpers-oX5_mOVs.mjs} +2 -3
  241. package/dist/utils/index.d.mts +5 -39
  242. package/dist/utils/index.mjs +12 -12
  243. package/dist/{utils-BG5P7_Vb.mjs → utils-CjjGOT4E.mjs} +20 -30
  244. package/dist/{validate-D_mdOCir.mjs → validate-4RlTKOJb.mjs} +5 -7
  245. package/dist/{versioning-DBGHjPh7.mjs → versioning-Dk2-19La.mjs} +4 -5
  246. package/dist/{versioning-Bqm_57Qt.d.mts → versioning-S18y2-0C.d.mts} +1 -15
  247. package/dist/{websocket-Cs4awVyD.d.mts → websocket-BGuc-WVZ.d.mts} +1 -15
  248. package/dist/{workScope-DPPfM4m6.mjs → workScope-DoBsoVo4.mjs} +3 -4
  249. package/llms.txt +37 -30
  250. package/package.json +9 -8
  251. package/skills/arc/SKILL.md +65 -844
  252. package/skills/arc/references/agent-auth.md +82 -193
  253. package/skills/arc/references/api-reference.md +41 -245
  254. package/skills/arc/references/auth-api-keys.md +99 -0
  255. package/skills/arc/references/auth-better-auth-overlay.md +87 -0
  256. package/skills/arc/references/auth-better-auth.md +78 -0
  257. package/skills/arc/references/auth-permissions.md +100 -0
  258. package/skills/arc/references/auth-strategies.md +122 -0
  259. package/skills/arc/references/boot.md +80 -0
  260. package/skills/arc/references/enterprise-auth.md +65 -81
  261. package/skills/arc/references/events-outbox.md +90 -0
  262. package/skills/arc/references/events.md +75 -440
  263. package/skills/arc/references/integrations-jobs.md +74 -0
  264. package/skills/arc/references/integrations-realtime.md +84 -0
  265. package/skills/arc/references/integrations-webhooks.md +71 -0
  266. package/skills/arc/references/integrations-workflows.md +47 -0
  267. package/skills/arc/references/mcp-auth.md +83 -0
  268. package/skills/arc/references/mcp-custom-tools.md +125 -0
  269. package/skills/arc/references/mcp-setup.md +115 -0
  270. package/skills/arc/references/mcp-testing.md +63 -0
  271. package/skills/arc/references/multi-tenancy.md +56 -230
  272. package/skills/arc/references/permissions-scope.md +81 -0
  273. package/skills/arc/references/production-api.md +119 -0
  274. package/skills/arc/references/production-audit.md +101 -0
  275. package/skills/arc/references/production-boot.md +91 -0
  276. package/skills/arc/references/production-caching.md +63 -0
  277. package/skills/arc/references/production-distributed.md +75 -0
  278. package/skills/arc/references/production-idempotency.md +83 -0
  279. package/skills/arc/references/production-observability.md +83 -0
  280. package/skills/arc/references/production-realtime.md +70 -0
  281. package/skills/arc/references/production-reliability.md +100 -0
  282. package/skills/arc/references/production-shutdown.md +43 -0
  283. package/skills/arc/references/querying.md +76 -0
  284. package/skills/arc/references/resources.md +97 -0
  285. package/skills/arc/references/schedules.md +79 -0
  286. package/skills/arc/references/scim.md +61 -208
  287. package/skills/arc/references/tenancy-scope-install.md +82 -0
  288. package/skills/arc/references/testing.md +101 -144
  289. package/skills/arc/references/usage-cleanup-capabilities.md +45 -0
  290. package/skills/arc/references/validation.md +91 -0
  291. package/skills/arc/references/writes-hooks-errors.md +80 -0
  292. package/skills/arc-code-review/SKILL.md +67 -114
  293. package/skills/arc-code-review/references/arc-cheatsheet.md +68 -167
  294. package/skills/arc-code-review/references/mongokit-repositories.md +104 -0
  295. package/skills/arc-code-review/references/recipe-events-cache-jobs.md +112 -0
  296. package/skills/arc-code-review/references/recipe-resource.md +100 -0
  297. package/skills/arc-code-review/references/recipe-schemas-fields.md +93 -0
  298. package/skills/arc-code-review/references/recipe-scope-permissions.md +82 -0
  299. package/skills/arc-code-review/references/scaffolding.md +61 -198
  300. package/skills/arc-code-review/references/severity.md +49 -102
  301. package/skills/arc-code-review/references/smells-auth-scope.md +80 -0
  302. package/skills/arc-code-review/references/smells-data-events.md +66 -0
  303. package/skills/arc-code-review/references/smells-imports-style.md +59 -0
  304. package/skills/arc-code-review/references/smells-platform.md +89 -0
  305. package/skills/arc-code-review/references/smells-routes-schemas.md +66 -0
  306. package/skills/arc-module-publishing/SKILL.md +82 -208
  307. package/skills/arc-module-publishing/references/action-presets-and-plugins.md +87 -0
  308. package/skills/arc-module-publishing/references/build-and-types.md +73 -0
  309. package/skills/arc-module-publishing/references/module-lifecycle.md +101 -0
  310. package/skills/arc-module-publishing/references/package-manifest.md +34 -122
  311. package/skills/arc-module-publishing/references/publishing-workflow.md +44 -140
  312. package/skills/arc-module-publishing/references/resource-assembly.md +102 -0
  313. package/skills/arc-module-publishing/references/testing-packages.md +82 -0
  314. package/skills/arc/references/auth.md +0 -729
  315. package/skills/arc/references/integrations.md +0 -452
  316. package/skills/arc/references/mcp.md +0 -691
  317. package/skills/arc/references/production.md +0 -835
  318. package/skills/arc-code-review/references/anti-patterns.md +0 -1008
  319. package/skills/arc-code-review/references/migration-recipes.md +0 -649
  320. package/skills/arc-code-review/references/mongokit-migration.md +0 -360
  321. package/skills/arc-module-publishing/references/authoring-modules.md +0 -327
@@ -1,265 +1,91 @@
1
- ---
2
- name: Multi-Tenancy Playbook
3
- description: Where `tenantField` takes effect, how it composes with `_policyFilters`, and how to install scope from custom auth (API keys, service accounts, gateway headers)
4
- ---
1
+ # Multi-tenancy: scope, tenantField, filters
5
2
 
6
- # Multi-Tenancy Playbook
3
+ One source of truth: `request.scope`. Installing scope from custom auth is in tenancy-scope-install.md.
7
4
 
8
- Arc's multi-tenancy has exactly **one source of truth**: `request.scope`. This document shows where it's read, how filters compose, and how to wire custom authentication strategies (API keys, service accounts) without fighting the framework.
9
-
10
- ## Mental model
11
-
12
- Every request goes through this ladder — if any step is missed, tenant isolation silently breaks:
5
+ ## Request ladder
13
6
 
14
7
  ```
15
- 1. Authenticator populates request.scope (member | service | elevated | ...)
16
- ↓
17
- 2. Permission check validates access (allowPublic | requireAuth | requireApiKey | ...)
18
- ↓ may ALSO set request.scope via PermissionResult.scope
19
- 3. fastifyAdapter snapshots scope into metadata._scope
20
- ↓
8
+ 1. Authenticator sets request.scope (member | service | elevated | ...)
9
+ 2. Permission check validates access (may also set scope via allow({ scope }))
10
+ 3. Adapter snapshots scope into metadata._scope
21
11
  4. QueryResolver / AccessControl read metadata._scope
22
- ↓
23
- 5. If tenantField is set AND getOrgId(scope) returns an orgId,
24
- the org filter is ALWAYS prepended to the query
12
+ 5. tenantField set AND getOrgId(scope) defined => org filter always applied
25
13
  ```
26
14
 
27
- ## The 5 scope kinds
15
+ Skip a step and isolation silently breaks.
28
16
 
29
- | Kind | Use case | Has `userId` | Has `organizationId` | Helper |
30
- |-----------------|-------------------------------------|:------------:|:--------------------:|--------------------------|
31
- | `public` | No authentication | ❌ | ❌ | `PUBLIC_SCOPE` |
32
- | `authenticated` | Logged-in user, no org context | ✅ | ❌ | `getUserId()` |
33
- | `member` | User in an org with specific roles | ✅ | ✅ | `isMember()` + `getOrgId()` |
34
- | `service` | Machine-to-machine (API keys, bots) | ❌ (`clientId` instead) | ✅ | `isService()` + `getClientId()` |
35
- | `elevated` | Platform admin, explicit elevation | ✅ | Optional | `isElevated()` |
17
+ ## Scope kinds
36
18
 
37
- **Why `service` is distinct from `member`:** a service account is not a human. It has no user record, no global roles, and should be auditable as a machine actor. Faking it as a `member` with `userId: client._id` pollutes audit logs, confuses rate-limit keys, and makes future per-service-scope authorization (OAuth scopes) harder.
19
+ | Kind | Use | `userId` | `organizationId` | Helper |
20
+ |---|---|:-:|:-:|---|
21
+ | `public` | No auth | no | no | `PUBLIC_SCOPE` |
22
+ | `authenticated` | Signed in, no org | yes | no | `getUserId()` |
23
+ | `member` | User in an org with roles | yes | yes | `isMember()`, `getOrgId()` |
24
+ | `service` | Machine caller (API key, bot) | no (`clientId`) | yes | `isService()`, `getClientId()` |
25
+ | `elevated` | Platform admin | yes | optional | `isElevated()` |
38
26
 
39
- ## Where `tenantField` is read
27
+ Never fake a service as a `member` with `userId: client._id`: it pollutes audit rows, rate-limit keys and OAuth-scope checks.
40
28
 
41
- Every resource defines `tenantField` (default: `'organizationId'`, or `false` to disable). **One function decides tenancy — `resolveTenancy()` in `src/core/tenancy.ts`** — and every layer switches on its result:
29
+ ## How `tenantField` is read
30
+
31
+ Every resource has `tenantField` (default `'organizationId'`, or `false`). `resolveTenancy()` (`src/core/tenancy.ts`) is the single decision; list, get/update/delete by id, post-fetch org check, the kit tenant options, bulk ops and the `sse`/`realtime` streams all switch on it:
42
32
 
43
33
  | Result | Meaning |
44
34
  |---|---|
45
- | `{ mode: 'scoped', field, orgId }` | filter by `field = orgId` (a member, a service key, or an elevated admin who SELECTED an org) |
46
- | `unscoped: 'platform'` | elevated admin with NO org — sees and writes across tenants |
47
- | `unscoped: 'cross-tenant'` | the route declared `multiTenantPreset({ crossTenant: [...] })` — reads only; the row policy still applies |
48
- | `unscoped: 'no-org'` | anonymous, or signed in with no org selected — reads get no tenant filter (the preset refuses earlier where one is required); **writes are refused** |
35
+ | `scoped` (`field`, `orgId`) | Filter `field = orgId` (member, service, or elevated admin who selected an org) |
36
+ | `unscoped: 'platform'` | Elevated admin, no org: sees and writes across tenants |
37
+ | `unscoped: 'cross-tenant'` | Route listed in `multiTenantPreset({ crossTenant })`: reads only, row policy still applies |
38
+ | `unscoped: 'no-org'` | Anonymous or no org selected: reads get no tenant filter (the preset refuses earlier where an org is required); writes are refused |
49
39
  | `unscoped: 'untenanted-resource'` | `tenantField: false` |
50
40
 
51
- Consumers: `QueryResolver` (list), `AccessControl.buildIdFilter` (get/update/delete by id) and `checkOrgScope` (post-fetch), `buildTenantRepoOptions` (what the kit is told, `bypassTenant`), the bulk mixin (`bulkCreate` stamping + `buildBulkFilter`), and — via `eventAudienceOf` / `isEventVisible` — the `sse` and `realtime` streams.
52
-
53
- **Never re-derive the org from the scope in a new layer.** Each layer used to, with its own condition, and they drifted: `crossTenant` was taught to three of four read layers (`get` silently ignored it for signed-in members), bulk writes skipped the org for ANY elevated admin (an admin acting as org-9 deleted across every tenant), and `realtime` withheld the platform view that reads grant. The union is exhaustive, so a new mode is a compile error in every consumer that has not handled it.
54
-
55
- The cache key (`deriveCacheScope`) deliberately does NOT use it: it answers "whose cache partition", which on a cross-tenant read is still the caller's org — dropping it could let one org's cached page answer another's.
41
+ Never re-derive the org from scope in a new layer; call `resolveTenancy`. The cache key (`deriveCacheScope`) deliberately does not use it: it names the caller's cache partition.
56
42
 
57
43
  ## Filter composition
58
44
 
59
- `_policyFilters` and `tenantField` are different and both apply:
45
+ Final filter = AND of the parsed query filters, `_policyFilters` (from permission checks: ownership, project scoping), and `{ [tenantField]: orgId }`.
60
46
 
61
- ```ts
62
- // The final filter passed to the database is:
63
- {
64
- ...parsedUserFilters, // from the incoming query string
65
- ..._policyFilters, // from permission checks (ownership, project scoping, etc.)
66
- [tenantField]: orgId, // from metadata._scope (if tenantField is set and scope has orgId)
67
- }
68
- ```
47
+ - A client filter can never widen or overwrite a policy filter (they are conjoined).
48
+ - The tenant filter is added unless the policy already constrains that field.
49
+ - Elevated scope without `organizationId`: no tenant filter (admin sees everything).
69
50
 
70
- **Priority rules:**
71
- - `_policyFilters` overrides user-supplied filters (the user can't bypass them)
72
- - `tenantField` only gets injected if `_policyFilters` does not already set it (so a more specific policy filter wins)
73
- - `elevated` scope with no `organizationId` means the filter is skipped entirely (admin sees everything)
51
+ ## Missing scope
74
52
 
75
- ## Four ways to install scope
53
+ If `tenantField` is set but `getOrgId(scope)` is undefined, list/get/update/delete are NOT narrowed: a `public` caller could read every tenant. Pair `tenantField` with a permission check that installs an org scope. `bulkUpdate` / `bulkDelete` return a null filter and are rejected.
76
54
 
77
- ### 1. Better Auth (recommended for human users)
55
+ Arc does NOT derive scope from `request.user.organizationId` inside permission checks. The JWT/`authenticator` path derives it for you (user with `organizationId` => `member`); otherwise return `scope` from the check.
78
56
 
79
- The `betterAuth` adapter reads the session cookie and installs `kind: 'member'` automatically. Nothing to wire.
57
+ ## Presets and fields
80
58
 
81
- ```ts
82
- await createApp({
83
- auth: getAuth(), // Better Auth instance
84
- // ... scope is set by the adapter, zero code
85
- });
59
+ ```typescript
60
+ presets: [{ name: 'multiTenant', tenantField: 'organizationId' }]
61
+ // or several dimensions, fail-closed if one is missing:
62
+ multiTenantPreset({ tenantFields: [
63
+ { field: 'organizationId', type: 'org' },
64
+ { field: 'branchId', contextKey: 'branchId' }, // from scope.context
65
+ ] })
86
66
  ```
87
67
 
88
- ### 2. Custom Fastify authenticator (JWT, headers, whatever)
89
-
90
- Arc's `authPlugin.ts` auto-derives scope from `request.user` after your authenticator returns. If your user has `organizationId`, you get a `member` scope for free:
91
-
92
- ```ts
93
- await createApp({
94
- auth: {
95
- type: 'authenticator',
96
- authenticate: async (request) => {
97
- const user = await verifyJwt(request.headers.authorization);
98
- return user; // Must have `organizationId` for member scope
99
- },
100
- },
101
- });
102
- ```
103
-
104
- ### 3. `PermissionResult.scope` (NEW — best for API keys, service accounts, custom headers)
105
-
106
- Return the scope directly from your permission check. This is the cleanest integration point for machine-to-machine auth — no separate auth plugin, no scope-derivation-from-user magic. It's explicit, typed, and auditable.
107
-
108
- ```ts
109
- // src/permissions/apiKey.ts
110
- import { allow, deny, type PermissionCheck } from '@classytic/arc/permissions';
111
- import { ClientModel } from '../models/Client.js';
112
-
113
- export function requireApiKey(): PermissionCheck {
114
- return async ({ request }) => {
115
- const apiKey = request.headers['x-api-key'] as string | undefined;
116
- if (!apiKey) return deny('Missing API key');
117
-
118
- const client = await ClientModel.findOne({ apiKey });
119
- if (!client) return deny('Invalid API key');
120
-
121
- return allow({
122
- scope: {
123
- kind: 'service',
124
- clientId: String(client._id),
125
- organizationId: String(client.companyId),
126
- scopes: client.allowedScopes, // optional OAuth-style scope strings
127
- },
128
- // Optional additional row-level narrowing
129
- ...(client.projectId ? { policy: { projectId: client.projectId } } : {}),
130
- });
131
- };
132
- }
133
- ```
134
-
135
- Then wire it into the resource:
136
-
137
- ```ts
138
- // import { createMongooseAdapter } from '@classytic/mongokit/adapter';
139
- // import { buildCrudSchemasFromModel } from '@classytic/mongokit';
140
-
141
- defineResource({
142
- name: 'job',
143
- adapter: createMongooseAdapter({ model: Job, repository: jobRepo, schemaGenerator: buildCrudSchemasFromModel }),
144
- controller: new BaseController(jobRepo, { tenantField: 'companyId' }),
145
- permissions: {
146
- list: requireApiKey(),
147
- get: requireApiKey(),
148
- create: requireApiKey(),
149
- update: requireApiKey(),
150
- delete: requireApiKey(),
151
- },
152
- });
153
- ```
154
-
155
- **That's the whole setup.** No auth plugin, no scope-resolution hook, no separate tenant-filter middleware. One file, one function, full tenant isolation — verified against cross-tenant `get`, `list`, `update`, and `delete` in [tests/e2e/permission-scope-wire.test.ts](../../../tests/e2e/permission-scope-wire.test.ts).
156
-
157
- **Override safety:** `PermissionResult.scope` only writes to `request.scope` when the current scope is still `public`. An already-authenticated request (from Better Auth, JWT, etc.) is never downgraded or overwritten.
158
-
159
- ### 4. Custom Fastify hook (advanced)
160
-
161
- For exotic cases (mTLS, downstream RPC calls), write an `onRequest` hook that sets `request.scope` directly. Arc reads from `request.scope` — it doesn't care how you got there.
162
-
163
- ## Decision table
164
-
165
- | Your auth source | Where to set scope |
166
- |-----------------------------------|------------------------------------------------------|
167
- | Better Auth session cookie | Nothing — `betterAuth` adapter handles it |
168
- | JWT with `organizationId` claim | Return it from `authenticate()` — auth plugin derives scope |
169
- | API key → DB lookup | **`PermissionResult.scope`** ← the clean path |
170
- | Gateway-injected headers | `PermissionResult.scope` or a custom `onRequest` hook |
171
- | Service account OAuth token | `PermissionResult.scope` with `kind: 'service'` |
172
- | Platform admin elevation | `elevationPlugin` — sets `kind: 'elevated'` |
173
-
174
- ## What happens when scope is missing
175
-
176
- If `tenantField` is set but `getOrgId(scope)` returns `undefined`:
177
-
178
- - **`list` / `get` / `update` / `delete`** — the filter is NOT narrowed. A caller with `public` scope would see ALL rows across ALL tenants. **This is why you must always pair `tenantField` with a permission check that installs a scope with `organizationId`.**
179
- - **`bulkUpdate` / `bulkDelete`** — `buildBulkFilter()` returns `null` and the bulk operation is rejected. This is a safety net, but don't rely on it for `list`.
180
-
181
- Arc does NOT auto-derive scope from `request.user.organizationId` — that's a footgun (silent tenant leak if you set the user but forget the scope). If you want this behavior, either use the JWT/custom authenticator path (which does derive automatically) or return `scope` explicitly from your permission check.
68
+ `multiTenantPreset` options: `tenantField` XOR `tenantFields`, `allowPublic: [routes]`, `crossTenant: ['list' | 'get']`. `crossTenant` removes the tenant filter, authorizes nothing: the check must return a row `policy` (e.g. `{ status: 'active' }`) or every tenant's rows are published.
182
69
 
183
70
  ## Gotchas
184
71
 
185
- 1. **`tenantField` is per-resource, not per-app.** Different resources can use different tenant field names (`companyId`, `workspaceId`, `tenantId`). The org ID always comes from `getOrgId(scope)`. **Auto-inference (2.12):** when the Mongoose model has no `organizationId` path AND no other tenant field is configured, arc auto-infers `tenantField: false` rather than emitting queries against a non-existent column.
186
- 2. **`elevated` with no `organizationId` bypasses tenant filtering.** This is intentional (admin sees everything), but it means you can't use `kind: 'elevated'` for normal per-org access.
187
- 3. **`systemManaged` is your seatbelt for create/update.** Mark tenant fields (`companyId`, `organizationId`) as `systemManaged` in `fieldRules` so `BodySanitizer` strips any client-supplied value. The tenant field is then injected from the scope at write time — not from the request body.
188
- 4. **Rate-limit keys respect all 5 scope kinds.** The built-in `createTenantKeyGenerator` uses `organizationId` for member/service/elevated and falls back to `userId`/IP for authenticated/public.
189
- 5. **multiTenant preset injects org on UPDATE (v2.9).** Body-supplied `organizationId` is overwritten with the caller's scope — closes the tenant-hop vector where a member could PATCH their own doc into another tenant. Elevated scope with no org still bypasses (admin cross-tenant).
190
-
191
- ## Mongokit tenant-context helper (optional)
192
-
193
- If your adapter is mongokit ≥3.7, you can wire mongokit's `createTenantContext()` to propagate the org id through `AsyncLocalStorage` — useful when domain code outside arc routes needs the current tenant without threading `req` everywhere:
194
-
195
- ```ts
196
- import { createTenantContext, multiTenantPlugin, Repository } from '@classytic/mongokit';
197
- import { getOrgId } from '@classytic/arc/scope';
198
-
199
- const tenantContext = createTenantContext();
200
- const repo = new Repository(Model, [
201
- multiTenantPlugin({ tenantField: 'organizationId', context: tenantContext }),
202
- ]);
203
-
204
- // Install scope → ALS bridge once in your app:
205
- fastify.addHook('preHandler', (req, _reply, done) => {
206
- const scope = (req.metadata as { _scope?: unknown } | undefined)?._scope;
207
- const orgId = scope ? getOrgId(scope as never) : undefined;
208
- if (orgId) tenantContext.run(orgId, done);
209
- else done();
210
- });
211
-
212
- // Now any domain code can read it:
213
- import { getTenantId } from './tenantContext.js';
214
- await someService.doThing({ orgId: getTenantId() });
215
- ```
216
-
217
- Arc doesn't bundle this — it's mongokit-specific. Arc's scope helpers (`getOrgId`, `getOrgContext`) remain the source of truth inside the request cycle; `createTenantContext()` is a complement for code that lives outside it.
72
+ 1. `tenantField` is per resource (`companyId`, `workspaceId`, ...); the value always comes from `getOrgId(scope)`.
73
+ 2. `kind: 'elevated'` without an org bypasses tenant filtering: unusable for normal per-org access.
74
+ 3. Mark the tenant field `systemManaged` in `fieldRules`: `BodySanitizer` strips client values and the scope value is injected on write.
75
+ 4. The preset overwrites a body-supplied org on UPDATE (blocks tenant hopping). Elevated without an org still bypasses.
76
+ 5. `createTenantKeyGenerator()` (`@classytic/arc/scope`) keys rate limits by org for member/service/elevated, else user or IP.
218
77
 
219
- ## Plugin-order safety (mongokit ≥3.7)
78
+ ## Helpers (`@classytic/arc/scope`)
220
79
 
221
- Mongokit's `Repository` constructor accepts `pluginOrderChecks: 'warn' | 'throw' | 'off'` (default `'warn'`). Pass `'throw'` in production to catch foot-guns — e.g. installing `softDeletePlugin` AFTER `batchOperationsPlugin` silently bypasses soft-delete on `deleteMany`:
222
-
223
- ```ts
224
- new Repository(Model, [
225
- multiTenantPlugin({...}), // must precede cache + batch-ops
226
- softDeletePlugin(), // must precede batch-ops
227
- batchOperationsPlugin(),
228
- ], {}, { pluginOrderChecks: 'throw' });
229
- ```
230
-
231
- Arc doesn't surface this option — configure it directly on the mongokit `Repository` you hand to `defineResource({ adapter: createMongooseAdapter({ repository }) })`.
232
-
233
- ## Helpers reference
234
-
235
- All exported from `@classytic/arc/scope`:
236
-
237
- ```ts
80
+ ```typescript
238
81
  import {
239
- // Type guards
240
- isMember, isService, isElevated, isAuthenticated, hasOrgAccess,
241
-
242
- // Accessors (return undefined when not applicable — no throws)
243
- getUserId, // authenticated | member | elevated
244
- getClientId, // service only
245
- getOrgId, // member | service | elevated
246
- getUserRoles, // authenticated | member
247
- getOrgRoles, // member only
248
- getServiceScopes, // service only (OAuth-style scope strings)
249
- getTeamId, // member with teamId set
250
-
251
- // Throwing accessors — return the value or throw a 403 ArcError
252
- requireUserId,
253
- requireOrgId,
254
- requireClientId,
255
- requireTeamId,
256
-
257
- // Canonical request extractor
258
- getOrgContext,
259
-
260
- // Constants
261
- PUBLIC_SCOPE, AUTHENTICATED_SCOPE,
262
-
263
- type RequestScope,
82
+ isMember, isService, isElevated, isAuthenticated, hasOrgAccess, // guards
83
+ getUserId, getClientId, getOrgId, getUserRoles, getOrgRoles, // return undefined, never throw
84
+ getServiceScopes, getTeamId, getScopeContext, getOrgContext,
85
+ requireUserId, requireOrgId, requireClientId, requireTeamId, // throw 403 / 401
86
+ isOrgInScope, getAncestorOrgIds, // explicit hierarchy checks
87
+ PUBLIC_SCOPE, AUTHENTICATED_SCOPE, type RequestScope,
264
88
  } from '@classytic/arc/scope';
265
89
  ```
90
+
91
+ Hierarchy: `scope.ancestorOrgIds` (closest first, loaded by your auth) plus `requireOrgInScope(...)` from `@classytic/arc/permissions`; there is no automatic inheritance.
@@ -0,0 +1,81 @@
1
+ # Permissions and RequestScope
2
+
3
+ ## PermissionCheck
4
+
5
+ A check returns `boolean | AuthorizationDecision`. Build decisions with `allow({ policy?, scope? })` and `deny(reason?)`: `policy` is ANDed into the repository query (row-level), `scope` stamps attributes downstream.
6
+
7
+ ```typescript
8
+ import {
9
+ allOf, allow, allowPublic, anyOf, deny, denyAll, requireAuth, requireOrgRole, requireOwnership,
10
+ requireRoles, requireServiceScope, when, type PermissionCheck,
11
+ } from '@classytic/arc/permissions';
12
+
13
+ permissions: {
14
+ list: allowPublic({ policy: { status: 'published' } }), // public but row-filtered
15
+ create: requireRoles(['admin', 'editor']),
16
+ update: anyOf(requireOwnership('userId'), requireRoles(['admin'])),
17
+ delete: allOf(requireAuth(), requireRoles(['admin'])),
18
+ bulkImport: anyOf(requireOrgRole('admin'), requireServiceScope('jobs:bulk-write')),
19
+ }
20
+
21
+ const requirePro = (): PermissionCheck => async (ctx) =>
22
+ !ctx.user ? deny('Auth required') : ctx.user.plan === 'pro' ? allow() : deny('Pro plan required');
23
+ ```
24
+
25
+ - Public + row filter: use `allowPublic({ policy })`. A hand-written `allow({ policy })` lacks the public flag and anonymous callers get 401.
26
+ - `policy` may be a function `(ctx) => filter`; `{}` means unrestricted.
27
+ - `requireRoles()` checks platform roles (`user.role`, singular: string, comma list or array) AND org roles (`scope.orgRoles`).
28
+ - Dynamic DB-backed ACL: `createDynamicPermissionMatrix({ resolveRolePermissions, cacheStore })`, then `acl.canAction('product', 'read')`.
29
+ - Quotas: `requireQuota({ kind, limit })` (needs `usagePlugin`). Agent mandates: `requireAgentScope`, `requireMandate`, `requireDPoP`.
30
+ - `isRevoked` errors deny (fail-closed).
31
+
32
+ ## Field-level
33
+
34
+ ```typescript
35
+ import { fields } from '@classytic/arc/permissions';
36
+ fields: {
37
+ password: fields.hidden(),
38
+ salary: fields.visibleTo(['admin', 'hr']),
39
+ role: fields.writableBy(['admin']),
40
+ email: fields.redactFor(['viewer'], '***'),
41
+ }
42
+ ```
43
+
44
+ ## RequestScope
45
+
46
+ Discriminated on `kind`: `public`, `authenticated`, `member`, `service`, `elevated`. Always read through accessors from `@classytic/arc/scope`, never properties.
47
+
48
+ ```typescript
49
+ import { getOrgId, getUserId, hasOrgAccess, isElevated, isMember, isService,
50
+ requireClientId, requireOrgId, requireTeamId, requireUserId } from '@classytic/arc/scope';
51
+
52
+ const orgId = requireOrgId(req.scope); // 403 ArcError when absent
53
+ const userId = getUserId(req.scope); // string | undefined
54
+ ```
55
+
56
+ | Throwing accessor | Status when missing |
57
+ |---|---|
58
+ | `requireUserId`, `requireClientId` | 401 |
59
+ | `requireOrgId`, `requireTeamId` | 403 |
60
+
61
+ | Helper | member | service | elevated |
62
+ |---|---|---|---|
63
+ | `requireOrgMembership()` | yes | yes | yes |
64
+ | `requireOrgRole(roles)` | role match | no | bypass |
65
+ | `requireServiceScope(scopes)` | no | scope match | bypass |
66
+ | `requireTeamMembership()` | `teamId` set | n/a | bypass |
67
+ | `requireOrgInScope(target)` | in chain | in chain | bypass |
68
+
69
+ Populate `scope.context` and `scope.ancestorOrgIds` in your auth function for branch or parent-child scoping; `multiTenantPreset({ tenantFields })` then filters every dimension. See `references/tenancy-*.md` / multi-tenancy references for the ladder.
70
+
71
+ ## Auth wiring
72
+
73
+ ```typescript
74
+ auth: { type: 'jwt', jwt: { secret, expiresIn: '15m' } }
75
+ auth: { type: 'betterAuth', betterAuth: createBetterAuthAdapter({ auth }) }
76
+ auth: { type: 'custom', plugin: myAuthPlugin }
77
+ auth: { type: 'authenticator', authenticate: async (req, reply) => {} }
78
+ auth: false
79
+ ```
80
+
81
+ Decorates `app.authenticate`, `app.optionalAuthenticate`, `app.authorize`. Better Auth stores `member.role = "admin,recruiter"`; arc splits it into `scope.orgRoles`, so filter with `role[like]=admin`.
@@ -0,0 +1,119 @@
1
+ # Production: errors, responses, versioning, rate limits, bulk, OpenAPI
2
+
3
+ ## Errors
4
+
5
+ `errorHandlerPlugin` is on by default in `createApp`. It maps AJV, driver duplicate-key (409 `arc.conflict`), repo-core errors and `ArcError` to the `ErrorContract` `{ code, message, status }`; unknown routes answer 404 `arc.not_found`.
6
+
7
+ ```typescript
8
+ import { defineErrorMapper, createDomainError } from '@classytic/arc/utils';
9
+
10
+ class AccountingError extends Error {
11
+ constructor(message: string, public status: number, public code: string) { super(message); }
12
+ }
13
+
14
+ const app = await createApp({
15
+ errorHandler: {
16
+ errorMappers: [defineErrorMapper({
17
+ type: AccountingError,
18
+ toResponse: (err) => ({ status: err.status, code: err.code, message: err.message }),
19
+ })],
20
+ errorMap: { PaymentError: { statusCode: 402, code: 'app.payment_failed' } }, // by error.name, lower priority
21
+ onError: (err, request) => Sentry.captureException(err),
22
+ },
23
+ });
24
+
25
+ throw createDomainError('INSUFFICIENT_BALANCE', 'Not enough credits', 402, { balance: 0 });
26
+ ```
27
+
28
+ Mappers run via `instanceof` before any other classification; first match wins. Internal messages are hidden in production (`exposeInternalMessages`).
29
+
30
+ ## Reply helpers and serialization
31
+
32
+ Arc returns raw data on success (no envelope); the HTTP status discriminates. `createApp({ replyHelpers: true })` adds two decorators:
33
+
34
+ ```typescript
35
+ return reply.sendList(result); // kit-shaped paginated result or bare array to the canonical list shape
36
+ return reply.stream(csvReadable, { contentType: 'text/csv', filename: 'export.csv' });
37
+ ```
38
+
39
+ `serializeBigInt: 'string'` turns BigInt into lossless decimal strings (`'number'` is lossy above 2^53-1); the default throws on BigInt.
40
+
41
+ ## Multipart bodies on CRUD routes
42
+
43
+ ```typescript
44
+ import { multipartBody } from '@classytic/arc/middleware';
45
+
46
+ defineResource({
47
+ middlewares: { create: [multipartBody({ allowedMimeTypes: ['image/png'], maxFileSize: 5_000_000, maxFiles: 3, filesKey: '_files' })] },
48
+ hooks: { 'before:create': async (data) => { /* data._files.image */ return data; } },
49
+ });
50
+ ```
51
+
52
+ Parses fields into `req.body` and files into `req.body[filesKey]`; no-op for JSON requests.
53
+
54
+ ## Versioning
55
+
56
+ ```typescript
57
+ createApp({ arcPlugins: { versioning: { type: 'header', defaultVersion: '1', versions: ['1', '2'], sunset: '2026-12-01' } } });
58
+ // type 'prefix': /v2/products
59
+ ```
60
+
61
+ Reads `accept-version` (`headerName`), sets `x-api-version` (`responseHeader`) and `request.apiVersion`. `VersioningOptions` also takes a list of retiring versions (see the type); those get `Deprecation: true` and a `Sunset` header from `sunset` (ISO date). With `versions` set, other versions return 400 `arc.unsupported_api_version` (`defaultVersion` must be listed); without it the plugin only annotates.
62
+
63
+ ## Rate limiting
64
+
65
+ ```typescript
66
+ import { createTenantKeyGenerator } from '@classytic/arc/scope';
67
+
68
+ createApp({
69
+ rateLimit: {
70
+ max: 100, timeWindow: '1 minute',
71
+ redis, // shared store, required with runtime 'distributed'
72
+ keyGenerator: createTenantKeyGenerator(), // or { strategy: (ctx) => ctx.ip }
73
+ skipPaths: ['/api/auth/*'],
74
+ },
75
+ });
76
+ ```
77
+
78
+ | Scope kind | Key |
79
+ |---|---|
80
+ | `member`, `service` | `organizationId` |
81
+ | `authenticated` | `userId` |
82
+ | `elevated` | `organizationId ?? userId` |
83
+ | `public` | IP |
84
+
85
+ Pre-auth paths see the public scope and key by IP: exempt them with `skipPaths`. Per-resource budgets: `defineResource({ rateLimit })`.
86
+
87
+ ## Bulk preset
88
+
89
+ ```typescript
90
+ import { bulkPreset } from '@classytic/arc/presets';
91
+
92
+ defineResource({ name: 'product', adapter, presets: ['bulk'] }); // all three
93
+ defineResource({ name: 'product', adapter, presets: [bulkPreset({ operations: ['createMany', 'updateMany'], maxCreateItems: 500 })] });
94
+ ```
95
+
96
+ | Route | Body | Repository method |
97
+ |---|---|---|
98
+ | `POST /bulk` | `{ items }` (max `maxCreateItems`, default 1000) | `createMany` |
99
+ | `PATCH /bulk` | `{ filter, data }` | `updateMany` |
100
+ | `DELETE /bulk` | `{ filter }` | `deleteMany` |
101
+
102
+ The repository must provide those methods; permissions inherit from `create`, `update`, `delete`.
103
+
104
+ ## OpenAPI
105
+
106
+ `buildOpenApiSpec` and `openApiPlugin` (default prefix `/_docs`) come from `@classytic/arc/docs`. Non-resource routes (auth adapters) inject paths with `ExternalOpenApiPaths`:
107
+
108
+ ```typescript
109
+ import type { ExternalOpenApiPaths } from '@classytic/arc/docs';
110
+
111
+ const ext: ExternalOpenApiPaths = {
112
+ paths: { '/api/auth/sign-in': { post: { summary: 'Sign in' } } },
113
+ schemas: {}, tags: [{ name: 'Authentication' }],
114
+ securitySchemes: { cookieAuth: { type: 'apiKey', in: 'cookie', name: 'session_token' } },
115
+ resourceSecurity: [{ apiKeyAuth: [], orgHeader: [] }], // "bearer OR (api-key AND org-header)"
116
+ };
117
+ ```
118
+
119
+ `resourceSecurity` items are OR'd with `bearerAuth`; keys inside one item are AND'd. Core schemes: `bearerAuth`, `orgHeader`. The Better Auth adapter (`extractBetterAuthOpenApi`, `@classytic/arc/auth`) supplies `cookieAuth`, and `apiKeyAuth` plus `resourceSecurity` when Better Auth's API-key plugin is present.
@@ -0,0 +1,101 @@
1
+ # Production: audit trail
2
+
3
+ Disabled unless `enabled: true`. With no `repository` or `customStores` it falls back to `MemoryAuditStore` (dev only; the capability audit rejects it under `runtime: 'distributed'`).
4
+
5
+ ```typescript
6
+ import { auditPlugin } from '@classytic/arc/audit';
7
+ import { Repository } from '@classytic/mongokit';
8
+
9
+ await fastify.register(auditPlugin, {
10
+ enabled: true,
11
+ repository: new Repository(AuditModel), // any RepositoryLike: create + findAll
12
+ customStores: [kafkaAuditStore], // compose with, or instead of, a repository
13
+ retention: { maxAgeMs: 365 * 86_400_000, purgeIntervalMs: 86_400_000 },
14
+ autoAudit: { perResource: true },
15
+ });
16
+ ```
17
+
18
+ ## Automatic auditing
19
+
20
+ `autoAudit` (default `true`) logs create, update, delete for every resource through hooks.
21
+
22
+ | Value | Effect |
23
+ |---|---|
24
+ | `true` | All resources, all three operations |
25
+ | `{ perResource: true }` | Only resources declaring `audit: true` (or `audit: { operations: ['delete'] }`) |
26
+ | `{ include: ['order'] }` / `{ exclude: ['health'] }` | Allowlist / denylist (include wins if both) |
27
+ | `{ operations: ['create', 'delete'] }` | Restrict operations |
28
+ | `false` | Manual calls only |
29
+
30
+ ```typescript
31
+ defineResource({ name: 'order', audit: true });
32
+ ```
33
+
34
+ ## Manual entries
35
+
36
+ Prefer a request-bound logger: actor and organization come from the validated scope and cannot be forged.
37
+
38
+ ```typescript
39
+ const audit = fastify.audit.forRequest(request);
40
+ await audit.custom('product', id, 'price_changed', { oldPrice: 100, newPrice: 150 });
41
+ await audit.update('product', id, before, after);
42
+
43
+ // Or with an explicit context
44
+ await fastify.audit.create('product', id, doc, request.auditContext);
45
+ await fastify.audit.delete('product', id, doc, ctx);
46
+ await fastify.audit.restore('product', id, doc, ctx);
47
+ ```
48
+
49
+ `request.auditMetadata = { reason }` adds fields to the row arc writes for that request.
50
+
51
+ ## Query and purge
52
+
53
+ ```typescript
54
+ const entries = await fastify.audit.query({
55
+ resource: 'product', documentId: 'p1', userId, organizationId,
56
+ action: ['update', 'delete'], from: new Date('2026-01-01'), to, limit: 100, offset: 0,
57
+ });
58
+ const deleted = await fastify.audit.purge(new Date(Date.now() - 90 * 86_400_000));
59
+ ```
60
+
61
+ `query` is deliberately narrow and uses the first store that supports it. For filter, sort and keyset search (admin UI, MCP), mount the audit repository as a read-only resource:
62
+
63
+ ```typescript
64
+ defineResource({
65
+ name: 'audit-log',
66
+ adapter: auditAdapter, // adapter over the audit repository
67
+ disabledRoutes: ['create', 'update', 'delete'],
68
+ queryParser: new QueryParser({ allowedFilterFields: ['resource', 'documentId', 'userId', 'action', 'organizationId'] }),
69
+ permissions: { list: requireRoles(['auditor']), get: requireRoles(['auditor']) },
70
+ });
71
+ ```
72
+
73
+ ## Entry shape
74
+
75
+ ```typescript
76
+ interface AuditEntry {
77
+ id: string; timestamp: Date;
78
+ action: 'create' | 'update' | 'delete' | 'restore' | 'custom';
79
+ resource: string; documentId: string;
80
+ userId?: string; organizationId?: string;
81
+ before?: Record<string, unknown>; after?: Record<string, unknown>;
82
+ changes?: string[]; // changed field names
83
+ requestId?: string; ipAddress?: string; userAgent?: string;
84
+ metadata?: Record<string, unknown>; // custom actions: { customAction, ...data }
85
+ }
86
+ ```
87
+
88
+ Custom store: implement `AuditStore` (`name`, `log`, optional `query`, `purgeOlderThan`, `close`).
89
+
90
+ ## Retention
91
+
92
+ | Option | Use |
93
+ |---|---|
94
+ | MongoDB TTL index on `timestamp` (`expireAfterSeconds`) | Zero code, server side |
95
+ | `retention: { maxAgeMs, purgeIntervalMs }` | Built-in timer; runs on every replica, so wasteful in a fleet |
96
+ | `purgeIntervalMs: 0` plus a `schedulesPlugin` entry calling `fastify.audit.purge(cutoff)` | Multi-replica, leader-safe |
97
+
98
+ ## Gotchas
99
+
100
+ - Index the audit model yourself: `{ resource: 1, documentId: 1, timestamp: -1 }`; SQL kits index `(resource, document_id, timestamp)`.
101
+ - The repository store writes with the active transaction session (`sessionProvider`, default `transactionContext.get()`), so the audit row commits or rolls back with the domain write. `sessionProvider: false` opts out.