@wildo-ai/saas-backend-lib 1.1.0 → 1.1.2

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 (265) hide show
  1. package/dist/esm/base-classes/services/controllers/controller-resource.backend.service.d.ts +14 -3
  2. package/dist/esm/base-classes/services/controllers/controller-resource.backend.service.d.ts.map +1 -1
  3. package/dist/esm/base-classes/services/controllers/controller-resource.backend.service.js +115 -22
  4. package/dist/esm/base-classes/services/controllers/controller-resource.backend.service.js.map +1 -1
  5. package/dist/esm/base-classes/services/controllers/controllers-registry-handler.backend.service.d.ts +3 -1
  6. package/dist/esm/base-classes/services/controllers/controllers-registry-handler.backend.service.d.ts.map +1 -1
  7. package/dist/esm/base-classes/services/controllers/controllers-registry-handler.backend.service.js +8 -3
  8. package/dist/esm/base-classes/services/controllers/controllers-registry-handler.backend.service.js.map +1 -1
  9. package/dist/esm/base-classes/services/repositories/field-clearing-partition.backend.d.ts +11 -0
  10. package/dist/esm/base-classes/services/repositories/field-clearing-partition.backend.d.ts.map +1 -1
  11. package/dist/esm/base-classes/services/repositories/field-clearing-partition.backend.js +11 -2
  12. package/dist/esm/base-classes/services/repositories/field-clearing-partition.backend.js.map +1 -1
  13. package/dist/esm/base-classes/services/repositories/http-api/http-api-resource-repository.backend.service.d.ts +1 -0
  14. package/dist/esm/base-classes/services/repositories/http-api/http-api-resource-repository.backend.service.d.ts.map +1 -1
  15. package/dist/esm/base-classes/services/repositories/http-api/http-api-resource-repository.backend.service.js +6 -1
  16. package/dist/esm/base-classes/services/repositories/http-api/http-api-resource-repository.backend.service.js.map +1 -1
  17. package/dist/esm/base-classes/services/repositories/http-api/odata-query-compiler.backend.d.ts.map +1 -1
  18. package/dist/esm/base-classes/services/repositories/http-api/odata-query-compiler.backend.js +16 -0
  19. package/dist/esm/base-classes/services/repositories/http-api/odata-query-compiler.backend.js.map +1 -1
  20. package/dist/esm/base-classes/services/repositories/infrastructure-tier-contract.backend.d.ts +20 -6
  21. package/dist/esm/base-classes/services/repositories/infrastructure-tier-contract.backend.d.ts.map +1 -1
  22. package/dist/esm/base-classes/services/repositories/infrastructure-tier-contract.backend.js +88 -32
  23. package/dist/esm/base-classes/services/repositories/infrastructure-tier-contract.backend.js.map +1 -1
  24. package/dist/esm/base-classes/services/repositories/introspection/introspection-resource-repository.backend.service.d.ts +3 -1
  25. package/dist/esm/base-classes/services/repositories/introspection/introspection-resource-repository.backend.service.d.ts.map +1 -1
  26. package/dist/esm/base-classes/services/repositories/introspection/introspection-resource-repository.backend.service.js +32 -7
  27. package/dist/esm/base-classes/services/repositories/introspection/introspection-resource-repository.backend.service.js.map +1 -1
  28. package/dist/esm/base-classes/services/repositories/introspection/introspection-resource-source.backend.port.d.ts +8 -5
  29. package/dist/esm/base-classes/services/repositories/introspection/introspection-resource-source.backend.port.d.ts.map +1 -1
  30. package/dist/esm/base-classes/services/repositories/introspection/introspection-resource-source.backend.port.js.map +1 -1
  31. package/dist/esm/base-classes/services/repositories/postgresql-resource-repository.backend.service.d.ts +31 -0
  32. package/dist/esm/base-classes/services/repositories/postgresql-resource-repository.backend.service.d.ts.map +1 -1
  33. package/dist/esm/base-classes/services/repositories/postgresql-resource-repository.backend.service.js +127 -5
  34. package/dist/esm/base-classes/services/repositories/postgresql-resource-repository.backend.service.js.map +1 -1
  35. package/dist/esm/base-classes/services/repositories/repositories-registry-handler.backend.service.d.ts +71 -1
  36. package/dist/esm/base-classes/services/repositories/repositories-registry-handler.backend.service.d.ts.map +1 -1
  37. package/dist/esm/base-classes/services/repositories/repositories-registry-handler.backend.service.js +62 -2
  38. package/dist/esm/base-classes/services/repositories/repositories-registry-handler.backend.service.js.map +1 -1
  39. package/dist/esm/base-classes/services/repositories/repository-resource.backend.service.d.ts +21 -0
  40. package/dist/esm/base-classes/services/repositories/repository-resource.backend.service.d.ts.map +1 -1
  41. package/dist/esm/base-classes/services/repositories/repository-resource.backend.service.js +126 -4
  42. package/dist/esm/base-classes/services/repositories/repository-resource.backend.service.js.map +1 -1
  43. package/dist/esm/base-classes/services/services/resource-operation-implementation-coverage.backend.utils.d.ts +3 -26
  44. package/dist/esm/base-classes/services/services/resource-operation-implementation-coverage.backend.utils.d.ts.map +1 -1
  45. package/dist/esm/base-classes/services/services/resource-operation-implementation-coverage.backend.utils.js +3 -68
  46. package/dist/esm/base-classes/services/services/resource-operation-implementation-coverage.backend.utils.js.map +1 -1
  47. package/dist/esm/base-classes/services/services/services-registry-handler.backend.service.d.ts.map +1 -1
  48. package/dist/esm/base-classes/services/services/services-registry-handler.backend.service.js +4 -2
  49. package/dist/esm/base-classes/services/services/services-registry-handler.backend.service.js.map +1 -1
  50. package/dist/esm/billing/services/custom-impl/billing-account.mutations.custom-impl.backend.service.js +6 -6
  51. package/dist/esm/billing/services/custom-impl/billing-account.mutations.custom-impl.backend.service.js.map +1 -1
  52. package/dist/esm/compliance/audit-trails/services/audit-event-dispatcher.backend.service.d.ts +38 -0
  53. package/dist/esm/compliance/audit-trails/services/audit-event-dispatcher.backend.service.d.ts.map +1 -1
  54. package/dist/esm/compliance/audit-trails/services/audit-event-dispatcher.backend.service.js +40 -0
  55. package/dist/esm/compliance/audit-trails/services/audit-event-dispatcher.backend.service.js.map +1 -1
  56. package/dist/esm/compliance/audit-trails/services/audit-logs.backend.service.d.ts +20 -0
  57. package/dist/esm/compliance/audit-trails/services/audit-logs.backend.service.d.ts.map +1 -1
  58. package/dist/esm/compliance/audit-trails/services/audit-logs.backend.service.js +28 -0
  59. package/dist/esm/compliance/audit-trails/services/audit-logs.backend.service.js.map +1 -1
  60. package/dist/esm/compliance/audit-trails/services/siem-export-config-cache-invalidation.custom-impl.backend.service.d.ts +12 -0
  61. package/dist/esm/compliance/audit-trails/services/siem-export-config-cache-invalidation.custom-impl.backend.service.d.ts.map +1 -0
  62. package/dist/esm/compliance/audit-trails/services/siem-export-config-cache-invalidation.custom-impl.backend.service.js +118 -0
  63. package/dist/esm/compliance/audit-trails/services/siem-export-config-cache-invalidation.custom-impl.backend.service.js.map +1 -0
  64. package/dist/esm/compliance/audit-trails/services/siem-webhook-delivery.backend.service.d.ts.map +1 -1
  65. package/dist/esm/compliance/audit-trails/services/siem-webhook-delivery.backend.service.js +8 -5
  66. package/dist/esm/compliance/audit-trails/services/siem-webhook-delivery.backend.service.js.map +1 -1
  67. package/dist/esm/compliance/audit-trails/services/utils/ocsf-activity-mapping.backend.utils.d.ts.map +1 -1
  68. package/dist/esm/compliance/audit-trails/services/utils/ocsf-activity-mapping.backend.utils.js +14 -0
  69. package/dist/esm/compliance/audit-trails/services/utils/ocsf-activity-mapping.backend.utils.js.map +1 -1
  70. package/dist/esm/config/custom/application-config-controller.backend.service.d.ts.map +1 -1
  71. package/dist/esm/config/custom/application-config-controller.backend.service.js +7 -1
  72. package/dist/esm/config/custom/application-config-controller.backend.service.js.map +1 -1
  73. package/dist/esm/config/models/app-config.backend.schemas.d.ts +4 -0
  74. package/dist/esm/config/models/app-config.backend.schemas.d.ts.map +1 -1
  75. package/dist/esm/config/services/app-configuration.backend.utils.d.ts +10 -1
  76. package/dist/esm/config/services/app-configuration.backend.utils.d.ts.map +1 -1
  77. package/dist/esm/config/services/app-configuration.backend.utils.js +13 -2
  78. package/dist/esm/config/services/app-configuration.backend.utils.js.map +1 -1
  79. package/dist/esm/data-seeding/services/shared/data-seed-scope-iteration.shared.utils.d.ts +2 -2
  80. package/dist/esm/data-seeding/services/shared/data-seed-scope-iteration.shared.utils.js +2 -2
  81. package/dist/esm/data-seeding/services/shared/data-seed-scope-iteration.shared.utils.js.map +1 -1
  82. package/dist/esm/databases/models/filter.backend.schemas.js +2 -2
  83. package/dist/esm/databases/models/filter.backend.schemas.js.map +1 -1
  84. package/dist/esm/databases/services/aggregation/aggregation-authorization.backend.service.d.ts.map +1 -1
  85. package/dist/esm/databases/services/aggregation/aggregation-authorization.backend.service.js +20 -1
  86. package/dist/esm/databases/services/aggregation/aggregation-authorization.backend.service.js.map +1 -1
  87. package/dist/esm/databases/services/redis.service.d.ts +27 -0
  88. package/dist/esm/databases/services/redis.service.d.ts.map +1 -1
  89. package/dist/esm/databases/services/redis.service.js +29 -0
  90. package/dist/esm/databases/services/redis.service.js.map +1 -1
  91. package/dist/esm/errors/services/error-handler.backend.service.d.ts.map +1 -1
  92. package/dist/esm/errors/services/error-handler.backend.service.js +5 -0
  93. package/dist/esm/errors/services/error-handler.backend.service.js.map +1 -1
  94. package/dist/esm/external-data/controllers/external-data-admin.backend.contracts.d.ts +41 -0
  95. package/dist/esm/external-data/controllers/external-data-admin.backend.contracts.d.ts.map +1 -0
  96. package/dist/esm/external-data/controllers/external-data-admin.backend.contracts.js +40 -0
  97. package/dist/esm/external-data/controllers/external-data-admin.backend.contracts.js.map +1 -0
  98. package/dist/esm/external-data/controllers/external-data-admin.backend.controller.d.ts +64 -0
  99. package/dist/esm/external-data/controllers/external-data-admin.backend.controller.d.ts.map +1 -0
  100. package/dist/esm/external-data/controllers/external-data-admin.backend.controller.js +193 -0
  101. package/dist/esm/external-data/controllers/external-data-admin.backend.controller.js.map +1 -0
  102. package/dist/esm/external-data/external-data-pipeline-run.backend.service.d.ts +13 -2
  103. package/dist/esm/external-data/external-data-pipeline-run.backend.service.d.ts.map +1 -1
  104. package/dist/esm/external-data/external-data-pipeline-run.backend.service.js +8 -2
  105. package/dist/esm/external-data/external-data-pipeline-run.backend.service.js.map +1 -1
  106. package/dist/esm/external-data/external-data-transform.backend.d.ts.map +1 -1
  107. package/dist/esm/external-data/external-data-transform.backend.js +7 -1
  108. package/dist/esm/external-data/external-data-transform.backend.js.map +1 -1
  109. package/dist/esm/external-data/models/external-data-pipeline-state.backend.schemas.d.ts +2 -0
  110. package/dist/esm/external-data/models/external-data-pipeline-state.backend.schemas.d.ts.map +1 -1
  111. package/dist/esm/external-data/models/external-data-pipeline-state.backend.schemas.js +13 -0
  112. package/dist/esm/external-data/models/external-data-pipeline-state.backend.schemas.js.map +1 -1
  113. package/dist/esm/external-providers/services/external-providers-registry.backend.service.d.ts +14 -0
  114. package/dist/esm/external-providers/services/external-providers-registry.backend.service.d.ts.map +1 -1
  115. package/dist/esm/external-providers/services/external-providers-registry.backend.service.js +6 -0
  116. package/dist/esm/external-providers/services/external-providers-registry.backend.service.js.map +1 -1
  117. package/dist/esm/files/controllers/file.controller.d.ts +24 -1
  118. package/dist/esm/files/controllers/file.controller.d.ts.map +1 -1
  119. package/dist/esm/files/controllers/file.controller.js +66 -2
  120. package/dist/esm/files/controllers/file.controller.js.map +1 -1
  121. package/dist/esm/files/handlers/file-upload-route-locals.backend.types.d.ts +17 -0
  122. package/dist/esm/files/handlers/file-upload-route-locals.backend.types.d.ts.map +1 -0
  123. package/dist/esm/files/handlers/file-upload-route-locals.backend.types.js +1 -0
  124. package/dist/esm/files/handlers/file-upload-route-locals.backend.types.js.map +1 -0
  125. package/dist/esm/files/handlers/resource-file-upload-handler.backend.service.d.ts +5 -1
  126. package/dist/esm/files/handlers/resource-file-upload-handler.backend.service.d.ts.map +1 -1
  127. package/dist/esm/files/handlers/resource-file-upload-handler.backend.service.js +42 -3
  128. package/dist/esm/files/handlers/resource-file-upload-handler.backend.service.js.map +1 -1
  129. package/dist/esm/files/services/file-operation-handler.backend.service.d.ts +18 -0
  130. package/dist/esm/files/services/file-operation-handler.backend.service.d.ts.map +1 -1
  131. package/dist/esm/files/services/file-operation-handler.backend.service.js +36 -28
  132. package/dist/esm/files/services/file-operation-handler.backend.service.js.map +1 -1
  133. package/dist/esm/files/services/file-upload-grant.backend.service.d.ts +163 -0
  134. package/dist/esm/files/services/file-upload-grant.backend.service.d.ts.map +1 -0
  135. package/dist/esm/files/services/file-upload-grant.backend.service.js +442 -0
  136. package/dist/esm/files/services/file-upload-grant.backend.service.js.map +1 -0
  137. package/dist/esm/files/services/files.backend.service.d.ts +19 -0
  138. package/dist/esm/files/services/files.backend.service.d.ts.map +1 -1
  139. package/dist/esm/files/services/files.backend.service.js +78 -15
  140. package/dist/esm/files/services/files.backend.service.js.map +1 -1
  141. package/dist/esm/files/utils/file-uploader.utils.d.ts.map +1 -1
  142. package/dist/esm/files/utils/file-uploader.utils.js +12 -0
  143. package/dist/esm/files/utils/file-uploader.utils.js.map +1 -1
  144. package/dist/esm/flows-actors/a2a/services/a2a-task-cancellation.backend.service.js +5 -5
  145. package/dist/esm/flows-actors/a2a/services/a2a-task-cancellation.backend.service.js.map +1 -1
  146. package/dist/esm/flows-actors/services/agents.backend.service.d.ts +79 -0
  147. package/dist/esm/flows-actors/services/agents.backend.service.d.ts.map +1 -1
  148. package/dist/esm/flows-actors/services/agents.backend.service.js +319 -42
  149. package/dist/esm/flows-actors/services/agents.backend.service.js.map +1 -1
  150. package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.d.ts +151 -41
  151. package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.d.ts.map +1 -1
  152. package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.js +300 -139
  153. package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.js.map +1 -1
  154. package/dist/esm/index.d.ts +4 -1
  155. package/dist/esm/index.d.ts.map +1 -1
  156. package/dist/esm/index.js +14 -1
  157. package/dist/esm/index.js.map +1 -1
  158. package/dist/esm/inject/models/container.d.ts.map +1 -1
  159. package/dist/esm/inject/models/container.js +4 -0
  160. package/dist/esm/inject/models/container.js.map +1 -1
  161. package/dist/esm/inject/models/service-types.d.ts +3 -0
  162. package/dist/esm/inject/models/service-types.d.ts.map +1 -1
  163. package/dist/esm/inject/models/service-types.js +2 -0
  164. package/dist/esm/inject/models/service-types.js.map +1 -1
  165. package/dist/esm/mcp/controllers/mcp.controller.d.ts.map +1 -1
  166. package/dist/esm/mcp/controllers/mcp.controller.js +12 -4
  167. package/dist/esm/mcp/controllers/mcp.controller.js.map +1 -1
  168. package/dist/esm/mcp/models/mcp-tool.backend.schemas.d.ts +34 -0
  169. package/dist/esm/mcp/models/mcp-tool.backend.schemas.d.ts.map +1 -1
  170. package/dist/esm/mcp/models/mcp-tool.backend.schemas.js +42 -0
  171. package/dist/esm/mcp/models/mcp-tool.backend.schemas.js.map +1 -1
  172. package/dist/esm/mcp/services/mcp-server.backend.service.d.ts +29 -1
  173. package/dist/esm/mcp/services/mcp-server.backend.service.d.ts.map +1 -1
  174. package/dist/esm/mcp/services/mcp-server.backend.service.js +131 -3
  175. package/dist/esm/mcp/services/mcp-server.backend.service.js.map +1 -1
  176. package/dist/esm/mcp/services/mcp-tool-adapter.backend.service.d.ts +64 -2
  177. package/dist/esm/mcp/services/mcp-tool-adapter.backend.service.d.ts.map +1 -1
  178. package/dist/esm/mcp/services/mcp-tool-adapter.backend.service.js +130 -6
  179. package/dist/esm/mcp/services/mcp-tool-adapter.backend.service.js.map +1 -1
  180. package/dist/esm/notifications/services/notifications-dispatcher.backend.service.d.ts +9 -0
  181. package/dist/esm/notifications/services/notifications-dispatcher.backend.service.d.ts.map +1 -1
  182. package/dist/esm/notifications/services/notifications-dispatcher.backend.service.js +11 -36
  183. package/dist/esm/notifications/services/notifications-dispatcher.backend.service.js.map +1 -1
  184. package/dist/esm/notifications/webhooks/outbound/batches/m2m-webhook-delivery.batch.backend.service.d.ts.map +1 -1
  185. package/dist/esm/notifications/webhooks/outbound/batches/m2m-webhook-delivery.batch.backend.service.js +9 -7
  186. package/dist/esm/notifications/webhooks/outbound/batches/m2m-webhook-delivery.batch.backend.service.js.map +1 -1
  187. package/dist/esm/notifications/webhooks/outbound/batches/m2m-webhook-delivery.batch.utils.d.ts +5 -5
  188. package/dist/esm/notifications/webhooks/outbound/batches/m2m-webhook-delivery.batch.utils.d.ts.map +1 -1
  189. package/dist/esm/notifications/webhooks/outbound/batches/m2m-webhook-delivery.batch.utils.js +14 -13
  190. package/dist/esm/notifications/webhooks/outbound/batches/m2m-webhook-delivery.batch.utils.js.map +1 -1
  191. package/dist/esm/notifications/webhooks/outbound/m2m-webhook-signed-request.backend.utils.d.ts +2 -1
  192. package/dist/esm/notifications/webhooks/outbound/m2m-webhook-signed-request.backend.utils.d.ts.map +1 -1
  193. package/dist/esm/notifications/webhooks/outbound/m2m-webhook-signed-request.backend.utils.js +2 -2
  194. package/dist/esm/notifications/webhooks/outbound/m2m-webhook-signed-request.backend.utils.js.map +1 -1
  195. package/dist/esm/notifications/webhooks/outbound/services/webhook-config-test-endpoint.custom-impl.backend.service.d.ts.map +1 -1
  196. package/dist/esm/notifications/webhooks/outbound/services/webhook-config-test-endpoint.custom-impl.backend.service.js +9 -7
  197. package/dist/esm/notifications/webhooks/outbound/services/webhook-config-test-endpoint.custom-impl.backend.service.js.map +1 -1
  198. package/dist/esm/organizations/services/organization-unit-custom-implementation.backend.service.d.ts.map +1 -1
  199. package/dist/esm/organizations/services/organization-unit-custom-implementation.backend.service.js +4 -1
  200. package/dist/esm/organizations/services/organization-unit-custom-implementation.backend.service.js.map +1 -1
  201. package/dist/esm/requests/service/websocket.service.d.ts.map +1 -1
  202. package/dist/esm/requests/service/websocket.service.js +56 -7
  203. package/dist/esm/requests/service/websocket.service.js.map +1 -1
  204. package/dist/esm/resources/models/custom-service-implementations.backend.definition.d.ts.map +1 -1
  205. package/dist/esm/resources/models/custom-service-implementations.backend.definition.js +2 -0
  206. package/dist/esm/resources/models/custom-service-implementations.backend.definition.js.map +1 -1
  207. package/dist/esm/resources/services/resource-id.backend.service.js +3 -3
  208. package/dist/esm/resources/services/resource-id.backend.service.js.map +1 -1
  209. package/dist/esm/resources/services/resources-registry.backend.service.js +1 -1
  210. package/dist/esm/resources/services/resources-registry.backend.service.js.map +1 -1
  211. package/dist/esm/runtime/services/execution-context-creator.backend.service.d.ts.map +1 -1
  212. package/dist/esm/runtime/services/execution-context-creator.backend.service.js +13 -7
  213. package/dist/esm/runtime/services/execution-context-creator.backend.service.js.map +1 -1
  214. package/dist/esm/runtime/services/start-application.backend.service.d.ts +28 -0
  215. package/dist/esm/runtime/services/start-application.backend.service.d.ts.map +1 -1
  216. package/dist/esm/runtime/services/start-application.backend.service.js +82 -0
  217. package/dist/esm/runtime/services/start-application.backend.service.js.map +1 -1
  218. package/dist/esm/security/authentications/models/jwt.backend.schemas.d.ts +3 -23
  219. package/dist/esm/security/authentications/models/jwt.backend.schemas.d.ts.map +1 -1
  220. package/dist/esm/security/authentications/models/jwt.backend.schemas.js +20 -45
  221. package/dist/esm/security/authentications/models/jwt.backend.schemas.js.map +1 -1
  222. package/dist/esm/security/authentications/services/auth-methods/auth-method-management.backend.service.d.ts +9 -1
  223. package/dist/esm/security/authentications/services/auth-methods/auth-method-management.backend.service.d.ts.map +1 -1
  224. package/dist/esm/security/authentications/services/auth-methods/auth-method-management.backend.service.js +9 -1
  225. package/dist/esm/security/authentications/services/auth-methods/auth-method-management.backend.service.js.map +1 -1
  226. package/dist/esm/security/authentications/services/auth-methods/auth-mfa.backend.service.d.ts.map +1 -1
  227. package/dist/esm/security/authentications/services/auth-methods/auth-mfa.backend.service.js +5 -3
  228. package/dist/esm/security/authentications/services/auth-methods/auth-mfa.backend.service.js.map +1 -1
  229. package/dist/esm/security/authentications/services/auth-token-issuer.backend.service.d.ts +25 -1
  230. package/dist/esm/security/authentications/services/auth-token-issuer.backend.service.d.ts.map +1 -1
  231. package/dist/esm/security/authentications/services/auth-token-issuer.backend.service.js +55 -4
  232. package/dist/esm/security/authentications/services/auth-token-issuer.backend.service.js.map +1 -1
  233. package/dist/esm/security/authorizations/initiator-organization-confinement.backend.d.ts.map +1 -1
  234. package/dist/esm/security/authorizations/initiator-organization-confinement.backend.js +24 -1
  235. package/dist/esm/security/authorizations/initiator-organization-confinement.backend.js.map +1 -1
  236. package/dist/esm/security/authorizations/privileged-access-review.backend.utils.d.ts +117 -0
  237. package/dist/esm/security/authorizations/privileged-access-review.backend.utils.d.ts.map +1 -0
  238. package/dist/esm/security/authorizations/privileged-access-review.backend.utils.js +104 -0
  239. package/dist/esm/security/authorizations/privileged-access-review.backend.utils.js.map +1 -0
  240. package/dist/esm/security/authorizations/services/authorizations.backend.service.d.ts +101 -6
  241. package/dist/esm/security/authorizations/services/authorizations.backend.service.d.ts.map +1 -1
  242. package/dist/esm/security/authorizations/services/authorizations.backend.service.js +210 -30
  243. package/dist/esm/security/authorizations/services/authorizations.backend.service.js.map +1 -1
  244. package/dist/esm/security/consumable-tokens/batches/consumable-tokens-cleanup.batch.backend.service.d.ts +18 -1
  245. package/dist/esm/security/consumable-tokens/batches/consumable-tokens-cleanup.batch.backend.service.d.ts.map +1 -1
  246. package/dist/esm/security/consumable-tokens/batches/consumable-tokens-cleanup.batch.backend.service.js +110 -74
  247. package/dist/esm/security/consumable-tokens/batches/consumable-tokens-cleanup.batch.backend.service.js.map +1 -1
  248. package/dist/esm/security/consumable-tokens/consumable-token-models.exports.d.ts +22 -0
  249. package/dist/esm/security/consumable-tokens/consumable-token-models.exports.d.ts.map +1 -0
  250. package/dist/esm/security/consumable-tokens/consumable-token-models.exports.js +22 -0
  251. package/dist/esm/security/consumable-tokens/consumable-token-models.exports.js.map +1 -0
  252. package/dist/esm/security/consumable-tokens/models/consumable-tokens.backend.resources-config.schemas.d.ts +17 -3
  253. package/dist/esm/security/consumable-tokens/models/consumable-tokens.backend.resources-config.schemas.d.ts.map +1 -1
  254. package/dist/esm/security/consumable-tokens/models/consumable-tokens.backend.resources-config.schemas.js +12 -0
  255. package/dist/esm/security/consumable-tokens/models/consumable-tokens.backend.resources-config.schemas.js.map +1 -1
  256. package/dist/esm/security/consumable-tokens/services/consumable-token.backend.service.d.ts +20 -0
  257. package/dist/esm/security/consumable-tokens/services/consumable-token.backend.service.d.ts.map +1 -1
  258. package/dist/esm/security/consumable-tokens/services/consumable-token.backend.service.js +58 -5
  259. package/dist/esm/security/consumable-tokens/services/consumable-token.backend.service.js.map +1 -1
  260. package/dist/esm/security/jwt/services/jwt.backend.service.d.ts.map +1 -1
  261. package/dist/esm/security/jwt/services/jwt.backend.service.js +1 -18
  262. package/dist/esm/security/jwt/services/jwt.backend.service.js.map +1 -1
  263. package/dist/tsconfig.build.tsbuildinfo +1 -1
  264. package/package.json +15 -9
  265. package/dist/esm/.builder.pid +0 -9
@@ -1 +1 @@
1
- {"version":3,"file":"repository-resource.backend.service.js","sourceRoot":"","sources":["../../../../../../src/base-classes/services/repositories/repository-resource.backend.service.ts"],"names":[],"mappings":"AAAA,OAAO,kBAAkB,CAAC;AAW1B,OAAO,EACL,qBAAqB,EACrB,gBAAgB,EAChB,2BAA2B,EAC3B,SAAS,EACT,8BAA8B,EAC9B,kBAAkB,EAClB,iCAAiC,EACjC,uBAAuB,EACvB,4BAA4B,EAE5B,kCAAkC,GAGnC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,+BAA+B,EAC/B,2BAA2B,EAC3B,wBAAwB,GACzB,MAAM,wEAAwE,CAAC;AAChF,OAAO,EACL,uCAAuC,EACvC,0CAA0C,EAC1C,6CAA6C,EAC7C,+CAA+C,EAC/C,8CAA8C,GAC/C,MAAM,4FAA4F,CAAC;AACpG,OAAO,EAAE,8CAA8C,EAAE,MAAM,uFAAuF,CAAC;AACvJ,OAAO,EAAE,4CAA4C,EAAE,MAAM,sFAAsF,CAAC;AACpJ,OAAO,EACL,wBAAwB,EACxB,qCAAqC,GACtC,MAAM,8EAA8E,CAAC;AACtF,OAAO,EAAE,2CAA2C,EAAE,MAAM,oFAAoF,CAAC;AACjJ,OAAO,EACL,sBAAsB,EAEtB,yBAAyB,GAC1B,MAAM,2EAA2E,CAAC;AACnF,OAAO,EACL,gCAAgC,GAEjC,MAAM,8EAA8E,CAAC;AAGtF,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,sBAAsB,EACtB,gBAAgB,EAChB,iBAAiB,EACjB,qBAAqB,EACrB,0BAA0B,GAC3B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,sBAAsB,EACtB,gCAAgC,GAEjC,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAAE,0BAA0B,EAAE,0BAA0B,EAAE,sBAAsB,EAAmC,MAAM,oCAAoC,CAAC;AACrK,OAAO,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AAChF,OAAO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,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,WAAW,CAAC;IAC7E,CAAC;CAIF","sourcesContent":["import 'reflect-metadata';\n\nimport type {\n ResourceConfiguration,\n ResourceConfiguration_Operation,\n ResourceConfiguration_OperationRepositoryPath,\n CollectionView_SearchOptions,\n Resources_PaginationRequest,\n SearchableFieldDescriptor,\n SearchableRelationDescriptor,\n} from '@wildo-ai/saas-models';\nimport {\n CoreResourceOperation,\n CoreResourceType,\n ErrorCustomMessageReference,\n ErrorType,\n isSearchableRelationDescriptor,\n PersistenceAdapter,\n PRIMARY_SCOPE_TO_FIELD_IDENTIFIER,\n ResourceOperationsUtils,\n ResourceOperationVariantType,\n Resources_PaginatedResult,\n ResourcesConfig_OperationPathUtils,\n ResourceType,\n WildoError_Backend,\n} from '@wildo-ai/saas-models';\nimport {\n assignRetentionHideForOperation,\n isRetentionGovernedResource,\n withRetentionHideApplied,\n} from '~wildo-backend-lib/compliance/privacy/retention-hide-predicate.backend';\nimport {\n assignOrganizationUnitNarrowingToFilter,\n isOrganizationUnitNarrowingExemptExecution,\n OrganizationUnitNarrowingWriteViolationReason,\n resolveSuppliedOrganizationUnitIdForTenantCheck,\n resolveOrganizationUnitNarrowingWriteViolation,\n} from '~wildo-backend-lib/security/authorizations/organization-unit-narrowing-enforcement.backend';\nimport { assignInitiatorOrganizationConfinementToFilter } from '~wildo-backend-lib/security/authorizations/initiator-organization-confinement.backend';\nimport { assignScopeRootCollectionConfinementToFilter } from '~wildo-backend-lib/security/authorizations/scope-root-collection-confinement.backend';\nimport {\n applyJunctionScopeFilter,\n collectJunctionScopedFieldIdentifiers,\n} from '~wildo-backend-lib/security/authorizations/junction-scope-resolution.backend';\nimport { assignRelationshipForeignKeyFiltersToFilter } from '~wildo-backend-lib/security/authorizations/relationship-foreign-key-filter.backend';\nimport {\n buildBusinessKeyFilter,\n resolveBusinessKeyFieldNames,\n BUSINESS_KEY_ERROR_PREFIX,\n} from '~wildo-backend-lib/data-seeding/models/business-key-resolver.shared.utils';\nimport {\n DATA_SEED_ROW_METADATA_FIELD_KEY,\n type DataSeedRowMetadata,\n} from '~wildo-backend-lib/data-seeding/models/data-seed-row-metadata.shared.schemas';\nimport { EnumLikeType } from '@wildo-ai/zod-decorators';\nimport type { FieldMetaEntry } from '@wildo-ai/saas-models';\nimport {\n lwwFieldWinner,\n CrdtResolutionWinner,\n nextMonotonicTimestamp,\n isCrdtOnlyUpdate,\n sanitizeFieldMeta,\n extractCrdtFieldNames,\n ResourceSerializationUtils,\n} from '@wildo-ai/saas-models';\nimport {\n guardedMutationHasWork,\n RepositoryArrayAdditionPlacement,\n type RepositoryGuardedMutation,\n} from './repository-guarded-mutation.backend.types';\nimport { assertCreateWriteIntegrity, assertUpdateWriteIntegrity, referenceConstraintsOf, type ResourceWriteIntegrityDeps } from './resource-write-integrity.backend';\nimport { partitionNullClearedFields } from './field-clearing-partition.backend';\nimport { Connection, Document, FilterQuery, Model, Types } from 'mongoose';\n\nimport { z } from 'zod';\nimport type { LoggerService } from '~wildo-backend-lib/monitoring/logger/services/logger.service';\nimport type { ZodToMongooseSchemaConvertorBackendService } from '~wildo-backend-lib/databases/services/zod-to-mongoose-schema-convertor.backend.service';\nimport { normalizeDateRangeFilters } from '~wildo-backend-lib/databases/models/filter.backend.schemas';\nimport { ErrorBuilderBackendService } from '~wildo-backend-lib/errors/services/error-builder.backend.service';\nimport { describeCaughtError, projectCaughtErrorLogFields } from '~wildo-backend-lib/errors/utils/error-log-level-classification.backend.utils';\nimport { ResourcesRegistryBackendService } from '~wildo-backend-lib/resources/services/resources-registry.backend.service';\nimport { ResourceIdBackendService } from '~wildo-backend-lib/resources/services/resource-id.backend.service';\nimport { ExecutionContext } from '~wildo-backend-lib/runtime/models/execution-context.backend.schemas';\nimport { normalizeRepositoryVersionMetadata } from '~wildo-backend-lib/base-classes/services/repositories/repository-version-metadata.backend.utils';\nimport { resolveDeclaredUniqueConflictReference } from '~wildo-backend-lib/base-classes/services/repositories/unique-constraint-conflict-reference.backend';\nimport { IdOrFilterType, IdOrIdsOrFilterType, IdsOrFilterType, RepositoryOptions } from '~wildo-backend-lib/base-classes/models/repositories.backend.schemas';\nimport { ResourceOperationHelperBackendService } from '~wildo-backend-lib/base-classes/services/resource-operations-helper.backend.service';\nimport {\n MainSchemaType,\n PartialMainSchemaType,\n MainSchemaArrayType,\n ConditionalReturnType,\n ConditionalArrayReturnType,\n ConditionalNullableReturnType\n} from '~wildo-backend-lib/base-classes/utils/backend-type-utils';\n\n\nconst DEBUG_ACTIVATED = false;\n\n// Forward declaration to avoid circular dependency\ntype RepositoriesRegistryHandlerBackendService = any;\n\n/**\n * Factory interface for creating repository resource instances\n *\n * NOTE: TDatabaseSchema has been removed. Backend-only fields are now marked with\n * the `isBackendOnly` decorator on mainSchema and handled at the service layer.\n */\nexport interface RepositoryResourceFactory {\n create<\n TCustomOperationEnum extends EnumLikeType | undefined = undefined,\n TCoreOperationEnum extends Partial<CoreResourceOperation> | undefined = undefined,\n TMainSchema extends z.ZodTypeAny = z.ZodTypeAny\n >(\n resourceConfiguration: ResourceConfiguration<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>\n ): RepositoryResourceBackendService<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\n}\n\n/**\n * MongoDB Repository Implementation\n *\n * This class provides the MongoDB/Mongoose implementation of the resource repository.\n * It conforms to the `BackendResourceRepository` interface contract through TypeScript's\n * structural typing.\n *\n * ## Transaction Support\n *\n * Uses the `getNativeSession()` helper to extract the Mongoose ClientSession from\n * the database-agnostic `options.transaction.nativeSession` (TransactionContext).\n *\n * @see BackendResourceRepository in repositories-registry-handler.backend.service.ts\n * @see PostgreSQLResourceRepositoryBackendService for PostgreSQL implementation\n */\nimport type { BackendResourceRepository } from './repositories-registry-handler.backend.service';\n\n/**\n * `import type` on purpose: the registry imports THIS module to construct repositories,\n * so a value import back would close a runtime cycle (and this package runs as native\n * ESM, where that surfaces as \"Cannot access … before initialization\"). A type-only\n * import is erased at compile time, so conformance can be declared without one.\n */\nexport class RepositoryResourceBackendService<\n TCustomOperationEnum extends EnumLikeType | undefined = undefined,\n TCoreOperationEnum extends Partial<CoreResourceOperation> | undefined = undefined,\n TMainSchema extends z.ZodTypeAny = z.ZodTypeAny\n> implements BackendResourceRepository<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> {\n\n private readonly resourceConfiguration: ResourceConfiguration<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\n private readonly mongooseModel: Model<any & Document>;\n private readonly inheritanceModels: Map<string, Model<any & Document>>;\n private readonly operationsMap: Map<string, ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>>;\n\n protected logDebug: (message: string, context?: Record<string, unknown>) => void;\n\n constructor(\n resourceType: ResourceType,\n private readonly zodToMongooseConverter: ZodToMongooseSchemaConvertorBackendService,\n private readonly logger: LoggerService,\n private readonly errorBuilder: ErrorBuilderBackendService,\n private readonly resourceRegistry: ResourcesRegistryBackendService,\n private readonly resourceOperationHelper: ResourceOperationHelperBackendService,\n private readonly repositoriesRegistry: RepositoriesRegistryHandlerBackendService,\n private readonly connection: Connection | undefined = undefined,\n private readonly resourceIdService?: ResourceIdBackendService,\n ) {\n this.resourceConfiguration = this.resourceRegistry.getResourceConfiguration(resourceType);\n this.zodToMongooseConverter = zodToMongooseConverter;\n\n this.inheritanceModels = new Map();\n this.operationsMap = new Map();\n\n this.logDebug = this.logger.debugByType(`RepositoryResource_${resourceType}`);\n this.logger.setDebugTypeLogging(`RepositoryResource_${resourceType}`, DEBUG_ACTIVATED);\n\n // Initialize mongoose model and operations\n this.mongooseModel = this.initializeMongooseModel();\n this.initializeOperationsMap();\n\n this.logDebug('Repository resource service created', { resourceType: this.resourceConfiguration.resourceIdentifier, operationsCount: this.operationsMap.size, hasInheritance: this.inheritanceModels.size > 0 });\n }\n\n // ================================\n // Transaction Session Helper\n // ================================\n\n /**\n * Get the native Mongoose session from repository options.\n *\n * Extracts the Mongoose ClientSession from the database-agnostic TransactionContext.\n * Includes runtime safety check to ensure MongoDB repository doesn't receive\n * a PostgreSQL transaction context.\n *\n * @param options - Repository options that may contain transaction\n * @returns The Mongoose ClientSession or undefined\n * @throws Error if a non-MongoDB transaction is provided\n */\n protected getNativeSession(options?: RepositoryOptions): import('mongoose').ClientSession | undefined {\n if (!options?.transaction) {\n return undefined;\n }\n\n // Runtime safety check: ensure this is a MongoDB transaction\n if (options.transaction.databaseType !== PersistenceAdapter.MONGODB) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n context: {\n // diagnostic (log-only): wrong persistence adapter wired for this resource (framework config bug).\n expectedDatabaseType: PersistenceAdapter.MONGODB,\n receivedDatabaseType: options.transaction.databaseType,\n },\n });\n }\n return options.transaction.nativeSession as import('mongoose').ClientSession | undefined;\n }\n\n // ================================\n // Initialization\n // ================================\n\n static createInstance<\n TCustomOperationEnum extends EnumLikeType | undefined = undefined,\n TCoreOperationEnum extends Partial<CoreResourceOperation> | undefined = undefined,\n TMainSchema extends z.ZodTypeAny = z.ZodTypeAny\n >(\n resourceType: ResourceType,\n zodToMongooseConverter: ZodToMongooseSchemaConvertorBackendService,\n logger: LoggerService,\n errorBuilder: ErrorBuilderBackendService,\n resourceRegistry: ResourcesRegistryBackendService,\n resourceOperationHelper: ResourceOperationHelperBackendService,\n repositoriesRegistry: RepositoriesRegistryHandlerBackendService,\n connection: Connection | undefined = undefined,\n resourceIdService?: ResourceIdBackendService,\n ): RepositoryResourceBackendService<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> {\n return new RepositoryResourceBackendService(\n resourceType,\n zodToMongooseConverter,\n logger,\n errorBuilder,\n resourceRegistry,\n resourceOperationHelper,\n repositoriesRegistry,\n connection,\n resourceIdService,\n );\n }\n\n private initializeOperationsMap(): void {\n if (!this.resourceConfiguration.operations) {\n return;\n }\n\n this.resourceConfiguration.operations.forEach(operation => {\n const operationKey = ResourcesConfig_OperationPathUtils.createOperationRepositoryPathKeyFromOperation(operation as any);\n this.operationsMap.set(operationKey, operation);\n });\n\n this.logDebug('Operations map initialized', {\n operationsCount: this.operationsMap.size,\n operationKeys: Array.from(this.operationsMap.keys())\n });\n }\n\n private initializeMongooseModel(): Model<any & Document> {\n try {\n const modelResult = this.zodToMongooseConverter.convertResourceConfigurationToModel(\n this.resourceConfiguration,\n {\n includeIndexes: true,\n applyDefaults: true,\n connection: this.connection\n }\n );\n\n // Store inheritance models if any\n // Use a Set to track created discriminator values to avoid duplicates\n const createdDiscriminatorValues = new Set<string>();\n modelResult.inheritanceSchemas.forEach(inheritance => {\n // Skip if discriminator with this value already exists\n if (createdDiscriminatorValues.has(inheritance.discriminatorValue)) {\n this.logDebug(`Skipping duplicate discriminator value: ${inheritance.discriminatorValue}`, {\n discriminatorKey: inheritance.discriminatorKey,\n discriminatorValue: inheritance.discriminatorValue\n });\n return;\n }\n\n try {\n // Check if discriminator already exists on the model\n const existingDiscriminator = (modelResult.mainModel as any).discriminators?.[inheritance.discriminatorValue];\n if (existingDiscriminator) {\n this.logDebug(`Discriminator already exists, reusing: ${inheritance.discriminatorValue}`, {\n discriminatorKey: inheritance.discriminatorKey,\n discriminatorValue: inheritance.discriminatorValue\n });\n this.inheritanceModels.set(inheritance.discriminatorValue, existingDiscriminator);\n createdDiscriminatorValues.add(inheritance.discriminatorValue);\n return;\n }\n\n // Create inheritance model from schema\n const inheritanceModel = modelResult.mainModel.discriminator(\n inheritance.discriminatorValue,\n inheritance.schema\n );\n this.inheritanceModels.set(inheritance.discriminatorValue, inheritanceModel);\n createdDiscriminatorValues.add(inheritance.discriminatorValue);\n } catch (error: any) {\n // If discriminator already exists, try to get it\n if (error?.message?.includes('already exists')) {\n this.logDebug(`Discriminator already exists, attempting to retrieve: ${inheritance.discriminatorValue}`, {\n discriminatorKey: inheritance.discriminatorKey,\n discriminatorValue: inheritance.discriminatorValue\n });\n const existingDiscriminator = (modelResult.mainModel as any).discriminators?.[inheritance.discriminatorValue];\n if (existingDiscriminator) {\n this.inheritanceModels.set(inheritance.discriminatorValue, existingDiscriminator);\n createdDiscriminatorValues.add(inheritance.discriminatorValue);\n } else {\n this.logger.warn(`Failed to create or retrieve discriminator: ${inheritance.discriminatorValue}`, {\n error: error.message,\n discriminatorKey: inheritance.discriminatorKey\n });\n }\n } else {\n throw error;\n }\n }\n });\n\n this.logDebug('Mongoose model initialized', {\n modelName: modelResult.mainModel.modelName,\n inheritanceCount: this.inheritanceModels.size\n });\n\n return modelResult.mainModel;\n } catch (error) {\n this.logger.error('Failed to initialize mongoose model', {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n ...projectCaughtErrorLogFields(error)\n });\n throw error;\n }\n }\n\n\n // ================================\n // Getters\n // ================================\n\n public getInheritanceModel(discriminatorValue: string): Model<any & Document> | undefined {\n return this.inheritanceModels.get(discriminatorValue);\n }\n\n // ================================\n // Execution\n // ================================\n\n public async doByPath<T = any, U = any>(\n operationRepositoryPath: ResourceConfiguration_OperationRepositoryPath,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: U,\n options?: RepositoryOptions\n ): Promise<T> {\n const operationRepositoryPathKey = ResourcesConfig_OperationPathUtils.createOperationRepositoryPathKey(operationRepositoryPath);\n\n this.logDebug('Executing operation by repository path', { operationRepositoryPath, operationRepositoryPathKey, hasData: !!data, id_or_ids_or_filter });\n\n return this.doByKey( operationRepositoryPathKey, executionContext, id_or_ids_or_filter, data, options );\n }\n\n /**\n * Execute operation by operation repository path key (string)\n */\n public async doByKey<T = any, U = any>(\n operationRepositoryPathKey: string,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: U,\n options?: RepositoryOptions\n ): Promise<T> {\n\n ResourcesConfig_OperationPathUtils.validateOperationRepositoryPathKey(operationRepositoryPathKey);\n\n const operation = this.operationsMap.get(operationRepositoryPathKey);\n\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.NOT_FOUND, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationRepositoryPathKey } } );\n }\n\n this.logDebug('Executing operation by repository path key', { operationRepositoryPathKey, hasData: !!data, id_or_ids_or_filter });\n\n return this.doOperation(operation, executionContext, id_or_ids_or_filter, data, options);\n }\n\n public async doByExecutionContext<T = any>(\n executionContext: ExecutionContext<ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>>,\n data?: any,\n options?: RepositoryOptions\n ): Promise<T> {\n const operation = executionContext.operation;\n\n // Extract IDs based on resourceFieldIdentifier from execution context\n const id_or_ids_or_filter = this.resourceOperationHelper.extractIdsFromExecutionContext(executionContext, this.resourceConfiguration.resourceFieldIdentifier);\n\n this.logDebug('Executing operation by execution context', {\n operationIdentifier: operation.operationIdentifier,\n resourceIdentifier: operation.resourceIdentifier,\n hasData: !!data,\n extractedIds: id_or_ids_or_filter,\n resourceFieldIdentifier: this.resourceConfiguration.resourceFieldIdentifier\n });\n\n return this.doOperation(operation, executionContext, id_or_ids_or_filter, data, options);\n }\n\n private async _prefixOperation(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: any,\n options?: RepositoryOptions\n ): Promise<void> {\n // Authorization is handled at the controller/middleware layer before reaching the repository.\n // Repository-level prefix operations are reserved for data-level pre-processing (e.g., input normalization).\n // Operation-level authorization is enforced by the ResourceOperationService via role + variant checks.\n }\n\n private async _postfixOperation(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: any,\n options?: RepositoryOptions\n ): Promise<void> {\n // Post-operation hook reserved for data-level post-processing (e.g., cache invalidation).\n // Currently no-op by design — business logic runs at the service layer.\n }\n\n /**\n * Execute a specific operation\n */\n private async doOperation(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: any,\n options?: RepositoryOptions\n ): Promise<any> {\n const operationRepositoryPathKey = ResourcesConfig_OperationPathUtils.createOperationRepositoryPathKeyFromOperation(operation);\n\n if(operation.resourceIdentifier !== this.resourceConfiguration.resourceIdentifier) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationRepositoryPathKey, resourceIdentifier: this.resourceConfiguration.resourceIdentifier } } );\n }\n const operationIdentifier = ResourceOperationsUtils.getCoreResourceOperationFromOperation(operation);\n\n if (!operationIdentifier) {\n\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationRepositoryPathKey } } );\n }\n\n await this._prefixOperation(operation, executionContext, id_or_ids_or_filter, data, options);\n\n let operationResult: any;\n // Handle core operations\n switch (operationIdentifier) {\n case CoreResourceOperation.CREATE:\n operationResult = await this._doCreate(operation, executionContext, data, options);\n break;\n\n case CoreResourceOperation.CREATE_MANY:\n operationResult = await this._doCreateMany(operation, executionContext, data, options);\n break;\n\n case CoreResourceOperation.READ:\n if(Array.isArray(id_or_ids_or_filter)) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED,\n context: { operationRepositoryPathKey, resourceIdentifier: this.resourceConfiguration.resourceIdentifier, id_or_ids_or_filter } } );\n }\n operationResult = await this._doRead(operation, executionContext, id_or_ids_or_filter as IdOrFilterType, options);\n break;\n\n case CoreResourceOperation.UPDATE:\n if(Array.isArray(id_or_ids_or_filter)) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED,\n context: { operationRepositoryPathKey, resourceIdentifier: this.resourceConfiguration.resourceIdentifier, id_or_ids_or_filter } } );\n }\n operationResult = await this._doUpdate(operation, executionContext, id_or_ids_or_filter as IdOrFilterType, data, options);\n break;\n\n case CoreResourceOperation.UPDATE_MANY:\n operationResult = await this._doUpdateMany(operation, executionContext, id_or_ids_or_filter as IdsOrFilterType, data, options);\n break;\n\n case CoreResourceOperation.DELETE:\n if(Array.isArray(id_or_ids_or_filter)) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED,\n context: { operationRepositoryPathKey, resourceIdentifier: this.resourceConfiguration.resourceIdentifier, id_or_ids_or_filter } } );\n }\n operationResult = await this._doDelete(operation, executionContext, id_or_ids_or_filter as IdOrIdsOrFilterType, options);\n break;\n\n case CoreResourceOperation.DELETE_MANY:\n const idToDelete = typeof id_or_ids_or_filter === 'string' ? [id_or_ids_or_filter] : id_or_ids_or_filter;\n operationResult = await this._doDeleteMany(operation, executionContext, idToDelete as IdsOrFilterType, options);\n break;\n\n case CoreResourceOperation.LIST:\n // For LIST operation, return paginated format\n const idsToList = typeof id_or_ids_or_filter === 'string' ? [id_or_ids_or_filter] : id_or_ids_or_filter;\n const listResult = await this._doList(operation, executionContext, idsToList as IdsOrFilterType, options);\n operationResult = listResult;\n break;\n\n case CoreResourceOperation.COUNT:\n operationResult = await this._doCount(\n operation,\n executionContext,\n (data?.filter as FilterQuery<any>) ?? {},\n options,\n );\n break;\n\n case CoreResourceOperation.SEARCH:\n operationResult = await this._doSearch(\n operation,\n executionContext,\n data?.query || '',\n (data?.filter as FilterQuery<any>) ?? {},\n {\n ...options,\n searchOptions: (options as { searchOptions?: { fieldsToSearch?: string[]; page?: number; limit?: number; sort?: any; } } | undefined)?.searchOptions ?? {},\n } as RepositoryOptions & { searchOptions: { fieldsToSearch?: string[]; page?: number; limit?: number; sort?: any; } },\n );\n break;\n\n default:\n // Handle custom operations\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { resourceIdentifier: this.resourceConfiguration.resourceIdentifier, operationIdentifier } });\n }\n\n await this._postfixOperation(operation, executionContext, id_or_ids_or_filter, data, options);\n\n return operationResult;\n }\n\n\n\n // ================================\n // Core Public Operations\n // ================================\n\n public async create<T = undefined>(\n executionContext: ExecutionContext<any>,\n data: MainSchemaType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalReturnType<T, TMainSchema>> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.CREATE && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.CREATE } } );\n }\n await this._prefixOperation(operation, executionContext, undefined, data, options);\n const result = await this._doCreate(operation, executionContext, data, options);\n await this._postfixOperation(operation, executionContext, undefined, data, options);\n return result as ConditionalReturnType<T, TMainSchema>;\n }\n\n public async createMany<T = undefined>(\n executionContext: ExecutionContext<any>,\n data: MainSchemaArrayType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalArrayReturnType<T, TMainSchema>> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.CREATE_MANY && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.CREATE_MANY } } );\n }\n await this._prefixOperation(operation, executionContext, undefined, data, options);\n const result = await this._doCreateMany(operation, executionContext, data, options);\n await this._postfixOperation(operation, executionContext, undefined, data, options);\n return result as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n public async read<T = undefined>(\n executionContext: ExecutionContext<any>,\n id_or_filter: IdOrFilterType,\n options?: RepositoryOptions\n ): Promise<ConditionalNullableReturnType<T, TMainSchema>> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.READ && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.READ } } );\n }\n await this._prefixOperation(operation, executionContext, id_or_filter, undefined, options);\n const result = await this._doRead(operation, executionContext, id_or_filter, options);\n await this._postfixOperation(operation, executionContext, id_or_filter, undefined, options);\n return result as ConditionalNullableReturnType<T, TMainSchema>;\n }\n\n /**\n * Repository-internal READ for framework recovery/reconciliation that must\n * not depend on a user-facing default READ operation.\n *\n * The synthetic operation is used only to drive the adapter's core read.\n * `_doRead` still applies contextual scope and retention filtering, while\n * skipping authored prefix/postfix hooks and response projections so the\n * caller receives canonical persisted resource truth.\n */\n /**\n * @see BackendResourceRepository.readUnscopedByKey — the contract carries the reasoning.\n *\n * No `buildContextualFilter`: the caller's filter is the whole confinement, by design. The\n * retention hide is applied ONCE at the registry dispatch point, matching `atomicGuardedMutation`\n * rather than duplicating the predicate here.\n *\n * retention-gate: N/A — applied at `RepositoriesRegistryHandlerBackendService.readUnscopedByKey`.\n */\n public async readUnscopedByKey<T = any>(\n filter: Record<string, unknown>,\n options?: RepositoryOptions,\n ): Promise<T | null> {\n const session = this.getNativeSession(options);\n const document = await this.mongooseModel\n .findOne(filter as FilterQuery<any>, null, session ? { session } : {})\n .exec();\n\n if (!document) return null;\n return (document.toObject ? document.toObject() : document) as T;\n }\n\n public async readForInternalScan<T = undefined>(\n executionContext: ExecutionContext<any>,\n id_or_filter: IdOrFilterType,\n options?: RepositoryOptions,\n ): Promise<ConditionalNullableReturnType<T, TMainSchema>> {\n const syntheticReadOperation = {\n operationIdentifier: CoreResourceOperation.READ,\n variantType: ResourceOperationVariantType.REPOSITORY_ONLY,\n isOperationDefault: true,\n } as unknown as ResourceConfiguration_Operation<\n TCustomOperationEnum,\n TCoreOperationEnum,\n TMainSchema\n >;\n return this._doRead<T>(\n syntheticReadOperation,\n executionContext,\n id_or_filter,\n options,\n );\n }\n\n public async update<T = undefined>(\n executionContext: ExecutionContext<any>,\n id_or_filter: IdOrFilterType,\n data: PartialMainSchemaType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalNullableReturnType<T, TMainSchema>> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.UPDATE && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.UPDATE } } );\n }\n await this._prefixOperation(operation, executionContext, id_or_filter, data, options);\n const result = await this._doUpdate(operation, executionContext, id_or_filter, data, options);\n await this._postfixOperation(operation, executionContext, id_or_filter, data, options);\n return result as ConditionalNullableReturnType<T, TMainSchema>;\n }\n\n public async updateMany<T = undefined>(\n executionContext: ExecutionContext<any>,\n data: PartialMainSchemaType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalArrayReturnType<T, TMainSchema>> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.UPDATE_MANY && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.UPDATE_MANY } } );\n }\n await this._prefixOperation(operation, executionContext, undefined, data, options);\n const result = await this._doUpdateMany(operation, executionContext, undefined, data, options);\n await this._postfixOperation(operation, executionContext, undefined, data, options);\n return result as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n public async delete(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<string> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.DELETE && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.DELETE } } );\n }\n await this._prefixOperation(operation, executionContext, id_or_ids_or_filter, undefined, options);\n const result = await this._doDelete(operation, executionContext, id_or_ids_or_filter, options);\n await this._postfixOperation(operation, executionContext, id_or_ids_or_filter, undefined, options);\n return result;\n }\n\n public async deleteMany(\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<string[]> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.DELETE_MANY && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.DELETE_MANY } } );\n }\n await this._prefixOperation(operation, executionContext, ids_or_filter, undefined, options);\n const result = await this._doDeleteMany(operation, executionContext, ids_or_filter, options);\n await this._postfixOperation(operation, executionContext, ids_or_filter, undefined, options);\n return result;\n }\n\n /**\n * Overloads declared to match what this method ALREADY DOES at runtime.\n *\n * `_doList` returns a paginated envelope when `options.paginated` is set, but the\n * single declared signature said \"array\" — so every caller passing `paginated: true`\n * was handed a wrong type. That went unnoticed because the class was cast through\n * `as any` at construction and never checked against its own contract.\n */\n public async list<T = undefined>(\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<ConditionalArrayReturnType<T, TMainSchema>>;\n public async list<T = undefined>(\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options: RepositoryOptions & { paginated: true; listOptions?: Partial<Resources_PaginationRequest> }\n ): Promise<Resources_PaginatedResult<ConditionalReturnType<T, TMainSchema>>>;\n public async list<T = undefined>(\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<any> {\n const operation = this.findDefaultListOperation();\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { resourceIdentifier: this.resourceConfiguration.resourceIdentifier, operationIdentifier: CoreResourceOperation.LIST, reason: 'no default LIST operation declared on this resource' } } );\n }\n return this._runListWithHooks(operation, executionContext, ids_or_filter, options) as Promise<ConditionalArrayReturnType<T, TMainSchema>>;\n }\n\n /**\n * Repository-internal LIST for FRAMEWORK-managed scans that must work\n * regardless of whether the resource declares a user-facing LIST\n * operation.\n *\n * Two framework-internal callers rely on this:\n * 1. The data-seed engines' idempotency / orphan / rename scans by\n * `__seed.seedKey` (seeded `REPOSITORY_ONLY` singletons such as the\n * M2M webhook config declare only repository-only CREATE/UPDATE).\n * 2. The controller's context-addressed-singleton authorization\n * (`resolveContextAddressedSingletonOperationAuthorizationId`),\n * which lists by the parent FK to resolve the singleton's id and\n * prove uniqueness for READ/UPDATE/DELETE — e.g. per-user singletons\n * like `userProgressionState` / `userGuidanceState` that expose only\n * READ to users, never LIST.\n *\n * In both cases the LIST is framework machinery, NOT a user-facing\n * collection read. Forcing every such resource to also declare a\n * user-facing LIST just to satisfy internal plumbing would push a\n * framework concern onto every resource author; resolving it here keeps\n * the contract in one place.\n *\n * Behaviour:\n * - When a default LIST operation IS declared, it is reused verbatim —\n * identical to {@link list} (same projection + prefix/postfix hooks),\n * so resources that DO expose LIST behave exactly as before.\n * - When NO default LIST operation is declared, a minimal synthetic\n * `REPOSITORY_ONLY` operation drives `_doList` directly (full-document\n * projection, since the synthetic op carries no response/repository\n * DTO) and the user hook pipeline is skipped — an internal scan is\n * not a user-facing operation, so user prefix/postfix hooks (ACL\n * narrowing, validation) must not apply.\n */\n /**\n * Overloads declared to match what this method ALREADY DOES at runtime.\n *\n * `_doList` returns a paginated envelope when `options.paginated` is set, but the\n * single declared signature said \"array\" — so every caller passing `paginated: true`\n * was handed a wrong type. That went unnoticed because the class was cast through\n * `as any` at construction and never checked against its own contract.\n */\n public async listForInternalScan<T = undefined>(\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<ConditionalArrayReturnType<T, TMainSchema>>;\n public async listForInternalScan<T = undefined>(\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options: RepositoryOptions & { paginated: true; listOptions?: Partial<Resources_PaginationRequest> }\n ): Promise<Resources_PaginatedResult<ConditionalReturnType<T, TMainSchema>>>;\n public async listForInternalScan<T = undefined>(\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<any> {\n const declaredListOperation = this.findDefaultListOperation();\n if (declaredListOperation) {\n return this._runListWithHooks(declaredListOperation, executionContext, ids_or_filter, options) as Promise<ConditionalArrayReturnType<T, TMainSchema>>;\n }\n const syntheticListOperation = this.buildSyntheticRepositoryListOperation();\n const result = await this._doList(syntheticListOperation, executionContext, ids_or_filter, options);\n return result as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n private findDefaultListOperation(): ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> | undefined {\n return this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.LIST && op.isOperationDefault === true);\n }\n\n private async _runListWithHooks(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<unknown> {\n await this._prefixOperation(operation, executionContext, ids_or_filter, undefined, options);\n const result = await this._doList(operation, executionContext, ids_or_filter, options);\n await this._postfixOperation(operation, executionContext, ids_or_filter, undefined, options);\n return result;\n }\n\n /**\n * Build a minimal synthetic default `REPOSITORY_ONLY` LIST operation for\n * {@link listForInternalScan} on resources that declare none.\n *\n * This object exists ONLY to drive `_doList`, which reads exactly one\n * field off the operation: the response/repository DTO (for the Mongo\n * projection). With neither DTO present, `_doList` uses a full-document\n * projection — the correct behaviour for a seed scan, which needs `_id`\n * plus arbitrary seeded fields (rename scans read author-declared fields)\n * and the `__seed` metadata it filters on. The synthetic op is NEVER\n * registered in the resource's operation set and is never variant-narrowed\n * by downstream code, so the `as` cast is safe — it carries no other\n * load-bearing fields.\n */\n private buildSyntheticRepositoryListOperation(): ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> {\n return {\n operationIdentifier: CoreResourceOperation.LIST,\n variantType: ResourceOperationVariantType.REPOSITORY_ONLY,\n isOperationDefault: true,\n } as unknown as ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\n }\n\n public async search<T = any>(\n executionContext: ExecutionContext<any>,\n searchQuery: string,\n filter: FilterQuery<any> = {},\n searchOptions: { fieldsToSearch?: string[]; page?: number; limit?: number; sort?: any} = {},\n options?: RepositoryOptions\n ): Promise<Resources_PaginatedResult<T>> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.SEARCH && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.SEARCH } } );\n }\n const searchOptionsWithDefaults = { searchOptions, ...options };\n await this._prefixOperation(operation, executionContext, undefined, { query: searchQuery }, searchOptionsWithDefaults);\n const result = await this._doSearch(operation, executionContext, searchQuery, filter, searchOptionsWithDefaults);\n await this._postfixOperation(operation, executionContext, undefined, { query: searchQuery }, searchOptionsWithDefaults);\n return result;\n }\n\n public supportsOperation(operationIdentifier: string): boolean {\n return this.resourceConfiguration.operations.some(\n op => op.operationIdentifier === operationIdentifier && op.isOperationDefault === true\n );\n }\n\n public async count(\n executionContext: ExecutionContext<any>,\n filter: FilterQuery<any> = {},\n options?: RepositoryOptions\n ): Promise<{ count: number }> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.COUNT && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.COUNT } } );\n }\n await this._prefixOperation(operation, executionContext, undefined, filter, options);\n const result = await this._doCount(operation, executionContext, filter, options);\n await this._postfixOperation(operation, executionContext, undefined, filter, options);\n return result;\n }\n\n /**\n * Aggregate a numeric field across documents matching the filter.\n * Framework infrastructure method for feature limit enforcement.\n *\n * Uses MongoDB aggregation pipeline: $match (with buildContextualFilter) + $group.\n * Handles null/undefined field values via $ifNull.\n * Does NOT require a COUNT operation to be configured (not API-facing).\n *\n * @param executionContext - Current execution context (used for scope filtering)\n * @param filter - Additional filter criteria (scope is added automatically by buildContextualFilter)\n * @param field - The document field to aggregate\n * @param operation - The aggregation operation (SUM, AVG, MAX)\n * @returns The aggregated numeric result (0 if no matching documents)\n */\n public async aggregateField(\n executionContext: ExecutionContext<any>,\n filter: FilterQuery<any>,\n field: string,\n operation: string,\n ): Promise<number> {\n const contextualFilter = this.buildContextualFilter(executionContext, filter, CoreResourceOperation.READ);\n\n // Map operation string to MongoDB aggregation operator\n let mongoOp: string;\n switch (operation) {\n case 'SUM':\n mongoOp = '$sum';\n break;\n case 'AVG':\n mongoOp = '$avg';\n break;\n case 'MAX':\n mongoOp = '$max';\n break;\n default:\n mongoOp = '$sum';\n }\n\n const pipeline = [\n { $match: contextualFilter },\n {\n $group: {\n _id: null,\n result: { [mongoOp]: { $ifNull: [`$${field}`, 0] } },\n },\n },\n ];\n\n this.logDebug('Aggregating field', { field, operation, filter: contextualFilter });\n\n const results = await this.mongooseModel.aggregate(pipeline).exec();\n const value = results.length > 0 ? (results[0].result ?? 0) : 0;\n\n this.logDebug('Aggregation result', { field, operation, value });\n return value;\n }\n\n // ================================\n // Business-Key Helpers (data-seeding)\n // ================================\n //\n // Spec refs (see also each method's JSDoc):\n // - data-seeding-as-first-class-feature plan §3.7 (atomic upsert + ledger)\n // - Phase 2 plan §5 (BackendResourceRepository contract)\n // - Decision P2-B (PostgreSQL sibling kept at parity)\n // - Audit findings R-2 / R-4 / R-6 / R-10 (this comment + per-method docs)\n\n /**\n * Find a single row whose business-key fields match `businessKeyShape`,\n * scoped by the current execution context (orgId, userId, …).\n *\n * Bypasses the operation-resolution / DTO-validation pipeline because this\n * is **infrastructure** used by the data-seeding subsystem (system writes\n * are trusted; the seed dispatcher validates payloads against `mainSchema`\n * before calling here). Context-scoped filtering still applies via\n * `buildContextualFilter`, so a seed declared with org-scoped business\n * keys (e.g. `[organizationId, templateKey]`) cannot leak rows across\n * organizations even if the caller forgot to pass `organizationId` in\n * the shape — the contextual filter would refuse to match.\n *\n * Returns `null` when no matching row exists.\n *\n * @throws WildoError_Backend(INTERNAL) if the schema declares no business\n * key (configuration error — see `resolveBusinessKeyFieldNames`).\n */\n public async findByBusinessKey<T = undefined>(\n executionContext: ExecutionContext<any>,\n businessKeyShape: Record<string, unknown>,\n options?: RepositoryOptions,\n ): Promise<ConditionalNullableReturnType<T, TMainSchema>> {\n const baseFilter = this._tryBuildBusinessKeyFilter(executionContext, businessKeyShape);\n const filter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.READ, options);\n\n const session = this.getNativeSession(options);\n this.logDebug('findByBusinessKey', { filter, hasTransaction: !!session });\n\n const document = await this.mongooseModel\n .findOne(filter, undefined, session ? { session } : undefined)\n .exec();\n\n return this.transformDocumentToResponse<T>(document, CoreResourceOperation.READ);\n }\n\n /**\n * ADAPTER-NEUTRAL atomic counter primitive (MongoDB arm) — add `delta` to one numeric column on\n * the single row matching `filter`, optionally `$set`ting other fields in the SAME statement, and\n * return the row as it stands AFTER the write.\n *\n * A shorthand over {@link atomicGuardedMutation}. Both replaced a raw-MongoDB\n * `atomicConditionalUpdate` (since retired) whose contract was arbitrary `$`-operators, which no\n * SQL adapter can honour — so a counter built on it silently stopped working on PostgreSQL.\n * \"Increment a field under a guard\" is something every adapter can implement truthfully, so\n * read-modify-write counters (token budgets, usage tallies, progression counts) stay correct and\n * race-free on both.\n *\n * Atomicity comes from the single `findOneAndUpdate` round-trip: concurrent callers each apply\n * their own delta; none reads-then-writes a stale value.\n *\n * @param filter - Pre-built filter, INCLUDING any guard conditions. Callers reach this through the\n * registry, which applies the retention-hide predicate first (a retained row is immutable).\n * @returns The updated row, or `null` when the filter matched nothing (guard failed / not found).\n */\n public async atomicIncrementField<T = any>(\n filter: Record<string, unknown>,\n field: string,\n delta: number,\n setFields?: Record<string, unknown>,\n options?: RepositoryOptions,\n ): Promise<T | null> {\n // `delta === 0` omits the increment entirely, degrading the call to a GUARDED SET. That is not a\n // micro-optimisation: a counter reset (e.g. rolling a budget period) must overwrite the field\n // rather than add to it, and MongoDB rejects an update whose `$inc` and `$set` touch the same\n // path (\"would create a conflict\"). One primitive therefore covers both add-to and reset-to.\n return this.atomicGuardedMutation<T>(\n filter,\n { ...(delta === 0 ? {} : { increment: { [field]: delta } }), set: setFields },\n options,\n );\n }\n\n /**\n * ADAPTER-NEUTRAL guarded set-and-clear (MongoDB arm) — set fields and/or CLEAR fields on the\n * single row matching `filter`, returning the row as it stands AFTER the write.\n *\n * **Why this exists.** Clearing a field had no expression on the repository contract at all. The\n * only way to do it was the raw-MongoDB `atomicConditionalUpdate` (since retired), which reached\n * for `mongooseModel` and threw on any other adapter — so every clear was also, silently, a\n * MongoDB pin. The file-cleanup batch is the case that\n * forced this: it clears stale link metadata off timed-out and malformed rows, and without a\n * neutral primitive a PostgreSQL-backed FILES resource would accept writes and then strand every\n * row that batch exists to normalize, failing in a background job far from the configuration that\n * caused it.\n *\n * Atomicity comes from the single `findOneAndUpdate` round-trip, and the caller's guard\n * conditions travel in `filter`, so this is a genuine compare-and-set on both adapters.\n *\n * **Scope, stated so it is not mistaken for more.** This is the GUARDED path. The ordinary\n * `update()` path still cannot clear a field (mongoose ignores `undefined`, and the framework\n * repository issues `$set` only) — see `m2m-webhook-delivery-log.repository.ts`, which documents\n * living with a stale `nextAttemptAt` for exactly that reason. That surface is a separate,\n * still-open gap; this primitive does not close it.\n *\n * @param filter - Pre-built filter INCLUDING guard conditions. Callers reach this through the\n * registry, which applies the retention-hide predicate first (a retained row is immutable).\n * @param clearFields - Field names to remove. Compiles to `$unset` here and to `SET col = NULL`\n * on PostgreSQL, which the `$exists` translation makes observationally identical.\n * @returns The updated row, or `null` when the filter matched nothing (guard failed / not found).\n */\n public async atomicConditionalSet<T = any>(\n filter: Record<string, unknown>,\n setFields: Record<string, unknown> | undefined,\n clearFields: readonly string[] | undefined,\n options?: RepositoryOptions,\n ): Promise<T | null> {\n return this.atomicGuardedMutation<T>(filter, { set: setFields, clear: clearFields }, options);\n }\n\n /**\n * INSERT one already-built document, below the operation tier.\n *\n * The document is CAST through the model's schema (`Model.castObject`) and then written through\n * the driver collection. Both halves are deliberate, and the split is what fixes issue #71:\n *\n * - **Cast, because this tier's other members cast.** `readUnscopedByKey`, `updateManyByRawFilter`,\n * `countByRawFilter` and the guarded mutations all go through the mongoose Model, which casts\n * FILTERS to the schema's types (`isForeignKey` paths are `Schema.Types.ObjectId`). An uncast\n * insert therefore stored a string where every sibling queries an ObjectId, and **a row written\n * by this tier was not reliably findable by this tier**: `revokeTokensByRelatedId` matched 0\n * rows that existed, and a model read dropped the uncastable stored value (`userId: undefined`)\n * without a sound. De-casting the five model members instead was rejected because they also\n * serve rows written by the NORMAL model paths — `bulkUpdateForInfrastructure`'s billing caller\n * filters `_id: { $in: … }` on ordinary usage-record rows, where the cast is what makes the\n * match, and a miss there is that caller's documented DUPLICATE-CHARGE condition. This also\n * mirrors the PostgreSQL arm, which routes the same insert through `toSqlWriteRow` — \"the same\n * projection every other write here uses\" — for exactly this reason.\n * - **Driver collection, because the callers build a COMPLETE document** — their own `_id`, their\n * own `createdAt`/`updatedAt` — and routing through a model WRITE would layer schema defaults\n * and the `timestamps` hook over a document that is already final. `castObject` does neither:\n * it applies the schema's type CASTS only — no defaults, no timestamps, no validation — so the\n * \"already final\" contract survives while the representation stops disagreeing.\n *\n * An uncastable value (a non-ObjectId string on an `isForeignKey` path) now throws at the WRITE,\n * loudly, exactly as the same value would on an ordinary model create — instead of storing a row\n * that no cast filter can ever match, which was this defect's silent form.\n *\n * Returns the CALLER's document, not the cast one: the cast document carries ObjectId instances,\n * and this tier's read members hand those back as strings (the schema's `toObject` transform), so\n * the input is already the round-trip shape — matching the PostgreSQL arm's string-typed return.\n *\n * retention-gate: N/A — INSERTs a brand-new row, so there is no existing row for a hide to\n * protect. A retained row is reached only through a filter, and this statement carries none.\n */\n public async insertRawDocument<T = any>(document: Record<string, unknown>, options?: RepositoryOptions): Promise<T> {\n const session = this.getNativeSession(options);\n\n /**\n * CAST THROUGH THE SCHEMA before writing, exactly as the PostgreSQL arm does with\n * `toSqlWriteRow`. A caller on this tier hands over a DOMAIN document; converting it to the\n * adapter's storage representation is this adapter's business, not the caller's.\n *\n * Without this, the raw driver stored the domain value verbatim while every OTHER method here\n * queries through the Mongoose Model, which CASTS. The two disagreed for any field whose\n * declared Zod type this adapter overrides — notably `z.string().isForeignKey()`, which the\n * schema convertor maps to `Schema.Types.ObjectId`. A row written by this tier was then\n * unmatchable by this tier: `revokeTokensByRelatedId` filtered on `relatedId` and got 0 for a\n * row that existed, silently, with a perfectly well-formed id. Measured on one row, one filter:\n * raw driver matched 1, the Model matched 0.\n *\n * `castObject` applies schema casting ONLY — no defaults, no validation — which is what keeps\n * this an insert of an already-built document rather than a model create. It THROWS on a value\n * the schema cannot represent, and that is deliberate: the alternative is what this replaced,\n * a write that appears to succeed and produces a row nothing can find.\n *\n * The RETURN stays the caller's domain document, matching the PostgreSQL arm, which returns a\n * domain-shaped row. Only the stored bytes change.\n */\n let storageDocument: Record<string, unknown>;\n try {\n storageDocument = this.mongooseModel.castObject(document as any, { ignoreCastErrors: false }) as Record<string, unknown>;\n } catch (error) {\n // Classified, adapter-neutral refusal — the same argument as the E11000→CONFLICT translation\n // below: a caller must not need adapter-specific detection to understand a refusal. Field\n // NAMES only, never values — this tier's first caller writes secrets (consumable tokens), and\n // the messages mongoose attaches carry the rejected values verbatim.\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n context: {\n reason: 'infrastructure_insert_document_not_castable',\n resourceType: (this.resourceConfiguration as { resourceType?: string })?.resourceType,\n fields: Object.keys((error as { errors?: Record<string, unknown> })?.errors ?? {}),\n },\n });\n }\n\n /**\n * An UNKNOWN top-level key — one the model has no path for — is refused by name, never silently\n * dropped. The strict-schema cast strips such keys, and even a preserved one would be invisible:\n * the model-side reads on this tier hydrate schema paths only. Both silences are the defect\n * class this method exists to remove.\n *\n * TOP LEVEL only, stated rather than implied: a key nested inside a cast subdocument is the\n * subdocument schema's business, and this predicate deliberately does not walk into it.\n *\n * Keys holding `undefined` OR `null` are exempt — the cast legitimately omits both, and their\n * ABSENCE is strictly better than what the old raw insert stored: an `.optional()` schema field\n * accepts a missing key on read and REJECTS a literal `null`, so persisting the null would\n * produce a row the strict re-parse cannot serve (the same trap the field-clearing contract\n * documents for updates). Flagging them as \"unknown\" would also be a wrong diagnosis — the\n * model knows the field perfectly well; it is the VALUE the cast declines to carry.\n */\n const unknownKeys = Object.keys(document).filter(\n (key) => document[key] !== undefined && document[key] !== null && !(key in storageDocument),\n );\n if (unknownKeys.length > 0) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n context: {\n reason: 'infrastructure_insert_unknown_fields',\n resourceType: (this.resourceConfiguration as { resourceType?: string })?.resourceType,\n unknownKeys,\n },\n });\n }\n\n try {\n await this.mongooseModel.collection.insertOne(storageDocument as any, session ? { session } : {});\n } catch (error) {\n // Translated to the CONFLICT contract, exactly as the PostgreSQL arm does. Without this the\n // two arms would report a duplicate DIFFERENTLY — a raw `E11000` here versus a classified\n // CONFLICT there — and every caller would need adapter-specific detection, which is precisely\n // what this tier exists to remove. `handleMongoDBError` returns non-duplicate errors untouched.\n throw this.handleMongoDBError(error);\n }\n return document as T;\n }\n\n /**\n * READ many rows matching an already-built filter, below the operation tier.\n *\n * The multi-row counterpart of `readUnscopedByKey`, and it goes through the SAME mongoose door —\n * `Model.find` with a per-document `toObject()` — for the same issue-#71 reason `insertRawDocument`\n * now casts: this tier's filters must mean one thing across all of its members. The previous raw\n * `collection.find` compared a string filter against the ObjectId values the schema stores on\n * `isForeignKey` paths, so this member could not find rows every model-side sibling could — and\n * could not find what a cast `insertRawDocument` writes.\n *\n * `toObject()` (not `.lean()`) keeps the return the tier's documented shape: plain stored\n * documents with the schema's ObjectId→string transform applied — byte-for-byte what\n * `readUnscopedByKey` returns for one row, and string-typed like the PostgreSQL arm's\n * `transformPersistenceRow` output.\n *\n * retention-gate: N/A — the hide is applied ONCE by the caller on this tier, matching every\n * sibling here.\n */\n public async findManyByRawFilter<T = any>(filter: Record<string, unknown>, options?: RepositoryOptions): Promise<T[]> {\n const session = this.getNativeSession(options);\n const documents = await this.mongooseModel\n .find(filter as FilterQuery<any>, null, session ? { session } : {})\n .exec();\n return documents.map((document) => (document.toObject ? document.toObject() : document)) as T[];\n }\n\n /**\n * Compile the adapter-neutral guarded mutation into a MongoDB update expression.\n *\n * Extracted from `atomicGuardedMutation` so the SINGLE-row and MULTI-row guarded writes cannot\n * drift: the descriptor's whole rationale is that \"each adapter now has a single place where\n * guarded-write semantics are decided, rather than three places that must agree\", and two inline\n * copies of this compilation would have reinstated exactly that.\n *\n * ## Why this `$set` does not carry the field-clearing partition\n *\n * The extraction MOVED the statement here, so the waiver that used to sit on `atomicGuardedMutation`\n * had to move with it. It is restated rather than copied, because the original was one asserted\n * sentence and the reasoning below was measured (2026-08-27):\n *\n * - **This vocabulary already HAS a clear channel.** `RepositoryGuardedMutation` splits `set`\n * (\"paths to assign\") from `clear` (\"paths to remove\"). A `null` in `set` is therefore an\n * explicit instruction to STORE null — not the JSON-Merge-Patch \"this field has no value\" that\n * `partitionNullClearedFields` exists to interpret. Partitioning here would give the descriptor a\n * SECOND, implicit removal channel and collapse the distinction `clear` exists to express.\n * - **No wire payload can reach this statement.** Both doors — the registry's\n * `atomicGuardedMutation` and `bulkUpdateForInfrastructure`, plus the `atomicIncrementField` /\n * `atomicConditionalSet` shorthands that delegate to them — are `@internal` and sit BELOW the\n * operation tier, so no validated UPDATE DTO (the only thing that carries a caller's null)\n * arrives. Enumerated rather than assumed: 12 descriptors across 7 engine files (consumable\n * tokens, lifecycle evaluator, files cleanup, credit pool, promotions, usage metering, A2A token\n * budget). Every `set` value is a constant, a `new Date()`, an enum member, a number, a boolean\n * or an array; NONE is null, and the two call sites that genuinely remove fields — the\n * file-cleanup batch and every token revocation — already use `clear`.\n * - **The partition is FIELD-keyed; this vocabulary is PATH-keyed.** `partitionNullClearedFields`\n * resolves each key through `getObjectLikeFieldSchema`, a top-level shape lookup with no dotted\n * traversal, while a guarded mutation routinely addresses `stageHistory.1.exitedAt` or\n * `engagement.operationsSinceActivation`. A null at such a path would miss the schema, land in\n * `unresolvedFieldNames`, and be `$unset` on the safe-direction fallback with a warning on every\n * write — while the PostgreSQL arm compiles the same null to a jsonb null that leaves the key\n * PRESENT. That is a NEW nested-path divergence, and it is the one the PostgreSQL `clear` branch\n * already refuses to create (\"assigning JSON null would leave the key PRESENT and make\n * `{ $exists: false }` disagree across adapters\").\n *\n * **The residual, stated rather than hidden.** Nothing MECHANICALLY stops a future caller writing\n * `set: { someOptionalField: null }`; on this adapter that stores a literal null which a later\n * ordinary READ cannot parse. Unbypassable is genuinely unavailable at this statement — a refusal\n * would need the same schema lookup the third bullet shows cannot answer for a path, and the two\n * shorthand doors bypass the descriptor-level expressibility check where such a rule would belong.\n * Tracked as owed work in issue #76 rather than absorbed here; the `clear` channel is the portable\n * answer and `RepositoryGuardedMutation.set` now says so at the surface every caller reads.\n */\n // field-clearing: N/A — `set` is an explicit ASSIGN channel and `clear` is the removal channel, so\n // no caller-supplied clear-instruction null reaches this statement (12 descriptors enumerated), and\n // the partition is field-keyed where this vocabulary is path-keyed. Full reasoning in the JSDoc above.\n private compileGuardedMutationToMongoUpdate(mutation: RepositoryGuardedMutation): Record<string, unknown> {\n const update: Record<string, unknown> = {};\n\n if (mutation.set && Object.keys(mutation.set).length > 0) update.$set = mutation.set;\n if (mutation.clear && mutation.clear.length > 0) {\n update.$unset = Object.fromEntries(mutation.clear.map((fieldName) => [fieldName, 1]));\n }\n if (mutation.increment && Object.keys(mutation.increment).length > 0) update.$inc = mutation.increment;\n\n for (const addition of mutation.arrayAdditions ?? []) {\n if (addition.values.length === 0) continue;\n if (addition.distinctOnly) {\n // The registry's expressibility rule has already refused `distinctOnly` combined with HEAD\n // placement or `maxLength`, so `$addToSet` is reachable only in the form it can honour.\n const addToSet = (update.$addToSet ??= {}) as Record<string, unknown>;\n addToSet[addition.path] = { $each: [...addition.values] };\n continue;\n }\n const push = (update.$push ??= {}) as Record<string, unknown>;\n push[addition.path] = {\n $each: [...addition.values],\n ...(addition.placement === RepositoryArrayAdditionPlacement.HEAD ? { $position: 0 } : {}),\n ...(addition.maxLength === undefined\n ? {}\n : { $slice: addition.placement === RepositoryArrayAdditionPlacement.HEAD ? addition.maxLength : -addition.maxLength }),\n };\n }\n\n return update;\n }\n\n /**\n * The MULTI-row guarded write: apply one mutation to EVERY row matching the filter, returning how\n * many were modified.\n *\n * retention-gate: N/A — the hide is applied ONCE by the caller\n * (`RepositoriesRegistryHandlerBackendService.bulkUpdateForInfrastructure`), matching every sibling\n * on this tier. A retained row must stay immutable, and excluding it there keeps the predicate in\n * one place.\n *\n * **Why the count is returned rather than a boolean.** Its billing caller reports usage to a\n * provider and then marks the records as reported; a PARTIAL marking is a duplicate-charge\n * condition, because whatever stayed unmarked is selected again by the next sweep. The caller\n * compares `modifiedCount` against the group size for exactly that reason, so a primitive that\n * flattened this to success/failure would make the condition unfalsifiable.\n */\n public async updateManyByRawFilter(\n filter: Record<string, unknown>,\n mutation: RepositoryGuardedMutation,\n options?: RepositoryOptions,\n ): Promise<number> {\n // NO-OP PARITY with the PostgreSQL arm and with the single-row path: an empty descriptor issues\n // no statement, rather than an empty update mongoose would still use to bump `updatedAt`.\n if (!guardedMutationHasWork(mutation)) return 0;\n\n const session = this.getNativeSession(options);\n const update = this.compileGuardedMutationToMongoUpdate(mutation);\n const result = await this.mongooseModel\n .updateMany(filter, update, { ...(session ? { session } : {}) })\n .exec();\n return result.modifiedCount ?? 0;\n }\n\n /**\n * Count rows matching an ALREADY-BUILT filter, with no operation and no authorization.\n *\n * retention-gate: N/A — the hide is applied ONCE by the caller\n * (`RepositoriesRegistryHandlerBackendService.countDocumentsForInfrastructure` passes the filter\n * through `applyRetentionHideToRawFilter`). Applying it a second time here would put the predicate\n * in two places, which is what the retention authority exists to prevent.\n *\n * **Why this exists.** The handler's infrastructure count used to reach\n * `(repository as any).mongooseModel` directly. That made a method with a general name work on ONE\n * adapter: on a PostgreSQL-backed resource it threw \"No underlying database model found\", so\n * field-uniqueness validation — its main caller — was broken for every such resource. Delegating to\n * a primitive each adapter implements is what makes the family's name true.\n *\n * Deliberately NOT the public `count(...)`: that requires a DECLARED `COUNT` operation and an\n * execution context, and an infrastructure caller has neither by design.\n */\n public async countByRawFilter(filter: Record<string, unknown>, options?: RepositoryOptions): Promise<number> {\n const session = this.getNativeSession(options);\n const query = this.mongooseModel.countDocuments(filter);\n if (session) query.session(session);\n return query.exec();\n }\n\n /**\n * The MongoDB update document for an ordinary versioned write, honouring the field-CLEARING\n * contract.\n *\n * Every ordinary update on this adapter goes through here — the single write, the CRDT retry\n * write, and the bulk write — because the contract is only real if it holds at all three. Issuing\n * a bare `$set` at any one of them would persist a literal `null` into a field whose schema\n * rejects null, so the write would succeed and the row would then be unreadable (`internalDto`\n * validates the after-image, and an `.optional()` field accepts absence but not null).\n *\n * `partitionNullClearedFields` owns the decision of WHICH nulls are clears; this method only\n * expresses it in MongoDB's vocabulary. `$set` is omitted entirely when nothing remains to write,\n * because MongoDB rejects an empty `$set` — reachable when a caller's only change is to clear\n * fields and no user-tracking field applies.\n *\n * This is the ordinary-path counterpart of `atomicGuardedMutation`'s `clear` channel, which\n * predates it and remains the door for explicit compare-and-swap clears.\n */\n private buildVersionedUpdateDocument(data: Record<string, unknown>): Record<string, unknown> {\n const { retainedData, clearedFieldNames, unresolvedFieldNames } = partitionNullClearedFields(\n data,\n this.resourceConfiguration.mainSchema,\n );\n\n if (unresolvedFieldNames.length > 0) {\n // The partition's safe-direction fallback fired: it cleared a field whose declaration it could\n // not find. Never an error — absence parses against every optional declaration — but it means\n // an authored `.nullish()` null could have been converted to an absence without anyone\n // knowing, so it is reported rather than assumed unreachable.\n this.logger.warn('Field-clearing partition could not resolve a field on the main schema', {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n unresolvedFieldNames,\n });\n }\n\n const updateDocument: Record<string, unknown> = { $inc: { _version_db_doc: 1 } };\n if (Object.keys(retainedData).length > 0) updateDocument.$set = retainedData;\n if (clearedFieldNames.length > 0) {\n updateDocument.$unset = Object.fromEntries(clearedFieldNames.map((fieldName) => [fieldName, 1]));\n }\n\n return updateDocument;\n }\n\n /**\n * ADAPTER-NEUTRAL guarded mutation (MongoDB arm) — the ONE compiler both primitives above are\n * shorthands over. See `RepositoryGuardedMutation` for the vocabulary and why it is a descriptor\n * rather than a third narrow primitive.\n *\n * Every part compiles to a native operator in a SINGLE `findOneAndUpdate`, so the caller's guard\n * conditions (which travel in `filter`) make this a genuine compare-and-set, and the row is never\n * observable half-mutated.\n *\n * `$slice`'s SIGN carries the placement: positive keeps the FIRST n elements, negative the LAST n.\n * Pairing it with the addition's own end is what makes `maxLength` mean \"keep the values nearest\n * `placement`\" — a bounded most-recent-first history keeps the newest precisely because the newest\n * were prepended.\n *\n * retention-gate: N/A — the hide is applied ONCE at the registry dispatch point\n * (`RepositoriesRegistryHandlerBackendService.atomicGuardedMutation` passes the caller's filter\n * through `applyRetentionHideToRawFilter`), which is the only route services take. Applying it a\n * second time here would put the predicate in two places, which is what the retention authority\n * exists to prevent. NOTE the residual this leaves: the method is public on the repository\n * contract, so app code holding a repository handle could call it directly and skip the hide —\n * a convention, not a mechanism.\n */\n // The field-clearing answer for this primitive now lives on `compileGuardedMutationToMongoUpdate`,\n // which owns the `$set` this method used to issue inline. Kept as a pointer rather than a second\n // copy: a waiver on a method that no longer carries the statement is a claim the guard cannot check.\n public async atomicGuardedMutation<T = any>(\n filter: Record<string, unknown>,\n mutation: RepositoryGuardedMutation,\n options?: RepositoryOptions,\n ): Promise<T | null> {\n // NO-OP PARITY with the PostgreSQL arm: issue no write at all rather than an empty update,\n // which mongoose would still use to bump `updatedAt`.\n if (!guardedMutationHasWork(mutation)) return null;\n\n const session = this.getNativeSession(options);\n const update = this.compileGuardedMutationToMongoUpdate(mutation);\n\n const document = await this.mongooseModel\n .findOneAndUpdate(filter, update, { returnDocument: 'after', ...(session ? { session } : {}) })\n .exec();\n\n if (!document) return null;\n return (document.toObject ? document.toObject() : document) as T;\n }\n\n /**\n * Find every row whose business-key matches one of the provided shapes,\n * scoped by the current execution context.\n *\n * Compiled into a single round-trip:\n * - `[]` returns immediately with no DB call;\n * - a single shape returns the bare per-shape filter (no `$or` wrapper)\n * so Mongo can use the most selective index directly;\n * - 2+ shapes are wrapped in a `$or`-disjunction (one branch per shape).\n *\n * The dispatcher uses this in `mode: SYNC` (Phase 4) to load every\n * existing seed-managed row for diff computation. See R-4 in the Phase 2\n * audit for the JSDoc/code alignment fix.\n */\n public async findManyByBusinessKeys<T = undefined>(\n executionContext: ExecutionContext<any>,\n businessKeyShapes: Array<Record<string, unknown>>,\n options?: RepositoryOptions,\n ): Promise<ConditionalArrayReturnType<T, TMainSchema>> {\n if (businessKeyShapes.length === 0) {\n return [] as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n const orBranches = businessKeyShapes.map((shape) =>\n this._tryBuildBusinessKeyFilter(executionContext, shape),\n );\n const baseFilter: FilterQuery<any> = orBranches.length === 1\n ? orBranches[0]\n : { $or: orBranches };\n\n const filter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.READ, options);\n\n const session = this.getNativeSession(options);\n this.logDebug('findManyByBusinessKeys', { count: businessKeyShapes.length, hasTransaction: !!session });\n\n const documents = await this.mongooseModel\n .find(filter, undefined, session ? { session } : undefined)\n .exec();\n\n return documents.map((doc) =>\n this.transformDocumentToResponse<T>(doc, CoreResourceOperation.LIST),\n ) as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n /**\n * Insert-or-update a row by its business key in a single atomic Mongo\n * `findOneAndUpdate({ upsert: true })` call.\n *\n * Spec refs: data-seeding-as-first-class-feature plan §3.7 (atomic\n * upsert + ledger), §5 (Phase 2 repository contract), and decision\n * P2-B (PG sibling parity). See `business-key-resolver.shared.utils.ts`\n * for the business-key resolution contract this method consumes.\n *\n * What gets written, atomically:\n * - The full `payload` (under `$set`) — caller must have already enriched\n * it with context fields (orgId, userId) and validated it against\n * `mainSchema`.\n * - The `__seed` ledger (under `$set`) — see\n * `DATA_SEED_ROW_METADATA_FIELD_KEY` in\n * `@wildo-ai/saas-backend-lib/src/data-seeding/models/`. Writing data\n * + ledger in the same `$set` is the whole reason `__seed` is nested\n * on the row (avoids \"row at v3, ledger still at v2\" partial states).\n * - The business-key fields themselves (under `$setOnInsert`) — guarantees\n * the freshly-inserted row carries the identity even if the caller\n * omitted those fields from `payload` (defensive).\n * - `_version_db_doc` is bumped via `$inc` so optimistic concurrency\n * keeps working on subsequent non-upsert writes (parity with the PG\n * sibling — see `postgresql-resource-repository.backend.service.ts`\n * `upsertByBusinessKey` and audit finding R-10).\n *\n * Returns `{ inserted, row }`:\n * - `inserted: true` iff this call created the row (Mongo upsert path).\n * - `inserted: false` iff this call updated a pre-existing row.\n * - `row` is the post-write document (always non-null because upsert\n * guarantees a row exists at return).\n *\n * @throws WildoError_Backend on Mongo write failure (E11000 etc., wrapped\n * by `handleMongoDBError`).\n */\n // field-clearing: N/A — the payload is validated against the CREATE DTO, which carries no nullable\n // wrapper, so a caller-supplied null is rejected before it can reach this `$set`.\n public async upsertByBusinessKey<T = undefined>(\n executionContext: ExecutionContext<any>,\n businessKeyShape: Record<string, unknown>,\n payload: Record<string, unknown>,\n seedMetadata: DataSeedRowMetadata,\n options?: RepositoryOptions,\n ): Promise<{ inserted: boolean; row: ConditionalReturnType<T, TMainSchema> }> {\n const businessKeyFilter = this._tryBuildBusinessKeyFilter(executionContext, businessKeyShape);\n const filter = this.buildContextualFilter(executionContext, businessKeyFilter, CoreResourceOperation.UPDATE, options);\n\n // WS-C: this upsert can INSERT, so it is governed by the row-creating rule. In practice seeding\n // runs under an internal system context, which narrowing exempts — the guard is here so that\n // coverage of the write surface is a PROPERTY of the chokepoint set rather than a consequence of\n // who happens to call it today.\n await this.assertOrganizationUnitWriteWithinGrant(payload, CoreResourceOperation.CREATE, executionContext);\n\n // Apply user-tracking on the same payload the caller validated. Anonymous\n // contexts simply skip the createdBy/updatedBy assignment (addUserTracking\n // is a no-op when initiatorIds.userId is missing).\n const trackedPayload = this.addUserTracking({ ...payload }, executionContext, CoreResourceOperation.UPDATE);\n\n // Coverage of the create-time write surface is a PROPERTY of the chokepoint set (see the org-unit\n // grant note above), not of who calls it today. An upsert that INSERTS is governed by the same\n // referential / cross-field rules; the effective inserted row is the tracked payload plus the\n // `$setOnInsert` business key. In practice seeding runs under an exempt internal context, so this\n // returns immediately — but a future non-exempt upsert-create inherits the guard for free.\n await assertCreateWriteIntegrity(\n this.writeIntegrityDeps,\n { ...businessKeyShape, ...trackedPayload },\n CoreResourceOperation.CREATE,\n seedMetadata.seedKey,\n executionContext,\n options,\n );\n\n const session = this.getNativeSession(options);\n const mongooseOpts: any = {\n upsert: true,\n // `returnDocument: 'after'` replaces the deprecated `new: true` (Mongoose maps\n // them identically — return the post-update document).\n returnDocument: 'after',\n includeResultMetadata: true,\n setDefaultsOnInsert: true,\n };\n if (session) {\n mongooseOpts.session = session;\n }\n\n this.logDebug('upsertByBusinessKey', {\n filter,\n hasTransaction: !!session,\n seedKey: seedMetadata.seedKey,\n seedVersion: seedMetadata.seedVersion,\n });\n\n let result: any;\n try {\n result = await this.mongooseModel.findOneAndUpdate(\n filter,\n {\n $set: {\n ...trackedPayload,\n [DATA_SEED_ROW_METADATA_FIELD_KEY]: seedMetadata,\n },\n $setOnInsert: { ...businessKeyShape },\n $inc: { _version_db_doc: 1 },\n },\n mongooseOpts,\n );\n } catch (error) {\n this.logDebug('upsertByBusinessKey failed', {\n error: describeCaughtError(error),\n filter,\n hasTransaction: !!session,\n });\n throw this.handleMongoDBError(error, executionContext);\n }\n\n // With includeResultMetadata: true, mongoose returns\n // { value: <doc>, lastErrorObject: { upserted?, updatedExisting }, ok: 1 }\n // updatedExisting === false on the insert path.\n const document = result?.value ?? null;\n const inserted = result?.lastErrorObject?.updatedExisting === false;\n\n const row = this.transformDocumentToResponse<T>(document, CoreResourceOperation.UPDATE) as ConditionalReturnType<T, TMainSchema>;\n return { inserted, row };\n }\n\n /**\n * Insert-or-update a singleton row by an explicit filter in one atomic Mongo\n * `findOneAndUpdate({ upsert: true })` call, without stamping `__seed`.\n *\n * This is intentionally separate from `upsertByBusinessKey`: data-seeding\n * owns `__seed`, while framework singleton materializers such as scope feature\n * ledgers need the same atomic persistence shape for normal resource writes.\n * The filter is still passed through contextual scoping unless callers opt out\n * through `RepositoryOptions`, matching the rest of the repository surface.\n */\n // field-clearing: N/A — CREATE-DTO validated, as `upsertByBusinessKey` above.\n public async upsertByFilter<T = undefined>(\n executionContext: ExecutionContext<any>,\n filterShape: Record<string, unknown>,\n payload: Record<string, unknown>,\n options?: RepositoryOptions,\n ): Promise<{ inserted: boolean; row: ConditionalReturnType<T, TMainSchema> }> {\n const isConcreteSingletonFilterValue = (value: unknown): boolean => {\n if (value === undefined || value === null) return false;\n if (typeof value === 'string') return value.length > 0;\n if (typeof value === 'number') return Number.isFinite(value);\n if (typeof value === 'boolean') return true;\n if (value instanceof Date) return !Number.isNaN(value.getTime());\n if (value instanceof Types.ObjectId) return true;\n return false;\n };\n const invalidFilterEntries = Object.entries(filterShape).filter(([, value]) =>\n !isConcreteSingletonFilterValue(value)\n );\n if (Object.keys(filterShape).length === 0 || invalidFilterEntries.length > 0) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n context: {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n message: 'upsertByFilter requires a non-empty filter with concrete singleton key values.',\n invalidFilterFields: invalidFilterEntries.map(([key]) => key),\n },\n });\n }\n\n const filter = this.buildContextualFilter(executionContext, filterShape as FilterQuery<any>, CoreResourceOperation.UPDATE, options);\n\n const cleanedPayload = this.resourceOperationHelper.cleanInputData(payload, CoreResourceOperation.CREATE);\n const validatedPayload = this.repositoriesRegistry.validateRequestData(\n cleanedPayload,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n CoreResourceOperation.CREATE,\n options,\n );\n const enrichedPayload = this.resourceOperationHelper.enrichDataWithContext(\n validatedPayload,\n executionContext,\n this.resourceConfiguration.mainSchema,\n this.resourceConfiguration.resourceFieldIdentifier,\n this.resourceConfiguration,\n CoreResourceOperation.CREATE,\n options,\n );\n\n // WS-C: an upsert can INSERT, so it is governed by the row-creating rule — the contextual filter\n // above constrains which row is matched, never the unit a newly inserted row would land in.\n await this.assertOrganizationUnitWriteWithinGrant(enrichedPayload, CoreResourceOperation.CREATE, executionContext);\n\n // Create-time write integrity for the INSERT branch — the SAME rule `upsertByBusinessKey` applies,\n // so this insert path cannot silently skip FK-existence / scope-membership / top-level checks. The\n // effective inserted row is the enriched payload plus the filter's singleton key. In practice the\n // callers (feature/billing/milestone/platform singleton materializers) run under an exempt internal\n // context, so this returns immediately; a future non-exempt upsert-create inherits the guard for\n // free. No `operation` here → the relationship baseline applies, exactly like the business-key path.\n await assertCreateWriteIntegrity(\n this.writeIntegrityDeps,\n { ...enrichedPayload, ...filterShape },\n CoreResourceOperation.CREATE,\n CoreResourceOperation.CREATE,\n executionContext,\n options,\n );\n\n if (executionContext.isAnonymousExecution() && this.resourceConfiguration.isAnonymizable) {\n enrichedPayload.userId = null;\n }\n\n const payloadWithLiterals = this.resourceOperationHelper.injectNonDiscriminatorLiteralValues(\n enrichedPayload,\n this.resourceConfiguration.mainSchema,\n );\n\n // Zod CREATE validation can materialize defaults that are correct for an\n // inserted row but dangerous on the update branch of an upsert. Only fields\n // explicitly authored by the caller may be `$set`; schema defaults remain\n // insert-time defaults via `setDefaultsOnInsert`.\n const explicitPayloadKeys = new Set(Object.keys(payload));\n const explicitPayloadWithLiterals = Object.fromEntries(\n Object.entries(payloadWithLiterals).filter(([key]) => explicitPayloadKeys.has(key))\n );\n const insertOnlyPayloadWithLiterals = Object.fromEntries(\n Object.entries(payloadWithLiterals).filter(([key]) =>\n !explicitPayloadKeys.has(key) &&\n !Object.prototype.hasOwnProperty.call(filterShape, key)\n )\n );\n const updatePayload = this.addUserTracking(\n { ...explicitPayloadWithLiterals },\n executionContext,\n CoreResourceOperation.UPDATE,\n );\n delete (updatePayload as Record<string, unknown>)._version_db_doc;\n for (const key of Object.keys(filterShape)) {\n delete (updatePayload as Record<string, unknown>)[key];\n }\n\n const insertOnlyPayload = this.addUserTracking(\n { ...insertOnlyPayloadWithLiterals, ...filterShape },\n executionContext,\n CoreResourceOperation.CREATE,\n );\n delete (insertOnlyPayload as Record<string, unknown>)._version_db_doc;\n\n const session = this.getNativeSession(options);\n const mongooseOpts: any = {\n upsert: true,\n // `returnDocument: 'after'` replaces the deprecated `new: true` (Mongoose maps\n // them identically — return the post-update document).\n returnDocument: 'after',\n includeResultMetadata: true,\n setDefaultsOnInsert: true,\n };\n if (session) {\n mongooseOpts.session = session;\n }\n\n this.logDebug('upsertByFilter', {\n filter,\n hasTransaction: !!session,\n });\n\n let result: any;\n try {\n result = await this.mongooseModel.findOneAndUpdate(\n filter,\n {\n $set: updatePayload,\n $setOnInsert: insertOnlyPayload,\n $inc: { _version_db_doc: 1 },\n },\n mongooseOpts,\n );\n } catch (error) {\n this.logDebug('upsertByFilter failed', {\n error: describeCaughtError(error),\n filter,\n hasTransaction: !!session,\n });\n throw this.handleMongoDBError(error, executionContext);\n }\n\n const document = result?.value ?? null;\n const inserted = result?.lastErrorObject?.updatedExisting === false;\n const row = this.transformDocumentToResponse<T>(document, CoreResourceOperation.UPDATE) as ConditionalReturnType<T, TMainSchema>;\n return { inserted, row };\n }\n\n /**\n * Mongo implementation of `BackendResourceRepository.updateSeedMetadata`.\n *\n * Privileged write path for the `__seed` row-metadata ledger ONLY.\n * See the interface JSDoc on `BackendResourceRepository.updateSeedMetadata`\n * (in `repositories-registry-handler.backend.service.ts`) for the full\n * rationale — short version: app resources never declare `__seed` on\n * their UPDATE `requestDto`, so the standard `update(...)` path would\n * `.strip()` it. This method bypasses `cleanInputData` +\n * `validateRequestData` and writes directly via `findOneAndUpdate`.\n *\n * Atomicity guarantees:\n * - Single `findOneAndUpdate` call → atomic at the document level.\n * - `$set` writes the full `__seed` ledger AND user-tracking together.\n * - `$inc` on `_version_db_doc` keeps optimistic-locking parity with\n * `_doUpdate` (the same convention `upsertByBusinessKey` honors).\n *\n * Contextual scoping (R3-1 review note):\n * - We DO apply `buildContextualFilter` for defense-in-depth — the\n * dispatcher always calls this from an internal super-admin context\n * that bypasses scope filters anyway, but if a future caller\n * accidentally invokes from a tenant-scoped context the scoping\n * would correctly prevent cross-scope writes (instead of silently\n * succeeding then failing on the next read).\n *\n * @throws WildoError_Backend(NOT_FOUND) when the `_id` doesn't match.\n * @throws WildoError_Backend on Mongo write failure.\n */\n // field-clearing: N/A — writes only the engine-reserved `__seed` ledger, never an authored field.\n // rag-ingestion-gate: N/A — writes only the engine-reserved `__seed` ledger (plan §3.c M5), so no\n // `.ragSource()` corpus text ever passes through this door; any drift class it could theoretically\n // join is bounded by the hourly RAG reconciliation sweep's contentHash comparison.\n public async updateSeedMetadata(\n executionContext: ExecutionContext<any>,\n id: string,\n seedMetadata: DataSeedRowMetadata,\n options?: RepositoryOptions,\n ): Promise<void> {\n const baseFilter = { _id: id };\n const filter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.UPDATE, options);\n\n // User-tracking only (no body validation). Anonymous contexts\n // become a no-op on `addUserTracking` per the same convention as\n // `upsertByBusinessKey`.\n const trackedPayload: Record<string, unknown> = this.addUserTracking({}, executionContext, CoreResourceOperation.UPDATE);\n\n const session = this.getNativeSession(options);\n const mongooseOpts: any = { returnDocument: 'after' };\n if (session) {\n mongooseOpts.session = session;\n }\n\n this.logDebug('updateSeedMetadata', {\n id,\n seedKey: seedMetadata.seedKey,\n seedVersion: seedMetadata.seedVersion,\n hasDeprecated: seedMetadata.deprecated !== null,\n hasTransaction: !!session,\n });\n\n let document;\n try {\n document = await this.mongooseModel.findOneAndUpdate(\n filter,\n {\n $set: {\n ...trackedPayload,\n [DATA_SEED_ROW_METADATA_FIELD_KEY]: seedMetadata,\n },\n $inc: { _version_db_doc: 1 },\n },\n mongooseOpts,\n );\n } catch (error) {\n this.logDebug('updateSeedMetadata failed', {\n error: describeCaughtError(error),\n id,\n });\n throw this.handleMongoDBError(error, executionContext);\n }\n\n if (!document) {\n throw this.errorBuilder.buildError(\n ErrorType.NOT_FOUND,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_SEED_METADATA_NOT_FOUND,\n context: {\n // diagnostic (log-only)\n resourceIdentifier: this.resourceConfiguration.resourceIdentifier,\n id,\n },\n },\n );\n }\n }\n\n /**\n * Wrap the schema-level business-key resolution so any\n * `BUSINESS_KEY_ERROR_PREFIX`-tagged failure (no business-key declared,\n * shape missing/extra fields, undefined values) bridges to a typed\n * `INTERNAL` repository error instead of a bare `Error`.\n *\n * All errors out of `buildBusinessKeyFilter` are programmer mistakes\n * (the seed dispatcher constructs the shape from the seed's own\n * declaration; the user never authors it). Classifying them as\n * `INTERNAL` rather than `VALIDATION` keeps the dispatcher's error\n * stream consistent with the resolver's own JSDoc contract — see\n * `business-key-resolver.shared.utils.ts` and audit finding R-3.\n * Untagged errors are bridged to `INTERNAL` too with an explicit note,\n * since they cannot have come from user input either.\n */\n private _tryBuildBusinessKeyFilter(\n executionContext: ExecutionContext<any>,\n businessKeyShape: Record<string, unknown>,\n ): FilterQuery<any> {\n try {\n return buildBusinessKeyFilter(this.resourceConfiguration.mainSchema, businessKeyShape) as FilterQuery<any>;\n } catch (error) {\n const message = describeCaughtError(error);\n const isTagged = message.startsWith(BUSINESS_KEY_ERROR_PREFIX);\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED,\n context: {\n resourceIdentifier: this.resourceConfiguration.resourceIdentifier,\n message: isTagged ? message : `[business-key:untagged] ${message}`,\n },\n },\n );\n }\n }\n\n // ================================\n // Core Private Operations\n // ================================\n\n /**\n * retention-gate: N/A — INSERTs a brand-new row, so there is no existing row for a hide to protect.\n * A retained row is reached only through a filter, and this statement carries none.\n */\n private async _doCreate<T = undefined>(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n data: MainSchemaType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalReturnType<T, TMainSchema>> {\n this.logDebug('Creating resource', { hasData: !!data, dataKeys: typeof data === 'object' ? Object.keys(data) : 'not-object' });\n\n // Clean input data FIRST (remove mandatory discard fields)\n const cleanedData = this.resourceOperationHelper.cleanInputData(data, CoreResourceOperation.CREATE);\n this.logDebug('Data cleaned', { cleanedKeys: typeof cleanedData === 'object' ? Object.keys(cleanedData) : 'not-object' });\n\n // Validate against request DTO (after cleaning)\n const validatedData = this.repositoriesRegistry.validateRequestData(\n cleanedData,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n CoreResourceOperation.CREATE,\n options,\n );\n this.logDebug('Data validated against requestDto', { validatedKeys: typeof validatedData === 'object' ? Object.keys(validatedData) : 'not-object' });\n\n // THEN apply execution context data enrichment to the validated data\n const enrichedData = this.resourceOperationHelper.enrichDataWithContext(validatedData, executionContext, this.resourceConfiguration.mainSchema, this.resourceConfiguration.resourceFieldIdentifier,\n this.resourceConfiguration, CoreResourceOperation.CREATE, options);\n this.logDebug('Data enriched with context', { enrichedKeys: typeof enrichedData === 'object' ? Object.keys(enrichedData) : 'not-object' });\n\n // WS-C: no filter can constrain a create, so the unit the row lands in is checked here.\n await this.assertOrganizationUnitWriteWithinGrant(enrichedData, CoreResourceOperation.CREATE, executionContext);\n\n // Defense-in-depth: anonymous creation on isAnonymizable resources must have userId = null\n if (executionContext.isAnonymousExecution() && this.resourceConfiguration.isAnonymizable) {\n enrichedData.userId = null;\n }\n\n // Inject non-discriminator literal values from schema (e.g., scope: 'ORGANIZATION')\n // These are fixed values excluded from CREATE DTOs but must be persisted\n const dataWithLiterals = this.resourceOperationHelper.injectNonDiscriminatorLiteralValues(enrichedData, this.resourceConfiguration.mainSchema);\n this.logDebug('Non-discriminator literals injected', { dataWithLiteralsKeys: typeof dataWithLiterals === 'object' ? Object.keys(dataWithLiterals) : 'not-object' });\n\n // Add user tracking to enriched data\n const dataWithUserTracking = this.addUserTracking(dataWithLiterals, executionContext, CoreResourceOperation.CREATE);\n this.logDebug('User tracking added', { finalKeys: typeof dataWithUserTracking === 'object' ? Object.keys(dataWithUserTracking) : 'not-object' });\n\n // Create-time write integrity (adapter-neutral authority): FK existence-in-scope + top-level\n // mainSchema cross-field checks, against the FULLY-ENRICHED row (never the request DTO, which omits\n // backend-injected fields). A create has no filter/pre-image, so this is the only place a dangling\n // or cross-tenant FK is caught, and where a junction's `source ≠ target` rejects a self-link.\n await assertCreateWriteIntegrity(\n this.writeIntegrityDeps,\n dataWithUserTracking,\n CoreResourceOperation.CREATE,\n operation.operationIdentifier,\n executionContext,\n options,\n referenceConstraintsOf(operation),\n );\n\n try {\n const nativeSession = this.getNativeSession(options);\n this.logDebug('Creating document with Model.create()...', {\n hasTransaction: !!nativeSession\n });\n\n // Use transaction session if provided\n const createOptions: any = nativeSession ? { session: nativeSession } : {};\n\n // DEBUG: Log the exact data being passed to mongoose\n this.logDebug('\\n=== DEBUG: About to call mongoose create ===');\n // Use the bigint-safe serializer: resource data may carry `z_money` (MoneyValue)\n // amounts stored as `bigint`, which a bare `JSON.stringify` cannot serialize\n // (\"Do not know how to serialize a BigInt\"). This eager argument is evaluated on\n // every create regardless of log level, so a bare stringify here throws before the\n // mongoose write for any money-bearing resource (e.g. billing prices).\n this.logDebug('dataWithUserTracking:', { dataWithUserTracking: ResourceSerializationUtils.stringifyWithBigInt(dataWithUserTracking, 2) });\n this.logDebug('keys:', { keys: Object.keys(dataWithUserTracking || {}) });\n this.logDebug('dataType:', { dataType: typeof dataWithUserTracking });\n this.logDebug('hasName:', { hasName: !!(dataWithUserTracking as any)?.name });\n this.logDebug('hasSlug:', { hasSlug: !!(dataWithUserTracking as any)?.slug });\n this.logDebug('nameValue:', (dataWithUserTracking as any)?.name);\n this.logDebug('slugValue:', { slugValue: (dataWithUserTracking as any)?.slug });\n\n // DEBUG: Log mongoose schema info\n this.logDebug('Mongoose model name:', { mongooseModelName: this.mongooseModel.modelName });\n this.logDebug('Mongoose schema paths:', { mongooseSchemaPaths: Object.keys(this.mongooseModel.schema.paths) });\n this.logDebug('Required paths:', { requiredPaths: Object.keys(this.mongooseModel.schema.paths).filter(path => {\n const schemaType = this.mongooseModel.schema.paths[path];\n return schemaType.isRequired;\n }) });\n\n this.logDebug('Name field config:', { nameFieldConfig: this.mongooseModel.schema.paths['name']?.isRequired, nameFieldInstance: this.mongooseModel.schema.paths['name']?.instance });\n this.logDebug('Slug field config:', { slugFieldConfig: this.mongooseModel.schema.paths['slug']?.isRequired, slugFieldInstance: this.mongooseModel.schema.paths['slug']?.instance });\n this.logDebug('Status field config:', { statusFieldConfig: this.mongooseModel.schema.paths['status']?.isRequired, statusFieldInstance: this.mongooseModel.schema.paths['status']?.instance });\n this.logDebug('=======================================\\n');\n\n // Mongoose only honors create() options like `session` when they are passed\n // through the variadic docs+options signature. For a single-document create,\n // using the array form preserves transaction participation.\n const [savedDocument] = await this.mongooseModel.create([dataWithUserTracking], createOptions);\n this.logDebug('Document created successfully');\n\n return this.transformDocumentToResponse(savedDocument, CoreResourceOperation.CREATE);\n } catch (error) {\n this.logDebug('Mongoose create failed', {\n error: describeCaughtError(error),\n enrichedData: enrichedData,\n hasTransaction: !!this.getNativeSession(options)\n });\n\n // Handle MongoDB unique constraint violations (E11000 duplicate key error)\n throw this.handleMongoDBError(error, executionContext);\n }\n }\n\n\n /** retention-gate: N/A — bulk INSERT of brand-new rows; see `_doCreate`. */\n private async _doCreateMany<T = undefined>(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n dataArray: MainSchemaArrayType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalArrayReturnType<T, TMainSchema>> {\n this.logDebug('Creating multiple resources', { count: dataArray.length });\n\n // Clean input data FIRST (remove mandatory discard fields)\n const cleanedDataArray = this.resourceOperationHelper.cleanInputDataArray(dataArray, CoreResourceOperation.CREATE_MANY);\n this.logDebug('Data array cleaned', { count: cleanedDataArray.length });\n\n // CreateMany always processes multiple items\n\n // Validate and enrich each item\n const isAnonymousCreate = executionContext.isAnonymousExecution() && this.resourceConfiguration.isAnonymizable;\n const isBulkOperation = 'isBulkOperation' in operation && operation.isBulkOperation === true;\n // `async` + `Promise.all` because the per-row narrowing guard now performs a scoped tenant read.\n // Kept PER ROW rather than hoisted: a bulk create must not let one out-of-tenant row ride in on a\n // batch, which is the same reason the grant check was already per row.\n const processedDataArray = await Promise.all(cleanedDataArray.map(async (data, index) => {\n const rowScopedOptions = this.repositoriesRegistry.buildGeneratedPdfRowRepositoryOptions?.(options, index) ?? options;\n const validatedData = this.repositoriesRegistry.validateRepositoryWriteData(\n data,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n String(operation.operationIdentifier),\n isBulkOperation,\n rowScopedOptions,\n );\n const enrichedData = this.resourceOperationHelper.enrichDataWithContext(validatedData, executionContext, this.resourceConfiguration.mainSchema, this.resourceConfiguration.resourceFieldIdentifier,\n this.resourceConfiguration, CoreResourceOperation.CREATE_MANY, rowScopedOptions);\n // WS-C: checked PER ROW — a bulk create must not let one out-of-grant row ride in on a batch.\n await this.assertOrganizationUnitWriteWithinGrant(enrichedData, CoreResourceOperation.CREATE_MANY, executionContext);\n if (isAnonymousCreate) { enrichedData.userId = null; }\n // Inject non-discriminator literal values from schema\n const dataWithLiterals = this.resourceOperationHelper.injectNonDiscriminatorLiteralValues(enrichedData, this.resourceConfiguration.mainSchema);\n const finalRow = this.addUserTracking(dataWithLiterals, executionContext, CoreResourceOperation.CREATE_MANY);\n // Create-time write integrity PER ROW (see _doCreate) — one dangling/cross-tenant FK or invalid\n // cross-field row must not ride in on a batch.\n await assertCreateWriteIntegrity(\n this.writeIntegrityDeps,\n finalRow,\n CoreResourceOperation.CREATE_MANY,\n operation.operationIdentifier,\n executionContext,\n rowScopedOptions,\n referenceConstraintsOf(operation),\n );\n return finalRow;\n }));\n\n // Prepare mongoose options with transaction session if provided\n const session = this.getNativeSession(options);\n const mongooseOpts: any = session ? { session } : {};\n\n this.logDebug('Creating multiple documents', {\n count: processedDataArray.length,\n hasTransaction: !!session\n });\n\n // insertMany returns an array of documents by default (not InsertManyResult unless rawResult: true)\n // TypeScript infers the wrong type, so we cast through unknown\n const documents = await this.mongooseModel.insertMany(processedDataArray, mongooseOpts) as unknown as any[];\n\n return documents.map(doc => this.transformDocumentToResponse(doc, CoreResourceOperation.CREATE_MANY)) as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n\n private async _doRead<T = undefined>(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_filter?: IdOrFilterType,\n options?: RepositoryOptions\n ): Promise<ConditionalNullableReturnType<T, TMainSchema>> {\n const session = this.getNativeSession(options);\n this.logDebug('Reading resource', { id_or_filter, hasOptions: !!options, hasTransaction: !!session });\n\n // Validate required parameter\n this.validateIdOrIdsOrFilterRequired(\n id_or_filter,\n executionContext,\n CoreResourceOperation.READ,\n );\n\n // Build base filter - read operation is always unitary (single entity)\n const { baseFilter } = this.buildBaseFilterFromIdOrIdsOrFilter(id_or_filter, executionContext);\n\n const filter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.READ, options);\n\n // Prepare mongoose options with transaction session if provided\n const mongooseOpts: any = session ? { session } : {};\n\n // Read operation always returns single entity or null. A CastError here means a filter\n // value (e.g. a malformed or UUID-format `_id`) could not be cast to its field type, so NO\n // document can match — that is semantically a not-found, not an INTERNAL/500. (FILES is\n // Mongo-pinned, so a UUID-format `fileId` reaching `{ _id: <uuid> }` lands here.)\n let document: any;\n try {\n document = await this.mongooseModel.findOne(filter, null, mongooseOpts);\n } catch (error) {\n if (this.isMongooseCastError(error)) {\n this.logDebug('Read filter value could not be cast — treating as not-found', {\n filter,\n error: describeCaughtError(error),\n });\n return null;\n }\n throw error;\n }\n this.logDebug('Read single result', {\n filter,\n found: !!document,\n preview: this.previewDocument(document),\n hasTransaction: !!session\n });\n\n if (!document) {\n return null;\n }\n\n return this.transformDocumentToResponse<T>(document, CoreResourceOperation.READ);\n }\n\n\n private async _doUpdate<T = undefined>(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_filter?: IdOrFilterType,\n data?: PartialMainSchemaType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalNullableReturnType<T, TMainSchema>> {\n this.logDebug('Updating resource', { id_or_filter, hasData: !!data, hasOptions: !!options });\n\n // Validate required parameter\n this.validateIdOrIdsOrFilterRequired(id_or_filter, executionContext, CoreResourceOperation.UPDATE);\n\n if (!data) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED }\n );\n }\n\n // Clean input data FIRST (remove mandatory discard fields)\n const cleanedData = this.resourceOperationHelper.cleanInputData(data, CoreResourceOperation.UPDATE);\n this.logDebug('Data cleaned for update', { cleanedKeys: typeof cleanedData === 'object' ? Object.keys(cleanedData) : 'not-object' });\n\n // Validate against request DTO (after cleaning)\n const validatedData = this.repositoriesRegistry.validateRequestData(\n cleanedData,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n String(operation.operationIdentifier),\n options,\n );\n this.logDebug('Data validated against requestDto', { validatedKeys: typeof validatedData === 'object' ? Object.keys(validatedData) : 'not-object' });\n\n // THEN apply execution context data enrichment to the validated data\n const enrichedData = this.resourceOperationHelper.enrichDataWithContext(validatedData, executionContext, this.resourceConfiguration.mainSchema, this.resourceConfiguration.resourceFieldIdentifier,\n this.resourceConfiguration, CoreResourceOperation.UPDATE, options);\n this.logDebug('Data enriched with context', { enrichedKeys: typeof enrichedData === 'object' ? Object.keys(enrichedData) : 'not-object' });\n\n // WS-C: the contextual filter already confines WHICH row is updated; this confines the unit the\n // update may move it TO. An update that does not touch the unit field is unaffected.\n await this.assertOrganizationUnitWriteWithinGrant(enrichedData, CoreResourceOperation.UPDATE, executionContext);\n\n // Referential + scope-via-junction integrity for any FK this update REASSIGNS (e.g. a reassigned\n // `assignedToUserId` must still be a member of the row's tenant). Create-only checks miss it, and a\n // reassignable lateral FK to an org-less target is exactly the cross-tenant gap this closes. Absent\n // FKs are skipped inside; exempt executions (internal/webhook/anon/seed) are exempt at the entry.\n await assertUpdateWriteIntegrity(this.writeIntegrityDeps, enrichedData, CoreResourceOperation.UPDATE, executionContext, options, referenceConstraintsOf(operation));\n\n // Add user tracking to enriched data\n const dataWithUserTracking = this.addUserTracking(enrichedData, executionContext, CoreResourceOperation.UPDATE);\n this.logDebug('User tracking added', { finalKeys: typeof dataWithUserTracking === 'object' ? Object.keys(dataWithUserTracking) : 'not-object' });\n\n // Build base filter - update operation is always unitary (single entity)\n const { baseFilter } = this.buildBaseFilterFromIdOrIdsOrFilter(id_or_filter, executionContext);\n\n // Ensure we have some filter criteria\n if (Object.keys(baseFilter).length === 0) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED }\n );\n }\n\n // Apply contextual filtering\n const filter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.UPDATE, options);\n\n if (options?.ifMatchVersion !== undefined) {\n filter._version_db_doc = options.ifMatchVersion;\n this.logDebug('Optimistic locking: added version filter', { ifMatchVersion: options.ifMatchVersion });\n }\n\n // Prepare mongoose options with transaction session if provided\n const session = this.getNativeSession(options);\n const mongooseOpts: any = { runValidators: true, returnDocument: 'after' };\n if (session) {\n mongooseOpts.session = session;\n }\n\n // Defense-in-depth: strip version fields from update data to prevent\n // $set/$inc conflict on _version_db_doc\n delete dataWithUserTracking._version_db_doc;\n delete dataWithUserTracking._version;\n\n // CRDT: userId needed by both the LWW merge and the version-conflict retry\n const userId = options?.fieldTimestamps ? (executionContext.initiatorIds?.userId ?? 'unknown') : undefined;\n const FIELD_META_CAP = 200;\n\n // CRDT field-level LWW merge\n // P1: The extra findOne (projection: _field_meta only) is an intentional round-trip —\n // LWW needs the latest per-field server timestamps before findOneAndUpdate; a blind\n // CAS without pre-read cannot compare client vs server field clocks.\n if (options?.fieldTimestamps && Object.keys(options.fieldTimestamps).length > 0) {\n /**\n * Pre-read through the CONTEXTUAL filter, not a bare `_id`.\n *\n * This is a raw `mongooseModel` call, so it skips `buildContextualFilter` — the chokepoint that\n * hides erased-but-retained rows and applies scope. Reading by `_id` alone therefore pre-read a\n * row the update itself could never touch. Nothing personal leaked (the projection is CRDT\n * causality only, and the write below matches nothing), which is why this was recorded as LOW\n * rather than fixed as a disclosure — but reading a DIFFERENT row set than the statement it\n * feeds is incoherent regardless of what happens to be in the projection.\n *\n * `filter` is the same expression the update runs, so the merge is now computed from exactly the\n * row that will be written, or from nothing when there is no such row.\n *\n * ⚠️ **This also changes behaviour on the FILTER-based update path, deliberately.**\n * `buildBaseFilterFromIdOrIdsOrFilter` has a raw-`FilterQuery` branch, so `baseFilter._id` can be\n * absent entirely — the previous expression then read `{ _id: undefined }`, which does not identify\n * the target row. Depending on how the driver treats an undefined value that is either no row or an\n * ARBITRARY one, and in the second case the LWW merge compared client clocks against a different\n * document's server clocks. Neither outcome is the intended one, so this is a second (pre-existing,\n * retention-unrelated) defect that the same one-line change removes.\n *\n * ⚠️ **Untested path, stated rather than implied:** nothing in the suite exercises\n * `options.fieldTimestamps` at all — searching `__tests__` for it returns no file — so this block\n * has no coverage before or after. The change is reasoned and typechecked, NOT behaviour-verified.\n * A pin belongs here; writing one needs a `_doUpdate` harness that does not exist yet.\n */\n const currentDoc = await this.mongooseModel.findOne(\n filter,\n { _field_meta: 1 },\n session ? { session } : undefined,\n );\n\n const currentFieldMeta: Record<string, FieldMetaEntry> = sanitizeFieldMeta(currentDoc?._field_meta);\n const mergedFieldMeta: Record<string, FieldMetaEntry> = { ...currentFieldMeta };\n const fieldsToRemoveFromUpdate: string[] = [];\n\n for (const [field, clientTs] of Object.entries(options.fieldTimestamps)) {\n const serverTs = currentFieldMeta[field]?.ts ?? 0;\n\n if (lwwFieldWinner(clientTs, serverTs) === CrdtResolutionWinner.INCOMING) {\n mergedFieldMeta[field] = { ts: nextMonotonicTimestamp(Date.now(), serverTs), by: userId! };\n } else {\n fieldsToRemoveFromUpdate.push(field);\n }\n }\n\n for (const field of fieldsToRemoveFromUpdate) {\n delete dataWithUserTracking[field];\n this.logDebug('CRDT LWW: server wins for field', { field });\n }\n\n // D1: Schema-aware prune — remove _field_meta keys for fields no longer in the schema.\n // Prevents unbounded growth after schema renames.\n const validCrdtKeys = extractCrdtFieldNames(this.resourceConfiguration.mainSchema, false);\n if (validCrdtKeys.size > 0) {\n const staleKeys: string[] = [];\n for (const key of Object.keys(mergedFieldMeta)) {\n if (!validCrdtKeys.has(key)) staleKeys.push(key);\n }\n for (const key of staleKeys) {\n delete mergedFieldMeta[key];\n }\n if (staleKeys.length > 0) {\n this.logDebug('CRDT D1: pruned stale _field_meta keys', { staleKeys });\n }\n }\n\n // S3: Cap _field_meta size — evict oldest entries beyond the cap.\n // Runs after D1 semantic prune as a second line of defense.\n const metaKeys = Object.keys(mergedFieldMeta);\n if (metaKeys.length > FIELD_META_CAP) {\n const sorted = metaKeys.sort((a, b) => (mergedFieldMeta[a].ts ?? 0) - (mergedFieldMeta[b].ts ?? 0));\n const toEvict = sorted.slice(0, metaKeys.length - FIELD_META_CAP);\n for (const key of toEvict) {\n delete mergedFieldMeta[key];\n }\n this.logDebug('CRDT S3: capped _field_meta', { evicted: toEvict.length, remaining: FIELD_META_CAP });\n }\n\n dataWithUserTracking._field_meta = mergedFieldMeta;\n\n this.logDebug('CRDT LWW merge', {\n clientFields: Object.keys(options.fieldTimestamps),\n removedFields: fieldsToRemoveFromUpdate,\n survivingFields: Object.keys(options.fieldTimestamps).filter(f => !fieldsToRemoveFromUpdate.includes(f)),\n });\n }\n\n // Update operation always updates single entity\n let document;\n try {\n document = await this.mongooseModel.findOneAndUpdate(\n filter,\n this.buildVersionedUpdateDocument(dataWithUserTracking),\n mongooseOpts\n );\n } catch (error) {\n this.logDebug('Mongoose update failed', {\n error: describeCaughtError(error),\n filter,\n hasTransaction: !!session\n });\n throw this.handleMongoDBError(error, executionContext);\n }\n\n this.logDebug('Single update completed', {\n filter,\n found: !!document,\n hasTransaction: !!session\n });\n\n if (!document) {\n if (options?.ifMatchVersion !== undefined) {\n // Disambiguate: version conflict vs resource deleted/absent.\n // Query by _id only (no version filter) to check existence.\n // M5a (F3): a RETAINED row must read as ABSENT here too, or the 409-vs-404 disambiguation becomes\n // an existence oracle — a normal caller updating a retained (behave-as-deleted) row would get 409\n // VERSION_CONFLICT, disclosing the row exists. Applies the SAME predicate authority as\n // `buildContextualFilter` (gated on retention + suppressed by see-through) so the caller gets 404,\n // consistent with the \"behave-as-deleted\" contract. No-op for non-retention resources.\n // The executed operation is UPDATE — a write — so a see-through EC can never suppress the hide here.\n const existsFilter: FilterQuery<any> = { ...baseFilter };\n assignRetentionHideForOperation(\n existsFilter,\n this.resourceConfiguration,\n executionContext,\n CoreResourceOperation.UPDATE,\n );\n const existsDoc = await this.mongooseModel.findOne(\n existsFilter,\n { _id: 1 },\n session ? { session } : undefined\n );\n\n // CRDT-only update retry: when two clients save different CRDT fields simultaneously,\n // the second client's findOneAndUpdate fails because the first already incremented\n // the version. Retry with the current version instead of returning 409.\n const crdtFieldSet = options?.fieldTimestamps ? new Set(Object.keys(options.fieldTimestamps)) : null;\n const userDataKeys = Object.keys(dataWithUserTracking).filter(\n k => !k.startsWith('_')\n );\n const isCrdtOnly = crdtFieldSet !== null && isCrdtOnlyUpdate(userDataKeys, crdtFieldSet);\n\n if (existsDoc && options?.fieldTimestamps && isCrdtOnly) {\n const freshDoc = await this.mongooseModel.findOne(\n baseFilter,\n { _field_meta: 1, _version_db_doc: 1 },\n session ? { session } : undefined,\n );\n if (freshDoc) {\n filter._version_db_doc = freshDoc._version_db_doc;\n\n const freshFieldMeta: Record<string, FieldMetaEntry> = sanitizeFieldMeta(freshDoc._field_meta);\n const freshMerged: Record<string, FieldMetaEntry> = { ...freshFieldMeta };\n for (const [field, clientTs] of Object.entries(options.fieldTimestamps)) {\n const serverTs = freshFieldMeta[field]?.ts ?? 0;\n if (lwwFieldWinner(clientTs, serverTs) === CrdtResolutionWinner.INCOMING) {\n freshMerged[field] = { ts: nextMonotonicTimestamp(Date.now(), serverTs), by: userId! };\n } else {\n delete dataWithUserTracking[field];\n }\n }\n // D1: Schema-aware prune on retry path\n const validCrdtKeysRetry = extractCrdtFieldNames(this.resourceConfiguration.mainSchema, false);\n if (validCrdtKeysRetry.size > 0) {\n for (const key of Object.keys(freshMerged)) {\n if (!validCrdtKeysRetry.has(key)) delete freshMerged[key];\n }\n }\n\n // S3: Cap _field_meta size on retry path\n const retryMetaKeys = Object.keys(freshMerged);\n if (retryMetaKeys.length > FIELD_META_CAP) {\n const sorted = retryMetaKeys.sort((a, b) => (freshMerged[a].ts ?? 0) - (freshMerged[b].ts ?? 0));\n const toEvict = sorted.slice(0, retryMetaKeys.length - FIELD_META_CAP);\n for (const key of toEvict) delete freshMerged[key];\n }\n\n dataWithUserTracking._field_meta = freshMerged;\n\n document = await this.mongooseModel.findOneAndUpdate(\n filter,\n this.buildVersionedUpdateDocument(dataWithUserTracking),\n mongooseOpts,\n );\n if (document) {\n this.logDebug('CRDT LWW: retry succeeded after version conflict');\n return this.transformDocumentToResponse<T>(document, CoreResourceOperation.UPDATE);\n }\n // O1: retry was attempted (freshDoc found) but second findOneAndUpdate still lost the race\n this.logger.warn('CRDT LWW retry exhausted — falling through to VERSION_CONFLICT', {\n resourceId: String(baseFilter._id),\n clientFields: options?.fieldTimestamps ? Object.keys(options.fieldTimestamps) : [],\n });\n }\n // If freshDoc was null, fall through to 409 without O1 (could not refresh version / meta)\n }\n\n if (existsDoc) {\n this.logDebug('Version conflict detected', {\n ifMatchVersion: options.ifMatchVersion,\n resourceId: baseFilter._id\n });\n throw this.errorBuilder.buildError(\n ErrorType.CONFLICT,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.VERSION_CONFLICT,\n context: {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n ifMatchVersion: options.ifMatchVersion,\n }\n }\n );\n }\n // Document truly doesn't exist — fall through to return null\n // (service layer will throw NOT_FOUND)\n }\n return null;\n }\n\n return this.transformDocumentToResponse<T>(document, CoreResourceOperation.UPDATE);\n }\n\n private async _doUpdateMany<T = undefined>(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType | undefined,\n data: PartialMainSchemaType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalArrayReturnType<T, TMainSchema>> {\n const { baseFilter } = this.buildBaseFilterFromIdOrIdsOrFilter(ids_or_filter, executionContext);\n const session = this.getNativeSession(options);\n this.logDebug('Updating multiple resources', { ids_or_filter, hasData: !!data, hasTransaction: !!session });\n\n // Clean input data FIRST (remove mandatory discard fields)\n const cleanedData = this.resourceOperationHelper.cleanInputData(data, CoreResourceOperation.UPDATE_MANY);\n this.logDebug('Data cleaned for updateMany', { cleanedKeys: typeof cleanedData === 'object' ? Object.keys(cleanedData) : 'not-object' });\n\n // Validate against request DTO (after cleaning)\n const isBulkOperation = 'isBulkOperation' in operation && operation.isBulkOperation === true;\n const validatedData = this.repositoriesRegistry.validateRepositoryWriteData(\n cleanedData,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n String(operation.operationIdentifier),\n isBulkOperation,\n options,\n );\n this.logDebug('Data validated against requestDto', { validatedKeys: typeof validatedData === 'object' ? Object.keys(validatedData) : 'not-object' });\n\n // THEN apply execution context data enrichment to the validated data\n const enrichedData = this.resourceOperationHelper.enrichDataWithContext(validatedData, executionContext, this.resourceConfiguration.mainSchema, this.resourceConfiguration.resourceFieldIdentifier,\n this.resourceConfiguration, CoreResourceOperation.UPDATE_MANY, options);\n this.logDebug('Data enriched with context', { enrichedKeys: typeof enrichedData === 'object' ? Object.keys(enrichedData) : 'not-object' });\n\n // WS-C: one patch applied to many rows — an out-of-grant unit value here would move EVERY matched\n // row out of the caller's grant at once, so the same value check applies.\n await this.assertOrganizationUnitWriteWithinGrant(enrichedData, CoreResourceOperation.UPDATE_MANY, executionContext);\n\n // Referential + scope-via-junction integrity for any FK this bulk patch REASSIGNS — one patch\n // moving every matched row's `assignedToUserId` to a cross-tenant user is refused once, up front.\n await assertUpdateWriteIntegrity(this.writeIntegrityDeps, enrichedData, CoreResourceOperation.UPDATE_MANY, executionContext, options, referenceConstraintsOf(operation));\n\n // Add user tracking to enriched data\n const dataWithUserTracking = this.addUserTracking(enrichedData, executionContext, CoreResourceOperation.UPDATE_MANY);\n this.logDebug('User tracking added', { finalKeys: typeof dataWithUserTracking === 'object' ? Object.keys(dataWithUserTracking) : 'not-object' });\n\n // Defense-in-depth: strip version fields from update data to prevent\n // $set/$inc conflict on _version_db_doc in bulk updates too.\n delete dataWithUserTracking._version_db_doc;\n delete dataWithUserTracking._version;\n\n const contextualFilter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.UPDATE_MANY, options);\n\n // Prepare mongoose options with transaction session if provided\n const mongooseOpts: any = { runValidators: true };\n if (session) {\n mongooseOpts.session = session;\n }\n\n const findOpts: any = session ? { session } : {};\n const matchedDocuments = await this.mongooseModel.find(contextualFilter, { _id: 1 }, findOpts);\n const matchedIds = matchedDocuments\n .map((doc: any) => doc?._id?.toString?.() ?? doc?._id)\n .filter((id: unknown): id is string => typeof id === 'string' && id.length > 0);\n\n if (matchedIds.length === 0) {\n return [] as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n const updateResult = await this.mongooseModel.updateMany(\n contextualFilter,\n this.buildVersionedUpdateDocument(dataWithUserTracking),\n mongooseOpts\n );\n\n this.logDebug('UpdateMany completed', {\n filter: contextualFilter,\n matchedCount: updateResult.matchedCount,\n modifiedCount: updateResult.modifiedCount,\n hasTransaction: !!session\n });\n\n if (updateResult.matchedCount === 0) {\n return [] as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n // Re-read by stable ids rather than the original filter.\n // Otherwise a patch that changes a matched filter field can make the follow-up\n // find() return an empty set even though Mongo actually updated documents.\n const updatedDocuments = await this.mongooseModel.find(\n { _id: { $in: matchedIds } } as FilterQuery<any>,\n null,\n findOpts\n );\n const updatedDocumentsById = new Map(\n updatedDocuments.map((doc: any) => [\n doc?._id?.toString?.() ?? doc?._id,\n doc,\n ] as const)\n );\n const orderedUpdatedDocuments = matchedIds\n .map((id) => updatedDocumentsById.get(id))\n .filter((doc): doc is any => !!doc);\n\n return orderedUpdatedDocuments.map(doc => this.transformDocumentToResponse<T>(doc, CoreResourceOperation.UPDATE_MANY)) as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n\n private async _doDelete(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_filter?: IdOrFilterType,\n options?: RepositoryOptions\n ): Promise<string> {\n // Prepare mongoose options with transaction session if provided\n const session = this.getNativeSession(options);\n const mongooseOpts: any = session ? { session } : {};\n\n this.logDebug('Deleting resource', { id_or_filter, hasTransaction: !!session });\n\n // Validate required parameter\n this.validateIdOrIdsOrFilterRequired(id_or_filter, executionContext, CoreResourceOperation.DELETE);\n\n // Build base filter - delete operation is always unitary (single entity)\n const { baseFilter: deleteFilter } = this.buildBaseFilterFromIdOrIdsOrFilter(id_or_filter, executionContext);\n\n const filter = this.buildContextualFilter(executionContext, deleteFilter, CoreResourceOperation.DELETE, options);\n\n // First, fetch the document to get its ID before deletion\n const documentToDelete = await this.mongooseModel.findOne(filter, { _id: 1 }, mongooseOpts);\n\n if (!documentToDelete) {\n this.logDebug('No document found to delete', { filter });\n return '';\n }\n\n const deletedId = (documentToDelete as any)._id.toString();\n\n // Delete operation always deletes single entity\n const result = await this.mongooseModel.deleteOne(filter, mongooseOpts);\n\n this.logDebug('Single delete completed', {\n filter,\n deletedCount: result.deletedCount,\n deletedId: deletedId,\n hasTransaction: !!session\n });\n\n return deletedId;\n }\n\n\n private async _doDeleteMany(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n ids_or_filter?: IdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<string[]> {\n // Prepare mongoose options with transaction session if provided\n const session = this.getNativeSession(options);\n const mongooseOpts: any = session ? { session } : {};\n\n this.logDebug('Deleting multiple resources', { ids_or_filter, hasTransaction: !!session });\n\n // Validate required parameter for deleteMany operation\n this.validateIdOrIdsOrFilterRequired(ids_or_filter, executionContext, CoreResourceOperation.DELETE_MANY);\n\n // Build base filter for multiple deletions - this handles IdsOrFilterType\n const { baseFilter } = this.buildBaseFilterFromIdOrIdsOrFilter(ids_or_filter, executionContext);\n\n // Apply contextual filtering\n const contextualFilter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.DELETE_MANY, options);\n\n // First, fetch all documents that match the filter to get their IDs before deletion\n const documentsToDelete = await this.mongooseModel.find(contextualFilter, { _id: 1 }, mongooseOpts);\n\n if (!documentsToDelete || documentsToDelete.length === 0) {\n this.logDebug('No documents found to delete', { contextualFilter });\n return [];\n }\n\n const deletedIds = documentsToDelete.map(doc => (doc as any)._id.toString());\n\n // Perform multiple deletions using deleteMany\n const result = await this.mongooseModel.deleteMany(contextualFilter, mongooseOpts);\n\n this.logDebug('Multiple delete completed', {\n contextualFilter,\n deletedCount: result.deletedCount,\n deletedIds: deletedIds,\n hasTransaction: !!session\n });\n\n return deletedIds;\n }\n\n private async _doList<T = undefined>(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n ids_or_filter?: IdsOrFilterType,\n options?: RepositoryOptions & { listOptions?: Partial<Resources_PaginationRequest> & { sort?: Record<string, 1 | -1> } }\n ): Promise<(T extends undefined ? any : T)[] | Resources_PaginatedResult<T extends undefined ? any : T>> {\n\n // Validate required parameter\n this.validateIdOrIdsOrFilterRequired(ids_or_filter, executionContext, CoreResourceOperation.LIST);\n\n // Build base filter\n const { baseFilter } = this.buildBaseFilterFromIdOrIdsOrFilter(ids_or_filter, executionContext);\n\n const contextualFilter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.LIST, options);\n\n // Build projection from operation's responseDto\n const projection = this.buildMongoProjectionFromResponseDto(operation);\n\n // Check if pagination wrapper is requested\n const paginated = options?.paginated ?? false;\n const listOptions = options?.listOptions;\n const hasPagination = listOptions?.page !== undefined || listOptions?.limit !== undefined;\n const session = this.getNativeSession(options);\n\n // Only count documents if we need pagination metadata\n let total = 0;\n let page = 1;\n let limit = 0;\n let skip = 0;\n let totalPages = 1;\n\n if (paginated || hasPagination) {\n let countQuery = this.mongooseModel.countDocuments(contextualFilter);\n if (session) {\n countQuery = countQuery.session(session);\n }\n total = await countQuery.exec();\n page = hasPagination ? Math.max(1, listOptions?.page || 1) : 1;\n // The ceiling the OPERATION declares. LIST used to consult it nowhere.\n //\n // The default is 100, NOT the 50 that `_doSearch` uses, and the difference is deliberate: 100\n // is the hard-coded cap this line replaced (`Math.min(100, …)`), so an operation that declares\n // nothing keeps exactly the ceiling it has always had. Defaulting to 50 \"for symmetry with\n // SEARCH\" silently halved every caller that asked for more — including billing usage-metering\n // (`limit: 10000`), the sidebar resource browser and the audit export, none of which declare a\n // ceiling. A consumer sweep found them; the symmetry was not worth the truncation.\n const maxLimit = (operation as { maxPaginatedResultPerPageLimit?: number }).maxPaginatedResultPerPageLimit || 100;\n // ⚠️ The `paginated && !hasPagination` branch used to be `total || 1` — i.e. \"return the WHOLE\n // collection in one page\". Combined with the response DTO's ceiling that is an unavoidable 500\n // for any collection larger than the ceiling: the repository builds a page the DTO then\n // refuses. Observed 2026-08-12 on `GET /users/admin` against 77 users.\n //\n // It was also an ADAPTER DIVERGENCE — the PostgreSQL `_doList` has always defaulted to 20 here\n // — so the same request returned every row on Mongo and 20 on PostgreSQL. Both now use the\n // framework's one default page size, capped by the declared ceiling.\n //\n // The NON-paginated path is deliberately untouched: with `paginated === false` and no\n // `listOptions`, this whole block is skipped, `limit` stays 0, and mongo returns every row.\n // That is the internal-call contract (engine code calls `list()` expecting the full set), and\n // capping it here would silently truncate every internal enumeration in the framework.\n limit = Math.min(maxLimit, Math.max(1, listOptions?.limit || 20));\n skip = (page - 1) * limit;\n totalPages = limit > 0 ? Math.ceil(total / limit) : 1;\n }\n\n this.logDebug('Listing resources', {\n ids_or_filter,\n paginated,\n hasPagination,\n page,\n limit,\n skip,\n total,\n hasTransaction: !!session\n });\n\n // Prepare query with projection and transaction session.\n // Sort mirrors SEARCH: `constructValidatedSortOptions` validates the\n // caller-supplied `sort` against the operation's `sortFields` (priority =\n // key order) and falls back to the first configured field, or createdAt-desc\n // when no sortFields are declared — so an absent `sort` preserves the prior\n // newest-first default for unconfigured resources.\n let query = this.mongooseModel\n .find(contextualFilter, projection)\n .sort(this.constructValidatedSortOptions(listOptions?.sort, operation));\n\n // Bound the QUERY whenever a paginated envelope is being returned.\n //\n // This used to be gated on `hasPagination` alone — true only when the CALLER supplied `page` or\n // `limit`. So `paginated: true` with no explicit page (every default `GET /<collection>`) fell\n // through unbounded and fetched the entire collection, while the envelope reported a `limit` it\n // had not applied. The metadata and the query disagreed, and the DTO ceiling then rejected the\n // oversized page as a 500.\n //\n // Computing a correct `limit` above is NOT sufficient on its own — that was the first attempt at\n // this fix, and the adapter-parity pin caught it by observing the query's `.limit()` rather than\n // the returned metadata. If a future change touches either half, both must move together.\n if (paginated || hasPagination) {\n query = query.skip(skip).limit(limit);\n }\n\n if (session) {\n query = query.session(session);\n }\n\n const documents = await query.exec();\n\n const data = documents.map(doc => this.transformDocumentToResponse<T>(doc, CoreResourceOperation.LIST)) as (T extends undefined ? any : T)[];\n\n this.logDebug('List result', {\n filter: contextualFilter,\n count: data.length,\n paginated,\n pagination: paginated ? { page, limit, total, totalPages } : undefined,\n sample: this.previewDocument(documents[0]),\n hasTransaction: !!session\n });\n\n // Return raw array by default, or with pagination wrapper if requested\n if (paginated) {\n return {\n data,\n pagination: { page, limit: limit || data.length, total: total || data.length, totalPages }\n };\n }\n\n return data;\n }\n\n private async _doSearch<T = any>(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n searchQuery: string,\n filter: FilterQuery<any> = {},\n options: RepositoryOptions & { searchOptions: { fieldsToSearch?: string[]; page?: number; limit?: number; sort?: any} }\n ): Promise<Resources_PaginatedResult<T>> {\n // Get session for transaction support\n const session = this.getNativeSession(options);\n\n // Search metadata must come from the same routed operation that controls\n // response projection. Falling back to a default SEARCH is only for legacy\n // direct helper paths that did not carry the full operation object.\n const searchConfig = ResourceOperationsUtils.getCoreResourceOperationFromOperation(operation) === CoreResourceOperation.SEARCH\n ? operation\n : this.findSearchOperationConfiguration();\n\n if (!searchConfig) {\n const error = this.errorBuilder.buildError(\n ErrorType.NOT_FOUND,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_SEARCH_NOT_CONFIGURED,\n }\n );\n throw error;\n }\n\n const op = searchConfig as unknown as {\n isSearchable?: boolean;\n searchableFields?: SearchableFieldDescriptor[];\n maxPaginatedResultPerPageLimit?: number;\n };\n\n if (!op.isSearchable) {\n const error = this.errorBuilder.buildError( ErrorType.BUSINESS_RULE, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_SEARCH_NOT_ENABLED }\n );\n throw error;\n }\n\n const page = Math.max(1, options.searchOptions.page || 1);\n const maxLimit = op.maxPaginatedResultPerPageLimit || 50;\n const limit = Math.min(maxLimit, Math.max(1, options.searchOptions.limit || 20));\n const skip = (page - 1) * limit;\n\n this.logDebug('Searching resources with configuration', {\n searchQuery, filter, page, limit, maxLimit,\n searchableFields: op.searchableFields,\n isSearchable: op.isSearchable,\n hasTransaction: !!session\n });\n\n // Build advanced search filter using configuration. Async because relational\n // `searchableFields` entries resolve their `$in` ids via a secondary match on\n // the related resource's repository (see {@link constructSearchQuery}).\n const searchFilter = await this.constructSearchQuery(searchQuery, searchConfig);\n const validatedFilter = this.sanitizeRequestFilter(filter, searchConfig);\n const combinedFilter = { ...validatedFilter, ...searchFilter };\n // Scope-required reference search: when a junction-tagged scope param is\n // present (e.g. /organizations/{org}/users/search), intersect the result set\n // with the membership ids resolved through the junction. No-op otherwise.\n let contextualFilter = this.buildContextualFilter(executionContext, combinedFilter, CoreResourceOperation.SEARCH, options);\n contextualFilter = await this.applyJunctionScopeFilter(executionContext, contextualFilter);\n\n // Build sort options using configuration\n const sortOptions = this.constructValidatedSortOptions(options.searchOptions.sort, searchConfig);\n\n // Build projection from operation's responseDto\n const projection = this.buildMongoProjectionFromResponseDto(operation);\n\n // Prepare mongoose queries with projection and transaction session if provided\n let findQuery = this.mongooseModel\n .find(contextualFilter, projection)\n .sort(sortOptions)\n .skip(skip)\n .limit(limit);\n\n let countQuery = this.mongooseModel.countDocuments(contextualFilter);\n\n if (session) {\n findQuery = findQuery.session(session);\n countQuery = countQuery.session(session);\n }\n\n const [documents, total] = await Promise.all([\n findQuery.exec(),\n countQuery.exec()\n ]);\n\n const data = documents.map(doc => this.transformDocumentToResponse(doc, CoreResourceOperation.SEARCH));\n\n return {\n data,\n pagination: { page, limit, total, totalPages: Math.ceil(total / limit) }\n };\n }\n\n private async _doCount(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n filter: FilterQuery<any> = {},\n options?: RepositoryOptions\n ): Promise<{ count: number }> {\n const session = this.getNativeSession(options);\n this.logDebug('Counting resources', { filter, hasTransaction: !!session });\n\n // Scope-required reference search: mirror _doSearch so a junction-scoped\n // count matches the search it paginates. No-op when no junction tag present.\n let contextualFilter = this.buildContextualFilter(executionContext, filter, CoreResourceOperation.COUNT, options);\n contextualFilter = await this.applyJunctionScopeFilter(executionContext, contextualFilter);\n\n // Prepare count query with transaction session if provided\n let countQuery = this.mongooseModel.countDocuments(contextualFilter);\n\n if (session) {\n countQuery = countQuery.session(session);\n }\n\n const count = await countQuery.exec();\n\n this.logDebug('Count result', {\n filter: contextualFilter,\n count,\n hasTransaction: !!session\n });\n\n return { count };\n }\n\n // ================================\n // Helper Methods\n // ================================\n\n /**\n * Format a string ID for MongoDB queries.\n * Uses ResourceIdBackendService if available, falls back to direct ObjectId creation.\n *\n * @param id - The string ID to format\n * @returns The formatted ID (Types.ObjectId for MongoDB)\n */\n private formatIdForQuery(id: string): Types.ObjectId {\n if (this.resourceIdService) {\n return this.resourceIdService.formatForQuery(id) as Types.ObjectId;\n }\n // Fallback for backward compatibility when service not available\n return new Types.ObjectId(id);\n }\n\n /**\n * Utility function to build a base filter from IdOrIdsOrFilterType\n * @param id_or_ids_or_filter - The input parameter to process\n * @param executionContext - Execution context for error handling\n * @returns Object containing the base filter and whether it represents multiple items\n */\n private buildBaseFilterFromIdOrIdsOrFilter(\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n executionContext: ExecutionContext<any>\n ): { baseFilter: FilterQuery<any>; isMultiple: boolean } {\n let baseFilter: FilterQuery<any> = {};\n let isMultiple = false;\n\n if (!id_or_ids_or_filter) {\n return { baseFilter, isMultiple };\n }\n\n if (typeof id_or_ids_or_filter === 'string') {\n // Single ID\n baseFilter = { _id: this.formatIdForQuery(id_or_ids_or_filter) } as FilterQuery<any>;\n isMultiple = false;\n } else if (Array.isArray(id_or_ids_or_filter)) {\n // Multiple IDs\n if (id_or_ids_or_filter.length > 0) {\n const objectIds = id_or_ids_or_filter.map(singleId => this.formatIdForQuery(singleId));\n baseFilter = { _id: { $in: objectIds } } as FilterQuery<any>;\n }\n isMultiple = true;\n } else if (typeof id_or_ids_or_filter === 'object' && !Array.isArray(id_or_ids_or_filter)) {\n // Handle different object types\n if ('id_or_ids' in id_or_ids_or_filter) {\n // Combined object with id_or_ids and optional filter\n const { id_or_ids: ids, filter } = id_or_ids_or_filter;\n if (typeof ids === 'string') {\n baseFilter = { _id: this.formatIdForQuery(ids) } as FilterQuery<any>;\n isMultiple = false;\n } else if (Array.isArray(ids) && ids.length > 0) {\n const objectIds = ids.map(singleId => this.formatIdForQuery(singleId));\n baseFilter = { _id: { $in: objectIds } } as FilterQuery<any>;\n isMultiple = true;\n }\n // Merge additional filter if present\n if (filter && Object.keys(filter).length > 0) {\n baseFilter = { ...baseFilter, ...filter };\n isMultiple = true; // Combined filters usually imply multiple results\n }\n } else if ('id' in id_or_ids_or_filter) {\n // Single-id combined shape from `IdOrFilterType` ({ id, filter? }) — the shape the\n // read / update / delete SINGLE-entity callers pass (their input type advertises it).\n // Without this branch the object falls through to the raw-FilterQuery case below and\n // Mongo tries to match literal `id` / `filter` fields (never present on a document) →\n // a silent no-match that surfaces as a spurious NOT_FOUND. Mirrors the `id_or_ids`\n // branch but for the singular contract, so `isMultiple` stays false. (Uncovered by the\n // SIEM DLQ RETRY drains, which read `{ id: entryId, filter: <scope FK> }`.)\n const { id, filter } = id_or_ids_or_filter as { id: string; filter?: FilterQuery<any> };\n baseFilter = { _id: this.formatIdForQuery(id) } as FilterQuery<any>;\n isMultiple = false;\n if (filter && Object.keys(filter).length > 0) {\n baseFilter = { ...baseFilter, ...filter };\n }\n } else {\n // Direct FilterQuery object\n baseFilter = id_or_ids_or_filter as FilterQuery<any>;\n isMultiple = true; // Filter queries usually imply multiple results\n }\n } else {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED }\n );\n }\n\n return { baseFilter, isMultiple };\n }\n\n /**\n * Utility function to validate that id_or_ids_or_filter parameter is provided\n * @param id_or_ids_or_filter - The parameter to validate\n * @param executionContext - Execution context for error handling\n * @param operationName - Name of the operation for error messages\n */\n private validateIdOrIdsOrFilterRequired(\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n executionContext: ExecutionContext<any>,\n operationName: string,\n ): void {\n if (!id_or_ids_or_filter) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationName } } // diagnostic (log-only)\n );\n }\n }\n\n\n\n /**\n * Escapes special regex characters in search query to prevent regex injection\n * @param text - The text to escape\n * @returns Escaped text safe for regex\n */\n private escapeRegex(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n }\n\n\n\n /**\n * Extract projection fields from operation's responseDto for MongoDB field selection\n * @param operation - The operation to extract responseDto fields from\n * @returns MongoDB projection object or null if no responseDto is defined\n */\n private buildMongoProjectionFromResponseDto(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>\n ): Record<string, 1> | null {\n // Prefer repositoryDto over responseDto\n // repositoryDto excludes virtual fields and populated placeholders,\n // but includes virtual field dependencies\n const dtoToUse = operation.repositoryDto ?? operation.responseDto;\n\n if (!dtoToUse) {\n this.logDebug('No responseDto/repositoryDto found in operation, using full document projection');\n return null;\n }\n\n try {\n // Parse the DTO to extract field names\n const responseSchema = dtoToUse;\n\n // For Zod schemas, we can use the shape property to get field names\n if (responseSchema && typeof responseSchema === 'object' && 'shape' in responseSchema) {\n const shape = (responseSchema as any).shape;\n const projection: Record<string, 1> = {};\n\n Object.keys(shape).forEach(fieldName => {\n projection[fieldName] = 1;\n });\n\n // A surrogate primary key (e.g. FILES `fileId`) is a Mongoose VIRTUAL = String(_id),\n // not a stored column — Mongo cannot project it, and it resolves ONLY if `_id` is in\n // the returned document. The responseDto names the surrogate, not `_id`, so make the\n // dependency explicit: force `_id` into the projection for surrogate-PK resources.\n // Without this, a future projection that excluded `_id` would silently null the\n // surrogate on every read/list (the fileId virtual would read `String(undefined)`).\n const surrogatePrimaryKey = this.resourceOperationHelper.getSurrogatePrimaryKeyFieldName(\n this.resourceConfiguration.mainSchema,\n );\n if (surrogatePrimaryKey) {\n projection._id = 1;\n }\n\n this.logDebug('Built projection from responseDto', {\n operationIdentifier: operation.operationIdentifier,\n projectionFields: Object.keys(projection)\n });\n\n return projection;\n }\n\n // If we can't extract fields from the schema, fall back to full document\n this.logDebug('Unable to extract fields from responseDto, using full document projection', {\n operationIdentifier: operation.operationIdentifier,\n responseDtoType: typeof responseSchema\n });\n\n return null;\n } catch (error) {\n this.logDebug('Error extracting projection from responseDto, using full document', {\n operationIdentifier: operation.operationIdentifier,\n error: describeCaughtError(error)\n });\n\n return null;\n }\n }\n\n /**\n * System-level membership projection (scope-required reference search).\n *\n * Reads THIS resource's own collection for rows matching `{ [scopeFkField]:\n * scopeId }` and returns the distinct `targetFkField` values. Called on the\n * JUNCTION repo (e.g. `organizationMembers`) to resolve \"the user ids that are\n * members of org X\". A raw, lean, SYSTEM read by design — no operation auth, no\n * contextual filter — because the caller is ALREADY authorized for the scope\n * and this is an internal membership projection feeding\n * {@link applyJunctionScopeFilter}.\n */\n /**\n * Apply the M5a retention hide to a RAW projection filter (gate G-RAW).\n *\n * The id/value-projection reads below query `this.mongooseModel` DIRECTLY and therefore skip\n * `buildContextualFilter`, where retained rows are normally hidden. Without this, an\n * impersonalized-and-retained row would still contribute its id to a relational search match or a\n * scope resolution — surfacing, indirectly, a record that is supposed to be invisible.\n *\n * Fail-closed and unconditional: these are framework-internal projections, never the audited\n * see-through path (`read/listRetainedAsSystem`), so they take no EC suppression. No-op unless the\n * resource opted into `retentionPolicy` (factory-normalized to truthy ⟺ retention-governed).\n *\n * The predicate itself comes from the single retention authority — this method only decides WHETHER\n * it applies on this raw path.\n */\n private withRawRetentionHide(filter: Record<string, unknown>): Record<string, unknown> {\n if (!isRetentionGovernedResource(this.resourceConfiguration)) {\n return filter;\n }\n return withRetentionHideApplied(filter);\n }\n\n public async findScopeRelatedTargetIds(scopeFkField: string, scopeId: string, targetFkField: string): Promise<string[]> {\n const documents = await this.mongooseModel\n .find(this.withRawRetentionHide({ [scopeFkField]: scopeId }), { [targetFkField]: 1, _id: 0 })\n .lean()\n .exec();\n const ids = new Set<string>();\n for (const document of documents) {\n const value = (document as Record<string, unknown>)[targetFkField];\n // The junction FK is a Mongoose ObjectId and is read RAW here via `.lean()`,\n // which BYPASSES the toObject/toJSON string serialization — so `value` is an\n // ObjectId instance, not a string. Coerce to its hex string; the downstream\n // `_id ∈ {…}` $in re-casts per the target's own `_id` (ObjectId) on the\n // users query. (Without this, a `typeof === 'string'` guard skipped every\n // value → empty $in → the scoped search returned zero rows.)\n if (value !== undefined && value !== null) {\n const id = String(value);\n if (id.length > 0) {\n ids.add(id);\n }\n }\n }\n return [...ids];\n }\n\n /**\n * Relational-search match projection (OR-match sibling of the AND-scope\n * {@link findScopeRelatedTargetIds}).\n *\n * Runs THIS resource's OWN searchable surface — regex across its configured\n * SEARCH `searchableFields` (string entries), or the `fields` override — against\n * `searchQuery`, and returns the distinct `joinField` values of the matching\n * rows, bounded by an internal cap. A raw, lean, SYSTEM read by design (no\n * operation auth, no contextual filter): the CALLER folds these ids into an\n * `$in` on its OWN already-scoped collection, so an unscoped match here can\n * never widen the caller's scoped result set (see {@link SearchableRelationDescriptor}).\n *\n * Returns [] — contributing no branch — when the query is blank or this resource\n * exposes no usable searchable fields; failing to ADD a match never leaks.\n *\n * @param searchQuery - The caller's search query string\n * @param joinField - Field whose values to collect (default `_id`); pass a shared\n * non-PK key (e.g. `userId`) when the caller joins on that instead of `_id`\n * @param options.fields - Override the fields to match (else this resource's own\n * string `searchableFields`)\n */\n public async findSearchMatchTargetIds(\n searchQuery: string,\n joinField: string,\n options?: { fields?: string[] }\n ): Promise<string[]> {\n if (!searchQuery?.trim()) {\n return [];\n }\n\n // Bound the candidate set so a broad term can't build an unbounded `$in`.\n // Tenant safety is unaffected (the caller's query stays scoped); this caps\n // perf / `$in` size only. Org-scale relations sit well under this.\n const MATCH_ID_CAP = 1000;\n\n const searchConfig = this.findSearchOperationConfiguration();\n const op = searchConfig as unknown as { searchableFields?: SearchableFieldDescriptor[]; searchableOptions?: CollectionView_SearchOptions } | null;\n\n // Default to THIS resource's own string searchable fields — \"use the juncted\n // element's search\" — unless the caller pins an explicit field subset.\n const ownStringFields = (op?.searchableFields ?? []).filter((field): field is string => typeof field === 'string');\n const fields = options?.fields && options.fields.length > 0 ? options.fields : ownStringFields;\n if (fields.length === 0) {\n this.logDebug('findSearchMatchTargetIds: no searchable fields resolved for relational match', {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n });\n return [];\n }\n\n const conditions = this.buildFieldSearchConditions(searchQuery, fields, op?.searchableOptions);\n const matchFilter: FilterQuery<any> = conditions.length > 1 ? { $or: conditions } : conditions[0];\n\n const projection = joinField === '_id' ? { _id: 1 } : { [joinField]: 1, _id: 0 };\n // Top-level AND with the retention hide: a retained row must not contribute a search match, even\n // though `matchFilter` may itself be an `$or` of field conditions.\n const documents = await this.mongooseModel\n .find(this.withRawRetentionHide(matchFilter as Record<string, unknown>), projection)\n .limit(MATCH_ID_CAP + 1)\n .lean()\n .exec();\n\n if (documents.length > MATCH_ID_CAP) {\n this.logDebug('findSearchMatchTargetIds: related match set truncated to cap', {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n cap: MATCH_ID_CAP,\n });\n }\n\n const ids = new Set<string>();\n for (const document of documents.slice(0, MATCH_ID_CAP)) {\n const value = (document as Record<string, unknown>)[joinField];\n // `.lean()` returns the FK raw: a string FK stays a string, an ObjectId FK is\n // an ObjectId instance. Coerce to its string form; the caller's `$in` re-casts\n // against its own join field type (mirrors findScopeRelatedTargetIds).\n if (value !== undefined && value !== null) {\n const id = String(value);\n if (id.length > 0) {\n ids.add(id);\n }\n }\n }\n return [...ids];\n }\n\n /**\n * Read-direction sibling of {@link findSearchMatchTargetIds} (and\n * {@link findScopeRelatedTargetIds}): given a set of join-key VALUES, return the\n * matching rows projected to `fields`, keyed by the (stringified) join value.\n *\n * Raw, lean, SYSTEM read by design — no operation auth, no contextual filter —\n * mirroring the relational-search tenant-safety contract in REVERSE: the CALLER\n * only ever passes join values that appear on rows it can ALREADY see (its own\n * already-scoped page), so resolving the related rows system-side can never\n * widen visibility. Powers label forwarding (`forwardedLabel` in\n * `@wildo-ai/saas-models`), which renders a junction row's \"other party\" fields\n * (e.g. a member's user-profile name) for display WITHOUT denormalizing them.\n *\n * Returns an empty Map when `joinValues` or `fields` is empty (nothing to\n * resolve / render). When a join value matches multiple related rows, the first\n * encountered wins — label joins are expected 1:1 on the join key (e.g. one\n * user_profile per `userId`).\n *\n * @param joinField - Related field matched against `joinValues` (e.g. `userId`); `_id` joins on the primary key\n * @param joinValues - Join values to resolve (typically one page's worth); de-duplicated internally\n * @param fields - Related fields to project (the caller renders them into the label)\n */\n public async findFieldValuesByJoinField(\n joinField: string,\n joinValues: string[],\n fields: string[],\n ): Promise<Map<string, Record<string, unknown>>> {\n const result = new Map<string, Record<string, unknown>>();\n\n const distinctValues = [...new Set(joinValues.filter((value) => typeof value === 'string' && value.length > 0))];\n if (distinctValues.length === 0 || fields.length === 0) {\n return result;\n }\n\n // Bound the related read. One page's worth of distinct join keys sits well\n // under this; the cap only protects against a pathologically large page.\n const MATCH_ID_CAP = 1000;\n\n // Retention hide: a retained row must not supply rendered field VALUES to a label/summary join —\n // that would leak the very data the scrub removed from view.\n const matchFilter: FilterQuery<any> = this.withRawRetentionHide({ [joinField]: { $in: distinctValues } });\n\n // Project the join field (to key the result) plus the rendered fields. Mongo\n // allows excluding `_id` alongside an inclusion projection — drop it unless we\n // are joining on it OR a caller actually wants `_id` rendered (`'_id' in\n // projection` after the inclusion loop), else the exclusion would silently\n // override a requested `_id: 1`.\n const projection: Record<string, 0 | 1> = { [joinField]: 1 };\n for (const field of fields) {\n projection[field] = 1;\n }\n if (joinField !== '_id' && !('_id' in projection)) {\n projection._id = 0;\n }\n\n const documents = await this.mongooseModel\n .find(matchFilter, projection)\n .limit(MATCH_ID_CAP)\n .lean()\n .exec();\n\n for (const document of documents) {\n const record = document as Record<string, unknown>;\n const rawKey = record[joinField];\n // `.lean()` returns the join key raw (string stays a string, ObjectId stays\n // an ObjectId). Stringify to match the caller's stringified join value.\n if (rawKey === undefined || rawKey === null) {\n continue;\n }\n const key = String(rawKey);\n if (key.length > 0 && !result.has(key)) {\n result.set(key, record);\n }\n }\n\n return result;\n }\n\n /**\n * Apply scope-required reference-search scoping (Phase 2 of\n * `.claude/plans/fk-filter-reference-search.md`).\n *\n * When a relationship context carries a `scopeViaJunction` tag — set ONLY on\n * the synthetic peer-under-scope param of a route like\n * `/organizations/{organizationId}/users/search` — the target resource (e.g.\n * `users`) has NO column for the scope, so it is scoped THROUGH the junction:\n * `T._id ∈ { J.targetFk : J.scopeFk = scopeId }`. The junction + its two FK\n * columns come from the Phase-1 `manyToManyScopeJunctions` registry map,\n * cross-checked against the runtime tag. No-op when no tagged context is\n * present (every normal search). Composes with any existing constraint via\n * `$and`.\n *\n * SECURITY: fail-closed. If the tag is present but the junction/repo can't be\n * resolved, intersect with an EMPTY id set rather than returning the unscoped\n * collection — a missing mapping must never widen visibility.\n *\n * Q2 (LOCKED): membership-first `$in`; the large-org `$lookup`-aggregation\n * optimization is deferred (bounded by org-membership size + paginated).\n */\n private async applyJunctionScopeFilter(\n executionContext: ExecutionContext<any>,\n filter: FilterQuery<any>,\n ): Promise<FilterQuery<any>> {\n return applyJunctionScopeFilter({\n filter,\n relationshipContexts: executionContext.relationshipContexts as any,\n targetResourceType: this.resourceConfiguration.resourceIdentifier as ResourceType,\n manyToManyScopeJunctions: this.resourceRegistry.getResourcesRegistry().manyToManyScopeJunctions as any,\n getJunctionRepository: (junctionResourceType) =>\n this.repositoriesRegistry.getRepository(junctionResourceType) as any,\n });\n }\n\n /**\n * Build contextual filter based on execution context with schema validation and blacklist support\n * @param executionContext - The execution context containing resource IDs\n * @param baseFilter - The base filter to enhance with context\n * @param options - Repository options containing exclusion rules\n * @returns Enhanced filter with context information\n */\n private buildContextualFilter(\n executionContext: ExecutionContext<any>,\n baseFilter: FilterQuery<any>,\n /**\n * The core operation THIS repository call is executing — NOT `executionContext.operation`. The\n * retention authority classifies it to decide whether a see-through EC may suppress the hide\n * (read-family only); see `assignRetentionHideForOperation`.\n */\n executedCoreOperation: CoreResourceOperation,\n options?: RepositoryOptions,\n ): FilterQuery<any> {\n // Translate the date-range filter vocabulary (`{ startDate?, endDate? }`, reconstructed by the\n // collection-query controller for a `z.date()` filter field) into `{ $gte?, $lte? }` BEFORE the\n // filter reaches mongoose — otherwise mongoose casts the whole `{startDate,endDate}` object to a\n // Date and throws `CastError`. No-op for filters without range vocabulary. This is the Mongo half\n // of the shared normalization; the PG adapter calls the SAME helper in its `buildContextualFilter`.\n const contextualFilter = normalizeDateRangeFilters({ ...baseFilter });\n\n // ── M5a: retention hide predicate (privacy boundary) ──────────────────────────────────────\n // For a retention-governed resource, hide impersonalized-and-retained rows from normal callers.\n // This chokepoint is SHARED by the read paths AND the write paths (`_doUpdate/_doUpdateMany/\n // _doDelete/_doDeleteMany` all filter on it), so a retained row becomes hidden on read AND\n // immutable to a normal write in one place — the intended \"kept but frozen\" state.\n //\n // The predicate, the governance test and the see-through suppression rule all live in the single\n // retention authority; this site only chooses WHERE the rule is applied. Two placement facts are\n // load-bearing and are the reason this call sits exactly here:\n // - BEFORE the `options.excludeContextualFilter` early-return ON PURPOSE. That flag bypasses\n // SCOPE — a DIFFERENT axis — so scope-bypass callers (anonymous-session, guidance evaluators,\n // features admin) must NOT thereby see or mutate retained rows.\n // - It writes at the TOP LEVEL of the filter, OVERWRITING any caller-supplied `retentionStatus`\n // (fail-closed). A caller who injects `retentionStatus: RETAINED` — e.g. a SEARCH whose\n // operation declares no `filterFields`, so `sanitizeRequestFilter` passes the raw client\n // filter through — is NEUTRALISED rather than honoured. A genuine compliance auditor targets\n // retained rows through the see-through path, which suppresses the hide entirely and so\n // PRESERVES their `retentionStatus` filter.\n assignRetentionHideForOperation(\n contextualFilter,\n this.resourceConfiguration,\n executionContext,\n executedCoreOperation,\n );\n\n // Check if contextual filtering should be excluded\n if (options?.excludeContextualFilter === true) {\n // Skip all contextual filtering if explicitly disabled\n this.logDebug('Contextual filtering disabled, returning base filter only');\n return contextualFilter;\n }\n\n // Determine blacklisted fields\n const blacklistedFields = new Set<string>();\n\n // Always exclude the resource's own resourceFieldIdentifier to avoid self-reference in filtering\n blacklistedFields.add(this.resourceConfiguration.resourceFieldIdentifier);\n\n // Add custom blacklisted fields if provided\n if (Array.isArray(options?.excludeContextualFilter)) {\n options.excludeContextualFilter.forEach(field => blacklistedFields.add(field));\n }\n\n // Scope-required reference search — the SKIP half. Its resolving half runs in\n // `_doSearch`/`_doCount`; the two must travel together, which is why they share a module.\n const junctionScopedFieldIdentifiers = collectJunctionScopedFieldIdentifiers({\n relationshipContexts: executionContext.relationshipContexts,\n allResourceFieldIdentifiers: this.resourceRegistry?.getResourcesRegistry()?.allResourceFieldIdentifiers,\n });\n\n // Add context resource filters (with nested path support, schema validation and blacklist filtering)\n const contextResourceIds = executionContext.getContextResourceIds();\n contextResourceIds.forEach((resourceId, fieldIdentifier) => {\n // Skip if field is blacklisted\n if (blacklistedFields.has(fieldIdentifier)) {\n this.logDebug('Skipping blacklisted field in contextual filter', { fieldIdentifier });\n return;\n }\n // Skip junction-scoped scope params — resolved via applyJunctionScopeFilter.\n if (junctionScopedFieldIdentifiers.has(fieldIdentifier)) {\n this.logDebug('Skipping junction-scoped field in contextual filter (resolved through junction)', { fieldIdentifier });\n return;\n }\n\n // A resource's PRIMARY-SCOPE FK is not always modeled in its Zod main schema, and that is\n // legitimate rather than an authoring mistake:\n //\n // - a schema SHARED across scopes cannot author one — `ScopeFeaturesWithOverridesSchema`\n // backs ORGANIZATION_FEATURES, APPLICATION_FEATURES and USER_FEATURES, each with a\n // different scope FK, so the column comes from the relationship's `foreignKeyField`;\n // - scope-AUGMENTED resources add the column at the persistence layer (the\n // `auditLogs.applicationId` case already documented on the write path below).\n //\n // The WRITE path accounts for this: `enrichDataWithContextFields` deliberately uses the\n // NON-throwing lookup and injects the scope field at the TOP LEVEL when the Zod schema does\n // not model it. The FILTER path used the throwing lookup, so the two disagreed about which\n // fields a scoped resource has — and filtering such a resource threw CONFIGURATION.\n //\n // Concretely (2026-08-04): deleting an ORGANIZATION cascades to ORGANIZATION_FEATURES, and\n // building that child's filter threw whenever the request context carried an `organizationId`.\n // An org-scoped request therefore could NOT delete a tenant at all — a 500 with the whole\n // transaction rolled back — while the `organization-purge` batch succeeded, because its\n // internal context carries no org and never reached this branch.\n //\n // FAIL-CLOSED IS PRESERVED. Only this resource's OWN primary-scope field identifier may\n // resolve to a top-level column, and only when the schema genuinely does not model it.\n // Every other unmodeled context field still throws: silently dropping an unrecognised context\n // filter would widen a query beyond its tenant, which is a far worse failure than a 500.\n const primaryScopeFieldIdentifier = this.resourceConfiguration.resourcePrimaryScope\n ? PRIMARY_SCOPE_TO_FIELD_IDENTIFIER[this.resourceConfiguration.resourcePrimaryScope]\n : undefined;\n if (\n fieldIdentifier === primaryScopeFieldIdentifier\n && this.resourceOperationHelper.findNestedFieldPathsFromZodSchema(\n this.resourceConfiguration.mainSchema,\n fieldIdentifier,\n ).length === 0\n ) {\n // Scoped resources always carry their scope FK as a top-level column — the same invariant\n // the write-path injection relies on, so the filter targets exactly what the write wrote.\n // The context value is AUTHORITATIVE: a caller-supplied value that disagrees is refused,\n // never deferred to. See `applyAuthoritativeContextFilterValue` for why this is one shared\n // authority rather than four look-alike branches.\n this.resourceOperationHelper.applyAuthoritativeContextFilterValue(\n contextualFilter, fieldIdentifier, resourceId,\n { fieldIdentifier, resourceIdentifier: String(this.resourceConfiguration.resourceIdentifier) },\n );\n return;\n }\n\n // Find all schema paths that end with this field identifier (including nested paths)\n const matchingPaths = this.resourceOperationHelper.findRequiredNestedFieldPathsFromZodSchema(\n this.resourceConfiguration.mainSchema,\n fieldIdentifier,\n executionContext,\n {\n reason: 'context_filter',\n resourceIdentifier: this.resourceConfiguration.resourceIdentifier,\n message: `Execution context field '${fieldIdentifier}' is missing from schema for resource '${this.resourceConfiguration.resourceIdentifier}' during contextual filtering`,\n }\n );\n\n // Process each matching path\n matchingPaths.forEach(fullPath => {\n // A surrogate primary key (e.g. FILES `fileId`) exists in the Zod schema but is stored\n // only as Mongo `_id` (a read-only virtual projection), so a filter keyed on it would\n // silently match nothing. Resolve to the queryable key (`_id` for a surrogate PK,\n // unchanged for every other field).\n const filterPath = this.resourceOperationHelper.resolveQueryableFilterPath(\n this.resourceConfiguration.mainSchema,\n fullPath,\n );\n // The context value is AUTHORITATIVE. This branch previously SKIPPED when the caller had\n // already supplied the path, which is how a tool call carrying another tenant's\n // `organizationId` was answered with that tenant's rows.\n this.resourceOperationHelper.applyAuthoritativeContextFilterValue(\n contextualFilter, filterPath, resourceId,\n { fieldIdentifier, resourceIdentifier: String(this.resourceConfiguration.resourceIdentifier) },\n );\n });\n });\n\n // D3 — initiator-organization confinement, previously PostgreSQL-only.\n // Mongo has no column plan, so every schema-modelled field is persisted by definition and\n // the persistence predicate is always true; the RULE is identical, which is the point of it\n // living in one place.\n assignInitiatorOrganizationConfinementToFilter({\n filter: contextualFilter,\n executionContext,\n blacklistedFields,\n mainSchema: this.resourceConfiguration.mainSchema,\n schemaPaths: this.resourceOperationHelper,\n isFieldPersisted: () => true,\n });\n\n // Defense-in-depth: enforce userId = null for ANONYMOUS scope on isAnonymizable resources.\n // Prevents any anonymous query from seeing authenticated users' data even if scoping is bypassed.\n //\n // THIS PREDICATE IS PRESENCE-BLIND, and stays correct only because of a declaration elsewhere.\n // MongoDB documents `{ field: null }` as matching documents where the field is null OR where it\n // is ABSENT, so this equality alone cannot tell \"anonymous\" from \"no userId key at all\" — and\n // absence is a reachable stored state now that clearing an optional field removes it.\n // What keeps it sound: `isAnonymizable` REQUIRES `userId` to accept null (config-time\n // `safeParse(null)` probe in the resource factory), so the field is authored nullable, the\n // field-clearing partition stores a literal null for it rather than removing it, and the\n // repository writes that null explicitly. Every such row therefore HAS the key.\n // If `userId` on an anonymizable resource is ever made merely `.optional()`, this filter starts\n // matching rows that never had a userId, and must move to an explicit presence predicate.\n if (executionContext.isAnonymousExecution() && this.resourceConfiguration.isAnonymizable) {\n const userPaths = this.resourceOperationHelper.findNestedFieldPathsFromZodSchema(\n this.resourceConfiguration.mainSchema, 'userId'\n );\n userPaths.forEach(fullPath => {\n this.resourceOperationHelper.setNestedValue(contextualFilter, fullPath, null);\n });\n }\n\n // Apply FK relationship filters from relationship contexts\n // This handles cases like /assigned-to-users/{userId}/todos where we need to filter by assignedToUserId\n this.applyFKRelationshipFilters(executionContext, contextualFilter, blacklistedFields);\n\n // ── WS-C: organization-unit narrowing (authorization boundary) ────────────────────────────────\n // Confines a caller whose authority for this resource came ONLY from a unit grant to the rows of\n // those units, reading the decision the authorization gate already stamped on the context.\n //\n // Three placement facts are load-bearing:\n // - AFTER the `options.excludeContextualFilter` early-return, unlike the retention hide above. A\n // unit narrows WITHIN the organization scope (D-C1), so it belongs to the SCOPE axis: a caller\n // who deliberately bypasses scope already crosses the tenant boundary, which is strictly wider\n // than crossing a unit boundary inside one tenant.\n // - LAST, writing at the TOP LEVEL, so a caller-supplied value for the unit field is OVERWRITTEN\n // rather than honoured — the same fail-closed reasoning as the retention hide.\n // - FAIL-CLOSED on a missing decision: a narrowed resource reached without one was reached around\n // the authorization layer, and the authority answers that with no rows, never all rows.\n assignOrganizationUnitNarrowingToFilter(\n contextualFilter,\n this.resourceConfiguration.resourceIdentifier,\n this.resourceRegistry?.getResourcesRegistry()?.organizationUnitNarrowing,\n executionContext,\n );\n\n // ── Scope-ROOT collection confinement (tenant boundary) ───────────────────────────────────────\n // The tenant resource itself carries no `organizationId` column, so every confinement above\n // loses the axis on it: the context loop skips the field (blacklisted as this resource's own\n // identifier) and D3 refuses for the same blacklist. Measured: a scope-root LIST compiled to the\n // EMPTY filter on both adapters. One authority, both adapters — a tenancy predicate present here\n // and absent on the PostgreSQL sibling would be a bypass, not a gap.\n //\n // Placement matches the unit narrowing and D3, not the retention hide: this is the SCOPE axis, so\n // a caller who deliberately bypassed scope via `excludeContextualFilter` has already returned\n // above.\n assignScopeRootCollectionConfinementToFilter({\n filter: contextualFilter,\n executionContext,\n resourceConfiguration: this.resourceConfiguration,\n executedCoreOperation: executedCoreOperation,\n });\n\n return contextualFilter;\n }\n\n /**\n * Refuse a write whose unit-field value falls outside the caller's unit grant (WS-C).\n *\n * assurance-control: WILDO.ACCESS.SCOPE_CONFINEMENT — least-privilege confinement on the WRITE side.\n *\n * A row filter cannot constrain a CREATE (there is no row yet) and does not constrain the VALUES an\n * UPDATE writes, so without this a caller confined to one unit could create rows in another unit, or\n * move an existing row out of their own — and every later read would correctly exclude those rows,\n * making the escalation invisible from the very surface meant to contain it.\n *\n * `executedCoreOperation` is the write THIS call performs, not `executionContext.operation`: the\n * rule differs between row-creating and updating writes (a create must supply a unit, an update may\n * omit it), and the repository's own write methods never `withOperation()` the context.\n */\n /**\n * TENANT COHERENCE on the narrowing dimension — the half the grant check structurally cannot cover.\n *\n * `resolveOrganizationUnitNarrowingWriteViolation` returns early for an `UNRESTRICTED` caller, which\n * is correct for the GRANT question (an organization-wide principal is not confined) but leaves the\n * VALUE unexamined. So an organization-wide admin could name any unit id at all — including one\n * belonging to ANOTHER TENANT. The row stays inside its own tenant, so nothing crosses; what it\n * becomes is an orphan pointing at a unit nobody in its tenant can hold, therefore confined to a\n * grant that cannot exist and visible only to organization-wide callers. Found by the hostile lane's\n * X-2 probe, which is why that probe reports the DATABASE and not just the status.\n *\n * The check is a SCOPED read: `readForInternalScan` applies the contextual scope filter (so the unit\n * must be in the caller's organization) without depending on a user-facing READ operation on\n * `ORGANIZATION_UNITS` — a plain `read()` would couple this write to that resource's operation\n * vocabulary and to the caller's `relationshipContexts`, which is the documented way cross-resource\n * reads on a borrowed execution context turn into 500s.\n *\n * Not found and belongs-to-another-tenant answer identically on purpose: a write payload must not\n * become a probe into another tenant's org chart.\n */\n private async assertOrganizationUnitBelongsToCallerTenant(\n payload: unknown,\n executedCoreOperation: CoreResourceOperation,\n executionContext: ExecutionContext<any>,\n ): Promise<void> {\n const suppliedUnitId = resolveSuppliedOrganizationUnitIdForTenantCheck(\n payload as Record<string, unknown> | null | undefined,\n this.resourceConfiguration.resourceIdentifier,\n this.resourceRegistry?.getResourcesRegistry()?.organizationUnitNarrowing,\n );\n if (!suppliedUnitId) return;\n\n // An exempt execution type never carries a unit grant and is trusted by the scope filter too, so\n // holding it to a tenant read here would fail closed on batches and webhooks for no gain.\n if (isOrganizationUnitNarrowingExemptExecution(executionContext.executionType)) return;\n\n const unitRepository = this.repositoriesRegistry?.getRepository(CoreResourceType.ORGANIZATION_UNITS);\n // An application that never registered organization units cannot have a unit to point at, so there\n // is nothing to verify — an accurate answer rather than a swallowed error.\n if (!unitRepository) return;\n\n // `excludeContextualFilter: true` + an EXPLICIT tenant comparison, rather than letting the\n // contextual filter do it. Borrowing the caller's execution context for a read of a DIFFERENT\n // resource is the documented way to produce a 500: that context carries THIS resource's field\n // identifier, and `buildContextualFilter` fails closed on `organizationUnits` with\n // \"Execution context field 'teamGoalId' is missing from schema\" (reason `context_filter`).\n // Observed exactly that before this line existed.\n //\n // Nothing is weakened by the bypass — the scope question is simply asked here instead, against the\n // tenant the ROW is being written into (falling back to the caller's own), which is the same\n // comparison `authorizeOrganizations` makes for a fetched row. The retention hide is unaffected:\n // it is applied BEFORE that early-return by design.\n const unit = await unitRepository.readForInternalScan(\n executionContext as never,\n { _id: suppliedUnitId },\n { excludeContextualFilter: true },\n );\n\n const writeTenantId = String(\n (payload as Record<string, unknown> | null | undefined)?.organizationId\n ?? executionContext.initiatorIds?.organizationId\n ?? '',\n );\n const unitTenantId = String((unit as { organizationId?: unknown } | null)?.organizationId ?? '');\n\n // Three ways to reach the refusal below, and the third is a DECISION rather than an oversight:\n // 1. no such unit anywhere — `unit` is null\n // 2. the unit belongs to another tenant — the ids differ\n // 3. the write's tenant is undeterminable — `writeTenantId` is empty\n //\n // (3) fails CLOSED deliberately. A unit-narrowed resource is organization-scoped by construction\n // (a unit belongs to an organization), so a write that carries no tenant on the payload and whose\n // principal has none either cannot have its unit reference verified at all — and this module's\n // governing rule is that an inability to verify must never read as permission. Exempt execution\n // types were already returned above, so this does not catch batches, cascades or webhooks.\n //\n // Do not \"simplify\" the emptiness test away: it looks like a defensive string check and is\n // actually the third branch.\n if (unit && writeTenantId && unitTenantId === writeTenantId) return;\n\n throw this.errorBuilder.buildError(ErrorType.AUTHORIZATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.AUTHORIZATIONS_ACCESS_DENIED,\n context: {\n reason: OrganizationUnitNarrowingWriteViolationReason.UNIT_OUTSIDE_TENANT,\n resourceIdentifier: this.resourceConfiguration.resourceIdentifier,\n executedCoreOperation,\n attemptedOrganizationUnitId: suppliedUnitId,\n },\n });\n }\n\n private async assertOrganizationUnitWriteWithinGrant(\n payload: unknown,\n executedCoreOperation: CoreResourceOperation,\n executionContext: ExecutionContext<any>,\n ): Promise<void> {\n await this.assertOrganizationUnitBelongsToCallerTenant(payload, executedCoreOperation, executionContext);\n\n const violation = resolveOrganizationUnitNarrowingWriteViolation(\n payload as Record<string, unknown> | null | undefined,\n executedCoreOperation,\n this.resourceConfiguration.resourceIdentifier,\n this.resourceRegistry?.getResourcesRegistry()?.organizationUnitNarrowing,\n executionContext,\n );\n if (!violation) return;\n\n throw this.errorBuilder.buildError(ErrorType.AUTHORIZATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.AUTHORIZATIONS_ACCESS_DENIED,\n context: {\n // diagnostic (log-only)\n reason: violation.reason,\n resourceIdentifier: this.resourceConfiguration.resourceIdentifier,\n executedCoreOperation,\n unitFieldName: violation.unitFieldName,\n grantedOrganizationUnitIds: violation.grantedOrganizationUnitIds,\n attemptedOrganizationUnitId: violation.attemptedOrganizationUnitId,\n },\n });\n }\n\n /**\n * Deps bundle handed to the ADAPTER-NEUTRAL write-integrity authority\n * (`resource-write-integrity.backend.ts`), on both CREATE and UPDATE. Both this MongoDB repository and\n * the PostgreSQL repository — separate classes, not an inheritance pair — pass the same shape, so the\n * FK-existence-in-scope, scope-via-junction-membership, and top-level-mainSchema-check invariants live\n * in ONE place and cannot become adapter-conditional.\n */\n private get writeIntegrityDeps(): ResourceWriteIntegrityDeps {\n return {\n resourceConfiguration: this.resourceConfiguration,\n resourceRegistry: this.resourceRegistry,\n repositoriesRegistry: this.repositoriesRegistry,\n errorBuilder: this.errorBuilder,\n };\n }\n\n /**\n * Apply FK relationship filters from ExecutionContext.relationshipContexts\n *\n * When a resource is accessed via a FK relationship path (e.g., /assigned-to-users/{userId}/todos),\n * this method adds the appropriate filter to ensure only resources matching the FK field are returned.\n *\n * For example:\n * - URL: /assigned-to-users/{userId}/todos\n * - relationshipContext: { resourceType: 'USERS', relationshipField: 'assignedToUserId', resourceId: '123' }\n * - Filter added: { assignedToUserId: '123' }\n */\n private applyFKRelationshipFilters(\n executionContext: ExecutionContext<any>,\n filter: FilterQuery<any>,\n blacklistedFields: Set<string>\n ): void {\n assignRelationshipForeignKeyFiltersToFilter({\n filter,\n executionContext,\n blacklistedFields,\n resourceIdentifier: String(this.resourceConfiguration.resourceIdentifier),\n mainSchema: this.resourceConfiguration.mainSchema,\n schemaPaths: this.resourceOperationHelper,\n });\n }\n\n\n\n /**\n * Check if a field exists in the mongoose model schema\n */\n private hasSchemaField(fieldName: string): boolean {\n if (!this.mongooseModel?.schema?.paths) {\n return false;\n }\n\n return this.mongooseModel.schema.paths[fieldName] !== undefined;\n }\n\n /**\n * Whether `error` is a Mongoose CastError (a query/value could not be cast to its field\n * type — e.g. a malformed or UUID-format string supplied for an ObjectId `_id`). On a READ\n * filter this means no document can match, so the caller treats it as not-found rather than\n * an INTERNAL error. Mongoose tags these with `name === 'CastError'`.\n */\n private isMongooseCastError(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { name?: unknown }).name === 'CastError'\n );\n }\n\n /**\n * Handle MongoDB errors and convert them to application-specific errors.\n * Specifically handles unique constraint violations (E11000 duplicate key error).\n *\n * A duplicate key resolves to the custom message reference the VIOLATED constraint declared\n * (`.isUnique({ conflictMessageReference })` / `.businessKeySet([...], { conflictMessageReference })`),\n * falling back to the generic {@link ErrorCustomMessageReference.UNIQUE_CONSTRAINT_VIOLATION}\n * when the resource named none or the violated index cannot be attributed unambiguously. Without\n * that, every duplicate on every resource reports the same code and an integrator has to parse a\n * database message to learn which identity was rejected.\n *\n * @param error - The error caught from MongoDB operation\n * @param executionContext - The execution context for error building\n * @returns The original error or a transformed application error\n */\n private handleMongoDBError(error: unknown, executionContext?: ExecutionContext<any>): Error | WildoError_Backend {\n // Check for MongoDB duplicate key error (E11000)\n const isMongoError = error && typeof error === 'object' && 'code' in error;\n\n if (isMongoError && (error as any).code === 11000) {\n // Extract field name from the error message\n // MongoDB error message format: \"E11000 duplicate key error collection: db.collection index: fieldName_1 dup key: { fieldName: \"value\" }\"\n const errorMessage = (error as any).message || '';\n const keyValueMatch = errorMessage.match(/dup key: \\{ ([^:]+):/);\n const fieldName = keyValueMatch ? keyValueMatch[1].trim() : 'unknown';\n\n // Extract the duplicate value if present\n const valueMatch = errorMessage.match(/dup key: \\{ [^:]+: \"([^\"]+)\" \\}/);\n const duplicateValue = valueMatch ? valueMatch[1] : undefined;\n\n const violatedFieldNames = this.extractViolatedUniqueIndexFields(error, errorMessage);\n const declaredConflictReference = resolveDeclaredUniqueConflictReference(\n this.resourceConfiguration.mainSchema as any,\n violatedFieldNames,\n );\n\n return this.errorBuilder.buildError(\n ErrorType.CONFLICT,\n executionContext,\n {\n customMessageReference: declaredConflictReference ?? ErrorCustomMessageReference.UNIQUE_CONSTRAINT_VIOLATION,\n context: {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n fieldName,\n duplicateValue,\n violatedFields: violatedFieldNames,\n originalError: errorMessage\n }\n }\n );\n }\n\n // Return the original error if not a unique constraint violation\n return error instanceof Error ? error : new Error(describeCaughtError(error));\n }\n\n /**\n * Every field covered by the unique index a duplicate-key error violated.\n *\n * `keyPattern` is the structured, driver-supplied answer and is preferred whenever present. The\n * message fallback exists because the field is not guaranteed across driver versions and error\n * wrappers, and losing attribution there would silently downgrade every conflict on the resource\n * back to the generic code — a regression that no test would notice, since the generic code is a\n * legitimate outcome. The message form is `index: a_1_b_1 dup key: …`, whose `_1` / `_-1`\n * direction suffixes are stripped to recover the field names.\n *\n * Returns `[]` when neither source yields anything, which the caller treats as \"unattributable\".\n */\n private extractViolatedUniqueIndexFields(error: unknown, errorMessage: string): string[] {\n const keyPattern = (error as { keyPattern?: unknown })?.keyPattern;\n if (keyPattern && typeof keyPattern === 'object') {\n return Object.keys(keyPattern as Record<string, unknown>);\n }\n\n const indexNameMatch = errorMessage.match(/index:\\s+(\\S+)\\s+dup key:/);\n const indexName = indexNameMatch?.[1];\n if (!indexName) {\n return [];\n }\n // `a_1_b_-1` → ['a', 'b']. A field name may itself contain underscores, so the split is on the\n // direction segments rather than on every underscore.\n return indexName\n .split(/_-?1(?:_|$)/)\n .map((segment) => segment.trim())\n .filter((segment) => segment.length > 0);\n }\n\n\n /**\n * Add user tracking to enriched data (timestamps are handled automatically by MongoDB)\n * @param enrichedData - The data to add user tracking to\n * @param executionContext - The execution context containing user info\n * @param operation - The operation being performed\n * @returns Data with user tracking added\n */\n private addUserTracking(enrichedData: any, executionContext: ExecutionContext<any>, operation?: CoreResourceOperation): any {\n // Note: createdAt and updatedAt timestamps are handled automatically by MongoDB, so we don't add them here\n\n // Add operation-specific user tracking if userId is available in execution context\n const userId = executionContext.initiatorIds?.userId;\n if (userId) {\n\n // For CREATE operations: populate createdByUserId if field exists in database schema\n if (operation === CoreResourceOperation.CREATE || operation === CoreResourceOperation.CREATE_MANY) {\n if (this.hasSchemaField('createdByUserId') && !enrichedData.createdByUserId) {\n enrichedData.createdByUserId = userId;\n }\n }\n\n // For UPDATE operations: populate updatedByUserId or lastUpdatedByUserId if field exists in database schema\n if (operation === CoreResourceOperation.UPDATE || operation === CoreResourceOperation.UPDATE_MANY) {\n // Try updatedByUserId first, then lastUpdatedByUserId as fallback\n if (this.hasSchemaField('updatedByUserId') && !enrichedData.updatedByUserId) {\n enrichedData.updatedByUserId = userId;\n } else if (this.hasSchemaField('lastUpdatedByUserId') && !enrichedData.lastUpdatedByUserId) {\n enrichedData.lastUpdatedByUserId = userId;\n }\n }\n }\n\n return enrichedData;\n }\n\n /**\n * Transform mongoose document to response format using operation DTO\n */\n private transformDocumentToResponse<T = undefined>(document: any, operationIdentifier: string): T extends undefined ? any : T {\n if (!document) {\n return null;\n }\n\n // Convert mongoose document to plain object with error handling\n let plainObject: any;\n try {\n plainObject = document.toObject ? document.toObject() : document;\n } catch (error) {\n this.logDebug('Document toObject() failed, using document as-is', {\n operationIdentifier,\n error: describeCaughtError(error)\n });\n plainObject = document;\n }\n\n plainObject = normalizeRepositoryVersionMetadata(plainObject);\n\n // Transforming to response DTO is the role of the service layer\n return plainObject;\n\n }\n\n private previewDocument(document: any): any {\n if (!document) return null;\n const obj = document.toObject ? document.toObject() : document;\n // Limit preview size and hide potentially large fields\n const clone: any = { ...obj };\n Object.keys(clone).forEach((k) => {\n const v = clone[k];\n if (v && typeof v === 'object') {\n if (Array.isArray(v)) {\n clone[k] = `[Array(${v.length})]`;\n } else {\n clone[k] = '[Object]';\n }\n }\n });\n return clone;\n }\n // ================================\n // Search Configuration Methods\n // ================================\n\n /**\n * Retrieves the default search operation configuration for direct helper paths.\n * Routed execution uses the concrete SEARCH variant passed into `_doSearch`,\n * because collection-view metadata and response projection must stay aligned.\n */\n private findSearchOperationConfiguration(): ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> | null {\n const searchOperations = Array.from(this.operationsMap.values()).filter(\n operation => operation.operationIdentifier === CoreResourceOperation.SEARCH\n );\n const defaultSearchOperations = searchOperations.filter(\n operation => operation.isOperationDefault === true\n );\n if (defaultSearchOperations.length > 1) {\n this.logDebug('Ambiguous default SEARCH operation configurations', {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n candidateVariants: defaultSearchOperations.map((operation) => ({\n variantType: operation.variantType,\n variantKey: operation.variantKey,\n })),\n });\n return null;\n }\n return defaultSearchOperations[0] ?? searchOperations[0] ?? null;\n }\n\n /**\n * Constructs the MongoDB search filter from the query string and the\n * operation's `searchableFields`.\n *\n * `searchableFields` is a union list: plain field names match THIS collection by\n * regex (legacy behaviour); {@link SearchableRelationDescriptor} entries match\n * via a RELATED resource and resolve into a `{ [localField]: { $in: ids } }`\n * branch (see {@link buildRelationalSearchCondition}). Both forms OR together.\n *\n * - Empty query → `{}` (no search constraint; scope still applies upstream).\n * - No `searchableFields` configured → legacy `$text` index fallback.\n * - `searchableFields` configured but every branch resolves empty → a\n * never-match guard (`{ _id: { $in: [] } }`), NOT `{}`: a configured search\n * that matches nothing must return nothing, never the whole (scoped) collection.\n *\n * Async because relational branches resolve their ids via a secondary match on\n * the related resource's repository.\n *\n * @param searchQuery - The search query string\n * @param searchConfig - The routed SEARCH operation configuration\n * @returns MongoDB filter query for search\n */\n private async constructSearchQuery(\n searchQuery: string,\n searchConfig: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>\n ): Promise<FilterQuery<any>> {\n if (!searchQuery?.trim()) {\n return {};\n }\n\n const op = searchConfig as unknown as { searchableFields?: SearchableFieldDescriptor[]; searchableOptions?: CollectionView_SearchOptions };\n const searchableFields = op.searchableFields;\n const searchableOptions = op.searchableOptions;\n\n if (!searchableFields?.length) {\n return { $text: { $search: searchQuery } };\n }\n\n // Own-collection field names → regex conditions (legacy path).\n const ownFields = searchableFields.filter((field): field is string => typeof field === 'string');\n const searchConditions = this.buildFieldSearchConditions(\n searchQuery,\n ownFields,\n searchableOptions\n );\n\n // Relational entries → secondary match on the related resource, folded into an\n // `$in` branch on this collection's join field. Resolved in declared order.\n const relationDescriptors = searchableFields.filter(isSearchableRelationDescriptor);\n for (const descriptor of relationDescriptors) {\n const relationCondition = await this.buildRelationalSearchCondition(searchQuery, descriptor);\n if (relationCondition) {\n searchConditions.push(relationCondition);\n }\n }\n\n if (searchConditions.length === 0) {\n // `searchableFields` was non-empty (relational-only, and every related match\n // resolved to zero ids) → match NOTHING rather than the whole collection.\n return { _id: { $in: [] } };\n }\n\n return searchConditions.length > 1\n ? { $or: searchConditions }\n : searchConditions[0];\n }\n\n /**\n * Resolve one {@link SearchableRelationDescriptor} into a\n * `{ [localField]: { $in: ids } }` branch by running the related resource's own\n * searchable surface against `searchQuery` (see {@link findSearchMatchTargetIds}).\n *\n * Returns `null` — contributing no OR branch — when the related repository can't\n * be resolved or the related match set is empty. This is the correct fail-safe\n * for a MATCH branch: it only ever ADDS results within the caller's already\n * scoped+filtered set, so omitting it can never widen visibility — it merely\n * under-matches.\n */\n private async buildRelationalSearchCondition(\n searchQuery: string,\n descriptor: SearchableRelationDescriptor\n ): Promise<FilterQuery<any> | null> {\n const relatedRepository = this.repositoriesRegistry.getRepository(descriptor.relatedResource);\n if (!relatedRepository || typeof relatedRepository.findSearchMatchTargetIds !== 'function') {\n this.logDebug('Relational search branch skipped: related repository unavailable', {\n relatedResource: descriptor.relatedResource,\n localField: descriptor.localField,\n });\n return null;\n }\n\n const joinField = descriptor.relatedJoinField ?? '_id';\n const ids: string[] = await relatedRepository.findSearchMatchTargetIds(searchQuery, joinField, { fields: descriptor.fields });\n if (ids.length === 0) {\n return null;\n }\n\n return { [descriptor.localField]: { $in: ids } };\n }\n\n /**\n * Builds individual field search conditions based on searchable options\n * @param searchQuery - The search query string\n * @param searchableFields - Array of fields that can be searched\n * @param searchableOptions - Search behavior options\n * @returns Array of MongoDB field conditions\n */\n private buildFieldSearchConditions(\n searchQuery: string,\n searchableFields: string[],\n searchableOptions?: CollectionView_SearchOptions\n ): FilterQuery<any>[] {\n const caseSensitive = searchableOptions?.caseSensitive || false;\n const fullMatchOnly = searchableOptions?.fullMatchOnly || false;\n\n return searchableFields.map((field: string) => {\n if (fullMatchOnly) {\n return caseSensitive\n ? { [field]: searchQuery }\n : { [field]: { $regex: `^${this.escapeRegex(searchQuery)}$`, $options: 'i' } };\n } else {\n return caseSensitive\n ? { [field]: { $regex: this.escapeRegex(searchQuery) } }\n : { [field]: { $regex: this.escapeRegex(searchQuery), $options: 'i' } };\n }\n });\n }\n\n /**\n * Validates and filters the provided filter object against allowed filter fields configuration\n * @param requestedFilter - The filter object from the request\n * @param searchConfig - The search operation configuration\n * @returns Validated and sanitized filter object\n */\n private sanitizeRequestFilter(\n requestedFilter: FilterQuery<any>,\n searchConfig: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>\n ): FilterQuery<any> {\n if (!requestedFilter || Object.keys(requestedFilter).length === 0) {\n return {};\n }\n\n const { filterFields } = searchConfig as unknown as { filterFields?: Record<string, unknown> };\n\n // If no filter fields configured, return filter as-is (fallback behavior)\n if (!filterFields || Object.keys(filterFields).length === 0) {\n return requestedFilter;\n }\n\n // Only include fields that are explicitly allowed in the configuration\n const sanitizedFilter: FilterQuery<any> = {};\n\n Object.entries(requestedFilter).forEach(([fieldName, fieldValue]) => {\n if (filterFields[fieldName]) {\n sanitizedFilter[fieldName] = fieldValue;\n }\n // Note: Invalid fields are silently ignored for security\n });\n\n return sanitizedFilter;\n }\n\n /**\n * Constructs validated sort options based on allowed sort fields configuration\n * @param requestedSort - The sort object from the request\n * @param searchConfig - The search operation configuration\n * @returns Validated MongoDB sort object\n */\n private constructValidatedSortOptions(\n requestedSort: Record<string, 1 | -1> | undefined,\n searchConfig: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>\n ): Record<string, 1 | -1> {\n const { sortFields } = searchConfig as unknown as { sortFields?: readonly string[] };\n const defaultSort: Record<string, 1 | -1> = { createdAt: -1 };\n\n // If no sort fields configured, use requested sort or default\n if (!sortFields?.length) {\n return requestedSort || defaultSort;\n }\n\n // If no sort requested, use first configured sort field\n if (!requestedSort) {\n const firstSortField = sortFields[0];\n return { [firstSortField]: -1 };\n }\n\n // Validate requested sort fields against configuration\n const validatedSort: Record<string, 1 | -1> = {};\n\n Object.entries(requestedSort).forEach(([fieldName, sortDirection]) => {\n if (sortFields.includes(fieldName) && (sortDirection === 1 || sortDirection === -1)) {\n validatedSort[fieldName] = sortDirection;\n }\n });\n\n // Return validated sort or fallback to default\n return Object.keys(validatedSort).length > 0 ? validatedSort : defaultSort;\n }\n\n\n\n}\n"]}
1
+ {"version":3,"file":"repository-resource.backend.service.js","sourceRoot":"","sources":["../../../../../../src/base-classes/services/repositories/repository-resource.backend.service.ts"],"names":[],"mappings":"AAAA,OAAO,kBAAkB,CAA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,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,WAAW,CAAC;IAC7E,CAAC;CAIF","sourcesContent":["import 'reflect-metadata';\n\nimport type {\n ResourceConfiguration,\n ResourceConfiguration_Operation,\n ResourceConfiguration_OperationRepositoryPath,\n CollectionView_SearchOptions,\n Resources_PaginationRequest,\n SearchableFieldDescriptor,\n SearchableRelationDescriptor,\n} from '@wildo-ai/saas-models';\nimport {\n CoreResourceOperation,\n CoreResourceType,\n ErrorCustomMessageReference,\n ErrorType,\n isSearchableRelationDescriptor,\n PersistenceAdapter,\n PRIMARY_SCOPE_TO_FIELD_IDENTIFIER,\n ResourceOperationsUtils,\n ResourceOperationVariantType,\n Resources_PaginatedResult,\n ResourcesConfig_OperationPathUtils,\n ResourceType,\n WildoError_Backend,\n} from '@wildo-ai/saas-models';\nimport {\n assignRetentionHideForOperation,\n isRetentionGovernedResource,\n withRetentionHideApplied,\n} from '~wildo-backend-lib/compliance/privacy/retention-hide-predicate.backend';\nimport {\n assignOrganizationUnitNarrowingToFilter,\n isOrganizationUnitNarrowingExemptExecution,\n OrganizationUnitNarrowingWriteViolationReason,\n resolveSuppliedOrganizationUnitIdForTenantCheck,\n resolveOrganizationUnitNarrowingWriteViolation,\n} from '~wildo-backend-lib/security/authorizations/organization-unit-narrowing-enforcement.backend';\nimport { assignInitiatorOrganizationConfinementToFilter } from '~wildo-backend-lib/security/authorizations/initiator-organization-confinement.backend';\nimport { assignScopeRootCollectionConfinementToFilter } from '~wildo-backend-lib/security/authorizations/scope-root-collection-confinement.backend';\nimport {\n applyJunctionScopeFilter,\n collectJunctionScopedFieldIdentifiers,\n} from '~wildo-backend-lib/security/authorizations/junction-scope-resolution.backend';\nimport { assignRelationshipForeignKeyFiltersToFilter } from '~wildo-backend-lib/security/authorizations/relationship-foreign-key-filter.backend';\nimport {\n buildBusinessKeyFilter,\n resolveBusinessKeyFieldNames,\n BUSINESS_KEY_ERROR_PREFIX,\n} from '~wildo-backend-lib/data-seeding/models/business-key-resolver.shared.utils';\nimport {\n DATA_SEED_ROW_METADATA_FIELD_KEY,\n type DataSeedRowMetadata,\n} from '~wildo-backend-lib/data-seeding/models/data-seed-row-metadata.shared.schemas';\nimport { EnumLikeType } from '@wildo-ai/zod-decorators';\nimport type { FieldMetaEntry } from '@wildo-ai/saas-models';\nimport {\n lwwFieldWinner,\n CrdtResolutionWinner,\n nextMonotonicTimestamp,\n isCrdtOnlyUpdate,\n sanitizeFieldMeta,\n extractCrdtFieldNames,\n ResourceSerializationUtils,\n} from '@wildo-ai/saas-models';\nimport {\n guardedMutationHasWork,\n RepositoryArrayAdditionPlacement,\n type RepositoryGuardedMutation,\n} from './repository-guarded-mutation.backend.types';\nimport { assertCreateWriteIntegrity, assertUpdateWriteIntegrity, referenceConstraintsOf, type ResourceWriteIntegrityDeps } from './resource-write-integrity.backend';\nimport { isEngineReservedFieldName, partitionNullClearedFields } from './field-clearing-partition.backend';\nimport { Connection, Document, FilterQuery, Model, Types } from 'mongoose';\n\nimport { z } from 'zod';\nimport type { LoggerService } from '~wildo-backend-lib/monitoring/logger/services/logger.service';\nimport type { ZodToMongooseSchemaConvertorBackendService } from '~wildo-backend-lib/databases/services/zod-to-mongoose-schema-convertor.backend.service';\nimport { normalizeDateRangeFilters } from '~wildo-backend-lib/databases/models/filter.backend.schemas';\nimport { ErrorBuilderBackendService } from '~wildo-backend-lib/errors/services/error-builder.backend.service';\nimport { describeCaughtError, projectCaughtErrorLogFields } from '~wildo-backend-lib/errors/utils/error-log-level-classification.backend.utils';\nimport { ResourcesRegistryBackendService } from '~wildo-backend-lib/resources/services/resources-registry.backend.service';\nimport { ResourceIdBackendService } from '~wildo-backend-lib/resources/services/resource-id.backend.service';\nimport { ExecutionContext } from '~wildo-backend-lib/runtime/models/execution-context.backend.schemas';\nimport { normalizeRepositoryVersionMetadata } from '~wildo-backend-lib/base-classes/services/repositories/repository-version-metadata.backend.utils';\nimport { resolveDeclaredUniqueConflictReference } from '~wildo-backend-lib/base-classes/services/repositories/unique-constraint-conflict-reference.backend';\nimport { IdOrFilterType, IdOrIdsOrFilterType, IdsOrFilterType, RepositoryOptions } from '~wildo-backend-lib/base-classes/models/repositories.backend.schemas';\nimport { ResourceOperationHelperBackendService } from '~wildo-backend-lib/base-classes/services/resource-operations-helper.backend.service';\nimport {\n MainSchemaType,\n PartialMainSchemaType,\n MainSchemaArrayType,\n ConditionalReturnType,\n ConditionalArrayReturnType,\n ConditionalNullableReturnType\n} from '~wildo-backend-lib/base-classes/utils/backend-type-utils';\n\n\nconst DEBUG_ACTIVATED = false;\n\n// Forward declaration to avoid circular dependency\ntype RepositoriesRegistryHandlerBackendService = any;\n\n/**\n * Factory interface for creating repository resource instances\n *\n * NOTE: TDatabaseSchema has been removed. Backend-only fields are now marked with\n * the `isBackendOnly` decorator on mainSchema and handled at the service layer.\n */\nexport interface RepositoryResourceFactory {\n create<\n TCustomOperationEnum extends EnumLikeType | undefined = undefined,\n TCoreOperationEnum extends Partial<CoreResourceOperation> | undefined = undefined,\n TMainSchema extends z.ZodTypeAny = z.ZodTypeAny\n >(\n resourceConfiguration: ResourceConfiguration<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>\n ): RepositoryResourceBackendService<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\n}\n\n/**\n * MongoDB Repository Implementation\n *\n * This class provides the MongoDB/Mongoose implementation of the resource repository.\n * It conforms to the `BackendResourceRepository` interface contract through TypeScript's\n * structural typing.\n *\n * ## Transaction Support\n *\n * Uses the `getNativeSession()` helper to extract the Mongoose ClientSession from\n * the database-agnostic `options.transaction.nativeSession` (TransactionContext).\n *\n * @see BackendResourceRepository in repositories-registry-handler.backend.service.ts\n * @see PostgreSQLResourceRepositoryBackendService for PostgreSQL implementation\n */\nimport type { BackendResourceRepository } from './repositories-registry-handler.backend.service';\n\n/**\n * `import type` on purpose: the registry imports THIS module to construct repositories,\n * so a value import back would close a runtime cycle (and this package runs as native\n * ESM, where that surfaces as \"Cannot access … before initialization\"). A type-only\n * import is erased at compile time, so conformance can be declared without one.\n */\nexport class RepositoryResourceBackendService<\n TCustomOperationEnum extends EnumLikeType | undefined = undefined,\n TCoreOperationEnum extends Partial<CoreResourceOperation> | undefined = undefined,\n TMainSchema extends z.ZodTypeAny = z.ZodTypeAny\n> implements BackendResourceRepository<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> {\n\n private readonly resourceConfiguration: ResourceConfiguration<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\n private readonly mongooseModel: Model<any & Document>;\n private readonly inheritanceModels: Map<string, Model<any & Document>>;\n private readonly operationsMap: Map<string, ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>>;\n\n protected logDebug: (message: string, context?: Record<string, unknown>) => void;\n\n constructor(\n resourceType: ResourceType,\n private readonly zodToMongooseConverter: ZodToMongooseSchemaConvertorBackendService,\n private readonly logger: LoggerService,\n private readonly errorBuilder: ErrorBuilderBackendService,\n private readonly resourceRegistry: ResourcesRegistryBackendService,\n private readonly resourceOperationHelper: ResourceOperationHelperBackendService,\n private readonly repositoriesRegistry: RepositoriesRegistryHandlerBackendService,\n private readonly connection: Connection | undefined = undefined,\n private readonly resourceIdService?: ResourceIdBackendService,\n ) {\n this.resourceConfiguration = this.resourceRegistry.getResourceConfiguration(resourceType);\n this.zodToMongooseConverter = zodToMongooseConverter;\n\n this.inheritanceModels = new Map();\n this.operationsMap = new Map();\n\n this.logDebug = this.logger.debugByType(`RepositoryResource_${resourceType}`);\n this.logger.setDebugTypeLogging(`RepositoryResource_${resourceType}`, DEBUG_ACTIVATED);\n\n // Initialize mongoose model and operations\n this.mongooseModel = this.initializeMongooseModel();\n this.initializeOperationsMap();\n\n this.logDebug('Repository resource service created', { resourceType: this.resourceConfiguration.resourceIdentifier, operationsCount: this.operationsMap.size, hasInheritance: this.inheritanceModels.size > 0 });\n }\n\n // ================================\n // Transaction Session Helper\n // ================================\n\n /**\n * Get the native Mongoose session from repository options.\n *\n * Extracts the Mongoose ClientSession from the database-agnostic TransactionContext.\n * Includes runtime safety check to ensure MongoDB repository doesn't receive\n * a PostgreSQL transaction context.\n *\n * @param options - Repository options that may contain transaction\n * @returns The Mongoose ClientSession or undefined\n * @throws Error if a non-MongoDB transaction is provided\n */\n protected getNativeSession(options?: RepositoryOptions): import('mongoose').ClientSession | undefined {\n if (!options?.transaction) {\n return undefined;\n }\n\n // Runtime safety check: ensure this is a MongoDB transaction\n if (options.transaction.databaseType !== PersistenceAdapter.MONGODB) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n context: {\n // diagnostic (log-only): wrong persistence adapter wired for this resource (framework config bug).\n expectedDatabaseType: PersistenceAdapter.MONGODB,\n receivedDatabaseType: options.transaction.databaseType,\n },\n });\n }\n return options.transaction.nativeSession as import('mongoose').ClientSession | undefined;\n }\n\n // ================================\n // Initialization\n // ================================\n\n static createInstance<\n TCustomOperationEnum extends EnumLikeType | undefined = undefined,\n TCoreOperationEnum extends Partial<CoreResourceOperation> | undefined = undefined,\n TMainSchema extends z.ZodTypeAny = z.ZodTypeAny\n >(\n resourceType: ResourceType,\n zodToMongooseConverter: ZodToMongooseSchemaConvertorBackendService,\n logger: LoggerService,\n errorBuilder: ErrorBuilderBackendService,\n resourceRegistry: ResourcesRegistryBackendService,\n resourceOperationHelper: ResourceOperationHelperBackendService,\n repositoriesRegistry: RepositoriesRegistryHandlerBackendService,\n connection: Connection | undefined = undefined,\n resourceIdService?: ResourceIdBackendService,\n ): RepositoryResourceBackendService<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> {\n return new RepositoryResourceBackendService(\n resourceType,\n zodToMongooseConverter,\n logger,\n errorBuilder,\n resourceRegistry,\n resourceOperationHelper,\n repositoriesRegistry,\n connection,\n resourceIdService,\n );\n }\n\n private initializeOperationsMap(): void {\n if (!this.resourceConfiguration.operations) {\n return;\n }\n\n this.resourceConfiguration.operations.forEach(operation => {\n const operationKey = ResourcesConfig_OperationPathUtils.createOperationRepositoryPathKeyFromOperation(operation as any);\n this.operationsMap.set(operationKey, operation);\n });\n\n this.logDebug('Operations map initialized', {\n operationsCount: this.operationsMap.size,\n operationKeys: Array.from(this.operationsMap.keys())\n });\n }\n\n private initializeMongooseModel(): Model<any & Document> {\n try {\n const modelResult = this.zodToMongooseConverter.convertResourceConfigurationToModel(\n this.resourceConfiguration,\n {\n includeIndexes: true,\n applyDefaults: true,\n connection: this.connection\n }\n );\n\n // Store inheritance models if any\n // Use a Set to track created discriminator values to avoid duplicates\n const createdDiscriminatorValues = new Set<string>();\n modelResult.inheritanceSchemas.forEach(inheritance => {\n // Skip if discriminator with this value already exists\n if (createdDiscriminatorValues.has(inheritance.discriminatorValue)) {\n this.logDebug(`Skipping duplicate discriminator value: ${inheritance.discriminatorValue}`, {\n discriminatorKey: inheritance.discriminatorKey,\n discriminatorValue: inheritance.discriminatorValue\n });\n return;\n }\n\n try {\n // Check if discriminator already exists on the model\n const existingDiscriminator = (modelResult.mainModel as any).discriminators?.[inheritance.discriminatorValue];\n if (existingDiscriminator) {\n this.logDebug(`Discriminator already exists, reusing: ${inheritance.discriminatorValue}`, {\n discriminatorKey: inheritance.discriminatorKey,\n discriminatorValue: inheritance.discriminatorValue\n });\n this.inheritanceModels.set(inheritance.discriminatorValue, existingDiscriminator);\n createdDiscriminatorValues.add(inheritance.discriminatorValue);\n return;\n }\n\n // Create inheritance model from schema\n const inheritanceModel = modelResult.mainModel.discriminator(\n inheritance.discriminatorValue,\n inheritance.schema\n );\n this.inheritanceModels.set(inheritance.discriminatorValue, inheritanceModel);\n createdDiscriminatorValues.add(inheritance.discriminatorValue);\n } catch (error: any) {\n // If discriminator already exists, try to get it\n if (error?.message?.includes('already exists')) {\n this.logDebug(`Discriminator already exists, attempting to retrieve: ${inheritance.discriminatorValue}`, {\n discriminatorKey: inheritance.discriminatorKey,\n discriminatorValue: inheritance.discriminatorValue\n });\n const existingDiscriminator = (modelResult.mainModel as any).discriminators?.[inheritance.discriminatorValue];\n if (existingDiscriminator) {\n this.inheritanceModels.set(inheritance.discriminatorValue, existingDiscriminator);\n createdDiscriminatorValues.add(inheritance.discriminatorValue);\n } else {\n this.logger.warn(`Failed to create or retrieve discriminator: ${inheritance.discriminatorValue}`, {\n error: error.message,\n discriminatorKey: inheritance.discriminatorKey\n });\n }\n } else {\n throw error;\n }\n }\n });\n\n this.logDebug('Mongoose model initialized', {\n modelName: modelResult.mainModel.modelName,\n inheritanceCount: this.inheritanceModels.size\n });\n\n return modelResult.mainModel;\n } catch (error) {\n this.logger.error('Failed to initialize mongoose model', {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n ...projectCaughtErrorLogFields(error)\n });\n throw error;\n }\n }\n\n\n // ================================\n // Getters\n // ================================\n\n public getInheritanceModel(discriminatorValue: string): Model<any & Document> | undefined {\n return this.inheritanceModels.get(discriminatorValue);\n }\n\n // ================================\n // Execution\n // ================================\n\n public async doByPath<T = any, U = any>(\n operationRepositoryPath: ResourceConfiguration_OperationRepositoryPath,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: U,\n options?: RepositoryOptions\n ): Promise<T> {\n const operationRepositoryPathKey = ResourcesConfig_OperationPathUtils.createOperationRepositoryPathKey(operationRepositoryPath);\n\n this.logDebug('Executing operation by repository path', { operationRepositoryPath, operationRepositoryPathKey, hasData: !!data, id_or_ids_or_filter });\n\n return this.doByKey( operationRepositoryPathKey, executionContext, id_or_ids_or_filter, data, options );\n }\n\n /**\n * Execute operation by operation repository path key (string)\n */\n public async doByKey<T = any, U = any>(\n operationRepositoryPathKey: string,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: U,\n options?: RepositoryOptions\n ): Promise<T> {\n\n ResourcesConfig_OperationPathUtils.validateOperationRepositoryPathKey(operationRepositoryPathKey);\n\n const operation = this.operationsMap.get(operationRepositoryPathKey);\n\n if (!operation) {\n // CONFIGURATION, not NOT_FOUND. An operation key absent from `operationsMap` means the\n // RESOURCE CONFIGURATION does not declare that operation — a structural fault in the\n // application's own wiring, never a row that happens not to exist. The HTTP router resolves a\n // route from the registry BEFORE dispatching, so a client cannot reach this by asking for a\n // missing record: getting here means engine or application code built an operation path the\n // registry does not have. Reporting it as 404 sent the reader to the data for a fault that is\n // in the wiring, and reported a SERVER fault as a CLIENT error where a 4xx/5xx split could\n // not see it.\n throw this.errorBuilder.buildError( ErrorType.CONFIGURATION, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationRepositoryPathKey } } );\n }\n\n this.logDebug('Executing operation by repository path key', { operationRepositoryPathKey, hasData: !!data, id_or_ids_or_filter });\n\n return this.doOperation(operation, executionContext, id_or_ids_or_filter, data, options);\n }\n\n public async doByExecutionContext<T = any>(\n executionContext: ExecutionContext<ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>>,\n data?: any,\n options?: RepositoryOptions\n ): Promise<T> {\n const operation = executionContext.operation;\n\n // Extract IDs based on resourceFieldIdentifier from execution context\n const id_or_ids_or_filter = this.resourceOperationHelper.extractIdsFromExecutionContext(executionContext, this.resourceConfiguration.resourceFieldIdentifier);\n\n this.logDebug('Executing operation by execution context', {\n operationIdentifier: operation.operationIdentifier,\n resourceIdentifier: operation.resourceIdentifier,\n hasData: !!data,\n extractedIds: id_or_ids_or_filter,\n resourceFieldIdentifier: this.resourceConfiguration.resourceFieldIdentifier\n });\n\n return this.doOperation(operation, executionContext, id_or_ids_or_filter, data, options);\n }\n\n private async _prefixOperation(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: any,\n options?: RepositoryOptions\n ): Promise<void> {\n // Authorization is handled at the controller/middleware layer before reaching the repository.\n // Repository-level prefix operations are reserved for data-level pre-processing (e.g., input normalization).\n // Operation-level authorization is enforced by the ResourceOperationService via role + variant checks.\n }\n\n private async _postfixOperation(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: any,\n options?: RepositoryOptions\n ): Promise<void> {\n // Post-operation hook reserved for data-level post-processing (e.g., cache invalidation).\n // Currently no-op by design — business logic runs at the service layer.\n }\n\n /**\n * Execute a specific operation\n */\n private async doOperation(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: any,\n options?: RepositoryOptions\n ): Promise<any> {\n const operationRepositoryPathKey = ResourcesConfig_OperationPathUtils.createOperationRepositoryPathKeyFromOperation(operation);\n\n if(operation.resourceIdentifier !== this.resourceConfiguration.resourceIdentifier) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationRepositoryPathKey, resourceIdentifier: this.resourceConfiguration.resourceIdentifier } } );\n }\n const operationIdentifier = ResourceOperationsUtils.getCoreResourceOperationFromOperation(operation);\n\n if (!operationIdentifier) {\n\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationRepositoryPathKey } } );\n }\n\n await this._prefixOperation(operation, executionContext, id_or_ids_or_filter, data, options);\n\n let operationResult: any;\n // Handle core operations\n switch (operationIdentifier) {\n case CoreResourceOperation.CREATE:\n operationResult = await this._doCreate(operation, executionContext, data, options);\n break;\n\n case CoreResourceOperation.CREATE_MANY:\n operationResult = await this._doCreateMany(operation, executionContext, data, options);\n break;\n\n case CoreResourceOperation.READ:\n if(Array.isArray(id_or_ids_or_filter)) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED,\n context: { operationRepositoryPathKey, resourceIdentifier: this.resourceConfiguration.resourceIdentifier, id_or_ids_or_filter } } );\n }\n operationResult = await this._doRead(operation, executionContext, id_or_ids_or_filter as IdOrFilterType, options);\n break;\n\n case CoreResourceOperation.UPDATE:\n if(Array.isArray(id_or_ids_or_filter)) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED,\n context: { operationRepositoryPathKey, resourceIdentifier: this.resourceConfiguration.resourceIdentifier, id_or_ids_or_filter } } );\n }\n operationResult = await this._doUpdate(operation, executionContext, id_or_ids_or_filter as IdOrFilterType, data, options);\n break;\n\n case CoreResourceOperation.UPDATE_MANY:\n operationResult = await this._doUpdateMany(operation, executionContext, id_or_ids_or_filter as IdsOrFilterType, data, options);\n break;\n\n case CoreResourceOperation.DELETE:\n if(Array.isArray(id_or_ids_or_filter)) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED,\n context: { operationRepositoryPathKey, resourceIdentifier: this.resourceConfiguration.resourceIdentifier, id_or_ids_or_filter } } );\n }\n operationResult = await this._doDelete(operation, executionContext, id_or_ids_or_filter as IdOrIdsOrFilterType, options);\n break;\n\n case CoreResourceOperation.DELETE_MANY:\n const idToDelete = typeof id_or_ids_or_filter === 'string' ? [id_or_ids_or_filter] : id_or_ids_or_filter;\n operationResult = await this._doDeleteMany(operation, executionContext, idToDelete as IdsOrFilterType, options);\n break;\n\n case CoreResourceOperation.LIST:\n // For LIST operation, return paginated format\n const idsToList = typeof id_or_ids_or_filter === 'string' ? [id_or_ids_or_filter] : id_or_ids_or_filter;\n const listResult = await this._doList(operation, executionContext, idsToList as IdsOrFilterType, options);\n operationResult = listResult;\n break;\n\n case CoreResourceOperation.COUNT:\n operationResult = await this._doCount(\n operation,\n executionContext,\n (data?.filter as FilterQuery<any>) ?? {},\n options,\n );\n break;\n\n case CoreResourceOperation.SEARCH:\n operationResult = await this._doSearch(\n operation,\n executionContext,\n data?.query || '',\n (data?.filter as FilterQuery<any>) ?? {},\n {\n ...options,\n searchOptions: (options as { searchOptions?: { fieldsToSearch?: string[]; page?: number; limit?: number; sort?: any; } } | undefined)?.searchOptions ?? {},\n } as RepositoryOptions & { searchOptions: { fieldsToSearch?: string[]; page?: number; limit?: number; sort?: any; } },\n );\n break;\n\n default:\n // Handle custom operations\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { resourceIdentifier: this.resourceConfiguration.resourceIdentifier, operationIdentifier } });\n }\n\n await this._postfixOperation(operation, executionContext, id_or_ids_or_filter, data, options);\n\n return operationResult;\n }\n\n\n\n // ================================\n // Core Public Operations\n // ================================\n\n public async create<T = undefined>(\n executionContext: ExecutionContext<any>,\n data: MainSchemaType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalReturnType<T, TMainSchema>> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.CREATE && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.CREATE } } );\n }\n await this._prefixOperation(operation, executionContext, undefined, data, options);\n const result = await this._doCreate(operation, executionContext, data, options);\n await this._postfixOperation(operation, executionContext, undefined, data, options);\n return result as ConditionalReturnType<T, TMainSchema>;\n }\n\n public async createMany<T = undefined>(\n executionContext: ExecutionContext<any>,\n data: MainSchemaArrayType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalArrayReturnType<T, TMainSchema>> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.CREATE_MANY && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.CREATE_MANY } } );\n }\n await this._prefixOperation(operation, executionContext, undefined, data, options);\n const result = await this._doCreateMany(operation, executionContext, data, options);\n await this._postfixOperation(operation, executionContext, undefined, data, options);\n return result as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n public async read<T = undefined>(\n executionContext: ExecutionContext<any>,\n id_or_filter: IdOrFilterType,\n options?: RepositoryOptions\n ): Promise<ConditionalNullableReturnType<T, TMainSchema>> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.READ && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.READ } } );\n }\n await this._prefixOperation(operation, executionContext, id_or_filter, undefined, options);\n const result = await this._doRead(operation, executionContext, id_or_filter, options);\n await this._postfixOperation(operation, executionContext, id_or_filter, undefined, options);\n return result as ConditionalNullableReturnType<T, TMainSchema>;\n }\n\n /**\n * Repository-internal READ for framework recovery/reconciliation that must\n * not depend on a user-facing default READ operation.\n *\n * The synthetic operation is used only to drive the adapter's core read.\n * `_doRead` still applies contextual scope and retention filtering, while\n * skipping authored prefix/postfix hooks and response projections so the\n * caller receives canonical persisted resource truth.\n */\n /**\n * @see BackendResourceRepository.readUnscopedByKey — the contract carries the reasoning.\n *\n * No `buildContextualFilter`: the caller's filter is the whole confinement, by design. The\n * retention hide is applied ONCE at the registry dispatch point, matching `atomicGuardedMutation`\n * rather than duplicating the predicate here.\n *\n * retention-gate: N/A — applied at `RepositoriesRegistryHandlerBackendService.readUnscopedByKey`.\n */\n public async readUnscopedByKey<T = any>(\n filter: Record<string, unknown>,\n options?: RepositoryOptions,\n ): Promise<T | null> {\n const session = this.getNativeSession(options);\n const document = await this.mongooseModel\n .findOne(filter as FilterQuery<any>, null, session ? { session } : {})\n .exec();\n\n if (!document) return null;\n return (document.toObject ? document.toObject() : document) as T;\n }\n\n public async readForInternalScan<T = undefined>(\n executionContext: ExecutionContext<any>,\n id_or_filter: IdOrFilterType,\n options?: RepositoryOptions,\n ): Promise<ConditionalNullableReturnType<T, TMainSchema>> {\n const syntheticReadOperation = {\n operationIdentifier: CoreResourceOperation.READ,\n variantType: ResourceOperationVariantType.REPOSITORY_ONLY,\n isOperationDefault: true,\n } as unknown as ResourceConfiguration_Operation<\n TCustomOperationEnum,\n TCoreOperationEnum,\n TMainSchema\n >;\n return this._doRead<T>(\n syntheticReadOperation,\n executionContext,\n id_or_filter,\n options,\n );\n }\n\n public async update<T = undefined>(\n executionContext: ExecutionContext<any>,\n id_or_filter: IdOrFilterType,\n data: PartialMainSchemaType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalNullableReturnType<T, TMainSchema>> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.UPDATE && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.UPDATE } } );\n }\n await this._prefixOperation(operation, executionContext, id_or_filter, data, options);\n const result = await this._doUpdate(operation, executionContext, id_or_filter, data, options);\n await this._postfixOperation(operation, executionContext, id_or_filter, data, options);\n return result as ConditionalNullableReturnType<T, TMainSchema>;\n }\n\n public async updateMany<T = undefined>(\n executionContext: ExecutionContext<any>,\n data: PartialMainSchemaType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalArrayReturnType<T, TMainSchema>> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.UPDATE_MANY && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.UPDATE_MANY } } );\n }\n await this._prefixOperation(operation, executionContext, undefined, data, options);\n const result = await this._doUpdateMany(operation, executionContext, undefined, data, options);\n await this._postfixOperation(operation, executionContext, undefined, data, options);\n return result as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n public async delete(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<string> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.DELETE && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.DELETE } } );\n }\n await this._prefixOperation(operation, executionContext, id_or_ids_or_filter, undefined, options);\n const result = await this._doDelete(operation, executionContext, id_or_ids_or_filter, options);\n await this._postfixOperation(operation, executionContext, id_or_ids_or_filter, undefined, options);\n return result;\n }\n\n public async deleteMany(\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<string[]> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.DELETE_MANY && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.DELETE_MANY } } );\n }\n await this._prefixOperation(operation, executionContext, ids_or_filter, undefined, options);\n const result = await this._doDeleteMany(operation, executionContext, ids_or_filter, options);\n await this._postfixOperation(operation, executionContext, ids_or_filter, undefined, options);\n return result;\n }\n\n /**\n * Overloads declared to match what this method ALREADY DOES at runtime.\n *\n * `_doList` returns a paginated envelope when `options.paginated` is set, but the\n * single declared signature said \"array\" — so every caller passing `paginated: true`\n * was handed a wrong type. That went unnoticed because the class was cast through\n * `as any` at construction and never checked against its own contract.\n */\n public async list<T = undefined>(\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<ConditionalArrayReturnType<T, TMainSchema>>;\n public async list<T = undefined>(\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options: RepositoryOptions & { paginated: true; listOptions?: Partial<Resources_PaginationRequest> }\n ): Promise<Resources_PaginatedResult<ConditionalReturnType<T, TMainSchema>>>;\n public async list<T = undefined>(\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<any> {\n const operation = this.findDefaultListOperation();\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { resourceIdentifier: this.resourceConfiguration.resourceIdentifier, operationIdentifier: CoreResourceOperation.LIST, reason: 'no default LIST operation declared on this resource' } } );\n }\n return this._runListWithHooks(operation, executionContext, ids_or_filter, options) as Promise<ConditionalArrayReturnType<T, TMainSchema>>;\n }\n\n /**\n * Repository-internal LIST for FRAMEWORK-managed scans that must work\n * regardless of whether the resource declares a user-facing LIST\n * operation.\n *\n * Two framework-internal callers rely on this:\n * 1. The data-seed engines' idempotency / orphan / rename scans by\n * `__seed.seedKey` (seeded `REPOSITORY_ONLY` singletons such as the\n * M2M webhook config declare only repository-only CREATE/UPDATE).\n * 2. The controller's context-addressed-singleton authorization\n * (`resolveContextAddressedSingletonOperationAuthorizationId`),\n * which lists by the parent FK to resolve the singleton's id and\n * prove uniqueness for READ/UPDATE/DELETE — e.g. per-user singletons\n * like `userProgressionState` / `userGuidanceState` that expose only\n * READ to users, never LIST.\n *\n * In both cases the LIST is framework machinery, NOT a user-facing\n * collection read. Forcing every such resource to also declare a\n * user-facing LIST just to satisfy internal plumbing would push a\n * framework concern onto every resource author; resolving it here keeps\n * the contract in one place.\n *\n * Behaviour:\n * - When a default LIST operation IS declared, it is reused verbatim —\n * identical to {@link list} (same projection + prefix/postfix hooks),\n * so resources that DO expose LIST behave exactly as before.\n * - When NO default LIST operation is declared, a minimal synthetic\n * `REPOSITORY_ONLY` operation drives `_doList` directly (full-document\n * projection, since the synthetic op carries no response/repository\n * DTO) and the user hook pipeline is skipped — an internal scan is\n * not a user-facing operation, so user prefix/postfix hooks (ACL\n * narrowing, validation) must not apply.\n */\n /**\n * Overloads declared to match what this method ALREADY DOES at runtime.\n *\n * `_doList` returns a paginated envelope when `options.paginated` is set, but the\n * single declared signature said \"array\" — so every caller passing `paginated: true`\n * was handed a wrong type. That went unnoticed because the class was cast through\n * `as any` at construction and never checked against its own contract.\n */\n public async listForInternalScan<T = undefined>(\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<ConditionalArrayReturnType<T, TMainSchema>>;\n public async listForInternalScan<T = undefined>(\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options: RepositoryOptions & { paginated: true; listOptions?: Partial<Resources_PaginationRequest> }\n ): Promise<Resources_PaginatedResult<ConditionalReturnType<T, TMainSchema>>>;\n public async listForInternalScan<T = undefined>(\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<any> {\n const declaredListOperation = this.findDefaultListOperation();\n if (declaredListOperation) {\n return this._runListWithHooks(declaredListOperation, executionContext, ids_or_filter, options) as Promise<ConditionalArrayReturnType<T, TMainSchema>>;\n }\n const syntheticListOperation = this.buildSyntheticRepositoryListOperation();\n const result = await this._doList(syntheticListOperation, executionContext, ids_or_filter, options);\n return result as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n private findDefaultListOperation(): ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> | undefined {\n return this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.LIST && op.isOperationDefault === true);\n }\n\n private async _runListWithHooks(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<unknown> {\n await this._prefixOperation(operation, executionContext, ids_or_filter, undefined, options);\n const result = await this._doList(operation, executionContext, ids_or_filter, options);\n await this._postfixOperation(operation, executionContext, ids_or_filter, undefined, options);\n return result;\n }\n\n /**\n * Build a minimal synthetic default `REPOSITORY_ONLY` LIST operation for\n * {@link listForInternalScan} on resources that declare none.\n *\n * This object exists ONLY to drive `_doList`, which reads exactly one\n * field off the operation: the response/repository DTO (for the Mongo\n * projection). With neither DTO present, `_doList` uses a full-document\n * projection — the correct behaviour for a seed scan, which needs `_id`\n * plus arbitrary seeded fields (rename scans read author-declared fields)\n * and the `__seed` metadata it filters on. The synthetic op is NEVER\n * registered in the resource's operation set and is never variant-narrowed\n * by downstream code, so the `as` cast is safe — it carries no other\n * load-bearing fields.\n */\n private buildSyntheticRepositoryListOperation(): ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> {\n return {\n operationIdentifier: CoreResourceOperation.LIST,\n variantType: ResourceOperationVariantType.REPOSITORY_ONLY,\n isOperationDefault: true,\n } as unknown as ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\n }\n\n public async search<T = any>(\n executionContext: ExecutionContext<any>,\n searchQuery: string,\n filter: FilterQuery<any> = {},\n searchOptions: { fieldsToSearch?: string[]; page?: number; limit?: number; sort?: any} = {},\n options?: RepositoryOptions\n ): Promise<Resources_PaginatedResult<T>> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.SEARCH && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.SEARCH } } );\n }\n const searchOptionsWithDefaults = { searchOptions, ...options };\n await this._prefixOperation(operation, executionContext, undefined, { query: searchQuery }, searchOptionsWithDefaults);\n const result = await this._doSearch(operation, executionContext, searchQuery, filter, searchOptionsWithDefaults);\n await this._postfixOperation(operation, executionContext, undefined, { query: searchQuery }, searchOptionsWithDefaults);\n return result;\n }\n\n public supportsOperation(operationIdentifier: string): boolean {\n return this.resourceConfiguration.operations.some(\n op => op.operationIdentifier === operationIdentifier && op.isOperationDefault === true\n );\n }\n\n public async count(\n executionContext: ExecutionContext<any>,\n filter: FilterQuery<any> = {},\n options?: RepositoryOptions\n ): Promise<{ count: number }> {\n const operation = this.resourceConfiguration.operations.find(op => op.operationIdentifier === CoreResourceOperation.COUNT && op.isOperationDefault === true);\n if (!operation) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationIdentifier: CoreResourceOperation.COUNT } } );\n }\n await this._prefixOperation(operation, executionContext, undefined, filter, options);\n const result = await this._doCount(operation, executionContext, filter, options);\n await this._postfixOperation(operation, executionContext, undefined, filter, options);\n return result;\n }\n\n /**\n * Aggregate a numeric field across documents matching the filter.\n * Framework infrastructure method for feature limit enforcement.\n *\n * Uses MongoDB aggregation pipeline: $match (with buildContextualFilter) + $group.\n * Handles null/undefined field values via $ifNull.\n * Does NOT require a COUNT operation to be configured (not API-facing).\n *\n * @param executionContext - Current execution context (used for scope filtering)\n * @param filter - Additional filter criteria (scope is added automatically by buildContextualFilter)\n * @param field - The document field to aggregate\n * @param operation - The aggregation operation (SUM, AVG, MAX)\n * @returns The aggregated numeric result (0 if no matching documents)\n */\n public async aggregateField(\n executionContext: ExecutionContext<any>,\n filter: FilterQuery<any>,\n field: string,\n operation: string,\n ): Promise<number> {\n const contextualFilter = this.buildContextualFilter(executionContext, filter, CoreResourceOperation.READ);\n\n // Map operation string to MongoDB aggregation operator\n let mongoOp: string;\n switch (operation) {\n case 'SUM':\n mongoOp = '$sum';\n break;\n case 'AVG':\n mongoOp = '$avg';\n break;\n case 'MAX':\n mongoOp = '$max';\n break;\n default:\n mongoOp = '$sum';\n }\n\n const pipeline = [\n { $match: contextualFilter },\n {\n $group: {\n _id: null,\n result: { [mongoOp]: { $ifNull: [`$${field}`, 0] } },\n },\n },\n ];\n\n this.logDebug('Aggregating field', { field, operation, filter: contextualFilter });\n\n const results = await this.mongooseModel.aggregate(pipeline).exec();\n const value = results.length > 0 ? (results[0].result ?? 0) : 0;\n\n this.logDebug('Aggregation result', { field, operation, value });\n return value;\n }\n\n // ================================\n // Business-Key Helpers (data-seeding)\n // ================================\n //\n // Spec refs (see also each method's JSDoc):\n // - data-seeding-as-first-class-feature plan §3.7 (atomic upsert + ledger)\n // - Phase 2 plan §5 (BackendResourceRepository contract)\n // - Decision P2-B (PostgreSQL sibling kept at parity)\n // - Audit findings R-2 / R-4 / R-6 / R-10 (this comment + per-method docs)\n\n /**\n * Find a single row whose business-key fields match `businessKeyShape`,\n * scoped by the current execution context (orgId, userId, …).\n *\n * Bypasses the operation-resolution / DTO-validation pipeline because this\n * is **infrastructure** used by the data-seeding subsystem (system writes\n * are trusted; the seed dispatcher validates payloads against `mainSchema`\n * before calling here). Context-scoped filtering still applies via\n * `buildContextualFilter`, so a seed declared with org-scoped business\n * keys (e.g. `[organizationId, templateKey]`) cannot leak rows across\n * organizations even if the caller forgot to pass `organizationId` in\n * the shape — the contextual filter would refuse to match.\n *\n * Returns `null` when no matching row exists.\n *\n * @throws WildoError_Backend(INTERNAL) if the schema declares no business\n * key (configuration error — see `resolveBusinessKeyFieldNames`).\n */\n public async findByBusinessKey<T = undefined>(\n executionContext: ExecutionContext<any>,\n businessKeyShape: Record<string, unknown>,\n options?: RepositoryOptions,\n ): Promise<ConditionalNullableReturnType<T, TMainSchema>> {\n const baseFilter = this._tryBuildBusinessKeyFilter(executionContext, businessKeyShape);\n const filter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.READ, options);\n\n const session = this.getNativeSession(options);\n this.logDebug('findByBusinessKey', { filter, hasTransaction: !!session });\n\n const document = await this.mongooseModel\n .findOne(filter, undefined, session ? { session } : undefined)\n .exec();\n\n return this.transformDocumentToResponse<T>(document, CoreResourceOperation.READ);\n }\n\n /**\n * ADAPTER-NEUTRAL atomic counter primitive (MongoDB arm) — add `delta` to one numeric column on\n * the single row matching `filter`, optionally `$set`ting other fields in the SAME statement, and\n * return the row as it stands AFTER the write.\n *\n * A shorthand over {@link atomicGuardedMutation}. Both replaced a raw-MongoDB\n * `atomicConditionalUpdate` (since retired) whose contract was arbitrary `$`-operators, which no\n * SQL adapter can honour — so a counter built on it silently stopped working on PostgreSQL.\n * \"Increment a field under a guard\" is something every adapter can implement truthfully, so\n * read-modify-write counters (token budgets, usage tallies, progression counts) stay correct and\n * race-free on both.\n *\n * Atomicity comes from the single `findOneAndUpdate` round-trip: concurrent callers each apply\n * their own delta; none reads-then-writes a stale value.\n *\n * @param filter - Pre-built filter, INCLUDING any guard conditions. Callers reach this through the\n * registry, which applies the retention-hide predicate first (a retained row is immutable).\n * @returns The updated row, or `null` when the filter matched nothing (guard failed / not found).\n */\n public async atomicIncrementField<T = any>(\n filter: Record<string, unknown>,\n field: string,\n delta: number,\n setFields?: Record<string, unknown>,\n options?: RepositoryOptions,\n ): Promise<T | null> {\n // `delta === 0` omits the increment entirely, degrading the call to a GUARDED SET. That is not a\n // micro-optimisation: a counter reset (e.g. rolling a budget period) must overwrite the field\n // rather than add to it, and MongoDB rejects an update whose `$inc` and `$set` touch the same\n // path (\"would create a conflict\"). One primitive therefore covers both add-to and reset-to.\n return this.atomicGuardedMutation<T>(\n filter,\n { ...(delta === 0 ? {} : { increment: { [field]: delta } }), set: setFields },\n options,\n );\n }\n\n /**\n * ADAPTER-NEUTRAL guarded set-and-clear (MongoDB arm) — set fields and/or CLEAR fields on the\n * single row matching `filter`, returning the row as it stands AFTER the write.\n *\n * **Why this exists.** Clearing a field had no expression on the repository contract at all. The\n * only way to do it was the raw-MongoDB `atomicConditionalUpdate` (since retired), which reached\n * for `mongooseModel` and threw on any other adapter — so every clear was also, silently, a\n * MongoDB pin. The file-cleanup batch is the case that\n * forced this: it clears stale link metadata off timed-out and malformed rows, and without a\n * neutral primitive a PostgreSQL-backed FILES resource would accept writes and then strand every\n * row that batch exists to normalize, failing in a background job far from the configuration that\n * caused it.\n *\n * Atomicity comes from the single `findOneAndUpdate` round-trip, and the caller's guard\n * conditions travel in `filter`, so this is a genuine compare-and-set on both adapters.\n *\n * **Scope, stated so it is not mistaken for more.** This is the GUARDED path. The ordinary\n * `update()` path still cannot clear a field (mongoose ignores `undefined`, and the framework\n * repository issues `$set` only) — see `m2m-webhook-delivery-log.repository.ts`, which documents\n * living with a stale `nextAttemptAt` for exactly that reason. That surface is a separate,\n * still-open gap; this primitive does not close it.\n *\n * @param filter - Pre-built filter INCLUDING guard conditions. Callers reach this through the\n * registry, which applies the retention-hide predicate first (a retained row is immutable).\n * @param clearFields - Field names to remove. Compiles to `$unset` here and to `SET col = NULL`\n * on PostgreSQL, which the `$exists` translation makes observationally identical.\n * @returns The updated row, or `null` when the filter matched nothing (guard failed / not found).\n */\n public async atomicConditionalSet<T = any>(\n filter: Record<string, unknown>,\n setFields: Record<string, unknown> | undefined,\n clearFields: readonly string[] | undefined,\n options?: RepositoryOptions,\n ): Promise<T | null> {\n return this.atomicGuardedMutation<T>(filter, { set: setFields, clear: clearFields }, options);\n }\n\n /**\n * INSERT one already-built document, below the operation tier.\n *\n * The document is CAST through the model's schema (`Model.castObject`) and then written through\n * the driver collection. Both halves are deliberate, and the split is what fixes issue #71:\n *\n * - **Cast, because this tier's other members cast.** `readUnscopedByKey`, `updateManyByRawFilter`,\n * `countByRawFilter` and the guarded mutations all go through the mongoose Model, which casts\n * FILTERS to the schema's types (`isForeignKey` paths are `Schema.Types.ObjectId`). An uncast\n * insert therefore stored a string where every sibling queries an ObjectId, and **a row written\n * by this tier was not reliably findable by this tier**: `revokeTokensByRelatedId` matched 0\n * rows that existed, and a model read dropped the uncastable stored value (`userId: undefined`)\n * without a sound. De-casting the five model members instead was rejected because they also\n * serve rows written by the NORMAL model paths — `bulkUpdateForInfrastructure`'s billing caller\n * filters `_id: { $in: … }` on ordinary usage-record rows, where the cast is what makes the\n * match, and a miss there is that caller's documented DUPLICATE-CHARGE condition. This also\n * mirrors the PostgreSQL arm, which routes the same insert through `toSqlWriteRow` — \"the same\n * projection every other write here uses\" — for exactly this reason.\n * - **Driver collection, because the callers build a COMPLETE document** — their own `_id`, their\n * own `createdAt`/`updatedAt` — and routing through a model WRITE would layer schema defaults\n * and the `timestamps` hook over a document that is already final. `castObject` does neither:\n * it applies the schema's type CASTS only — no defaults, no timestamps, no validation — so the\n * \"already final\" contract survives while the representation stops disagreeing.\n *\n * An uncastable value (a non-ObjectId string on an `isForeignKey` path) now throws at the WRITE,\n * loudly, exactly as the same value would on an ordinary model create — instead of storing a row\n * that no cast filter can ever match, which was this defect's silent form.\n *\n * Returns the CALLER's document, not the cast one: the cast document carries ObjectId instances,\n * and this tier's read members hand those back as strings (the schema's `toObject` transform), so\n * the input is already the round-trip shape — matching the PostgreSQL arm's string-typed return.\n *\n * retention-gate: N/A — INSERTs a brand-new row, so there is no existing row for a hide to\n * protect. A retained row is reached only through a filter, and this statement carries none.\n */\n public async insertRawDocument<T = any>(document: Record<string, unknown>, options?: RepositoryOptions): Promise<T> {\n const session = this.getNativeSession(options);\n\n /**\n * CAST THROUGH THE SCHEMA before writing, exactly as the PostgreSQL arm does with\n * `toSqlWriteRow`. A caller on this tier hands over a DOMAIN document; converting it to the\n * adapter's storage representation is this adapter's business, not the caller's.\n *\n * Without this, the raw driver stored the domain value verbatim while every OTHER method here\n * queries through the Mongoose Model, which CASTS. The two disagreed for any field whose\n * declared Zod type this adapter overrides — notably `z.string().isForeignKey()`, which the\n * schema convertor maps to `Schema.Types.ObjectId`. A row written by this tier was then\n * unmatchable by this tier: `revokeTokensByRelatedId` filtered on `relatedId` and got 0 for a\n * row that existed, silently, with a perfectly well-formed id. Measured on one row, one filter:\n * raw driver matched 1, the Model matched 0.\n *\n * `castObject` applies schema casting ONLY — no defaults, no validation — which is what keeps\n * this an insert of an already-built document rather than a model create. It THROWS on a value\n * the schema cannot represent, and that is deliberate: the alternative is what this replaced,\n * a write that appears to succeed and produces a row nothing can find.\n *\n * The RETURN stays the caller's domain document, matching the PostgreSQL arm, which returns a\n * domain-shaped row. Only the stored bytes change.\n */\n let storageDocument: Record<string, unknown>;\n try {\n storageDocument = this.mongooseModel.castObject(document as any, { ignoreCastErrors: false }) as Record<string, unknown>;\n } catch (error) {\n // Classified, adapter-neutral refusal — the same argument as the E11000→CONFLICT translation\n // below: a caller must not need adapter-specific detection to understand a refusal. Field\n // NAMES only, never values — this tier's first caller writes secrets (consumable tokens), and\n // the messages mongoose attaches carry the rejected values verbatim.\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n context: {\n reason: 'infrastructure_insert_document_not_castable',\n resourceType: (this.resourceConfiguration as { resourceType?: string })?.resourceType,\n fields: Object.keys((error as { errors?: Record<string, unknown> })?.errors ?? {}),\n },\n });\n }\n\n /**\n * An UNKNOWN top-level key — one the model has no path for — is refused by name, never silently\n * dropped. The strict-schema cast strips such keys, and even a preserved one would be invisible:\n * the model-side reads on this tier hydrate schema paths only. Both silences are the defect\n * class this method exists to remove.\n *\n * TOP LEVEL only, stated rather than implied: a key nested inside a cast subdocument is the\n * subdocument schema's business, and this predicate deliberately does not walk into it.\n *\n * Keys holding `undefined` OR `null` are exempt — the cast legitimately omits both, and their\n * ABSENCE is strictly better than what the old raw insert stored: an `.optional()` schema field\n * accepts a missing key on read and REJECTS a literal `null`, so persisting the null would\n * produce a row the strict re-parse cannot serve (the same trap the field-clearing contract\n * documents for updates). Flagging them as \"unknown\" would also be a wrong diagnosis — the\n * model knows the field perfectly well; it is the VALUE the cast declines to carry.\n */\n const unknownKeys = Object.keys(document).filter(\n (key) => document[key] !== undefined && document[key] !== null && !(key in storageDocument),\n );\n if (unknownKeys.length > 0) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n context: {\n reason: 'infrastructure_insert_unknown_fields',\n resourceType: (this.resourceConfiguration as { resourceType?: string })?.resourceType,\n unknownKeys,\n },\n });\n }\n\n try {\n await this.mongooseModel.collection.insertOne(storageDocument as any, session ? { session } : {});\n } catch (error) {\n // Translated to the CONFLICT contract, exactly as the PostgreSQL arm does. Without this the\n // two arms would report a duplicate DIFFERENTLY — a raw `E11000` here versus a classified\n // CONFLICT there — and every caller would need adapter-specific detection, which is precisely\n // what this tier exists to remove. `handleMongoDBError` returns non-duplicate errors untouched.\n throw this.handleMongoDBError(error);\n }\n return document as T;\n }\n\n /**\n * READ many rows matching an already-built filter, below the operation tier.\n *\n * The multi-row counterpart of `readUnscopedByKey`, and it goes through the SAME mongoose door —\n * `Model.find` with a per-document `toObject()` — for the same issue-#71 reason `insertRawDocument`\n * now casts: this tier's filters must mean one thing across all of its members. The previous raw\n * `collection.find` compared a string filter against the ObjectId values the schema stores on\n * `isForeignKey` paths, so this member could not find rows every model-side sibling could — and\n * could not find what a cast `insertRawDocument` writes.\n *\n * `toObject()` (not `.lean()`) keeps the return the tier's documented shape: plain stored\n * documents with the schema's ObjectId→string transform applied — byte-for-byte what\n * `readUnscopedByKey` returns for one row, and string-typed like the PostgreSQL arm's\n * `transformPersistenceRow` output.\n *\n * retention-gate: N/A — the hide is applied ONCE by the caller on this tier, matching every\n * sibling here.\n */\n public async findManyByRawFilter<T = any>(filter: Record<string, unknown>, options?: RepositoryOptions): Promise<T[]> {\n const session = this.getNativeSession(options);\n const documents = await this.mongooseModel\n .find(filter as FilterQuery<any>, null, session ? { session } : {})\n .exec();\n return documents.map((document) => (document.toObject ? document.toObject() : document)) as T[];\n }\n\n /**\n * Compile the adapter-neutral guarded mutation into a MongoDB update expression.\n *\n * Extracted from `atomicGuardedMutation` so the SINGLE-row and MULTI-row guarded writes cannot\n * drift: the descriptor's whole rationale is that \"each adapter now has a single place where\n * guarded-write semantics are decided, rather than three places that must agree\", and two inline\n * copies of this compilation would have reinstated exactly that.\n *\n * ## Why this `$set` does not carry the field-clearing partition\n *\n * The extraction MOVED the statement here, so the waiver that used to sit on `atomicGuardedMutation`\n * had to move with it. It is restated rather than copied, because the original was one asserted\n * sentence and the reasoning below was measured (2026-08-27):\n *\n * - **This vocabulary already HAS a clear channel.** `RepositoryGuardedMutation` splits `set`\n * (\"paths to assign\") from `clear` (\"paths to remove\"). A `null` in `set` is therefore an\n * explicit instruction to STORE null — not the JSON-Merge-Patch \"this field has no value\" that\n * `partitionNullClearedFields` exists to interpret. Partitioning here would give the descriptor a\n * SECOND, implicit removal channel and collapse the distinction `clear` exists to express.\n * - **No wire payload can reach this statement.** Both doors — the registry's\n * `atomicGuardedMutation` and `bulkUpdateForInfrastructure`, plus the `atomicIncrementField` /\n * `atomicConditionalSet` shorthands that delegate to them — are `@internal` and sit BELOW the\n * operation tier, so no validated UPDATE DTO (the only thing that carries a caller's null)\n * arrives. Enumerated rather than assumed: 12 descriptors across 7 engine files (consumable\n * tokens, lifecycle evaluator, files cleanup, credit pool, promotions, usage metering, A2A token\n * budget). Every `set` value is a constant, a `new Date()`, an enum member, a number, a boolean\n * or an array; NONE is null, and the two call sites that genuinely remove fields — the\n * file-cleanup batch and every token revocation — already use `clear`.\n * - **The partition is FIELD-keyed; this vocabulary is PATH-keyed.** `partitionNullClearedFields`\n * resolves each key through `getObjectLikeFieldSchema`, a top-level shape lookup with no dotted\n * traversal, while a guarded mutation routinely addresses `stageHistory.1.exitedAt` or\n * `engagement.operationsSinceActivation`. A null at such a path would miss the schema, land in\n * `unresolvedFieldNames`, and be `$unset` on the safe-direction fallback with a warning on every\n * write — while the PostgreSQL arm compiles the same null to a jsonb null that leaves the key\n * PRESENT. That is a NEW nested-path divergence, and it is the one the PostgreSQL `clear` branch\n * already refuses to create (\"assigning JSON null would leave the key PRESENT and make\n * `{ $exists: false }` disagree across adapters\").\n *\n * **The residual, stated rather than hidden.** Nothing MECHANICALLY stops a future caller writing\n * `set: { someOptionalField: null }`; on this adapter that stores a literal null which a later\n * ordinary READ cannot parse. Unbypassable is genuinely unavailable at this statement — a refusal\n * would need the same schema lookup the third bullet shows cannot answer for a path, and the two\n * shorthand doors bypass the descriptor-level expressibility check where such a rule would belong.\n * Tracked as owed work in issue #76 rather than absorbed here; the `clear` channel is the portable\n * answer and `RepositoryGuardedMutation.set` now says so at the surface every caller reads.\n */\n // field-clearing: N/A — `set` is an explicit ASSIGN channel and `clear` is the removal channel, so\n // no caller-supplied clear-instruction null reaches this statement (12 descriptors enumerated), and\n // the partition is field-keyed where this vocabulary is path-keyed. Full reasoning in the JSDoc above.\n private compileGuardedMutationToMongoUpdate(mutation: RepositoryGuardedMutation): Record<string, unknown> {\n const update: Record<string, unknown> = {};\n\n if (mutation.set && Object.keys(mutation.set).length > 0) update.$set = mutation.set;\n if (mutation.clear && mutation.clear.length > 0) {\n update.$unset = Object.fromEntries(mutation.clear.map((fieldName) => [fieldName, 1]));\n }\n if (mutation.increment && Object.keys(mutation.increment).length > 0) update.$inc = mutation.increment;\n\n for (const addition of mutation.arrayAdditions ?? []) {\n if (addition.values.length === 0) continue;\n if (addition.distinctOnly) {\n // The registry's expressibility rule has already refused `distinctOnly` combined with HEAD\n // placement or `maxLength`, so `$addToSet` is reachable only in the form it can honour.\n const addToSet = (update.$addToSet ??= {}) as Record<string, unknown>;\n addToSet[addition.path] = { $each: [...addition.values] };\n continue;\n }\n const push = (update.$push ??= {}) as Record<string, unknown>;\n push[addition.path] = {\n $each: [...addition.values],\n ...(addition.placement === RepositoryArrayAdditionPlacement.HEAD ? { $position: 0 } : {}),\n ...(addition.maxLength === undefined\n ? {}\n : { $slice: addition.placement === RepositoryArrayAdditionPlacement.HEAD ? addition.maxLength : -addition.maxLength }),\n };\n }\n\n return update;\n }\n\n /**\n * The MULTI-row guarded write: apply one mutation to EVERY row matching the filter, returning how\n * many were modified.\n *\n * retention-gate: N/A — the hide is applied ONCE by the caller\n * (`RepositoriesRegistryHandlerBackendService.bulkUpdateForInfrastructure`), matching every sibling\n * on this tier. A retained row must stay immutable, and excluding it there keeps the predicate in\n * one place.\n *\n * **Why the count is returned rather than a boolean.** Its billing caller reports usage to a\n * provider and then marks the records as reported; a PARTIAL marking is a duplicate-charge\n * condition, because whatever stayed unmarked is selected again by the next sweep. The caller\n * compares `modifiedCount` against the group size for exactly that reason, so a primitive that\n * flattened this to success/failure would make the condition unfalsifiable.\n */\n public async updateManyByRawFilter(\n filter: Record<string, unknown>,\n mutation: RepositoryGuardedMutation,\n options?: RepositoryOptions,\n ): Promise<number> {\n // NO-OP PARITY with the PostgreSQL arm and with the single-row path: an empty descriptor issues\n // no statement, rather than an empty update mongoose would still use to bump `updatedAt`.\n if (!guardedMutationHasWork(mutation)) return 0;\n\n const session = this.getNativeSession(options);\n const update = this.compileGuardedMutationToMongoUpdate(mutation);\n const result = await this.mongooseModel\n .updateMany(filter, update, { ...(session ? { session } : {}) })\n .exec();\n return result.modifiedCount ?? 0;\n }\n\n /**\n * The MULTI-row DELETE below the operation tier: destroy every row matching an already-built\n * filter, returning how many went.\n *\n * retention-gate: N/A — the hide is applied ONCE by the caller\n * (`RepositoriesRegistryHandlerBackendService.deleteManyForInfrastructure`), matching every sibling\n * on this tier. A retained (erased-but-kept) row is immutable, so it must never be reaped by a\n * framework sweep, and excluding it at the single dispatch point keeps the predicate in one place.\n *\n * rag-removal-gate: N/A — a raw repository door, bounded by the hourly RAG reconciliation sweep's\n * orphan reconciliation, exactly as `_doDelete` / `_doDeleteMany` are. The removal-seam guard\n * excludes this door family by declaration, not by omission.\n *\n * **The empty-filter refusal is the whole reason this is not one line.** `deleteMany({})` on the\n * native driver empties the collection and reports success, and the caller most likely to hand it\n * an empty filter is a background sweep whose predicate came out undefined — the quietest possible\n * route to total data loss. `updateManyByRawFilter` above can afford a no-op return because an\n * empty MUTATION writes nothing; an empty FILTER is the opposite, so it is refused rather than\n * degraded. The PostgreSQL arm refuses the same shape for the same reason.\n */\n public async deleteManyByRawFilter(\n filter: Record<string, unknown>,\n options?: RepositoryOptions,\n ): Promise<number> {\n // `Array.isArray` for the reason the handler states: an array's `Object.keys` are its indices,\n // so a non-empty array would pass a keys-length check and reach the driver as a filter.\n if (!filter || typeof filter !== 'object' || Array.isArray(filter) || Object.keys(filter).length === 0) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n reason: 'deleteManyByRawFilter requires a non-empty filter — refusing an unfiltered DELETE',\n },\n });\n }\n\n const session = this.getNativeSession(options);\n const result = await this.mongooseModel\n .deleteMany(filter, { ...(session ? { session } : {}) })\n .exec();\n return result.deletedCount ?? 0;\n }\n\n /**\n * Count rows matching an ALREADY-BUILT filter, with no operation and no authorization.\n *\n * retention-gate: N/A — the hide is applied ONCE by the caller\n * (`RepositoriesRegistryHandlerBackendService.countDocumentsForInfrastructure` passes the filter\n * through `applyRetentionHideToRawFilter`). Applying it a second time here would put the predicate\n * in two places, which is what the retention authority exists to prevent.\n *\n * **Why this exists.** The handler's infrastructure count used to reach\n * `(repository as any).mongooseModel` directly. That made a method with a general name work on ONE\n * adapter: on a PostgreSQL-backed resource it threw \"No underlying database model found\", so\n * field-uniqueness validation — its main caller — was broken for every such resource. Delegating to\n * a primitive each adapter implements is what makes the family's name true.\n *\n * Deliberately NOT the public `count(...)`: that requires a DECLARED `COUNT` operation and an\n * execution context, and an infrastructure caller has neither by design.\n */\n public async countByRawFilter(filter: Record<string, unknown>, options?: RepositoryOptions): Promise<number> {\n const session = this.getNativeSession(options);\n const query = this.mongooseModel.countDocuments(filter);\n if (session) query.session(session);\n return query.exec();\n }\n\n /**\n * The MongoDB update document for an ordinary versioned write, honouring the field-CLEARING\n * contract.\n *\n * Every ordinary update on this adapter goes through here — the single write, the CRDT retry\n * write, and the bulk write — because the contract is only real if it holds at all three. Issuing\n * a bare `$set` at any one of them would persist a literal `null` into a field whose schema\n * rejects null, so the write would succeed and the row would then be unreadable (`internalDto`\n * validates the after-image, and an `.optional()` field accepts absence but not null).\n *\n * `partitionNullClearedFields` owns the decision of WHICH nulls are clears; this method only\n * expresses it in MongoDB's vocabulary. `$set` is omitted entirely when nothing remains to write,\n * because MongoDB rejects an empty `$set` — reachable when a caller's only change is to clear\n * fields and no user-tracking field applies.\n *\n * This is the ordinary-path counterpart of `atomicGuardedMutation`'s `clear` channel, which\n * predates it and remains the door for explicit compare-and-swap clears.\n */\n private buildVersionedUpdateDocument(data: Record<string, unknown>): Record<string, unknown> {\n const { retainedData, clearedFieldNames, unresolvedFieldNames } = partitionNullClearedFields(\n data,\n this.resourceConfiguration.mainSchema,\n );\n\n if (unresolvedFieldNames.length > 0) {\n // The partition's safe-direction fallback fired: it cleared a field whose declaration it could\n // not find. Never an error — absence parses against every optional declaration — but it means\n // an authored `.nullish()` null could have been converted to an absence without anyone\n // knowing, so it is reported rather than assumed unreachable.\n this.logger.warn('Field-clearing partition could not resolve a field on the main schema', {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n unresolvedFieldNames,\n });\n }\n\n const updateDocument: Record<string, unknown> = { $inc: { _version_db_doc: 1 } };\n if (Object.keys(retainedData).length > 0) updateDocument.$set = retainedData;\n if (clearedFieldNames.length > 0) {\n updateDocument.$unset = Object.fromEntries(clearedFieldNames.map((fieldName) => [fieldName, 1]));\n }\n\n return updateDocument;\n }\n\n /**\n * ADAPTER-NEUTRAL guarded mutation (MongoDB arm) — the ONE compiler both primitives above are\n * shorthands over. See `RepositoryGuardedMutation` for the vocabulary and why it is a descriptor\n * rather than a third narrow primitive.\n *\n * Every part compiles to a native operator in a SINGLE `findOneAndUpdate`, so the caller's guard\n * conditions (which travel in `filter`) make this a genuine compare-and-set, and the row is never\n * observable half-mutated.\n *\n * `$slice`'s SIGN carries the placement: positive keeps the FIRST n elements, negative the LAST n.\n * Pairing it with the addition's own end is what makes `maxLength` mean \"keep the values nearest\n * `placement`\" — a bounded most-recent-first history keeps the newest precisely because the newest\n * were prepended.\n *\n * retention-gate: N/A — the hide is applied ONCE at the registry dispatch point\n * (`RepositoriesRegistryHandlerBackendService.atomicGuardedMutation` passes the caller's filter\n * through `applyRetentionHideToRawFilter`), which is the only route services take. Applying it a\n * second time here would put the predicate in two places, which is what the retention authority\n * exists to prevent. NOTE the residual this leaves: the method is public on the repository\n * contract, so app code holding a repository handle could call it directly and skip the hide —\n * a convention, not a mechanism.\n */\n // The field-clearing answer for this primitive now lives on `compileGuardedMutationToMongoUpdate`,\n // which owns the `$set` this method used to issue inline. Kept as a pointer rather than a second\n // copy: a waiver on a method that no longer carries the statement is a claim the guard cannot check.\n public async atomicGuardedMutation<T = any>(\n filter: Record<string, unknown>,\n mutation: RepositoryGuardedMutation,\n options?: RepositoryOptions,\n ): Promise<T | null> {\n // NO-OP PARITY with the PostgreSQL arm: issue no write at all rather than an empty update,\n // which mongoose would still use to bump `updatedAt`.\n if (!guardedMutationHasWork(mutation)) return null;\n\n const session = this.getNativeSession(options);\n const update = this.compileGuardedMutationToMongoUpdate(mutation);\n\n const document = await this.mongooseModel\n .findOneAndUpdate(filter, update, { returnDocument: 'after', ...(session ? { session } : {}) })\n .exec();\n\n if (!document) return null;\n return (document.toObject ? document.toObject() : document) as T;\n }\n\n /**\n * Find every row whose business-key matches one of the provided shapes,\n * scoped by the current execution context.\n *\n * Compiled into a single round-trip:\n * - `[]` returns immediately with no DB call;\n * - a single shape returns the bare per-shape filter (no `$or` wrapper)\n * so Mongo can use the most selective index directly;\n * - 2+ shapes are wrapped in a `$or`-disjunction (one branch per shape).\n *\n * The dispatcher uses this in `mode: SYNC` (Phase 4) to load every\n * existing seed-managed row for diff computation. See R-4 in the Phase 2\n * audit for the JSDoc/code alignment fix.\n */\n public async findManyByBusinessKeys<T = undefined>(\n executionContext: ExecutionContext<any>,\n businessKeyShapes: Array<Record<string, unknown>>,\n options?: RepositoryOptions,\n ): Promise<ConditionalArrayReturnType<T, TMainSchema>> {\n if (businessKeyShapes.length === 0) {\n return [] as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n const orBranches = businessKeyShapes.map((shape) =>\n this._tryBuildBusinessKeyFilter(executionContext, shape),\n );\n const baseFilter: FilterQuery<any> = orBranches.length === 1\n ? orBranches[0]\n : { $or: orBranches };\n\n const filter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.READ, options);\n\n const session = this.getNativeSession(options);\n this.logDebug('findManyByBusinessKeys', { count: businessKeyShapes.length, hasTransaction: !!session });\n\n const documents = await this.mongooseModel\n .find(filter, undefined, session ? { session } : undefined)\n .exec();\n\n return documents.map((doc) =>\n this.transformDocumentToResponse<T>(doc, CoreResourceOperation.LIST),\n ) as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n /**\n * Insert-or-update a row by its business key in a single atomic Mongo\n * `findOneAndUpdate({ upsert: true })` call.\n *\n * Spec refs: data-seeding-as-first-class-feature plan §3.7 (atomic\n * upsert + ledger), §5 (Phase 2 repository contract), and decision\n * P2-B (PG sibling parity). See `business-key-resolver.shared.utils.ts`\n * for the business-key resolution contract this method consumes.\n *\n * What gets written, atomically:\n * - The full `payload` (under `$set`) — caller must have already enriched\n * it with context fields (orgId, userId) and validated it against\n * `mainSchema`.\n * - The `__seed` ledger (under `$set`) — see\n * `DATA_SEED_ROW_METADATA_FIELD_KEY` in\n * `@wildo-ai/saas-backend-lib/src/data-seeding/models/`. Writing data\n * + ledger in the same `$set` is the whole reason `__seed` is nested\n * on the row (avoids \"row at v3, ledger still at v2\" partial states).\n * - The business-key fields themselves (under `$setOnInsert`) — guarantees\n * the freshly-inserted row carries the identity even if the caller\n * omitted those fields from `payload` (defensive).\n * - `_version_db_doc` is bumped via `$inc` so optimistic concurrency\n * keeps working on subsequent non-upsert writes (parity with the PG\n * sibling — see `postgresql-resource-repository.backend.service.ts`\n * `upsertByBusinessKey` and audit finding R-10).\n *\n * Returns `{ inserted, row }`:\n * - `inserted: true` iff this call created the row (Mongo upsert path).\n * - `inserted: false` iff this call updated a pre-existing row.\n * - `row` is the post-write document (always non-null because upsert\n * guarantees a row exists at return).\n *\n * @throws WildoError_Backend on Mongo write failure (E11000 etc., wrapped\n * by `handleMongoDBError`).\n */\n // field-clearing: N/A — the payload is validated against the CREATE DTO, which carries no nullable\n // wrapper, so a caller-supplied null is rejected before it can reach this `$set`.\n public async upsertByBusinessKey<T = undefined>(\n executionContext: ExecutionContext<any>,\n businessKeyShape: Record<string, unknown>,\n payload: Record<string, unknown>,\n seedMetadata: DataSeedRowMetadata,\n options?: RepositoryOptions,\n ): Promise<{ inserted: boolean; row: ConditionalReturnType<T, TMainSchema> }> {\n const businessKeyFilter = this._tryBuildBusinessKeyFilter(executionContext, businessKeyShape);\n const filter = this.buildContextualFilter(executionContext, businessKeyFilter, CoreResourceOperation.UPDATE, options);\n\n // WS-C: this upsert can INSERT, so it is governed by the row-creating rule. In practice seeding\n // runs under an internal system context, which narrowing exempts — the guard is here so that\n // coverage of the write surface is a PROPERTY of the chokepoint set rather than a consequence of\n // who happens to call it today.\n await this.assertOrganizationUnitWriteWithinGrant(payload, CoreResourceOperation.CREATE, executionContext);\n\n // The BUSINESS KEY is written by `$setOnInsert` below and must NOT also appear in `$set`:\n // MongoDB rejects an update document whose two operators touch one path\n // (`ConflictingUpdateOperators`, code 40 — \"would create a conflict at ...\"). The same holds\n // for every path another operator here owns: `_version_db_doc` belongs to `$inc`, and `_id` is\n // immutable on an update.\n //\n // That was always the contract — the integrity call just below already says \"the tracked\n // payload PLUS the `$setOnInsert` business key\" — but it lived only in prose, so a caller could\n // not see it and nothing enforced it.\n //\n // Enforced HERE rather than asked of callers because the invariant has one meaning and N call\n // sites: every seed in the framework, and now every external-data pipeline load. A caller\n // cannot avoid it — a seed UPGRADE writes the managed-field overlay, which is the PERSISTED row\n // with managed paths replaced, and a persisted row necessarily carries its own key and its own\n // version counter. Stripping is semantically free: these are paths this call MATCHES on or\n // OWNS, so a payload disagreeing with them could never be honoured anyway.\n //\n // Found by the first real-datastore proof of this path\n // (`external-data-pipeline-load.mongo.integration.test.ts`). No mock can raise\n // ConflictingUpdateOperators — it is a property of the driver's update document, not of our\n // shapes — and there were NO data-seeding integration tests against a real store at all, so\n // this whole write path had only ever met mocks.\n //\n // The engine-reserved half is applied via the NAMED rule (`isEngineReservedFieldName`) rather\n // than a hand-list, because the hand-list under-counted: it named `_version_db_doc` and `_id`\n // but not the PUBLIC `_version` that every read projection carries. On Mongo that wrote a junk\n // path under a strict schema (silent); on PostgreSQL the same payload names a column that does\n // not exist, which is how it was finally caught. One rule, both arms, and a future engine-owned\n // key needs no further enumeration.\n const payloadWithoutOperatorOwnedPaths = { ...payload };\n for (const operatorOwnedPath of Object.keys(payloadWithoutOperatorOwnedPaths)) {\n if (isEngineReservedFieldName(operatorOwnedPath)) delete payloadWithoutOperatorOwnedPaths[operatorOwnedPath];\n }\n for (const businessKeyPath of Object.keys(businessKeyShape)) {\n delete payloadWithoutOperatorOwnedPaths[businessKeyPath];\n }\n\n // Apply user-tracking on the same payload the caller validated. Anonymous\n // contexts simply skip the createdBy/updatedBy assignment (addUserTracking\n // is a no-op when initiatorIds.userId is missing).\n const trackedPayload = this.addUserTracking(payloadWithoutOperatorOwnedPaths, executionContext, CoreResourceOperation.UPDATE);\n\n // Coverage of the create-time write surface is a PROPERTY of the chokepoint set (see the org-unit\n // grant note above), not of who calls it today. An upsert that INSERTS is governed by the same\n // referential / cross-field rules; the effective inserted row is the tracked payload plus the\n // `$setOnInsert` business key. In practice seeding runs under an exempt internal context, so this\n // returns immediately — but a future non-exempt upsert-create inherits the guard for free.\n await assertCreateWriteIntegrity(\n this.writeIntegrityDeps,\n { ...businessKeyShape, ...trackedPayload },\n CoreResourceOperation.CREATE,\n seedMetadata.seedKey,\n executionContext,\n options,\n );\n\n const session = this.getNativeSession(options);\n const mongooseOpts: any = {\n upsert: true,\n // `returnDocument: 'after'` replaces the deprecated `new: true` (Mongoose maps\n // them identically — return the post-update document).\n returnDocument: 'after',\n includeResultMetadata: true,\n setDefaultsOnInsert: true,\n };\n if (session) {\n mongooseOpts.session = session;\n }\n\n this.logDebug('upsertByBusinessKey', {\n filter,\n hasTransaction: !!session,\n seedKey: seedMetadata.seedKey,\n seedVersion: seedMetadata.seedVersion,\n });\n\n let result: any;\n try {\n result = await this.mongooseModel.findOneAndUpdate(\n filter,\n {\n $set: {\n ...trackedPayload,\n [DATA_SEED_ROW_METADATA_FIELD_KEY]: seedMetadata,\n },\n $setOnInsert: { ...businessKeyShape },\n $inc: { _version_db_doc: 1 },\n },\n mongooseOpts,\n );\n } catch (error) {\n this.logDebug('upsertByBusinessKey failed', {\n error: describeCaughtError(error),\n filter,\n hasTransaction: !!session,\n });\n throw this.handleMongoDBError(error, executionContext);\n }\n\n // With includeResultMetadata: true, mongoose returns\n // { value: <doc>, lastErrorObject: { upserted?, updatedExisting }, ok: 1 }\n // updatedExisting === false on the insert path.\n const document = result?.value ?? null;\n const inserted = result?.lastErrorObject?.updatedExisting === false;\n\n const row = this.transformDocumentToResponse<T>(document, CoreResourceOperation.UPDATE) as ConditionalReturnType<T, TMainSchema>;\n return { inserted, row };\n }\n\n /**\n * Insert-or-update a singleton row by an explicit filter in one atomic Mongo\n * `findOneAndUpdate({ upsert: true })` call, without stamping `__seed`.\n *\n * This is intentionally separate from `upsertByBusinessKey`: data-seeding\n * owns `__seed`, while framework singleton materializers such as scope feature\n * ledgers need the same atomic persistence shape for normal resource writes.\n * The filter is still passed through contextual scoping unless callers opt out\n * through `RepositoryOptions`, matching the rest of the repository surface.\n */\n // field-clearing: N/A — CREATE-DTO validated, as `upsertByBusinessKey` above.\n public async upsertByFilter<T = undefined>(\n executionContext: ExecutionContext<any>,\n filterShape: Record<string, unknown>,\n payload: Record<string, unknown>,\n options?: RepositoryOptions,\n ): Promise<{ inserted: boolean; row: ConditionalReturnType<T, TMainSchema> }> {\n const isConcreteSingletonFilterValue = (value: unknown): boolean => {\n if (value === undefined || value === null) return false;\n if (typeof value === 'string') return value.length > 0;\n if (typeof value === 'number') return Number.isFinite(value);\n if (typeof value === 'boolean') return true;\n if (value instanceof Date) return !Number.isNaN(value.getTime());\n if (value instanceof Types.ObjectId) return true;\n return false;\n };\n const invalidFilterEntries = Object.entries(filterShape).filter(([, value]) =>\n !isConcreteSingletonFilterValue(value)\n );\n if (Object.keys(filterShape).length === 0 || invalidFilterEntries.length > 0) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n context: {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n message: 'upsertByFilter requires a non-empty filter with concrete singleton key values.',\n invalidFilterFields: invalidFilterEntries.map(([key]) => key),\n },\n });\n }\n\n const filter = this.buildContextualFilter(executionContext, filterShape as FilterQuery<any>, CoreResourceOperation.UPDATE, options);\n\n const cleanedPayload = this.resourceOperationHelper.cleanInputData(payload, CoreResourceOperation.CREATE);\n const validatedPayload = this.repositoriesRegistry.validateRequestData(\n cleanedPayload,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n CoreResourceOperation.CREATE,\n options,\n );\n const enrichedPayload = this.resourceOperationHelper.enrichDataWithContext(\n validatedPayload,\n executionContext,\n this.resourceConfiguration.mainSchema,\n this.resourceConfiguration.resourceFieldIdentifier,\n this.resourceConfiguration,\n CoreResourceOperation.CREATE,\n options,\n );\n\n // WS-C: an upsert can INSERT, so it is governed by the row-creating rule — the contextual filter\n // above constrains which row is matched, never the unit a newly inserted row would land in.\n await this.assertOrganizationUnitWriteWithinGrant(enrichedPayload, CoreResourceOperation.CREATE, executionContext);\n\n // Create-time write integrity for the INSERT branch — the SAME rule `upsertByBusinessKey` applies,\n // so this insert path cannot silently skip FK-existence / scope-membership / top-level checks. The\n // effective inserted row is the enriched payload plus the filter's singleton key. In practice the\n // callers (feature/billing/milestone/platform singleton materializers) run under an exempt internal\n // context, so this returns immediately; a future non-exempt upsert-create inherits the guard for\n // free. No `operation` here → the relationship baseline applies, exactly like the business-key path.\n await assertCreateWriteIntegrity(\n this.writeIntegrityDeps,\n { ...enrichedPayload, ...filterShape },\n CoreResourceOperation.CREATE,\n CoreResourceOperation.CREATE,\n executionContext,\n options,\n );\n\n if (executionContext.isAnonymousExecution() && this.resourceConfiguration.isAnonymizable) {\n enrichedPayload.userId = null;\n }\n\n const payloadWithLiterals = this.resourceOperationHelper.injectNonDiscriminatorLiteralValues(\n enrichedPayload,\n this.resourceConfiguration.mainSchema,\n );\n\n // Zod CREATE validation can materialize defaults that are correct for an\n // inserted row but dangerous on the update branch of an upsert. Only fields\n // explicitly authored by the caller may be `$set`; schema defaults remain\n // insert-time defaults via `setDefaultsOnInsert`.\n const explicitPayloadKeys = new Set(Object.keys(payload));\n const explicitPayloadWithLiterals = Object.fromEntries(\n Object.entries(payloadWithLiterals).filter(([key]) => explicitPayloadKeys.has(key))\n );\n const insertOnlyPayloadWithLiterals = Object.fromEntries(\n Object.entries(payloadWithLiterals).filter(([key]) =>\n !explicitPayloadKeys.has(key) &&\n !Object.prototype.hasOwnProperty.call(filterShape, key)\n )\n );\n const updatePayload = this.addUserTracking(\n { ...explicitPayloadWithLiterals },\n executionContext,\n CoreResourceOperation.UPDATE,\n );\n delete (updatePayload as Record<string, unknown>)._version_db_doc;\n for (const key of Object.keys(filterShape)) {\n delete (updatePayload as Record<string, unknown>)[key];\n }\n\n const insertOnlyPayload = this.addUserTracking(\n { ...insertOnlyPayloadWithLiterals, ...filterShape },\n executionContext,\n CoreResourceOperation.CREATE,\n );\n delete (insertOnlyPayload as Record<string, unknown>)._version_db_doc;\n\n const session = this.getNativeSession(options);\n const mongooseOpts: any = {\n upsert: true,\n // `returnDocument: 'after'` replaces the deprecated `new: true` (Mongoose maps\n // them identically — return the post-update document).\n returnDocument: 'after',\n includeResultMetadata: true,\n setDefaultsOnInsert: true,\n };\n if (session) {\n mongooseOpts.session = session;\n }\n\n this.logDebug('upsertByFilter', {\n filter,\n hasTransaction: !!session,\n });\n\n let result: any;\n try {\n result = await this.mongooseModel.findOneAndUpdate(\n filter,\n {\n $set: updatePayload,\n $setOnInsert: insertOnlyPayload,\n $inc: { _version_db_doc: 1 },\n },\n mongooseOpts,\n );\n } catch (error) {\n this.logDebug('upsertByFilter failed', {\n error: describeCaughtError(error),\n filter,\n hasTransaction: !!session,\n });\n throw this.handleMongoDBError(error, executionContext);\n }\n\n const document = result?.value ?? null;\n const inserted = result?.lastErrorObject?.updatedExisting === false;\n const row = this.transformDocumentToResponse<T>(document, CoreResourceOperation.UPDATE) as ConditionalReturnType<T, TMainSchema>;\n return { inserted, row };\n }\n\n /**\n * Mongo implementation of `BackendResourceRepository.updateSeedMetadata`.\n *\n * Privileged write path for the `__seed` row-metadata ledger ONLY.\n * See the interface JSDoc on `BackendResourceRepository.updateSeedMetadata`\n * (in `repositories-registry-handler.backend.service.ts`) for the full\n * rationale — short version: app resources never declare `__seed` on\n * their UPDATE `requestDto`, so the standard `update(...)` path would\n * `.strip()` it. This method bypasses `cleanInputData` +\n * `validateRequestData` and writes directly via `findOneAndUpdate`.\n *\n * Atomicity guarantees:\n * - Single `findOneAndUpdate` call → atomic at the document level.\n * - `$set` writes the full `__seed` ledger AND user-tracking together.\n * - `$inc` on `_version_db_doc` keeps optimistic-locking parity with\n * `_doUpdate` (the same convention `upsertByBusinessKey` honors).\n *\n * Contextual scoping (R3-1 review note):\n * - We DO apply `buildContextualFilter` for defense-in-depth — the\n * dispatcher always calls this from an internal super-admin context\n * that bypasses scope filters anyway, but if a future caller\n * accidentally invokes from a tenant-scoped context the scoping\n * would correctly prevent cross-scope writes (instead of silently\n * succeeding then failing on the next read).\n *\n * @throws WildoError_Backend(NOT_FOUND) when the `_id` doesn't match.\n * @throws WildoError_Backend on Mongo write failure.\n */\n // field-clearing: N/A — writes only the engine-reserved `__seed` ledger, never an authored field.\n // rag-ingestion-gate: N/A — writes only the engine-reserved `__seed` ledger (plan §3.c M5), so no\n // `.ragSource()` corpus text ever passes through this door; any drift class it could theoretically\n // join is bounded by the hourly RAG reconciliation sweep's contentHash comparison.\n public async updateSeedMetadata(\n executionContext: ExecutionContext<any>,\n id: string,\n seedMetadata: DataSeedRowMetadata,\n options?: RepositoryOptions,\n ): Promise<void> {\n const baseFilter = { _id: id };\n const filter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.UPDATE, options);\n\n // User-tracking only (no body validation). Anonymous contexts\n // become a no-op on `addUserTracking` per the same convention as\n // `upsertByBusinessKey`.\n const trackedPayload: Record<string, unknown> = this.addUserTracking({}, executionContext, CoreResourceOperation.UPDATE);\n\n const session = this.getNativeSession(options);\n const mongooseOpts: any = { returnDocument: 'after' };\n if (session) {\n mongooseOpts.session = session;\n }\n\n this.logDebug('updateSeedMetadata', {\n id,\n seedKey: seedMetadata.seedKey,\n seedVersion: seedMetadata.seedVersion,\n hasDeprecated: seedMetadata.deprecated !== null,\n hasTransaction: !!session,\n });\n\n let document;\n try {\n document = await this.mongooseModel.findOneAndUpdate(\n filter,\n {\n $set: {\n ...trackedPayload,\n [DATA_SEED_ROW_METADATA_FIELD_KEY]: seedMetadata,\n },\n $inc: { _version_db_doc: 1 },\n },\n mongooseOpts,\n );\n } catch (error) {\n this.logDebug('updateSeedMetadata failed', {\n error: describeCaughtError(error),\n id,\n });\n throw this.handleMongoDBError(error, executionContext);\n }\n\n if (!document) {\n throw this.errorBuilder.buildError(\n ErrorType.NOT_FOUND,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_SEED_METADATA_NOT_FOUND,\n context: {\n // diagnostic (log-only)\n resourceIdentifier: this.resourceConfiguration.resourceIdentifier,\n id,\n },\n },\n );\n }\n }\n\n /**\n * Wrap the schema-level business-key resolution so any\n * `BUSINESS_KEY_ERROR_PREFIX`-tagged failure (no business-key declared,\n * shape missing/extra fields, undefined values) bridges to a typed\n * `INTERNAL` repository error instead of a bare `Error`.\n *\n * All errors out of `buildBusinessKeyFilter` are programmer mistakes\n * (the seed dispatcher constructs the shape from the seed's own\n * declaration; the user never authors it). Classifying them as\n * `INTERNAL` rather than `VALIDATION` keeps the dispatcher's error\n * stream consistent with the resolver's own JSDoc contract — see\n * `business-key-resolver.shared.utils.ts` and audit finding R-3.\n * Untagged errors are bridged to `INTERNAL` too with an explicit note,\n * since they cannot have come from user input either.\n */\n private _tryBuildBusinessKeyFilter(\n executionContext: ExecutionContext<any>,\n businessKeyShape: Record<string, unknown>,\n ): FilterQuery<any> {\n try {\n return buildBusinessKeyFilter(this.resourceConfiguration.mainSchema, businessKeyShape) as FilterQuery<any>;\n } catch (error) {\n const message = describeCaughtError(error);\n const isTagged = message.startsWith(BUSINESS_KEY_ERROR_PREFIX);\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED,\n context: {\n resourceIdentifier: this.resourceConfiguration.resourceIdentifier,\n message: isTagged ? message : `[business-key:untagged] ${message}`,\n },\n },\n );\n }\n }\n\n // ================================\n // Core Private Operations\n // ================================\n\n /**\n * retention-gate: N/A — INSERTs a brand-new row, so there is no existing row for a hide to protect.\n * A retained row is reached only through a filter, and this statement carries none.\n */\n private async _doCreate<T = undefined>(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n data: MainSchemaType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalReturnType<T, TMainSchema>> {\n this.logDebug('Creating resource', { hasData: !!data, dataKeys: typeof data === 'object' ? Object.keys(data) : 'not-object' });\n\n // Clean input data FIRST (remove mandatory discard fields)\n const cleanedData = this.resourceOperationHelper.cleanInputData(data, CoreResourceOperation.CREATE);\n this.logDebug('Data cleaned', { cleanedKeys: typeof cleanedData === 'object' ? Object.keys(cleanedData) : 'not-object' });\n\n // Validate against request DTO (after cleaning)\n const validatedData = this.repositoriesRegistry.validateRequestData(\n cleanedData,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n CoreResourceOperation.CREATE,\n options,\n );\n this.logDebug('Data validated against requestDto', { validatedKeys: typeof validatedData === 'object' ? Object.keys(validatedData) : 'not-object' });\n\n // THEN apply execution context data enrichment to the validated data\n const enrichedData = this.resourceOperationHelper.enrichDataWithContext(validatedData, executionContext, this.resourceConfiguration.mainSchema, this.resourceConfiguration.resourceFieldIdentifier,\n this.resourceConfiguration, CoreResourceOperation.CREATE, options);\n this.logDebug('Data enriched with context', { enrichedKeys: typeof enrichedData === 'object' ? Object.keys(enrichedData) : 'not-object' });\n\n // WS-C: no filter can constrain a create, so the unit the row lands in is checked here.\n await this.assertOrganizationUnitWriteWithinGrant(enrichedData, CoreResourceOperation.CREATE, executionContext);\n\n // Defense-in-depth: anonymous creation on isAnonymizable resources must have userId = null\n if (executionContext.isAnonymousExecution() && this.resourceConfiguration.isAnonymizable) {\n enrichedData.userId = null;\n }\n\n // Inject non-discriminator literal values from schema (e.g., scope: 'ORGANIZATION')\n // These are fixed values excluded from CREATE DTOs but must be persisted\n const dataWithLiterals = this.resourceOperationHelper.injectNonDiscriminatorLiteralValues(enrichedData, this.resourceConfiguration.mainSchema);\n this.logDebug('Non-discriminator literals injected', { dataWithLiteralsKeys: typeof dataWithLiterals === 'object' ? Object.keys(dataWithLiterals) : 'not-object' });\n\n // Add user tracking to enriched data\n const dataWithUserTracking = this.addUserTracking(dataWithLiterals, executionContext, CoreResourceOperation.CREATE);\n this.logDebug('User tracking added', { finalKeys: typeof dataWithUserTracking === 'object' ? Object.keys(dataWithUserTracking) : 'not-object' });\n\n // Create-time write integrity (adapter-neutral authority): FK existence-in-scope + top-level\n // mainSchema cross-field checks, against the FULLY-ENRICHED row (never the request DTO, which omits\n // backend-injected fields). A create has no filter/pre-image, so this is the only place a dangling\n // or cross-tenant FK is caught, and where a junction's `source ≠ target` rejects a self-link.\n await assertCreateWriteIntegrity(\n this.writeIntegrityDeps,\n dataWithUserTracking,\n CoreResourceOperation.CREATE,\n operation.operationIdentifier,\n executionContext,\n options,\n referenceConstraintsOf(operation),\n );\n\n try {\n const nativeSession = this.getNativeSession(options);\n this.logDebug('Creating document with Model.create()...', {\n hasTransaction: !!nativeSession\n });\n\n // Use transaction session if provided\n const createOptions: any = nativeSession ? { session: nativeSession } : {};\n\n // DEBUG: Log the exact data being passed to mongoose\n this.logDebug('\\n=== DEBUG: About to call mongoose create ===');\n // Use the bigint-safe serializer: resource data may carry `z_money` (MoneyValue)\n // amounts stored as `bigint`, which a bare `JSON.stringify` cannot serialize\n // (\"Do not know how to serialize a BigInt\"). This eager argument is evaluated on\n // every create regardless of log level, so a bare stringify here throws before the\n // mongoose write for any money-bearing resource (e.g. billing prices).\n this.logDebug('dataWithUserTracking:', { dataWithUserTracking: ResourceSerializationUtils.stringifyWithBigInt(dataWithUserTracking, 2) });\n this.logDebug('keys:', { keys: Object.keys(dataWithUserTracking || {}) });\n this.logDebug('dataType:', { dataType: typeof dataWithUserTracking });\n this.logDebug('hasName:', { hasName: !!(dataWithUserTracking as any)?.name });\n this.logDebug('hasSlug:', { hasSlug: !!(dataWithUserTracking as any)?.slug });\n this.logDebug('nameValue:', (dataWithUserTracking as any)?.name);\n this.logDebug('slugValue:', { slugValue: (dataWithUserTracking as any)?.slug });\n\n // DEBUG: Log mongoose schema info\n this.logDebug('Mongoose model name:', { mongooseModelName: this.mongooseModel.modelName });\n this.logDebug('Mongoose schema paths:', { mongooseSchemaPaths: Object.keys(this.mongooseModel.schema.paths) });\n this.logDebug('Required paths:', { requiredPaths: Object.keys(this.mongooseModel.schema.paths).filter(path => {\n const schemaType = this.mongooseModel.schema.paths[path];\n return schemaType.isRequired;\n }) });\n\n this.logDebug('Name field config:', { nameFieldConfig: this.mongooseModel.schema.paths['name']?.isRequired, nameFieldInstance: this.mongooseModel.schema.paths['name']?.instance });\n this.logDebug('Slug field config:', { slugFieldConfig: this.mongooseModel.schema.paths['slug']?.isRequired, slugFieldInstance: this.mongooseModel.schema.paths['slug']?.instance });\n this.logDebug('Status field config:', { statusFieldConfig: this.mongooseModel.schema.paths['status']?.isRequired, statusFieldInstance: this.mongooseModel.schema.paths['status']?.instance });\n this.logDebug('=======================================\\n');\n\n // Mongoose only honors create() options like `session` when they are passed\n // through the variadic docs+options signature. For a single-document create,\n // using the array form preserves transaction participation.\n const [savedDocument] = await this.mongooseModel.create([dataWithUserTracking], createOptions);\n this.logDebug('Document created successfully');\n\n return this.transformDocumentToResponse(savedDocument, CoreResourceOperation.CREATE);\n } catch (error) {\n this.logDebug('Mongoose create failed', {\n error: describeCaughtError(error),\n enrichedData: enrichedData,\n hasTransaction: !!this.getNativeSession(options)\n });\n\n // Handle MongoDB unique constraint violations (E11000 duplicate key error)\n throw this.handleMongoDBError(error, executionContext);\n }\n }\n\n\n /** retention-gate: N/A — bulk INSERT of brand-new rows; see `_doCreate`. */\n private async _doCreateMany<T = undefined>(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n dataArray: MainSchemaArrayType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalArrayReturnType<T, TMainSchema>> {\n this.logDebug('Creating multiple resources', { count: dataArray.length });\n\n // Clean input data FIRST (remove mandatory discard fields)\n const cleanedDataArray = this.resourceOperationHelper.cleanInputDataArray(dataArray, CoreResourceOperation.CREATE_MANY);\n this.logDebug('Data array cleaned', { count: cleanedDataArray.length });\n\n // CreateMany always processes multiple items\n\n // Validate and enrich each item\n const isAnonymousCreate = executionContext.isAnonymousExecution() && this.resourceConfiguration.isAnonymizable;\n const isBulkOperation = 'isBulkOperation' in operation && operation.isBulkOperation === true;\n // `async` + `Promise.all` because the per-row narrowing guard now performs a scoped tenant read.\n // Kept PER ROW rather than hoisted: a bulk create must not let one out-of-tenant row ride in on a\n // batch, which is the same reason the grant check was already per row.\n const processedDataArray = await Promise.all(cleanedDataArray.map(async (data, index) => {\n const rowScopedOptions = this.repositoriesRegistry.buildGeneratedPdfRowRepositoryOptions?.(options, index) ?? options;\n const validatedData = this.repositoriesRegistry.validateRepositoryWriteData(\n data,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n String(operation.operationIdentifier),\n isBulkOperation,\n rowScopedOptions,\n );\n const enrichedData = this.resourceOperationHelper.enrichDataWithContext(validatedData, executionContext, this.resourceConfiguration.mainSchema, this.resourceConfiguration.resourceFieldIdentifier,\n this.resourceConfiguration, CoreResourceOperation.CREATE_MANY, rowScopedOptions);\n // WS-C: checked PER ROW — a bulk create must not let one out-of-grant row ride in on a batch.\n await this.assertOrganizationUnitWriteWithinGrant(enrichedData, CoreResourceOperation.CREATE_MANY, executionContext);\n if (isAnonymousCreate) { enrichedData.userId = null; }\n // Inject non-discriminator literal values from schema\n const dataWithLiterals = this.resourceOperationHelper.injectNonDiscriminatorLiteralValues(enrichedData, this.resourceConfiguration.mainSchema);\n const finalRow = this.addUserTracking(dataWithLiterals, executionContext, CoreResourceOperation.CREATE_MANY);\n // Create-time write integrity PER ROW (see _doCreate) — one dangling/cross-tenant FK or invalid\n // cross-field row must not ride in on a batch.\n await assertCreateWriteIntegrity(\n this.writeIntegrityDeps,\n finalRow,\n CoreResourceOperation.CREATE_MANY,\n operation.operationIdentifier,\n executionContext,\n rowScopedOptions,\n referenceConstraintsOf(operation),\n );\n return finalRow;\n }));\n\n // Prepare mongoose options with transaction session if provided\n const session = this.getNativeSession(options);\n const mongooseOpts: any = session ? { session } : {};\n\n this.logDebug('Creating multiple documents', {\n count: processedDataArray.length,\n hasTransaction: !!session\n });\n\n // insertMany returns an array of documents by default (not InsertManyResult unless rawResult: true)\n // TypeScript infers the wrong type, so we cast through unknown\n const documents = await this.mongooseModel.insertMany(processedDataArray, mongooseOpts) as unknown as any[];\n\n return documents.map(doc => this.transformDocumentToResponse(doc, CoreResourceOperation.CREATE_MANY)) as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n\n private async _doRead<T = undefined>(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_filter?: IdOrFilterType,\n options?: RepositoryOptions\n ): Promise<ConditionalNullableReturnType<T, TMainSchema>> {\n const session = this.getNativeSession(options);\n this.logDebug('Reading resource', { id_or_filter, hasOptions: !!options, hasTransaction: !!session });\n\n // Validate required parameter\n this.validateIdOrIdsOrFilterRequired(\n id_or_filter,\n executionContext,\n CoreResourceOperation.READ,\n );\n\n // Build base filter - read operation is always unitary (single entity)\n const { baseFilter } = this.buildBaseFilterFromIdOrIdsOrFilter(id_or_filter, executionContext);\n\n const filter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.READ, options);\n\n // Prepare mongoose options with transaction session if provided\n const mongooseOpts: any = session ? { session } : {};\n\n // Read operation always returns single entity or null. A CastError here means a filter\n // value (e.g. a malformed or UUID-format `_id`) could not be cast to its field type, so NO\n // document can match — that is semantically a not-found, not an INTERNAL/500. (FILES is\n // Mongo-pinned, so a UUID-format `fileId` reaching `{ _id: <uuid> }` lands here.)\n let document: any;\n try {\n document = await this.mongooseModel.findOne(filter, null, mongooseOpts);\n } catch (error) {\n if (this.isMongooseCastError(error)) {\n this.logDebug('Read filter value could not be cast — treating as not-found', {\n filter,\n error: describeCaughtError(error),\n });\n return null;\n }\n throw error;\n }\n this.logDebug('Read single result', {\n filter,\n found: !!document,\n preview: this.previewDocument(document),\n hasTransaction: !!session\n });\n\n if (!document) {\n return null;\n }\n\n return this.transformDocumentToResponse<T>(document, CoreResourceOperation.READ);\n }\n\n\n private async _doUpdate<T = undefined>(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_filter?: IdOrFilterType,\n data?: PartialMainSchemaType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalNullableReturnType<T, TMainSchema>> {\n this.logDebug('Updating resource', { id_or_filter, hasData: !!data, hasOptions: !!options });\n\n // Validate required parameter\n this.validateIdOrIdsOrFilterRequired(id_or_filter, executionContext, CoreResourceOperation.UPDATE);\n\n if (!data) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED }\n );\n }\n\n // Clean input data FIRST (remove mandatory discard fields)\n const cleanedData = this.resourceOperationHelper.cleanInputData(data, CoreResourceOperation.UPDATE);\n this.logDebug('Data cleaned for update', { cleanedKeys: typeof cleanedData === 'object' ? Object.keys(cleanedData) : 'not-object' });\n\n // Validate against request DTO (after cleaning)\n const validatedData = this.repositoriesRegistry.validateRequestData(\n cleanedData,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n String(operation.operationIdentifier),\n options,\n );\n this.logDebug('Data validated against requestDto', { validatedKeys: typeof validatedData === 'object' ? Object.keys(validatedData) : 'not-object' });\n\n // THEN apply execution context data enrichment to the validated data\n const enrichedData = this.resourceOperationHelper.enrichDataWithContext(validatedData, executionContext, this.resourceConfiguration.mainSchema, this.resourceConfiguration.resourceFieldIdentifier,\n this.resourceConfiguration, CoreResourceOperation.UPDATE, options);\n this.logDebug('Data enriched with context', { enrichedKeys: typeof enrichedData === 'object' ? Object.keys(enrichedData) : 'not-object' });\n\n // WS-C: the contextual filter already confines WHICH row is updated; this confines the unit the\n // update may move it TO. An update that does not touch the unit field is unaffected.\n await this.assertOrganizationUnitWriteWithinGrant(enrichedData, CoreResourceOperation.UPDATE, executionContext);\n\n // Referential + scope-via-junction integrity for any FK this update REASSIGNS (e.g. a reassigned\n // `assignedToUserId` must still be a member of the row's tenant). Create-only checks miss it, and a\n // reassignable lateral FK to an org-less target is exactly the cross-tenant gap this closes. Absent\n // FKs are skipped inside; exempt executions (internal/webhook/anon/seed) are exempt at the entry.\n await assertUpdateWriteIntegrity(this.writeIntegrityDeps, enrichedData, CoreResourceOperation.UPDATE, executionContext, options, referenceConstraintsOf(operation));\n\n // Add user tracking to enriched data\n const dataWithUserTracking = this.addUserTracking(enrichedData, executionContext, CoreResourceOperation.UPDATE);\n this.logDebug('User tracking added', { finalKeys: typeof dataWithUserTracking === 'object' ? Object.keys(dataWithUserTracking) : 'not-object' });\n\n // Build base filter - update operation is always unitary (single entity)\n const { baseFilter } = this.buildBaseFilterFromIdOrIdsOrFilter(id_or_filter, executionContext);\n\n // Ensure we have some filter criteria\n if (Object.keys(baseFilter).length === 0) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED }\n );\n }\n\n // Apply contextual filtering\n const filter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.UPDATE, options);\n\n if (options?.ifMatchVersion !== undefined) {\n filter._version_db_doc = options.ifMatchVersion;\n this.logDebug('Optimistic locking: added version filter', { ifMatchVersion: options.ifMatchVersion });\n }\n\n // Prepare mongoose options with transaction session if provided\n const session = this.getNativeSession(options);\n const mongooseOpts: any = { runValidators: true, returnDocument: 'after' };\n if (session) {\n mongooseOpts.session = session;\n }\n\n // Defense-in-depth: strip version fields from update data to prevent\n // $set/$inc conflict on _version_db_doc\n delete dataWithUserTracking._version_db_doc;\n delete dataWithUserTracking._version;\n\n // CRDT: userId needed by both the LWW merge and the version-conflict retry\n const userId = options?.fieldTimestamps ? (executionContext.initiatorIds?.userId ?? 'unknown') : undefined;\n const FIELD_META_CAP = 200;\n\n // CRDT field-level LWW merge\n // P1: The extra findOne (projection: _field_meta only) is an intentional round-trip —\n // LWW needs the latest per-field server timestamps before findOneAndUpdate; a blind\n // CAS without pre-read cannot compare client vs server field clocks.\n if (options?.fieldTimestamps && Object.keys(options.fieldTimestamps).length > 0) {\n /**\n * Pre-read through the CONTEXTUAL filter, not a bare `_id`.\n *\n * This is a raw `mongooseModel` call, so it skips `buildContextualFilter` — the chokepoint that\n * hides erased-but-retained rows and applies scope. Reading by `_id` alone therefore pre-read a\n * row the update itself could never touch. Nothing personal leaked (the projection is CRDT\n * causality only, and the write below matches nothing), which is why this was recorded as LOW\n * rather than fixed as a disclosure — but reading a DIFFERENT row set than the statement it\n * feeds is incoherent regardless of what happens to be in the projection.\n *\n * `filter` is the same expression the update runs, so the merge is now computed from exactly the\n * row that will be written, or from nothing when there is no such row.\n *\n * ⚠️ **This also changes behaviour on the FILTER-based update path, deliberately.**\n * `buildBaseFilterFromIdOrIdsOrFilter` has a raw-`FilterQuery` branch, so `baseFilter._id` can be\n * absent entirely — the previous expression then read `{ _id: undefined }`, which does not identify\n * the target row. Depending on how the driver treats an undefined value that is either no row or an\n * ARBITRARY one, and in the second case the LWW merge compared client clocks against a different\n * document's server clocks. Neither outcome is the intended one, so this is a second (pre-existing,\n * retention-unrelated) defect that the same one-line change removes.\n *\n * ⚠️ **Untested path, stated rather than implied:** nothing in the suite exercises\n * `options.fieldTimestamps` at all — searching `__tests__` for it returns no file — so this block\n * has no coverage before or after. The change is reasoned and typechecked, NOT behaviour-verified.\n * A pin belongs here; writing one needs a `_doUpdate` harness that does not exist yet.\n */\n const currentDoc = await this.mongooseModel.findOne(\n filter,\n { _field_meta: 1 },\n session ? { session } : undefined,\n );\n\n const currentFieldMeta: Record<string, FieldMetaEntry> = sanitizeFieldMeta(currentDoc?._field_meta);\n const mergedFieldMeta: Record<string, FieldMetaEntry> = { ...currentFieldMeta };\n const fieldsToRemoveFromUpdate: string[] = [];\n\n for (const [field, clientTs] of Object.entries(options.fieldTimestamps)) {\n const serverTs = currentFieldMeta[field]?.ts ?? 0;\n\n if (lwwFieldWinner(clientTs, serverTs) === CrdtResolutionWinner.INCOMING) {\n mergedFieldMeta[field] = { ts: nextMonotonicTimestamp(Date.now(), serverTs), by: userId! };\n } else {\n fieldsToRemoveFromUpdate.push(field);\n }\n }\n\n for (const field of fieldsToRemoveFromUpdate) {\n delete dataWithUserTracking[field];\n this.logDebug('CRDT LWW: server wins for field', { field });\n }\n\n // D1: Schema-aware prune — remove _field_meta keys for fields no longer in the schema.\n // Prevents unbounded growth after schema renames.\n const validCrdtKeys = extractCrdtFieldNames(this.resourceConfiguration.mainSchema, false);\n if (validCrdtKeys.size > 0) {\n const staleKeys: string[] = [];\n for (const key of Object.keys(mergedFieldMeta)) {\n if (!validCrdtKeys.has(key)) staleKeys.push(key);\n }\n for (const key of staleKeys) {\n delete mergedFieldMeta[key];\n }\n if (staleKeys.length > 0) {\n this.logDebug('CRDT D1: pruned stale _field_meta keys', { staleKeys });\n }\n }\n\n // S3: Cap _field_meta size — evict oldest entries beyond the cap.\n // Runs after D1 semantic prune as a second line of defense.\n const metaKeys = Object.keys(mergedFieldMeta);\n if (metaKeys.length > FIELD_META_CAP) {\n const sorted = metaKeys.sort((a, b) => (mergedFieldMeta[a].ts ?? 0) - (mergedFieldMeta[b].ts ?? 0));\n const toEvict = sorted.slice(0, metaKeys.length - FIELD_META_CAP);\n for (const key of toEvict) {\n delete mergedFieldMeta[key];\n }\n this.logDebug('CRDT S3: capped _field_meta', { evicted: toEvict.length, remaining: FIELD_META_CAP });\n }\n\n dataWithUserTracking._field_meta = mergedFieldMeta;\n\n this.logDebug('CRDT LWW merge', {\n clientFields: Object.keys(options.fieldTimestamps),\n removedFields: fieldsToRemoveFromUpdate,\n survivingFields: Object.keys(options.fieldTimestamps).filter(f => !fieldsToRemoveFromUpdate.includes(f)),\n });\n }\n\n // Update operation always updates single entity\n let document;\n try {\n document = await this.mongooseModel.findOneAndUpdate(\n filter,\n this.buildVersionedUpdateDocument(dataWithUserTracking),\n mongooseOpts\n );\n } catch (error) {\n this.logDebug('Mongoose update failed', {\n error: describeCaughtError(error),\n filter,\n hasTransaction: !!session\n });\n throw this.handleMongoDBError(error, executionContext);\n }\n\n this.logDebug('Single update completed', {\n filter,\n found: !!document,\n hasTransaction: !!session\n });\n\n if (!document) {\n if (options?.ifMatchVersion !== undefined) {\n // Disambiguate: version conflict vs resource deleted/absent.\n // Query by _id only (no version filter) to check existence.\n // M5a (F3): a RETAINED row must read as ABSENT here too, or the 409-vs-404 disambiguation becomes\n // an existence oracle — a normal caller updating a retained (behave-as-deleted) row would get 409\n // VERSION_CONFLICT, disclosing the row exists. Applies the SAME predicate authority as\n // `buildContextualFilter` (gated on retention + suppressed by see-through) so the caller gets 404,\n // consistent with the \"behave-as-deleted\" contract. No-op for non-retention resources.\n // The executed operation is UPDATE — a write — so a see-through EC can never suppress the hide here.\n const existsFilter: FilterQuery<any> = { ...baseFilter };\n assignRetentionHideForOperation(\n existsFilter,\n this.resourceConfiguration,\n executionContext,\n CoreResourceOperation.UPDATE,\n );\n const existsDoc = await this.mongooseModel.findOne(\n existsFilter,\n { _id: 1 },\n session ? { session } : undefined\n );\n\n // CRDT-only update retry: when two clients save different CRDT fields simultaneously,\n // the second client's findOneAndUpdate fails because the first already incremented\n // the version. Retry with the current version instead of returning 409.\n const crdtFieldSet = options?.fieldTimestamps ? new Set(Object.keys(options.fieldTimestamps)) : null;\n const userDataKeys = Object.keys(dataWithUserTracking).filter(\n k => !k.startsWith('_')\n );\n const isCrdtOnly = crdtFieldSet !== null && isCrdtOnlyUpdate(userDataKeys, crdtFieldSet);\n\n if (existsDoc && options?.fieldTimestamps && isCrdtOnly) {\n const freshDoc = await this.mongooseModel.findOne(\n baseFilter,\n { _field_meta: 1, _version_db_doc: 1 },\n session ? { session } : undefined,\n );\n if (freshDoc) {\n filter._version_db_doc = freshDoc._version_db_doc;\n\n const freshFieldMeta: Record<string, FieldMetaEntry> = sanitizeFieldMeta(freshDoc._field_meta);\n const freshMerged: Record<string, FieldMetaEntry> = { ...freshFieldMeta };\n for (const [field, clientTs] of Object.entries(options.fieldTimestamps)) {\n const serverTs = freshFieldMeta[field]?.ts ?? 0;\n if (lwwFieldWinner(clientTs, serverTs) === CrdtResolutionWinner.INCOMING) {\n freshMerged[field] = { ts: nextMonotonicTimestamp(Date.now(), serverTs), by: userId! };\n } else {\n delete dataWithUserTracking[field];\n }\n }\n // D1: Schema-aware prune on retry path\n const validCrdtKeysRetry = extractCrdtFieldNames(this.resourceConfiguration.mainSchema, false);\n if (validCrdtKeysRetry.size > 0) {\n for (const key of Object.keys(freshMerged)) {\n if (!validCrdtKeysRetry.has(key)) delete freshMerged[key];\n }\n }\n\n // S3: Cap _field_meta size on retry path\n const retryMetaKeys = Object.keys(freshMerged);\n if (retryMetaKeys.length > FIELD_META_CAP) {\n const sorted = retryMetaKeys.sort((a, b) => (freshMerged[a].ts ?? 0) - (freshMerged[b].ts ?? 0));\n const toEvict = sorted.slice(0, retryMetaKeys.length - FIELD_META_CAP);\n for (const key of toEvict) delete freshMerged[key];\n }\n\n dataWithUserTracking._field_meta = freshMerged;\n\n document = await this.mongooseModel.findOneAndUpdate(\n filter,\n this.buildVersionedUpdateDocument(dataWithUserTracking),\n mongooseOpts,\n );\n if (document) {\n this.logDebug('CRDT LWW: retry succeeded after version conflict');\n return this.transformDocumentToResponse<T>(document, CoreResourceOperation.UPDATE);\n }\n // O1: retry was attempted (freshDoc found) but second findOneAndUpdate still lost the race\n this.logger.warn('CRDT LWW retry exhausted — falling through to VERSION_CONFLICT', {\n resourceId: String(baseFilter._id),\n clientFields: options?.fieldTimestamps ? Object.keys(options.fieldTimestamps) : [],\n });\n }\n // If freshDoc was null, fall through to 409 without O1 (could not refresh version / meta)\n }\n\n if (existsDoc) {\n this.logDebug('Version conflict detected', {\n ifMatchVersion: options.ifMatchVersion,\n resourceId: baseFilter._id\n });\n throw this.errorBuilder.buildError(\n ErrorType.CONFLICT,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.VERSION_CONFLICT,\n context: {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n ifMatchVersion: options.ifMatchVersion,\n }\n }\n );\n }\n // Document truly doesn't exist — fall through to return null\n // (service layer will throw NOT_FOUND)\n }\n return null;\n }\n\n return this.transformDocumentToResponse<T>(document, CoreResourceOperation.UPDATE);\n }\n\n private async _doUpdateMany<T = undefined>(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n ids_or_filter: IdsOrFilterType | undefined,\n data: PartialMainSchemaType<TMainSchema>,\n options?: RepositoryOptions\n ): Promise<ConditionalArrayReturnType<T, TMainSchema>> {\n const { baseFilter } = this.buildBaseFilterFromIdOrIdsOrFilter(ids_or_filter, executionContext);\n const session = this.getNativeSession(options);\n this.logDebug('Updating multiple resources', { ids_or_filter, hasData: !!data, hasTransaction: !!session });\n\n // Clean input data FIRST (remove mandatory discard fields)\n const cleanedData = this.resourceOperationHelper.cleanInputData(data, CoreResourceOperation.UPDATE_MANY);\n this.logDebug('Data cleaned for updateMany', { cleanedKeys: typeof cleanedData === 'object' ? Object.keys(cleanedData) : 'not-object' });\n\n // Validate against request DTO (after cleaning)\n const isBulkOperation = 'isBulkOperation' in operation && operation.isBulkOperation === true;\n const validatedData = this.repositoriesRegistry.validateRepositoryWriteData(\n cleanedData,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n String(operation.operationIdentifier),\n isBulkOperation,\n options,\n );\n this.logDebug('Data validated against requestDto', { validatedKeys: typeof validatedData === 'object' ? Object.keys(validatedData) : 'not-object' });\n\n // THEN apply execution context data enrichment to the validated data\n const enrichedData = this.resourceOperationHelper.enrichDataWithContext(validatedData, executionContext, this.resourceConfiguration.mainSchema, this.resourceConfiguration.resourceFieldIdentifier,\n this.resourceConfiguration, CoreResourceOperation.UPDATE_MANY, options);\n this.logDebug('Data enriched with context', { enrichedKeys: typeof enrichedData === 'object' ? Object.keys(enrichedData) : 'not-object' });\n\n // WS-C: one patch applied to many rows — an out-of-grant unit value here would move EVERY matched\n // row out of the caller's grant at once, so the same value check applies.\n await this.assertOrganizationUnitWriteWithinGrant(enrichedData, CoreResourceOperation.UPDATE_MANY, executionContext);\n\n // Referential + scope-via-junction integrity for any FK this bulk patch REASSIGNS — one patch\n // moving every matched row's `assignedToUserId` to a cross-tenant user is refused once, up front.\n await assertUpdateWriteIntegrity(this.writeIntegrityDeps, enrichedData, CoreResourceOperation.UPDATE_MANY, executionContext, options, referenceConstraintsOf(operation));\n\n // Add user tracking to enriched data\n const dataWithUserTracking = this.addUserTracking(enrichedData, executionContext, CoreResourceOperation.UPDATE_MANY);\n this.logDebug('User tracking added', { finalKeys: typeof dataWithUserTracking === 'object' ? Object.keys(dataWithUserTracking) : 'not-object' });\n\n // Defense-in-depth: strip version fields from update data to prevent\n // $set/$inc conflict on _version_db_doc in bulk updates too.\n delete dataWithUserTracking._version_db_doc;\n delete dataWithUserTracking._version;\n\n const contextualFilter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.UPDATE_MANY, options);\n\n // Prepare mongoose options with transaction session if provided\n const mongooseOpts: any = { runValidators: true };\n if (session) {\n mongooseOpts.session = session;\n }\n\n const findOpts: any = session ? { session } : {};\n const matchedDocuments = await this.mongooseModel.find(contextualFilter, { _id: 1 }, findOpts);\n const matchedIds = matchedDocuments\n .map((doc: any) => doc?._id?.toString?.() ?? doc?._id)\n .filter((id: unknown): id is string => typeof id === 'string' && id.length > 0);\n\n if (matchedIds.length === 0) {\n return [] as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n const updateResult = await this.mongooseModel.updateMany(\n contextualFilter,\n this.buildVersionedUpdateDocument(dataWithUserTracking),\n mongooseOpts\n );\n\n this.logDebug('UpdateMany completed', {\n filter: contextualFilter,\n matchedCount: updateResult.matchedCount,\n modifiedCount: updateResult.modifiedCount,\n hasTransaction: !!session\n });\n\n if (updateResult.matchedCount === 0) {\n return [] as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n // Re-read by stable ids rather than the original filter.\n // Otherwise a patch that changes a matched filter field can make the follow-up\n // find() return an empty set even though Mongo actually updated documents.\n const updatedDocuments = await this.mongooseModel.find(\n { _id: { $in: matchedIds } } as FilterQuery<any>,\n null,\n findOpts\n );\n const updatedDocumentsById = new Map(\n updatedDocuments.map((doc: any) => [\n doc?._id?.toString?.() ?? doc?._id,\n doc,\n ] as const)\n );\n const orderedUpdatedDocuments = matchedIds\n .map((id) => updatedDocumentsById.get(id))\n .filter((doc): doc is any => !!doc);\n\n return orderedUpdatedDocuments.map(doc => this.transformDocumentToResponse<T>(doc, CoreResourceOperation.UPDATE_MANY)) as ConditionalArrayReturnType<T, TMainSchema>;\n }\n\n\n private async _doDelete(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_filter?: IdOrFilterType,\n options?: RepositoryOptions\n ): Promise<string> {\n // Prepare mongoose options with transaction session if provided\n const session = this.getNativeSession(options);\n const mongooseOpts: any = session ? { session } : {};\n\n this.logDebug('Deleting resource', { id_or_filter, hasTransaction: !!session });\n\n // Validate required parameter\n this.validateIdOrIdsOrFilterRequired(id_or_filter, executionContext, CoreResourceOperation.DELETE);\n\n // Build base filter - delete operation is always unitary (single entity)\n const { baseFilter: deleteFilter } = this.buildBaseFilterFromIdOrIdsOrFilter(id_or_filter, executionContext);\n\n const filter = this.buildContextualFilter(executionContext, deleteFilter, CoreResourceOperation.DELETE, options);\n\n // First, fetch the document to get its ID before deletion\n const documentToDelete = await this.mongooseModel.findOne(filter, { _id: 1 }, mongooseOpts);\n\n if (!documentToDelete) {\n this.logDebug('No document found to delete', { filter });\n return '';\n }\n\n const deletedId = (documentToDelete as any)._id.toString();\n\n // Delete operation always deletes single entity\n const result = await this.mongooseModel.deleteOne(filter, mongooseOpts);\n\n this.logDebug('Single delete completed', {\n filter,\n deletedCount: result.deletedCount,\n deletedId: deletedId,\n hasTransaction: !!session\n });\n\n return deletedId;\n }\n\n\n private async _doDeleteMany(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n ids_or_filter?: IdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<string[]> {\n // Prepare mongoose options with transaction session if provided\n const session = this.getNativeSession(options);\n const mongooseOpts: any = session ? { session } : {};\n\n this.logDebug('Deleting multiple resources', { ids_or_filter, hasTransaction: !!session });\n\n // Validate required parameter for deleteMany operation\n this.validateIdOrIdsOrFilterRequired(ids_or_filter, executionContext, CoreResourceOperation.DELETE_MANY);\n\n // Build base filter for multiple deletions - this handles IdsOrFilterType\n const { baseFilter } = this.buildBaseFilterFromIdOrIdsOrFilter(ids_or_filter, executionContext);\n\n // Apply contextual filtering\n const contextualFilter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.DELETE_MANY, options);\n\n // First, fetch all documents that match the filter to get their IDs before deletion\n const documentsToDelete = await this.mongooseModel.find(contextualFilter, { _id: 1 }, mongooseOpts);\n\n if (!documentsToDelete || documentsToDelete.length === 0) {\n this.logDebug('No documents found to delete', { contextualFilter });\n return [];\n }\n\n const deletedIds = documentsToDelete.map(doc => (doc as any)._id.toString());\n\n // Perform multiple deletions using deleteMany\n const result = await this.mongooseModel.deleteMany(contextualFilter, mongooseOpts);\n\n this.logDebug('Multiple delete completed', {\n contextualFilter,\n deletedCount: result.deletedCount,\n deletedIds: deletedIds,\n hasTransaction: !!session\n });\n\n return deletedIds;\n }\n\n private async _doList<T = undefined>(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n ids_or_filter?: IdsOrFilterType,\n options?: RepositoryOptions & { listOptions?: Partial<Resources_PaginationRequest> & { sort?: Record<string, 1 | -1> } }\n ): Promise<(T extends undefined ? any : T)[] | Resources_PaginatedResult<T extends undefined ? any : T>> {\n\n // Validate required parameter\n this.validateIdOrIdsOrFilterRequired(ids_or_filter, executionContext, CoreResourceOperation.LIST);\n\n // Build base filter\n const { baseFilter } = this.buildBaseFilterFromIdOrIdsOrFilter(ids_or_filter, executionContext);\n\n const contextualFilter = this.buildContextualFilter(executionContext, baseFilter, CoreResourceOperation.LIST, options);\n\n // Build projection from operation's responseDto\n const projection = this.buildMongoProjectionFromResponseDto(operation);\n\n // Check if pagination wrapper is requested\n const paginated = options?.paginated ?? false;\n const listOptions = options?.listOptions;\n const hasPagination = listOptions?.page !== undefined || listOptions?.limit !== undefined;\n const session = this.getNativeSession(options);\n\n // Only count documents if we need pagination metadata\n let total = 0;\n let page = 1;\n let limit = 0;\n let skip = 0;\n let totalPages = 1;\n\n if (paginated || hasPagination) {\n let countQuery = this.mongooseModel.countDocuments(contextualFilter);\n if (session) {\n countQuery = countQuery.session(session);\n }\n total = await countQuery.exec();\n page = hasPagination ? Math.max(1, listOptions?.page || 1) : 1;\n // The ceiling the OPERATION declares. LIST used to consult it nowhere.\n //\n // The default is 100, NOT the 50 that `_doSearch` uses, and the difference is deliberate: 100\n // is the hard-coded cap this line replaced (`Math.min(100, …)`), so an operation that declares\n // nothing keeps exactly the ceiling it has always had. Defaulting to 50 \"for symmetry with\n // SEARCH\" silently halved every caller that asked for more — including billing usage-metering\n // (`limit: 10000`), the sidebar resource browser and the audit export, none of which declare a\n // ceiling. A consumer sweep found them; the symmetry was not worth the truncation.\n const maxLimit = (operation as { maxPaginatedResultPerPageLimit?: number }).maxPaginatedResultPerPageLimit || 100;\n // ⚠️ The `paginated && !hasPagination` branch used to be `total || 1` — i.e. \"return the WHOLE\n // collection in one page\". Combined with the response DTO's ceiling that is an unavoidable 500\n // for any collection larger than the ceiling: the repository builds a page the DTO then\n // refuses. Observed 2026-08-12 on `GET /users/admin` against 77 users.\n //\n // It was also an ADAPTER DIVERGENCE — the PostgreSQL `_doList` has always defaulted to 20 here\n // — so the same request returned every row on Mongo and 20 on PostgreSQL. Both now use the\n // framework's one default page size, capped by the declared ceiling.\n //\n // The NON-paginated path is deliberately untouched: with `paginated === false` and no\n // `listOptions`, this whole block is skipped, `limit` stays 0, and mongo returns every row.\n // That is the internal-call contract (engine code calls `list()` expecting the full set), and\n // capping it here would silently truncate every internal enumeration in the framework.\n limit = Math.min(maxLimit, Math.max(1, listOptions?.limit || 20));\n skip = (page - 1) * limit;\n totalPages = limit > 0 ? Math.ceil(total / limit) : 1;\n }\n\n this.logDebug('Listing resources', {\n ids_or_filter,\n paginated,\n hasPagination,\n page,\n limit,\n skip,\n total,\n hasTransaction: !!session\n });\n\n // Prepare query with projection and transaction session.\n // Sort mirrors SEARCH: `constructValidatedSortOptions` validates the\n // caller-supplied `sort` against the operation's `sortFields` (priority =\n // key order) and falls back to the first configured field, or createdAt-desc\n // when no sortFields are declared — so an absent `sort` preserves the prior\n // newest-first default for unconfigured resources.\n let query = this.mongooseModel\n .find(contextualFilter, projection)\n .sort(this.constructValidatedSortOptions(listOptions?.sort, operation));\n\n // Bound the QUERY whenever a paginated envelope is being returned.\n //\n // This used to be gated on `hasPagination` alone — true only when the CALLER supplied `page` or\n // `limit`. So `paginated: true` with no explicit page (every default `GET /<collection>`) fell\n // through unbounded and fetched the entire collection, while the envelope reported a `limit` it\n // had not applied. The metadata and the query disagreed, and the DTO ceiling then rejected the\n // oversized page as a 500.\n //\n // Computing a correct `limit` above is NOT sufficient on its own — that was the first attempt at\n // this fix, and the adapter-parity pin caught it by observing the query's `.limit()` rather than\n // the returned metadata. If a future change touches either half, both must move together.\n if (paginated || hasPagination) {\n query = query.skip(skip).limit(limit);\n }\n\n if (session) {\n query = query.session(session);\n }\n\n const documents = await query.exec();\n\n const data = documents.map(doc => this.transformDocumentToResponse<T>(doc, CoreResourceOperation.LIST)) as (T extends undefined ? any : T)[];\n\n this.logDebug('List result', {\n filter: contextualFilter,\n count: data.length,\n paginated,\n pagination: paginated ? { page, limit, total, totalPages } : undefined,\n sample: this.previewDocument(documents[0]),\n hasTransaction: !!session\n });\n\n // Return raw array by default, or with pagination wrapper if requested\n if (paginated) {\n return {\n data,\n pagination: { page, limit: limit || data.length, total: total || data.length, totalPages }\n };\n }\n\n return data;\n }\n\n private async _doSearch<T = any>(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n searchQuery: string,\n filter: FilterQuery<any> = {},\n options: RepositoryOptions & { searchOptions: { fieldsToSearch?: string[]; page?: number; limit?: number; sort?: any} }\n ): Promise<Resources_PaginatedResult<T>> {\n // Get session for transaction support\n const session = this.getNativeSession(options);\n\n // Search metadata must come from the same routed operation that controls\n // response projection. Falling back to a default SEARCH is only for legacy\n // direct helper paths that did not carry the full operation object.\n const searchConfig = ResourceOperationsUtils.getCoreResourceOperationFromOperation(operation) === CoreResourceOperation.SEARCH\n ? operation\n : this.findSearchOperationConfiguration();\n\n if (!searchConfig) {\n const error = this.errorBuilder.buildError(\n ErrorType.NOT_FOUND,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_SEARCH_NOT_CONFIGURED,\n }\n );\n throw error;\n }\n\n const op = searchConfig as unknown as {\n isSearchable?: boolean;\n searchableFields?: SearchableFieldDescriptor[];\n maxPaginatedResultPerPageLimit?: number;\n };\n\n if (!op.isSearchable) {\n const error = this.errorBuilder.buildError( ErrorType.BUSINESS_RULE, executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_SEARCH_NOT_ENABLED }\n );\n throw error;\n }\n\n const page = Math.max(1, options.searchOptions.page || 1);\n const maxLimit = op.maxPaginatedResultPerPageLimit || 50;\n const limit = Math.min(maxLimit, Math.max(1, options.searchOptions.limit || 20));\n const skip = (page - 1) * limit;\n\n this.logDebug('Searching resources with configuration', {\n searchQuery, filter, page, limit, maxLimit,\n searchableFields: op.searchableFields,\n isSearchable: op.isSearchable,\n hasTransaction: !!session\n });\n\n // Build advanced search filter using configuration. Async because relational\n // `searchableFields` entries resolve their `$in` ids via a secondary match on\n // the related resource's repository (see {@link constructSearchQuery}).\n const searchFilter = await this.constructSearchQuery(searchQuery, searchConfig);\n const validatedFilter = this.sanitizeRequestFilter(filter, searchConfig);\n const combinedFilter = { ...validatedFilter, ...searchFilter };\n // Scope-required reference search: when a junction-tagged scope param is\n // present (e.g. /organizations/{org}/users/search), intersect the result set\n // with the membership ids resolved through the junction. No-op otherwise.\n let contextualFilter = this.buildContextualFilter(executionContext, combinedFilter, CoreResourceOperation.SEARCH, options);\n contextualFilter = await this.applyJunctionScopeFilter(executionContext, contextualFilter);\n\n // Build sort options using configuration\n const sortOptions = this.constructValidatedSortOptions(options.searchOptions.sort, searchConfig);\n\n // Build projection from operation's responseDto\n const projection = this.buildMongoProjectionFromResponseDto(operation);\n\n // Prepare mongoose queries with projection and transaction session if provided\n let findQuery = this.mongooseModel\n .find(contextualFilter, projection)\n .sort(sortOptions)\n .skip(skip)\n .limit(limit);\n\n let countQuery = this.mongooseModel.countDocuments(contextualFilter);\n\n if (session) {\n findQuery = findQuery.session(session);\n countQuery = countQuery.session(session);\n }\n\n const [documents, total] = await Promise.all([\n findQuery.exec(),\n countQuery.exec()\n ]);\n\n const data = documents.map(doc => this.transformDocumentToResponse(doc, CoreResourceOperation.SEARCH));\n\n return {\n data,\n pagination: { page, limit, total, totalPages: Math.ceil(total / limit) }\n };\n }\n\n private async _doCount(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n filter: FilterQuery<any> = {},\n options?: RepositoryOptions\n ): Promise<{ count: number }> {\n const session = this.getNativeSession(options);\n this.logDebug('Counting resources', { filter, hasTransaction: !!session });\n\n // Scope-required reference search: mirror _doSearch so a junction-scoped\n // count matches the search it paginates. No-op when no junction tag present.\n let contextualFilter = this.buildContextualFilter(executionContext, filter, CoreResourceOperation.COUNT, options);\n contextualFilter = await this.applyJunctionScopeFilter(executionContext, contextualFilter);\n\n // Prepare count query with transaction session if provided\n let countQuery = this.mongooseModel.countDocuments(contextualFilter);\n\n if (session) {\n countQuery = countQuery.session(session);\n }\n\n const count = await countQuery.exec();\n\n this.logDebug('Count result', {\n filter: contextualFilter,\n count,\n hasTransaction: !!session\n });\n\n return { count };\n }\n\n // ================================\n // Helper Methods\n // ================================\n\n /**\n * Format a string ID for MongoDB queries.\n * Uses ResourceIdBackendService if available, falls back to direct ObjectId creation.\n *\n * @param id - The string ID to format\n * @returns The formatted ID (Types.ObjectId for MongoDB)\n */\n private formatIdForQuery(id: string): Types.ObjectId {\n if (this.resourceIdService) {\n return this.resourceIdService.formatForQuery(id) as Types.ObjectId;\n }\n // Fallback for backward compatibility when service not available\n return new Types.ObjectId(id);\n }\n\n /**\n * Utility function to build a base filter from IdOrIdsOrFilterType\n * @param id_or_ids_or_filter - The input parameter to process\n * @param executionContext - Execution context for error handling\n * @returns Object containing the base filter and whether it represents multiple items\n */\n private buildBaseFilterFromIdOrIdsOrFilter(\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n executionContext: ExecutionContext<any>\n ): { baseFilter: FilterQuery<any>; isMultiple: boolean } {\n let baseFilter: FilterQuery<any> = {};\n let isMultiple = false;\n\n if (!id_or_ids_or_filter) {\n return { baseFilter, isMultiple };\n }\n\n if (typeof id_or_ids_or_filter === 'string') {\n // Single ID\n baseFilter = { _id: this.formatIdForQuery(id_or_ids_or_filter) } as FilterQuery<any>;\n isMultiple = false;\n } else if (Array.isArray(id_or_ids_or_filter)) {\n // Multiple IDs\n if (id_or_ids_or_filter.length > 0) {\n const objectIds = id_or_ids_or_filter.map(singleId => this.formatIdForQuery(singleId));\n baseFilter = { _id: { $in: objectIds } } as FilterQuery<any>;\n }\n isMultiple = true;\n } else if (typeof id_or_ids_or_filter === 'object' && !Array.isArray(id_or_ids_or_filter)) {\n // Handle different object types\n if ('id_or_ids' in id_or_ids_or_filter) {\n // Combined object with id_or_ids and optional filter\n const { id_or_ids: ids, filter } = id_or_ids_or_filter;\n if (typeof ids === 'string') {\n baseFilter = { _id: this.formatIdForQuery(ids) } as FilterQuery<any>;\n isMultiple = false;\n } else if (Array.isArray(ids) && ids.length > 0) {\n const objectIds = ids.map(singleId => this.formatIdForQuery(singleId));\n baseFilter = { _id: { $in: objectIds } } as FilterQuery<any>;\n isMultiple = true;\n }\n // Merge additional filter if present\n if (filter && Object.keys(filter).length > 0) {\n baseFilter = { ...baseFilter, ...filter };\n isMultiple = true; // Combined filters usually imply multiple results\n }\n } else if ('id' in id_or_ids_or_filter) {\n // Single-id combined shape from `IdOrFilterType` ({ id, filter? }) — the shape the\n // read / update / delete SINGLE-entity callers pass (their input type advertises it).\n // Without this branch the object falls through to the raw-FilterQuery case below and\n // Mongo tries to match literal `id` / `filter` fields (never present on a document) →\n // a silent no-match that surfaces as a spurious NOT_FOUND. Mirrors the `id_or_ids`\n // branch but for the singular contract, so `isMultiple` stays false. (Uncovered by the\n // SIEM DLQ RETRY drains, which read `{ id: entryId, filter: <scope FK> }`.)\n const { id, filter } = id_or_ids_or_filter as { id: string; filter?: FilterQuery<any> };\n baseFilter = { _id: this.formatIdForQuery(id) } as FilterQuery<any>;\n isMultiple = false;\n if (filter && Object.keys(filter).length > 0) {\n baseFilter = { ...baseFilter, ...filter };\n }\n } else {\n // Direct FilterQuery object\n baseFilter = id_or_ids_or_filter as FilterQuery<any>;\n isMultiple = true; // Filter queries usually imply multiple results\n }\n } else {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED }\n );\n }\n\n return { baseFilter, isMultiple };\n }\n\n /**\n * Utility function to validate that id_or_ids_or_filter parameter is provided\n * @param id_or_ids_or_filter - The parameter to validate\n * @param executionContext - Execution context for error handling\n * @param operationName - Name of the operation for error messages\n */\n private validateIdOrIdsOrFilterRequired(\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n executionContext: ExecutionContext<any>,\n operationName: string,\n ): void {\n if (!id_or_ids_or_filter) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n { customMessageReference: ErrorCustomMessageReference.REPOSITORY_RESOURCE_OPERATION_FAILED, context: { operationName } } // diagnostic (log-only)\n );\n }\n }\n\n\n\n /**\n * Escapes special regex characters in search query to prevent regex injection\n * @param text - The text to escape\n * @returns Escaped text safe for regex\n */\n private escapeRegex(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n }\n\n\n\n /**\n * Extract projection fields from operation's responseDto for MongoDB field selection\n * @param operation - The operation to extract responseDto fields from\n * @returns MongoDB projection object or null if no responseDto is defined\n */\n private buildMongoProjectionFromResponseDto(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>\n ): Record<string, 1> | null {\n // Prefer repositoryDto over responseDto\n // repositoryDto excludes virtual fields and populated placeholders,\n // but includes virtual field dependencies\n const dtoToUse = operation.repositoryDto ?? operation.responseDto;\n\n if (!dtoToUse) {\n this.logDebug('No responseDto/repositoryDto found in operation, using full document projection');\n return null;\n }\n\n try {\n // Parse the DTO to extract field names\n const responseSchema = dtoToUse;\n\n // For Zod schemas, we can use the shape property to get field names\n if (responseSchema && typeof responseSchema === 'object' && 'shape' in responseSchema) {\n const shape = (responseSchema as any).shape;\n const projection: Record<string, 1> = {};\n\n Object.keys(shape).forEach(fieldName => {\n projection[fieldName] = 1;\n });\n\n // A surrogate primary key (e.g. FILES `fileId`) is a Mongoose VIRTUAL = String(_id),\n // not a stored column — Mongo cannot project it, and it resolves ONLY if `_id` is in\n // the returned document. The responseDto names the surrogate, not `_id`, so make the\n // dependency explicit: force `_id` into the projection for surrogate-PK resources.\n // Without this, a future projection that excluded `_id` would silently null the\n // surrogate on every read/list (the fileId virtual would read `String(undefined)`).\n const surrogatePrimaryKey = this.resourceOperationHelper.getSurrogatePrimaryKeyFieldName(\n this.resourceConfiguration.mainSchema,\n );\n if (surrogatePrimaryKey) {\n projection._id = 1;\n }\n\n this.logDebug('Built projection from responseDto', {\n operationIdentifier: operation.operationIdentifier,\n projectionFields: Object.keys(projection)\n });\n\n return projection;\n }\n\n // If we can't extract fields from the schema, fall back to full document\n this.logDebug('Unable to extract fields from responseDto, using full document projection', {\n operationIdentifier: operation.operationIdentifier,\n responseDtoType: typeof responseSchema\n });\n\n return null;\n } catch (error) {\n this.logDebug('Error extracting projection from responseDto, using full document', {\n operationIdentifier: operation.operationIdentifier,\n error: describeCaughtError(error)\n });\n\n return null;\n }\n }\n\n /**\n * System-level membership projection (scope-required reference search).\n *\n * Reads THIS resource's own collection for rows matching `{ [scopeFkField]:\n * scopeId }` and returns the distinct `targetFkField` values. Called on the\n * JUNCTION repo (e.g. `organizationMembers`) to resolve \"the user ids that are\n * members of org X\". A raw, lean, SYSTEM read by design — no operation auth, no\n * contextual filter — because the caller is ALREADY authorized for the scope\n * and this is an internal membership projection feeding\n * {@link applyJunctionScopeFilter}.\n */\n /**\n * Apply the M5a retention hide to a RAW projection filter (gate G-RAW).\n *\n * The id/value-projection reads below query `this.mongooseModel` DIRECTLY and therefore skip\n * `buildContextualFilter`, where retained rows are normally hidden. Without this, an\n * impersonalized-and-retained row would still contribute its id to a relational search match or a\n * scope resolution — surfacing, indirectly, a record that is supposed to be invisible.\n *\n * Fail-closed and unconditional: these are framework-internal projections, never the audited\n * see-through path (`read/listRetainedAsSystem`), so they take no EC suppression. No-op unless the\n * resource opted into `retentionPolicy` (factory-normalized to truthy ⟺ retention-governed).\n *\n * The predicate itself comes from the single retention authority — this method only decides WHETHER\n * it applies on this raw path.\n */\n private withRawRetentionHide(filter: Record<string, unknown>): Record<string, unknown> {\n if (!isRetentionGovernedResource(this.resourceConfiguration)) {\n return filter;\n }\n return withRetentionHideApplied(filter);\n }\n\n public async findScopeRelatedTargetIds(scopeFkField: string, scopeId: string, targetFkField: string): Promise<string[]> {\n const documents = await this.mongooseModel\n .find(this.withRawRetentionHide({ [scopeFkField]: scopeId }), { [targetFkField]: 1, _id: 0 })\n .lean()\n .exec();\n const ids = new Set<string>();\n for (const document of documents) {\n const value = (document as Record<string, unknown>)[targetFkField];\n // The junction FK is a Mongoose ObjectId and is read RAW here via `.lean()`,\n // which BYPASSES the toObject/toJSON string serialization — so `value` is an\n // ObjectId instance, not a string. Coerce to its hex string; the downstream\n // `_id ∈ {…}` $in re-casts per the target's own `_id` (ObjectId) on the\n // users query. (Without this, a `typeof === 'string'` guard skipped every\n // value → empty $in → the scoped search returned zero rows.)\n if (value !== undefined && value !== null) {\n const id = String(value);\n if (id.length > 0) {\n ids.add(id);\n }\n }\n }\n return [...ids];\n }\n\n /**\n * Relational-search match projection (OR-match sibling of the AND-scope\n * {@link findScopeRelatedTargetIds}).\n *\n * Runs THIS resource's OWN searchable surface — regex across its configured\n * SEARCH `searchableFields` (string entries), or the `fields` override — against\n * `searchQuery`, and returns the distinct `joinField` values of the matching\n * rows, bounded by an internal cap. A raw, lean, SYSTEM read by design (no\n * operation auth, no contextual filter): the CALLER folds these ids into an\n * `$in` on its OWN already-scoped collection, so an unscoped match here can\n * never widen the caller's scoped result set (see {@link SearchableRelationDescriptor}).\n *\n * Returns [] — contributing no branch — when the query is blank or this resource\n * exposes no usable searchable fields; failing to ADD a match never leaks.\n *\n * @param searchQuery - The caller's search query string\n * @param joinField - Field whose values to collect (default `_id`); pass a shared\n * non-PK key (e.g. `userId`) when the caller joins on that instead of `_id`\n * @param options.fields - Override the fields to match (else this resource's own\n * string `searchableFields`)\n */\n public async findSearchMatchTargetIds(\n searchQuery: string,\n joinField: string,\n options?: { fields?: string[] }\n ): Promise<string[]> {\n if (!searchQuery?.trim()) {\n return [];\n }\n\n // Bound the candidate set so a broad term can't build an unbounded `$in`.\n // Tenant safety is unaffected (the caller's query stays scoped); this caps\n // perf / `$in` size only. Org-scale relations sit well under this.\n const MATCH_ID_CAP = 1000;\n\n const searchConfig = this.findSearchOperationConfiguration();\n const op = searchConfig as unknown as { searchableFields?: SearchableFieldDescriptor[]; searchableOptions?: CollectionView_SearchOptions } | null;\n\n // Default to THIS resource's own string searchable fields — \"use the juncted\n // element's search\" — unless the caller pins an explicit field subset.\n const ownStringFields = (op?.searchableFields ?? []).filter((field): field is string => typeof field === 'string');\n const fields = options?.fields && options.fields.length > 0 ? options.fields : ownStringFields;\n if (fields.length === 0) {\n this.logDebug('findSearchMatchTargetIds: no searchable fields resolved for relational match', {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n });\n return [];\n }\n\n const conditions = this.buildFieldSearchConditions(searchQuery, fields, op?.searchableOptions);\n const matchFilter: FilterQuery<any> = conditions.length > 1 ? { $or: conditions } : conditions[0];\n\n const projection = joinField === '_id' ? { _id: 1 } : { [joinField]: 1, _id: 0 };\n // Top-level AND with the retention hide: a retained row must not contribute a search match, even\n // though `matchFilter` may itself be an `$or` of field conditions.\n const documents = await this.mongooseModel\n .find(this.withRawRetentionHide(matchFilter as Record<string, unknown>), projection)\n .limit(MATCH_ID_CAP + 1)\n .lean()\n .exec();\n\n if (documents.length > MATCH_ID_CAP) {\n this.logDebug('findSearchMatchTargetIds: related match set truncated to cap', {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n cap: MATCH_ID_CAP,\n });\n }\n\n const ids = new Set<string>();\n for (const document of documents.slice(0, MATCH_ID_CAP)) {\n const value = (document as Record<string, unknown>)[joinField];\n // `.lean()` returns the FK raw: a string FK stays a string, an ObjectId FK is\n // an ObjectId instance. Coerce to its string form; the caller's `$in` re-casts\n // against its own join field type (mirrors findScopeRelatedTargetIds).\n if (value !== undefined && value !== null) {\n const id = String(value);\n if (id.length > 0) {\n ids.add(id);\n }\n }\n }\n return [...ids];\n }\n\n /**\n * Read-direction sibling of {@link findSearchMatchTargetIds} (and\n * {@link findScopeRelatedTargetIds}): given a set of join-key VALUES, return the\n * matching rows projected to `fields`, keyed by the (stringified) join value.\n *\n * Raw, lean, SYSTEM read by design — no operation auth, no contextual filter —\n * mirroring the relational-search tenant-safety contract in REVERSE: the CALLER\n * only ever passes join values that appear on rows it can ALREADY see (its own\n * already-scoped page), so resolving the related rows system-side can never\n * widen visibility. Powers label forwarding (`forwardedLabel` in\n * `@wildo-ai/saas-models`), which renders a junction row's \"other party\" fields\n * (e.g. a member's user-profile name) for display WITHOUT denormalizing them.\n *\n * Returns an empty Map when `joinValues` or `fields` is empty (nothing to\n * resolve / render). When a join value matches multiple related rows, the first\n * encountered wins — label joins are expected 1:1 on the join key (e.g. one\n * user_profile per `userId`).\n *\n * @param joinField - Related field matched against `joinValues` (e.g. `userId`); `_id` joins on the primary key\n * @param joinValues - Join values to resolve (typically one page's worth); de-duplicated internally\n * @param fields - Related fields to project (the caller renders them into the label)\n */\n public async findFieldValuesByJoinField(\n joinField: string,\n joinValues: string[],\n fields: string[],\n ): Promise<Map<string, Record<string, unknown>>> {\n const result = new Map<string, Record<string, unknown>>();\n\n const distinctValues = [...new Set(joinValues.filter((value) => typeof value === 'string' && value.length > 0))];\n if (distinctValues.length === 0 || fields.length === 0) {\n return result;\n }\n\n // Bound the related read. One page's worth of distinct join keys sits well\n // under this; the cap only protects against a pathologically large page.\n const MATCH_ID_CAP = 1000;\n\n // Retention hide: a retained row must not supply rendered field VALUES to a label/summary join —\n // that would leak the very data the scrub removed from view.\n const matchFilter: FilterQuery<any> = this.withRawRetentionHide({ [joinField]: { $in: distinctValues } });\n\n // Project the join field (to key the result) plus the rendered fields. Mongo\n // allows excluding `_id` alongside an inclusion projection — drop it unless we\n // are joining on it OR a caller actually wants `_id` rendered (`'_id' in\n // projection` after the inclusion loop), else the exclusion would silently\n // override a requested `_id: 1`.\n const projection: Record<string, 0 | 1> = { [joinField]: 1 };\n for (const field of fields) {\n projection[field] = 1;\n }\n if (joinField !== '_id' && !('_id' in projection)) {\n projection._id = 0;\n }\n\n const documents = await this.mongooseModel\n .find(matchFilter, projection)\n .limit(MATCH_ID_CAP)\n .lean()\n .exec();\n\n for (const document of documents) {\n const record = document as Record<string, unknown>;\n const rawKey = record[joinField];\n // `.lean()` returns the join key raw (string stays a string, ObjectId stays\n // an ObjectId). Stringify to match the caller's stringified join value.\n if (rawKey === undefined || rawKey === null) {\n continue;\n }\n const key = String(rawKey);\n if (key.length > 0 && !result.has(key)) {\n result.set(key, record);\n }\n }\n\n return result;\n }\n\n /**\n * Apply scope-required reference-search scoping (Phase 2 of\n * `.claude/plans/fk-filter-reference-search.md`).\n *\n * When a relationship context carries a `scopeViaJunction` tag — set ONLY on\n * the synthetic peer-under-scope param of a route like\n * `/organizations/{organizationId}/users/search` — the target resource (e.g.\n * `users`) has NO column for the scope, so it is scoped THROUGH the junction:\n * `T._id ∈ { J.targetFk : J.scopeFk = scopeId }`. The junction + its two FK\n * columns come from the Phase-1 `manyToManyScopeJunctions` registry map,\n * cross-checked against the runtime tag. No-op when no tagged context is\n * present (every normal search). Composes with any existing constraint via\n * `$and`.\n *\n * SECURITY: fail-closed. If the tag is present but the junction/repo can't be\n * resolved, intersect with an EMPTY id set rather than returning the unscoped\n * collection — a missing mapping must never widen visibility.\n *\n * Q2 (LOCKED): membership-first `$in`; the large-org `$lookup`-aggregation\n * optimization is deferred (bounded by org-membership size + paginated).\n */\n private async applyJunctionScopeFilter(\n executionContext: ExecutionContext<any>,\n filter: FilterQuery<any>,\n ): Promise<FilterQuery<any>> {\n return applyJunctionScopeFilter({\n filter,\n relationshipContexts: executionContext.relationshipContexts as any,\n targetResourceType: this.resourceConfiguration.resourceIdentifier as ResourceType,\n manyToManyScopeJunctions: this.resourceRegistry.getResourcesRegistry().manyToManyScopeJunctions as any,\n getJunctionRepository: (junctionResourceType) =>\n this.repositoriesRegistry.getRepository(junctionResourceType) as any,\n });\n }\n\n /**\n * Build contextual filter based on execution context with schema validation and blacklist support\n * @param executionContext - The execution context containing resource IDs\n * @param baseFilter - The base filter to enhance with context\n * @param options - Repository options containing exclusion rules\n * @returns Enhanced filter with context information\n */\n private buildContextualFilter(\n executionContext: ExecutionContext<any>,\n baseFilter: FilterQuery<any>,\n /**\n * The core operation THIS repository call is executing — NOT `executionContext.operation`. The\n * retention authority classifies it to decide whether a see-through EC may suppress the hide\n * (read-family only); see `assignRetentionHideForOperation`.\n */\n executedCoreOperation: CoreResourceOperation,\n options?: RepositoryOptions,\n ): FilterQuery<any> {\n // Translate the date-range filter vocabulary (`{ startDate?, endDate? }`, reconstructed by the\n // collection-query controller for a `z.date()` filter field) into `{ $gte?, $lte? }` BEFORE the\n // filter reaches mongoose — otherwise mongoose casts the whole `{startDate,endDate}` object to a\n // Date and throws `CastError`. No-op for filters without range vocabulary. This is the Mongo half\n // of the shared normalization; the PG adapter calls the SAME helper in its `buildContextualFilter`.\n const contextualFilter = normalizeDateRangeFilters({ ...baseFilter });\n\n // ── M5a: retention hide predicate (privacy boundary) ──────────────────────────────────────\n // For a retention-governed resource, hide impersonalized-and-retained rows from normal callers.\n // This chokepoint is SHARED by the read paths AND the write paths (`_doUpdate/_doUpdateMany/\n // _doDelete/_doDeleteMany` all filter on it), so a retained row becomes hidden on read AND\n // immutable to a normal write in one place — the intended \"kept but frozen\" state.\n //\n // The predicate, the governance test and the see-through suppression rule all live in the single\n // retention authority; this site only chooses WHERE the rule is applied. Two placement facts are\n // load-bearing and are the reason this call sits exactly here:\n // - BEFORE the `options.excludeContextualFilter` early-return ON PURPOSE. That flag bypasses\n // SCOPE — a DIFFERENT axis — so scope-bypass callers (anonymous-session, guidance evaluators,\n // features admin) must NOT thereby see or mutate retained rows.\n // - It writes at the TOP LEVEL of the filter, OVERWRITING any caller-supplied `retentionStatus`\n // (fail-closed). A caller who injects `retentionStatus: RETAINED` — e.g. a SEARCH whose\n // operation declares no `filterFields`, so `sanitizeRequestFilter` passes the raw client\n // filter through — is NEUTRALISED rather than honoured. A genuine compliance auditor targets\n // retained rows through the see-through path, which suppresses the hide entirely and so\n // PRESERVES their `retentionStatus` filter.\n assignRetentionHideForOperation(\n contextualFilter,\n this.resourceConfiguration,\n executionContext,\n executedCoreOperation,\n );\n\n // Check if contextual filtering should be excluded\n if (options?.excludeContextualFilter === true) {\n // Skip all contextual filtering if explicitly disabled\n this.logDebug('Contextual filtering disabled, returning base filter only');\n return contextualFilter;\n }\n\n // Determine blacklisted fields\n const blacklistedFields = new Set<string>();\n\n // Always exclude the resource's own resourceFieldIdentifier to avoid self-reference in filtering\n blacklistedFields.add(this.resourceConfiguration.resourceFieldIdentifier);\n\n // Add custom blacklisted fields if provided\n if (Array.isArray(options?.excludeContextualFilter)) {\n options.excludeContextualFilter.forEach(field => blacklistedFields.add(field));\n }\n\n // Scope-required reference search — the SKIP half. Its resolving half runs in\n // `_doSearch`/`_doCount`; the two must travel together, which is why they share a module.\n const junctionScopedFieldIdentifiers = collectJunctionScopedFieldIdentifiers({\n relationshipContexts: executionContext.relationshipContexts,\n allResourceFieldIdentifiers: this.resourceRegistry?.getResourcesRegistry()?.allResourceFieldIdentifiers,\n });\n\n // Add context resource filters (with nested path support, schema validation and blacklist filtering)\n const contextResourceIds = executionContext.getContextResourceIds();\n contextResourceIds.forEach((resourceId, fieldIdentifier) => {\n // Skip if field is blacklisted\n if (blacklistedFields.has(fieldIdentifier)) {\n this.logDebug('Skipping blacklisted field in contextual filter', { fieldIdentifier });\n return;\n }\n // Skip junction-scoped scope params — resolved via applyJunctionScopeFilter.\n if (junctionScopedFieldIdentifiers.has(fieldIdentifier)) {\n this.logDebug('Skipping junction-scoped field in contextual filter (resolved through junction)', { fieldIdentifier });\n return;\n }\n\n // A resource's PRIMARY-SCOPE FK is not always modeled in its Zod main schema, and that is\n // legitimate rather than an authoring mistake:\n //\n // - a schema SHARED across scopes cannot author one — `ScopeFeaturesWithOverridesSchema`\n // backs ORGANIZATION_FEATURES, APPLICATION_FEATURES and USER_FEATURES, each with a\n // different scope FK, so the column comes from the relationship's `foreignKeyField`;\n // - scope-AUGMENTED resources add the column at the persistence layer (the\n // `auditLogs.applicationId` case already documented on the write path below).\n //\n // The WRITE path accounts for this: `enrichDataWithContextFields` deliberately uses the\n // NON-throwing lookup and injects the scope field at the TOP LEVEL when the Zod schema does\n // not model it. The FILTER path used the throwing lookup, so the two disagreed about which\n // fields a scoped resource has — and filtering such a resource threw CONFIGURATION.\n //\n // Concretely (2026-08-04): deleting an ORGANIZATION cascades to ORGANIZATION_FEATURES, and\n // building that child's filter threw whenever the request context carried an `organizationId`.\n // An org-scoped request therefore could NOT delete a tenant at all — a 500 with the whole\n // transaction rolled back — while the `organization-purge` batch succeeded, because its\n // internal context carries no org and never reached this branch.\n //\n // FAIL-CLOSED IS PRESERVED. Only this resource's OWN primary-scope field identifier may\n // resolve to a top-level column, and only when the schema genuinely does not model it.\n // Every other unmodeled context field still throws: silently dropping an unrecognised context\n // filter would widen a query beyond its tenant, which is a far worse failure than a 500.\n const primaryScopeFieldIdentifier = this.resourceConfiguration.resourcePrimaryScope\n ? PRIMARY_SCOPE_TO_FIELD_IDENTIFIER[this.resourceConfiguration.resourcePrimaryScope]\n : undefined;\n if (\n fieldIdentifier === primaryScopeFieldIdentifier\n && this.resourceOperationHelper.findNestedFieldPathsFromZodSchema(\n this.resourceConfiguration.mainSchema,\n fieldIdentifier,\n ).length === 0\n ) {\n // Scoped resources always carry their scope FK as a top-level column — the same invariant\n // the write-path injection relies on, so the filter targets exactly what the write wrote.\n // The context value is AUTHORITATIVE: a caller-supplied value that disagrees is refused,\n // never deferred to. See `applyAuthoritativeContextFilterValue` for why this is one shared\n // authority rather than four look-alike branches.\n this.resourceOperationHelper.applyAuthoritativeContextFilterValue(\n contextualFilter, fieldIdentifier, resourceId,\n { fieldIdentifier, resourceIdentifier: String(this.resourceConfiguration.resourceIdentifier) },\n );\n return;\n }\n\n // Find all schema paths that end with this field identifier (including nested paths)\n const allMatchingPaths = this.resourceOperationHelper.findRequiredNestedFieldPathsFromZodSchema(\n this.resourceConfiguration.mainSchema,\n fieldIdentifier,\n executionContext,\n {\n reason: 'context_filter',\n resourceIdentifier: this.resourceConfiguration.resourceIdentifier,\n message: `Execution context field '${fieldIdentifier}' is missing from schema for resource '${this.resourceConfiguration.resourceIdentifier}' during contextual filtering`,\n }\n );\n\n /*\n * THE SCOPE FIELD FILTERS AT THE TOP LEVEL ONLY — the read-side twin of the write path's own\n * lesson (`enrichDataWithContextFields`: \"Deep matches inside embedded payloads are never the\n * scope column\", learned on `DataSeedRun.failureReport` embedding `initiatorIds.applicationId`).\n *\n * Measured on the first PostgreSQL-backed resource to carry a nested occurrence of its scope\n * field's NAME (`wildoApplicationActorTasks` models\n * `errorStates.errorItems.initiatorIds.organizationId` — a recorded error's initiator, pure\n * data): the unfiltered sweep put that dotted path into the filter, which PostgreSQL refused\n * as an invalid column reference (a 400 on every LIST), and which MongoDB would have matched\n * as \"rows whose nested error items carry the value\" — silently hiding every row WITHOUT such\n * errors from its own tenant. Same defect as the initiator-organization confinement fixed the\n * same day; this is its sibling call site.\n *\n * FAIL-CLOSED, not fail-open: for the scope field, a schema that models the name ONLY nested\n * is refused outright — silently dropping the context filter would widen the query beyond its\n * tenant, and filtering on the nested path is wrong on both adapters. Non-scope context\n * identifiers keep the full nested behavior; their nested matches are the relationship\n * machinery's business, not tenancy's.\n */\n const isScopeField = fieldIdentifier === primaryScopeFieldIdentifier;\n const matchingPaths = isScopeField\n ? allMatchingPaths.filter(fullPath => fullPath === fieldIdentifier)\n : allMatchingPaths;\n if (isScopeField && matchingPaths.length === 0 && allMatchingPaths.length > 0) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n reason: 'scope_field_modeled_only_nested',\n resourceIdentifier: this.resourceConfiguration.resourceIdentifier,\n fieldIdentifier,\n nestedPaths: allMatchingPaths,\n message: `Scope field '${fieldIdentifier}' appears only NESTED in the schema for resource `\n + `'${this.resourceConfiguration.resourceIdentifier}'. A scoped resource carries its scope FK as a `\n + 'top-level column (the write path injects it there); a nested occurrence of the name is data. '\n + 'Refusing rather than widening the query beyond its tenant.',\n },\n });\n }\n\n // Process each matching path\n matchingPaths.forEach(fullPath => {\n // A surrogate primary key (e.g. FILES `fileId`) exists in the Zod schema but is stored\n // only as Mongo `_id` (a read-only virtual projection), so a filter keyed on it would\n // silently match nothing. Resolve to the queryable key (`_id` for a surrogate PK,\n // unchanged for every other field).\n const filterPath = this.resourceOperationHelper.resolveQueryableFilterPath(\n this.resourceConfiguration.mainSchema,\n fullPath,\n );\n // The context value is AUTHORITATIVE. This branch previously SKIPPED when the caller had\n // already supplied the path, which is how a tool call carrying another tenant's\n // `organizationId` was answered with that tenant's rows.\n this.resourceOperationHelper.applyAuthoritativeContextFilterValue(\n contextualFilter, filterPath, resourceId,\n { fieldIdentifier, resourceIdentifier: String(this.resourceConfiguration.resourceIdentifier) },\n );\n });\n });\n\n // D3 — initiator-organization confinement, previously PostgreSQL-only.\n // Mongo has no column plan, so every schema-modelled field is persisted by definition and\n // the persistence predicate is always true; the RULE is identical, which is the point of it\n // living in one place.\n assignInitiatorOrganizationConfinementToFilter({\n filter: contextualFilter,\n executionContext,\n blacklistedFields,\n mainSchema: this.resourceConfiguration.mainSchema,\n schemaPaths: this.resourceOperationHelper,\n isFieldPersisted: () => true,\n });\n\n // Defense-in-depth: enforce userId = null for ANONYMOUS scope on isAnonymizable resources.\n // Prevents any anonymous query from seeing authenticated users' data even if scoping is bypassed.\n //\n // THIS PREDICATE IS PRESENCE-BLIND, and stays correct only because of a declaration elsewhere.\n // MongoDB documents `{ field: null }` as matching documents where the field is null OR where it\n // is ABSENT, so this equality alone cannot tell \"anonymous\" from \"no userId key at all\" — and\n // absence is a reachable stored state now that clearing an optional field removes it.\n // What keeps it sound: `isAnonymizable` REQUIRES `userId` to accept null (config-time\n // `safeParse(null)` probe in the resource factory), so the field is authored nullable, the\n // field-clearing partition stores a literal null for it rather than removing it, and the\n // repository writes that null explicitly. Every such row therefore HAS the key.\n // If `userId` on an anonymizable resource is ever made merely `.optional()`, this filter starts\n // matching rows that never had a userId, and must move to an explicit presence predicate.\n if (executionContext.isAnonymousExecution() && this.resourceConfiguration.isAnonymizable) {\n const userPaths = this.resourceOperationHelper.findNestedFieldPathsFromZodSchema(\n this.resourceConfiguration.mainSchema, 'userId'\n );\n userPaths.forEach(fullPath => {\n this.resourceOperationHelper.setNestedValue(contextualFilter, fullPath, null);\n });\n }\n\n // Apply FK relationship filters from relationship contexts\n // This handles cases like /assigned-to-users/{userId}/todos where we need to filter by assignedToUserId\n this.applyFKRelationshipFilters(executionContext, contextualFilter, blacklistedFields);\n\n // ── WS-C: organization-unit narrowing (authorization boundary) ────────────────────────────────\n // Confines a caller whose authority for this resource came ONLY from a unit grant to the rows of\n // those units, reading the decision the authorization gate already stamped on the context.\n //\n // Three placement facts are load-bearing:\n // - AFTER the `options.excludeContextualFilter` early-return, unlike the retention hide above. A\n // unit narrows WITHIN the organization scope (D-C1), so it belongs to the SCOPE axis: a caller\n // who deliberately bypasses scope already crosses the tenant boundary, which is strictly wider\n // than crossing a unit boundary inside one tenant.\n // - LAST, writing at the TOP LEVEL, so a caller-supplied value for the unit field is OVERWRITTEN\n // rather than honoured — the same fail-closed reasoning as the retention hide.\n // - FAIL-CLOSED on a missing decision: a narrowed resource reached without one was reached around\n // the authorization layer, and the authority answers that with no rows, never all rows.\n assignOrganizationUnitNarrowingToFilter(\n contextualFilter,\n this.resourceConfiguration.resourceIdentifier,\n this.resourceRegistry?.getResourcesRegistry()?.organizationUnitNarrowing,\n executionContext,\n );\n\n // ── Scope-ROOT collection confinement (tenant boundary) ───────────────────────────────────────\n // The tenant resource itself carries no `organizationId` column, so every confinement above\n // loses the axis on it: the context loop skips the field (blacklisted as this resource's own\n // identifier) and D3 refuses for the same blacklist. Measured: a scope-root LIST compiled to the\n // EMPTY filter on both adapters. One authority, both adapters — a tenancy predicate present here\n // and absent on the PostgreSQL sibling would be a bypass, not a gap.\n //\n // Placement matches the unit narrowing and D3, not the retention hide: this is the SCOPE axis, so\n // a caller who deliberately bypassed scope via `excludeContextualFilter` has already returned\n // above.\n assignScopeRootCollectionConfinementToFilter({\n filter: contextualFilter,\n executionContext,\n resourceConfiguration: this.resourceConfiguration,\n executedCoreOperation: executedCoreOperation,\n });\n\n return contextualFilter;\n }\n\n /**\n * Refuse a write whose unit-field value falls outside the caller's unit grant (WS-C).\n *\n * assurance-control: WILDO.ACCESS.SCOPE_CONFINEMENT — least-privilege confinement on the WRITE side.\n *\n * A row filter cannot constrain a CREATE (there is no row yet) and does not constrain the VALUES an\n * UPDATE writes, so without this a caller confined to one unit could create rows in another unit, or\n * move an existing row out of their own — and every later read would correctly exclude those rows,\n * making the escalation invisible from the very surface meant to contain it.\n *\n * `executedCoreOperation` is the write THIS call performs, not `executionContext.operation`: the\n * rule differs between row-creating and updating writes (a create must supply a unit, an update may\n * omit it), and the repository's own write methods never `withOperation()` the context.\n */\n /**\n * TENANT COHERENCE on the narrowing dimension — the half the grant check structurally cannot cover.\n *\n * `resolveOrganizationUnitNarrowingWriteViolation` returns early for an `UNRESTRICTED` caller, which\n * is correct for the GRANT question (an organization-wide principal is not confined) but leaves the\n * VALUE unexamined. So an organization-wide admin could name any unit id at all — including one\n * belonging to ANOTHER TENANT. The row stays inside its own tenant, so nothing crosses; what it\n * becomes is an orphan pointing at a unit nobody in its tenant can hold, therefore confined to a\n * grant that cannot exist and visible only to organization-wide callers. Found by the hostile lane's\n * X-2 probe, which is why that probe reports the DATABASE and not just the status.\n *\n * The check is a SCOPED read: `readForInternalScan` applies the contextual scope filter (so the unit\n * must be in the caller's organization) without depending on a user-facing READ operation on\n * `ORGANIZATION_UNITS` — a plain `read()` would couple this write to that resource's operation\n * vocabulary and to the caller's `relationshipContexts`, which is the documented way cross-resource\n * reads on a borrowed execution context turn into 500s.\n *\n * Not found and belongs-to-another-tenant answer identically on purpose: a write payload must not\n * become a probe into another tenant's org chart.\n */\n private async assertOrganizationUnitBelongsToCallerTenant(\n payload: unknown,\n executedCoreOperation: CoreResourceOperation,\n executionContext: ExecutionContext<any>,\n ): Promise<void> {\n const suppliedUnitId = resolveSuppliedOrganizationUnitIdForTenantCheck(\n payload as Record<string, unknown> | null | undefined,\n this.resourceConfiguration.resourceIdentifier,\n this.resourceRegistry?.getResourcesRegistry()?.organizationUnitNarrowing,\n );\n if (!suppliedUnitId) return;\n\n // An exempt execution type never carries a unit grant and is trusted by the scope filter too, so\n // holding it to a tenant read here would fail closed on batches and webhooks for no gain.\n if (isOrganizationUnitNarrowingExemptExecution(executionContext.executionType)) return;\n\n const unitRepository = this.repositoriesRegistry?.getRepository(CoreResourceType.ORGANIZATION_UNITS);\n // An application that never registered organization units cannot have a unit to point at, so there\n // is nothing to verify — an accurate answer rather than a swallowed error.\n if (!unitRepository) return;\n\n // `excludeContextualFilter: true` + an EXPLICIT tenant comparison, rather than letting the\n // contextual filter do it. Borrowing the caller's execution context for a read of a DIFFERENT\n // resource is the documented way to produce a 500: that context carries THIS resource's field\n // identifier, and `buildContextualFilter` fails closed on `organizationUnits` with\n // \"Execution context field 'teamGoalId' is missing from schema\" (reason `context_filter`).\n // Observed exactly that before this line existed.\n //\n // Nothing is weakened by the bypass — the scope question is simply asked here instead, against the\n // tenant the ROW is being written into (falling back to the caller's own), which is the same\n // comparison `authorizeOrganizations` makes for a fetched row. The retention hide is unaffected:\n // it is applied BEFORE that early-return by design.\n const unit = await unitRepository.readForInternalScan(\n executionContext as never,\n { _id: suppliedUnitId },\n { excludeContextualFilter: true },\n );\n\n const writeTenantId = String(\n (payload as Record<string, unknown> | null | undefined)?.organizationId\n ?? executionContext.initiatorIds?.organizationId\n ?? '',\n );\n const unitTenantId = String((unit as { organizationId?: unknown } | null)?.organizationId ?? '');\n\n // Three ways to reach the refusal below, and the third is a DECISION rather than an oversight:\n // 1. no such unit anywhere — `unit` is null\n // 2. the unit belongs to another tenant — the ids differ\n // 3. the write's tenant is undeterminable — `writeTenantId` is empty\n //\n // (3) fails CLOSED deliberately. A unit-narrowed resource is organization-scoped by construction\n // (a unit belongs to an organization), so a write that carries no tenant on the payload and whose\n // principal has none either cannot have its unit reference verified at all — and this module's\n // governing rule is that an inability to verify must never read as permission. Exempt execution\n // types were already returned above, so this does not catch batches, cascades or webhooks.\n //\n // Do not \"simplify\" the emptiness test away: it looks like a defensive string check and is\n // actually the third branch.\n if (unit && writeTenantId && unitTenantId === writeTenantId) return;\n\n throw this.errorBuilder.buildError(ErrorType.AUTHORIZATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.AUTHORIZATIONS_ACCESS_DENIED,\n context: {\n reason: OrganizationUnitNarrowingWriteViolationReason.UNIT_OUTSIDE_TENANT,\n resourceIdentifier: this.resourceConfiguration.resourceIdentifier,\n executedCoreOperation,\n attemptedOrganizationUnitId: suppliedUnitId,\n },\n });\n }\n\n private async assertOrganizationUnitWriteWithinGrant(\n payload: unknown,\n executedCoreOperation: CoreResourceOperation,\n executionContext: ExecutionContext<any>,\n ): Promise<void> {\n await this.assertOrganizationUnitBelongsToCallerTenant(payload, executedCoreOperation, executionContext);\n\n const violation = resolveOrganizationUnitNarrowingWriteViolation(\n payload as Record<string, unknown> | null | undefined,\n executedCoreOperation,\n this.resourceConfiguration.resourceIdentifier,\n this.resourceRegistry?.getResourcesRegistry()?.organizationUnitNarrowing,\n executionContext,\n );\n if (!violation) return;\n\n throw this.errorBuilder.buildError(ErrorType.AUTHORIZATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.AUTHORIZATIONS_ACCESS_DENIED,\n context: {\n // diagnostic (log-only)\n reason: violation.reason,\n resourceIdentifier: this.resourceConfiguration.resourceIdentifier,\n executedCoreOperation,\n unitFieldName: violation.unitFieldName,\n grantedOrganizationUnitIds: violation.grantedOrganizationUnitIds,\n attemptedOrganizationUnitId: violation.attemptedOrganizationUnitId,\n },\n });\n }\n\n /**\n * Deps bundle handed to the ADAPTER-NEUTRAL write-integrity authority\n * (`resource-write-integrity.backend.ts`), on both CREATE and UPDATE. Both this MongoDB repository and\n * the PostgreSQL repository — separate classes, not an inheritance pair — pass the same shape, so the\n * FK-existence-in-scope, scope-via-junction-membership, and top-level-mainSchema-check invariants live\n * in ONE place and cannot become adapter-conditional.\n */\n private get writeIntegrityDeps(): ResourceWriteIntegrityDeps {\n return {\n resourceConfiguration: this.resourceConfiguration,\n resourceRegistry: this.resourceRegistry,\n repositoriesRegistry: this.repositoriesRegistry,\n errorBuilder: this.errorBuilder,\n };\n }\n\n /**\n * Apply FK relationship filters from ExecutionContext.relationshipContexts\n *\n * When a resource is accessed via a FK relationship path (e.g., /assigned-to-users/{userId}/todos),\n * this method adds the appropriate filter to ensure only resources matching the FK field are returned.\n *\n * For example:\n * - URL: /assigned-to-users/{userId}/todos\n * - relationshipContext: { resourceType: 'USERS', relationshipField: 'assignedToUserId', resourceId: '123' }\n * - Filter added: { assignedToUserId: '123' }\n */\n private applyFKRelationshipFilters(\n executionContext: ExecutionContext<any>,\n filter: FilterQuery<any>,\n blacklistedFields: Set<string>\n ): void {\n assignRelationshipForeignKeyFiltersToFilter({\n filter,\n executionContext,\n blacklistedFields,\n resourceIdentifier: String(this.resourceConfiguration.resourceIdentifier),\n mainSchema: this.resourceConfiguration.mainSchema,\n schemaPaths: this.resourceOperationHelper,\n });\n }\n\n\n\n /**\n * Check if a field exists in the mongoose model schema\n */\n private hasSchemaField(fieldName: string): boolean {\n if (!this.mongooseModel?.schema?.paths) {\n return false;\n }\n\n return this.mongooseModel.schema.paths[fieldName] !== undefined;\n }\n\n /**\n * Whether `error` is a Mongoose CastError (a query/value could not be cast to its field\n * type — e.g. a malformed or UUID-format string supplied for an ObjectId `_id`). On a READ\n * filter this means no document can match, so the caller treats it as not-found rather than\n * an INTERNAL error. Mongoose tags these with `name === 'CastError'`.\n */\n private isMongooseCastError(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { name?: unknown }).name === 'CastError'\n );\n }\n\n /**\n * Handle MongoDB errors and convert them to application-specific errors.\n * Specifically handles unique constraint violations (E11000 duplicate key error).\n *\n * A duplicate key resolves to the custom message reference the VIOLATED constraint declared\n * (`.isUnique({ conflictMessageReference })` / `.businessKeySet([...], { conflictMessageReference })`),\n * falling back to the generic {@link ErrorCustomMessageReference.UNIQUE_CONSTRAINT_VIOLATION}\n * when the resource named none or the violated index cannot be attributed unambiguously. Without\n * that, every duplicate on every resource reports the same code and an integrator has to parse a\n * database message to learn which identity was rejected.\n *\n * @param error - The error caught from MongoDB operation\n * @param executionContext - The execution context for error building\n * @returns The original error or a transformed application error\n */\n private handleMongoDBError(error: unknown, executionContext?: ExecutionContext<any>): Error | WildoError_Backend {\n // Check for MongoDB duplicate key error (E11000)\n const isMongoError = error && typeof error === 'object' && 'code' in error;\n\n if (isMongoError && (error as any).code === 11000) {\n // Extract field name from the error message\n // MongoDB error message format: \"E11000 duplicate key error collection: db.collection index: fieldName_1 dup key: { fieldName: \"value\" }\"\n const errorMessage = (error as any).message || '';\n const keyValueMatch = errorMessage.match(/dup key: \\{ ([^:]+):/);\n const fieldName = keyValueMatch ? keyValueMatch[1].trim() : 'unknown';\n\n // Extract the duplicate value if present\n const valueMatch = errorMessage.match(/dup key: \\{ [^:]+: \"([^\"]+)\" \\}/);\n const duplicateValue = valueMatch ? valueMatch[1] : undefined;\n\n const violatedFieldNames = this.extractViolatedUniqueIndexFields(error, errorMessage);\n const declaredConflictReference = resolveDeclaredUniqueConflictReference(\n this.resourceConfiguration.mainSchema as any,\n violatedFieldNames,\n );\n\n return this.errorBuilder.buildError(\n ErrorType.CONFLICT,\n executionContext,\n {\n customMessageReference: declaredConflictReference ?? ErrorCustomMessageReference.UNIQUE_CONSTRAINT_VIOLATION,\n context: {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n fieldName,\n duplicateValue,\n violatedFields: violatedFieldNames,\n originalError: errorMessage\n }\n }\n );\n }\n\n // Return the original error if not a unique constraint violation\n return error instanceof Error ? error : new Error(describeCaughtError(error));\n }\n\n /**\n * Every field covered by the unique index a duplicate-key error violated.\n *\n * `keyPattern` is the structured, driver-supplied answer and is preferred whenever present. The\n * message fallback exists because the field is not guaranteed across driver versions and error\n * wrappers, and losing attribution there would silently downgrade every conflict on the resource\n * back to the generic code — a regression that no test would notice, since the generic code is a\n * legitimate outcome. The message form is `index: a_1_b_1 dup key: …`, whose `_1` / `_-1`\n * direction suffixes are stripped to recover the field names.\n *\n * Returns `[]` when neither source yields anything, which the caller treats as \"unattributable\".\n */\n private extractViolatedUniqueIndexFields(error: unknown, errorMessage: string): string[] {\n const keyPattern = (error as { keyPattern?: unknown })?.keyPattern;\n if (keyPattern && typeof keyPattern === 'object') {\n return Object.keys(keyPattern as Record<string, unknown>);\n }\n\n const indexNameMatch = errorMessage.match(/index:\\s+(\\S+)\\s+dup key:/);\n const indexName = indexNameMatch?.[1];\n if (!indexName) {\n return [];\n }\n // `a_1_b_-1` → ['a', 'b']. A field name may itself contain underscores, so the split is on the\n // direction segments rather than on every underscore.\n return indexName\n .split(/_-?1(?:_|$)/)\n .map((segment) => segment.trim())\n .filter((segment) => segment.length > 0);\n }\n\n\n /**\n * Add user tracking to enriched data (timestamps are handled automatically by MongoDB)\n * @param enrichedData - The data to add user tracking to\n * @param executionContext - The execution context containing user info\n * @param operation - The operation being performed\n * @returns Data with user tracking added\n */\n private addUserTracking(enrichedData: any, executionContext: ExecutionContext<any>, operation?: CoreResourceOperation): any {\n // Note: createdAt and updatedAt timestamps are handled automatically by MongoDB, so we don't add them here\n\n // Add operation-specific user tracking if userId is available in execution context\n const userId = executionContext.initiatorIds?.userId;\n if (userId) {\n\n // For CREATE operations: populate createdByUserId if field exists in database schema\n if (operation === CoreResourceOperation.CREATE || operation === CoreResourceOperation.CREATE_MANY) {\n if (this.hasSchemaField('createdByUserId') && !enrichedData.createdByUserId) {\n enrichedData.createdByUserId = userId;\n }\n }\n\n // For UPDATE operations: populate updatedByUserId or lastUpdatedByUserId if field exists in database schema\n if (operation === CoreResourceOperation.UPDATE || operation === CoreResourceOperation.UPDATE_MANY) {\n // Try updatedByUserId first, then lastUpdatedByUserId as fallback\n if (this.hasSchemaField('updatedByUserId') && !enrichedData.updatedByUserId) {\n enrichedData.updatedByUserId = userId;\n } else if (this.hasSchemaField('lastUpdatedByUserId') && !enrichedData.lastUpdatedByUserId) {\n enrichedData.lastUpdatedByUserId = userId;\n }\n }\n }\n\n return enrichedData;\n }\n\n /**\n * Transform mongoose document to response format using operation DTO\n */\n private transformDocumentToResponse<T = undefined>(document: any, operationIdentifier: string): T extends undefined ? any : T {\n if (!document) {\n return null;\n }\n\n // Convert mongoose document to plain object with error handling\n let plainObject: any;\n try {\n plainObject = document.toObject ? document.toObject() : document;\n } catch (error) {\n this.logDebug('Document toObject() failed, using document as-is', {\n operationIdentifier,\n error: describeCaughtError(error)\n });\n plainObject = document;\n }\n\n plainObject = normalizeRepositoryVersionMetadata(plainObject);\n\n // Transforming to response DTO is the role of the service layer\n return plainObject;\n\n }\n\n private previewDocument(document: any): any {\n if (!document) return null;\n const obj = document.toObject ? document.toObject() : document;\n // Limit preview size and hide potentially large fields\n const clone: any = { ...obj };\n Object.keys(clone).forEach((k) => {\n const v = clone[k];\n if (v && typeof v === 'object') {\n if (Array.isArray(v)) {\n clone[k] = `[Array(${v.length})]`;\n } else {\n clone[k] = '[Object]';\n }\n }\n });\n return clone;\n }\n // ================================\n // Search Configuration Methods\n // ================================\n\n /**\n * Retrieves the default search operation configuration for direct helper paths.\n * Routed execution uses the concrete SEARCH variant passed into `_doSearch`,\n * because collection-view metadata and response projection must stay aligned.\n */\n private findSearchOperationConfiguration(): ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> | null {\n const searchOperations = Array.from(this.operationsMap.values()).filter(\n operation => operation.operationIdentifier === CoreResourceOperation.SEARCH\n );\n const defaultSearchOperations = searchOperations.filter(\n operation => operation.isOperationDefault === true\n );\n if (defaultSearchOperations.length > 1) {\n this.logDebug('Ambiguous default SEARCH operation configurations', {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n candidateVariants: defaultSearchOperations.map((operation) => ({\n variantType: operation.variantType,\n variantKey: operation.variantKey,\n })),\n });\n return null;\n }\n return defaultSearchOperations[0] ?? searchOperations[0] ?? null;\n }\n\n /**\n * Constructs the MongoDB search filter from the query string and the\n * operation's `searchableFields`.\n *\n * `searchableFields` is a union list: plain field names match THIS collection by\n * regex (legacy behaviour); {@link SearchableRelationDescriptor} entries match\n * via a RELATED resource and resolve into a `{ [localField]: { $in: ids } }`\n * branch (see {@link buildRelationalSearchCondition}). Both forms OR together.\n *\n * - Empty query → `{}` (no search constraint; scope still applies upstream).\n * - No `searchableFields` configured → legacy `$text` index fallback.\n * - `searchableFields` configured but every branch resolves empty → a\n * never-match guard (`{ _id: { $in: [] } }`), NOT `{}`: a configured search\n * that matches nothing must return nothing, never the whole (scoped) collection.\n *\n * Async because relational branches resolve their ids via a secondary match on\n * the related resource's repository.\n *\n * @param searchQuery - The search query string\n * @param searchConfig - The routed SEARCH operation configuration\n * @returns MongoDB filter query for search\n */\n private async constructSearchQuery(\n searchQuery: string,\n searchConfig: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>\n ): Promise<FilterQuery<any>> {\n if (!searchQuery?.trim()) {\n return {};\n }\n\n const op = searchConfig as unknown as { searchableFields?: SearchableFieldDescriptor[]; searchableOptions?: CollectionView_SearchOptions };\n const searchableFields = op.searchableFields;\n const searchableOptions = op.searchableOptions;\n\n if (!searchableFields?.length) {\n return { $text: { $search: searchQuery } };\n }\n\n // Own-collection field names → regex conditions (legacy path).\n const ownFields = searchableFields.filter((field): field is string => typeof field === 'string');\n const searchConditions = this.buildFieldSearchConditions(\n searchQuery,\n ownFields,\n searchableOptions\n );\n\n // Relational entries → secondary match on the related resource, folded into an\n // `$in` branch on this collection's join field. Resolved in declared order.\n const relationDescriptors = searchableFields.filter(isSearchableRelationDescriptor);\n for (const descriptor of relationDescriptors) {\n const relationCondition = await this.buildRelationalSearchCondition(searchQuery, descriptor);\n if (relationCondition) {\n searchConditions.push(relationCondition);\n }\n }\n\n if (searchConditions.length === 0) {\n // `searchableFields` was non-empty (relational-only, and every related match\n // resolved to zero ids) → match NOTHING rather than the whole collection.\n return { _id: { $in: [] } };\n }\n\n return searchConditions.length > 1\n ? { $or: searchConditions }\n : searchConditions[0];\n }\n\n /**\n * Resolve one {@link SearchableRelationDescriptor} into a\n * `{ [localField]: { $in: ids } }` branch by running the related resource's own\n * searchable surface against `searchQuery` (see {@link findSearchMatchTargetIds}).\n *\n * Returns `null` — contributing no OR branch — when the related repository can't\n * be resolved or the related match set is empty. This is the correct fail-safe\n * for a MATCH branch: it only ever ADDS results within the caller's already\n * scoped+filtered set, so omitting it can never widen visibility — it merely\n * under-matches.\n */\n private async buildRelationalSearchCondition(\n searchQuery: string,\n descriptor: SearchableRelationDescriptor\n ): Promise<FilterQuery<any> | null> {\n const relatedRepository = this.repositoriesRegistry.getRepository(descriptor.relatedResource);\n if (!relatedRepository || typeof relatedRepository.findSearchMatchTargetIds !== 'function') {\n this.logDebug('Relational search branch skipped: related repository unavailable', {\n relatedResource: descriptor.relatedResource,\n localField: descriptor.localField,\n });\n return null;\n }\n\n const joinField = descriptor.relatedJoinField ?? '_id';\n const ids: string[] = await relatedRepository.findSearchMatchTargetIds(searchQuery, joinField, { fields: descriptor.fields });\n if (ids.length === 0) {\n return null;\n }\n\n return { [descriptor.localField]: { $in: ids } };\n }\n\n /**\n * Builds individual field search conditions based on searchable options\n * @param searchQuery - The search query string\n * @param searchableFields - Array of fields that can be searched\n * @param searchableOptions - Search behavior options\n * @returns Array of MongoDB field conditions\n */\n private buildFieldSearchConditions(\n searchQuery: string,\n searchableFields: string[],\n searchableOptions?: CollectionView_SearchOptions\n ): FilterQuery<any>[] {\n const caseSensitive = searchableOptions?.caseSensitive || false;\n const fullMatchOnly = searchableOptions?.fullMatchOnly || false;\n\n return searchableFields.map((field: string) => {\n if (fullMatchOnly) {\n return caseSensitive\n ? { [field]: searchQuery }\n : { [field]: { $regex: `^${this.escapeRegex(searchQuery)}$`, $options: 'i' } };\n } else {\n return caseSensitive\n ? { [field]: { $regex: this.escapeRegex(searchQuery) } }\n : { [field]: { $regex: this.escapeRegex(searchQuery), $options: 'i' } };\n }\n });\n }\n\n /**\n * Validates and filters the provided filter object against allowed filter fields configuration\n * @param requestedFilter - The filter object from the request\n * @param searchConfig - The search operation configuration\n * @returns Validated and sanitized filter object\n */\n private sanitizeRequestFilter(\n requestedFilter: FilterQuery<any>,\n searchConfig: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>\n ): FilterQuery<any> {\n if (!requestedFilter || Object.keys(requestedFilter).length === 0) {\n return {};\n }\n\n const { filterFields } = searchConfig as unknown as { filterFields?: Record<string, unknown> };\n\n // If no filter fields configured, return filter as-is (fallback behavior)\n if (!filterFields || Object.keys(filterFields).length === 0) {\n return requestedFilter;\n }\n\n // Only include fields that are explicitly allowed in the configuration\n const sanitizedFilter: FilterQuery<any> = {};\n\n Object.entries(requestedFilter).forEach(([fieldName, fieldValue]) => {\n if (filterFields[fieldName]) {\n sanitizedFilter[fieldName] = fieldValue;\n }\n // Note: Invalid fields are silently ignored for security\n });\n\n return sanitizedFilter;\n }\n\n /**\n * Constructs validated sort options based on allowed sort fields configuration\n * @param requestedSort - The sort object from the request\n * @param searchConfig - The search operation configuration\n * @returns Validated MongoDB sort object\n */\n private constructValidatedSortOptions(\n requestedSort: Record<string, 1 | -1> | undefined,\n searchConfig: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>\n ): Record<string, 1 | -1> {\n const { sortFields } = searchConfig as unknown as { sortFields?: readonly string[] };\n const defaultSort: Record<string, 1 | -1> = { createdAt: -1 };\n\n // If no sort fields configured, use requested sort or default\n if (!sortFields?.length) {\n return requestedSort || defaultSort;\n }\n\n // If no sort requested, use first configured sort field\n if (!requestedSort) {\n const firstSortField = sortFields[0];\n return { [firstSortField]: -1 };\n }\n\n // Validate requested sort fields against configuration\n const validatedSort: Record<string, 1 | -1> = {};\n\n Object.entries(requestedSort).forEach(([fieldName, sortDirection]) => {\n if (sortFields.includes(fieldName) && (sortDirection === 1 || sortDirection === -1)) {\n validatedSort[fieldName] = sortDirection;\n }\n });\n\n // Return validated sort or fallback to default\n return Object.keys(validatedSort).length > 0 ? validatedSort : defaultSort;\n }\n\n\n\n}\n"]}