@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.
- package/dist/esm/base-classes/services/controllers/controller-resource.backend.service.d.ts +14 -3
- package/dist/esm/base-classes/services/controllers/controller-resource.backend.service.d.ts.map +1 -1
- package/dist/esm/base-classes/services/controllers/controller-resource.backend.service.js +115 -22
- package/dist/esm/base-classes/services/controllers/controller-resource.backend.service.js.map +1 -1
- package/dist/esm/base-classes/services/controllers/controllers-registry-handler.backend.service.d.ts +3 -1
- package/dist/esm/base-classes/services/controllers/controllers-registry-handler.backend.service.d.ts.map +1 -1
- package/dist/esm/base-classes/services/controllers/controllers-registry-handler.backend.service.js +8 -3
- package/dist/esm/base-classes/services/controllers/controllers-registry-handler.backend.service.js.map +1 -1
- package/dist/esm/base-classes/services/repositories/field-clearing-partition.backend.d.ts +11 -0
- package/dist/esm/base-classes/services/repositories/field-clearing-partition.backend.d.ts.map +1 -1
- package/dist/esm/base-classes/services/repositories/field-clearing-partition.backend.js +11 -2
- package/dist/esm/base-classes/services/repositories/field-clearing-partition.backend.js.map +1 -1
- package/dist/esm/base-classes/services/repositories/http-api/http-api-resource-repository.backend.service.d.ts +1 -0
- package/dist/esm/base-classes/services/repositories/http-api/http-api-resource-repository.backend.service.d.ts.map +1 -1
- package/dist/esm/base-classes/services/repositories/http-api/http-api-resource-repository.backend.service.js +6 -1
- package/dist/esm/base-classes/services/repositories/http-api/http-api-resource-repository.backend.service.js.map +1 -1
- package/dist/esm/base-classes/services/repositories/http-api/odata-query-compiler.backend.d.ts.map +1 -1
- package/dist/esm/base-classes/services/repositories/http-api/odata-query-compiler.backend.js +16 -0
- package/dist/esm/base-classes/services/repositories/http-api/odata-query-compiler.backend.js.map +1 -1
- package/dist/esm/base-classes/services/repositories/infrastructure-tier-contract.backend.d.ts +20 -6
- package/dist/esm/base-classes/services/repositories/infrastructure-tier-contract.backend.d.ts.map +1 -1
- package/dist/esm/base-classes/services/repositories/infrastructure-tier-contract.backend.js +88 -32
- package/dist/esm/base-classes/services/repositories/infrastructure-tier-contract.backend.js.map +1 -1
- package/dist/esm/base-classes/services/repositories/introspection/introspection-resource-repository.backend.service.d.ts +3 -1
- package/dist/esm/base-classes/services/repositories/introspection/introspection-resource-repository.backend.service.d.ts.map +1 -1
- package/dist/esm/base-classes/services/repositories/introspection/introspection-resource-repository.backend.service.js +32 -7
- package/dist/esm/base-classes/services/repositories/introspection/introspection-resource-repository.backend.service.js.map +1 -1
- package/dist/esm/base-classes/services/repositories/introspection/introspection-resource-source.backend.port.d.ts +8 -5
- package/dist/esm/base-classes/services/repositories/introspection/introspection-resource-source.backend.port.d.ts.map +1 -1
- package/dist/esm/base-classes/services/repositories/introspection/introspection-resource-source.backend.port.js.map +1 -1
- package/dist/esm/base-classes/services/repositories/postgresql-resource-repository.backend.service.d.ts +31 -0
- package/dist/esm/base-classes/services/repositories/postgresql-resource-repository.backend.service.d.ts.map +1 -1
- package/dist/esm/base-classes/services/repositories/postgresql-resource-repository.backend.service.js +127 -5
- package/dist/esm/base-classes/services/repositories/postgresql-resource-repository.backend.service.js.map +1 -1
- package/dist/esm/base-classes/services/repositories/repositories-registry-handler.backend.service.d.ts +71 -1
- package/dist/esm/base-classes/services/repositories/repositories-registry-handler.backend.service.d.ts.map +1 -1
- package/dist/esm/base-classes/services/repositories/repositories-registry-handler.backend.service.js +62 -2
- package/dist/esm/base-classes/services/repositories/repositories-registry-handler.backend.service.js.map +1 -1
- package/dist/esm/base-classes/services/repositories/repository-resource.backend.service.d.ts +21 -0
- package/dist/esm/base-classes/services/repositories/repository-resource.backend.service.d.ts.map +1 -1
- package/dist/esm/base-classes/services/repositories/repository-resource.backend.service.js +126 -4
- package/dist/esm/base-classes/services/repositories/repository-resource.backend.service.js.map +1 -1
- package/dist/esm/base-classes/services/services/resource-operation-implementation-coverage.backend.utils.d.ts +3 -26
- package/dist/esm/base-classes/services/services/resource-operation-implementation-coverage.backend.utils.d.ts.map +1 -1
- package/dist/esm/base-classes/services/services/resource-operation-implementation-coverage.backend.utils.js +3 -68
- package/dist/esm/base-classes/services/services/resource-operation-implementation-coverage.backend.utils.js.map +1 -1
- package/dist/esm/base-classes/services/services/services-registry-handler.backend.service.d.ts.map +1 -1
- package/dist/esm/base-classes/services/services/services-registry-handler.backend.service.js +4 -2
- package/dist/esm/base-classes/services/services/services-registry-handler.backend.service.js.map +1 -1
- package/dist/esm/billing/services/custom-impl/billing-account.mutations.custom-impl.backend.service.js +6 -6
- package/dist/esm/billing/services/custom-impl/billing-account.mutations.custom-impl.backend.service.js.map +1 -1
- package/dist/esm/compliance/audit-trails/services/audit-event-dispatcher.backend.service.d.ts +38 -0
- package/dist/esm/compliance/audit-trails/services/audit-event-dispatcher.backend.service.d.ts.map +1 -1
- package/dist/esm/compliance/audit-trails/services/audit-event-dispatcher.backend.service.js +40 -0
- package/dist/esm/compliance/audit-trails/services/audit-event-dispatcher.backend.service.js.map +1 -1
- package/dist/esm/compliance/audit-trails/services/audit-logs.backend.service.d.ts +20 -0
- package/dist/esm/compliance/audit-trails/services/audit-logs.backend.service.d.ts.map +1 -1
- package/dist/esm/compliance/audit-trails/services/audit-logs.backend.service.js +28 -0
- package/dist/esm/compliance/audit-trails/services/audit-logs.backend.service.js.map +1 -1
- package/dist/esm/compliance/audit-trails/services/siem-export-config-cache-invalidation.custom-impl.backend.service.d.ts +12 -0
- package/dist/esm/compliance/audit-trails/services/siem-export-config-cache-invalidation.custom-impl.backend.service.d.ts.map +1 -0
- package/dist/esm/compliance/audit-trails/services/siem-export-config-cache-invalidation.custom-impl.backend.service.js +118 -0
- package/dist/esm/compliance/audit-trails/services/siem-export-config-cache-invalidation.custom-impl.backend.service.js.map +1 -0
- package/dist/esm/compliance/audit-trails/services/siem-webhook-delivery.backend.service.d.ts.map +1 -1
- package/dist/esm/compliance/audit-trails/services/siem-webhook-delivery.backend.service.js +8 -5
- package/dist/esm/compliance/audit-trails/services/siem-webhook-delivery.backend.service.js.map +1 -1
- package/dist/esm/compliance/audit-trails/services/utils/ocsf-activity-mapping.backend.utils.d.ts.map +1 -1
- package/dist/esm/compliance/audit-trails/services/utils/ocsf-activity-mapping.backend.utils.js +14 -0
- package/dist/esm/compliance/audit-trails/services/utils/ocsf-activity-mapping.backend.utils.js.map +1 -1
- package/dist/esm/config/custom/application-config-controller.backend.service.d.ts.map +1 -1
- package/dist/esm/config/custom/application-config-controller.backend.service.js +7 -1
- package/dist/esm/config/custom/application-config-controller.backend.service.js.map +1 -1
- package/dist/esm/config/models/app-config.backend.schemas.d.ts +4 -0
- package/dist/esm/config/models/app-config.backend.schemas.d.ts.map +1 -1
- package/dist/esm/config/services/app-configuration.backend.utils.d.ts +10 -1
- package/dist/esm/config/services/app-configuration.backend.utils.d.ts.map +1 -1
- package/dist/esm/config/services/app-configuration.backend.utils.js +13 -2
- package/dist/esm/config/services/app-configuration.backend.utils.js.map +1 -1
- package/dist/esm/data-seeding/services/shared/data-seed-scope-iteration.shared.utils.d.ts +2 -2
- package/dist/esm/data-seeding/services/shared/data-seed-scope-iteration.shared.utils.js +2 -2
- package/dist/esm/data-seeding/services/shared/data-seed-scope-iteration.shared.utils.js.map +1 -1
- package/dist/esm/databases/models/filter.backend.schemas.js +2 -2
- package/dist/esm/databases/models/filter.backend.schemas.js.map +1 -1
- package/dist/esm/databases/services/aggregation/aggregation-authorization.backend.service.d.ts.map +1 -1
- package/dist/esm/databases/services/aggregation/aggregation-authorization.backend.service.js +20 -1
- package/dist/esm/databases/services/aggregation/aggregation-authorization.backend.service.js.map +1 -1
- package/dist/esm/databases/services/redis.service.d.ts +27 -0
- package/dist/esm/databases/services/redis.service.d.ts.map +1 -1
- package/dist/esm/databases/services/redis.service.js +29 -0
- package/dist/esm/databases/services/redis.service.js.map +1 -1
- package/dist/esm/errors/services/error-handler.backend.service.d.ts.map +1 -1
- package/dist/esm/errors/services/error-handler.backend.service.js +5 -0
- package/dist/esm/errors/services/error-handler.backend.service.js.map +1 -1
- package/dist/esm/external-data/controllers/external-data-admin.backend.contracts.d.ts +41 -0
- package/dist/esm/external-data/controllers/external-data-admin.backend.contracts.d.ts.map +1 -0
- package/dist/esm/external-data/controllers/external-data-admin.backend.contracts.js +40 -0
- package/dist/esm/external-data/controllers/external-data-admin.backend.contracts.js.map +1 -0
- package/dist/esm/external-data/controllers/external-data-admin.backend.controller.d.ts +64 -0
- package/dist/esm/external-data/controllers/external-data-admin.backend.controller.d.ts.map +1 -0
- package/dist/esm/external-data/controllers/external-data-admin.backend.controller.js +193 -0
- package/dist/esm/external-data/controllers/external-data-admin.backend.controller.js.map +1 -0
- package/dist/esm/external-data/external-data-pipeline-run.backend.service.d.ts +13 -2
- package/dist/esm/external-data/external-data-pipeline-run.backend.service.d.ts.map +1 -1
- package/dist/esm/external-data/external-data-pipeline-run.backend.service.js +8 -2
- package/dist/esm/external-data/external-data-pipeline-run.backend.service.js.map +1 -1
- package/dist/esm/external-data/external-data-transform.backend.d.ts.map +1 -1
- package/dist/esm/external-data/external-data-transform.backend.js +7 -1
- package/dist/esm/external-data/external-data-transform.backend.js.map +1 -1
- package/dist/esm/external-data/models/external-data-pipeline-state.backend.schemas.d.ts +2 -0
- package/dist/esm/external-data/models/external-data-pipeline-state.backend.schemas.d.ts.map +1 -1
- package/dist/esm/external-data/models/external-data-pipeline-state.backend.schemas.js +13 -0
- package/dist/esm/external-data/models/external-data-pipeline-state.backend.schemas.js.map +1 -1
- package/dist/esm/external-providers/services/external-providers-registry.backend.service.d.ts +14 -0
- package/dist/esm/external-providers/services/external-providers-registry.backend.service.d.ts.map +1 -1
- package/dist/esm/external-providers/services/external-providers-registry.backend.service.js +6 -0
- package/dist/esm/external-providers/services/external-providers-registry.backend.service.js.map +1 -1
- package/dist/esm/files/controllers/file.controller.d.ts +24 -1
- package/dist/esm/files/controllers/file.controller.d.ts.map +1 -1
- package/dist/esm/files/controllers/file.controller.js +66 -2
- package/dist/esm/files/controllers/file.controller.js.map +1 -1
- package/dist/esm/files/handlers/file-upload-route-locals.backend.types.d.ts +17 -0
- package/dist/esm/files/handlers/file-upload-route-locals.backend.types.d.ts.map +1 -0
- package/dist/esm/files/handlers/file-upload-route-locals.backend.types.js +1 -0
- package/dist/esm/files/handlers/file-upload-route-locals.backend.types.js.map +1 -0
- package/dist/esm/files/handlers/resource-file-upload-handler.backend.service.d.ts +5 -1
- package/dist/esm/files/handlers/resource-file-upload-handler.backend.service.d.ts.map +1 -1
- package/dist/esm/files/handlers/resource-file-upload-handler.backend.service.js +42 -3
- package/dist/esm/files/handlers/resource-file-upload-handler.backend.service.js.map +1 -1
- package/dist/esm/files/services/file-operation-handler.backend.service.d.ts +18 -0
- package/dist/esm/files/services/file-operation-handler.backend.service.d.ts.map +1 -1
- package/dist/esm/files/services/file-operation-handler.backend.service.js +36 -28
- package/dist/esm/files/services/file-operation-handler.backend.service.js.map +1 -1
- package/dist/esm/files/services/file-upload-grant.backend.service.d.ts +163 -0
- package/dist/esm/files/services/file-upload-grant.backend.service.d.ts.map +1 -0
- package/dist/esm/files/services/file-upload-grant.backend.service.js +442 -0
- package/dist/esm/files/services/file-upload-grant.backend.service.js.map +1 -0
- package/dist/esm/files/services/files.backend.service.d.ts +19 -0
- package/dist/esm/files/services/files.backend.service.d.ts.map +1 -1
- package/dist/esm/files/services/files.backend.service.js +78 -15
- package/dist/esm/files/services/files.backend.service.js.map +1 -1
- package/dist/esm/files/utils/file-uploader.utils.d.ts.map +1 -1
- package/dist/esm/files/utils/file-uploader.utils.js +12 -0
- package/dist/esm/files/utils/file-uploader.utils.js.map +1 -1
- package/dist/esm/flows-actors/a2a/services/a2a-task-cancellation.backend.service.js +5 -5
- package/dist/esm/flows-actors/a2a/services/a2a-task-cancellation.backend.service.js.map +1 -1
- package/dist/esm/flows-actors/services/agents.backend.service.d.ts +79 -0
- package/dist/esm/flows-actors/services/agents.backend.service.d.ts.map +1 -1
- package/dist/esm/flows-actors/services/agents.backend.service.js +319 -42
- package/dist/esm/flows-actors/services/agents.backend.service.js.map +1 -1
- package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.d.ts +151 -41
- package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.d.ts.map +1 -1
- package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.js +300 -139
- package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.js.map +1 -1
- package/dist/esm/index.d.ts +4 -1
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +14 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/inject/models/container.d.ts.map +1 -1
- package/dist/esm/inject/models/container.js +4 -0
- package/dist/esm/inject/models/container.js.map +1 -1
- package/dist/esm/inject/models/service-types.d.ts +3 -0
- package/dist/esm/inject/models/service-types.d.ts.map +1 -1
- package/dist/esm/inject/models/service-types.js +2 -0
- package/dist/esm/inject/models/service-types.js.map +1 -1
- package/dist/esm/mcp/controllers/mcp.controller.d.ts.map +1 -1
- package/dist/esm/mcp/controllers/mcp.controller.js +12 -4
- package/dist/esm/mcp/controllers/mcp.controller.js.map +1 -1
- package/dist/esm/mcp/models/mcp-tool.backend.schemas.d.ts +34 -0
- package/dist/esm/mcp/models/mcp-tool.backend.schemas.d.ts.map +1 -1
- package/dist/esm/mcp/models/mcp-tool.backend.schemas.js +42 -0
- package/dist/esm/mcp/models/mcp-tool.backend.schemas.js.map +1 -1
- package/dist/esm/mcp/services/mcp-server.backend.service.d.ts +29 -1
- package/dist/esm/mcp/services/mcp-server.backend.service.d.ts.map +1 -1
- package/dist/esm/mcp/services/mcp-server.backend.service.js +131 -3
- package/dist/esm/mcp/services/mcp-server.backend.service.js.map +1 -1
- package/dist/esm/mcp/services/mcp-tool-adapter.backend.service.d.ts +64 -2
- package/dist/esm/mcp/services/mcp-tool-adapter.backend.service.d.ts.map +1 -1
- package/dist/esm/mcp/services/mcp-tool-adapter.backend.service.js +130 -6
- package/dist/esm/mcp/services/mcp-tool-adapter.backend.service.js.map +1 -1
- package/dist/esm/notifications/services/notifications-dispatcher.backend.service.d.ts +9 -0
- package/dist/esm/notifications/services/notifications-dispatcher.backend.service.d.ts.map +1 -1
- package/dist/esm/notifications/services/notifications-dispatcher.backend.service.js +11 -36
- package/dist/esm/notifications/services/notifications-dispatcher.backend.service.js.map +1 -1
- package/dist/esm/notifications/webhooks/outbound/batches/m2m-webhook-delivery.batch.backend.service.d.ts.map +1 -1
- package/dist/esm/notifications/webhooks/outbound/batches/m2m-webhook-delivery.batch.backend.service.js +9 -7
- package/dist/esm/notifications/webhooks/outbound/batches/m2m-webhook-delivery.batch.backend.service.js.map +1 -1
- package/dist/esm/notifications/webhooks/outbound/batches/m2m-webhook-delivery.batch.utils.d.ts +5 -5
- package/dist/esm/notifications/webhooks/outbound/batches/m2m-webhook-delivery.batch.utils.d.ts.map +1 -1
- package/dist/esm/notifications/webhooks/outbound/batches/m2m-webhook-delivery.batch.utils.js +14 -13
- package/dist/esm/notifications/webhooks/outbound/batches/m2m-webhook-delivery.batch.utils.js.map +1 -1
- package/dist/esm/notifications/webhooks/outbound/m2m-webhook-signed-request.backend.utils.d.ts +2 -1
- package/dist/esm/notifications/webhooks/outbound/m2m-webhook-signed-request.backend.utils.d.ts.map +1 -1
- package/dist/esm/notifications/webhooks/outbound/m2m-webhook-signed-request.backend.utils.js +2 -2
- package/dist/esm/notifications/webhooks/outbound/m2m-webhook-signed-request.backend.utils.js.map +1 -1
- package/dist/esm/notifications/webhooks/outbound/services/webhook-config-test-endpoint.custom-impl.backend.service.d.ts.map +1 -1
- package/dist/esm/notifications/webhooks/outbound/services/webhook-config-test-endpoint.custom-impl.backend.service.js +9 -7
- package/dist/esm/notifications/webhooks/outbound/services/webhook-config-test-endpoint.custom-impl.backend.service.js.map +1 -1
- package/dist/esm/organizations/services/organization-unit-custom-implementation.backend.service.d.ts.map +1 -1
- package/dist/esm/organizations/services/organization-unit-custom-implementation.backend.service.js +4 -1
- package/dist/esm/organizations/services/organization-unit-custom-implementation.backend.service.js.map +1 -1
- package/dist/esm/requests/service/websocket.service.d.ts.map +1 -1
- package/dist/esm/requests/service/websocket.service.js +56 -7
- package/dist/esm/requests/service/websocket.service.js.map +1 -1
- package/dist/esm/resources/models/custom-service-implementations.backend.definition.d.ts.map +1 -1
- package/dist/esm/resources/models/custom-service-implementations.backend.definition.js +2 -0
- package/dist/esm/resources/models/custom-service-implementations.backend.definition.js.map +1 -1
- package/dist/esm/resources/services/resource-id.backend.service.js +3 -3
- package/dist/esm/resources/services/resource-id.backend.service.js.map +1 -1
- package/dist/esm/resources/services/resources-registry.backend.service.js +1 -1
- package/dist/esm/resources/services/resources-registry.backend.service.js.map +1 -1
- package/dist/esm/runtime/services/execution-context-creator.backend.service.d.ts.map +1 -1
- package/dist/esm/runtime/services/execution-context-creator.backend.service.js +13 -7
- package/dist/esm/runtime/services/execution-context-creator.backend.service.js.map +1 -1
- package/dist/esm/runtime/services/start-application.backend.service.d.ts +28 -0
- package/dist/esm/runtime/services/start-application.backend.service.d.ts.map +1 -1
- package/dist/esm/runtime/services/start-application.backend.service.js +82 -0
- package/dist/esm/runtime/services/start-application.backend.service.js.map +1 -1
- package/dist/esm/security/authentications/models/jwt.backend.schemas.d.ts +3 -23
- package/dist/esm/security/authentications/models/jwt.backend.schemas.d.ts.map +1 -1
- package/dist/esm/security/authentications/models/jwt.backend.schemas.js +20 -45
- package/dist/esm/security/authentications/models/jwt.backend.schemas.js.map +1 -1
- package/dist/esm/security/authentications/services/auth-methods/auth-method-management.backend.service.d.ts +9 -1
- package/dist/esm/security/authentications/services/auth-methods/auth-method-management.backend.service.d.ts.map +1 -1
- package/dist/esm/security/authentications/services/auth-methods/auth-method-management.backend.service.js +9 -1
- package/dist/esm/security/authentications/services/auth-methods/auth-method-management.backend.service.js.map +1 -1
- package/dist/esm/security/authentications/services/auth-methods/auth-mfa.backend.service.d.ts.map +1 -1
- package/dist/esm/security/authentications/services/auth-methods/auth-mfa.backend.service.js +5 -3
- package/dist/esm/security/authentications/services/auth-methods/auth-mfa.backend.service.js.map +1 -1
- package/dist/esm/security/authentications/services/auth-token-issuer.backend.service.d.ts +25 -1
- package/dist/esm/security/authentications/services/auth-token-issuer.backend.service.d.ts.map +1 -1
- package/dist/esm/security/authentications/services/auth-token-issuer.backend.service.js +55 -4
- package/dist/esm/security/authentications/services/auth-token-issuer.backend.service.js.map +1 -1
- package/dist/esm/security/authorizations/initiator-organization-confinement.backend.d.ts.map +1 -1
- package/dist/esm/security/authorizations/initiator-organization-confinement.backend.js +24 -1
- package/dist/esm/security/authorizations/initiator-organization-confinement.backend.js.map +1 -1
- package/dist/esm/security/authorizations/privileged-access-review.backend.utils.d.ts +117 -0
- package/dist/esm/security/authorizations/privileged-access-review.backend.utils.d.ts.map +1 -0
- package/dist/esm/security/authorizations/privileged-access-review.backend.utils.js +104 -0
- package/dist/esm/security/authorizations/privileged-access-review.backend.utils.js.map +1 -0
- package/dist/esm/security/authorizations/services/authorizations.backend.service.d.ts +101 -6
- package/dist/esm/security/authorizations/services/authorizations.backend.service.d.ts.map +1 -1
- package/dist/esm/security/authorizations/services/authorizations.backend.service.js +210 -30
- package/dist/esm/security/authorizations/services/authorizations.backend.service.js.map +1 -1
- package/dist/esm/security/consumable-tokens/batches/consumable-tokens-cleanup.batch.backend.service.d.ts +18 -1
- package/dist/esm/security/consumable-tokens/batches/consumable-tokens-cleanup.batch.backend.service.d.ts.map +1 -1
- package/dist/esm/security/consumable-tokens/batches/consumable-tokens-cleanup.batch.backend.service.js +110 -74
- package/dist/esm/security/consumable-tokens/batches/consumable-tokens-cleanup.batch.backend.service.js.map +1 -1
- package/dist/esm/security/consumable-tokens/consumable-token-models.exports.d.ts +22 -0
- package/dist/esm/security/consumable-tokens/consumable-token-models.exports.d.ts.map +1 -0
- package/dist/esm/security/consumable-tokens/consumable-token-models.exports.js +22 -0
- package/dist/esm/security/consumable-tokens/consumable-token-models.exports.js.map +1 -0
- package/dist/esm/security/consumable-tokens/models/consumable-tokens.backend.resources-config.schemas.d.ts +17 -3
- package/dist/esm/security/consumable-tokens/models/consumable-tokens.backend.resources-config.schemas.d.ts.map +1 -1
- package/dist/esm/security/consumable-tokens/models/consumable-tokens.backend.resources-config.schemas.js +12 -0
- package/dist/esm/security/consumable-tokens/models/consumable-tokens.backend.resources-config.schemas.js.map +1 -1
- package/dist/esm/security/consumable-tokens/services/consumable-token.backend.service.d.ts +20 -0
- package/dist/esm/security/consumable-tokens/services/consumable-token.backend.service.d.ts.map +1 -1
- package/dist/esm/security/consumable-tokens/services/consumable-token.backend.service.js +58 -5
- package/dist/esm/security/consumable-tokens/services/consumable-token.backend.service.js.map +1 -1
- package/dist/esm/security/jwt/services/jwt.backend.service.d.ts.map +1 -1
- package/dist/esm/security/jwt/services/jwt.backend.service.js +1 -18
- package/dist/esm/security/jwt/services/jwt.backend.service.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +15 -9
- package/dist/esm/.builder.pid +0 -9
package/dist/esm/base-classes/services/services/services-registry-handler.backend.service.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"services-registry-handler.backend.service.js","sourceRoot":"","sources":["../../../../../../src/base-classes/services/services/services-registry-handler.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,kBAAkB,CAAC;AAC1B,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAOzD,OAAO,EAEL,qBAAqB,EACrB,gBAAgB,EAChB,4BAA4B,EAC5B,0BAA0B,EAC1B,+BAA+B,EAE/B,kBAAkB,EAClB,0BAA0B,EAC1B,kCAAkC,EAClC,SAAS,EACT,2BAA2B,EAC3B,4BAA4B,EAC5B,0BAA0B,EAC1B,uBAAuB,EAEvB,QAAQ,EACR,qBAAqB,EACrB,kBAAkB,EAClB,sBAAsB,EACtB,4BAA4B,EAC5B,yBAAyB,EACzB,iCAAi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B,EACnB,gBAAuC;QAGvC,0CAA0C;QAC1C,sBAAsB;QACtB,oBAAoB;QACpB,qBAAqB;QACrB,wCAAwC;QAExC,OAAO,WAAW,CAAC,CAAC,wBAAwB;IAC9C,CAAC;IAED;;OAEG;IACK,KAAK,CAAC,2BAA2B,CACvC,IAAS,EACT,gBAAuC;QAGvC,gDAAgD;QAChD,sBAAsB;QACtB,wBAAwB;QACxB,6BAA6B;QAC7B,0BAA0B;QAE1B,0BAA0B;IAC5B,CAAC;IAED,mCAAmC;IACnC,uBAAuB;IACvB,mCAAmC;IAEnC;;;;;;;OAOG;IACK,KAAK,CAAC,qBAAqB,CACjC,gBAAuC,EACvC,SAAc,EACd,aAAkB,EAClB,qBAAoD,EACpD,aAAuB;QAEvB,MAAM,4CAA4C,CAChD;YACE,sBAAsB,EAAE,IAAI,CAAC,sBAAsB;YACnD,iBAAiB,EAAE,IAAI,CAAC,iBAAiB;YACzC,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,QAAQ,EAAE,IAAI,CAAC,QAAQ;SACxB,EACD,gBAAgB,EAChB,SAAS,EACT,aAAa,EACb,qBAAqB,EACrB,aAAa,CACd,CAAC;IACJ,CAAC","sourcesContent":["import 'reflect-metadata';\nimport { randomUUID } from 'node:crypto';\nimport { injectable, inject, optional } from 'inversify';\nimport type {\n ResourceConfiguration,\n ResourceConfiguration_Operation,\n ResourceConfiguration_OperationPath,\n ResourceDataSubjectPolicy,\n} from '@wildo-ai/saas-models';\nimport {\n ResourceType,\n CoreResourceOperation,\n CoreResourceType,\n readBulkOperationSelectorIds,\n stripBulkOperationSelector,\n composeDefaultOperationResponse,\n DEFAULT_PERSISTENCE_ADAPTER,\n PersistenceAdapter,\n selectByPersistenceAdapter,\n ResourcesConfig_OperationPathUtils,\n ErrorType,\n ErrorCustomMessageReference,\n ResourceOperationVariantType,\n ResourceOperationRiskLevel,\n ResourceOperationsUtils,\n createOrUpdateMandatoryDiscardFields,\n DataMode,\n OPERATION_VARIANT_KEY,\n ChildLifecycleMode,\n ChildLifecycleStrategy,\n buildImpersonalizeScrubPatch,\n SubjectErasureDisposition,\n classifySubjectErasureDisposition,\n isBlockingSubjectErasureDisposition,\n SubjectExportPurpose,\n SubjectExportEdgeDisposition,\n SubjectExportFieldScope,\n SubjectExportFieldDecisionBasis,\n compileSubjectExportFieldDecisions,\n enumerateSubjectExportRelationshipTraversals,\n isIncludedSubjectExportEdgeDisposition,\n ResourceSystemAccessMode,\n ResourceOperation_ServiceRuntimeMode,\n ResourceConfiguration_OperationVariant_CustomImplementation_FunctionParameters,\n ResourceSerializationUtils,\n ExecutionContext_ExecutionType,\n CoreConsumableTokenTypes,\n isWildoBackendError,\n Resources_SharedUtils,\n type PersistenceAdapterType,\n ResourceRelationshipBulkAction,\n type ResourceRelationshipBulkActionRequest,\n ResourceRelationshipBulkActionRequestSchema,\n type ResourceRelationshipBulkActionResult,\n type ResourceRelationshipBulkOperationSelector,\n ResourceRelationshipBulkClearOperationRequestSchema,\n type ResourceRelationshipBulkClearOperationRequest,\n ResourceRelationshipBulkCreateOperationRequestSchema,\n type ResourceRelationshipBulkCreateOperationRequest,\n ResourceRelationshipBulkLinkOperationRequestSchema,\n type ResourceRelationshipBulkLinkOperationRequest,\n ResourceRelationshipBulkReplaceOperationRequestSchema,\n type ResourceRelationshipBulkReplaceOperationRequest,\n ResourceRelationshipBulkSetOperationRequestSchema,\n type ResourceRelationshipBulkSetOperationRequest,\n ResourceRelationshipBulkUnlinkOperationRequestSchema,\n type ResourceRelationshipBulkUnlinkOperationRequest,\n ResourceGeneratedOperationKind,\n ResourceDataSubjectKind,\n} from '@wildo-ai/saas-models';\nimport { EnumLikeType, getZodObjectShape, isAuditEvidenceField, isZodObject, unwrapSchema } from '@wildo-ai/zod-decorators';\nimport { isWriteIntegrityExemptExecution } from '~wildo-backend-lib/base-classes/services/repositories/resource-write-integrity.backend';\nimport { collectCandidateReadOnlyFields, filterChangedReadOnlyFields, stringifyPersistedValueForCompare } from '~wildo-backend-lib/base-classes/services/services/read-only-field-change.backend.utils';\nimport { AuditLogsBackendService } from '~wildo-backend-lib/compliance/audit-trails/services/audit-logs.backend.service';\nimport {\n resolveResourceOperationAuditDecision,\n resolveResourceOperationFieldEffect,\n} from '~wildo-backend-lib/base-classes/services/services/resource-operation-audit-emission.backend.utils';\nimport { resolveServerInjectedFieldAllowList } from '~wildo-backend-lib/base-classes/services/services/resource-operation-server-injected-fields.backend.utils';\nimport { buildRetentionMarkerStampPatch } from '~wildo-backend-lib/compliance/privacy/retention-hide-predicate.backend';\nimport { SAAS_SERVICE_TYPES } from '~wildo-backend-lib/inject/models/service-types';\nimport type { SubjectSessionRevocationBackendService } from '~wildo-backend-lib/compliance/privacy/services/subject-session-revocation.backend.service';\nimport { ExecutionContext } from '~wildo-backend-lib/runtime/models/execution-context.backend.schemas';\nimport { RepositoriesRegistryHandlerBackendService } from '~wildo-backend-lib/base-classes/services/repositories/repositories-registry-handler.backend.service';\nimport { ResourceOperationHelperBackendService } from '~wildo-backend-lib/base-classes/services/resource-operations-helper.backend.service';\nimport { RepositoryOptions, ServiceOptions, IdOrIdsOrFilterType } from '~wildo-backend-lib/base-classes/models/repositories.backend.schemas';\nimport {\n Resources_PaginationRequest,\n Resources_PaginatedResult,\n extractFunctionContextNeeds,\n ResourceConfiguration_FunctionWithContextNeeds,\n ResourcesConfigOperationsDtosBuilderUtils,\n} from '@wildo-ai/saas-models';\nimport { LoggerService } from '~wildo-backend-lib/monitoring/logger/services/logger.service';\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 { z } from 'zod';\nimport { PlatformMutualizedHandlerBackendService } from '~wildo-backend-lib/requests/service/platform-mutualized-handler.backend.service';\nimport { ResourcesRegistryBackendService } from '~wildo-backend-lib/resources/services/resources-registry.backend.service';\nimport { ExternalApiHandlerBackendService } from '~wildo-backend-lib/external-providers/services/external-api-handler.backend.service';\nimport {\n ResourceOperationCustomImplementationRegistryBackendService,\n type ResourceOperationCustomImplementationRegistration,\n} from './resource-operation-custom-implementation-registry.backend.service';\nimport {\n createResourceWritePersistenceRequest,\n resolveResourceOperationTransactionPersistenceContract,\n ResourceWriteFileParticipation,\n type ResourceOperationTransactionPersistenceContract,\n} from './resource-operation-transaction-persistence.backend.utils';\nimport {\n ResourceCustomServiceImplementationTransactionalCoreConflictAction,\n type ResourceCustomServiceImplementationTransactionalCoreConflictResolution,\n type ResourceCustomServiceImplementationTransactionalCoreConflictResolver,\n} from './resource-operation-custom-implementation.factory.backend';\nimport { ServerlessServicesHandlerBackendService } from '~wildo-backend-lib/requests/service/serverless-services-handler.backend.service';\nimport { ResourceOperation_CustomServiceImplementationMode } from '@wildo-ai/saas-models';\nimport { ResourceOperation_CustomImplementation_Utils } from './resource-operation-custom-implementation-base.backend.service';\nimport {\n NotificationDispatcherService,\n type NotificationDispatchOptions,\n} from '~wildo-backend-lib/notifications/services/notifications-dispatcher.backend.service';\nimport {\n type ComputationContext,\n ComputationContextFailureMode,\n ResourcePopulationBackendService,\n} from '~wildo-backend-lib/resources/services/resource-population.backend.service';\nimport { VirtualFieldsBackendService } from '~wildo-backend-lib/resources/services/virtual-fields.backend.service';\nimport { MongoDBService } from '~wildo-backend-lib/databases/services/mongodb.service';\nimport { PostgreSQLDatabaseBackendService } from '~wildo-backend-lib/databases/services/postgresql-database.backend.service';\nimport {\n resolveDefaultPersistenceAdapter,\n resolvePersistenceAdapterForConfiguration,\n} from '~wildo-backend-lib/databases/models/resolve-persistence-adapter.backend.utils';\nimport type {\n ResourcePersistenceUnitOfWorkBackendService,\n} from '~wildo-backend-lib/databases/services/resource-persistence-unit-of-work.backend.service';\nimport {\n registerTransactionPostCommitEffect,\n type IDatabaseService,\n type TransactionContext,\n} from '~wildo-backend-lib/databases/models/transaction.shared.schemas';\nimport { FilterQuery } from 'mongoose';\nimport type { ClientSession } from 'mongoose';\nimport { ResourceRelationship, ResourceRelationshipCardinality, ResourceParentResourceRequirement, getContextAddressedCompositionSingletonRelationshipCandidates, isOneToOneCardinality, isArrayCardinality, getChildDirectionRelationships, RelationshipNature, PRIMARY_SCOPE_TO_FIELD_IDENTIFIER } from '@wildo-ai/saas-models';\nimport { ResourcesConfigNamingUtils } from '@wildo-ai/saas-models';\nimport type { TokenGenerationConfig } from '@wildo-ai/saas-models';\nimport type {\n SubjectErasureEdgeOutcome,\n SubjectErasureReport,\n SubjectExportBundle,\n SubjectExportEdgeOutcome,\n SubjectExportReport,\n SubjectExportResourceSlice,\n} from '@wildo-ai/saas-models';\nimport { FileOperationHandlerBackendService } from '~wildo-backend-lib/files/services/file-operation-handler.backend.service';\nimport { FileFieldDetectionBackendService, type FileFieldMetadata } from '~wildo-backend-lib/files/services/file-field-detection.backend.service';\nimport { hasExplicitCanonicalFieldMutation } from '~wildo-backend-lib/files/utils/file-field-schema-path.backend.utils';\nimport type { RagSourceFieldDetectionBackendService } from '~wildo-backend-lib/files/services/rag-source-field-detection.backend.service';\nimport type { RagChunkStoreBackendService } from '~wildo-backend-lib/rag/services/rag-chunk-store.backend.service';\nimport {\n scheduleRagChunkRemovalForDeletedRows,\n scheduleRagChunkRemovalForFields,\n type RagChunkRemovalContext,\n} from '~wildo-backend-lib/rag/utils/rag-chunk-removal.backend.utils';\nimport type { RagIngestionBackendService } from '~wildo-backend-lib/rag/services/rag-ingestion.backend.service';\nimport {\n isUndeclaredCustomOperationIdentifier,\n RAG_INGESTION_WRITE_OPERATIONS,\n reportRagIngestionSkippedUndeclaredCustomOperation,\n runRagIngestionForServiceWrite,\n type RagIngestionTriggerContext,\n} from '~wildo-backend-lib/rag/utils/rag-ingestion-trigger.backend.utils';\nimport { ExecutionContextCreatorBackendService } from '~wildo-backend-lib/runtime/services/execution-context-creator.backend.service';\nimport { QueueBackendService } from '~wildo-backend-lib/queue/queue.backend.service';\nimport { FeatureGateBackendService } from '~wildo-backend-lib/features/services/feature-gate.backend.service';\nimport {\n ConsumableTokenBackendService,\n} from '~wildo-backend-lib/security/consumable-tokens/services/consumable-token.backend.service';\nimport { AppConfigurationService } from '~wildo-backend-lib/config/services/app-configuration.backend.service';\nimport type { TokenGenerationResult } from '~wildo-backend-lib/security/consumable-tokens/services/consumable-token.backend.service';\nimport { GuidanceTriggerEvaluatorBackendService } from '~wildo-backend-lib/guidance/services/guidance-trigger-evaluator.backend.service';\nimport { MilestoneEvaluatorBackendService } from '~wildo-backend-lib/guidance/services/milestone-evaluator.backend.service';\nimport { LifecycleEvaluatorBackendService } from '~wildo-backend-lib/guidance/services/lifecycle-evaluator.backend.service';\nimport type { SAMLMetadataBackendService } from '~wildo-backend-lib/security/authentications/services/auth-methods/saml-metadata.backend.service';\nimport type { SystemAccessBackendService } from '~wildo-backend-lib/base-classes/services/services/system-access.backend.service';\nimport { PdfGenerationOrchestratorBackendService, PdfGenerationRenderPhase, type GeneratePdfForFieldResult } from '~wildo-backend-lib/pdf-templates/services/pdf-generation-orchestrator.backend.service';\nimport { getConfiguredPrimaryLanguage } from '~wildo-backend-lib/config/services/app-configuration.backend.utils';\nimport { FileGenerationSource } from '@wildo-ai/zod-decorators';\nimport { isUnconfinedScopeRootDirectoryRead } from '~wildo-backend-lib/security/authorizations/scope-root-collection-confinement.backend';\n\ninterface PostOperationNotificationDispatcher {\n dispatchResourceRoomNotifications<TResourceConfigOperation extends ResourceConfiguration_Operation<any, any, any>>(\n executionContext: ExecutionContext<TResourceConfigOperation>,\n functionParameters: ResourceConfiguration_OperationVariant_CustomImplementation_FunctionParameters,\n ): Promise<void>;\n dispatchConfiguredNotifications<TResourceConfigOperation extends ResourceConfiguration_Operation<any, any, any>>(\n executionContext: ExecutionContext<TResourceConfigOperation>,\n functionParameters: ResourceConfiguration_OperationVariant_CustomImplementation_FunctionParameters,\n options?: NotificationDispatchOptions,\n ): Promise<void>;\n}\n\ninterface PostOperationNotificationDispatchDeps {\n notificationDispatcher: PostOperationNotificationDispatcher;\n populationService: Pick<ResourcePopulationBackendService, 'analyzeContextNeeds' | 'fetchComputationContext'>;\n logger: Pick<LoggerService, 'error'>;\n logDebug: (message: string, context?: Record<string, unknown>) => void;\n}\n\n/**\n * Resolution outcome for a context-addressed singleton operation (a child resource\n * that is a singleton per parent scope, e.g. one `userProgressionState` per user,\n * addressed by the parent FK rather than by its own `_id`).\n *\n * Discriminated by `kind`:\n * - `resolved` — the singleton row exists; the operation is addressed by its real\n * `_id` (`operationId`/`mutationId`) and `currentObject` is the fetched row.\n * - `absent-read-by-scope` — a READ found no row yet. Rather than fail the read as\n * not-found at this (target-resolution) layer, the read is addressed by the\n * parent-scope `selector` so the core read returns `null` and any registered\n * POSTFIX materialization hook (e.g. scoped progression/guidance state) can\n * create-and-return the row. If no hook is registered, the operation layer emits\n * `CONTROLLER_RESOURCE_NOT_FOUND` after the null read (same HTTP outcome, correct\n * layer). Only ever produced for READ — UPDATE/DELETE on an absent singleton still\n * fail closed with not-found, because a mutation cannot target a non-existent row.\n */\ntype ContextAddressedSingletonOperationTarget =\n | {\n addressedBy: 'parent-context';\n kind: 'resolved';\n selector: Record<string, string>;\n currentObject: Record<string, unknown>;\n operationId: string;\n mutationId: string;\n relationship: ResourceRelationship;\n }\n | {\n addressedBy: 'parent-context';\n kind: 'absent-read-by-scope';\n selector: Record<string, string>;\n relationship: ResourceRelationship;\n };\n\ntype ContextAddressedAssociationOperationTarget = {\n addressedBy: 'association-complete-context';\n selector: Record<string, string>;\n currentObject: Record<string, unknown>;\n operationId: string;\n mutationId: string;\n relationships: ResourceRelationship[];\n};\n\ntype GeneratedPdfMaterializationRecord = GeneratePdfForFieldResult & {\n resourceType: ResourceType;\n fieldName: string;\n rowIndex?: number;\n};\n\n/**\n * Snapshot-isolated values owned by the successful core attempt and consumed\n * only after its transaction commits.\n *\n * The wrapper is frozen when registered. For a deferred transaction effect,\n * arrays and plain DTO records are also copied recursively so code that regains\n * control before the root commit cannot rewrite notification conditions,\n * recipients, or template context. Opaque contract values retain their runtime\n * type and identity, matching the transaction-attempt cloning contract.\n */\ninterface FrameworkManagedPostCommitPayload {\n readonly currentState: any;\n readonly inputData: any;\n readonly transactionallyPreparedTokenGenerationResult: TokenGenerationResult | null;\n readonly transactionalCoreConflictReconciled: boolean;\n}\n\ninterface FrameworkManagedPostCommitExecution {\n readonly payload: FrameworkManagedPostCommitPayload;\n readonly executionContext: ExecutionContext<any>;\n readonly operation: ResourceConfiguration_Operation<any, any, any>;\n readonly resolvedOperation: ResourceConfiguration_Operation<any, any, any>;\n readonly operationPath: ResourceConfiguration_OperationPath<any, any>;\n /**\n * The row as it stood BEFORE the write, for the audit event's before/after evidence.\n *\n * Carried on the EXECUTION rather than the PAYLOAD deliberately. The payload is snapshot-cloned\n * when a transaction defers it, to stop code that regains control before commit from rewriting\n * notification config — a protection the pre-image does not need (it is read-only here and never\n * re-enters the operation). Putting it on the execution also avoids threading a new field through\n * `executeTransactionalCoreAttempt`, since both scheduling sites run the SAME closure built in\n * `doOperation`, where the pre-image is already in scope.\n *\n * `undefined` for CREATE (nothing existed) and for bulk writes (the framework fetches a pre-image\n * only when exactly one id is selected).\n */\n readonly preOperationState?: unknown;\n}\n\ninterface FrameworkManagedPostCommitScheduling {\n readonly registeredByCoreTransaction: boolean;\n readonly transaction: RepositoryOptions['transaction'] | undefined;\n readonly operationPath: ResourceConfiguration_OperationPath<any, any>;\n readonly occurrenceId: string;\n readonly payload: FrameworkManagedPostCommitPayload;\n readonly execute: (payload: FrameworkManagedPostCommitPayload) => Promise<void>;\n}\n\ninterface ResourceOperationCorePhaseResult {\n readonly state: any;\n readonly inputData: any;\n readonly terminalCustomImplUtils: ResourceOperation_CustomImplementation_Utils;\n}\n\ninterface ResourceOperationTransactionalCoreAttemptResult extends ResourceOperationCorePhaseResult {\n readonly tokenGenerationResult: TokenGenerationResult | null;\n readonly consumedIncomingToken: boolean;\n readonly transformedState: unknown;\n}\n\ninterface ResourceOperationReconciledCoreResult extends ResourceOperationCorePhaseResult {\n readonly tokenGenerationResult: TokenGenerationResult | null;\n}\n\ninterface ResourceOperationCoreBoundaryResult extends ResourceOperationCorePhaseResult {\n readonly transactionalCoreConflictReconciled: boolean;\n readonly transactionallyPreparedTokenGenerationResult: TokenGenerationResult | null;\n readonly frameworkPostCommitRegisteredTransactionally: boolean;\n readonly consumableTokenConsumedTransactionally: boolean;\n readonly transactionallyPreparedOutput?: Readonly<{ value: unknown }>;\n}\n\ninterface ResourceOperationTransactionalCoreBoundaryExecution {\n readonly persistenceContract: ResourceOperationTransactionPersistenceContract;\n readonly baseOptions: ServiceOptions | undefined;\n readonly requiresRootOwnership: boolean;\n readonly originalCoreInput: unknown;\n readonly executionContext: ExecutionContext<any>;\n readonly operation: ResourceConfiguration_Operation<any, any, any>;\n readonly customImplUtils: ResourceOperation_CustomImplementation_Utils;\n readonly conflictResolvers: readonly ResourceCustomServiceImplementationTransactionalCoreConflictResolver[];\n readonly executeAttempt: (optionsWithTransaction: ServiceOptions) => Promise<ResourceOperationTransactionalCoreAttemptResult>;\n readonly resolveReconciledResult: (reconciledState: unknown) => Promise<ResourceOperationReconciledCoreResult>;\n}\n\ninterface ResourceOperationTransactionalCoreAttemptExecution {\n readonly optionsWithTransaction: ServiceOptions;\n readonly originalCoreInput: unknown;\n readonly executeCorePhase: (\n options: RepositoryOptions,\n inputData: any,\n ) => Promise<ResourceOperationCorePhaseResult>;\n readonly executionContext: ExecutionContext<any>;\n readonly dataMode: DataMode;\n readonly operation: ResourceConfiguration_Operation<any, any, any>;\n readonly resolvedOperation: ResourceConfiguration_Operation<any, any, any>;\n readonly tokenGeneration: TokenGenerationConfig | undefined;\n readonly operationPath: ResourceConfiguration_OperationPath<any, any>;\n readonly postCommitEffectOccurrenceId: string;\n readonly executePostCommit: (\n payload: FrameworkManagedPostCommitPayload,\n ) => Promise<void>;\n}\n\ninterface ConsumableTokenContextMarkRegistration {\n readonly transaction: NonNullable<RepositoryOptions['transaction']>;\n readonly operationPath: ResourceConfiguration_OperationPath<any, any>;\n readonly occurrenceId: string;\n readonly executionContext: ExecutionContext<any>;\n}\n\ninterface ResourceOperationCorePersistenceExecution {\n readonly operation: ResourceConfiguration_Operation<any, any, any>;\n readonly operationPath: ResourceConfiguration_OperationPath<any, any>;\n readonly coreOperation: CoreResourceOperation;\n readonly executionContext: ExecutionContext<any>;\n readonly target: IdOrIdsOrFilterType | undefined;\n readonly inputData: any;\n readonly currentObject: any;\n readonly options: RepositoryOptions | undefined;\n}\n\ninterface ResourceOperationCoreAttemptContext {\n readonly currentObject: any;\n readonly hookCurrentObject: any;\n readonly computationContext: ComputationContext;\n}\n\ninterface ResourceOperationCorePhaseExecution {\n readonly operation: ResourceConfiguration_Operation<any, any, any>;\n readonly operationPath: ResourceConfiguration_OperationPath<any, any>;\n readonly coreOperation: CoreResourceOperation;\n readonly resourceType: ResourceType;\n readonly executionContext: ExecutionContext<any>;\n readonly target: IdOrIdsOrFilterType | undefined;\n readonly inputData: any;\n readonly options: RepositoryOptions | undefined;\n readonly preflightContext: ResourceOperationCoreAttemptContext;\n readonly customImplUtils: ResourceOperation_CustomImplementation_Utils;\n readonly customImplRegistrations: ResourceOperationCustomImplementationRegistration[];\n readonly customImplPlaceholders: ReadonlySet<ResourceOperation_CustomServiceImplementationMode>;\n readonly refreshTransactionalContext: (\n inputData: any,\n options: RepositoryOptions,\n ) => Promise<ResourceOperationCoreAttemptContext>;\n}\n\ninterface ResourceOperationTerminalCustomPhaseExecution {\n readonly state: any;\n readonly target: IdOrIdsOrFilterType | undefined;\n readonly executionContext: ExecutionContext<any>;\n readonly terminalCustomImplUtils: ResourceOperation_CustomImplementation_Utils;\n readonly customImplRegistrations: ResourceOperationCustomImplementationRegistration[];\n readonly customImplPlaceholders: ReadonlySet<ResourceOperation_CustomServiceImplementationMode>;\n readonly transactionalCoreRequired: boolean;\n readonly transactionalCoreConflictReconciled: boolean;\n readonly operation: ResourceConfiguration_Operation<any, any, any>;\n}\n\n/**\n * Build a fresh input graph for one database-driver transaction attempt.\n *\n * MongoDB may invoke the transaction callback more than once after a\n * transient abort. Prefix hooks are allowed to return augmented DTO objects\n * and older hooks may still mutate plain input objects in place, so sharing\n * the previous callback's graph would make a retry observe server-injected\n * fields as if they had come from the caller. Only arrays and plain DTO\n * records are copied recursively; opaque contract values (for example Date,\n * Buffer, ObjectId, or File-like instances) retain their type and identity.\n */\nfunction cloneResourceTransactionAttemptInput<T>(value: T): T {\n const seen = new WeakMap<object, unknown>();\n\n const cloneDtoValue = (candidate: unknown): unknown => {\n if (candidate === null || typeof candidate !== 'object') {\n return candidate;\n }\n const cached = seen.get(candidate);\n if (cached !== undefined) return cached;\n\n if (Array.isArray(candidate)) {\n const clone: unknown[] = [];\n seen.set(candidate, clone);\n for (const item of candidate) {\n clone.push(cloneDtoValue(item));\n }\n return clone;\n }\n\n const prototype = Object.getPrototypeOf(candidate);\n if (prototype !== Object.prototype && prototype !== null) {\n return candidate;\n }\n\n const clone: Record<string, unknown> = Object.create(prototype);\n seen.set(candidate, clone);\n for (const [key, item] of Object.entries(candidate)) {\n clone[key] = cloneDtoValue(item);\n }\n return clone;\n };\n\n return cloneDtoValue(value) as T;\n}\n\n/**\n * Capture the successful operation values before a caller-owned transaction\n * returns control to its owner.\n *\n * A nested service call completes before the root transaction commits. Its\n * caller may legitimately reuse or mutate the input object, and may also\n * receive a result object sharing nested references with the persisted state.\n * Deferred effects must observe the values that actually participated in the\n * operation, not those later mutations.\n */\nfunction snapshotFrameworkManagedPostCommitPayload(\n payload: FrameworkManagedPostCommitPayload,\n): FrameworkManagedPostCommitPayload {\n return Object.freeze({\n currentState:\n cloneResourceTransactionAttemptInput(payload.currentState),\n inputData:\n cloneResourceTransactionAttemptInput(payload.inputData),\n transactionallyPreparedTokenGenerationResult:\n cloneResourceTransactionAttemptInput(\n payload.transactionallyPreparedTokenGenerationResult,\n ),\n transactionalCoreConflictReconciled:\n payload.transactionalCoreConflictReconciled,\n });\n}\n\n/**\n * Dependencies for {@link maybeProcessTokenGenerationForOperation} — just the token-mint seam, so the\n * config-declared gate is unit-testable with a mocked `processTokenGeneration`.\n */\nexport interface OperationTokenGenerationDeps {\n consumableTokenService: Pick<ConsumableTokenBackendService, 'processTokenGeneration'>;\n}\n\n/**\n * Honor a CREATE/RESEND-like operation's optional `tokenGeneration.condition` gate, then mint the token\n * ONLY when it passes. Extracted (like {@link dispatchPostOperationNotificationsBestEffort}) so the gate is\n * unit-testable in isolation, decoupled from the full operation-execution method.\n *\n * A POLYMORPHIC operation (org-member INVITE vs DIRECT-ADD) sets `condition` to\n * `({ currentObject }) => currentObject.status === INVITED`: the INVITE branch (INVITED) mints the single-use\n * accept token, while a DIRECT-ADD (founder / SSO-JIT / SCIM — status ACTIVE) mints NOTHING, so no live accept\n * token dangles on an already-ACTIVE row. Absent `condition` = always mint.\n *\n * @returns the mint result, or `null` when the condition gated it out (`processTokenGeneration` is not called).\n */\nexport async function maybeProcessTokenGenerationForOperation(\n deps: OperationTokenGenerationDeps,\n tokenGeneration: TokenGenerationConfig,\n currentState: Record<string, any>,\n tokenExecutionContext: {\n organizationId?: string;\n userId?: string;\n resourceType?: string;\n },\n transaction: TransactionContext,\n): Promise<TokenGenerationResult | null> {\n const shouldGenerate = !tokenGeneration.condition\n || tokenGeneration.condition({ currentObject: currentState });\n if (!shouldGenerate) return null;\n return deps.consumableTokenService.processTokenGeneration(\n tokenGeneration,\n currentState,\n tokenExecutionContext,\n transaction,\n );\n}\n\nexport async function dispatchPostOperationNotificationsBestEffort(\n deps: PostOperationNotificationDispatchDeps,\n executionContext: ExecutionContext<any>,\n inputData: any,\n currentResult: any,\n tokenGenerationResult?: TokenGenerationResult | null,\n previousState?: unknown,\n): Promise<void> {\n const resourceRoomParameters: Record<string, any> = {\n inputDto: inputData,\n currentObject: currentResult,\n initiatorIds: executionContext.initiatorIds,\n };\n\n try {\n // Resource-room notifications run first and on thinner inputs on purpose:\n // websocket coherence only needs authoritative object truth + initiator ids,\n // not the richer population/user context required by authored notifications.\n await deps.notificationDispatcher.dispatchResourceRoomNotifications(\n executionContext,\n resourceRoomParameters as any,\n );\n } catch (error) {\n deps.logger.error('Failed to dispatch resource-room notifications', {\n ...projectCaughtErrorLogFields(error),\n operationIdentifier: executionContext.operation.operationIdentifier,\n resourceIdentifier: executionContext.operation.resourceIdentifier,\n });\n }\n\n try {\n // Configured notifications are the richer second phase. They may depend on\n // populated object context, user context, and additional authored delivery\n // channels, so they intentionally run after the lightweight websocket pass.\n const resourceType = executionContext.operation.resourceIdentifier as ResourceType;\n const needs = deps.populationService.analyzeContextNeeds(resourceType);\n const computationContext = await deps.populationService.fetchComputationContext(\n resourceType,\n currentResult,\n needs,\n executionContext,\n );\n\n const functionParameters: Record<string, any> = {\n inputDto: inputData,\n currentObject: currentResult,\n // The pre-image (single-row UPDATE/DELETE only; undefined for CREATE and bulk). Carried for\n // the derived-badge recompute, which re-counts the scope a row moved OUT of on reassignment.\n // (A selector notifying a prior assignee could also use it, but selectors are not fed it yet.)\n previousObject: previousState,\n objectContext: computationContext.objectContext,\n initiatorUserContext: computationContext.userContext,\n initiatorIds: executionContext.initiatorIds,\n };\n\n if (tokenGenerationResult) {\n functionParameters.additionalContext = {\n ...(functionParameters.additionalContext || {}),\n tokenValue: tokenGenerationResult.tokenValue,\n };\n }\n\n await deps.notificationDispatcher.dispatchConfiguredNotifications(\n executionContext,\n functionParameters as any,\n tokenGenerationResult\n ? { emailSubmissionSourceId: tokenGenerationResult.tokenId }\n : undefined,\n );\n\n deps.logDebug('Configured notifications dispatched successfully');\n } catch (error) {\n deps.logger.error('Failed to dispatch configured notifications', {\n ...projectCaughtErrorLogFields(error),\n operationIdentifier: executionContext.operation.operationIdentifier,\n resourceIdentifier: executionContext.operation.resourceIdentifier,\n });\n }\n}\n\n@injectable()\nexport class ServicesRegistryHandlerBackendService {\n\n private readonly services: Map<ResourceType, ServiceResourceBackendService<any, any, any>>;\n private readonly serviceOperationsMap: Map<string, {\n operationPath: ResourceConfiguration_OperationPath<any, any>;\n service: ServiceResourceBackendService<any, any, any>;\n\n }>;\n\n private isInitialized = false;\n protected logDebug: (message: string, context?: Record<string, unknown>) => void;\n\n /**\n * Post-operation hooks: fire after a successful mutation on a resource type.\n * Key = resource type identifier, Value = array of hook callbacks.\n *\n * Failure semantics: errors thrown by post-hooks are caught and logged\n * (fire-and-forget). The mutation has already committed by the time the\n * hook runs; propagating here would report success at the API layer\n * then surface a crash to the caller, corrupting observable state.\n */\n private readonly postOperationHooks: Map<string, PostOperationHookCallback[]> = new Map();\n\n /**\n * Pre-operation hooks: fire BEFORE the core op on a resource type.\n * Key = resource type identifier, Value = array of hook callbacks.\n *\n * Failure semantics (plan §Phase-3 decision P3-A = A1): the FIRST hook\n * that throws short-circuits the dispatch loop and the error\n * propagates unchanged to the caller. This lets pre-hooks act as a\n * real enforcement point (rejecting e.g. a Level-B seed's\n * `beforeCreate` short-circuit the operation) without needing to\n * mutate data via a custom `prefixCoreOperations` impl.\n *\n * Mutation contract: pre-hooks are **observation + veto only** — they\n * do NOT transform the incoming `data`. Enforced by callback shape\n * (no return value). Data mutation stays inside\n * `prefixCoreOperations` of custom operation impls.\n */\n private readonly preOperationHooks: Map<string, PreOperationHookCallback[]> = new Map();\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.RepositoriesRegistryHandlerService) private readonly repositoriesRegistry: RepositoriesRegistryHandlerBackendService,\n @inject(SAAS_SERVICE_TYPES.Logger) private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.ErrorBuilderService) private readonly errorBuilder: ErrorBuilderBackendService,\n @inject(SAAS_SERVICE_TYPES.ResourceRegistryService) private readonly resourcesRegistry: ResourcesRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.ResourceOperationHelperService) private readonly repositoryHelper: ResourceOperationHelperBackendService,\n @inject(SAAS_SERVICE_TYPES.ResourceOperationCustomImplementationRegistryService) private readonly customImplRegistry: ResourceOperationCustomImplementationRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.ResourcePersistenceUnitOfWorkService) private readonly resourcePersistenceUnitOfWork: ResourcePersistenceUnitOfWorkBackendService,\n @inject(SAAS_SERVICE_TYPES.ExternalApiHandlerService) private readonly externalApiHandler: ExternalApiHandlerBackendService,\n @inject(SAAS_SERVICE_TYPES.PlatformMutualizedHandlerService) private readonly platformMutualizedHandler: PlatformMutualizedHandlerBackendService,\n @inject(SAAS_SERVICE_TYPES.ServerlessServicesHandlerService) private readonly serverlessServicesHandler: ServerlessServicesHandlerBackendService,\n @inject(SAAS_SERVICE_TYPES.NotificationDispatcherService) private readonly notificationDispatcher: NotificationDispatcherService,\n @inject(SAAS_SERVICE_TYPES.ResourcePopulationService) private readonly populationService: ResourcePopulationBackendService,\n @inject(SAAS_SERVICE_TYPES.VirtualFieldsService) private readonly virtualFieldsService: VirtualFieldsBackendService,\n @inject(SAAS_SERVICE_TYPES.MongoDBService) private readonly mongoDBService: MongoDBService,\n @inject(SAAS_SERVICE_TYPES.FileOperationHandlerService) private readonly fileOperationHandler: FileOperationHandlerBackendService,\n @inject(SAAS_SERVICE_TYPES.FileFieldDetectionService) private readonly fileFieldDetection: FileFieldDetectionBackendService,\n @inject(SAAS_SERVICE_TYPES.ExecutionContextCreatorBackendService) private readonly executionContextCreator: ExecutionContextCreatorBackendService,\n @inject(SAAS_SERVICE_TYPES.QueueBackendService) private readonly queueService: QueueBackendService,\n @inject(SAAS_SERVICE_TYPES.FeatureGateService) private readonly featureGate: FeatureGateBackendService,\n @inject(SAAS_SERVICE_TYPES.ConsumableTokenService) private readonly consumableTokenService: ConsumableTokenBackendService,\n @inject(SAAS_SERVICE_TYPES.AppConfigService) private readonly appConfigService: AppConfigurationService,\n @inject(SAAS_SERVICE_TYPES.PdfGenerationOrchestrator) private readonly pdfGenerationOrchestrator: PdfGenerationOrchestratorBackendService,\n @inject(SAAS_SERVICE_TYPES.GuidanceTriggerEvaluator) @optional() private readonly guidanceTriggerEvaluator?: GuidanceTriggerEvaluatorBackendService,\n @inject(SAAS_SERVICE_TYPES.MilestoneEvaluator) @optional() private readonly milestoneEvaluator?: MilestoneEvaluatorBackendService,\n @inject(SAAS_SERVICE_TYPES.LifecycleEvaluator) @optional() private readonly lifecycleEvaluator?: LifecycleEvaluatorBackendService,\n @inject(SAAS_SERVICE_TYPES.PostgreSQLDatabaseService) @optional() private readonly postgreSQLDatabaseService?: PostgreSQLDatabaseBackendService,\n @inject(SAAS_SERVICE_TYPES.SAMLMetadataService) @optional() private readonly samlMetadataService?: SAMLMetadataBackendService,\n // Late/optional: exposed to custom-impl utils as the SANCTIONED privileged-access\n // path (readAsSystem/…), so request-triggered ACL bypass is fail-closed + audited\n // instead of hand-rolled via the raw EC creator. `@optional()` keeps minimal test\n // containers constructing; no construction cycle (SystemAccess resolves THIS handler\n // lazily via the container, never in its constructor).\n @inject(SAAS_SERVICE_TYPES.SystemAccessService) @optional() private readonly systemAccessService?: SystemAccessBackendService,\n @inject(SAAS_SERVICE_TYPES.SubjectSessionRevocationService) @optional() private readonly subjectSessionRevocation?: SubjectSessionRevocationBackendService,\n // Late/optional, for the SAME reason as SystemAccess above: the post-commit lane records that a\n // HIGH/CRITICAL resource operation took effect. `@optional()` keeps minimal test containers\n // constructing, and there is no construction cycle — `AuditLogsBackendService` depends on the\n // REPOSITORIES registry, the audit dispatcher and the EC creator, never on this handler.\n // assurance-control: WILDO.AUDIT.SECURITY_EVENT — privileged resource actions are attributable.\n @inject(SAAS_SERVICE_TYPES.AuditLogsService) @optional() private readonly auditLogsService?: AuditLogsBackendService,\n // RAG derived-data tier (plan D3) — the removal-seam pair, exposed to the per-resource services\n // through `getRagChunkRemovalContext()` (like SystemAccess: `ServiceResourceBackendService`'s\n // constructor is invoked POSITIONALLY, so new dependencies land here, never there). `@optional()`\n // keeps minimal test containers constructing; a container missing either simply has no chunk\n // tier, and the seams no-op (the startup capability probe is what refuses a REAL application\n // whose RAG-source resources have no usable store).\n @inject(SAAS_SERVICE_TYPES.RagSourceFieldDetectionService) @optional() private readonly ragSourceFieldDetection?: RagSourceFieldDetectionBackendService,\n @inject(SAAS_SERVICE_TYPES.RagChunkStoreService) @optional() private readonly ragChunkStore?: RagChunkStoreBackendService,\n // RAG write path (plan §3.c) — the ingestion pipeline behind `getRagIngestionContext()`, the\n // removal pair's write-side sibling. Appended LAST and `@optional()` for the same positional-\n // construction reasons documented on the pair above.\n @inject(SAAS_SERVICE_TYPES.RagIngestionService) @optional() private readonly ragIngestion?: RagIngestionBackendService,\n ) {\n this.logger = logger;\n this.errorBuilder = errorBuilder;\n this.services = new Map();\n this.serviceOperationsMap = new Map();\n\n this.logDebug = this.logger.debugByType('ServicesRegistryHandler');\n this.logger.setDebugTypeLogging('ServicesRegistryHandler', false);\n\n this.logDebug('Services registry service created');\n }\n\n /** Exposes SAML metadata service for custom impl utils (DISCOVER_ENDPOINTS). */\n public getSamlMetadataService(): SAMLMetadataBackendService | undefined {\n return this.samlMetadataService;\n }\n\n /**\n * Exposes the system-access service to custom-impl utils as the sanctioned\n * privileged-access path (readAsSystem / listAsSystem / createAsSystem /\n * updateAsSystem — fail-closed + audited). Returns `undefined` only in minimal\n * containers that do not bind it; consumers degrade gracefully.\n */\n public getSystemAccessService(): SystemAccessBackendService | undefined {\n return this.systemAccessService;\n }\n\n /**\n * Exposes the session-revocation port to the per-resource services, whose scrub chokepoint ends an\n * erased person's sessions. A port rather than a direct dependency because `AuthTokenIssuer` already\n * injects THIS class — see {@link SubjectSessionRevocationBackendService}.\n *\n * Returns `undefined` only in a minimal container that does not bind it; the chokepoint then logs\n * loudly rather than silently reporting a terminated session that is still live.\n */\n public getSubjectSessionRevocationService(): SubjectSessionRevocationBackendService | undefined {\n return this.subjectSessionRevocation;\n }\n\n /**\n * The RAG chunk-removal context for the per-resource services' removal seams (row-delete cascade,\n * field impersonalization) — see `rag-chunk-removal.backend.utils.ts` for the ONE failure/\n * transaction discipline every seam shares.\n *\n * A getter on the registry rather than a `ServiceResourceBackendService` constructor parameter for\n * the same reason as `getSystemAccessService`: that constructor is invoked POSITIONALLY from\n * `createService` and from focused tests, so a new parameter shifts existing arguments silently.\n *\n * Returns `undefined` when either half is unbound (minimal test containers). The seams then no-op:\n * for a real application the startup capability probe — not the seams — is what refuses a\n * configuration whose RAG-source resources would have no reachable chunk store.\n */\n public getRagChunkRemovalContext(): RagChunkRemovalContext | undefined {\n if (!this.ragChunkStore || !this.ragSourceFieldDetection) {\n return undefined;\n }\n return {\n ragChunkStore: this.ragChunkStore,\n ragSourceFieldDetection: this.ragSourceFieldDetection,\n logger: this.logger,\n };\n }\n\n /**\n * The RAG ingestion context for the per-resource services' WRITE hook (the changed-field\n * re-index in the framework-managed post-commit chokepoint) — the write-side sibling of\n * {@link getRagChunkRemovalContext}, a getter for the same positional-construction reason.\n *\n * Returns `undefined` when any member is unbound (minimal test containers): the hook then no-ops,\n * and — as for removal — the startup capability probe is what refuses a REAL application whose\n * RAG-source resources would have no reachable chunk store.\n */\n public getRagIngestionContext(): RagIngestionTriggerContext | undefined {\n if (!this.ragIngestion || !this.ragSourceFieldDetection) {\n return undefined;\n }\n return {\n ragIngestion: this.ragIngestion,\n ragSourceFieldDetection: this.ragSourceFieldDetection,\n logger: this.logger,\n };\n }\n\n /**\n * Exposes the audit service to the per-resource services, which record that a HIGH/CRITICAL\n * operation took effect from their post-commit lane.\n *\n * Reached through this getter rather than added to `ServiceResourceBackendService`'s constructor:\n * that constructor is invoked POSITIONALLY from `createService` and from focused tests, so a new\n * parameter shifts existing arguments silently. Same reasoning as `getSystemAccessService`.\n *\n * Returns `undefined` only in minimal containers that do not bind it. That degrades to \"no audit\n * row\", which is the correct behaviour for a test container and is why the emission is guarded\n * rather than asserted — a missing binding must not break the operation.\n */\n public getAuditLogsService(): AuditLogsBackendService | undefined {\n return this.auditLogsService;\n }\n\n // ================================\n // Initialization Methods\n // ================================\n\n /**\n * @param serviceWhiteList - Optional resource types to limit service instantiation to. Mirrors\n * `ControllersRegistryHandlerBackendService.initialize`'s `controllerWhiteList`, and exists for\n * the same reason: a host may hold a registry far wider than the surface it serves.\n *\n * The dev companion is that host — its registry is the union of the observed application's\n * vocabulary, platform-core's and the engine's, and it serves generated routes for a handful of\n * workbench resources. Without this parameter it had to build a service for EVERY resource, and\n * `createService` throwing aborts the whole initialization: one resource whose service\n * implementation the host does not carry would fail its boot outright.\n *\n * Omitted means every resource, which is what an application backend wants and is the behaviour\n * this method has always had.\n */\n public async initializeServices(serviceWhiteList?: readonly string[]): Promise<void> {\n if (this.isInitialized) {\n this.logDebug('Registry already initialized, skipping...');\n return;\n }\n\n const allResourceTypes = this.resourcesRegistry.getResourceTypes();\n const resourceTypes = serviceWhiteList\n ? allResourceTypes.filter((resourceType) => serviceWhiteList.includes(resourceType))\n : allResourceTypes;\n\n if (serviceWhiteList) {\n this.logDebug('Applied service whitelist filter', {\n originalResourceCount: allResourceTypes.length,\n filteredResourceCount: resourceTypes.length,\n whitelistedResources: serviceWhiteList,\n });\n }\n\n this.logDebug('Initializing services', { resourceCount: resourceTypes.length, resourceTypes: resourceTypes });\n\n // First pass: Create all services\n for (const resourceType of resourceTypes) {\n try {\n await this.createService(resourceType);\n } catch (error) {\n\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL, undefined,\n { customMessageReference: ErrorCustomMessageReference.SERVICE_CREATION_FAILED, context: { resourceType, error: describeCaughtError(error) } } );\n }\n }\n\n this.buildOperationPathsMap();\n\n this.isInitialized = true;\n\n this.logDebug('Services registry initialization completed', {\n serviceCount: this.services.size,\n operationPathsCount: this.serviceOperationsMap.size\n });\n }\n\n private async createService( resourceType: ResourceType): Promise<void> {\n this.logDebug('Creating service', { resourceType });\n\n\n const service = ServiceResourceBackendService.createInstance(\n resourceType, this.logger, this.errorBuilder, this.repositoriesRegistry, this,\n this.resourcesRegistry, this.repositoryHelper, this.customImplRegistry,\n this.resourcePersistenceUnitOfWork,\n this.externalApiHandler, this.platformMutualizedHandler, this.serverlessServicesHandler,\n this.notificationDispatcher,\n this.populationService, this.virtualFieldsService, this.mongoDBService,\n this.fileOperationHandler, this.fileFieldDetection,\n this.executionContextCreator,\n this.queueService,\n this.featureGate,\n this.consumableTokenService,\n this.appConfigService,\n this.pdfGenerationOrchestrator,\n this.guidanceTriggerEvaluator,\n this.milestoneEvaluator,\n this.lifecycleEvaluator,\n this.postgreSQLDatabaseService,\n );\n\n this.services.set(resourceType, service);\n\n this.logDebug('Service created successfully', { resourceType });\n }\n\n private buildOperationPathsMap(): void {\n this.logDebug('Building operation paths map');\n\n let totalOperationPaths = 0;\n\n this.services.forEach((service, resourceType) => {\n const resourceConfiguration = this.resourcesRegistry.getResourceConfiguration(resourceType);\n\n if (!resourceConfiguration.operations) {\n return;\n }\n\n resourceConfiguration.operations.forEach(operation => {\n const operationPath = ResourcesConfig_OperationPathUtils.extractOperationPath(operation);\n const operationKey = ResourcesConfig_OperationPathUtils.createOperationPathKey(operationPath);\n\n this.serviceOperationsMap.set(operationKey, { service, operationPath });\n\n totalOperationPaths++;\n });\n });\n\n this.logDebug('Operation paths map built', { totalOperationPaths,operationKeys: Array.from(this.serviceOperationsMap.keys()).slice(0, 5) });\n }\n\n // ================================\n // Service Access Methods\n // ================================\n\n public getService<\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 ): ServiceResourceBackendService<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> | undefined {\n\n const service = this.services.get(resourceType);\n\n if (!service) {\n this.logDebug('Service not found', { resourceType });\n return undefined;\n }\n\n return service as ServiceResourceBackendService<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\n }\n\n public getServiceOrThrow<\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 ): ServiceResourceBackendService<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> {\n\n const service = this.getService<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>(resourceType);\n\n if (!service) {\n throw this.errorBuilder.buildError( ErrorType.NOT_FOUND, undefined, { customMessageReference: ErrorCustomMessageReference.SERVICE_NOT_FOUND, context: { resourceType } } );\n }\n\n return service;\n }\n\n // ================================\n // Execution Methods\n // ================================\n\n public async doByOperationPath<T = any>(\n operationPath: ResourceConfiguration_OperationPath<any, any>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: any,\n options?: RepositoryOptions\n ): Promise<T> {\n\n const operationKey = ResourcesConfig_OperationPathUtils.createOperationPathKey(operationPath);\n const operationInfo = this.serviceOperationsMap.get(operationKey);\n\n if (!operationInfo) {\n throw this.errorBuilder.buildError( ErrorType.NOT_FOUND, executionContext, { customMessageReference: ErrorCustomMessageReference.SERVICE_NOT_FOUND, context: { operationKey, operationPath } } );\n }\n\n this.logDebug('Executing operation by path', { operationPath, operationKey, id_or_ids_or_filter });\n\n return operationInfo.service.doByOperationPath( operationPath, executionContext, id_or_ids_or_filter, data, options );\n }\n\n\n public async doByExecutionContext<T = any>( executionContext: ExecutionContext<any>, data?: any, options?: RepositoryOptions ): Promise<T> {\n\n const operation = executionContext.operation;\n const resourceType = operation.resourceIdentifier as ResourceType;\n\n const service = this.getServiceOrThrow(resourceType);\n\n this.logDebug('Executing operation by execution context', { resourceType, operationIdentifier: operation.operationIdentifier });\n\n return service.doByExecutionContext(executionContext, data, options);\n }\n\n // ════════════════════════════════════════════════════════════════════\n // Convenience methods for programmatic resource operations.\n //\n // These pass the caller's executionContext through to doByOperationPath,\n // which resolves the target operation from the registry. If the caller's\n // executionContext.operation differs from the target operation (e.g., a\n // webhook handler calling create(SUBSCRIPTION, webhookCtx)), doOperation's\n // Correction Point 1 corrects the context before any pipeline logic runs.\n //\n // For proper sub-call depth tracking and cycle detection, callers should\n // use executionContextCreator.createForSubCall() before calling these\n // methods. Without it, operations are functionally correct but skip\n // depth/cycle safety checks.\n //\n // ────────────────────────────────────────────────────────────────────\n // ⚠️ WHAT THESE METHODS DO **NOT** APPLY: the operation's ROLE ACL.\n // ────────────────────────────────────────────────────────────────────\n //\n // Read this before using one of them to serve an EXTERNAL caller.\n //\n // A programmatic operation enters at the SERVICE tier. It therefore gets\n // the repository's contextual filter (tenancy, relationship-FK narrowing,\n // organization-unit narrowing, the anonymous guard and the retention\n // row-hide — all fail-closed, no opt-out) and the whole operation pipeline\n // (Zod validation, enabled conditions, custom impl, hooks). It does NOT\n // get `AuthorizationsBackendService.authorizeInController`, which is\n // mounted at the CONTROLLER tier and is the only place the operation's\n // declared `roles` are checked. A caller whose roles would be refused the\n // operation, but whose tenancy admits the row, succeeds here.\n //\n // That is DELIBERATE, and load-bearing rather than merely tolerated: this\n // surface's dominant population is authentication (registration, OAuth /\n // SAML identity-link resolution, credential lookup, token issuance), SCIM\n // provisioning, billing webhook routing, sweeps and feature resolution —\n // reads that run BEFORE a role-bearing principal exists. Applying the role\n // gate here would deny the reads that ESTABLISH identity. The service tier\n // is INSIDE the trust boundary; the boundary is the controller, because\n // that is where an untrusted principal names an operation.\n //\n // ⇒ If you are building a service-tier surface that takes a CALLER-SUPPLIED\n // query and returns row CONTENT to that caller on their own authority,\n // you are on the boundary and the role gate is yours to apply: call\n // `AuthorizationsBackendService.authorizeInProgrammaticSurface` ONCE PER\n // RESOURCE TYPE before you go looking (never per row — the gate is\n // row-independent, and a post-hoc per-row refusal re-creates the very\n // existence side channel a pre-filter closes). `RagRetrievalBackendService`\n // is the worked example; the full decision is on that method.\n // ════════════════════════════════════════════════════════════════════\n\n public async create<T = any>(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n data: any,\n options?: ServiceOptions\n ): Promise<T> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.CREATE);\n return service.doByOperationPath(operationPath, executionContext, undefined, data, options);\n }\n\n public async createMany<T = any>(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n data: any[],\n options?: ServiceOptions\n ): Promise<T[]> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.CREATE_MANY);\n return service.doByOperationPath(operationPath, executionContext, undefined, data, options);\n }\n\n public async read<T = any>(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n options?: ServiceOptions\n ): Promise<T | null> {\n const service = this.getServiceOrThrow(resourceType);\n // If variantKey is specified, get that variant's operationPath\n const operationPath : ResourceConfiguration_OperationPath<any, any> = options?.variantKey\n ? this.resourcesRegistry.getServiceOperationPath(resourceType, CoreResourceOperation.READ, options.variantKey)\n : this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.READ);\n return service.doByOperationPath(operationPath, executionContext, id_or_ids_or_filter, undefined, options);\n }\n\n public async update<T = any>(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n data: any,\n options?: ServiceOptions\n ): Promise<T | null> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.UPDATE);\n return service.doByOperationPath(operationPath, executionContext, id_or_ids_or_filter, data, options);\n }\n\n public async updateMany<T = any>(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n data: any,\n options?: ServiceOptions\n ): Promise<T[]> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.UPDATE_MANY);\n return service.doByOperationPath(operationPath, executionContext, id_or_ids_or_filter, data, options);\n }\n\n public async delete(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n resourceId: string,\n options?: ServiceOptions\n ): Promise<string> {\n if (typeof resourceId !== 'string' || resourceId.length === 0) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n operation: CoreResourceOperation.DELETE,\n reason: 'ServicesRegistryHandlerBackendService.delete() only accepts a single resource id. Use deleteMany() for ids or filters.',\n resourceType,\n },\n });\n }\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.DELETE);\n return service.doByOperationPath(operationPath, executionContext, resourceId, undefined, options);\n }\n\n public async deleteMany(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n options?: ServiceOptions\n ): Promise<string[]> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.DELETE_MANY);\n return service.doByOperationPath(operationPath, executionContext, id_or_ids_or_filter, undefined, options);\n }\n\n // ════════════════════════════════════════════════════════════════════\n // Custom operations\n // ════════════════════════════════════════════════════════════════════\n\n /**\n * Execute a custom operation on a resource through the full pipeline.\n * Routes through the same operation pipeline as HTTP-triggered custom operations\n * (Zod validation, RBAC, custom impl dispatch, post-operation hooks).\n *\n * @param resourceType - The resource type to execute the operation on\n * @param customOperationIdentifier - The custom operation name (e.g., 'top_up', 'consume')\n * @param executionContext - The execution context for RBAC and scoping\n * @param id_or_ids_or_filter - The resource ID to target (most custom ops require this)\n * @param data - The request payload for the custom operation\n * @param options - Optional service options\n */\n public async executeCustomOperation<T = any>(\n resourceType: ResourceType,\n customOperationIdentifier: string,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: any,\n options?: ServiceOptions,\n ): Promise<T> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath: ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, customOperationIdentifier);\n return service.doByOperationPath(operationPath, executionContext, id_or_ids_or_filter, data, options);\n }\n\n /**\n * Execute an explicit multi-target relationship action.\n *\n * This is the service-level implementation seam behind the planned operation\n * split:\n * - `UPDATE_MANY` stays a bulk patch of the main resource\n * - explicit relationship actions (`set`, `clear`, `create`, `link`,\n * `unlink`) are applied to a named relationship from the current resource's\n * perspective\n */\n public async applyRelationshipActionMany(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n request: ResourceRelationshipBulkActionRequest,\n options?: ServiceOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n const service = this.getServiceOrThrow(resourceType);\n const parsedRequest = ResourceRelationshipBulkActionRequestSchema.parse(request);\n return service.applyRelationshipActionMany(\n executionContext,\n id_or_ids_or_filter,\n parsedRequest,\n options\n );\n }\n\n // ════════════════════════════════════════════════════════════════════\n // Post-operation hooks\n // ════════════════════════════════════════════════════════════════════\n\n /**\n * Register a callback that fires after any successful mutation on a resource type.\n * Hooks are fire-and-forget — errors are logged but do not fail the operation.\n *\n * @param resourceType - The resource type to observe\n * @param callback - Invoked after CREATE, UPDATE, DELETE, or custom mutation succeeds\n */\n public registerPostOperationHook(resourceType: string, callback: PostOperationHookCallback): void {\n const hooks = this.postOperationHooks.get(resourceType) ?? [];\n hooks.push(callback);\n this.postOperationHooks.set(resourceType, hooks);\n this.logDebug('Post-operation hook registered', { resourceType });\n }\n\n /**\n * Dispatch post-operation hooks for a resource type.\n * Called by ServiceResourceBackendService after successful operations.\n * @internal\n */\n public async dispatchPostOperationHooks(\n resourceType: string,\n operationIdentifier: string,\n result: any,\n executionContext: ExecutionContext<any>,\n ): Promise<void> {\n const hooks = this.postOperationHooks.get(resourceType);\n if (!hooks || hooks.length === 0) return;\n\n for (const hook of hooks) {\n try {\n await hook(resourceType, operationIdentifier, result, executionContext);\n } catch (error) {\n this.logger.warn('Post-operation hook failed', {\n resourceType,\n operationIdentifier,\n error: (error as Error).message,\n });\n }\n }\n }\n\n /**\n * Register a callback that fires BEFORE a core operation on a resource type.\n *\n * **Operation coverage** (Phase 5 / P5-H = H1 widened):\n * - Mutating ops: CREATE / CREATE_MANY / UPDATE / UPDATE_MANY /\n * DELETE / DELETE_MANY (Phase-3 baseline).\n * - Read ops: READ / LIST (Phase 5 widening, to support the LAZY\n * seeding guard installed by `wireLazyAccessGuards`). The\n * pre-hook callback receives the raw `id_or_ids_or_filter`\n * (READ) or `filter` (LIST) as its `data` arg; LAZY guards\n * ignore it, but future read-side pre-hooks (audit-on-read,\n * cache-warming, access-policy-enforcement) can inspect it.\n *\n * Operations not in the list above (RELATE_*, custom operations,\n * etc.) do not fire pre-hooks today.\n *\n * Symmetric companion to {@link registerPostOperationHook}. Unlike the\n * post variant, pre-hook failures are **propagated** (plan §Phase-3\n * decision P3-A = A1, reaffirmed for read paths by P5-A = A1):\n * throwing from a pre-hook short-circuits the dispatch loop AND the\n * triggering operation. This is deliberate — pre-hooks are the veto\n * point for Level-B data seeding, LAZY first-access bootstrap, guard\n * checks, and cross-resource consistency rules that should abort\n * the operation. Soft observations belong on the post-hook side.\n *\n * Registration order is preserved by dispatch order (first registered,\n * first invoked). If an earlier hook throws, later hooks in the same\n * bucket do NOT run — rollback of previously-invoked hooks is the\n * caller's responsibility and does not exist in the framework.\n *\n * **Performance**: registered hooks pay an O(1) Map lookup + the\n * hook's own work per invocation. Resources without any registered\n * pre-hook short-circuit in {@link dispatchPreOperationHooks} on the\n * empty-hooks branch — no per-call cost. The READ/LIST widening\n * therefore costs nothing for resources that do not opt into a\n * pre-hook (the common case).\n *\n * @param resourceType - The resource type to observe\n * @param callback - Invoked before CREATE / UPDATE / DELETE / READ / LIST (and their bulk variants where applicable) on this resource type\n */\n public registerPreOperationHook(resourceType: string, callback: PreOperationHookCallback): void {\n const hooks = this.preOperationHooks.get(resourceType) ?? [];\n hooks.push(callback);\n this.preOperationHooks.set(resourceType, hooks);\n this.logDebug('Pre-operation hook registered', { resourceType });\n }\n\n /**\n * `true` iff at least one pre-operation hook is registered for\n * `resourceType`. Used by mutation paths that have to decide whether\n * to perform extra preparatory work for hooks (e.g. `updateMany`\n * loading `currentStates` so the pre-hook payload can carry per-row\n * `_id` anchors — see {@link executePreOperationLogic}). Resources\n * without any subscribed hook MUST NOT pay that cost — the predicate\n * exists exclusively as the gate that keeps the framework\n * pay-for-what-you-use.\n */\n public hasPreOperationHooks(resourceType: string): boolean {\n const hooks = this.preOperationHooks.get(resourceType);\n return Array.isArray(hooks) && hooks.length > 0;\n }\n\n /**\n * Dispatch pre-operation hooks for a resource type.\n * Called by {@link ServiceResourceBackendService} during\n * {@link ServiceResourceBackendService.executePreOperationLogic}\n * BEFORE the core repository call.\n *\n * Short-circuit on first throw — errors propagate unchanged to the\n * caller so the operation surfaces the failure through its normal\n * error-handling path (custom impl `prefixCoreOperations` throws take\n * the same shape from the caller's POV).\n *\n * @internal\n */\n public async dispatchPreOperationHooks(\n resourceType: string,\n operationIdentifier: string,\n data: any,\n executionContext: ExecutionContext<any>,\n ): Promise<void> {\n const hooks = this.preOperationHooks.get(resourceType);\n if (!hooks || hooks.length === 0) return;\n\n for (const hook of hooks) {\n // Intentionally no try/catch — see plan §Phase-3 P3-A=A1. A thrown\n // hook aborts the loop; subsequent hooks in the same bucket do not\n // run and the error propagates to `executePreOperationLogic`, which\n // lets it bubble to the top of the pipeline (same shape as a\n // `prefixCoreOperations` rejection).\n await hook(resourceType, operationIdentifier, data, executionContext);\n }\n }\n\n // ════════════════════════════════════════════════════════════════════\n // Read / List / Search / Count\n // ════════════════════════════════════════════════════════════════════\n\n /**\n * List resources with optional pagination.\n * @param options.paginated - When true, returns { data: T[], pagination: {...} }. Default: false (returns T[])\n * @param options.variantKey - Optional variant key (e.g., 'summary', 'context')\n * @param options.dataMode - Optional data mode for population behavior\n */\n public async list<T = any>(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n filter?: FilterQuery<any>,\n pagination?: Partial<Resources_PaginationRequest>,\n options?: ServiceOptions\n ): Promise<T[] | Resources_PaginatedResult<T>> {\n\n const service = this.getServiceOrThrow(resourceType);\n // If variantKey is specified, get that variant's operationPath\n const operationPath : ResourceConfiguration_OperationPath<any, any> = options?.variantKey\n ? this.resourcesRegistry.getServiceOperationPath(resourceType, CoreResourceOperation.LIST, options.variantKey)\n : this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.LIST);\n const listData = { filter, page: pagination?.page, limit: pagination?.limit };\n return service.doByOperationPath(operationPath, executionContext, undefined, listData, options);\n }\n\n public async search<T = any>(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n searchQuery: string,\n filter?: FilterQuery<any>,\n options?: ServiceOptions\n ): Promise<Resources_PaginatedResult<T>> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.SEARCH);\n return service.doByOperationPath(operationPath, executionContext, undefined, { searchQuery, filter }, options);\n }\n\n public async count( resourceType: ResourceType, executionContext: ExecutionContext<any>, filter?: FilterQuery<any>, options?: ServiceOptions ): Promise<{ count: number }> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.COUNT);\n const countData = filter ? { filter } : undefined;\n return service.doByOperationPath(operationPath, executionContext, undefined, countData, options);\n }\n\n // ================================\n // Utility Methods\n // ================================\n\n public getAvailableOperationPaths(): ResourceConfiguration_OperationPath<any, any>[] {\n return Array.from(this.serviceOperationsMap.values()).map(info => info.operationPath);\n }\n\n public hasService(resourceType: ResourceType): boolean {\n return this.services.has(resourceType);\n }\n\n public getRegisteredResourceTypes(): ResourceType[] {\n return Array.from(this.services.keys());\n }\n\n public getServiceCount(): number {\n return this.services.size;\n }\n\n public getDebugInfo(): {\n serviceCount: number;\n operationPathsCount: number;\n resourceTypes: ResourceType[];\n isInitialized: boolean;\n } {\n return {\n serviceCount: this.services.size,\n operationPathsCount: this.serviceOperationsMap.size,\n resourceTypes: Array.from(this.services.keys()),\n isInitialized: this.isInitialized\n };\n }\n}\n\n/**\n * Callback type for post-operation hooks.\n * Fired after a successful mutation (CREATE/UPDATE/DELETE/custom) on a resource.\n */\nexport type PostOperationHookCallback = (\n resourceType: string,\n operationIdentifier: string,\n result: any,\n executionContext: ExecutionContext<any>,\n) => Promise<void>;\n\n/**\n * Callback type for pre-operation hooks.\n * Fired BEFORE the core mutation (CREATE/UPDATE/DELETE) on a resource.\n *\n * Observation + veto only — the return value is `void` (no mutation of\n * incoming `data` through the hook surface). To short-circuit the\n * operation, throw — errors propagate unchanged to the caller (plan\n * §Phase-3 decision P3-A=A1). To transform data, use the custom\n * operation's `prefixCoreOperations` hook instead.\n */\nexport type PreOperationHookCallback = (\n resourceType: string,\n operationIdentifier: string,\n data: any,\n executionContext: ExecutionContext<any>,\n) => Promise<void>;\n\n//============================================================================================================================\n//\n// Service Resource Backend Service\n//\n//============================================================================================================================\n\n\nexport class ServiceResourceBackendService<\n TCustomOperationEnum extends EnumLikeType | undefined = undefined,\n TCoreOperationEnum extends Partial<CoreResourceOperation> | undefined = undefined,\n TMainSchema extends z.ZodTypeAny = z.ZodTypeAny\n> {\n\n private readonly resourceConfiguration: ResourceConfiguration<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\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 resourcesRegistry: ResourcesRegistryBackendService,\n private readonly logger: LoggerService,\n private readonly errorBuilder: ErrorBuilderBackendService,\n private readonly repositoryHelper: ResourceOperationHelperBackendService,\n private readonly customImplRegistry: ResourceOperationCustomImplementationRegistryBackendService,\n private readonly repositoriesRegistry: RepositoriesRegistryHandlerBackendService,\n private readonly servicesRegistry: ServicesRegistryHandlerBackendService,\n private readonly externalApiHandler: ExternalApiHandlerBackendService,\n private readonly platformMutualizedHandler: PlatformMutualizedHandlerBackendService,\n private readonly serverlessServicesHandler: ServerlessServicesHandlerBackendService,\n private readonly notificationDispatcher: NotificationDispatcherService,\n private readonly populationService: ResourcePopulationBackendService,\n private readonly virtualFieldsService: VirtualFieldsBackendService,\n private readonly mongoDBService: MongoDBService,\n private readonly fileOperationHandler: FileOperationHandlerBackendService,\n private readonly fileFieldDetection: FileFieldDetectionBackendService,\n private readonly executionContextCreator: ExecutionContextCreatorBackendService,\n private readonly queueService: QueueBackendService,\n private readonly featureGate: FeatureGateBackendService,\n private readonly consumableTokenService: ConsumableTokenBackendService,\n private readonly appConfigService: AppConfigurationService,\n private readonly pdfGenerationOrchestrator: PdfGenerationOrchestratorBackendService,\n private readonly guidanceTriggerEvaluator?: GuidanceTriggerEvaluatorBackendService,\n private readonly milestoneEvaluator?: MilestoneEvaluatorBackendService,\n private readonly lifecycleEvaluator?: LifecycleEvaluatorBackendService,\n private readonly postgreSQLDatabaseService?: PostgreSQLDatabaseBackendService,\n private readonly resourcePersistenceUnitOfWork?:\n ResourcePersistenceUnitOfWorkBackendService,\n ) {\n this.operationsMap = new Map();\n\n this.resourceConfiguration = this.resourcesRegistry.getResourceConfiguration(resourceType);\n\n this.logDebug = this.logger.debugByType(`ServiceResource_${resourceType}`);\n this.logger.setDebugTypeLogging(`ServiceResource_${resourceType}`, false);\n\n this.initializeOperationsMap();\n\n this.logDebug('Service resource created', {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n operationsCount: this.operationsMap.size\n });\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 logger: LoggerService,\n errorBuilder: ErrorBuilderBackendService,\n repositoriesRegistry: RepositoriesRegistryHandlerBackendService,\n servicesRegistry: ServicesRegistryHandlerBackendService,\n resourcesRegistry: ResourcesRegistryBackendService,\n repositoryHelper: ResourceOperationHelperBackendService,\n customImplRegistry: ResourceOperationCustomImplementationRegistryBackendService,\n resourcePersistenceUnitOfWork: ResourcePersistenceUnitOfWorkBackendService,\n externalApiHandler: ExternalApiHandlerBackendService,\n platformMutualizedHandler: PlatformMutualizedHandlerBackendService,\n serverlessServicesHandler: ServerlessServicesHandlerBackendService,\n notificationDispatcher: NotificationDispatcherService,\n populationService: ResourcePopulationBackendService,\n virtualFieldsService: VirtualFieldsBackendService,\n mongoDBService: MongoDBService,\n fileOperationHandler: FileOperationHandlerBackendService,\n fileFieldDetection: FileFieldDetectionBackendService,\n executionContextCreator: ExecutionContextCreatorBackendService,\n queueService: QueueBackendService,\n featureGate: FeatureGateBackendService,\n consumableTokenService: ConsumableTokenBackendService,\n appConfigService: AppConfigurationService,\n pdfGenerationOrchestrator: PdfGenerationOrchestratorBackendService,\n guidanceTriggerEvaluator?: GuidanceTriggerEvaluatorBackendService,\n milestoneEvaluator?: MilestoneEvaluatorBackendService,\n lifecycleEvaluator?: LifecycleEvaluatorBackendService,\n postgreSQLDatabaseService?: PostgreSQLDatabaseBackendService,\n ): ServiceResourceBackendService<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> {\n\n return new ServiceResourceBackendService(\n resourceType, resourcesRegistry, logger,\n errorBuilder, repositoryHelper, customImplRegistry, repositoriesRegistry,\n servicesRegistry, externalApiHandler, platformMutualizedHandler,\n serverlessServicesHandler, notificationDispatcher,\n populationService, virtualFieldsService, mongoDBService,\n fileOperationHandler, fileFieldDetection,\n executionContextCreator,\n queueService,\n featureGate,\n consumableTokenService,\n appConfigService,\n pdfGenerationOrchestrator,\n guidanceTriggerEvaluator,\n milestoneEvaluator,\n lifecycleEvaluator,\n postgreSQLDatabaseService,\n resourcePersistenceUnitOfWork,\n );\n }\n\n public async applyRelationshipActionMany(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n request: ResourceRelationshipBulkActionRequest,\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const parsedRequest = ResourceRelationshipBulkActionRequestSchema.parse(request);\n let relationship: ResourceRelationship;\n try {\n relationship = this.getRelationshipForBulkAction(parsedRequest.relationshipField);\n } catch (error) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField: parsedRequest.relationshipField,\n resourceType,\n reason: describeCaughtError(error),\n },\n }\n );\n }\n const allowedActions = Resources_SharedUtils.resolveAllowedBulkRelationshipActionsForResource(\n relationship,\n resourceType\n );\n\n if (!allowedActions.includes(parsedRequest.action)) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField: parsedRequest.relationshipField,\n action: parsedRequest.action,\n resourceType,\n allowedActions,\n reason: 'Requested bulk relationship action is not allowed for this relationship from the current resource perspective',\n },\n }\n );\n }\n\n switch (parsedRequest.action) {\n case ResourceRelationshipBulkAction.SET:\n return this.applyReferenceSetActionMany(\n executionContext,\n id_or_ids_or_filter,\n relationship,\n parsedRequest.relationshipField,\n parsedRequest.targetId,\n options\n );\n case ResourceRelationshipBulkAction.CLEAR:\n return this.applyReferenceClearActionMany(\n executionContext,\n id_or_ids_or_filter,\n relationship,\n parsedRequest.relationshipField,\n options\n );\n case ResourceRelationshipBulkAction.CREATE:\n return this.applyCompositionCreateActionMany(\n executionContext,\n id_or_ids_or_filter,\n relationship,\n parsedRequest.relationshipField,\n parsedRequest.data,\n options\n );\n case ResourceRelationshipBulkAction.LINK:\n return this.applyAssociationLinkActionMany(\n executionContext,\n id_or_ids_or_filter,\n relationship,\n parsedRequest.relationshipField,\n parsedRequest.peerIds,\n options\n );\n case ResourceRelationshipBulkAction.UNLINK:\n return this.applyAssociationUnlinkActionMany(\n executionContext,\n id_or_ids_or_filter,\n relationship,\n parsedRequest.relationshipField,\n parsedRequest.peerIds,\n options\n );\n case ResourceRelationshipBulkAction.REPLACE:\n return this.applyAssociationReplaceActionMany(\n executionContext,\n id_or_ids_or_filter,\n relationship,\n parsedRequest.relationshipField,\n parsedRequest.peerIds,\n options\n );\n }\n }\n\n private async executeGeneratedRelationshipBulkOperation(\n resolvedOperation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n operation: { action: ResourceRelationshipBulkAction; relationshipField: string },\n executionContext: ExecutionContext<any>,\n data: any,\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n switch (operation.action) {\n case ResourceRelationshipBulkAction.SET: {\n const request = this.parseGeneratedRelationshipBulkOperationRequest(\n ResourceRelationshipBulkSetOperationRequestSchema,\n operation,\n data,\n executionContext\n );\n await this.assertGeneratedRelationshipBulkOperationEnabled(\n resolvedOperation,\n request,\n executionContext\n );\n return this.applyRelationshipActionMany(\n executionContext,\n this.resolveGeneratedRelationshipBulkSelector(request),\n {\n relationshipField: operation.relationshipField,\n action: ResourceRelationshipBulkAction.SET,\n targetId: request.targetId,\n },\n options\n );\n }\n case ResourceRelationshipBulkAction.CLEAR: {\n const request = this.parseGeneratedRelationshipBulkOperationRequest(\n ResourceRelationshipBulkClearOperationRequestSchema,\n operation,\n data,\n executionContext\n );\n await this.assertGeneratedRelationshipBulkOperationEnabled(\n resolvedOperation,\n request,\n executionContext\n );\n return this.applyRelationshipActionMany(\n executionContext,\n this.resolveGeneratedRelationshipBulkSelector(request),\n {\n relationshipField: operation.relationshipField,\n action: ResourceRelationshipBulkAction.CLEAR,\n },\n options\n );\n }\n case ResourceRelationshipBulkAction.CREATE: {\n const request = this.parseGeneratedRelationshipBulkOperationRequest(\n ResourceRelationshipBulkCreateOperationRequestSchema,\n operation,\n data,\n executionContext\n );\n await this.assertGeneratedRelationshipBulkOperationEnabled(\n resolvedOperation,\n request,\n executionContext\n );\n return this.applyRelationshipActionMany(\n executionContext,\n this.resolveGeneratedRelationshipBulkSelector(request),\n {\n relationshipField: operation.relationshipField,\n action: ResourceRelationshipBulkAction.CREATE,\n data: request.data,\n },\n options\n );\n }\n case ResourceRelationshipBulkAction.LINK: {\n const request = this.parseGeneratedRelationshipBulkOperationRequest(\n ResourceRelationshipBulkLinkOperationRequestSchema,\n operation,\n data,\n executionContext\n );\n await this.assertGeneratedRelationshipBulkOperationEnabled(\n resolvedOperation,\n request,\n executionContext\n );\n return this.applyRelationshipActionMany(\n executionContext,\n this.resolveGeneratedRelationshipBulkSelector(request),\n {\n relationshipField: operation.relationshipField,\n action: ResourceRelationshipBulkAction.LINK,\n peerIds: request.peerIds,\n },\n options\n );\n }\n case ResourceRelationshipBulkAction.UNLINK: {\n const request = this.parseGeneratedRelationshipBulkOperationRequest(\n ResourceRelationshipBulkUnlinkOperationRequestSchema,\n operation,\n data,\n executionContext\n );\n await this.assertGeneratedRelationshipBulkOperationEnabled(\n resolvedOperation,\n request,\n executionContext\n );\n return this.applyRelationshipActionMany(\n executionContext,\n this.resolveGeneratedRelationshipBulkSelector(request),\n {\n relationshipField: operation.relationshipField,\n action: ResourceRelationshipBulkAction.UNLINK,\n peerIds: request.peerIds,\n },\n options\n );\n }\n case ResourceRelationshipBulkAction.REPLACE: {\n const request = this.parseGeneratedRelationshipBulkOperationRequest(\n ResourceRelationshipBulkReplaceOperationRequestSchema,\n operation,\n data,\n executionContext\n );\n await this.assertGeneratedRelationshipBulkOperationEnabled(\n resolvedOperation,\n request,\n executionContext\n );\n return this.applyRelationshipActionMany(\n executionContext,\n this.resolveGeneratedRelationshipBulkSelector(request),\n {\n relationshipField: operation.relationshipField,\n action: ResourceRelationshipBulkAction.REPLACE,\n peerIds: request.peerIds,\n },\n options\n );\n }\n }\n }\n\n private parseGeneratedRelationshipBulkOperationRequest<T>(\n schema: z.ZodType<T>,\n operation: { action: ResourceRelationshipBulkAction; relationshipField: string },\n data: unknown,\n executionContext: ExecutionContext<any>\n ): T {\n try {\n return schema.parse(data);\n } catch (error) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n action: operation.action,\n relationshipField: operation.relationshipField,\n reason: describeCaughtError(error),\n },\n }\n );\n }\n }\n\n private resolveGeneratedRelationshipBulkSelector(\n request:\n | ResourceRelationshipBulkOperationSelector\n | ResourceRelationshipBulkSetOperationRequest\n | ResourceRelationshipBulkClearOperationRequest\n | ResourceRelationshipBulkCreateOperationRequest\n | ResourceRelationshipBulkLinkOperationRequest\n | ResourceRelationshipBulkUnlinkOperationRequest\n | ResourceRelationshipBulkReplaceOperationRequest\n ): IdOrIdsOrFilterType {\n if ('_ids' in request && Array.isArray(request._ids)) {\n return request._ids.length === 1 ? request._ids[0] : request._ids;\n }\n\n if ('filter' in request && request.filter) {\n return request.filter as IdOrIdsOrFilterType;\n }\n\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.BULK_RELATIONSHIP_SELECTOR_REQUIRED,\n });\n }\n\n private async assertGeneratedRelationshipBulkOperationEnabled(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n request:\n | ResourceRelationshipBulkSetOperationRequest\n | ResourceRelationshipBulkClearOperationRequest\n | ResourceRelationshipBulkCreateOperationRequest\n | ResourceRelationshipBulkLinkOperationRequest\n | ResourceRelationshipBulkUnlinkOperationRequest,\n executionContext: ExecutionContext<any>\n ): Promise<void> {\n if (!('enabledCondition' in operation) || !operation.enabledCondition) {\n return;\n }\n\n const selector = this.resolveGeneratedRelationshipBulkSelector(request);\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const singleSelectedId =\n Array.isArray(request._ids) && request._ids.length === 1\n ? request._ids[0]\n : undefined;\n\n const needs = extractFunctionContextNeeds(operation.enabledCondition);\n if (!singleSelectedId && needs.needsObjectContext) {\n throw this.errorBuilder.buildError(\n ErrorType.AUTHORIZATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_DISABLED,\n context: {\n reason: 'Generated bulk relationship operations with multi-target selectors cannot satisfy enabledCondition object-context requirements',\n operationIdentifier: String(operation.operationIdentifier),\n },\n }\n );\n }\n\n const currentObject = singleSelectedId\n ? await this.fetchCurrentObjectForOperation(\n CoreResourceOperation.UPDATE_MANY,\n resourceType,\n singleSelectedId,\n executionContext\n )\n : undefined;\n if (singleSelectedId && needs.needsObjectContext && !currentObject) {\n throw this.errorBuilder.buildError(\n ErrorType.AUTHORIZATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_DISABLED,\n context: {\n reason: 'Generated bulk relationship operations requiring object context cannot run when the selected current object cannot be loaded',\n operationIdentifier: String(operation.operationIdentifier),\n },\n }\n );\n }\n const { objectContext, initiatorUserContext } = await this.fetchContextsForOperationFunction(\n operation.enabledCondition,\n resourceType,\n currentObject,\n executionContext\n );\n // Generated bulk operations only have a persisted current object when the\n // selector is exactly one `_id`. Multi-target selectors deliberately fail\n // closed before this point if `needsObjectContext` is declared.\n const isEnabled = operation.enabledCondition({\n inputDto: request as any,\n currentObject: currentObject as any,\n objectContext,\n initiatorUserContext,\n initiatorIds: executionContext.initiatorIds,\n });\n\n if (!isEnabled) {\n throw this.errorBuilder.buildError(\n ErrorType.AUTHORIZATION,\n executionContext,\n { customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_DISABLED }\n );\n }\n }\n\n private resolveSingleSelectedId(\n id_or_ids_or_filter: IdOrIdsOrFilterType | undefined\n ): string | undefined {\n if (typeof id_or_ids_or_filter === 'string') {\n return id_or_ids_or_filter;\n }\n\n if (\n Array.isArray(id_or_ids_or_filter)\n && id_or_ids_or_filter.length === 1\n && typeof id_or_ids_or_filter[0] === 'string'\n ) {\n return id_or_ids_or_filter[0];\n }\n\n if (id_or_ids_or_filter && typeof id_or_ids_or_filter === 'object'\n && !Array.isArray(id_or_ids_or_filter)\n ) {\n if (\n 'id_or_ids' in id_or_ids_or_filter\n && Array.isArray(id_or_ids_or_filter.id_or_ids)\n && id_or_ids_or_filter.id_or_ids.length === 1\n && typeof id_or_ids_or_filter.id_or_ids[0] === 'string'\n ) {\n return id_or_ids_or_filter.id_or_ids[0];\n }\n\n if (\n 'ids' in id_or_ids_or_filter\n && Array.isArray(id_or_ids_or_filter.ids)\n && id_or_ids_or_filter.ids.length === 1\n && typeof id_or_ids_or_filter.ids[0] === 'string'\n ) {\n return id_or_ids_or_filter.ids[0];\n }\n }\n\n return undefined;\n }\n\n private resolveHookCurrentObject(\n coreOperation: CoreResourceOperation | undefined,\n currentObject: any,\n data: any\n ): any {\n return coreOperation === CoreResourceOperation.CREATE\n || coreOperation === CoreResourceOperation.CREATE_MANY\n ? data\n : currentObject;\n }\n\n private async resolveContextAddressedSingletonOperationTarget(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n coreOperation: CoreResourceOperation | undefined,\n resourceType: ResourceType,\n idOrIdsOrFilter: IdOrIdsOrFilterType | undefined,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<ContextAddressedSingletonOperationTarget | undefined> {\n const operationEffectiveIdentifier = operation.resourceOperationLike ?? operation.operationIdentifier;\n if (\n coreOperation !== CoreResourceOperation.READ\n && coreOperation !== CoreResourceOperation.UPDATE\n && coreOperation !== CoreResourceOperation.DELETE\n ) {\n return undefined;\n }\n\n if (\n operationEffectiveIdentifier !== CoreResourceOperation.READ\n && operationEffectiveIdentifier !== CoreResourceOperation.UPDATE\n && operationEffectiveIdentifier !== CoreResourceOperation.DELETE\n ) {\n return undefined;\n }\n\n // Resolve the context-addressed target for USER *and* MACHINE principals — both are EXTERNAL request\n // principals (scope-bound + role-checked) that address a context-addressed resource via the PARENT SCOPE\n // in the URL (e.g. `GET …/organizations/{orgId}/organization-webhook-config`, which carries no explicit\n // id). The original `USER_REQUEST`-only gate excluded machine tokens (ORGANIZATION_MACHINE/\n // APPLICATION_MACHINE), so a machine read of such a resource resolved NO id and failed\n // `repository_resource_operation_failed` (400). Machine principals now resolve it like a user;\n // INTERNAL/PUBLIC/WEBHOOK/ANONYMOUS/CONSUMABLE are still excluded (they must not reinterpret the parent\n // scope as identity), and role authorization + the tenant-scoped contextual filter still apply.\n if (!executionContext.isUserExecution() && !executionContext.isMachineExecution()) {\n return undefined;\n }\n\n if ('isBulkOperation' in operation && operation.isBulkOperation === true) {\n return undefined;\n }\n\n if (idOrIdsOrFilter !== undefined && idOrIdsOrFilter !== null) {\n return undefined;\n }\n\n if (!operation.resourceRelationships) {\n return undefined;\n }\n\n const candidates = getContextAddressedCompositionSingletonRelationshipCandidates(operation.resourceRelationships)\n .map((candidate) => {\n const parentResourceId = this.resolveParentContextResourceId(\n candidate.parentResourceType,\n candidate.foreignKeyField,\n executionContext\n );\n return parentResourceId\n ? { ...candidate, parentResourceId }\n : undefined;\n })\n .filter((candidate): candidate is {\n relationship: ResourceRelationship;\n foreignKeyField: string;\n parentResourceType: ResourceType;\n parentResourceId: string;\n } => candidate !== undefined);\n\n if (candidates.length === 0) {\n return undefined;\n }\n\n if (candidates.length > 1) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Ambiguous context-addressed singleton mutation target',\n resourceType,\n parentResourceTypes: candidates.map((candidate) => candidate.parentResourceType),\n },\n }\n );\n }\n\n const candidate = candidates[0];\n const selector = { [candidate.foreignKeyField]: candidate.parentResourceId };\n const repo = this.repositoriesRegistry.getRepository(resourceType);\n // Use `listForInternalScan` (NOT the public `list`), mirroring the controller-side\n // authorization probe: context-addressed singletons (e.g. `userProgressionState`)\n // expose only READ to users and declare NO user-facing LIST operation. This probe\n // is framework machinery proving uniqueness by parent FK, so it must scan\n // regardless of a declared LIST surface — `list` would throw\n // `repository_resource_operation_failed` (\"no default LIST operation declared\")\n // exactly on the absent-singleton READ path this resolver now serves.\n if (!repo) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Context-addressed singleton operation requires a registered repository to prove uniqueness',\n resourceType,\n },\n }\n );\n }\n\n const listResult = // `T` is pinned: the repository handle is schema-less here, so the strengthened\n // contract types rows as `unknown` rather than pretending to know them. This probe\n // only needs the persisted-id shape.\n await repo.listForInternalScan<Record<string, unknown>>(executionContext, selector, {\n ...options,\n paginated: false,\n });\n // The paginated-envelope unwrapping that used to live here is gone, not overlooked:\n // `paginated: false` selects the array overload, so the contract now states the shape\n // that the runtime always returned. The branch was unreachable and only looked\n // defensive because the call was cast to `any`.\n const matches = listResult;\n\n if (matches.length === 0) {\n // No singleton row exists yet for this parent scope.\n //\n // READ: do NOT treat absence as a target-resolution failure. Address the read\n // by the parent-scope `selector` so the core read returns null and a registered\n // POSTFIX materialization hook (scoped progression/guidance state) can\n // create-and-return the row. Without a hook the operation layer still emits\n // CONTROLLER_RESOURCE_NOT_FOUND after the null read — same outcome, correct layer.\n // The selector is derived from the execution context (auth/session-scoped, never\n // request input), so the read stays locked to the authenticated scope.\n //\n // UPDATE/DELETE: a mutation cannot be addressed to a non-existent singleton —\n // keep failing closed with not-found.\n if (coreOperation === CoreResourceOperation.READ) {\n return {\n addressedBy: 'parent-context',\n kind: 'absent-read-by-scope',\n selector,\n relationship: candidate.relationship,\n };\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.NOT_FOUND,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: {\n operation: coreOperation,\n selector,\n resourceType,\n },\n }\n );\n }\n\n if (matches.length > 1) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Context-addressed singleton mutation matched multiple rows',\n resourceType,\n selector,\n matchCount: matches.length,\n },\n }\n );\n }\n\n const currentObject = matches[0];\n const operationId = this.extractPersistedResourceId(currentObject);\n if (!operationId) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Context-addressed singleton operation resolved a row without _id',\n resourceType,\n selector,\n },\n }\n );\n }\n\n return {\n addressedBy: 'parent-context',\n kind: 'resolved',\n selector,\n currentObject,\n operationId,\n mutationId: operationId,\n relationship: candidate.relationship,\n };\n }\n\n private async resolveContextAddressedAssociationOperationTarget(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n coreOperation: CoreResourceOperation | undefined,\n resourceType: ResourceType,\n idOrIdsOrFilter: IdOrIdsOrFilterType | undefined,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<ContextAddressedAssociationOperationTarget | undefined> {\n const operationEffectiveIdentifier = operation.resourceOperationLike ?? operation.operationIdentifier;\n if (\n coreOperation !== CoreResourceOperation.READ\n && coreOperation !== CoreResourceOperation.UPDATE\n && coreOperation !== CoreResourceOperation.DELETE\n ) {\n return undefined;\n }\n\n if (\n operationEffectiveIdentifier !== CoreResourceOperation.READ\n && operationEffectiveIdentifier !== CoreResourceOperation.UPDATE\n && operationEffectiveIdentifier !== CoreResourceOperation.DELETE\n ) {\n return undefined;\n }\n\n // Resolve the context-addressed target for USER *and* MACHINE principals — both are EXTERNAL request\n // principals (scope-bound + role-checked) that address a context-addressed resource via the PARENT SCOPE\n // in the URL (e.g. `GET …/organizations/{orgId}/organization-webhook-config`, which carries no explicit\n // id). The original `USER_REQUEST`-only gate excluded machine tokens (ORGANIZATION_MACHINE/\n // APPLICATION_MACHINE), so a machine read of such a resource resolved NO id and failed\n // `repository_resource_operation_failed` (400). Machine principals now resolve it like a user;\n // INTERNAL/PUBLIC/WEBHOOK/ANONYMOUS/CONSUMABLE are still excluded (they must not reinterpret the parent\n // scope as identity), and role authorization + the tenant-scoped contextual filter still apply.\n if (!executionContext.isUserExecution() && !executionContext.isMachineExecution()) {\n return undefined;\n }\n\n if ('isBulkOperation' in operation && operation.isBulkOperation === true) {\n return undefined;\n }\n\n if (idOrIdsOrFilter !== undefined && idOrIdsOrFilter !== null) {\n return undefined;\n }\n\n if (!operation.resourceRelationships) {\n return undefined;\n }\n\n const associationParentRelationships = (operation.resourceRelationships.parentRelationships ?? [])\n .filter((relationship) =>\n relationship.nature === RelationshipNature.ASSOCIATION\n && relationship.jointResourceType === resourceType\n && relationship.resourceType2 === resourceType\n && relationship.cardinality1 === ResourceRelationshipCardinality.ONE\n && relationship.cardinality2 === ResourceRelationshipCardinality.MANY\n );\n if (associationParentRelationships.length === 0) {\n return undefined;\n }\n\n if (associationParentRelationships.length !== 2) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Complete association-context operation target requires exactly two eligible parent relationships',\n resourceType,\n parentResourceTypes: associationParentRelationships.map((relationship) => relationship.resourceType1),\n },\n },\n );\n }\n\n const duplicatedParentResourceTypes = new Set(\n associationParentRelationships.map((relationship) => relationship.resourceType1)\n .filter((resourceType, _index, resourceTypes) =>\n resourceTypes.filter((candidate) => candidate === resourceType).length > 1\n )\n );\n const contextParents = associationParentRelationships\n .map((relationship) => {\n const foreignKeyField = this.resourcesRegistry.resolveForeignKeyField({\n resourceType1: relationship.resourceType1,\n foreignKeyField: relationship.foreignKeyField,\n });\n const parentResourceId = this.resolveAssociationParentContextResourceId(\n relationship.resourceType1,\n foreignKeyField,\n executionContext,\n { allowGenericParentContext: !duplicatedParentResourceTypes.has(relationship.resourceType1) },\n );\n return parentResourceId\n ? { relationship, foreignKeyField, parentResourceId }\n : undefined;\n })\n .filter((candidate): candidate is {\n relationship: ResourceRelationship;\n foreignKeyField: string;\n parentResourceId: string;\n } => candidate !== undefined);\n\n if (contextParents.length < 2) {\n return undefined;\n }\n\n const selector = Object.fromEntries(\n contextParents.map((candidate) => [candidate.foreignKeyField, candidate.parentResourceId])\n );\n if (Object.keys(selector).length !== contextParents.length) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Complete association-context operation target resolved duplicate foreign key fields',\n resourceType,\n foreignKeyFields: contextParents.map((candidate) => candidate.foreignKeyField),\n },\n },\n );\n }\n\n const repo = this.repositoriesRegistry.getRepository(resourceType);\n // Framework-internal uniqueness probe — resolve the junction row's id by its\n // two parent FKs to address a context-addressed READ/UPDATE/DELETE. Use\n // `listForInternalScan` (NOT the public `list`), mirroring the singleton\n // resolver above and the controller-side association authorization probe: an\n // association junction resource may expose READ/UPDATE/DELETE without declaring\n // a user-facing default LIST, in which case `repo.list()` throws\n // `repository_resource_operation_failed` (\"no default LIST operation declared\",\n // INTERNAL/critical 500). `listForInternalScan` synthesizes a REPOSITORY_ONLY\n // scan when no LIST is declared and reuses the declared LIST (with its hooks)\n // otherwise, so this swap removes the latent 500 without changing behavior for\n // junctions that DO expose LIST. Unlike singletons, an absent junction row is a\n // genuine not-found (no lazy materialization), so the 0-rows branch below still\n // fails closed with NOT_FOUND for every verb.\n if (!repo) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Complete association-context operation requires a registered repository to prove uniqueness',\n resourceType,\n },\n },\n );\n }\n\n const listResult = // `T` is pinned: the repository handle is schema-less here, so the strengthened\n // contract types rows as `unknown` rather than pretending to know them. This probe\n // only needs the persisted-id shape.\n await repo.listForInternalScan<Record<string, unknown>>(executionContext, selector, {\n ...options,\n paginated: false,\n });\n // The paginated-envelope unwrapping that used to live here is gone, not overlooked:\n // `paginated: false` selects the array overload, so the contract now states the shape\n // that the runtime always returned. The branch was unreachable and only looked\n // defensive because the call was cast to `any`.\n const matches = listResult;\n\n if (matches.length === 0) {\n throw this.errorBuilder.buildError(\n ErrorType.NOT_FOUND,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: {\n operation: coreOperation,\n selector,\n resourceType,\n },\n },\n );\n }\n\n if (matches.length > 1) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Complete association-context operation matched multiple rows',\n resourceType,\n selector,\n matchCount: matches.length,\n },\n },\n );\n }\n\n const currentObject = matches[0];\n const operationId = this.extractPersistedResourceId(currentObject);\n if (!operationId) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Complete association-context operation resolved a row without _id',\n resourceType,\n selector,\n },\n },\n );\n }\n\n return {\n addressedBy: 'association-complete-context',\n selector,\n currentObject,\n operationId,\n mutationId: operationId,\n relationships: contextParents.map((candidate) => candidate.relationship),\n };\n }\n\n private resolveContextAddressedSingletonMutationTarget(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n coreOperation: CoreResourceOperation | undefined,\n resourceType: ResourceType,\n idOrIdsOrFilter: IdOrIdsOrFilterType | undefined,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<ContextAddressedSingletonOperationTarget | undefined> {\n return this.resolveContextAddressedSingletonOperationTarget(\n operation,\n coreOperation,\n resourceType,\n idOrIdsOrFilter,\n executionContext,\n options,\n );\n }\n\n private resolveContextAddressedAssociationMutationTarget(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n coreOperation: CoreResourceOperation | undefined,\n resourceType: ResourceType,\n idOrIdsOrFilter: IdOrIdsOrFilterType | undefined,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<ContextAddressedAssociationOperationTarget | undefined> {\n return this.resolveContextAddressedAssociationOperationTarget(\n operation,\n coreOperation,\n resourceType,\n idOrIdsOrFilter,\n executionContext,\n options,\n );\n }\n\n private resolveParentContextResourceId(\n parentResourceType: ResourceType,\n foreignKeyField: string,\n executionContext: ExecutionContext<any>\n ): string | undefined {\n const byForeignKey = executionContext.getContextResourceId(foreignKeyField);\n if (byForeignKey) {\n return byForeignKey;\n }\n\n const relationshipContext = executionContext.getRelationshipContext(\n parentResourceType,\n foreignKeyField,\n ) ?? executionContext.getRelationshipContext(parentResourceType);\n if (relationshipContext?.resourceId) {\n return relationshipContext.resourceId;\n }\n\n const parentConfig = this.resourcesRegistry.tryGetResourceConfiguration(\n parentResourceType\n );\n if (!parentConfig) {\n return undefined;\n }\n\n return executionContext.getContextResourceId(parentConfig.resourceFieldIdentifier);\n }\n\n private resolveAssociationParentContextResourceId(\n parentResourceType: ResourceType,\n foreignKeyField: string,\n executionContext: ExecutionContext<any>,\n options?: { allowGenericParentContext?: boolean },\n ): string | undefined {\n const byForeignKey = executionContext.getContextResourceId(foreignKeyField);\n if (byForeignKey) {\n return byForeignKey;\n }\n\n const relationshipContext = executionContext.getRelationshipContext(\n parentResourceType,\n foreignKeyField,\n );\n if (relationshipContext?.resourceId) {\n return relationshipContext.resourceId;\n }\n\n if (options?.allowGenericParentContext !== true) {\n return undefined;\n }\n\n const genericRelationshipContext = executionContext.getRelationshipContext(parentResourceType);\n if (genericRelationshipContext?.resourceId) {\n return genericRelationshipContext.resourceId;\n }\n\n const parentConfig = this.resourcesRegistry.tryGetResourceConfiguration(parentResourceType);\n return parentConfig\n ? executionContext.getContextResourceId(parentConfig.resourceFieldIdentifier)\n : undefined;\n }\n\n private extractPersistedResourceId(currentObject: Record<string, unknown>): string | undefined {\n const id = currentObject._id;\n if (typeof id === 'string') {\n return id;\n }\n if (id && typeof id === 'object' && 'toString' in id && typeof id.toString === 'function') {\n return id.toString();\n }\n return undefined;\n }\n\n private hasContextAddressedSingletonParentScope(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n ): boolean {\n if (!operation.resourceRelationships) {\n return false;\n }\n\n return getContextAddressedCompositionSingletonRelationshipCandidates(operation.resourceRelationships)\n .some((candidate) => this.resolveParentContextResourceId(\n candidate.parentResourceType,\n candidate.foreignKeyField,\n executionContext,\n ) !== undefined);\n }\n\n private hasContextAddressedAssociationParentScope(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n ): boolean {\n if (!operation.resourceRelationships) {\n return false;\n }\n\n const operationResourceType = operation.resourceIdentifier as ResourceType | undefined;\n if (!operationResourceType) {\n return false;\n }\n\n const associationParentRelationships = (operation.resourceRelationships.parentRelationships ?? [])\n .filter((relationship) =>\n relationship.nature === RelationshipNature.ASSOCIATION\n && relationship.jointResourceType === operationResourceType\n && relationship.resourceType2 === operationResourceType\n && relationship.cardinality1 === ResourceRelationshipCardinality.ONE\n && relationship.cardinality2 === ResourceRelationshipCardinality.MANY\n );\n if (associationParentRelationships.length !== 2) {\n return false;\n }\n\n const duplicatedParentResourceTypes = new Set(\n associationParentRelationships.map((relationship) => relationship.resourceType1)\n .filter((resourceType, _index, resourceTypes) =>\n resourceTypes.filter((candidate) => candidate === resourceType).length > 1\n )\n );\n\n return associationParentRelationships.every((relationship) => {\n const foreignKeyField = this.resourcesRegistry.resolveForeignKeyField({\n resourceType1: relationship.resourceType1,\n foreignKeyField: relationship.foreignKeyField,\n });\n return this.resolveAssociationParentContextResourceId(\n relationship.resourceType1,\n foreignKeyField,\n executionContext,\n { allowGenericParentContext: !duplicatedParentResourceTypes.has(relationship.resourceType1) },\n ) !== undefined;\n });\n }\n\n /**\n * Refuse a core UPDATE that ATTEMPTS TO CHANGE a read-only (`.excludeFromUpdate()`) field.\n *\n * Such a field is stripped from the UPDATE request DTO, so a raw `PUT` that sends a NEW value for it\n * — e.g. `PUT /users/{id} { status: 'SUSPENDED' }`, where `status` is a lifecycle field written only\n * through `suspend_user` / `updateAsSystem` — currently strips it and answers `2xx` having changed\n * nothing: the \"answered success, did nothing\" defect this repository treats as worse than an error.\n * The client believes it changed the field; it did not. This turns the silent no-op into an explicit\n * `4xx` so the caller learns the field is not editable through the core update.\n *\n * Runs for BOTH the single `UPDATE` and the bulk `UPDATE_MANY` core operations — the controller\n * re-attaches read-only fields for both, so the guard must cover both or the sibling bulk path keeps\n * the silent no-op (see `.claude/rules/invariant-call-site-enumeration.md`). The two arms differ:\n * - **single (`isBulkUpdate = false`)**: compared against the ALREADY-FETCHED `currentObject` (no extra\n * read) — a payload that merely ECHOES the field at its current value is fine (the common \"PUT the\n * whole object back\" flow) and is NOT refused, only a genuine CHANGE is.\n * - **bulk (`isBulkUpdate = true`)**: there is no single stored row to echo-compare against, and a bulk\n * write sets one value across every matching row, so the mere PRESENCE of a non-exempt read-only\n * field is refused.\n *\n * Trusted system writers are EXEMPT via {@link isWriteIntegrityExemptExecution}: `updateAsSystem` (how\n * `status` is LEGITIMATELY written), seeds, webhooks and anonymous writes go through the system door\n * and re-attach these fields on purpose. Server-injected authoritative writes (a lifecycle verb's\n * prefix hook, carried via `options.preserveServerInjectedFields`) are also skipped. Discriminated-union\n * / non-object mainSchemas are skipped (no flat field set to inspect).\n *\n * LIMITATION: for a read-only field whose value is a plain OBJECT or ARRAY, the single-row echo compare\n * falls back to `stringifyPersistedValueForCompare` (`\"[object Object]\"`), so two distinct object values read\n * as equal and a genuine change is NOT refused — it degrades to the pre-existing silent no-op rather than\n * a loud `4xx`. Bounded: the repository's strict re-parse still strips the field so nothing persists;\n * only the \"loud refusal\" guarantee is unmet, and only for non-scalar read-only fields (ids / enums /\n * dates / version numbers — the overwhelming majority — are handled). The bulk arm is unaffected (it is\n * presence-based, not value-based).\n */\n private async assertNoForbiddenReadOnlyFieldChange(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n target: IdOrIdsOrFilterType | undefined,\n inputData: unknown,\n currentObject: unknown,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n isBulkUpdate = false,\n ): Promise<void> {\n if (isWriteIntegrityExemptExecution(executionContext, options)) return;\n if (!inputData || typeof inputData !== 'object') return;\n // The RESOURCE's full mainSchema (carries the `.excludeFromUpdate()` fields) — NOT `operation.mainSchema`,\n // which for a core UPDATE operation can be a per-operation / request-shaped schema that has already\n // dropped them, so the read-only fields would be invisible here.\n const mainSchema = this.resourceConfiguration.mainSchema as z.ZodTypeAny;\n if (!isZodObject(mainSchema)) return;\n const inputRecord = inputData as Record<string, unknown>;\n\n // Which read-only fields does THIS payload actually carry a value for? The overwhelming majority of\n // updates touch none, so this presence check runs first and the (possible) read below never happens\n // for them. Fields a custom operation AUTHORITATIVELY injected are skipped: a lifecycle verb\n // (`request-deletion`, `suspend`, `activate`, …) sets `status` / `deletionRequestedAt` through its\n // prefix hook and carries them past the repository's strict re-parse via `preserveServerInjectedFields`\n // — legitimate SERVER writes, not a client editing a read-only field. A CLIENT-supplied value\n // (re-attached from the request body by the controller) is NOT in that allow-list, so it is caught.\n // Decision logic is in `collectCandidateReadOnlyFields` / `filterChangedReadOnlyFields` so it can be\n // unit-pinned on both arms (see `read-only-field-change.backend.utils`).\n const serverInjectedFields = new Set(options?.preserveServerInjectedFields ?? []);\n const candidateFields = collectCandidateReadOnlyFields(mainSchema, inputRecord, serverInjectedFields);\n if (candidateFields.length === 0) return;\n\n // ── Bulk (UPDATE_MANY): refuse on PRESENCE ────────────────────────────────────────────────────\n // A filter- or id-set-addressed bulk update has no single stored row to echo-compare against, and a\n // bulk write is a partial \"set field = V on every matching row\". Applying ONE value to a read-only\n // field across many rows (whose stored values differ) is inherently a CHANGE, never the \"PUT the\n // whole object back\" echo the single-row path tolerates — so the mere PRESENCE of a non-exempt\n // read-only field is refused. Without this, the controller RE-ATTACHES read-only fields for\n // UPDATE_MANY too (so the service can see them), they flow to `_doUpdateMany`'s strict re-parse, get\n // stripped, and reproduce the silent-2xx-no-op on the bulk path — the sibling-call-site miss this\n // guard exists to prevent (see `.claude/rules/invariant-call-site-enumeration.md`).\n if (isBulkUpdate) {\n throw this.buildReadOnlyFieldNotEditableError(operation, executionContext, candidateFields);\n }\n\n // ── Single (UPDATE): compare against the stored row; a pure ECHO of the current value is allowed ─\n // Reuse the already-fetched `currentObject` when a hook needed it; otherwise read it now — a cost\n // paid ONLY on the rare update that carries a read-only field.\n let stored = (currentObject && typeof currentObject === 'object') ? (currentObject as Record<string, unknown>) : undefined;\n if (!stored) {\n const id = this.resolveSingleSelectedId(target);\n if (!id) return; // population/filter-addressed update — no single stored row to compare against here\n const repository = this.repositoriesRegistry.getRepository(this.resourceConfiguration.resourceIdentifier as ResourceType);\n if (!repository || typeof (repository as any).read !== 'function') return;\n try {\n const readResult = await (repository as any).read(executionContext, id, options);\n stored = (readResult && typeof readResult === 'object' && !Array.isArray(readResult)) ? readResult : undefined;\n } catch {\n return; // an unreadable target fails the update itself downstream (404); do not mask that here\n }\n if (!stored) return;\n }\n\n const forbiddenFields = filterChangedReadOnlyFields(candidateFields, inputRecord, stored);\n if (forbiddenFields.length === 0) return;\n\n throw this.buildReadOnlyFieldNotEditableError(operation, executionContext, forbiddenFields);\n }\n\n /**\n * The shared `4xx` for a client attempt to write a read-only (`.excludeFromUpdate()`) field — used by\n * both the single-row (CHANGE detected) and bulk (field PRESENT) arms of\n * {@link assertNoForbiddenReadOnlyFieldChange} so the two paths cannot drift in shape.\n */\n private buildReadOnlyFieldNotEditableError(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n forbiddenFields: string[],\n ) {\n return this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n reason: 'read_only_field_not_editable',\n resourceIdentifier: this.resourceConfiguration.resourceIdentifier,\n operationIdentifier: operation.operationIdentifier,\n forbiddenFields,\n },\n });\n }\n\n private ensureExplicitMutationTargetMatchesContext(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n coreOperation: CoreResourceOperation | undefined,\n idOrIdsOrFilter: IdOrIdsOrFilterType | undefined,\n currentObject: Record<string, unknown> | undefined,\n executionContext: ExecutionContext<any>,\n ): void {\n if (\n coreOperation !== CoreResourceOperation.READ\n && coreOperation !== CoreResourceOperation.UPDATE\n && coreOperation !== CoreResourceOperation.DELETE\n ) {\n return;\n }\n\n if (typeof idOrIdsOrFilter !== 'string' || !currentObject || !operation.resourceRelationships) {\n return;\n }\n\n const expectedSelectors: Record<string, string> = {};\n for (const candidate of getContextAddressedCompositionSingletonRelationshipCandidates(operation.resourceRelationships)) {\n const parentResourceId = this.resolveParentContextResourceId(\n candidate.parentResourceType,\n candidate.foreignKeyField,\n executionContext,\n );\n if (parentResourceId) {\n expectedSelectors[candidate.foreignKeyField] = parentResourceId;\n }\n }\n\n const associationParentRelationships = (operation.resourceRelationships.parentRelationships ?? [])\n .filter((relationship) =>\n relationship.nature === RelationshipNature.ASSOCIATION\n && relationship.jointResourceType === operation.resourceIdentifier\n && relationship.resourceType2 === operation.resourceIdentifier\n && relationship.cardinality1 === ResourceRelationshipCardinality.ONE\n && relationship.cardinality2 === ResourceRelationshipCardinality.MANY\n );\n const duplicatedParentResourceTypes = new Set(\n associationParentRelationships.map((relationship) => relationship.resourceType1)\n .filter((resourceType, _index, resourceTypes) =>\n resourceTypes.filter((candidate) => candidate === resourceType).length > 1\n )\n );\n\n // The resource's PRIMARY-SCOPE foreign key (e.g. `organizationId` on an\n // organization-scoped resource) is a LEGITIMATE single-peer addressing\n // context, NOT a partial association. A scope route nests the resource under\n // its primary scope (`/organizations/:orgId/organization-members/:id`) and\n // the explicit `_id` already addresses the row unambiguously within that\n // scope. When an association resource's primary scope COINCIDES with one of\n // its two association peers — the org↔user `organizationMembers` junction is\n // the canonical case, where `organizationId` is BOTH the primary scope AND\n // an association peer — that peer must NOT gate \"complete association\n // context\" completeness. Otherwise a scope-bounded explicit-`_id`\n // read/update/delete (and every custom op that is `resourceOperationLike:\n // UPDATE`, e.g. promote/demote/suspend) fails closed merely because the\n // OTHER, non-primary peer (`userId`) is absent from the route — even though\n // the primary-scope peer is still validated below against `currentObject`\n // and the row is uniquely addressed. Only NON-primary-scope peers gate\n // completeness; the primary-scope peer is always validated (it stays in\n // `expectedSelectors`) but never requires its sibling peer to be present.\n const primaryScopeFieldIdentifier = operation.resourcePrimaryScope\n ? PRIMARY_SCOPE_TO_FIELD_IDENTIFIER[operation.resourcePrimaryScope]\n : undefined;\n\n let resolvedAssociationContextCount = 0;\n let nonPrimaryScopeAssociationParentCount = 0;\n let resolvedNonPrimaryScopeAssociationContextCount = 0;\n const associationForeignKeyFields = associationParentRelationships.map((relationship) =>\n this.resourcesRegistry.resolveForeignKeyField({\n resourceType1: relationship.resourceType1,\n foreignKeyField: relationship.foreignKeyField,\n })\n );\n\n for (const relationship of associationParentRelationships) {\n const foreignKeyField = this.resourcesRegistry.resolveForeignKeyField({\n resourceType1: relationship.resourceType1,\n foreignKeyField: relationship.foreignKeyField,\n });\n const isPrimaryScopePeer =\n primaryScopeFieldIdentifier !== undefined\n && foreignKeyField === primaryScopeFieldIdentifier;\n if (!isPrimaryScopePeer) {\n nonPrimaryScopeAssociationParentCount += 1;\n }\n const parentResourceId = this.resolveAssociationParentContextResourceId(\n relationship.resourceType1,\n foreignKeyField,\n executionContext,\n { allowGenericParentContext: !duplicatedParentResourceTypes.has(relationship.resourceType1) },\n );\n if (parentResourceId) {\n resolvedAssociationContextCount += 1;\n if (!isPrimaryScopePeer) {\n resolvedNonPrimaryScopeAssociationContextCount += 1;\n }\n expectedSelectors[foreignKeyField] = parentResourceId;\n }\n }\n\n if (\n associationParentRelationships.length > 0\n && associationParentRelationships.length !== 2\n && resolvedAssociationContextCount > 0\n ) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operation: coreOperation,\n id_or_ids_or_filter: idOrIdsOrFilter,\n reason: 'Explicit association id has malformed complete-association metadata',\n parentResourceTypes: associationParentRelationships.map((relationship) => relationship.resourceType1),\n resolvedAssociationContextCount,\n },\n });\n }\n\n // Fail closed ONLY for a genuinely partial association context: some — but\n // not all — of the NON-primary-scope peers are present. A primary-scope-only\n // context (the common `/organizations/:orgId/organization-members/:id` route)\n // is NOT partial — the primary-scope peer is validated against `currentObject`\n // below and the explicit `_id` uniquely addresses the row, so it falls\n // through to the per-selector validation. When the resource has no\n // primary-scope peer, `nonPrimaryScopeAssociationParentCount` equals the full\n // peer count, preserving the original all-or-nothing fail-closed behavior.\n if (\n associationParentRelationships.length === 2\n && resolvedNonPrimaryScopeAssociationContextCount > 0\n && resolvedNonPrimaryScopeAssociationContextCount < nonPrimaryScopeAssociationParentCount\n ) {\n throw this.errorBuilder.buildError(ErrorType.NOT_FOUND, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: {\n operation: coreOperation,\n id_or_ids_or_filter: idOrIdsOrFilter,\n reason: 'Explicit association id is scoped by only part of a complete association context',\n expectedForeignKeyFields: associationForeignKeyFields,\n },\n });\n }\n\n for (const [foreignKeyField, expectedValue] of Object.entries(expectedSelectors)) {\n const actualValue = stringifyPersistedValueForCompare(currentObject[foreignKeyField]);\n if (actualValue !== expectedValue) {\n throw this.errorBuilder.buildError(ErrorType.NOT_FOUND, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: {\n operation: coreOperation,\n id_or_ids_or_filter: idOrIdsOrFilter,\n foreignKeyField,\n missingForeignKey: actualValue === undefined,\n },\n });\n }\n }\n }\n\n /**\n * The ONE canonical \"is this dispatch a BULK update?\" discriminant, shared by everything that must\n * branch on it — the read-only-field write guard and the bulk-hook object-context check.\n *\n * A `haveBulkOperation` variant reaches the persistence switch as `coreOperation === UPDATE` with\n * `isBulkOperation === true` (its `operationIdentifier` is `UPDATE`, so\n * `getCoreResourceOperationFromOperation` returns `UPDATE`); a plain / relationship `UPDATE_MANY`\n * reaches it as `coreOperation === UPDATE_MANY`. BOTH are bulk. Keeping this in one method is\n * deliberate: the read-only guard once re-derived it inline and covered only the `UPDATE_MANY` case,\n * so the guard silently skipped the `haveBulkOperation` path — the sibling-call-site drift\n * `.claude/rules/invariant-call-site-enumeration.md` #8 is written to prevent.\n */\n private isBulkUpdateCoreOperation(\n coreOperation: CoreResourceOperation | undefined,\n isBulkOperation: boolean | undefined,\n ): boolean {\n return coreOperation === CoreResourceOperation.UPDATE_MANY\n || (coreOperation === CoreResourceOperation.UPDATE && isBulkOperation === true);\n }\n\n private assertBulkHookObjectContextAvailability(\n coreOperation: CoreResourceOperation | undefined,\n isBulkOperation: boolean | undefined,\n fn: ResourceConfiguration_FunctionWithContextNeeds<any> | undefined,\n currentObject: any,\n executionContext: ExecutionContext<any>,\n operationIdentifier: string,\n hookName: 'enabledCondition' | 'basicPrefixOperation'\n ): void {\n if (!this.isBulkUpdateCoreOperation(coreOperation, isBulkOperation)) {\n return;\n }\n\n const needs = extractFunctionContextNeeds(fn);\n if (!needs.needsObjectContext || currentObject) {\n return;\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.AUTHORIZATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_DISABLED,\n context: {\n reason: `${hookName} requires object context, but this bulk update cannot provide a single persisted current object`,\n operationIdentifier,\n },\n }\n );\n }\n\n\n private initializeOperationsMap(): void {\n if (!this.resourceConfiguration.operations) {\n return;\n }\n\n // Include operations that should be handled by services\n const serviceOperations = this.resourceConfiguration.operations.filter(\n (op): op is ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> =>\n op.variantType === ResourceOperationVariantType.INTERNAL_CALL ||\n op.variantType === ResourceOperationVariantType.API_CALL ||\n op.variantType === ResourceOperationVariantType.CRON_JOB ||\n op.variantType === ResourceOperationVariantType.BATCH_JOB\n );\n\n serviceOperations.forEach(operation => {\n const operationKey = ResourcesConfig_OperationPathUtils.createOperationPathKeyFromOperation(operation as any);\n this.operationsMap.set(operationKey, operation);\n });\n\n this.logDebug('Service operations map initialized', {\n totalOperations: this.resourceConfiguration.operations.length,\n serviceOperations: serviceOperations.length\n });\n }\n\n\n\n\n /**\n * Entry point from registry convenience methods (`create`, `update`, `delete`, etc.)\n * and controller-level `doByOperationPath`.\n *\n * Resolves `operation` from this handler's `operationsMap`. The caller's\n * `executionContext.operation` may point to a DIFFERENT operation (e.g., a parent's\n * operation or a generic webhook operation). `doOperation()` corrects this mismatch\n * via Correction Point 1 before any pipeline logic executes.\n */\n public async doByOperationPath(\n operationPath: ResourceConfiguration_OperationPath<TCustomOperationEnum, TCoreOperationEnum>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: any,\n options?: RepositoryOptions\n ): Promise<any> {\n const operationKey = ResourcesConfig_OperationPathUtils.createOperationPathKey(operationPath);\n const operation = this.operationsMap.get(operationKey);\n\n if (!operation) {\n const error = this.errorBuilder.buildError(\n ErrorType.NOT_FOUND,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Requested service operation path is not registered for this resource service.',\n resourceType: this.resourceConfiguration.resourceIdentifier,\n operationPath,\n operationKey,\n id_or_ids_or_filter,\n },\n }\n );\n throw error;\n }\n\n this.logDebug('Executing operation by path', {\n operationPath,\n operationKey,\n resourceType: this.resourceConfiguration.resourceIdentifier,\n id_or_ids_or_filter\n });\n\n return this.doOperation(operation, executionContext, id_or_ids_or_filter, data, options);\n }\n\n\n /**\n * Entry point from controller-level `doByExecutionContext`.\n *\n * Reads `operation` directly from `executionContext.operation` — guaranteed to match\n * (same object reference). `doOperation()` correction points are no-ops in this path.\n * Context-addressed singleton / complete-association resolution is deliberately\n * USER_REQUEST-only. Internal contexts must already carry the concrete\n * persisted child/junction id; they are not allowed to reinterpret parent\n * context as mutation identity.\n */\n public async doByExecutionContext(\n executionContext: ExecutionContext<ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>>,\n data?: any,\n options?: RepositoryOptions\n ): Promise<any> {\n const operation = executionContext.operation;\n\n // Extract IDs based on resourceFieldIdentifier from execution context\n const id_or_ids_or_filter = this.repositoryHelper.extractIdsFromExecutionContext(executionContext, this.resourceConfiguration.resourceFieldIdentifier);\n\n this.logDebug('Executing operation by execution context', {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n operationIdentifier: operation.operationIdentifier,\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 public resolveOperationForDataMode(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n dataMode: DataMode | undefined,\n ): ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> {\n if (!dataMode || dataMode === DataMode.RAW) {\n return operation;\n }\n\n return this.resolveOperationVariant(operation, dataMode);\n }\n\n /**\n * Helper method to fetch contexts for operation functions (enabledCondition, basicPrefixOperation).\n * Fetches objectContext and userContext only when needed based on function flags.\n *\n * @param fn - Function with optional context needs flags\n * @param resourceType - Resource type for context fetching\n * @param currentObject - Current object (fetched if needed for UPDATE/DELETE)\n * @param executionContext - Execution context\n * @returns Object with objectContext, userContext, and resolved currentObject\n */\n private async fetchContextsForOperationFunction(\n fn: ResourceConfiguration_FunctionWithContextNeeds<any> | undefined,\n resourceType: ResourceType,\n currentObject: any,\n executionContext: ExecutionContext<any>,\n repositoryOptions?: RepositoryOptions,\n ): Promise<{ objectContext?: any; initiatorUserContext?: any; currentObject: any }> {\n const needs = extractFunctionContextNeeds(fn);\n let objectContext: any = undefined;\n let initiatorUserContext: any = undefined;\n\n if (needs.needsObjectContext) {\n const resourceNeeds = this.populationService.analyzeContextNeeds(resourceType);\n const computationContext = await this.populationService.fetchComputationContext(\n resourceType,\n currentObject || {},\n resourceNeeds,\n executionContext,\n repositoryOptions,\n ComputationContextFailureMode.PROPAGATE,\n );\n objectContext = computationContext.objectContext;\n }\n\n // Initiator user context — provided UNCONDITIONALLY (not gated on\n // `needs.needsUserContext`), mirroring the frontend evaluator which always\n // injects `initiatorUserContext` when a user is present\n // (`operation-enabled-condition.frontend.utils.ts`). Two bugs converged here\n // before this:\n //\n // 1. Phantom read: `ExecutionContext` has NO `.user` property (identity is\n // exposed as `executionContext.userId`, from `initiatorIds.userId`). The\n // former `(executionContext as any).user` cast resolved to `undefined`\n // on every request, so `initiatorUserContext?._id` was always undefined.\n // 2. Gating asymmetry: the backend only populated it when the operation\n // function carried a manually-attached `needsUserContext = true` flag,\n // while the frontend supplies it ungated.\n //\n // Together they made any owner-scoped condition (e.g. todos `change_status`\n // member variant: `currentObject.assignedToUserId === initiatorUserContext?._id`)\n // pass on the frontend (button shown enabled) yet fail on the backend\n // (`service_resource_operation_disabled` → 403) — the exact \"shown but\n // blocked\" divergence. The initiator identity is already on the execution\n // context (no fetch), so the `needsUserContext` gate was a pure footgun for\n // this axis and is removed; `needsUserContext` still governs only the\n // (fetch-bearing) object-context path above.\n const initiatorUserId = executionContext.userId;\n if (initiatorUserId) {\n initiatorUserContext = {\n _id: initiatorUserId,\n roles: executionContext.initiatorRoles,\n };\n }\n\n return { objectContext, initiatorUserContext, currentObject };\n }\n\n /**\n * Fetch current object for UPDATE/DELETE operations.\n * For CREATE operations, returns undefined (object doesn't exist yet).\n *\n * @param coreOperation - The core operation type\n * @param resourceType - Resource type\n * @param id_or_ids_or_filter - ID or filter\n * @param executionContext - Execution context\n * @returns Current object or undefined for CREATE\n */\n private async fetchCurrentObjectForOperation(\n coreOperation: CoreResourceOperation | undefined,\n resourceType: ResourceType,\n id_or_ids_or_filter: IdOrIdsOrFilterType | undefined,\n executionContext: ExecutionContext<any>,\n repositoryOptions?: RepositoryOptions,\n ): Promise<any> {\n const isCreateOperation = coreOperation === CoreResourceOperation.CREATE ||\n coreOperation === CoreResourceOperation.CREATE_MANY;\n\n // For CREATE operations, currentObject is undefined (object doesn't exist yet)\n if (isCreateOperation) {\n return undefined;\n }\n\n const singleSelectedId = this.resolveSingleSelectedId(id_or_ids_or_filter);\n\n // For UPDATE/DELETE/READ operations, fetch current object if we have exactly one ID\n if (singleSelectedId) {\n try {\n const repo = this.repositoriesRegistry.getRepository(resourceType);\n if (repo && 'read' in repo) {\n const readResult = await (repo as any).read(\n executionContext,\n singleSelectedId,\n repositoryOptions,\n );\n return Array.isArray(readResult) ? readResult[0] : readResult;\n }\n } catch (error) {\n // Read failures are terminal for single-target mutations. Returning\n // undefined here made downstream hooks/conditions see a fabricated\n // \"no current object\" state while the repository read had actually\n // failed (for example NOT_FOUND or adapter errors).\n this.logDebug('Failed to fetch current object for operation', {\n resourceType,\n id: singleSelectedId,\n error: describeCaughtError(error)\n });\n throw error;\n }\n }\n\n // Fallback: return undefined if we can't determine the object\n return undefined;\n }\n\n private static readonly STEP_UP_EXEMPT_OPERATIONS = new Set([\n CoreResourceOperation.READ,\n CoreResourceOperation.LIST,\n CoreResourceOperation.SEARCH,\n CoreResourceOperation.COUNT,\n ]);\n\n /**\n * W7.1: Enforces step-up re-authentication for sensitive (mutating) operations.\n *\n * Two independent triggers, both satisfied by the SAME proof (a single-use `REAUTH` consumable\n * token in `X-Reauth-Token`, minted by `POST /auth/reauth`):\n *\n * - **Per-user-type freshness policy** (`UserTypeAuthPolicy.stepUpAuth`) — opt-in, off by\n * default, challenges only once `lastAuthenticatedAt` is older than `maxAgeSeconds`.\n * - **Per-operation requirement** (`requiresStepUpAuthentication`) — UNCONDITIONAL for that one\n * operation, and deliberately independent of the policy above: it applies even when the user\n * type declares no `stepUpAuth` at all, and it ignores freshness. An irreversible action wants\n * proof *now*, not proof that the session is younger than five minutes.\n *\n * Skip conditions (all must be false for either trigger to apply):\n * 1. Non-user requests (INTERNAL_CALL, API_KEY, etc.) — exempt, no interactive credential exists\n * 2. Worker executions — already authorized at queue time\n * 3. Sub-calls (subCallDepth > 0) — parent already passed step-up\n * 4. Read-only operations (READ, LIST, SEARCH, COUNT) — exempt\n *\n * A principal with no resolvable `activeUserType` is exempt from the FRESHNESS policy (there is no\n * policy to read) but NOT from a per-operation requirement — the requirement is a property of the\n * operation, and letting an unresolved user type waive it would make the gate depend on\n * configuration completeness. Fail closed.\n *\n * Failing either trigger throws STEP_UP_REQUIRED (HTTP 403); the frontend HTTP client catches that\n * status, obtains a token through its registered step-up handler, and replays the request.\n */\n private async enforceStepUpAuth(\n coreOperation: CoreResourceOperation | null,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n operation?: ResourceConfiguration_Operation<any, any, any>,\n ): Promise<void> {\n if (executionContext.executionType !== ExecutionContext_ExecutionType.USER_REQUEST) return;\n if (options?.isWorkerExecution) return;\n if (executionContext.subCallDepth > 0) return;\n if (coreOperation && ServiceResourceBackendService.STEP_UP_EXEMPT_OPERATIONS.has(coreOperation)) return;\n\n const operationRequiresStepUp = operation?.requiresStepUpAuthentication === true;\n\n const activeUserType = executionContext.activeUserType;\n const authPolicy = activeUserType\n ? this.appConfigService.getUserTypeAuthPolicy(activeUserType)\n : undefined;\n const stepUpConfig = authPolicy?.stepUpAuth;\n\n // Neither trigger fires → nothing to enforce.\n if (!operationRequiresStepUp && !stepUpConfig?.enabled) return;\n\n // Freshness can satisfy the POLICY trigger, but never the per-operation one.\n if (!operationRequiresStepUp) {\n const lastAuthAt = executionContext.lastAuthenticatedAt ?? 0;\n const nowSeconds = Math.floor(Date.now() / 1000);\n if (nowSeconds - lastAuthAt <= stepUpConfig!.maxAgeSeconds) return;\n }\n\n const reAuthTokenValue = executionContext.reAuthTokenValue;\n if (reAuthTokenValue) {\n try {\n const consumed = await this.consumableTokenService.consumeToken(reAuthTokenValue);\n if (consumed.tokenType === CoreConsumableTokenTypes.REAUTH\n && consumed.userId === executionContext.initiatorIds.userId) {\n return;\n }\n } catch (err: unknown) {\n if (isWildoBackendError(err)) {\n this.logDebug('Re-auth token consumption failed', { error: err.customMessageReference });\n }\n }\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.AUTHORIZATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.STEP_UP_REQUIRED,\n context: {\n // Which trigger refused, so an operator reading the log knows whether to look at the\n // user-type policy or at the operation declaration.\n reason: operationRequiresStepUp\n ? 'operation_requires_step_up_authentication'\n : 'authentication_older_than_user_type_max_age',\n ...(operationRequiresStepUp\n ? { operationIdentifier: operation?.operationIdentifier, resourceIdentifier: operation?.resourceIdentifier }\n : { maxAgeSeconds: stepUpConfig!.maxAgeSeconds }),\n },\n },\n );\n }\n\n /**\n * Ask the registered conflict resolvers for one explicit framework action.\n *\n * Resolvers run only after an owned transaction has aborted. A reconciled\n * winner takes precedence immediately; otherwise one or more retry requests\n * collapse into the framework's single bounded retry. Runtime validation is\n * retained because application-owned implementations can bypass TypeScript.\n */\n private async resolveTransactionalCoreConflict(\n error: unknown,\n originalCoreInput: unknown,\n executionContext: ExecutionContext<any>,\n operation: ResourceConfiguration_Operation<any, any, any>,\n customImplUtils: ResourceOperation_CustomImplementation_Utils,\n conflictResolvers: readonly ResourceCustomServiceImplementationTransactionalCoreConflictResolver[],\n ): Promise<ResourceCustomServiceImplementationTransactionalCoreConflictResolution> {\n let retryTransactionRequested = false;\n\n for (const resolveConflict of conflictResolvers) {\n const resolution: unknown = await resolveConflict(\n error,\n cloneResourceTransactionAttemptInput(originalCoreInput),\n executionContext,\n customImplUtils,\n );\n if (\n !resolution\n || typeof resolution !== 'object'\n || !('action' in resolution)\n ) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n context: {\n reason: 'transactional_core_conflict_resolver_returned_invalid_resolution',\n resourceType: operation.resourceIdentifier,\n operationIdentifier: operation.operationIdentifier,\n },\n },\n );\n }\n\n switch (resolution.action) {\n case ResourceCustomServiceImplementationTransactionalCoreConflictAction.RECONCILED:\n if (!('value' in resolution) || resolution.value === undefined) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n context: {\n reason: 'transactional_core_conflict_resolver_reconciled_without_value',\n resourceType: operation.resourceIdentifier,\n operationIdentifier: operation.operationIdentifier,\n },\n },\n );\n }\n return Object.freeze({\n action: ResourceCustomServiceImplementationTransactionalCoreConflictAction.RECONCILED,\n value: resolution.value,\n });\n case ResourceCustomServiceImplementationTransactionalCoreConflictAction.RETRY_TRANSACTION:\n retryTransactionRequested = true;\n break;\n case ResourceCustomServiceImplementationTransactionalCoreConflictAction.UNHANDLED:\n break;\n default:\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n context: {\n reason: 'transactional_core_conflict_resolver_returned_unknown_action',\n resourceType: operation.resourceIdentifier,\n operationIdentifier: operation.operationIdentifier,\n conflictResolutionAction: resolution.action,\n },\n },\n );\n }\n }\n\n return Object.freeze({\n action: retryTransactionRequested\n ? ResourceCustomServiceImplementationTransactionalCoreConflictAction.RETRY_TRANSACTION\n : ResourceCustomServiceImplementationTransactionalCoreConflictAction.UNHANDLED,\n });\n }\n\n /**\n * Own the resource-operation transaction boundary without knowing how one\n * core attempt is implemented or how a reconciled winner is materialized.\n *\n * Database-driver callback retries remain inside `executeTransaction`.\n * Conflict-resolver retries remain outside it and are bounded to one complete\n * replay. Caller-owned transactions are never reconciled here because only\n * their root owner can restart an aborted native transaction.\n */\n private async executeTransactionalCoreBoundary(execution: ResourceOperationTransactionalCoreBoundaryExecution): Promise<ResourceOperationCoreBoundaryResult> {\n const transactionPersistenceRequest = execution.persistenceContract.request;\n if (\n !transactionPersistenceRequest\n || !this.resourcePersistenceUnitOfWork\n ) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n execution.executionContext,\n {\n context: {\n reason: 'resource_operation_transaction_coordinator_unavailable',\n resourceType: execution.operation.resourceIdentifier,\n operationIdentifier: execution.operation.operationIdentifier,\n hasPersistenceRequest: Boolean(transactionPersistenceRequest),\n hasUnitOfWorkService: Boolean(this.resourcePersistenceUnitOfWork),\n },\n },\n );\n }\n\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n const committed =\n await this.resourcePersistenceUnitOfWork.executeTransaction(\n transactionPersistenceRequest,\n execution.executeAttempt,\n execution.baseOptions,\n {\n requiresRootOwnership: execution.requiresRootOwnership,\n },\n );\n return Object.freeze({\n state: committed.state,\n inputData: committed.inputData,\n terminalCustomImplUtils: committed.terminalCustomImplUtils,\n transactionalCoreConflictReconciled: false,\n transactionallyPreparedTokenGenerationResult:\n committed.tokenGenerationResult,\n frameworkPostCommitRegisteredTransactionally: true,\n consumableTokenConsumedTransactionally:\n committed.consumedIncomingToken,\n transactionallyPreparedOutput: Object.freeze({\n value: committed.transformedState,\n }),\n });\n } catch (error) {\n const isConflict =\n isWildoBackendError(error)\n && error.statusCode === 409;\n if (\n !isConflict\n || execution.conflictResolvers.length === 0\n || execution.baseOptions?.transaction\n ) {\n throw error;\n }\n\n const conflictResolution =\n await this.resolveTransactionalCoreConflict(\n error,\n execution.originalCoreInput,\n execution.executionContext,\n execution.operation,\n execution.customImplUtils,\n execution.conflictResolvers,\n );\n if (conflictResolution.action === ResourceCustomServiceImplementationTransactionalCoreConflictAction.RECONCILED) {\n const reconciled = await execution.resolveReconciledResult(conflictResolution.value);\n return Object.freeze({\n state: reconciled.state,\n inputData: reconciled.inputData,\n terminalCustomImplUtils: reconciled.terminalCustomImplUtils,\n transactionalCoreConflictReconciled: true,\n transactionallyPreparedTokenGenerationResult:\n reconciled.tokenGenerationResult,\n frameworkPostCommitRegisteredTransactionally: false,\n consumableTokenConsumedTransactionally: false,\n });\n }\n if (\n conflictResolution.action !== ResourceCustomServiceImplementationTransactionalCoreConflictAction.RETRY_TRANSACTION\n || attempt === 1\n ) {\n throw error;\n }\n }\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n execution.executionContext,\n {\n context: {\n reason: 'transactional_core_boundary_completed_without_result',\n resourceType: execution.operation.resourceIdentifier,\n operationIdentifier: execution.operation.operationIdentifier,\n },\n },\n );\n }\n\n /**\n * Terminal hooks run after a framework-owned root transaction has\n * completed. Never expose its completed native transaction through\n * `utils.serviceOptions`; retain every other option and the successful\n * callback-attempt context snapshot.\n */\n private createTerminalCustomImplUtils(source: ResourceOperation_CustomImplementation_Utils): ResourceOperation_CustomImplementation_Utils {\n const terminalServiceOptions = source.serviceOptions\n ? { ...source.serviceOptions }\n : undefined;\n if (terminalServiceOptions) {\n delete terminalServiceOptions.transaction;\n }\n return {\n ...source,\n serviceOptions: terminalServiceOptions,\n };\n }\n\n /**\n * Dispatch the framework-owned persistence operation for one core attempt.\n *\n * Custom PREFIX/REPLACE/POSTFIX hooks stay outside this method so their\n * authored ordering remains visible in the core phase.\n */\n private async executeCorePersistenceOperation(execution: ResourceOperationCorePersistenceExecution): Promise<any> {\n const {\n operation,\n operationPath,\n coreOperation,\n executionContext,\n target,\n inputData,\n currentObject,\n options,\n } = execution;\n\n if (operation.generatedOperation?.kind === ResourceGeneratedOperationKind.GENERATED_FILE_REGENERATE) {\n return this.executeGeneratedFileRegenerateOperation(\n operation,\n operation.generatedOperation.fieldName,\n executionContext,\n target,\n currentObject,\n options,\n );\n }\n\n // The read-only-field guard's bulk flag, from the ONE canonical discriminant (see\n // `isBulkUpdateCoreOperation`). Both the UPDATE case (a `haveBulkOperation` variant) and the\n // UPDATE_MANY case are bulk; computing it here means the two guard call sites cannot drift — the\n // drift that let the guard silently skip the `haveBulkOperation` path.\n const isBulkUpdate = this.isBulkUpdateCoreOperation(\n coreOperation,\n 'isBulkOperation' in operation ? operation.isBulkOperation : undefined,\n );\n\n switch (coreOperation) {\n // NO read-only-field guard on CREATE / CREATE_MANY, deliberately — do not add one by symmetry with\n // the UPDATE cases below. A `.excludeFromCreate()` field a client sends is SILENTLY STRIPPED by the\n // strict request DTO, and that is the intended mass-assignment-protection contract, pinned by\n // `resource-validation-matrix.e2e.ts` V-14a (\"create with unknown fields → 201, strict-DTO strips\").\n // The UPDATE guard exists because CHANGING an EXISTING immutable field to a new value and answering\n // 2xx is a false success on live data (the `users.status` → magic-link cascade). CREATE has no such\n // hazard: there is no stored value to falsely \"change\", and every `.excludeFromCreate()` field is\n // server-owned (createdAt/updatedAt, `_id`, context-injected FKs, a defaulted status) whose SERVER\n // value is the correct one — so stripping the client's value is right, not a silent defect. Making\n // create refuse-on-presence would be a stricter SECURITY POSTURE, not a bug fix, and would contradict\n // V-14a. Decision recorded 2026-08-11 (see memory `create-side-strip-is-intended-not-a-defect`).\n case CoreResourceOperation.CREATE:\n return this.create(\n operation,\n executionContext,\n inputData,\n options,\n );\n case CoreResourceOperation.CREATE_MANY:\n return this.createMany(\n operation,\n executionContext,\n inputData,\n options,\n );\n case CoreResourceOperation.READ:\n return this.read(\n operation,\n executionContext,\n target,\n options,\n );\n case CoreResourceOperation.UPDATE:\n // Refuse an update that tries to CHANGE a read-only field instead of silently 2xx-ing it.\n //\n // A `haveBulkOperation` variant reaches THIS case, not UPDATE_MANY: its `operationIdentifier` is\n // `UPDATE`, so `getCoreResourceOperationFromOperation` returns `UPDATE` and the bulk-ness rides on\n // the operation's `isBulkOperation` flag (the canonical predicate — see `isBulkUpdateOperation`).\n // That is the ACTUAL working bulk-update mechanism (todos `change_status`/`assign`, org-features,\n // …); a plain core UPDATE_MANY reaching the sibling case below is the rarer INTERNAL_CALL form. So\n // the guard must key on `isBulkOperation` here, or the bulk path stays a silent no-op — the exact\n // sibling-call-site miss `.claude/rules/invariant-call-site-enumeration.md` #8 is written for.\n // Single (isBulk=false): compare to the stored row, an echo is allowed. Bulk: refuse on PRESENCE.\n await this.assertNoForbiddenReadOnlyFieldChange(\n operation, target, inputData, currentObject, executionContext, options, isBulkUpdate,\n );\n return this.update(\n operation,\n executionContext,\n target,\n inputData,\n options,\n );\n case CoreResourceOperation.UPDATE_MANY:\n // The other bulk site: a core UPDATE_MANY (operationIdentifier IS UPDATE_MANY — the INTERNAL_CALL\n // retention-scrub form). `isBulkUpdate` is `true` here (same canonical discriminant); no single\n // stored row exists, so `currentObject` is not passed.\n await this.assertNoForbiddenReadOnlyFieldChange(operation, target, inputData, undefined, executionContext, options, isBulkUpdate);\n return this.updateMany(\n operation,\n executionContext,\n target,\n inputData,\n options,\n );\n case CoreResourceOperation.DELETE:\n return this.delete(\n operation,\n executionContext,\n target,\n options,\n );\n case CoreResourceOperation.DELETE_MANY:\n return this.deleteMany(\n operation,\n executionContext,\n target,\n options,\n );\n case CoreResourceOperation.LIST:\n return this.list(\n operation,\n executionContext,\n inputData?.filter as FilterQuery<any>,\n {\n page: inputData?.page,\n limit: inputData?.limit,\n sort: inputData?.sort,\n },\n options,\n );\n case CoreResourceOperation.COUNT:\n return this.count(\n operation,\n executionContext,\n inputData?.filter as FilterQuery<any>,\n options,\n );\n case CoreResourceOperation.SEARCH:\n return this.search(\n operation,\n executionContext,\n inputData?.searchQuery ?? '',\n inputData?.filter as FilterQuery<any>,\n {\n ...(options ?? {}),\n searchOptions: {\n page: inputData?.page,\n limit: inputData?.limit,\n sort: inputData?.sort,\n },\n } as ServiceOptions & {\n searchOptions: {\n page?: number;\n limit?: number;\n sort?: Record<string, 1 | -1>;\n };\n },\n );\n default:\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference:\n ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operationIdentifier: operation.operationIdentifier,\n operationPath,\n },\n },\n );\n }\n }\n\n /**\n * Execute PREFIX, framework persistence, REPLACE, and POSTFIX for one core\n * attempt.\n *\n * The caller supplies either the preflight state snapshot or, when a native\n * transaction is present, a refresher that re-reads and re-validates that\n * state inside the exact database-driver callback attempt.\n */\n private async executeCorePhase(execution: ResourceOperationCorePhaseExecution): Promise<ResourceOperationCorePhaseResult> {\n const {\n operation,\n operationPath,\n coreOperation,\n resourceType,\n executionContext,\n target,\n customImplUtils,\n customImplRegistrations,\n customImplPlaceholders,\n } = execution;\n const operationIdentifier = operation.operationIdentifier;\n let coreOptions = execution.options;\n let coreInput = execution.inputData;\n let coreState: any;\n let coreContext = execution.preflightContext;\n\n if (coreOptions?.transaction) {\n coreContext = await execution.refreshTransactionalContext(\n coreInput,\n coreOptions,\n );\n }\n\n const {\n currentObject: coreCurrentObject,\n hookCurrentObject: coreHookCurrentObject,\n computationContext: coreComputationContext,\n } = coreContext;\n const coreCustomImplUtils: ResourceOperation_CustomImplementation_Utils = {\n ...customImplUtils,\n serviceOptions: coreOptions,\n objectContext: {\n parents: coreComputationContext.objectContext?.parents || {},\n children: coreComputationContext.objectContext?.children || {},\n },\n initiatorUserContext: coreComputationContext.userContext,\n currentObject: coreHookCurrentObject,\n };\n\n // Snapshot the payload keys before any trusted prefix runs. Only fields\n // added after this point can be forwarded through strict request parsing as\n // server-injected persistence fields.\n const payloadKeysBeforePrefix =\n coreInput\n && typeof coreInput === 'object'\n && !Array.isArray(coreInput)\n ? new Set(Object.keys(coreInput))\n : null;\n\n // Fields a trusted hook DECLARES it owns, preserved regardless of the snapshot above.\n //\n // The added-key diff alone is not sufficient. It infers authorship from \"this key was not in\n // the payload\", but the snapshot is taken HERE — at the service tier, after a LOOSE parse\n // (`z.looseObject`) that passes unknown keys through. A caller that reaches this tier with the\n // field already present (MCP `callTool` forwards its arguments with no strict parse) puts the\n // key into `payloadKeysBeforePrefix`; the hook's own value is then not classified as injected,\n // the repository's strict `requestDto` re-parse strips it, and the operation answers success\n // having written nothing — the exact silent-no-op class the unimplemented-operation guard\n // exists to eliminate, reintroduced through the mechanism meant to fix it.\n //\n // An explicit declaration removes the inference. The value preserved is always the POST-hook\n // value (see `preserveServerInjectedFields`), so a caller-supplied value is overwritten rather\n // than honored, and client reachability of the field is unchanged — that stays governed by the\n // operation's `requestDto` and the schema decorators.\n const authoritativeFieldNames = new Set<string>();\n const declareAuthoritativeFields = (fields: readonly string[] | undefined): void => {\n for (const field of fields ?? []) authoritativeFieldNames.add(field);\n };\n\n if ('authoritativeFields' in operation) {\n // Config-level declaration, for `basicPrefixOperation` — which is authored on the operation\n // variant rather than through a custom-implementation registration and has no other place to\n // declare what it owns.\n declareAuthoritativeFields(\n (operation as { authoritativeFields?: readonly string[] }).authoritativeFields,\n );\n }\n\n if (\n 'basicPrefixOperation' in operation\n && operation.basicPrefixOperation\n ) {\n this.assertBulkHookObjectContextAvailability(\n coreOperation,\n 'isBulkOperation' in operation ? operation.isBulkOperation : false,\n operation.basicPrefixOperation,\n coreCurrentObject,\n executionContext,\n operationIdentifier,\n 'basicPrefixOperation',\n );\n\n const { objectContext, initiatorUserContext } =\n await this.fetchContextsForOperationFunction(\n operation.basicPrefixOperation,\n resourceType,\n coreCurrentObject,\n executionContext,\n coreOptions,\n );\n const inputAdding = operation.basicPrefixOperation({\n inputDto: coreInput,\n currentObject: coreHookCurrentObject,\n objectContext,\n initiatorUserContext,\n initiatorIds: executionContext.initiatorIds,\n });\n\n if (inputAdding && typeof inputAdding === 'object'\n && !Array.isArray(inputAdding)\n ) {\n coreInput = { ...coreInput, ...inputAdding };\n }\n }\n\n if (\n customImplPlaceholders.has(\n ResourceOperation_CustomServiceImplementationMode.PREFIX_CORE_OPERARTIONS,\n )\n ) {\n const prefixRegistrations =\n this.customImplRegistry.resolveRegistrationsForMode(\n customImplRegistrations,\n ResourceOperation_CustomServiceImplementationMode.PREFIX_CORE_OPERARTIONS,\n this.logger,\n );\n for (const registration of prefixRegistrations) {\n declareAuthoritativeFields(registration.authoritativeFields);\n const prefixResult =\n await registration.implementation.prefixCoreOperations(\n target as any,\n coreInput,\n executionContext,\n coreCustomImplUtils,\n );\n if (Array.isArray(coreInput)) {\n if (Array.isArray(prefixResult)) {\n coreInput = prefixResult;\n } else {\n this.logDebug(\n `[CustomImpl] PREFIX handler [${registration.debugLabel}] returned non-array for array input, result ignored`,\n );\n }\n } else if (prefixResult && typeof prefixResult === 'object'\n && !Array.isArray(prefixResult)\n ) {\n coreInput = { ...coreInput, ...prefixResult };\n } else if (prefixResult !== undefined && prefixResult !== null) {\n this.logDebug(\n `[CustomImpl] PREFIX handler [${registration.debugLabel}] returned non-object (${typeof prefixResult}), result ignored`,\n );\n }\n }\n }\n\n // Client-supplied keys were present before the prefixes and are never whitelisted. Only fields\n // INTRODUCED by trusted hooks — or explicitly DECLARED as owned by one via\n // `authoritativeFields` — are preserved. See `resolveServerInjectedFieldAllowList` for why the\n // introduced-key rule alone is not sufficient.\n if (payloadKeysBeforePrefix && coreInput\n && typeof coreInput === 'object'\n && !Array.isArray(coreInput)\n ) {\n const injectedFields = resolveServerInjectedFieldAllowList({\n payloadKeysBeforePrefix,\n postPrefixPayloadKeys: Object.keys(coreInput),\n authoritativeFields: authoritativeFieldNames,\n });\n if (injectedFields.length > 0) {\n coreOptions = {\n ...(coreOptions ?? {}),\n preserveServerInjectedFields: [\n ...(coreOptions?.preserveServerInjectedFields ?? []),\n ...injectedFields,\n ],\n };\n coreCustomImplUtils.serviceOptions = coreOptions;\n }\n }\n\n if (\n 'tokenRevocation' in operation\n && operation.tokenRevocation\n && coreCurrentObject\n ) {\n await this.consumableTokenService.processTokenRevocation(\n operation.tokenRevocation,\n coreCurrentObject,\n { organizationId: executionContext.initiatorIds?.organizationId },\n coreOptions?.transaction,\n );\n }\n\n // A REPLACE_CORE_OPERATIONS custom impl OWNS the operation and produces the\n // authoritative `coreState` below — the core persistence result is discarded.\n // We normally still run the core op (for an ENTITY replace that supplies a\n // target, its write is a tolerated near-no-op). But a COLLECTION-SCOPED custom\n // ACTION — e.g. \"retry all\" / \"purge all\", which borrows a `*_MANY` verb for its\n // id-less collection route and carries NO target selector — would make the core\n // `update`/`delete` throw `missingParameter: id_or_ids_or_filter` HERE, before\n // the replace handler ever runs. Skip the core persistence in exactly that case\n // (a replace impl is present, the core op is a target-requiring mutation, and no\n // target was resolved) so the custom handler is the sole authority. This changes\n // behavior ONLY for ops that were already unreachable (they threw at this line);\n // entity replace ops that DO supply a target are unaffected.\n const willReplaceCore = customImplPlaceholders.has(\n ResourceOperation_CustomServiceImplementationMode.REPLACE_CORE_OPERARTIONS,\n );\n const coreMutationRequiresTarget = coreOperation === CoreResourceOperation.UPDATE\n || coreOperation === CoreResourceOperation.UPDATE_MANY\n || coreOperation === CoreResourceOperation.DELETE\n || coreOperation === CoreResourceOperation.DELETE_MANY;\n const skipCorePersistenceForTargetlessReplace = willReplaceCore && coreMutationRequiresTarget && !target;\n\n coreState = skipCorePersistenceForTargetlessReplace\n ? undefined\n : await this.executeCorePersistenceOperation({\n operation,\n operationPath,\n coreOperation,\n executionContext,\n target,\n inputData: coreInput,\n currentObject: coreCurrentObject,\n options: coreOptions,\n });\n\n if (willReplaceCore) {\n const replaceWinner = this.customImplRegistry.resolveSingleOwner(\n customImplRegistrations,\n ResourceOperation_CustomServiceImplementationMode.REPLACE_CORE_OPERARTIONS,\n this.logger,\n );\n if (replaceWinner) {\n coreState = await replaceWinner.implementation.replaceCoreOperations(\n target as any,\n coreInput,\n executionContext,\n coreCustomImplUtils,\n );\n }\n }\n\n if (\n customImplPlaceholders.has(\n ResourceOperation_CustomServiceImplementationMode.POSTFIX_CORE_OPERARTIONS,\n )\n ) {\n const postfixRegistrations =\n this.customImplRegistry.resolveRegistrationsForMode(\n customImplRegistrations,\n ResourceOperation_CustomServiceImplementationMode.POSTFIX_CORE_OPERARTIONS,\n this.logger,\n );\n for (const registration of postfixRegistrations) {\n this.logDebug(\n `Executing postfixCoreOperations [${registration.debugLabel}]`,\n {\n operationIdentifier,\n currentStateKeys:\n coreState && typeof coreState === 'object'\n ? Object.keys(coreState)\n : typeof coreState,\n },\n );\n coreState = await registration.implementation.postfixCoreOperations(\n target as any,\n coreState,\n executionContext,\n coreCustomImplUtils,\n );\n }\n }\n\n return Object.freeze({\n state: coreState,\n inputData: coreInput,\n terminalCustomImplUtils:\n this.createTerminalCustomImplUtils(coreCustomImplUtils),\n });\n }\n\n private registerConsumableTokenContextMark(registration: ConsumableTokenContextMarkRegistration): void {\n registerTransactionPostCommitEffect(registration.transaction, {\n key: [\n 'consumable-token-context-mark',\n String(registration.operationPath.resourceIdentifier),\n String(registration.operationPath.operationIdentifier),\n registration.transaction.id,\n registration.occurrenceId,\n ].join(':'),\n execute: async () => {\n registration.executionContext.markConsumableTokenConsumed();\n },\n });\n }\n\n /**\n * Execute one database-driver callback attempt, including only work that must\n * commit atomically with the core resource mutation.\n */\n private async executeTransactionalCoreAttempt(\n execution: ResourceOperationTransactionalCoreAttemptExecution,\n ): Promise<ResourceOperationTransactionalCoreAttemptResult> {\n const coreResult = await execution.executeCorePhase(\n execution.optionsWithTransaction,\n cloneResourceTransactionAttemptInput(execution.originalCoreInput),\n );\n const {\n state,\n inputData,\n terminalCustomImplUtils: attemptTerminalCustomImplUtils,\n } = coreResult;\n const transformedState = state == null\n ? state\n : await this.transformOutput(\n execution.executionContext,\n state,\n execution.dataMode,\n execution.resolvedOperation,\n );\n const transaction = execution.optionsWithTransaction.transaction;\n if (!transaction) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n execution.executionContext,\n {\n context: {\n reason: 'transactional_core_missing_transaction_context',\n resourceType: execution.operation.resourceIdentifier,\n operationIdentifier: execution.operation.operationIdentifier,\n },\n },\n );\n }\n\n const tokenGenerationResult =\n execution.tokenGeneration\n && state\n ? await maybeProcessTokenGenerationForOperation(\n { consumableTokenService: this.consumableTokenService },\n execution.tokenGeneration,\n state,\n {\n organizationId:\n execution.executionContext.initiatorIds?.organizationId,\n userId: execution.executionContext.initiatorIds?.userId,\n resourceType: execution.operation.resourceIdentifier,\n },\n transaction,\n )\n : null;\n\n const incomingConsumableToken = execution.executionContext.consumableTokenValue;\n const consumedIncomingToken = Boolean(incomingConsumableToken);\n if (incomingConsumableToken) {\n await this.consumableTokenService.consumeToken(\n incomingConsumableToken,\n transaction,\n );\n this.registerConsumableTokenContextMark({\n transaction,\n operationPath: execution.operationPath,\n occurrenceId: execution.postCommitEffectOccurrenceId,\n executionContext: execution.executionContext,\n });\n }\n\n await this.scheduleFrameworkManagedPostCommitEffects({\n registeredByCoreTransaction: false,\n transaction,\n operationPath: execution.operationPath,\n occurrenceId: execution.postCommitEffectOccurrenceId,\n payload: Object.freeze({\n currentState: state,\n inputData,\n transactionallyPreparedTokenGenerationResult: tokenGenerationResult,\n transactionalCoreConflictReconciled: false,\n }),\n execute: execution.executePostCommit,\n });\n\n return Object.freeze({\n state,\n tokenGenerationResult,\n consumedIncomingToken,\n transformedState,\n inputData,\n terminalCustomImplUtils: attemptTerminalCustomImplUtils,\n });\n }\n\n /**\n * Execute framework-managed work that is outside the database rollback\n * domain.\n *\n * A nested resource operation can run inside another operation's\n * transaction. The caller must therefore invoke this phase only from an\n * immediate no-transaction path or a registered root post-commit effect.\n */\n private async executeFrameworkManagedPostCommitEffects(execution: FrameworkManagedPostCommitExecution): Promise<void> {\n const {\n payload,\n executionContext,\n operation,\n resolvedOperation,\n operationPath,\n preOperationState,\n } = execution;\n const {\n currentState,\n inputData,\n transactionallyPreparedTokenGenerationResult,\n transactionalCoreConflictReconciled,\n } = payload;\n\n if (transactionalCoreConflictReconciled) {\n // This request did not perform the mutation. Request-scoped terminal\n // result transformers still run, but winner-owned effects must not be\n // emitted twice.\n //\n // The audit emission below sits AFTER this guard on purpose: an event here would assert that\n // this request performed a mutation it lost the race for, which is exactly the false record\n // \"emit after commit\" exists to prevent.\n return;\n }\n\n // Audit BEFORE the evaluators. This is the compliance-bearing effect in this lane; the\n // guidance / milestone / lifecycle evaluators below are product behaviour and are deliberately\n // fire-and-forget via `setImmediate`. Ordering them after keeps an evaluator's slow path from\n // delaying the record of what happened.\n await this.emitResourceOperationAudit({\n executionContext,\n resolvedOperation,\n operationPath,\n inputData,\n preOperationState,\n postOperationState: currentState,\n });\n\n const notificationCurrentState =\n resolvedOperation.generatedOperation?.kind === ResourceGeneratedOperationKind.GENERATED_FILE_REGENERATE\n && currentState\n && typeof currentState === 'object'\n && !Array.isArray(currentState)\n && 'resource' in currentState\n ? (currentState as { resource: unknown }).resource\n : currentState;\n\n await this.dispatchNotifications(\n executionContext,\n inputData,\n notificationCurrentState,\n transactionallyPreparedTokenGenerationResult,\n preOperationState,\n );\n\n // RAG INGESTION seam — the service-tier CHANGED-FIELD hook (plan §3.c / H1). Sits in THIS\n // chokepoint because it is the one post-commit point every service-tier write door reaches\n // (create/createMany/update/updateMany, system writes, custom operations, nested mutations, on\n // both the transactional and inline paths) — see `rag-ingestion-trigger.backend.utils.ts` for\n // the full placement argument and the retained-row (impersonalize) exclusion.\n this.runRagChunkIngestionForWrite(resolvedOperation, operationPath, executionContext, inputData, currentState);\n\n // Scheduling itself happens after commit. Evaluator work stays\n // intentionally fire-and-forget and isolated from the request result.\n if (this.guidanceTriggerEvaluator) {\n setImmediate(() => {\n this.guidanceTriggerEvaluator!.evaluateForOperation({\n resourceType: executionContext.operation.resourceIdentifier,\n operationIdentifier: executionContext.operation.operationIdentifier,\n userId: executionContext.initiatorIds?.userId,\n organizationId: executionContext.initiatorIds?.organizationId,\n }).catch((err: unknown) => {\n this.logDebug('Guidance trigger evaluation failed (non-blocking)', {\n error: describeCaughtError(err),\n });\n });\n });\n }\n\n if (this.milestoneEvaluator) {\n setImmediate(() => {\n this.milestoneEvaluator!.evaluateForOperation({\n resourceType: executionContext.operation.resourceIdentifier,\n operationIdentifier: executionContext.operation.operationIdentifier,\n userId: executionContext.initiatorIds?.userId,\n organizationId: executionContext.initiatorIds?.organizationId,\n }).catch((err: unknown) => {\n this.logDebug('Milestone evaluation failed (non-blocking)', {\n error: describeCaughtError(err),\n });\n });\n });\n }\n\n if (this.lifecycleEvaluator) {\n setImmediate(() => {\n this.lifecycleEvaluator!.onOperation({\n // Deliberately NOT normalised to `''`. An execution with no user principal — machine\n // (client-credentials), internal call, cron, public endpoint — has no user scope at all,\n // and an empty-string id is the ABSENCE of a user rather than a user. Every evaluator\n // below distinguishes the two by `undefined`.\n userId: executionContext.initiatorIds?.userId,\n organizationId: executionContext.initiatorIds?.organizationId,\n operationIdentifier: String(operationPath.operationIdentifier),\n resourceIdentifier: operationPath.resourceIdentifier,\n executionContext,\n }).catch((err: unknown) => {\n this.logDebug('Lifecycle activity check failed (non-blocking)', {\n error: describeCaughtError(err),\n });\n });\n });\n }\n }\n\n /**\n * Record that a HIGH / CRITICAL resource operation took effect.\n *\n * # Why here\n *\n * This is the one point that sees EVERY execution surface — API, internal call, repository-only —\n * and it runs only after the mutation is durable, so the row can never assert a change that was\n * rolled back. The HTTP controller cannot do this job: it is blind to the two non-API surfaces,\n * which carry 68 of the catalogue's 149 HIGH/CRITICAL variants, including every SSO-config,\n * auth-policy, SCIM-provisioning and credential write.\n *\n * # Failure model — best-effort, and why that preserves assurance evidence\n *\n * A throw here is caught and logged. Refusing an already-committed business operation cannot undo\n * it; the assurance obligation is instead to produce the event, DETECT delivery failures and\n * tamper-protect the record — all three of\n * which exist (`audit_store_failure_total`, the DB⇄immudb completeness reconciler, and the\n * immutable Layer-2 sink). Throwing post-commit would be strictly worse than best-effort: the\n * caller would be told the operation failed after it had already persisted, which corrupts the\n * accuracy of the very trail the criteria protect.\n *\n * Fail-closed remains correct where refusing still withholds something — a privileged READ, where\n * `SystemAccessBackendService.emitPrivilegedReadAudit` refuses to hand a minion data whose access\n * could not be recorded. A committed write has no such boundary left to hold.\n *\n * assurance-control: WILDO.AUDIT.EVIDENCE_INTEGRITY — privileged resource actions\n * are attributable and their authorization effect is reconstructable.\n */\n private async emitResourceOperationAudit(params: {\n executionContext: ExecutionContext<any>;\n resolvedOperation: ResourceConfiguration_Operation<any, any, any>;\n operationPath: ResourceConfiguration_OperationPath<any, any>;\n inputData: unknown;\n preOperationState: unknown;\n postOperationState: unknown;\n }): Promise<void> {\n const { executionContext, resolvedOperation, operationPath, inputData, preOperationState, postOperationState } = params;\n\n try {\n const decision = resolveResourceOperationAuditDecision(resolvedOperation);\n if (!decision.shouldEmit) {\n return;\n }\n\n const auditLogsService = this.servicesRegistry.getAuditLogsService?.();\n if (!auditLogsService) {\n return;\n }\n\n const operation = resolvedOperation as unknown as {\n riskLevel?: ResourceOperationRiskLevel;\n variantType?: ResourceOperationVariantType;\n variantKey?: string;\n isBulkOperation?: boolean;\n resourceOperationLike?: CoreResourceOperation;\n };\n\n const mainSchema = this.resourceConfiguration.mainSchema as unknown;\n const shape = mainSchema && isZodObject(mainSchema as never)\n ? getZodObjectShape(mainSchema as never)\n : {};\n /**\n * Resolve an evidence path against the resource schema.\n *\n * Accepts a top-level field name or a DOTTED path one level in\n * (`privacy.dataProcessingConsent`). Each hop is unwrapped before descending because a group\n * field is typically a `.default(...)`-wrapped object, and `isZodObject` answers on the\n * wrapper's own type — reading the shape without unwrapping finds nothing and would silently\n * report \"not evidence\" for every nested leaf.\n */\n const isEvidenceField = (path: string): boolean => {\n const [head, ...nested] = path.split('.');\n let fieldSchema = (shape as Record<string, unknown>)[head!];\n for (const segment of nested) {\n if (!fieldSchema) return false;\n const unwrapped = unwrapSchema(fieldSchema as never);\n if (!isZodObject(unwrapped as never)) return false;\n fieldSchema = (getZodObjectShape(unwrapped as never) as Record<string, unknown>)[segment];\n }\n return fieldSchema ? isAuditEvidenceField(fieldSchema as never) : false;\n };\n\n const { changedFields, fieldEvidence } = resolveResourceOperationFieldEffect({\n inputData,\n preOperationState,\n postOperationState,\n isEvidenceField,\n });\n\n // A bulk write names a COUNT rather than an id; a singular write names the row. Reading the\n // id off the post-state (falling back to the pre-image) covers DELETE, whose post-state may\n // not echo the row.\n const isBulk = Array.isArray(postOperationState);\n const singularState = (isBulk ? undefined : postOperationState) ?? preOperationState;\n const resourceId = this.extractPersistedResourceId(\n (singularState ?? {}) as Record<string, unknown>,\n );\n\n await auditLogsService.logResourceOperationPerformed({\n riskLevel: operation.riskLevel ?? ResourceOperationRiskLevel.LOW,\n actorUserId: executionContext.initiatorIds?.userId,\n organizationId: executionContext.initiatorIds?.organizationId,\n applicationId: executionContext.initiatorIds?.applicationId,\n\n resourceType: String(operationPath.resourceIdentifier),\n operationIdentifier: String(operationPath.operationIdentifier),\n variantType: operation.variantType as ResourceOperationVariantType,\n variantKey: operation.variantKey,\n resourceOperationLike: operation.resourceOperationLike,\n isBulkOperation: operation.isBulkOperation,\n\n resourceId,\n affectedRecordCount: isBulk ? (postOperationState as unknown[]).length : undefined,\n\n // Roles AS THEY WERE for this request. `ExecutionContext_RoleInfo` groups roles per\n // primary scope; flatten to the union, because what an auditor checks is whether the actor\n // held a role at all, and the scope it applied in is already implied by the resource.\n initiatorRoles: executionContext.initiatorRoles.flatMap(r => r.roles.map(String)),\n executionType: executionContext.executionType,\n machineCredentialAuthMethod: executionContext.initiatorIds?.machineCredential?.authMethod,\n machineCredentialId: executionContext.initiatorIds?.machineCredential?.credentialId,\n\n subCallDepth: executionContext.subCallDepth,\n\n changedFields: changedFields.length > 0 ? changedFields : undefined,\n fieldEvidence: Object.keys(fieldEvidence).length > 0 ? fieldEvidence : undefined,\n }, executionContext);\n } catch (error) {\n this.logger.warn('Failed to emit the resource-operation audit event', {\n resourceType: String(params.operationPath.resourceIdentifier),\n operationIdentifier: String(params.operationPath.operationIdentifier),\n ...projectCaughtErrorLogFields(error),\n });\n }\n }\n\n /**\n * Keep post-commit work on the owner of the active rollback domain.\n *\n * A core transaction registers its successful-attempt payload before commit.\n * A caller-owned transaction receives the same registration here. With no\n * transaction, the phase executes immediately.\n */\n private async scheduleFrameworkManagedPostCommitEffects(scheduling: FrameworkManagedPostCommitScheduling): Promise<void> {\n if (scheduling.registeredByCoreTransaction) {\n return;\n }\n\n if (!scheduling.transaction) {\n await scheduling.execute(Object.freeze(scheduling.payload));\n return;\n }\n\n const transaction = scheduling.transaction;\n const payload = snapshotFrameworkManagedPostCommitPayload(scheduling.payload);\n registerTransactionPostCommitEffect(transaction, {\n key: [\n 'resource-post-commit',\n String(scheduling.operationPath.resourceIdentifier),\n String(scheduling.operationPath.operationIdentifier),\n String(\n (payload.currentState as { _id?: unknown } | null)?._id ?? 'no-id',\n ),\n transaction.id,\n scheduling.occurrenceId,\n ].join(':'),\n execute: () => scheduling.execute(payload),\n });\n }\n\n /**\n * Run synchronous result-transforming custom phases in the request path.\n *\n * Framework-owned root transactions have committed and drained their\n * post-commit effects before this method is called. Caller-owned transaction\n * shapes with these phases are rejected during preflight.\n */\n private async executeTerminalCustomPhases(execution: ResourceOperationTerminalCustomPhaseExecution): Promise<any> {\n let state = execution.state;\n\n try {\n if (\n execution.customImplPlaceholders.has(\n ResourceOperation_CustomServiceImplementationMode.AFTER_USER_NOTIFICATIONS,\n )\n ) {\n const afterNotificationRegistrations =\n this.customImplRegistry.resolveRegistrationsForMode(\n execution.customImplRegistrations,\n ResourceOperation_CustomServiceImplementationMode.AFTER_USER_NOTIFICATIONS,\n this.logger,\n );\n for (const registration of afterNotificationRegistrations) {\n state = await registration.implementation.afterUserNotifications(\n execution.target as any,\n state,\n execution.executionContext,\n execution.terminalCustomImplUtils,\n );\n }\n }\n\n if (\n execution.customImplPlaceholders.has(\n ResourceOperation_CustomServiceImplementationMode.AT_THE_END,\n )\n ) {\n const atTheEndRegistrations =\n this.customImplRegistry.resolveRegistrationsForMode(\n execution.customImplRegistrations,\n ResourceOperation_CustomServiceImplementationMode.AT_THE_END,\n this.logger,\n );\n for (const registration of atTheEndRegistrations) {\n state = await registration.implementation.atTheEnd(\n execution.target as any,\n state,\n execution.executionContext,\n execution.terminalCustomImplUtils,\n );\n }\n }\n } catch (error) {\n if (execution.transactionalCoreRequired) {\n this.logger.error(\n 'Synchronous terminal custom phase failed after the resource mutation committed',\n {\n transactionCommitted: true,\n transactionConflictReconciled:\n execution.transactionalCoreConflictReconciled,\n resourceType: execution.operation.resourceIdentifier,\n operationIdentifier: execution.operation.operationIdentifier,\n ...projectCaughtErrorLogFields(error),\n },\n );\n }\n throw error;\n }\n\n return state;\n }\n\n /**\n * Central orchestration method — ALL resource operations flow through here.\n *\n * Two entry points:\n * - `doByOperationPath()` — resolves `operation` from the operations map. The caller's\n * `executionContext.operation` may differ (e.g., webhook context with a generic operation).\n * - `doByExecutionContext()` — reads `operation` from `executionContext.operation`.\n * Guaranteed to match (same reference).\n *\n * Two correction points enforce the invariant that `executionContext.operation` always\n * matches the operation being executed:\n * - Correction Point 1 (pre-queue): corrects to the base `operation` parameter.\n * - Correction Point 2 (post-variant): refines to `resolvedOperation` when `dataMode !== RAW`.\n *\n * After correction, ALL downstream reads of `executionContext.operation` — notifications,\n * guidance, milestones, queue serialization, repositories — use the correct 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 frameworkPostCommitEffectOccurrenceId = randomUUID();\n options = {\n ...options,\n // Always replace a caller-provided value: this identity belongs to this\n // exact service-operation occurrence, not to the ambient transaction.\n frameworkPostCommitEffectOccurrenceId,\n };\n\n if(operation.variantType === ResourceOperationVariantType.REPOSITORY_ONLY) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED });\n }\n\n // ── An acknowledged implementation gap must never answer a success status ──\n // Refused HERE, before the runtime-mode switch, so the operation is not queued either: a\n // job that will never do the work is a delayed lie, not a lesser one.\n //\n // Without this, a custom operation whose `requestDto` nothing consumes falls through to the\n // generic core path, writes nothing, and returns 200 with the unchanged row. That is how\n // `organizationMembers | promote` reported success for a role change it never performed\n // (found by a hostile e2e probe on 2026-08-01; 41 routed operations shared the shape).\n // Acknowledging the gap must CLOSE it, not document it.\n //\n // The declaration is trustworthy because `ApplicationStartupConfigValidatorService` refuses\n // to boot when it disagrees with `resolveResourceOperationImplementationCoverage` in either\n // direction — an unacknowledged gap AND a stale acknowledgement on a now-working operation\n // are both startup errors. So the flag is read directly here rather than re-deriving the\n // verdict (a schema walk) on every request; the two cannot drift apart silently.\n if (operation.unimplementedAcknowledgement) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference:\n ErrorCustomMessageReference.RESOURCE_OPERATION_CUSTOM_IMPLEMENTATION_NOT_IMPLEMENTED,\n context: {\n message:\n 'Operation is declared but not implemented, and refuses rather than reporting a success it did not perform',\n resourceIdentifier: operation.resourceIdentifier,\n operationIdentifier: operation.operationIdentifier,\n variantKey: operation.variantKey,\n acknowledgedReason: operation.unimplementedAcknowledgement.reason,\n trackingRef: operation.unimplementedAcknowledgement.trackingRef,\n },\n },\n );\n }\n\n // ── INVARIANT: executionContext.operation must match the operation being executed ──\n // Correction Point 1 (pre-queue): ensures queue serialization and all non-INLINE\n // dispatch paths use the correct operation. Without this, QueueBackendService.buildJobPayload\n // would serialize the caller's stale operation path.\n if (executionContext.operation !== operation) {\n this.logDebug('Correcting executionContext.operation mismatch', {\n contextOp: `${executionContext.operation.resourceIdentifier}.${executionContext.operation.operationIdentifier}`,\n actualOp: `${operation.resourceIdentifier}.${operation.operationIdentifier}`,\n });\n executionContext = executionContext.withOperation(operation);\n }\n\n // ── A BULK operation takes its target from its payload's `_ids` selector ──\n //\n // A bulk operation's URL is COLLECTION-level plus a `/bulk` segment, so it carries no id path\n // parameter and `extractIdsFromExecutionContext` (the only target source on the\n // `doByExecutionContext` entry) can never resolve one. The rows are named in the body, by the\n // `_ids` selector the DTO builder wraps around every bulk request DTO\n // (`Resouces_BulkOperationBaseSchema`). Nothing lifted it, so EVERY client-facing bulk operation\n // reached `update()` / `delete()` / `updateMany()` / `deleteMany()` with an undefined target and\n // was refused as `missingParameter: id_or_ids_or_filter`. Fails closed, never mis-targeted — but\n // the whole generic bulk lane was unreachable from a client, and no test could see it because\n // every backend test passes the target explicitly as `doOperation`'s third argument and so skips\n // this resolution entirely.\n //\n // Resolved HERE rather than in the HTTP controller because `doOperation` is the SINGLE funnel\n // every dispatch surface converges on — `doByExecutionContext` (HTTP controller, batches/cron)\n // and `doByOperationPath` (MCP, queue, programmatic) are its only two entries. The controller is\n // one of four call sites of the same invariant, and MCP is a second broken one: it resolves a\n // target from `options.resourceId`, a SINGLE id, so a bulk tool call has no way to name its rows\n // either. Fixing the funnel covers all of them and cannot drift\n // (`.claude/rules/invariant-call-site-enumeration.md`).\n //\n // An EXPLICIT target always wins: a programmatic caller (`updateManyAsSystem`, the retention\n // scrub, a queue job replaying `job.inputId`) has already named its rows, and a payload-borne\n // selector must never be able to widen or redirect a target the caller authored. So this only\n // ever fills an absent target.\n //\n // The selector is then STRIPPED from the payload: it names rows, it is not a field to write.\n // `_ids` is not in `createOrUpdateMandatoryDiscardFields`, so leaving it in place would carry it\n // to the repository to be silently dropped by the strict re-parse — and would show the\n // read-only-field guard a payload that is not the payload.\n if ('isBulkOperation' in operation && operation.isBulkOperation === true) {\n const selectorIds = readBulkOperationSelectorIds(data);\n if (selectorIds) {\n if (id_or_ids_or_filter === undefined) {\n // One id is passed as a bare string rather than a one-element array, matching\n // `resolveGeneratedRelationshipBulkSelector`: a single-target selector must reach the same\n // single-row code path (pre-image fetch, `enabledCondition` object context) as the\n // non-bulk operation, or a one-row bulk action silently loses per-row semantics.\n id_or_ids_or_filter = selectorIds.length === 1 ? selectorIds[0] : selectorIds;\n }\n data = stripBulkOperationSelector(data);\n }\n }\n\n // ============================================\n // STEP 1: Check serviceRuntimeMode FIRST\n // Skip this check if executing from worker (prevents infinite loop)\n // ============================================\n const runtimeMode = operation.serviceRuntimeMode ?? ResourceOperation_ServiceRuntimeMode.INLINE;\n\n if (!options?.isWorkerExecution && runtimeMode !== ResourceOperation_ServiceRuntimeMode.INLINE) {\n const preRuntimeCoreOperation = ResourceOperationsUtils.getCoreResourceOperationFromOperation(operation);\n const isContextAddressedOperationRuntimeTarget =\n preRuntimeCoreOperation === CoreResourceOperation.READ\n || preRuntimeCoreOperation === CoreResourceOperation.UPDATE\n || preRuntimeCoreOperation === CoreResourceOperation.DELETE;\n const hasContextAddressedParentScope =\n this.hasContextAddressedSingletonParentScope(operation, executionContext)\n || this.hasContextAddressedAssociationParentScope(operation, executionContext);\n const authorizedContextAddressedOperationId = options?.contextAddressedOperationAuthorizationId\n ?? options?.contextAddressedMutationAuthorizationId;\n if (\n id_or_ids_or_filter === undefined\n && authorizedContextAddressedOperationId\n && isContextAddressedOperationRuntimeTarget\n ) {\n id_or_ids_or_filter = authorizedContextAddressedOperationId;\n const authorizedCurrentObject = await this.fetchCurrentObjectForOperation(\n preRuntimeCoreOperation,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n id_or_ids_or_filter,\n executionContext,\n );\n this.ensureExplicitMutationTargetMatchesContext(\n operation,\n preRuntimeCoreOperation,\n id_or_ids_or_filter,\n authorizedCurrentObject,\n executionContext,\n );\n }\n\n if (\n id_or_ids_or_filter === undefined\n && isContextAddressedOperationRuntimeTarget\n && !('isBulkOperation' in operation && operation.isBulkOperation === true)\n ) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Context-addressed operations with non-inline runtime modes require a controller-resolved target id before dispatch',\n operationIdentifier: operation.operationIdentifier,\n runtimeMode,\n },\n }\n );\n }\n\n if (\n id_or_ids_or_filter === undefined\n && preRuntimeCoreOperation === undefined\n && hasContextAddressedParentScope\n && !('isBulkOperation' in operation && operation.isBulkOperation === true)\n ) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Non-inline context-scoped custom operations must declare resourceOperationLike before dispatch so target identity and authorization cannot fall back to collection scope',\n operationIdentifier: operation.operationIdentifier,\n runtimeMode,\n },\n }\n );\n }\n\n switch (runtimeMode) {\n case ResourceOperation_ServiceRuntimeMode.NONE:\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: { message: 'Operation has serviceRuntimeMode: NONE (disabled)' },\n }\n );\n\n case ResourceOperation_ServiceRuntimeMode.QUEUED:\n // Queue and wait for result via RPC pattern\n return this.executeQueued(executionContext, id_or_ids_or_filter, data, true);\n\n case ResourceOperation_ServiceRuntimeMode.QUEUED_NOT_AWAITABLE:\n // Queue and return immediately\n return this.executeQueued(executionContext, id_or_ids_or_filter, data, false);\n\n case ResourceOperation_ServiceRuntimeMode.BACKGROUND_JOB:\n // Queue with callback pattern (async notification)\n return this.executeBackgroundJob(executionContext, id_or_ids_or_filter, data);\n\n case ResourceOperation_ServiceRuntimeMode.INLINE_NOT_AWAITABLE:\n // Fire and forget - execute async but don't wait\n this.executeInlineAsync(operation, executionContext, id_or_ids_or_filter, data, options);\n return { acknowledged: true };\n }\n }\n\n // ============================================\n // STEP 2: Continue with inline execution (existing logic)\n // ============================================\n const operationIdentifier = String(operation.operationIdentifier);\n\n // CRITICAL FIX: Resolve operation variant BEFORE custom impl lookup\n // If dataMode is specified in options, resolve the variant first so custom impl\n // lookup can match the correct variant operation (e.g., 'context' variant)\n const dataMode = (options as any)?.dataMode ?? DataMode.RAW;\n const resolvedOperation = dataMode !== DataMode.RAW\n ? this.resolveOperationVariant(operation, dataMode)\n : operation;\n\n // Correction Point 2 (post-variant): when dataMode !== RAW, the resolvedOperation\n // may differ from the base operation. Update the context to the variant so all\n // downstream reads (notifications, guidance, milestones, repos) use variant configs.\n if (executionContext.operation !== resolvedOperation) {\n executionContext = executionContext.withOperation(resolvedOperation);\n }\n\n this.logDebug('Operation variant resolution for doOperation', {\n operationIdentifier,\n originalVariantKey: operation.variantKey,\n dataMode,\n resolvedVariantKey: resolvedOperation.variantKey,\n variantResolved: resolvedOperation !== operation\n });\n\n const operationPath = ResourcesConfig_OperationPathUtils.extractOperationPath(\n resolvedOperation as unknown as ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum>\n );\n\n const coreOperation = ResourceOperationsUtils.getCoreResourceOperationFromOperation(resolvedOperation);\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const generatedBulkRelationshipOperation = Resources_SharedUtils.parseRelationshipBulkOperationIdentifier(\n operationIdentifier\n );\n if (generatedBulkRelationshipOperation) {\n await this.featureGate.checkOperationFeatures(resolvedOperation, executionContext, data);\n await this.enforceStepUpAuth(coreOperation, executionContext, options, resolvedOperation);\n return this.executeGeneratedRelationshipBulkOperation(\n resolvedOperation,\n generatedBulkRelationshipOperation,\n executionContext,\n data,\n options\n );\n }\n\n const authorizedContextAddressedOperationId = options?.contextAddressedOperationAuthorizationId\n ?? options?.contextAddressedMutationAuthorizationId;\n if (\n id_or_ids_or_filter === undefined\n && authorizedContextAddressedOperationId\n && (\n coreOperation === CoreResourceOperation.READ\n || coreOperation === CoreResourceOperation.UPDATE\n || coreOperation === CoreResourceOperation.DELETE\n )\n // USER *and* MACHINE principals (both external request principals) may use a controller-authorized\n // context-addressed target id — consistent with the resolver gates above; INTERNAL/PUBLIC/etc. excluded.\n && (executionContext.isUserExecution() || executionContext.isMachineExecution())\n ) {\n id_or_ids_or_filter = authorizedContextAddressedOperationId;\n const authorizedCurrentObject = await this.fetchCurrentObjectForOperation(\n coreOperation,\n resourceType,\n id_or_ids_or_filter,\n executionContext,\n );\n this.ensureExplicitMutationTargetMatchesContext(\n resolvedOperation,\n coreOperation,\n id_or_ids_or_filter,\n authorizedCurrentObject,\n executionContext,\n );\n this.logDebug('Using controller-authorized context-addressed operation target', {\n resourceType,\n operationIdentifier,\n operationId: authorizedContextAddressedOperationId,\n });\n }\n\n const contextAddressedSingletonTarget = await this.resolveContextAddressedSingletonOperationTarget(\n resolvedOperation,\n coreOperation,\n resourceType,\n id_or_ids_or_filter,\n executionContext,\n options,\n );\n if (contextAddressedSingletonTarget) {\n // `resolved` → address the operation by the singleton's real `_id`.\n // `absent-read-by-scope` (READ only) → address the read by the parent-scope\n // selector so it returns null and the POSTFIX materialization hook can run.\n id_or_ids_or_filter = contextAddressedSingletonTarget.kind === 'absent-read-by-scope'\n ? contextAddressedSingletonTarget.selector\n : contextAddressedSingletonTarget.operationId;\n this.logDebug('Resolved context-addressed singleton operation target', {\n resourceType,\n operationIdentifier,\n targetKind: contextAddressedSingletonTarget.kind,\n operationId: contextAddressedSingletonTarget.kind === 'resolved'\n ? contextAddressedSingletonTarget.operationId\n : undefined,\n selector: contextAddressedSingletonTarget.selector,\n parentResourceType: contextAddressedSingletonTarget.relationship.resourceType1,\n });\n }\n\n const contextAddressedAssociationTarget = await this.resolveContextAddressedAssociationOperationTarget(\n resolvedOperation,\n coreOperation,\n resourceType,\n id_or_ids_or_filter,\n executionContext,\n options,\n );\n if (contextAddressedAssociationTarget) {\n id_or_ids_or_filter = contextAddressedAssociationTarget.operationId;\n this.logDebug('Resolved complete association-context operation target', {\n resourceType,\n operationIdentifier,\n operationId: contextAddressedAssociationTarget.operationId,\n selector: contextAddressedAssociationTarget.selector,\n parentResourceTypes: contextAddressedAssociationTarget.relationships.map((relationship) => relationship.resourceType1),\n });\n }\n\n // Lookup custom impl registrations with RESOLVED operation (includes variantKey if dataMode specified)\n const customImplRegistrations = this.customImplRegistry.getRegistrationsForOperation(resolvedOperation);\n const customImplPlaceholders = new Set(\n customImplRegistrations.flatMap(r => r.implementation.getPlaceholders())\n );\n\n /**\n * A configured token belongs to the successful resource mutation. The\n * operation and token therefore share one transaction; only notification\n * submission remains a post-commit effect.\n */\n const transactionPersistenceContract =\n resolveResourceOperationTransactionPersistenceContract(\n resolvedOperation,\n customImplRegistrations,\n );\n const transactionalCoreRequired = transactionPersistenceContract.transactionRequired;\n if (transactionalCoreRequired && transactionPersistenceContract.overrideAllRegistrationLabels.length > 0\n ) {\n /**\n * OVERRIDE_ALL replaces this entire framework pipeline and returns before\n * the UoW callback. Allowing it here would make the authored transaction\n * contract fictitious: neither the business write nor its generated token\n * would be guaranteed to execute in the assessed boundary.\n */\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n context: {\n reason:\n 'override_all_not_supported_for_transaction_requiring_operation',\n resourceType: resolvedOperation.resourceIdentifier,\n operationIdentifier: resolvedOperation.operationIdentifier,\n overrideAllRegistrationLabels:\n transactionPersistenceContract.overrideAllRegistrationLabels,\n },\n },\n );\n }\n const hasSynchronousTerminalCustomPhase =\n customImplPlaceholders.has(\n ResourceOperation_CustomServiceImplementationMode.AFTER_USER_NOTIFICATIONS,\n )\n || customImplPlaceholders.has(\n ResourceOperation_CustomServiceImplementationMode.AT_THE_END,\n );\n if (\n options?.transaction\n && hasSynchronousTerminalCustomPhase\n ) {\n /**\n * A framework-owned root transaction returns only after commit and after\n * its post-commit queue has drained, so terminal result transformers can\n * retain their authored ordering there. A nested operation cannot do the\n * same: it must return its synchronous result while the caller still owns\n * an uncommitted transaction. Running the hook now would place\n * AFTER_USER_NOTIFICATIONS before notifications and could leak effects\n * from an eventual abort; deferring it would lose its result transform.\n * Fail before mutation only for that irreconcilable caller-owned shape.\n */\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n context: {\n reason: 'synchronous_terminal_custom_phase_not_supported_in_transaction',\n transactionOwnership: 'caller',\n resourceType: resolvedOperation.resourceIdentifier,\n operationIdentifier: resolvedOperation.operationIdentifier,\n },\n });\n }\n\n this.logDebug('Custom implementation check', {\n operationIdentifier,\n resourceIdentifier: this.resourceConfiguration.resourceIdentifier,\n registrationCount: customImplRegistrations.length,\n placeholders: [...customImplPlaceholders],\n registrations: customImplRegistrations.map(r => r.debugLabel),\n operationPathKey: ResourcesConfig_OperationPathUtils.createOperationPathKeyFromOperation(resolvedOperation as any),\n usedResolvedOperation: resolvedOperation !== operation\n });\n\n // Fetch current object for UPDATE/DELETE operations (needed for enabledCondition and basicPrefixOperation)\n const currentObject = await this.fetchCurrentObjectForOperation(\n coreOperation,\n resourceType,\n id_or_ids_or_filter,\n executionContext,\n options,\n );\n this.ensureExplicitMutationTargetMatchesContext(\n resolvedOperation,\n coreOperation,\n id_or_ids_or_filter,\n currentObject,\n executionContext,\n );\n const hookCurrentObject = this.resolveHookCurrentObject(coreOperation, currentObject, data);\n\n // Fetch computation context for custom implementations\n const needs = this.populationService.analyzeContextNeeds(resourceType);\n const computationContext = await this.populationService.fetchComputationContext(\n resourceType,\n hookCurrentObject || {},\n needs,\n executionContext,\n options,\n );\n\n const customImplUtils : ResourceOperation_CustomImplementation_Utils = {\n logger: this.logger,\n errorBuilder: this.errorBuilder,\n resourcesRegistry: this.resourcesRegistry,\n servicesRegistry: this.servicesRegistry,\n serviceOptions: options,\n repositoriesRegistry: this.repositoriesRegistry,\n externalApiHandler: this.externalApiHandler,\n platformMutualizedHandler: this.platformMutualizedHandler,\n serverlessServicesHandler: this.serverlessServicesHandler,\n executionContextCreator: this.executionContextCreator,\n systemAccessService: this.servicesRegistry.getSystemAccessService?.(),\n samlMetadataService: this.servicesRegistry.getSamlMetadataService?.(),\n objectContext: {\n parents: computationContext.objectContext?.parents || {},\n children: computationContext.objectContext?.children || {}\n } as { parents: Record<string, any>; children: Record<string, any> },\n initiatorUserContext: computationContext.userContext,\n currentObject: hookCurrentObject\n }\n // Check feature gate — is this capability available for this scope?\n // Runs before enabledCondition because feature availability is independent of RBAC/object state.\n // The gate handles its own bypass logic (INTERNAL_CALL, REPOSITORY_ONLY, system resources).\n await this.featureGate.checkOperationFeatures(resolvedOperation, executionContext, data);\n\n // W7.1: Step-up authentication enforcement — the per-user-type freshness policy AND any\n // per-operation `requiresStepUpAuthentication`. The RESOLVED operation is passed because the\n // flag lives on the variant, and a variant that declares it must be judged on its own terms.\n await this.enforceStepUpAuth(coreOperation, executionContext, options, resolvedOperation);\n\n const assertRequiredMutationTargetExists = (\n attemptCurrentObject: unknown,\n ): void => {\n if (\n attemptCurrentObject == null\n && typeof id_or_ids_or_filter === 'string'\n && (\n coreOperation === CoreResourceOperation.UPDATE\n || coreOperation === CoreResourceOperation.DELETE\n )\n ) {\n // A concurrent delete/revoke is an absent explicit mutation target,\n // not an authored-condition programming error. Classify it before\n // evaluating predicates such as `currentObject.status === ...`.\n throw this.errorBuilder.buildError(\n ErrorType.NOT_FOUND,\n executionContext,\n {\n customMessageReference:\n ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: {\n operation: coreOperation,\n id_or_ids_or_filter,\n },\n },\n );\n }\n };\n\n const assertOperationEnabledForState = async (\n attemptCurrentObject: any,\n attemptHookCurrentObject: any,\n attemptInput: any,\n repositoryOptions?: RepositoryOptions,\n ): Promise<void> => {\n // Only API_CALL and API_CALL_WITH_CALLBACK variants carry this gate.\n if (\n !('enabledCondition' in resolvedOperation)\n || !resolvedOperation.enabledCondition\n ) {\n return;\n }\n\n assertRequiredMutationTargetExists(attemptCurrentObject);\n\n this.assertBulkHookObjectContextAvailability(\n coreOperation,\n 'isBulkOperation' in resolvedOperation\n ? resolvedOperation.isBulkOperation\n : false,\n resolvedOperation.enabledCondition,\n attemptCurrentObject,\n executionContext,\n operationIdentifier,\n 'enabledCondition',\n );\n\n const { objectContext, initiatorUserContext } =\n await this.fetchContextsForOperationFunction(\n resolvedOperation.enabledCondition,\n resourceType,\n attemptCurrentObject,\n executionContext,\n repositoryOptions,\n );\n const isEnabled = resolvedOperation.enabledCondition({\n inputDto: attemptInput,\n currentObject: attemptHookCurrentObject,\n objectContext,\n initiatorUserContext,\n initiatorIds: executionContext.initiatorIds,\n });\n\n if (!isEnabled) {\n throw this.errorBuilder.buildError(\n ErrorType.AUTHORIZATION,\n executionContext,\n {\n customMessageReference:\n ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_DISABLED,\n },\n );\n }\n };\n\n // This is an early rejection only. Transaction-required operations repeat\n // the same state-sensitive check from a callback-local database snapshot\n // before any prefix, token, or repository write.\n await assertOperationEnabledForState(\n currentObject,\n hookCurrentObject,\n data,\n options,\n );\n\n if (customImplPlaceholders.has(ResourceOperation_CustomServiceImplementationMode.OVERRIDE_ALL)) {\n const winner = this.customImplRegistry.resolveSingleOwner(\n customImplRegistrations,\n ResourceOperation_CustomServiceImplementationMode.OVERRIDE_ALL,\n this.logger,\n );\n if (winner) {\n return winner.implementation.overrideAll(id_or_ids_or_filter as any, data, executionContext, customImplUtils);\n }\n }\n\n const preflightCoreContext: ResourceOperationCoreAttemptContext =\n Object.freeze({\n currentObject,\n hookCurrentObject,\n computationContext,\n });\n const refreshTransactionalCoreContext = async (\n attemptInput: any,\n attemptOptions: RepositoryOptions,\n ): Promise<ResourceOperationCoreAttemptContext> => {\n // Driver callbacks may be retried, so no state from an earlier callback\n // or from the outer preflight is authoritative.\n const attemptCurrentObject =\n await this.fetchCurrentObjectForOperation(\n coreOperation,\n resourceType,\n id_or_ids_or_filter,\n executionContext,\n attemptOptions,\n );\n assertRequiredMutationTargetExists(attemptCurrentObject);\n this.ensureExplicitMutationTargetMatchesContext(\n resolvedOperation,\n coreOperation,\n id_or_ids_or_filter,\n attemptCurrentObject,\n executionContext,\n );\n const attemptHookCurrentObject = this.resolveHookCurrentObject(\n coreOperation,\n attemptCurrentObject,\n attemptInput,\n );\n const attemptComputationContext =\n await this.populationService.fetchComputationContext(\n resourceType,\n attemptHookCurrentObject || {},\n needs,\n executionContext,\n attemptOptions,\n );\n await assertOperationEnabledForState(\n attemptCurrentObject,\n attemptHookCurrentObject,\n attemptInput,\n attemptOptions,\n );\n return Object.freeze({\n currentObject: attemptCurrentObject,\n hookCurrentObject: attemptHookCurrentObject,\n computationContext: attemptComputationContext,\n });\n };\n const executeCorePhaseAttempt = (\n attemptOptions: RepositoryOptions | undefined,\n attemptInput: any,\n ): Promise<ResourceOperationCorePhaseResult> =>\n this.executeCorePhase({\n operation: resolvedOperation,\n operationPath,\n coreOperation,\n resourceType,\n executionContext,\n target: id_or_ids_or_filter,\n inputData: attemptInput,\n options: attemptOptions,\n preflightContext: preflightCoreContext,\n customImplUtils,\n customImplRegistrations,\n customImplPlaceholders,\n refreshTransactionalContext: refreshTransactionalCoreContext,\n });\n\n const executeFrameworkManagedPostCommit = (\n payload: FrameworkManagedPostCommitPayload,\n ): Promise<void> =>\n this.executeFrameworkManagedPostCommitEffects({\n payload,\n executionContext,\n operation,\n resolvedOperation,\n operationPath,\n // Captured from `doOperation`'s scope, where it was already fetched for `enabledCondition`\n // and `basicPrefixOperation`. Both scheduling sites — the transactional attempt and the\n // non-transactional path — run THIS closure, so the pre-image reaches the audit emission on\n // either route with no signature threading and no extra read.\n preOperationState: currentObject,\n });\n\n const executeTransactionalAttempt = (\n optionsWithTransaction: ServiceOptions,\n originalCoreInput: unknown,\n ): Promise<ResourceOperationTransactionalCoreAttemptResult> =>\n this.executeTransactionalCoreAttempt({\n optionsWithTransaction,\n originalCoreInput,\n executeCorePhase: executeCorePhaseAttempt,\n executionContext,\n dataMode,\n operation,\n resolvedOperation,\n tokenGeneration: transactionPersistenceContract.tokenGeneration,\n operationPath,\n postCommitEffectOccurrenceId: frameworkPostCommitEffectOccurrenceId,\n executePostCommit: executeFrameworkManagedPostCommit,\n });\n\n const executeCoreBoundary = async (): Promise<ResourceOperationCoreBoundaryResult> => {\n if (transactionalCoreRequired) {\n const originalCoreInput = cloneResourceTransactionAttemptInput(data);\n const conflictResolvers = customImplRegistrations\n .map((registration) => registration.transactionalCoreConflictResolver)\n .filter((resolver): resolver is NonNullable<typeof resolver> => resolver !== undefined);\n return this.executeTransactionalCoreBoundary({\n persistenceContract: transactionPersistenceContract,\n baseOptions: options,\n requiresRootOwnership: hasSynchronousTerminalCustomPhase,\n originalCoreInput,\n executionContext,\n operation,\n customImplUtils,\n conflictResolvers,\n executeAttempt: (optionsWithTransaction) =>\n executeTransactionalAttempt(\n optionsWithTransaction,\n originalCoreInput,\n ),\n resolveReconciledResult: async (reconciledState) =>\n Object.freeze({\n state: reconciledState,\n inputData: data,\n /**\n * No callback attempt committed for this request, so an\n * attempt's captured utils would describe an aborted snapshot.\n * Preserve the request's preflight currentObject contract for\n * its request-scoped terminal result transform instead.\n */\n terminalCustomImplUtils:\n this.createTerminalCustomImplUtils(customImplUtils),\n tokenGenerationResult: null,\n }),\n });\n }\n\n const coreResult = await executeCorePhaseAttempt(options, data);\n return Object.freeze({\n ...coreResult,\n transactionalCoreConflictReconciled: false,\n transactionallyPreparedTokenGenerationResult: null,\n frameworkPostCommitRegisteredTransactionally: false,\n consumableTokenConsumedTransactionally: false,\n });\n };\n\n const coreBoundaryResult = await executeCoreBoundary();\n let currentState = coreBoundaryResult.state;\n data = coreBoundaryResult.inputData;\n const terminalCustomImplUtils = coreBoundaryResult.terminalCustomImplUtils;\n const {\n transactionalCoreConflictReconciled,\n transactionallyPreparedTokenGenerationResult,\n frameworkPostCommitRegisteredTransactionally,\n consumableTokenConsumedTransactionally,\n transactionallyPreparedOutput,\n } = coreBoundaryResult;\n\n // ── TOKEN CONSUMPTION (post-operation, MF2) ─────────────────────\n // Consume the token ONLY after the core operation succeeded (Trap 4).\n // Checks consumableTokenValue presence (not executionType) so it works for BOTH:\n // - ALTERNATIVE tokens (executionType = CONSUMABLE_TOKEN)\n // - ADDITIVE tokens (executionType = USER_REQUEST, token validated alongside JWT)\n // consumptionMode logic (SINGLE_USE vs BOUNDED_REUSE) lives inside consumeToken().\n if (executionContext.consumableTokenValue && !consumableTokenConsumedTransactionally\n ) {\n await this.consumableTokenService.consumeToken(\n executionContext.consumableTokenValue,\n options?.transaction,\n );\n if (options?.transaction) {\n this.registerConsumableTokenContextMark({\n transaction: options.transaction,\n operationPath,\n occurrenceId: frameworkPostCommitEffectOccurrenceId,\n executionContext,\n });\n } else {\n executionContext.markConsumableTokenConsumed();\n }\n }\n\n await this.scheduleFrameworkManagedPostCommitEffects({\n registeredByCoreTransaction: frameworkPostCommitRegisteredTransactionally,\n transaction: options?.transaction,\n operationPath,\n occurrenceId: frameworkPostCommitEffectOccurrenceId,\n payload: Object.freeze({\n currentState,\n inputData: data,\n transactionallyPreparedTokenGenerationResult,\n transactionalCoreConflictReconciled,\n }),\n execute: executeFrameworkManagedPostCommit,\n });\n\n currentState = await this.executeTerminalCustomPhases({\n state: currentState,\n target: id_or_ids_or_filter,\n executionContext,\n terminalCustomImplUtils,\n customImplRegistrations,\n customImplPlaceholders,\n transactionalCoreRequired,\n transactionalCoreConflictReconciled,\n operation: resolvedOperation,\n });\n\n // READ/UPDATE/DELETE can legitimately return null (document not found).\n // Skip Zod output validation for null — callers already handle it.\n if (currentState == null) {\n return null;\n }\n\n // Transform output using resolved operation's internalDto\n // Use the already-resolved operation to avoid double resolution\n const finalResult =\n transactionallyPreparedOutput && !hasSynchronousTerminalCustomPhase\n ? transactionallyPreparedOutput.value\n : await this.transformOutput(\n executionContext,\n currentState,\n dataMode,\n resolvedOperation,\n );\n\n return finalResult;\n }\n\n // ================================\n // Queue Runtime Mode Methods\n // ================================\n\n /**\n * Execute operation via queue with RPC pattern (QUEUED / QUEUED_NOT_AWAITABLE).\n *\n * @param executionContext - The execution context with operation\n * @param id_or_ids_or_filter - Resource ID(s) or filter for the operation\n * @param data - Input data for the operation\n * @param awaitable - If true, wait for result (QUEUED); if false, return immediately (QUEUED_NOT_AWAITABLE)\n * @returns For awaitable: the operation result; otherwise: { jobId, status: 'queued' }\n */\n private async executeQueued(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n data: any,\n awaitable: boolean\n ): Promise<any> {\n // Extract inputId for READ/UPDATE/DELETE operations\n const inputId = this.resolveQueuedSingularTargetIdOrThrow(\n executionContext,\n id_or_ids_or_filter,\n 'Queued',\n );\n\n if (awaitable) {\n // QUEUED: Wait for result via RPC\n return this.queueService.enqueueAndWait(executionContext, data, inputId);\n } else {\n // QUEUED_NOT_AWAITABLE: Fire and forget to queue\n const result = await this.queueService.enqueueOperation(executionContext, data, inputId);\n return { jobId: result.jobId, status: 'queued' };\n }\n }\n\n /**\n * Execute operation via queue with callback pattern (BACKGROUND_JOB).\n * Returns immediately with job tracking info.\n *\n * @param executionContext - The execution context with operation\n * @param id_or_ids_or_filter - Resource ID(s) or filter for the operation\n * @param data - Input data for the operation\n * @returns Job tracking info: { jobId, status: 'processing', message }\n */\n private async executeBackgroundJob(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n data: any\n ): Promise<any> {\n const inputId = this.resolveQueuedSingularTargetIdOrThrow(\n executionContext,\n id_or_ids_or_filter,\n 'Background job',\n );\n\n // Enqueue with callback (async result notification)\n const result = await this.queueService.enqueueWithCallback(executionContext, data, inputId);\n\n // Return immediately with job tracking info\n return {\n jobId: result.jobId,\n status: 'processing',\n message: 'Job has been queued for background processing',\n };\n }\n\n private resolveQueuedSingularTargetIdOrThrow(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType | undefined,\n runtimeLabel: string,\n ): string | undefined {\n const inputId = typeof id_or_ids_or_filter === 'string' ? id_or_ids_or_filter : undefined;\n const coreOperation = ResourceOperationsUtils.getCoreResourceOperationFromOperation(\n executionContext.operation as ResourceConfiguration_Operation<any, any, any>,\n );\n if (\n id_or_ids_or_filter !== undefined\n && inputId === undefined\n && (\n coreOperation === CoreResourceOperation.READ\n || coreOperation === CoreResourceOperation.UPDATE\n || coreOperation === CoreResourceOperation.DELETE\n )\n ) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: `${runtimeLabel} singular resource operations require a concrete string target id`,\n operation: coreOperation,\n resourceType: executionContext.operation.resourceIdentifier,\n },\n });\n }\n\n return inputId;\n }\n\n /**\n * Execute operation inline but don't wait for result (INLINE_NOT_AWAITABLE).\n * Fire and forget pattern - executes in the next tick.\n *\n * @param operation - The operation to execute\n * @param executionContext - The execution context\n * @param id_or_ids_or_filter - Resource ID(s) or filter\n * @param data - Input data\n * @param options - Repository options\n */\n private executeInlineAsync(\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 ): void {\n // Execute in next tick, don't await - use setImmediate for true async\n setImmediate(async () => {\n try {\n // Call doOperation with isWorkerExecution to prevent infinite loop\n await this.doOperation(operation, executionContext, id_or_ids_or_filter, data, {\n ...options,\n isWorkerExecution: true, // Prevents runtime mode check\n });\n } catch (error) {\n this.logger.error('Inline async operation failed', {\n operationPathKey: ResourcesConfig_OperationPathUtils.createOperationPathKeyFromOperation(operation as any),\n ...projectCaughtErrorLogFields(error),\n });\n }\n });\n }\n\n private async callRepository(\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\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n\n const repository = this.repositoriesRegistry.getRepositoryOrThrow(resourceType);\n\n\n const operationRepositoryPath = ResourcesConfig_OperationPathUtils.extractOperationRepositoryPath(operation);\n return repository.doByPath(operationRepositoryPath, executionContext, id_or_ids_or_filter, data, options);\n\n }\n\n\n\n // ================================\n // Business Logic Methods\n // ================================\n\n\n private async create(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n data: any,\n options?: RepositoryOptions\n ): Promise<any> {\n\n this.logDebug('Executing create business operation');\n\n // 0. Clean input data (remove mandatory discard fields)\n const cleanedData = this.repositoryHelper.cleanInputData(data, CoreResourceOperation.CREATE);\n this.logDebug('Data cleaned for create operation', {\n originalKeys: typeof data === 'object' ? Object.keys(data) : 'not-object',\n cleanedKeys: typeof cleanedData === 'object' ? Object.keys(cleanedData) : 'not-object'\n });\n\n // 1. Validate input against operation's requestDto\n const validatedData = await this.validateAndTransformInput(executionContext, cleanedData);\n\n // 2. Extract nested data if nested operations are configured\n const resourceRelationships = this.resourceConfiguration.resourceRelationships;\n const childRelationships = getChildDirectionRelationships(resourceRelationships);\n const relationshipsWithNested = childRelationships.filter(rel =>\n this.getResolvedNestedMutationConfig(rel, CoreResourceOperation.CREATE)\n );\n\n const { parentData, nestedData } = relationshipsWithNested.length > 0\n ? this.extractNestedData(validatedData, relationshipsWithNested, CoreResourceOperation.CREATE)\n : { parentData: validatedData, nestedData: {} };\n\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n this.assertGeneratedPdfCreationSupported(resourceType, executionContext);\n\n // 3. Apply business validation\n const businessValidatedData = await this.applyBusinessValidation(CoreResourceOperation.CREATE, parentData, executionContext);\n\n // 3.5. Validate file fields (fail fast before resource creation)\n // ============================================================================\n // FILE FIELD VALIDATION (Pre-CREATE)\n // ============================================================================\n // This validation runs BEFORE resource creation to fail fast if file references\n // are invalid. However, note the following limitations:\n //\n // 1. Files are validated by fileId lookup but scope validation (ensuring the file\n // belongs to the same organization/user scope) relies on organizationId in\n // ExecutionContext. Scope-based file segregation is not fully implemented.\n //\n // 2. The validation doesn't check if the user has permission to link the specific\n // file - only that the file exists and is in UPLOADED status.\n //\n // 3. For PostgreSQL resources, file metadata lookup still uses MongoDB,\n // which could have latency implications.\n //\n // See: .cursor/plans for file/storage context\n // ============================================================================\n const generatedPdfMaterializations: GeneratedPdfMaterializationRecord[] = [];\n let enrichedData: any;\n let result: any;\n try {\n if (this.fileFieldDetection.hasFileFields(resourceType)) {\n await this.fileOperationHandler.validateFileFieldsForCreate(\n businessValidatedData,\n resourceType,\n executionContext,\n this.buildFileRepositoryOptions(options)\n );\n }\n\n const materialized = await this.materializeGeneratedPdfFieldsForCreate(\n businessValidatedData,\n resourceType,\n executionContext,\n options,\n );\n generatedPdfMaterializations.push(...materialized.materializations);\n const materializedBusinessData = materialized.data;\n\n if (this.fileFieldDetection.hasFileFields(resourceType)) {\n await this.fileOperationHandler.validateFileFieldsForCreate(\n materializedBusinessData,\n resourceType,\n executionContext,\n this.buildFileRepositoryOptions(options),\n this.buildGeneratedPdfProcessingOptions(generatedPdfMaterializations),\n );\n }\n\n // 4. Execute pre-creation business logic\n enrichedData = await this.executePreOperationLogic(CoreResourceOperation.CREATE, materializedBusinessData, executionContext);\n\n // 5. Execute repository operation (create parent) and process nested operations\n result = await this.persistCreatedResourceWithSideEffects({\n operation,\n executionContext,\n enrichedData,\n nestedData,\n relationshipsWithNested,\n resourceType,\n generatedPdfMaterializations,\n options,\n });\n } catch (error) {\n await this.cleanupGeneratedPdfMaterializations(generatedPdfMaterializations, executionContext);\n throw error;\n }\n\n // 8. Execute post-creation business logic (including engine cascading + composition seeding).\n // `options` is threaded so composition-seed re-entrancy depth (compositionSeedDepth)\n // survives createAsSystem → create → post-op (createAsSystem synthesises a fresh EC).\n const processedResult = await this.executePostOperationLogic(CoreResourceOperation.CREATE, result, executionContext, undefined, options);\n\n this.logDebug('Create business operation completed');\n return processedResult;\n }\n\n private async persistCreatedResourceWithSideEffects(params: {\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\n executionContext: ExecutionContext<any>;\n enrichedData: any;\n nestedData: Record<string, any>;\n relationshipsWithNested: ResourceRelationship[];\n resourceType: ResourceType;\n generatedPdfMaterializations: GeneratedPdfMaterializationRecord[];\n options?: RepositoryOptions;\n }): Promise<any> {\n // ALWAYS use transaction for file operations, even without nested operations\n // Extract organizationId early (needed for file operations and transactions)\n const hasFileFields = this.fileFieldDetection.hasFileFields(params.resourceType);\n const hasNestedOperations = params.relationshipsWithNested.length > 0 && Object.keys(params.nestedData).length > 0;\n const fileWorkIsSeparatelyCommitted = this.fileMetadataRequiresSeparateCommit(params.resourceType);\n\n if (hasNestedOperations || hasFileFields) {\n return this.executeResourceTransaction(params.executionContext, async (optionsWithTransaction) => {\n // 1. Create resource within transaction\n const parentResult = await this.callRepository(\n params.operation,\n params.executionContext,\n undefined,\n params.enrichedData,\n {\n ...optionsWithTransaction,\n ...this.buildGeneratedPdfProcessingOptions(params.generatedPdfMaterializations),\n },\n );\n\n const activeRelationships = hasNestedOperations\n ? this.filterRelationshipsByParent(params.relationshipsWithNested, parentResult)\n : [];\n\n if (activeRelationships.length > 0) {\n this.assertNestedMutationAdaptersMatchCurrentResource(activeRelationships, params.executionContext);\n }\n\n const runNestedOperations = async (): Promise<void> => {\n if (activeRelationships.length === 0) {\n return;\n }\n await this.processNestedOperations(\n CoreResourceOperation.CREATE,\n parentResult,\n params.nestedData,\n {},\n activeRelationships,\n params.executionContext,\n optionsWithTransaction\n );\n };\n\n const runFileWork = async (): Promise<void> => {\n if (!hasFileFields) {\n return;\n }\n const resourceId = parentResult?._id?.toString() || parentResult?.id;\n if (!resourceId) {\n return;\n }\n const processFileFields = async (fileOptions: RepositoryOptions | undefined): Promise<void> => {\n await this.fileOperationHandler.processFileFieldsForCreate(\n params.enrichedData,\n params.resourceType,\n resourceId,\n params.executionContext,\n fileOptions,\n this.buildGeneratedPdfProcessingOptions(params.generatedPdfMaterializations),\n );\n };\n\n if (fileWorkIsSeparatelyCommitted) {\n // The row's transaction cannot be shared, so the OUTER options are passed\n // and `executeFileMetadataWork` opens the FILES adapter's own transaction.\n await this.executeFileMetadataWork(params.executionContext, params.options, processFileFields);\n return;\n }\n await processFileFields(optionsWithTransaction);\n };\n\n /**\n * Order by COUPLING, not by adapter.\n *\n * Separately-committed file work runs LAST because it cannot be rolled back\n * with the row: running it after everything that can still fail is the\n * smallest possible window for orphaned file metadata. When it joins the\n * row's transaction no such window exists and the original order stands.\n *\n * Both orders PREDATE this refactor and were selected by adapter with no\n * recorded rationale (single commit, 2026-03-30). They are preserved exactly\n * — unifying them is a behaviour change that deserves its own decision and\n * its own test, not a silent ride along a condition swap.\n */\n if (fileWorkIsSeparatelyCommitted) {\n await runNestedOperations();\n await runFileWork();\n } else {\n await runFileWork();\n await runNestedOperations();\n }\n\n return parentResult;\n }, params.options);\n } else {\n // No file fields, no nested operations - no transaction needed\n return this.callRepository(\n params.operation,\n params.executionContext,\n undefined,\n params.enrichedData,\n {\n ...params.options,\n ...this.buildGeneratedPdfProcessingOptions(params.generatedPdfMaterializations),\n },\n );\n }\n }\n\n private async createMany(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n data: any,\n options?: RepositoryOptions\n ): Promise<any[]> {\n\n this.logDebug('Executing createMany business operation');\n\n const normalizedCreateManyPayload = this.normalizeCreateManyRequestPayload(data, executionContext);\n\n // 0. Clean input data array (remove mandatory discard fields)\n const cleanedDataArray = this.repositoryHelper.cleanInputDataArray(\n normalizedCreateManyPayload.data,\n CoreResourceOperation.CREATE_MANY\n );\n const cleanedRequestPayload = {\n ...normalizedCreateManyPayload,\n data: cleanedDataArray,\n };\n this.logDebug('Data array cleaned for createMany operation', {\n originalCount: normalizedCreateManyPayload.data.length,\n cleanedCount: cleanedDataArray?.length\n });\n\n // 1. Validate input against operation's requestDto\n const validatedData = await this.validateAndTransformInput(executionContext, cleanedRequestPayload);\n\n // 2. Extract nested data per item if nested operations are configured\n const resourceRelationships = this.resourceConfiguration.resourceRelationships;\n const childRelationships = getChildDirectionRelationships(resourceRelationships);\n const relationshipsWithNested = childRelationships.filter(rel =>\n this.getResolvedNestedMutationConfig(rel, CoreResourceOperation.CREATE_MANY)\n );\n\n const validatedDataArray = this.normalizeCreateManyInput(validatedData, executionContext);\n\n const { parentDataArray, nestedDataArray } = relationshipsWithNested.length > 0\n ? this.extractNestedDataArray(validatedDataArray, relationshipsWithNested, CoreResourceOperation.CREATE_MANY, executionContext)\n : { parentDataArray: validatedDataArray, nestedDataArray: [] };\n\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n this.assertGeneratedPdfCreationSupported(resourceType, executionContext);\n\n // 3. Apply business validation\n const businessValidatedData = await this.applyBusinessValidation(CoreResourceOperation.CREATE_MANY, parentDataArray, executionContext);\n\n const hasFileFields = this.fileFieldDetection.hasFileFields(resourceType);\n\n if (hasFileFields) {\n for (const item of businessValidatedData) {\n await this.fileOperationHandler.validateFileFieldsForCreate(\n item,\n resourceType,\n executionContext,\n this.buildFileRepositoryOptions(options)\n );\n }\n }\n\n const generatedPdfMaterializations: GeneratedPdfMaterializationRecord[] = [];\n const generatedPdfMaterializationsByRow: GeneratedPdfMaterializationRecord[][] = [];\n let materializedBusinessData = businessValidatedData;\n try {\n const materializedRows: Record<string, any>[] = [];\n for (const [rowIndex, item] of businessValidatedData.entries()) {\n const materialized = await this.materializeGeneratedPdfFieldsForCreate(\n item,\n resourceType,\n executionContext,\n options,\n );\n const rowMaterializations = materialized.materializations.map((entry) => ({\n ...entry,\n rowIndex,\n }));\n materializedRows.push(materialized.data);\n generatedPdfMaterializationsByRow[rowIndex] = rowMaterializations;\n generatedPdfMaterializations.push(...rowMaterializations);\n }\n materializedBusinessData = materializedRows;\n\n if (hasFileFields) {\n for (const [rowIndex, item] of materializedBusinessData.entries()) {\n await this.fileOperationHandler.validateFileFieldsForCreate(\n item,\n resourceType,\n executionContext,\n this.buildFileRepositoryOptions(options),\n this.buildGeneratedPdfProcessingOptions(generatedPdfMaterializationsByRow[rowIndex] ?? []),\n );\n }\n }\n } catch (error) {\n await this.cleanupGeneratedPdfMaterializations(generatedPdfMaterializations, executionContext);\n throw error;\n }\n\n let enrichedData: any;\n try {\n // 4. Execute pre-creation business logic\n enrichedData = await this.executePreOperationLogic(CoreResourceOperation.CREATE_MANY, materializedBusinessData, executionContext);\n } catch (error) {\n await this.cleanupGeneratedPdfMaterializations(generatedPdfMaterializations, executionContext);\n throw error;\n }\n\n const hasNestedOperations = relationshipsWithNested.length > 0 &&\n nestedDataArray.some(item => Object.keys(item).length > 0);\n const requiresTransactionalBulkCreate = hasNestedOperations || hasFileFields;\n\n let result: any[];\n\n if (requiresTransactionalBulkCreate) {\n if (hasNestedOperations) {\n this.assertNestedMutationAdaptersMatchCurrentResource(relationshipsWithNested, executionContext);\n }\n try {\n result = await this.executeResourceTransaction(executionContext, async (optionsWithTransaction) => {\n const parentResults = await this.callRepository(\n operation,\n executionContext,\n undefined,\n enrichedData,\n {\n ...optionsWithTransaction,\n ...this.buildGeneratedPdfProcessingOptions(generatedPdfMaterializations, generatedPdfMaterializationsByRow),\n },\n );\n\n if (hasFileFields) {\n if (this.fileMetadataRequiresSeparateCommit(resourceType)) {\n await this.executeFileMetadataWork(\n executionContext,\n options,\n async (fileOptions) => this.processBulkCreateFileFields(\n parentResults,\n enrichedData,\n resourceType,\n executionContext,\n fileOptions,\n this.buildGeneratedPdfProcessingOptions(generatedPdfMaterializations, generatedPdfMaterializationsByRow),\n ),\n );\n } else {\n await this.processBulkCreateFileFields(\n parentResults,\n enrichedData,\n resourceType,\n executionContext,\n optionsWithTransaction,\n this.buildGeneratedPdfProcessingOptions(generatedPdfMaterializations, generatedPdfMaterializationsByRow),\n );\n }\n }\n\n await this.processBulkNestedOperations(\n CoreResourceOperation.CREATE_MANY,\n parentResults,\n nestedDataArray,\n [],\n relationshipsWithNested,\n executionContext,\n optionsWithTransaction\n );\n\n return parentResults;\n }, options);\n } catch (error) {\n await this.cleanupGeneratedPdfMaterializations(generatedPdfMaterializations, executionContext);\n throw error;\n }\n } else {\n // 5. Execute repository operation\n try {\n result = await this.callRepository(\n operation,\n executionContext,\n undefined,\n enrichedData,\n {\n ...options,\n ...this.buildGeneratedPdfProcessingOptions(generatedPdfMaterializations, generatedPdfMaterializationsByRow),\n },\n );\n } catch (error) {\n await this.cleanupGeneratedPdfMaterializations(generatedPdfMaterializations, executionContext);\n throw error;\n }\n }\n\n // 6. Execute post-creation business logic (including engine cascading)\n const processedResult = await this.executePostOperationLogic(\n CoreResourceOperation.CREATE_MANY,\n result,\n executionContext,\n undefined,\n options,\n );\n\n this.logDebug('CreateMany business operation completed', { resultCount: processedResult?.length });\n return processedResult;\n }\n\n\n /**\n * Resolve operation variant based on dataMode.\n * Maps dataMode to appropriate variantKey:\n * - RAW -> default variant (no variantKey)\n * - SUMMARY -> 'summary' variant (throws if not found)\n * - CONTEXT -> 'context' variant (throws if not found)\n *\n * Throws error if requested variant doesn't exist (fail-fast).\n */\n private resolveOperationVariant(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n dataMode: DataMode\n ): ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> {\n // Delegate to the registry's shared data-mode resolution (single source of\n // truth with the controller's authorization-time resolution). RAW → base op;\n // SUMMARY/CONTEXT → keyed auto-variant when declared (READ/LIST); SEARCH-like\n // → base op (search is summary by construction, so it has no distinct\n // data-mode variant); otherwise fail fast on a genuinely missing variant.\n const resolved = this.resourcesRegistry.getOperationForDataMode(operation, dataMode) as ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\n this.logDebug('Resolved operation for dataMode', {\n operationIdentifier: operation.operationIdentifier,\n dataMode,\n resolvedVariantKey: resolved.variantKey,\n fellBackToBaseOperation: resolved === operation,\n });\n return resolved;\n }\n\n private async read(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n options?: ServiceOptions\n ): Promise<any> {\n\n // Phase 5 / P5-H (H1) — pre-operation hook dispatch on READ.\n // Symmetric with the existing CREATE/UPDATE/DELETE pre-hook\n // dispatch sites, this fires the registered pre-operation hooks\n // (notably the Phase-5 LAZY guard installed by\n // `wireLazyAccessGuards`) before any data is read. The `data`\n // payload forwarded to hooks is the raw `id_or_ids_or_filter`\n // — LAZY guards ignore it, but future read-side pre-hooks\n // (audit-on-read, cache-warming, access-policy-enforcement)\n // can inspect the requested key. Cost is O(1) Map lookup +\n // empty for-loop when no hook is registered for the resource.\n // Failure semantics: any throw propagates to the caller (P5-A\n // = A1 short-circuits the read), matching the mutating-op pre\n // -hook contract.\n await this.executePreOperationLogic(\n CoreResourceOperation.READ,\n id_or_ids_or_filter,\n executionContext,\n );\n\n // Extract dataMode from ServiceOptions, or infer from operation's variantKey\n // This allows direct URL calls to /resource/{id}/context to use CONTEXT mode\n let dataMode = options?.dataMode ?? DataMode.RAW;\n\n // If operation already has a variantKey (direct URL call), infer dataMode from it\n if (operation.variantKey === OPERATION_VARIANT_KEY.CONTEXT) {\n dataMode = DataMode.CONTEXT;\n } else if (operation.variantKey === OPERATION_VARIANT_KEY.SUMMARY) {\n dataMode = DataMode.SUMMARY;\n }\n\n // Resolve operation variant based on dataMode\n const resolvedOperation = this.resolveOperationVariant(operation, dataMode);\n\n this.logDebug('Executing read business operation', { id_or_ids_or_filter, dataMode, variantKey: resolvedOperation.variantKey });\n\n // 1. Execute repository operation with resolved variant (uses correct repositoryDto)\n const result = await this.callRepository(resolvedOperation, executionContext, id_or_ids_or_filter, undefined, options);\n\n if (!result) {\n return null;\n }\n\n // 2. Process nested read operations if configured\n const resourceRelationships = this.resourceConfiguration.resourceRelationships;\n const childRelationships = getChildDirectionRelationships(resourceRelationships);\n const relationshipsWithNestedRead = childRelationships.filter(rel =>\n this.getResolvedNestedReadConfig(rel)\n );\n\n // Application point #2: Nested READ — filter by discriminator/condition using\n // the read result (parent data) so we only fetch nested children for relationships\n // that are active for this particular parent resource variant.\n if (relationshipsWithNestedRead.length > 0) {\n const activeReadRelationships = this.filterRelationshipsByParent(relationshipsWithNestedRead, result);\n if (activeReadRelationships.length > 0) {\n await this.processNestedRead(result, activeReadRelationships, executionContext, options);\n }\n }\n\n // 3. Process based on DataMode\n let processedResult = result;\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n\n if (dataMode !== DataMode.RAW) {\n // Analyze context needs for virtual fields\n const needs = this.populationService.analyzeContextNeeds(resourceType);\n\n // Fetch computation context if needed (for virtual field computation only)\n let computationContext: { objectContext?: any; userContext?: any } = {};\n if (needs.needsObjectContext || needs.needsUserContext) {\n computationContext = await this.populationService.fetchComputationContext(\n resourceType, result, needs, executionContext\n );\n }\n\n // Compute virtual fields with fault tolerance\n processedResult = await this.virtualFieldsService.computeVirtualFields(\n resourceType, processedResult, executionContext,\n {\n faultTolerant: true,\n includeContextDependent: needs.needsObjectContext || needs.needsUserContext,\n objectContext: computationContext.objectContext,\n userContext: computationContext.userContext,\n forSummary: dataMode === DataMode.SUMMARY,\n }\n );\n\n // Apply population based on DataMode\n // Extract populateFiles option from ServiceOptions (default: true)\n const populateFiles = options?.populateFiles !== false;\n const populationOptions = { populateFiles };\n\n if (dataMode === DataMode.SUMMARY) {\n processedResult = await this.populationService.populateForSummary(\n resourceType, processedResult, executionContext, populationOptions, options\n );\n } else if (dataMode === DataMode.CONTEXT) {\n processedResult = await this.populationService.populateForContext(\n resourceType, processedResult, executionContext, populationOptions, options\n );\n }\n }\n\n // 3. Apply business context enrichment\n const enrichedResult = await this.enrichBusinessContext(CoreResourceOperation.READ, processedResult, executionContext);\n\n this.logDebug('Read business operation completed', { dataMode });\n return enrichedResult;\n }\n\n\n private async update(\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\n this.logDebug('Executing update business operation', { id_or_ids_or_filter });\n\n if (!id_or_ids_or_filter) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { operation: 'UPDATE', missingParameter: 'id_or_ids_or_filter' },\n });\n }\n\n if (!data) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { operation: 'UPDATE', missingParameter: 'data' },\n });\n }\n\n // 0. Clean input data (remove mandatory discard fields)\n const cleanedData = this.repositoryHelper.cleanInputData(data, CoreResourceOperation.UPDATE);\n this.logDebug('Data cleaned for update operation', {\n originalKeys: typeof data === 'object' ? Object.keys(data) : 'not-object',\n cleanedKeys: typeof cleanedData === 'object' ? Object.keys(cleanedData) : 'not-object'\n });\n\n // 1. Validate input against operation's requestDto\n const validatedData = await this.validateAndTransformInput(executionContext, cleanedData);\n\n // 1.5. Extract nested data if nested operations are configured\n const resourceRelationships = this.resourceConfiguration.resourceRelationships;\n const childRelationships = getChildDirectionRelationships(resourceRelationships);\n const relationshipsWithNested = childRelationships.filter(rel =>\n this.getResolvedNestedMutationConfig(rel, CoreResourceOperation.UPDATE)\n );\n\n const { parentData, nestedData, deleteData } = relationshipsWithNested.length > 0\n ? this.extractNestedDataForUpdate(validatedData, relationshipsWithNested)\n : { parentData: validatedData, nestedData: {}, deleteData: {} };\n\n // 2. Get current state - for single updates only (bulk update skips current state fetching)\n let currentState = null;\n if (typeof id_or_ids_or_filter === 'string') {\n currentState = await this.fetchCurrentObjectForOperation(\n CoreResourceOperation.UPDATE,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n id_or_ids_or_filter,\n executionContext,\n options,\n );\n if (!currentState) {\n throw this.errorBuilder.buildError(ErrorType.NOT_FOUND, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: { operation: 'UPDATE', id_or_ids_or_filter },\n });\n }\n }\n\n // 3. Apply business validation for changes\n const businessValidatedData = await this.applyBusinessValidation(CoreResourceOperation.UPDATE, parentData, executionContext, currentState);\n\n // 3.5. Validate file fields (fail fast before resource update)\n // Note: we only reuse validateFileFieldsForCreate() when this UPDATE path does\n // not have a persisted current state to diff against. When currentState exists,\n // processFileFieldsForUpdate() owns validation of newly introduced file ids\n // inside the same transaction as the parent update.\n // ============================================================================\n // FILE FIELD VALIDATION (Pre-UPDATE)\n // ============================================================================\n // Same limitations as CREATE validation apply here. Additionally:\n //\n // 1. Only NEW file references are validated. The old-to-new file transition\n // (unlinking old files, linking new ones) happens in processFileFieldsForUpdate\n // which runs AFTER the resource update, not during validation.\n //\n // 2. If a file being replaced is still referenced by other resources, this\n // validation doesn't check for that. File reference counting is not implemented.\n //\n // 3. Bulk UPDATE_MANY now has its own dedicated path: it validates explicit\n // file-field mutations and reloads per-parent snapshots before processing\n // file diffs inside the transactional bulk branch.\n //\n // See: .cursor/plans for file/storage context\n // ============================================================================\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n if (this.fileFieldDetection.hasFileFields(resourceType) && !currentState) {\n try {\n await this.fileOperationHandler.validateFileFieldsForCreate(\n businessValidatedData,\n resourceType,\n executionContext,\n this.buildFileRepositoryOptions(options)\n );\n } catch (error) {\n // File validation errors should fail the operation\n throw error;\n }\n }\n\n // 4. Execute pre-update business logic\n const enrichedData = await this.executePreOperationLogic(CoreResourceOperation.UPDATE, businessValidatedData, executionContext, currentState);\n\n // 5. Execute repository operation (update parent) and process nested operations\n // ALWAYS use transaction for file operations, even without nested operations\n // Extract organizationId early (needed for file operations and transactions)\n const hasFileFields = this.fileFieldDetection.hasFileFields(resourceType);\n const hasNestedOperations = relationshipsWithNested.length > 0 && (Object.keys(nestedData).length > 0 || Object.keys(deleteData).length > 0);\n // Note: File operations only for single updates (currentState is only fetched for single updates)\n const canProcessFileFields = hasFileFields && currentState && typeof id_or_ids_or_filter === 'string';\n const fileWorkIsSeparatelyCommitted = this.fileMetadataRequiresSeparateCommit(resourceType);\n let result: any;\n\n if (hasNestedOperations || canProcessFileFields) {\n result = await this.executeResourceTransaction(executionContext, async (optionsWithTransaction) => {\n // 1. Update resource within transaction\n const parentResult = await this.callRepository(operation, executionContext, id_or_ids_or_filter, enrichedData, optionsWithTransaction);\n\n const activeRelationships = hasNestedOperations\n ? this.filterRelationshipsByParent(relationshipsWithNested, parentResult)\n : [];\n\n if (activeRelationships.length > 0) {\n this.assertNestedMutationAdaptersMatchCurrentResource(activeRelationships, executionContext);\n }\n\n const runNestedOperations = async (): Promise<void> => {\n if (activeRelationships.length === 0) {\n return;\n }\n await this.processNestedOperations(\n CoreResourceOperation.UPDATE,\n parentResult,\n nestedData,\n deleteData,\n activeRelationships,\n executionContext,\n optionsWithTransaction\n );\n };\n\n const runFileWork = async (): Promise<void> => {\n if (!canProcessFileFields) {\n return;\n }\n const resourceId = typeof id_or_ids_or_filter === 'string'\n ? id_or_ids_or_filter\n : parentResult?._id?.toString() || parentResult?.id;\n if (!resourceId) {\n return;\n }\n const processFileFields = async (fileOptions: RepositoryOptions | undefined): Promise<void> => {\n await this.fileOperationHandler.processFileFieldsForUpdate(\n enrichedData,\n currentState,\n resourceType,\n resourceId,\n executionContext,\n fileOptions\n );\n };\n\n if (fileWorkIsSeparatelyCommitted) {\n // The row's transaction cannot be shared, so the OUTER options are passed\n // and `executeFileMetadataWork` opens the FILES adapter's own transaction.\n await this.executeFileMetadataWork(executionContext, options, processFileFields);\n return;\n }\n await processFileFields(optionsWithTransaction);\n };\n\n // Order by COUPLING, not by adapter — see the CREATE sibling for the full\n // rationale. Separately-committed file work runs LAST because it cannot roll\n // back with the row; both orders are preserved exactly as they were.\n if (fileWorkIsSeparatelyCommitted) {\n await runNestedOperations();\n await runFileWork();\n } else {\n await runFileWork();\n await runNestedOperations();\n }\n\n return parentResult;\n }, options);\n } else {\n // No file fields, no nested operations - no transaction needed\n result = await this.callRepository(operation, executionContext, id_or_ids_or_filter, enrichedData, options);\n }\n\n // 7. Execute post-update business logic (including engine cascading)\n const processedResult = await this.executePostOperationLogic(\n CoreResourceOperation.UPDATE,\n result,\n executionContext,\n currentState,\n options,\n );\n\n this.logDebug('Update business operation completed');\n return processedResult;\n }\n\n private async executeGeneratedFileRegenerateOperation(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n fieldName: string,\n executionContext: ExecutionContext<any>,\n idOrIdsOrFilter: IdOrIdsOrFilterType | undefined,\n currentObject: any,\n options?: RepositoryOptions,\n ): Promise<{ file: { fileId: string; updatedAt: Date }; resource: any }> {\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const resourceId = typeof idOrIdsOrFilter === 'string'\n ? idOrIdsOrFilter\n : this.getResourceIdValue(currentObject);\n if (!resourceId || !currentObject) {\n throw this.errorBuilder.buildError(ErrorType.NOT_FOUND, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: { operation: operation.operationIdentifier, fieldName, idOrIdsOrFilter },\n });\n }\n\n const fileField = this.fileFieldDetection.getFileFieldMetadata(resourceType, fieldName);\n if (fileField?.fileMetadata.generation?.source !== FileGenerationSource.PDF_TEMPLATE) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `Generated file regenerate operation targets a non-generated PDF field: \"${resourceType}.${fieldName}\".`,\n resourceType,\n fieldName,\n },\n });\n }\n\n this.assertGeneratedFileMaterializationCommitsWithRow(\n resourceType,\n executionContext,\n 'Generated PDF regenerate is not yet supported for PostgreSQL-backed resources because FILES metadata is Mongo-backed and cannot be swapped atomically with the parent row.',\n { fieldName },\n );\n\n const generated = await this.pdfGenerationOrchestrator.generateForField({\n resourceType,\n parentRecord: currentObject,\n fieldName,\n fileMetadata: fileField.fileMetadata,\n executionContext,\n repositoryOptions: this.buildFileRepositoryOptions(options),\n renderPhase: PdfGenerationRenderPhase.REGENERATE,\n locale: getConfiguredPrimaryLanguage(this.appConfigService.config),\n defaultLocale: getConfiguredPrimaryLanguage(this.appConfigService.config),\n });\n const generatedFileValue = {\n fileId: generated.fileId,\n updatedAt: generated.updatedAt,\n };\n const updatePatch = this.buildGeneratedFileFieldPatch(fieldName, generatedFileValue);\n const repositoryPatch = this.buildGeneratedFileRepositoryPatch(fieldName, generatedFileValue);\n const previousGeneratedFileId = this.getGeneratedFileIdAtPath(currentObject, fieldName);\n const processingOptions = this.buildGeneratedPdfProcessingOptions([{\n ...generated,\n resourceType,\n fieldName,\n }]);\n\n try {\n const updatedResource = await this.executeResourceTransaction(executionContext, async (optionsWithTransaction) => {\n const parentResult = await this.callRepository(\n operation,\n executionContext,\n resourceId,\n repositoryPatch,\n {\n ...optionsWithTransaction,\n ...processingOptions,\n },\n );\n\n await this.fileOperationHandler.processFileFieldsForUpdate(\n updatePatch,\n currentObject,\n resourceType,\n resourceId,\n executionContext,\n optionsWithTransaction,\n processingOptions,\n );\n\n await this.fileOperationHandler.softDeleteGeneratedFileReplacement({\n fileId: previousGeneratedFileId,\n replacementFileId: generated.fileId,\n fieldName,\n executionContext,\n options: optionsWithTransaction,\n });\n\n return parentResult;\n }, options);\n\n return {\n file: generatedFileValue,\n resource: updatedResource,\n };\n } catch (error) {\n await this.cleanupGeneratedPdfMaterializations([{\n ...generated,\n resourceType,\n fieldName,\n }], executionContext);\n throw error;\n }\n }\n\n private async updateMany(\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\n this.logDebug('Executing updateMany business operation', { id_or_ids_or_filter });\n\n if (!id_or_ids_or_filter) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { operation: 'UPDATE_MANY', missingParameter: 'id_or_ids_or_filter' },\n });\n }\n\n if (!data) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { operation: 'UPDATE_MANY', missingParameter: 'data' },\n });\n }\n\n // 0. Clean input data (remove mandatory discard fields - preserve _id for updateMany)\n const cleanedData = this.repositoryHelper.cleanInputData(data, CoreResourceOperation.UPDATE_MANY);\n this.logDebug('Data cleaned for updateMany operation', {\n originalKeys: typeof data === 'object' ? Object.keys(data) : 'not-object',\n cleanedKeys: typeof cleanedData === 'object' ? Object.keys(cleanedData) : 'not-object'\n });\n\n // 1. Validate input against operation's requestDto\n const validatedData = await this.validateAndTransformInput(executionContext, cleanedData);\n\n // 1.5. Extract nested data if nested operations are configured\n const resourceRelationships = this.resourceConfiguration.resourceRelationships;\n const childRelationships = getChildDirectionRelationships(resourceRelationships);\n const relationshipsWithNested = childRelationships.filter(rel =>\n this.getResolvedNestedMutationConfig(rel, CoreResourceOperation.UPDATE_MANY)\n );\n\n const { parentData, nestedData, deleteData } = relationshipsWithNested.length > 0\n ? this.extractNestedDataForUpdate(validatedData, relationshipsWithNested)\n : { parentData: validatedData, nestedData: {}, deleteData: {} };\n\n // 2. Apply business validation for bulk changes (no current state fetching for bulk operations)\n const businessValidatedData = await this.applyBusinessValidation(CoreResourceOperation.UPDATE_MANY, parentData, executionContext);\n\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const hasFileFields = this.fileFieldDetection.hasFileFields(resourceType);\n const hasBulkFileMutations = hasFileFields && this.hasExplicitFileFieldMutations(resourceType, businessValidatedData);\n if (hasBulkFileMutations) {\n await this.fileOperationHandler.validateFileFieldsForCreate(\n businessValidatedData,\n resourceType,\n executionContext,\n options\n );\n }\n\n // 3. Execute pre-update business logic.\n //\n // Phase 3.2 fix (review Findings #1/#2): if any pre-operation hook is\n // registered for this resource, load the bulk target snapshots so\n // the hook payload can be materialised as `Array<{...patch, _id}>`\n // inside `executePreOperationLogic` (per-row anchors are required\n // by Level-B seeding's P3-F=F1 invariant — the dispatcher's\n // `runResourceLifecycle` throws CONFIGURATION without `_id`).\n //\n // **Cost gate**: the snapshot load only runs when a hook is actually\n // subscribed — UPDATE_MANY callers without any wired hook keep their\n // pre-Phase-3.2 cost envelope (no extra read). This trade-off is the\n // explicit framework convention: pre-hook registration is the opt-in\n // for the per-row materialisation cost.\n //\n // The resolved `currentStates` are NOT reused beyond pre-hook\n // dispatch — UPDATE_MANY's later transactional / file-mutation\n // paths still load their own per-parent snapshots when needed\n // (see `loadBulkParentStateMap` further down). Re-loading there is\n // intentional: it runs INSIDE the transaction (which the pre-hook\n // load does not), and the snapshot semantics differ.\n const preHookCurrentStates = this.servicesRegistry.hasPreOperationHooks(resourceType)\n ? await this.loadBulkTargetResources(executionContext, id_or_ids_or_filter, options)\n : undefined;\n let enrichedData: any;\n if (preHookCurrentStates !== undefined && preHookCurrentStates.length === 0) {\n // Mirror DELETE_MANY's empty-selector early-exit: no rows ⇒ no\n // pre-hook dispatch (Level-B seeds have nothing to anchor to,\n // and any non-seed hook is observation-only on a zero-row op).\n enrichedData = businessValidatedData;\n } else {\n enrichedData = await this.executePreOperationLogic(\n CoreResourceOperation.UPDATE_MANY,\n businessValidatedData,\n executionContext,\n preHookCurrentStates,\n );\n }\n\n const hasNestedOperations = relationshipsWithNested.length > 0 &&\n (Object.keys(nestedData).length > 0 || Object.keys(deleteData).length > 0);\n const requiresTransactionalBulkUpdate = hasNestedOperations || hasBulkFileMutations;\n\n let result: any[];\n\n if (requiresTransactionalBulkUpdate) {\n // UPDATE_MANY shares the same limitation as CREATE_MANY: once nested payloads\n // or file-field mutations are present, the service currently relies on\n // MongoDBService to own the outer transaction while parent updates and\n // follow-up side effects are replayed.\n this.assertMongoBulkTransactionSupport(\n executionContext,\n hasNestedOperations\n ? 'Bulk nested update transactions currently require MongoDB-backed resources'\n : 'Bulk update file-field transactions currently require MongoDB-backed resources'\n );\n\n result = await this.executeResourceTransaction(\n executionContext,\n async (optionsWithTransaction) => {\n const currentStatesById = hasBulkFileMutations\n ? await this.loadBulkParentStateMap(executionContext, id_or_ids_or_filter, optionsWithTransaction)\n : new Map<string, any>();\n const parentResults = await this.callRepository(\n operation,\n executionContext,\n id_or_ids_or_filter,\n enrichedData,\n optionsWithTransaction\n );\n\n if (Object.keys(deleteData).length > 0 && Array.isArray(parentResults) && parentResults.length > 1) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n operation: CoreResourceOperation.UPDATE_MANY,\n parentResultsCount: parentResults.length,\n reason: 'nested delete payloads in UPDATE_MANY are only supported when the mutation targets exactly one parent resource',\n },\n }\n );\n }\n\n if (hasBulkFileMutations) {\n await this.processBulkUpdateFileFields(\n parentResults,\n currentStatesById,\n enrichedData,\n resourceType,\n executionContext,\n optionsWithTransaction\n );\n }\n\n // Contract: UPDATE_MANY uses broadcast semantics for nested create/update payloads.\n // The validated nestedData object is treated as one shared envelope and replayed\n // once per matched parent result. This is intentional: bulk parent mutation +\n // nested mutation means \"apply this same nested update plan to every parent that\n // matched the bulk selector\". Nested deletes remain stricter because replaying the\n // same child-id delete list across multiple parents is ambiguous and unsafe.\n await this.processBulkNestedOperations(\n CoreResourceOperation.UPDATE_MANY,\n parentResults,\n Array.isArray(parentResults) ? parentResults.map(() => nestedData) : [],\n Array.isArray(parentResults) ? parentResults.map(() => deleteData) : [],\n relationshipsWithNested,\n executionContext,\n optionsWithTransaction\n );\n\n return parentResults;\n },\n options,\n );\n } else {\n // 4. Execute repository operation\n result = await this.callRepository(operation, executionContext, id_or_ids_or_filter, enrichedData, options);\n }\n\n // 5. Execute post-update business logic (including engine cascading)\n const processedResult = await this.executePostOperationLogic(\n CoreResourceOperation.UPDATE_MANY,\n result,\n executionContext,\n undefined,\n options,\n );\n\n this.logDebug('UpdateMany business operation completed', { resultCount: processedResult?.length });\n return processedResult;\n }\n\n private async delete(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<string | string[]> {\n\n this.logDebug('Executing delete business operation', { id_or_ids_or_filter });\n\n if (!id_or_ids_or_filter) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { operation: 'DELETE', missingParameter: 'id_or_ids_or_filter' },\n });\n }\n\n // 1. Get current state - for single deletes only (bulk delete skips current state fetching)\n let currentState = null;\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const hasFileFields = this.fileFieldDetection.hasFileFields(resourceType);\n\n // ============================================================================\n // FILE MANAGEMENT DELETE NOTES\n // ============================================================================\n //\n // Current contract:\n // 1. Parent deletes fail closed if pre-delete file cleanup throws.\n // 2. Mongo-backed parents still keep parent + file metadata work in one Mongo\n // transaction context.\n // 3. PostgreSQL-backed parents use a best-effort split boundary: file metadata\n // cleanup runs through the Mongo-backed FILES seam first, then parent delete\n // runs inside the PostgreSQL transaction.\n //\n // Remaining limitations:\n // 1. Cross-database delete is still best-effort, not one ACID transaction.\n // 2. File storage cleanup stays outside the parent DB rollback boundary and is\n // intentionally owned later by the cleanup batch.\n // 3. Lifecycle-delete coverage for child resources that own file fields is\n // still narrower than the direct parent delete path.\n //\n // NOTE: organizationId validation is intentionally NOT done here. Tenant isolation\n // is enforced at the FilesBackendService level, not duplicated in the service handler.\n // See: .cursor/plans for file/storage context\n //\n // ============================================================================\n\n if (typeof id_or_ids_or_filter === 'string') {\n currentState = await this.fetchCurrentObjectForOperation(\n CoreResourceOperation.DELETE,\n resourceType,\n id_or_ids_or_filter,\n executionContext,\n options,\n );\n if (!currentState) {\n if (\n this.hasContextAddressedSingletonParentScope(operation, executionContext)\n || this.hasContextAddressedAssociationParentScope(operation, executionContext)\n || executionContext.getContextResourceIds().size > 0\n ) {\n throw this.errorBuilder.buildError(ErrorType.NOT_FOUND, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: {\n operation: CoreResourceOperation.DELETE,\n id_or_ids_or_filter,\n reason: 'Explicit child id does not match the context-addressed operation scope',\n },\n });\n }\n return '';\n }\n\n // 2. Check business constraints for deletion\n await this.validateDeletionConstraints(currentState, executionContext);\n\n // 3. Execute pre-deletion business logic\n await this.executePreOperationLogic(CoreResourceOperation.DELETE, currentState, executionContext);\n\n // 4. Execute repository operation plus lifecycle cascading inside the\n // resource transaction so child-delete failures can still roll back the\n // parent row on same-adapter paths.\n const result = await this.executeResourceTransaction(executionContext, async (optionsWithTransaction) => {\n if (hasFileFields) {\n if (this.fileMetadataRequiresSeparateCommit(resourceType)) {\n await this.executeFileMetadataWork(\n executionContext,\n options,\n async (fileOptions) => this.fileOperationHandler.processFileFieldsForDelete(\n resourceType,\n id_or_ids_or_filter as string,\n executionContext,\n fileOptions\n )\n );\n } else {\n await this.fileOperationHandler.processFileFieldsForDelete(\n resourceType,\n id_or_ids_or_filter as string,\n executionContext,\n optionsWithTransaction\n );\n }\n }\n\n const deleteResult = await this.callRepository(\n operation,\n executionContext,\n id_or_ids_or_filter,\n undefined,\n optionsWithTransaction\n );\n\n await this.executeLifecycleOperations(\n CoreResourceOperation.DELETE,\n deleteResult,\n executionContext,\n currentState,\n optionsWithTransaction\n );\n\n // RAG removal seam — ROW DELETE (single). Registered post-commit on the delete transaction,\n // so an aborted delete never destroys chunks for a row that survived.\n const deletedRowId = (typeof deleteResult === 'string' && deleteResult.length > 0)\n ? deleteResult\n : (currentState ? this.getResourceIdValue(currentState) : undefined);\n if (deletedRowId) {\n await this.runRagChunkRemovalForDeletedRows(\n resourceType,\n [deletedRowId],\n 'row-delete',\n optionsWithTransaction,\n );\n }\n\n return deleteResult;\n }, options);\n\n // 5. Execute non-cascading post-deletion logic after the delete transaction commits.\n await this.executeAdditionalPostOperationLogic(\n CoreResourceOperation.DELETE,\n result,\n executionContext,\n currentState,\n options,\n );\n\n this.logDebug('Delete business operation completed');\n return result;\n }\n\n const deleteManyOperationPath = this.resourcesRegistry.getServiceOperationPathDefault(\n resourceType,\n CoreResourceOperation.DELETE_MANY\n );\n const deleteManyOperation = this.resourcesRegistry.getOperationFromPath(deleteManyOperationPath) as ResourceConfiguration_Operation<\n TCustomOperationEnum,\n TCoreOperationEnum,\n TMainSchema\n >;\n\n return this.deleteMany(deleteManyOperation, executionContext, id_or_ids_or_filter, options);\n }\n\n private async deleteMany(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<string[]> {\n\n this.logDebug('Executing deleteMany business operation', { id_or_ids_or_filter });\n\n if (!id_or_ids_or_filter) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { operation: 'DELETE_MANY', missingParameter: 'id_or_ids_or_filter' },\n });\n }\n\n // 1. Fetch resources BEFORE deletion so post-delete lifecycle logic can still\n // evaluate relationship activation against real parent snapshots. The same\n // snapshot set is also reused for pre-delete file handling.\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const hasFileFields = this.fileFieldDetection.hasFileFields(resourceType);\n const childRelationships = getChildDirectionRelationships(\n this.resourceConfiguration.resourceRelationships\n );\n const fileWorkIsSeparatelyCommitted = this.fileMetadataRequiresSeparateCommit(resourceType);\n const hasLifecycleDeleteRelationships = childRelationships\n .some((relationship) => this.getResolvedLifecycleOnParentDelete(relationship)?.enabled === true);\n const hasFileOwningChildRelationships = childRelationships\n .some((relationship) => this.fileFieldDetection.hasFileFields(relationship.resourceType2 as ResourceType));\n const currentStates = await this.loadBulkTargetResources(executionContext, id_or_ids_or_filter, options);\n\n // Pre-deletion business logic dispatch (Phase-3 P3-A=A1: hook throws abort the\n // entire deleteMany before any side-effect — file cleanup, transaction, repo\n // delete, lifecycle cascades, post-hooks). Symmetric with the singular DELETE\n // path at L3143 and with CREATE_MANY/UPDATE_MANY which call this method on\n // their own data shape. The payload is the resolved `currentStates` array (NOT\n // the raw filter) so hooks observe the same row snapshots that the post-hook\n // and lifecycle layers receive. Skipped when no rows matched, matching the\n // singular DELETE early-exit on missing currentState.\n if (currentStates.length > 0) {\n await this.executePreOperationLogic(\n CoreResourceOperation.DELETE_MANY,\n currentStates,\n executionContext,\n );\n }\n\n // ============================================================================\n // FILE MANAGEMENT DELETE_MANY NOTES\n // ============================================================================\n //\n // Current contract:\n // 1. Bulk deletes now keep lifecycle cascades inside the parent resource\n // transaction whenever a shared same-adapter transaction is available.\n // 2. MongoDB-backed bulk deletes with file fields reuse that same\n // transaction for file metadata cleanup plus parent-row deletion.\n // 3. Non-Mongo bulk deletes without lifecycle still fail closed before the\n // repository delete if any resource-level file cleanup throws.\n // 4. File cleanup no longer inherits a foreign PostgreSQL transaction when the\n // parent bulk delete is called inside an outer SQL transaction.\n //\n // Remaining limitations:\n // 1. PostgreSQL-backed bulk deletes still have no shared parent+file rollback\n // boundary because FILES remains Mongo-backed by design.\n // 2. Fetching all resources before deletion can be expensive for large\n // datasets. Consider streaming/pagination for very large deletes.\n // 3. Scope-based cleanup still relies on FilesBackendService boundaries rather\n // than service-layer duplication.\n //\n // NOTE: organizationId validation is intentionally NOT done here. Tenant isolation\n // is enforced at the FilesBackendService level, not duplicated in the service handler.\n //\n // ============================================================================\n\n if (\n this.fileMetadataRequiresSeparateCommit(resourceType)\n && hasFileOwningChildRelationships\n && !hasLifecycleDeleteRelationships\n ) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: 'PostgreSQL bulk delete is not supported for resources with file-owning child relationships unless service-managed lifecycle delete is enabled',\n resourceType,\n },\n }\n );\n }\n\n const processBulkDeleteFileCleanup = async (fileRepositoryOptions?: RepositoryOptions) => {\n const batchSize = 100;\n for (let i = 0; i < currentStates.length; i += batchSize) {\n const batch = currentStates.slice(i, i + batchSize);\n\n for (const resource of batch) {\n const resourceId = resource._id?.toString() || resource.id;\n if (!resourceId) {\n this.logger.warn('Resource missing ID in bulk delete, skipping file processing', {\n resource,\n });\n continue;\n }\n\n await this.fileOperationHandler.processFileFieldsForDelete(\n resourceType,\n resourceId,\n executionContext,\n fileRepositoryOptions\n );\n }\n }\n };\n\n /**\n * A transaction is required when file cleanup will run INSIDE it — that is the\n * only reason the row delete and the cleanup must succeed or fail together.\n * When file work is committed separately there is nothing to bind, so opening a\n * transaction for that reason alone would buy no atomicity (and would fail\n * outright on a standalone MongoDB).\n */\n const requiresTransactionalBulkDelete = hasLifecycleDeleteRelationships\n || (hasFileFields && !fileWorkIsSeparatelyCommitted);\n\n const processBulkDeleteWithinTransaction = async (\n optionsWithTransaction: RepositoryOptions\n ): Promise<string[]> => {\n if (hasFileFields) {\n if (fileWorkIsSeparatelyCommitted) {\n await this.executeFileMetadataWork(\n executionContext,\n optionsWithTransaction,\n async (fileOptions) => processBulkDeleteFileCleanup(fileOptions)\n );\n } else {\n await processBulkDeleteFileCleanup(optionsWithTransaction);\n }\n }\n\n const deleteResult = await this.callRepository(\n operation,\n executionContext,\n id_or_ids_or_filter,\n undefined,\n optionsWithTransaction\n );\n\n if (hasLifecycleDeleteRelationships) {\n await this.executeLifecycleOperations(\n CoreResourceOperation.DELETE_MANY,\n deleteResult,\n executionContext,\n currentStates,\n optionsWithTransaction\n );\n }\n\n // RAG removal seam — ROW DELETE (bulk, transactional path). Post-commit on the bulk\n // transaction; the non-transactional branch below carries its own call.\n await this.runRagChunkRemovalForDeletedRows(\n resourceType,\n this.collectDeletedRowIdsForRagRemoval(deleteResult, currentStates),\n 'row-delete-many',\n optionsWithTransaction,\n );\n\n return deleteResult;\n };\n\n let result: string[];\n\n if (requiresTransactionalBulkDelete) {\n if (hasFileFields && !fileWorkIsSeparatelyCommitted) {\n this.assertMongoBulkTransactionSupport(\n executionContext,\n 'Bulk delete file-field transactions currently require MongoDB-backed resources'\n );\n }\n\n result = await this.executeResourceTransaction(\n executionContext,\n async (optionsWithTransaction) => processBulkDeleteWithinTransaction(optionsWithTransaction),\n options\n );\n\n await this.executeAdditionalPostOperationLogic(\n CoreResourceOperation.DELETE_MANY,\n result,\n executionContext,\n currentStates,\n options,\n );\n } else {\n if (hasFileFields) {\n const fileRepositoryOptions = this.buildFileRepositoryOptions(options);\n if (!this.mongoDBService) {\n this.logger.warn('Transaction support unavailable for file operations during DELETE_MANY, processing sequentially', {\n resourceType,\n reason: 'MongoDBService not available'\n });\n }\n\n // Process file fields for each resource BEFORE deletion so non-Mongo bulk\n // paths still fail closed before the repository mutation lands.\n await processBulkDeleteFileCleanup(fileRepositoryOptions);\n }\n\n // 2. Execute repository operation (delete resources)\n result = await this.callRepository(operation, executionContext, id_or_ids_or_filter, undefined, options);\n\n // RAG removal seam — ROW DELETE (bulk, non-transactional path). The delete is already durable,\n // so this runs inline (still log-not-throw — the shared failure contract).\n await this.runRagChunkRemovalForDeletedRows(\n resourceType,\n this.collectDeletedRowIdsForRagRemoval(result, currentStates),\n 'row-delete-many',\n options,\n );\n\n // 3. Execute post-deletion business logic (including engine cascading)\n await this.executePostOperationLogic(\n CoreResourceOperation.DELETE_MANY,\n result,\n executionContext,\n currentStates,\n options,\n );\n }\n\n this.logDebug('DeleteMany business operation completed', { deletedCount: result?.length });\n return result;\n }\n\n private async list(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n filter?: FilterQuery<any>,\n // `sort` rides alongside page/limit (a local widening — NOT a change to the\n // shared `Resources_PaginationRequest` request DTO) and is forwarded into\n // `listOptions` for the repository to apply. Priority = key order.\n pagination?: Partial<Resources_PaginationRequest> & { sort?: Record<string, 1 | -1> },\n options?: ServiceOptions\n ): Promise<any[] | Resources_PaginatedResult<any>> {\n\n // Phase 5 / P5-H (H1) — pre-operation hook dispatch on LIST.\n // Same rationale as the READ branch above: gives the LAZY\n // guard installed by `wireLazyAccessGuards` (Phase 5.C) a\n // chance to materialize the seed row BEFORE the list scan.\n // The raw `filter` is passed as the hook payload so future\n // read-side pre-hooks can inspect the user's filter intent;\n // the LAZY guard itself ignores it.\n await this.executePreOperationLogic(\n CoreResourceOperation.LIST,\n filter ?? {},\n executionContext,\n );\n\n const paginated = options?.paginated ?? false;\n // Extract dataMode from ServiceOptions, or infer from operation's variantKey\n // This allows direct URL calls to /resource/context to use CONTEXT mode\n let dataMode = options?.dataMode ?? DataMode.RAW;\n\n // If operation already has a variantKey (direct URL call), infer dataMode from it\n if (operation.variantKey === OPERATION_VARIANT_KEY.CONTEXT) {\n dataMode = DataMode.CONTEXT;\n } else if (operation.variantKey === OPERATION_VARIANT_KEY.SUMMARY) {\n dataMode = DataMode.SUMMARY;\n }\n\n // Resolve operation variant based on dataMode\n const resolvedOperation = this.resolveOperationVariant(operation, dataMode);\n\n this.logDebug('Executing list business operation', { hasFilter: !!filter, pagination, paginated, dataMode, variantKey: resolvedOperation.variantKey, hasOptions: !!options });\n\n // 1. Apply business filtering to the provided filter\n const businessFilter = await this.applyBusinessFilter(filter || {}, executionContext);\n\n // 2. Execute repository operation with resolved variant (uses correct repositoryDto) - pass filter and pagination\n const listOptions = pagination ? { ...options, listOptions: pagination } : options;\n const result = await this.callRepository(resolvedOperation, executionContext, businessFilter, undefined, listOptions);\n\n // 3. Process based on DataMode\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n\n const processItems = async (items: any[]): Promise<any[]> => {\n if (dataMode === DataMode.RAW) {\n // No population or virtual fields processing\n return items;\n }\n\n // Analyze context needs for virtual fields\n const needs = this.populationService.analyzeContextNeeds(resourceType);\n const includeContextDependent = needs.needsObjectContext || needs.needsUserContext;\n\n // Process each item with virtual fields\n let processedItems = items;\n if (includeContextDependent) {\n // Process items with computation context (slower path)\n processedItems = await Promise.all(\n items.map(async (item) => {\n const computationContext = await this.populationService.fetchComputationContext(\n resourceType, item, needs, executionContext\n );\n return this.virtualFieldsService.computeVirtualFields(\n resourceType, item, executionContext,\n {\n faultTolerant: true,\n includeContextDependent: true,\n objectContext: computationContext.objectContext,\n userContext: computationContext.userContext,\n forSummary: dataMode === DataMode.SUMMARY,\n }\n );\n })\n );\n } else {\n // Process items without context fetching (fast path)\n processedItems = await Promise.all(\n items.map((item) => this.virtualFieldsService.computeVirtualFields(\n resourceType, item, executionContext, {\n faultTolerant: true,\n forSummary: dataMode === DataMode.SUMMARY,\n }\n ))\n );\n }\n\n // Apply population based on DataMode\n // Extract populateFiles option from ServiceOptions (default: true)\n const populateFiles = options?.populateFiles !== false;\n const populationOptions = { populateFiles };\n\n if (dataMode === DataMode.SUMMARY) {\n return this.populationService.populateListForSummary(resourceType, processedItems, executionContext, populationOptions, options);\n } else if (dataMode === DataMode.CONTEXT) {\n return this.populationService.populateListForContext(resourceType, processedItems, executionContext, populationOptions, options);\n }\n\n return processedItems;\n };\n\n // 4. Handle both raw array and paginated response from repository\n if (paginated && result.data !== undefined) {\n // Repository returned { data: [...], pagination: {...} }\n const processedData = await processItems(result.data);\n const enrichedData = await Promise.all(\n processedData.map((item: any) => this.enrichBusinessContext(CoreResourceOperation.LIST, item, executionContext))\n );\n this.logDebug('List business operation completed (paginated)', { count: enrichedData.length, pagination: result.pagination, dataMode });\n this.recordPlatformDirectoryAccess(operation, executionContext, CoreResourceOperation.LIST, enrichedData.length);\n return { data: enrichedData, pagination: result.pagination };\n } else {\n // Repository returned raw array\n const items = Array.isArray(result) ? result : result.data || [];\n const processedData = await processItems(items);\n const enrichedData = await Promise.all(\n processedData.map((item: any) => this.enrichBusinessContext(CoreResourceOperation.LIST, item, executionContext))\n );\n this.logDebug('List business operation completed (raw)', { count: enrichedData.length, dataMode });\n this.recordPlatformDirectoryAccess(operation, executionContext, CoreResourceOperation.LIST, enrichedData.length);\n return enrichedData;\n }\n }\n\n /**\n * Record an APPLICATION-WIDE directory enumeration, when that is what just happened.\n *\n * assurance-control: WILDO.ACCESS.AUTHORIZATION_DECISION_AUDIT — an unconfined administrative read\n * of application-wide data leaves evidence.\n *\n * ## Why here, and not in the authorizer or the repository\n *\n * The authorizer decides admission BEFORE any rows exist, so it cannot carry `returnedCount` — and\n * the size is the signal that separates \"an operator opened the directory\" from \"an operator\n * exported it\". The repository has the count but exists once PER ADAPTER, so an emission there\n * would be two emissions to keep in step, and audit is not a persistence concern. This seam has\n * the operation, the execution context and the result, and is adapter-neutral.\n *\n * ## Fire-and-forget, deliberately\n *\n * No `await`, and the rejection is swallowed — the same contract as\n * `CROSS_TENANT_ADMINISTRATIVE_ACCESS`. A directory read must not fail because the audit sink is\n * down, and a fail-closed variant would hand anyone a way to disable an administrative surface by\n * breaking the sink. Feature-detected against the service so a partial DI binding (unit suites,\n * minimal containers) cannot turn an observation into a crash.\n */\n private recordPlatformDirectoryAccess(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n executedCoreOperation: CoreResourceOperation,\n returnedCount: number,\n ): void {\n try {\n const resourceConfiguration = this.resourcesRegistry?.getResourceConfiguration?.(\n operation.resourceIdentifier as never,\n );\n if (!resourceConfiguration) return;\n\n // ONE predicate, shared with the confinement authority: a read is a directory read precisely\n // when that authority declines to confine it. Deriving it separately here is how the trail\n // would start claiming \"unconfined\" about reads that had since been confined.\n if (!isUnconfinedScopeRootDirectoryRead({\n executionContext: executionContext as never,\n resourceConfiguration: resourceConfiguration as never,\n executedCoreOperation,\n })) return;\n\n const auditLogsService = this.servicesRegistry?.getAuditLogsService?.();\n if (typeof auditLogsService?.logPlatformDirectoryAccess !== 'function') return;\n\n void auditLogsService.logPlatformDirectoryAccess({\n resourceType: String(operation.resourceIdentifier),\n operationIdentifier: String(operation.operationIdentifier),\n variantType: operation.variantType,\n variantKey: operation.variantKey,\n returnedCount,\n initiatorRoles: (executionContext.initiatorRoles ?? []).flatMap((roleInfo) => roleInfo.roles ?? []),\n executionType: executionContext.executionType,\n actorUserId: executionContext.initiatorIds?.userId,\n applicationId: executionContext.initiatorIds?.applicationId,\n }, executionContext).catch(() => { /* observation only — never fail the read it observes */ });\n } catch {\n /* observation only */\n }\n }\n\n private async search(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n searchQuery: string,\n filter?: FilterQuery<any>,\n options?: ServiceOptions & {\n searchOptions?: {\n fieldsToSearch?: string[];\n page?: number;\n limit?: number;\n sort?: Record<string, 1 | -1>;\n };\n }\n ): Promise<any> {\n\n // Extract dataMode from options (default: RAW)\n const dataMode = (options as any)?.dataMode ?? DataMode.RAW;\n\n // Resolve operation variant based on dataMode\n const resolvedOperation = this.resolveOperationVariant(operation, dataMode);\n\n this.logDebug('Executing search business operation', { searchQuery, hasFilter: !!filter, dataMode, variantKey: resolvedOperation.variantKey });\n\n // 1. Apply business search logic\n const businessFilter = await this.applyBusinessFilter(filter || {}, executionContext);\n const enhancedSearchQuery = await this.enhanceSearchQuery(searchQuery, executionContext);\n\n // 2. Execute repository operation with resolved variant - search doesn't use id_or_ids_or_filter, pass search data via data parameter\n const searchData = { query: enhancedSearchQuery, filter: businessFilter };\n const result = await this.callRepository(resolvedOperation, executionContext, undefined, searchData, options);\n\n // 3. Enrich each item with business context\n const enrichedData = result.data ?\n await Promise.all(result.data.map(item => this.enrichBusinessContext(CoreResourceOperation.SEARCH, item, executionContext))) :\n [];\n\n // 4. Return result with enriched data (transformation happens in doOperation)\n const processedResult = { ...result, data: enrichedData };\n\n this.logDebug('Search business operation completed', { count: enrichedData.length });\n return processedResult;\n }\n\n private async count(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n filter?: FilterQuery<any>,\n options?: RepositoryOptions\n ): Promise<{ count: number }> {\n\n this.logDebug('Executing count business operation', { hasFilter: !!filter });\n\n // 1. Apply business filtering\n const businessFilter = await this.applyBusinessFilter(filter || {}, executionContext);\n\n // 2. Execute repository operation - count doesn't use id_or_ids_or_filter, pass filter via data parameter\n const countData = Object.keys(businessFilter).length > 0 ? { filter: businessFilter } : undefined;\n const result = await this.callRepository(operation, executionContext, undefined, countData, options);\n\n this.logDebug('Count business operation completed', { count: result.count });\n return result;\n }\n\n // ================================\n // DTO Validation and Transformation Methods\n // ================================\n\n /**\n * Validate and transform input data using operation's requestDto\n */\n private async validateAndTransformInput(\n executionContext: ExecutionContext<any>,\n data: any\n ): Promise<any> {\n\n const operation = executionContext.operation;\n\n if (!operation.requestDto) {\n this.logDebug('No requestDto defined for operation, skipping validation');\n return data;\n }\n\n try {\n // Strip any `.isWriteOnlySecret()` field the client echoed back as the mask\n // sentinel — it means \"keep the existing stored secret\". UPDATE is a partial\n // `$set`, so removing the field preserves the stored value; on CREATE it is\n // simply omitted. Runs at the service tier so it covers in-process writes too.\n const sanitizedInput = ResourcesConfigOperationsDtosBuilderUtils.stripWriteOnlySecretSentinel(\n operation.requestDto,\n data,\n );\n\n // Validate and transform input — use loose parse to preserve PREFIX-augmented\n // persistence fields that are not part of the API's requestDto schema.\n // Field-level security is enforced at the controller boundary; Mongoose strict\n // mode strips schema-unknown fields at the repository layer.\n const validatedData = (operation.requestDto instanceof z.ZodObject)\n ? z.looseObject(operation.requestDto.shape).parse(sanitizedInput)\n : operation.requestDto.parse(sanitizedInput);\n this.logDebug('Input validation successful');\n return validatedData;\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n stack: error.stack,\n context: {\n operationIdentifier: operation.operationIdentifier,\n inputData: data,\n zodIssues: error.issues,\n }\n });\n }\n throw this.errorBuilder.buildFromStandardError(\n error instanceof Error ? error : new Error('Unknown validation error'),\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n operationIdentifier: operation.operationIdentifier,\n inputData: data,\n }\n }\n );\n }\n }\n\n\n private async transformOutput(\n executionContext: ExecutionContext<any>,\n data: any,\n dataMode: DataMode = DataMode.RAW,\n alreadyResolvedOperation?: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>\n ): Promise<any> {\n\n const operation = executionContext.operation as ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\n\n // Use already-resolved operation if provided (to avoid double resolution)\n // Otherwise resolve based on dataMode\n const resolvedOperation = alreadyResolvedOperation ?? this.resolveOperationVariant(operation, dataMode);\n\n this.logDebug('Transform output - using resolved operation', {\n operationIdentifier: operation.operationIdentifier,\n dataMode,\n resolvedVariantKey: resolvedOperation.variantKey,\n wasAlreadyResolved: !!alreadyResolvedOperation\n });\n\n // Use internalDto for service-layer validation\n // internalDto MUST exist - it's built by buildAllOperationDtos() for all operations\n if (!resolvedOperation.internalDto) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_TRANSFORMATION_FAILED,\n context: {\n reason: 'Missing internalDto - this indicates a configuration error in buildAllOperationDtos()',\n operationIdentifier: resolvedOperation.operationIdentifier,\n resourceIdentifier: resolvedOperation.resourceIdentifier,\n variantKey: resolvedOperation.variantKey,\n dataMode\n }\n }\n );\n }\n\n this.logDebug('Service transformOutput - resolved operation', {\n operationIdentifier: operation.operationIdentifier,\n dataMode,\n resolvedVariantKey: resolvedOperation.variantKey,\n hasInternalDto: !!resolvedOperation.internalDto\n });\n\n this.logDebug('transformOutput - before validation', {\n dataKeys: data && typeof data === 'object' && !Array.isArray(data) ? Object.keys(data) : 'not plain object',\n hasUserSelfProfile: data && typeof data === 'object' ? 'userSelfProfile' in data : false,\n hasUserSelfPreference: data && typeof data === 'object' ? 'userSelfPreference' in data : false,\n hasOrgMembers: data && typeof data === 'object' ? 'organizationMembers' in data : false\n });\n\n try {\n // Transform and validate output using resolved operation's internalDto\n const effectiveOperation = resolvedOperation.resourceOperationLike || resolvedOperation.operationIdentifier;\n\n // Compose the operation's DECLARED response value from the raw service output BEFORE\n // validating it. This is the single, GENERAL seam between \"what the service/repository layer\n // returns\" and \"what the operation's `internalDto` (and the controller response serializer)\n // expect\" — no per-operation special-casing lives here. For almost every operation this is the\n // identity (the service already returns the resource object / per-item array / `{ count }` /\n // pagination wrapper). The only non-identity cases are the genuine core deletes, whose\n // repository layer returns the deleted id(s) as a bare scalar (`delete(): Promise<string>` —\n // the `_id`, `''` when nothing matched; `deleteMany(): Promise<string[]>`);\n // `composeDefaultOperationResponse` lifts those into `DefaultDeleteResponseSchema` /\n // `DefaultBulkDeleteResponseSchema`. Before this, the raw scalar was parsed straight against\n // the resource object schema and threw `service_resource_transformation_failed` → HTTP 500 on\n // every delete. Composition is pure and total (never throws); the subsequent parse stays inside\n // this `try`, so a genuinely malformed output still surfaces the transformation error below.\n //\n // TWO guards keep this from touching custom operations that merely borrow DELETE/COUNT\n // semantics (`resourceOperationLike`) while returning their OWN shape:\n // 1. Key on the op's own `operationIdentifier`, NOT `effectiveOperation` — a custom op has a\n // custom identifier, so the composer switch falls through to identity for it.\n // 2. Skip entirely when the op declares a `customResponseDto` (`hasCustomResponseDto`) — that\n // op returns its custom shape directly (for example `{ message, domain }`),\n // and its `internalDto` IS that custom schema; composing `{ id: <custom object> }` would\n // wrongly fail validation.\n //\n // ⚠️ The op must actually PRODUCE that custom shape. Skipping composition hands the raw\n // service output to the custom DTO, and a borrowed core DELETE returns a bare id STRING —\n // so a delete-like op declaring a custom object response with no implementation to build\n // it throws `service_resource_transformation_failed` on every call, AFTER the delete has\n // committed. `user_self | delete_account` did exactly that and was removed on 2026-08-01.\n // Mirrors `buildEnhancedResponseDto`, which lets a custom `responseDto` win over the default.\n const outputToValidate = resolvedOperation.hasCustomResponseDto\n ? data\n : composeDefaultOperationResponse(resolvedOperation.operationIdentifier as string, data);\n\n const isBulkArrayOperation = (\n effectiveOperation === CoreResourceOperation.CREATE_MANY\n || effectiveOperation === CoreResourceOperation.UPDATE_MANY\n );\n const isCollectionOperation = (\n effectiveOperation === CoreResourceOperation.LIST\n || effectiveOperation === CoreResourceOperation.SEARCH\n );\n const collectionItemDto = (\n Array.isArray(outputToValidate) && isCollectionOperation\n )\n ? this.extractCollectionItemDto(resolvedOperation.internalDto) ?? resolvedOperation.repositoryDto\n : null;\n\n // `_version` (optimistic-locking counter) and `_field_meta` (CRDT causality) are engine\n // metadata NOT declared in any resource schema, so the `internalDto.parse` below strips\n // them. They must survive to the HTTP response: the frontend Resource Mutation Manager\n // seeds its optimistic-locking version from the READ response and echoes it as `If-Match`\n // on inline updates — stripped, it seeds `0` and every inline update 409s. Snapshot per\n // item before parse and reattach after (mirrors the same guard in\n // `operation-response-serializer.backend.utils`, which covers the controller/webhook parse).\n const preserveEngineMetadata = (source: unknown, parsed: unknown): unknown => {\n if (!source || typeof source !== 'object' || !parsed || typeof parsed !== 'object') return parsed;\n for (const key of ['_field_meta', '_version'] as const) {\n const value = (source as Record<string, unknown>)[key];\n if (value !== undefined && (parsed as Record<string, unknown>)[key] === undefined) {\n (parsed as Record<string, unknown>)[key] = value;\n }\n }\n return parsed;\n };\n\n const transformedData = (\n Array.isArray(outputToValidate) && (isBulkArrayOperation || !!collectionItemDto)\n )\n ? outputToValidate.map((item) => preserveEngineMetadata(item, (collectionItemDto ?? resolvedOperation.internalDto!).parse(item)))\n : preserveEngineMetadata(outputToValidate, resolvedOperation.internalDto.parse(outputToValidate));\n\n this.logDebug('transformOutput - after validation', {\n dataKeys: transformedData && typeof transformedData === 'object' && !Array.isArray(transformedData) ? Object.keys(transformedData) : 'not plain object',\n hasUserSelfProfile: transformedData && typeof transformedData === 'object' ? 'userSelfProfile' in transformedData : false,\n hasUserSelfPreference: transformedData && typeof transformedData === 'object' ? 'userSelfPreference' in transformedData : false,\n hasOrgMembers: transformedData && typeof transformedData === 'object' ? 'organizationMembers' in transformedData : false\n });\n\n this.logDebug('Output transformation successful');\n return transformedData;\n } catch (error) {\n // Output transformation failures are programming/configuration errors.\n // The DTO doesn't match the actual output structure.\n const transformationError = this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_TRANSFORMATION_FAILED,\n context: {\n operationIdentifier: operation.operationIdentifier,\n resourceIdentifier: operation.resourceIdentifier,\n outputDataType: Array.isArray(data) ? 'array' : typeof data,\n outputDataLength: Array.isArray(data) ? data.length : undefined,\n outputDataKeys: data && typeof data === 'object' && !Array.isArray(data) ? Object.keys(data) : undefined,\n /**\n * The CAUSE, which this catch used to drop.\n *\n * It kept only the stack, so the error named the resource and the key LIST but never\n * which field failed or why — and a Zod issue path is the entire diagnostic content of a\n * DTO mismatch. Debugging one meant adding a temporary log to the framework and\n * re-running, every time.\n */\n transformationFailure: describeCaughtError(error),\n },\n stack: error instanceof Error ? error.stack : undefined\n }\n );\n throw transformationError;\n }\n }\n\n private extractCollectionItemDto(dto: z.ZodTypeAny | undefined): z.ZodTypeAny | null {\n if (!(dto instanceof z.ZodObject)) {\n return null;\n }\n\n const dataField = dto.shape?.data;\n const paginationField = dto.shape?.pagination;\n\n if (!(dataField instanceof z.ZodArray) || !paginationField) {\n return null;\n }\n\n return dataField.element as unknown as z.ZodTypeAny;\n }\n\n /**\n * Apply business validation\n */\n private async applyBusinessValidation(\n operation: CoreResourceOperation,\n data: any,\n executionContext: ExecutionContext<any>,\n currentState?: any\n ): Promise<any> {\n\n // Implement business validation logic here\n // This could include:\n // - Business rule validation\n // - Permission checks\n // - Data consistency validation\n // - Cross-resource validation\n\n return data; // Default: pass through\n }\n\n /**\n * Execute pre-operation business logic.\n *\n * Dispatches registered pre-operation hooks for this resource type\n * BEFORE returning the (possibly-enriched) data to the pipeline.\n *\n * Short-circuit contract (plan §Phase-3 P3-A=A1): hook exceptions\n * propagate unchanged — this method performs NO `try/catch` around\n * `dispatchPreOperationHooks` and the pipeline callers already wrap\n * the full operation in their own error-handling so the failure\n * surfaces as a normal operation-level error to the API layer.\n *\n * Mutation contract: pre-hooks are observation + veto only (no return\n * value). Data transformation continues to live in\n * `prefixCoreOperations` of custom operation impls.\n *\n * **Hook-payload contract — `_id` injection for UPDATE / UPDATE_MANY**\n * (Phase 3.2 review fix, Findings #2/#10):\n *\n * The pipeline callers pass the validated **patch** as `data` and the\n * pre-update **row snapshot** as `currentState`. Hooks consuming a\n * patch alone cannot anchor per-row work (Level-B seeds need\n * `triggeringRow._id` to anchor the `DataSeedRun` ledger; cross-resource\n * consistency hooks need to identify the target row). We therefore\n * publish a **hook payload** that lifts `_id` from `currentState` onto\n * the patch for singular `UPDATE`, and an array of `{...currentState,\n * _id}` for bulk `UPDATE_MANY`. The **return value** stays the\n * original `data` so the repository receives only the patch — adding\n * `_id` to the persistence payload would otherwise be rejected by\n * adapters that forbid `_id` mutation.\n *\n * `currentState` shapes accepted:\n * - singular `UPDATE` → object with `_id` (single fetched snapshot).\n * - `UPDATE_MANY` / `DELETE_MANY` → array of objects with `_id`.\n * - other operations → undefined / passthrough (no transform).\n */\n private async executePreOperationLogic(\n operation: CoreResourceOperation,\n data: any,\n executionContext: ExecutionContext<any>,\n currentState?: any\n ): Promise<any> {\n\n const resourceType = this.resourceConfiguration.resourceIdentifier as string;\n\n let hookPayload: any = data;\n if (\n operation === CoreResourceOperation.UPDATE\n && currentState\n && typeof currentState._id === 'string'\n && currentState._id.length > 0\n && data\n && typeof data === 'object'\n && !Array.isArray(data)\n ) {\n // Spread `data` first so the patch's keys are visible to the hook,\n // then assign canonical `_id` last to defeat any accidental `_id`\n // shadowing in the patch (post-validation patches must not carry\n // `_id`, but defensive overlay keeps the contract crash-free).\n hookPayload = { ...data, _id: currentState._id };\n } else if (\n operation === CoreResourceOperation.UPDATE_MANY\n && Array.isArray(currentState)\n && currentState.length > 0\n && data\n && typeof data === 'object'\n && !Array.isArray(data)\n ) {\n // Bulk patch is broadcast across N rows: materialise per-row hook\n // shape `{...patch, _id}` so each downstream Level-B seed dispatch\n // gets the row anchor it needs (P3-F=F1). Skipped when no rows\n // matched the bulk selector (mirrors DELETE_MANY's `length > 0`\n // guard) so empty selectors don't fire spurious hook callbacks.\n hookPayload = currentState\n .filter((row) => row && typeof row._id === 'string' && row._id.length > 0)\n .map((row) => ({ ...data, _id: row._id }));\n }\n\n await this.servicesRegistry.dispatchPreOperationHooks(\n resourceType,\n operation,\n hookPayload,\n executionContext,\n );\n\n return data;\n }\n\n /**\n * Execute post-operation business logic using engine lifecycle operations\n */\n private async executePostOperationLogic(\n operation: CoreResourceOperation,\n result: any,\n executionContext: ExecutionContext<any>,\n currentState?: any,\n options?: RepositoryOptions\n ): Promise<any> {\n\n // Get the current operation configuration\n const operationConfig = executionContext.operation;\n const resourceType = operationConfig.resourceIdentifier;\n\n // Execute lifecycle operations for DELETE (child deletion based on childOperations config)\n // rag-removal-gate: N/A — pure delegation. The deleted ROWS' chunk removal lives in the\n // delete/deleteMany methods that call this; the cascaded CHILDREN's lives in\n // deleteChildrenImmediate. This dispatcher destroys nothing itself.\n if (operation === CoreResourceOperation.DELETE || operation === CoreResourceOperation.DELETE_MANY) {\n await this.executeLifecycleOperations(operation, result, executionContext, currentState);\n }\n\n // Execute composition onParentCreate seeding — eager creation of composition\n // children declared with `lifecycle.onParentCreate.enabled = true`. `options`\n // carries `compositionSeedDepth` for the re-entrancy bound (see the method).\n if (operation === CoreResourceOperation.CREATE) {\n await this.executeCompositionSeedingForCreate(result, executionContext, options);\n }\n\n // Execute other post-operation logic (events, notifications, etc.)\n await this.executeAdditionalPostOperationLogic(\n operation,\n result,\n executionContext,\n currentState,\n options,\n );\n\n return result;\n }\n\n // =============================================================================\n // NESTED OPERATIONS PROCESSING\n // =============================================================================\n\n private getRelationshipFieldNameForCurrentResource(rel: ResourceRelationship): string {\n return Resources_SharedUtils.resolveRelationshipObjectIdentityForResource(\n rel,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n this.getAllResourceFieldIdentifiers()\n ).objectFieldName;\n }\n\n private getRelationshipForBulkAction(relationshipField: string): ResourceRelationship {\n const currentResourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const candidateRelationships = this.resourcesRegistry\n .getResourcesRegistry()\n .resourceRelationships\n .filter((rel) =>\n rel.isDisabled !== true\n && (rel.resourceType1 === currentResourceType || rel.resourceType2 === currentResourceType)\n );\n const matches = candidateRelationships.filter((rel) =>\n this.getRelationshipFieldNameForCurrentResource(rel) === relationshipField\n );\n\n if (matches.length === 1) {\n return matches[0];\n }\n\n if (matches.length > 1) {\n throw new Error(\n `Bulk relationship field \"${relationshipField}\" is ambiguous for resource \"${this.resourceConfiguration.resourceIdentifier}\".`\n );\n }\n\n throw new Error(\n `Bulk relationship field \"${relationshipField}\" does not map to a relationship on resource \"${this.resourceConfiguration.resourceIdentifier}\".`\n );\n }\n\n private async applyReferenceSetActionMany(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n relationship: ResourceRelationship,\n relationshipField: string,\n targetId: string,\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n const relatedReadContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n relationship.resourceType1,\n CoreResourceOperation.READ\n );\n const relatedTarget = await this.servicesRegistry.read(\n relationship.resourceType1,\n relatedReadContext,\n targetId,\n options\n );\n\n if (!relatedTarget) {\n throw this.errorBuilder.buildError(\n ErrorType.NOT_FOUND,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.SET,\n targetId,\n relatedResourceType: relationship.resourceType1,\n },\n }\n );\n }\n\n if (!Resources_SharedUtils.isRelationshipActiveForParent(relationship, relatedTarget, {\n onMissingParentResource: 'exclude',\n onConditionError: 'throw',\n })) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.SET,\n targetId,\n reason: 'Reference relationship is inactive for the selected related resource',\n },\n }\n );\n }\n\n const updateManyContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n CoreResourceOperation.UPDATE_MANY\n );\n const fkField = this.getFKFieldForRelationship(relationship);\n const updatedTargets = await this.servicesRegistry.updateMany(\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n updateManyContext,\n id_or_ids_or_filter,\n { [fkField]: targetId },\n options\n );\n\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.SET,\n matchedTargetIds: this.extractResourceIds(updatedTargets),\n affectedCount: Array.isArray(updatedTargets) ? updatedTargets.length : 0,\n results: Array.isArray(updatedTargets) ? updatedTargets : [],\n };\n }\n\n private async applyReferenceClearActionMany(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n relationship: ResourceRelationship,\n relationshipField: string,\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n if (relationship.parentResourceRequirement === ResourceParentResourceRequirement.MANDATORY) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.CLEAR,\n reason: 'Cannot clear a mandatory parent relationship through bulk reference mutation',\n },\n }\n );\n }\n\n const updateManyContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n CoreResourceOperation.UPDATE_MANY\n );\n const fkField = this.getFKFieldForRelationship(relationship);\n const updatedTargets = await this.servicesRegistry.updateMany(\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n updateManyContext,\n id_or_ids_or_filter,\n { [fkField]: null },\n options\n );\n\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.CLEAR,\n matchedTargetIds: this.extractResourceIds(updatedTargets),\n affectedCount: Array.isArray(updatedTargets) ? updatedTargets.length : 0,\n results: Array.isArray(updatedTargets) ? updatedTargets : [],\n };\n }\n\n private async applyCompositionCreateActionMany(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n relationship: ResourceRelationship,\n relationshipField: string,\n data: Record<string, any>,\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n const fkField = this.getFKFieldForRelationship(relationship);\n if (fkField in data) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.CREATE,\n fkField,\n reason: 'Bulk composition create payload must not provide the relationship foreign key explicitly',\n },\n }\n );\n }\n\n const targetResources = await this.loadBulkTargetResources(\n executionContext,\n id_or_ids_or_filter,\n options\n );\n const createdChildren: any[] = [];\n const matchedTargetIds: string[] = [];\n\n for (const targetResource of targetResources) {\n if (!Resources_SharedUtils.isRelationshipActiveForParent(relationship, targetResource, {\n onMissingParentResource: 'exclude',\n onConditionError: 'throw',\n })) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.CREATE,\n reason: 'Composition relationship is inactive for one of the matched target resources',\n targetResourceId: this.getResourceIdValue(targetResource),\n },\n }\n );\n }\n\n const targetResourceId = this.getResourceIdValue(targetResource);\n if (!targetResourceId) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.CREATE,\n reason: 'Bulk composition create requires every matched target resource to expose an id',\n },\n }\n );\n }\n\n const createContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n relationship.resourceType2,\n CoreResourceOperation.CREATE\n );\n const createdChild = await this.servicesRegistry.create(\n relationship.resourceType2,\n createContext,\n {\n ...data,\n [fkField]: targetResourceId,\n },\n options\n );\n\n matchedTargetIds.push(targetResourceId);\n createdChildren.push(createdChild);\n }\n\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.CREATE,\n matchedTargetIds,\n affectedCount: createdChildren.length,\n results: createdChildren,\n };\n }\n\n private async applyAssociationLinkActionMany(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n relationship: ResourceRelationship,\n relationshipField: string,\n peerIds: string[],\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n const {\n jointResourceType,\n peerResourceType,\n currentForeignKeyField,\n peerForeignKeyField,\n } = this.resolveAssociationBulkIdentity(relationship);\n const uniquePeerIds = [...new Set(peerIds)];\n await this.assertAssociationPeerResourcesExist(\n executionContext,\n relationshipField,\n peerResourceType,\n uniquePeerIds,\n ResourceRelationshipBulkAction.LINK,\n options\n );\n\n const targetResources = await this.loadBulkTargetResources(\n executionContext,\n id_or_ids_or_filter,\n options\n );\n const matchedTargetIds: string[] = [];\n\n for (const targetResource of targetResources) {\n if (!Resources_SharedUtils.isRelationshipActiveForParent(relationship, targetResource, {\n onMissingParentResource: 'exclude',\n onConditionError: 'throw',\n })) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.LINK,\n reason: 'Association relationship is inactive for one of the matched target resources',\n targetResourceId: this.getResourceIdValue(targetResource),\n },\n }\n );\n }\n\n const targetResourceId = this.getResourceIdValue(targetResource);\n if (!targetResourceId) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.LINK,\n reason: 'Bulk association link requires every matched target resource to expose an id',\n },\n }\n );\n }\n\n matchedTargetIds.push(targetResourceId);\n }\n\n const existingRows = matchedTargetIds.length > 0\n ? await this.listAssociationRowsByCurrentAndPeerIds(\n executionContext,\n jointResourceType,\n currentForeignKeyField,\n matchedTargetIds,\n peerForeignKeyField,\n uniquePeerIds,\n options\n )\n : [];\n const existingKeys = new Set(\n existingRows.map((row) => {\n const currentId = row?.[currentForeignKeyField];\n const peerId = row?.[peerForeignKeyField];\n return typeof currentId === 'string' && typeof peerId === 'string'\n ? `${currentId}::${peerId}`\n : undefined;\n })\n .filter((key): key is string => Boolean(key))\n );\n\n const createdRows: any[] = [];\n for (const targetResourceId of matchedTargetIds) {\n for (const peerId of uniquePeerIds) {\n const key = `${targetResourceId}::${peerId}`;\n if (existingKeys.has(key)) {\n continue;\n }\n\n const createContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n jointResourceType,\n CoreResourceOperation.CREATE\n );\n const createdRow = await this.servicesRegistry.create(\n jointResourceType,\n createContext,\n {\n [currentForeignKeyField]: targetResourceId,\n [peerForeignKeyField]: peerId,\n },\n options\n );\n createdRows.push(createdRow);\n }\n }\n\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.LINK,\n matchedTargetIds,\n affectedCount: createdRows.length,\n results: createdRows,\n };\n }\n\n private async applyAssociationUnlinkActionMany(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n relationship: ResourceRelationship,\n relationshipField: string,\n peerIds: string[],\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n const {\n jointResourceType,\n currentForeignKeyField,\n peerForeignKeyField,\n } = this.resolveAssociationBulkIdentity(relationship);\n const uniquePeerIds = [...new Set(peerIds)];\n const targetResources = await this.loadBulkTargetResources(\n executionContext,\n id_or_ids_or_filter,\n options\n );\n const matchedTargetIds: string[] = [];\n\n for (const targetResource of targetResources) {\n if (!Resources_SharedUtils.isRelationshipActiveForParent(relationship, targetResource, {\n onMissingParentResource: 'exclude',\n onConditionError: 'throw',\n })) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.UNLINK,\n reason: 'Association relationship is inactive for one of the matched target resources',\n targetResourceId: this.getResourceIdValue(targetResource),\n },\n }\n );\n }\n\n const targetResourceId = this.getResourceIdValue(targetResource);\n if (!targetResourceId) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.UNLINK,\n reason: 'Bulk association unlink requires every matched target resource to expose an id',\n },\n }\n );\n }\n\n matchedTargetIds.push(targetResourceId);\n }\n\n if (matchedTargetIds.length === 0 || uniquePeerIds.length === 0) {\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.UNLINK,\n matchedTargetIds,\n affectedCount: 0,\n results: [],\n };\n }\n\n const existingRows = await this.listAssociationRowsByCurrentAndPeerIds(\n executionContext,\n jointResourceType,\n currentForeignKeyField,\n matchedTargetIds,\n peerForeignKeyField,\n uniquePeerIds,\n options\n );\n const existingRowIds = existingRows\n .map((row) => this.getResourceIdValue(row))\n .filter((rowId): rowId is string => Boolean(rowId));\n\n if (existingRowIds.length !== existingRows.length) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.UNLINK,\n reason: 'Bulk association unlink requires every junction row to expose an id',\n },\n }\n );\n }\n\n if (existingRowIds.length === 0) {\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.UNLINK,\n matchedTargetIds,\n affectedCount: 0,\n results: [],\n };\n }\n\n const deleteManyContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n jointResourceType,\n CoreResourceOperation.DELETE_MANY\n );\n const deletedRowIds = await this.servicesRegistry.deleteMany(\n jointResourceType,\n deleteManyContext,\n existingRowIds,\n options\n );\n\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.UNLINK,\n matchedTargetIds,\n affectedCount: Array.isArray(deletedRowIds) ? deletedRowIds.length : 0,\n results: Array.isArray(deletedRowIds) ? deletedRowIds : [],\n };\n }\n\n private async applyAssociationReplaceActionMany(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n relationship: ResourceRelationship,\n relationshipField: string,\n peerIds: string[],\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n const {\n jointResourceType,\n peerResourceType,\n currentForeignKeyField,\n peerForeignKeyField,\n } = this.resolveAssociationBulkIdentity(relationship);\n const uniquePeerIds = [...new Set(peerIds)];\n await this.assertAssociationPeerResourcesExist(\n executionContext,\n relationshipField,\n peerResourceType,\n uniquePeerIds,\n ResourceRelationshipBulkAction.REPLACE,\n options\n );\n\n const matchedTargetIds = await this.resolveActiveAssociationBulkTargetIds(\n executionContext,\n id_or_ids_or_filter,\n relationship,\n relationshipField,\n ResourceRelationshipBulkAction.REPLACE,\n options\n );\n\n if (matchedTargetIds.length === 0) {\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.REPLACE,\n matchedTargetIds,\n affectedCount: 0,\n results: [],\n };\n }\n\n const existingRows = await this.listAssociationRowsByCurrentIds(\n executionContext,\n jointResourceType,\n currentForeignKeyField,\n matchedTargetIds,\n options\n );\n const desiredKeys = new Set<string>();\n for (const targetResourceId of matchedTargetIds) {\n for (const peerId of uniquePeerIds) {\n desiredKeys.add(`${targetResourceId}::${peerId}`);\n }\n }\n\n const rowsToDelete = existingRows.filter((row) => {\n const currentId = row?.[currentForeignKeyField];\n const peerId = row?.[peerForeignKeyField];\n if (typeof currentId !== 'string' || typeof peerId !== 'string') {\n return false;\n }\n\n return !desiredKeys.has(`${currentId}::${peerId}`);\n });\n const deleteRowIds = rowsToDelete\n .map((row) => this.getResourceIdValue(row))\n .filter((rowId): rowId is string => Boolean(rowId));\n\n if (deleteRowIds.length !== rowsToDelete.length) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.REPLACE,\n reason: 'Bulk association replace requires every junction row to expose an id',\n },\n }\n );\n }\n\n const existingKeys = new Set(\n existingRows.map((row) => {\n const currentId = row?.[currentForeignKeyField];\n const peerId = row?.[peerForeignKeyField];\n return typeof currentId === 'string' && typeof peerId === 'string'\n ? `${currentId}::${peerId}`\n : undefined;\n })\n .filter((key): key is string => Boolean(key))\n );\n\n const createdRows: any[] = [];\n for (const targetResourceId of matchedTargetIds) {\n for (const peerId of uniquePeerIds) {\n const key = `${targetResourceId}::${peerId}`;\n if (existingKeys.has(key)) {\n continue;\n }\n\n const createContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n jointResourceType,\n CoreResourceOperation.CREATE\n );\n const createdRow = await this.servicesRegistry.create(\n jointResourceType,\n createContext,\n {\n [currentForeignKeyField]: targetResourceId,\n [peerForeignKeyField]: peerId,\n },\n options\n );\n createdRows.push(createdRow);\n }\n }\n\n if (deleteRowIds.length > 0) {\n const deleteManyContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n jointResourceType,\n CoreResourceOperation.DELETE_MANY\n );\n await this.servicesRegistry.deleteMany(\n jointResourceType,\n deleteManyContext,\n deleteRowIds,\n options\n );\n }\n\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.REPLACE,\n matchedTargetIds,\n affectedCount: createdRows.length + deleteRowIds.length,\n results: [\n ...createdRows,\n ...deleteRowIds,\n ],\n };\n }\n\n /**\n * Extract nested field name from relationship using the shared\n * relationship-object identity rule.\n */\n private getNestedFieldName(rel: ResourceRelationship): string {\n return Resources_SharedUtils.resolveRelationshipObjectIdentity(\n rel,\n rel.resourceType2,\n rel.cardinality2,\n this.getAllResourceFieldIdentifiers()\n ).objectFieldName;\n }\n\n private getAllResourceFieldIdentifiers(): Partial<Record<ResourceType, string>> {\n const registry = this.resourcesRegistry.getResourcesRegistry();\n const allResourceFieldIdentifiers: Partial<Record<ResourceType, string>> = {};\n\n for (const resourceType of Object.keys(registry.resourceConfigurations) as ResourceType[]) {\n const fieldIdentifier = registry.resourceConfigurations[resourceType]?.resourceFieldIdentifier;\n if (typeof fieldIdentifier === 'string' && fieldIdentifier.length > 0) {\n allResourceFieldIdentifiers[resourceType] = fieldIdentifier;\n }\n }\n\n return allResourceFieldIdentifiers;\n }\n\n private extractResourceIds(resources: any[]): string[] {\n if (!Array.isArray(resources)) {\n return [];\n }\n\n return resources\n .map((resource) => this.getResourceIdValue(resource))\n .filter((resourceId): resourceId is string => Boolean(resourceId));\n }\n\n /**\n * Get FK field name for a relationship.\n * Delegates to the registry so backend services do not improvise their own\n * FK fallback semantics.\n */\n private getFKFieldForRelationship(rel: ResourceRelationship): string {\n return this.resourcesRegistry.resolveForeignKeyField({\n resourceType1: rel.resourceType1,\n foreignKeyField: rel.foreignKeyField,\n });\n }\n\n private async resolveActiveAssociationBulkTargetIds(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n relationship: ResourceRelationship,\n relationshipField: string,\n action: ResourceRelationshipBulkAction,\n options?: RepositoryOptions\n ): Promise<string[]> {\n const targetResources = await this.loadBulkTargetResources(\n executionContext,\n id_or_ids_or_filter,\n options\n );\n const matchedTargetIds: string[] = [];\n\n for (const targetResource of targetResources) {\n if (!Resources_SharedUtils.isRelationshipActiveForParent(relationship, targetResource, {\n onMissingParentResource: 'exclude',\n onConditionError: 'throw',\n })) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField,\n action,\n reason: 'Association relationship is inactive for one of the matched target resources',\n targetResourceId: this.getResourceIdValue(targetResource),\n },\n }\n );\n }\n\n const targetResourceId = this.getResourceIdValue(targetResource);\n if (!targetResourceId) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action,\n reason: 'Bulk association mutation requires every matched target resource to expose an id',\n },\n }\n );\n }\n\n matchedTargetIds.push(targetResourceId);\n }\n\n return matchedTargetIds;\n }\n\n private resolveAssociationBulkIdentity(relationship: ResourceRelationship): {\n jointResourceType: ResourceType;\n peerResourceType: ResourceType;\n currentForeignKeyField: string;\n peerForeignKeyField: string;\n } {\n const currentResourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const perspective = Resources_SharedUtils.getRelationshipPerspectiveForResource(\n relationship,\n currentResourceType\n );\n\n if (!perspective || !relationship.jointResourceType) {\n throw new Error('Association bulk actions require a non-self association relationship with jointResourceType');\n }\n\n const currentForeignKeyField = this.resourcesRegistry.resolveForeignKeyField({\n resourceType1: currentResourceType,\n foreignKeyField: perspective === 'resourceType1' ? relationship.foreignKeyField : undefined,\n });\n const peerResourceType = perspective === 'resourceType1'\n ? relationship.resourceType2\n : relationship.resourceType1;\n const peerForeignKeyField = this.resourcesRegistry.resolveForeignKeyField({\n resourceType1: peerResourceType,\n foreignKeyField: perspective === 'resourceType2' ? relationship.foreignKeyField : undefined,\n });\n\n return {\n jointResourceType: relationship.jointResourceType,\n peerResourceType,\n currentForeignKeyField,\n peerForeignKeyField,\n };\n }\n\n private async assertAssociationPeerResourcesExist(\n executionContext: ExecutionContext<any>,\n relationshipField: string,\n peerResourceType: ResourceType,\n peerIds: string[],\n action: ResourceRelationshipBulkAction = ResourceRelationshipBulkAction.LINK,\n options?: RepositoryOptions\n ): Promise<void> {\n for (const peerId of peerIds) {\n const readContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n peerResourceType,\n CoreResourceOperation.READ\n );\n const peerResource = await this.servicesRegistry.read(\n peerResourceType,\n readContext,\n peerId,\n options\n );\n\n if (!peerResource) {\n throw this.errorBuilder.buildError(\n ErrorType.NOT_FOUND,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action,\n peerId,\n peerResourceType,\n },\n }\n );\n }\n }\n }\n\n private async listAssociationRowsByCurrentAndPeerIds(\n executionContext: ExecutionContext<any>,\n jointResourceType: ResourceType,\n currentForeignKeyField: string,\n currentIds: string[],\n peerForeignKeyField: string,\n peerIds: string[],\n options?: RepositoryOptions\n ): Promise<any[]> {\n const existingRows: any[] = [];\n const seenRowIds = new Set<string>();\n\n for (const currentId of currentIds) {\n for (const peerId of peerIds) {\n const listContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n jointResourceType,\n CoreResourceOperation.LIST\n );\n const result = await this.servicesRegistry.list(\n jointResourceType,\n listContext,\n {\n [currentForeignKeyField]: currentId,\n [peerForeignKeyField]: peerId,\n },\n undefined,\n options\n );\n const rows = Array.isArray(result) ? result : result.data;\n\n for (const row of rows) {\n const rowId = this.getResourceIdValue(row);\n if (rowId) {\n if (seenRowIds.has(rowId)) {\n continue;\n }\n seenRowIds.add(rowId);\n }\n\n existingRows.push(row);\n }\n }\n }\n\n return existingRows;\n }\n\n private async listAssociationRowsByCurrentIds(\n executionContext: ExecutionContext<any>,\n jointResourceType: ResourceType,\n currentForeignKeyField: string,\n currentIds: string[],\n options?: RepositoryOptions\n ): Promise<any[]> {\n const existingRows: any[] = [];\n const seenRowIds = new Set<string>();\n\n for (const currentId of currentIds) {\n const listContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n jointResourceType,\n CoreResourceOperation.LIST\n );\n const result = await this.servicesRegistry.list(\n jointResourceType,\n listContext,\n {\n [currentForeignKeyField]: currentId,\n },\n undefined,\n options\n );\n const rows = Array.isArray(result) ? result : result.data;\n\n for (const row of rows) {\n const rowId = this.getResourceIdValue(row);\n if (rowId) {\n if (seenRowIds.has(rowId)) {\n continue;\n }\n seenRowIds.add(rowId);\n }\n\n existingRows.push(row);\n }\n }\n\n return existingRows;\n }\n\n private getResolvedNestedMutationConfig(\n rel: ResourceRelationship,\n operation: CoreResourceOperation\n ) {\n return Resources_SharedUtils.resolveRelationshipNestedMutationConfig(rel, operation);\n }\n\n private getResolvedNestedReadConfig(rel: ResourceRelationship) {\n return Resources_SharedUtils.resolveRelationshipNestedReadConfig(rel);\n }\n\n private getResolvedLifecycleOnParentDelete(rel: ResourceRelationship) {\n return Resources_SharedUtils.resolveRelationshipLifecycleOnParentDeleteConfig(rel);\n }\n\n private getResolvedLifecycleOnParentCreate(rel: ResourceRelationship) {\n return Resources_SharedUtils.resolveRelationshipLifecycleOnParentCreateConfig(rel);\n }\n\n /**\n * Extract nested data from request, separating parent data from nested child data.\n * Returns { parentData, nestedData } where nestedData is keyed by field name.\n */\n private extractNestedData(\n data: any,\n relationships: ResourceRelationship[],\n operation: CoreResourceOperation\n ): { parentData: any; nestedData: Record<string, any> } {\n const parentData = { ...data };\n const nestedData: Record<string, any> = {};\n\n for (const rel of relationships) {\n const nestedConfig = this.getResolvedNestedMutationConfig(rel, operation);\n\n if (!nestedConfig) continue;\n\n const fieldName = this.getNestedFieldName(rel);\n\n if (fieldName in parentData) {\n nestedData[fieldName] = parentData[fieldName];\n delete parentData[fieldName];\n }\n }\n\n return { parentData, nestedData };\n }\n\n /**\n * Bulk variant of extractNestedData().\n * Applies the same nested field split to each item independently.\n */\n private extractNestedDataArray(\n dataArray: any[],\n relationships: ResourceRelationship[],\n operation: CoreResourceOperation,\n executionContext: ExecutionContext<any>\n ): { parentDataArray: any[]; nestedDataArray: Record<string, any>[] } {\n if (!Array.isArray(dataArray)) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n operation,\n reason: 'Bulk create expects an array of parent payloads after validation',\n receivedType: typeof dataArray,\n }\n }\n );\n }\n\n const parentDataArray: any[] = [];\n const nestedDataArray: Record<string, any>[] = [];\n\n for (const item of dataArray) {\n const { parentData, nestedData } = this.extractNestedData(item, relationships, operation);\n parentDataArray.push(parentData);\n nestedDataArray.push(nestedData);\n }\n\n return { parentDataArray, nestedDataArray };\n }\n\n /**\n * Normalize bulk create payloads to the array shape expected by the service layer.\n * Some callers may already pass the raw array, while others may use a `{ data: [] }`\n * envelope before controller-level extraction.\n */\n private normalizeCreateManyInput(\n validatedData: any,\n executionContext: ExecutionContext<any>\n ): any[] {\n if (Array.isArray(validatedData)) {\n return validatedData;\n }\n\n if (validatedData && typeof validatedData === 'object' && Array.isArray(validatedData.data)) {\n return validatedData.data;\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n operation: CoreResourceOperation.CREATE_MANY,\n reason: 'Bulk create expects either an array payload or an object with a data array',\n }\n }\n );\n }\n\n /**\n * Normalize the CREATE_MANY request shape so service callers may pass either\n * a raw array or the controller-facing `{ data: [...] }` envelope.\n */\n private normalizeCreateManyRequestPayload(\n data: any,\n executionContext: ExecutionContext<any>\n ): { data: any[] } {\n if (Array.isArray(data)) {\n return { data };\n }\n\n if (data && typeof data === 'object' && Array.isArray(data.data)) {\n return { ...data, data: data.data };\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n operation: CoreResourceOperation.CREATE_MANY,\n reason: 'Bulk create expects either an array payload or an object with a data array',\n }\n }\n );\n }\n\n /**\n * Both resolvers route through the ONE derivation seam (review R2) — previously they read\n * hydrated config directly, so in platform mode they knew nothing of the construction-time\n * `platformPersistenceAdapter` override and agreed with the repositories that actually exist\n * only through the apps-manager env-truth overlay. A pre-hydration service-tier write on a\n * platform resource would have opened a MongoDB transaction against a PostgreSQL repository.\n */\n private getResolvedPersistenceAdapter(): PersistenceAdapterType {\n return resolvePersistenceAdapterForConfiguration(\n this.resourceConfiguration.persistenceAdapter,\n this.appConfigService,\n );\n }\n\n private getResolvedPersistenceAdapterForResource(resourceType: ResourceType): PersistenceAdapterType {\n const resourceConfiguration = this.resourcesRegistry.getResourceConfiguration(resourceType);\n return resolvePersistenceAdapterForConfiguration(\n resourceConfiguration.persistenceAdapter,\n this.appConfigService,\n );\n }\n\n /**\n * The adapter that owns FILE METADATA.\n *\n * Several checks around file work compared against `MONGODB` when what they meant\n * was \"the adapter FILES lives on\". Those coincide today and only today; naming\n * the concept means they follow FILES if it ever moves, instead of inverting in\n * silence. This is the same substitution the routing sites already made — an\n * adapter literal is almost never the question being asked.\n */\n private getFileMetadataAdapter(): PersistenceAdapterType {\n try {\n return this.getResolvedPersistenceAdapterForResource(CoreResourceType.FILES as ResourceType);\n } catch {\n /**\n * FILES is not registered in this registry.\n *\n * Tolerated rather than propagated: this accessor is consulted on ordinary\n * write paths that may have nothing to do with files, and the previous adapter\n * literal never asked the registry anything — so throwing here would turn a\n * total function partial and break callers that were never about FILES at all\n * (it did: five lifecycle-cascade tests, whose registries register only the\n * resources under test).\n *\n * The framework default is the honest answer: with no FILES resource there is\n * no separate store to coordinate with, so nothing should be split out.\n */\n return resolveDefaultPersistenceAdapter(this.appConfigService);\n }\n }\n\n private getResourceDatabaseService(\n executionContext: ExecutionContext<any>\n ): IDatabaseService {\n return this.getDatabaseServiceForAdapter(\n this.getResolvedPersistenceAdapter(),\n executionContext,\n );\n }\n\n /**\n * The database service that owns transactions for ONE adapter.\n *\n * Split out of {@link getResourceDatabaseService} so that a caller which needs a\n * transaction on a DIFFERENT resource's store — file metadata being the only one\n * today — can open it by asking for that resource's adapter, rather than naming\n * `this.mongoDBService` and being right only for as long as FILES stays on MongoDB.\n *\n * The dispatch literals here are the ONE place an adapter name legitimately appears:\n * mapping an adapter to its own service is the definition of dispatch, not a\n * question standing in for something else.\n */\n private getDatabaseServiceForAdapter(\n persistenceAdapter: PersistenceAdapterType,\n executionContext: ExecutionContext<any>\n ): IDatabaseService {\n // Exhaustive selection: the old `=== POSTGRESQL ? pg : mongo` shape handed the Mongo service\n // to any adapter it did not name. A new enum member is a compile error here; an unknown\n // runtime value throws inside the selector instead of opening a MongoDB transaction.\n const { databaseService, serviceName } = selectByPersistenceAdapter<{\n databaseService: IDatabaseService | undefined;\n serviceName: string;\n }>(persistenceAdapter, {\n [PersistenceAdapter.POSTGRESQL]: { databaseService: this.postgreSQLDatabaseService, serviceName: 'PostgreSQLDatabaseService' },\n [PersistenceAdapter.MONGODB]: { databaseService: this.mongoDBService, serviceName: 'MongoDBService' },\n // HTTP_API owns no transaction-capable database service BY CONSTRUCTION — remote rows have\n // no engine transaction (ETL D3: read-only slice; writes are refused). `undefined` routes\n // into the fail-closed refusal below, whose message names the missing capability.\n [PersistenceAdapter.HTTP_API]: { databaseService: undefined, serviceName: 'HTTP_API (no transaction-capable database service exists for API-backed resources)' },\n // Same `undefined`, different reason: introspection has no STORE, not merely no transaction.\n // Rows are recomputed per read from the application's own source.\n [PersistenceAdapter.INTROSPECTION]: { databaseService: undefined, serviceName: 'INTROSPECTION (rows are derived per read; no store and no transaction exist)' },\n });\n\n if (!databaseService) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `${serviceName} is required for ${persistenceAdapter}-backed resource transactions`,\n resourceType: this.resourceConfiguration.resourceIdentifier,\n persistenceAdapter,\n },\n }\n );\n }\n\n return databaseService;\n }\n\n private buildFileRepositoryOptions(options?: RepositoryOptions): RepositoryOptions | undefined {\n if (\n !options?.transaction\n || options.transaction.databaseType === this.getFileMetadataAdapter()\n ) {\n return options;\n }\n\n const { transaction: _ignoredTransaction, ...fileOptions } = options;\n return fileOptions;\n }\n\n private buildRepositoryOptionsForResource(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions\n ): RepositoryOptions | undefined {\n if (!options?.transaction) {\n return options;\n }\n\n const expectedDatabaseType = this.getResolvedPersistenceAdapterForResource(resourceType);\n if (options.transaction.databaseType === expectedDatabaseType) {\n return options;\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: 'Lifecycle deletes across mixed persistence adapters are not supported within a shared resource transaction',\n parentResourceType: this.resourceConfiguration.resourceIdentifier,\n childResourceType: resourceType,\n parentPersistenceAdapter: options.transaction.databaseType,\n childPersistenceAdapter: expectedDatabaseType,\n },\n }\n );\n }\n\n private async executeResourceTransaction<T>(\n executionContext: ExecutionContext<any>,\n callback: (optionsWithTransaction: RepositoryOptions) => Promise<T>,\n options?: RepositoryOptions\n ): Promise<T> {\n const persistenceAdapter = this.getResolvedPersistenceAdapter();\n if (options?.transaction) {\n if (options.transaction.databaseType !== persistenceAdapter) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n context: {\n reason:\n 'resource_transaction_persistence_adapter_mismatch',\n resourceType:\n this.resourceConfiguration.resourceIdentifier,\n resourcePersistenceAdapter: persistenceAdapter,\n transactionDatabaseType:\n options.transaction.databaseType,\n },\n },\n );\n }\n\n /**\n * The caller owns this native transaction. Reuse the exact context\n * directly instead of relying on a database service's AsyncLocalStorage\n * to rediscover it; doing so also makes it impossible for a nested call\n * to open and commit an accidental second transaction.\n */\n return callback(options);\n }\n\n const databaseService = this.getResourceDatabaseService(executionContext);\n\n return databaseService.executeTransaction(\n async (transactionContext) => callback({\n ...options,\n transaction: transactionContext,\n }),\n {\n nestedBehavior: 'reuse',\n }\n );\n }\n\n /**\n * Route file metadata work through the FILES resource adapter instead of\n * leaking the current resource transaction into a different repository backend.\n *\n * The transaction is opened on the FILES adapter's OWN service, resolved through\n * {@link getFileMetadataAdapter}. It used to be opened on `this.mongoDBService`\n * by name — a hardcoding that would have committed file metadata through the wrong\n * connection the moment FILES moved, while every surrounding check reported the move\n * as supported. A `assertMongoBackedFilesResource` guard stood in front of this to\n * make that unreachable; it was removed once the transaction, the guarded writes, and\n * the schema plan all followed FILES rather than naming MongoDB.\n */\n private async executeFileMetadataWork<T>(\n executionContext: ExecutionContext<any>,\n options: RepositoryOptions | undefined,\n callback: (fileOptions: RepositoryOptions | undefined) => Promise<T>\n ): Promise<T> {\n const fileMetadataAdapter = this.getFileMetadataAdapter();\n const fileOptions = this.buildFileRepositoryOptions(options);\n if (fileOptions?.transaction?.databaseType === fileMetadataAdapter) {\n return callback(fileOptions);\n }\n\n return this.getDatabaseServiceForAdapter(fileMetadataAdapter, executionContext).executeTransaction(\n async (transactionContext) => callback({\n ...fileOptions,\n transaction: transactionContext,\n }),\n {\n nestedBehavior: 'reuse',\n }\n );\n }\n\n private assertNestedMutationAdaptersMatchCurrentResource(\n relationships: ResourceRelationship[],\n executionContext: ExecutionContext<any>\n ): void {\n const currentPersistenceAdapter = this.getResolvedPersistenceAdapter();\n const incompatibleNestedResourceTypes = relationships\n .map((relationship) => relationship.resourceType2 as ResourceType)\n .filter((childResourceType) => {\n return this.getResolvedPersistenceAdapterForResource(childResourceType) !== currentPersistenceAdapter;\n });\n\n if (incompatibleNestedResourceTypes.length === 0) {\n return;\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: 'Nested mutations across mixed persistence adapters are not supported within a shared resource transaction',\n resourceType: this.resourceConfiguration.resourceIdentifier,\n persistenceAdapter: currentPersistenceAdapter,\n incompatibleNestedResourceTypes,\n },\n }\n );\n }\n\n /**\n * Refuse bulk NESTED or FILE-FIELD mutations on a non-MongoDB-backed resource.\n *\n * This is the one refusal in this file that is a genuine **adapter capability gap**\n * rather than the FILES co-transaction question wearing an adapter literal. Its\n * sibling messages mention bulk NESTED updates, which have nothing to do with file\n * metadata: the limitation is that the PostgreSQL path has no equivalent bulk\n * nested/file transaction implementation yet.\n *\n * So the literal stays, deliberately, and means exactly what it says. It is a\n * PARITY GAP to close (see the plan's Wave 4), not a comparison to re-express —\n * rewriting it in terms of the FILES boundary would claim support that does not\n * exist.\n *\n * Note the two call sites differ: from bulk UPDATE the adapter check is reachable\n * and is the real gate; from bulk DELETE it is unreachable, because the caller has\n * already established the same condition. The second check (`mongoDBService`\n * availability) is live from both.\n */\n private assertMongoBulkTransactionSupport(\n executionContext: ExecutionContext<any>,\n message: string\n ): void {\n const persistenceAdapter = this.getResolvedPersistenceAdapter();\n\n if (persistenceAdapter !== PersistenceAdapter.MONGODB) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message,\n resourceType: this.resourceConfiguration.resourceIdentifier,\n persistenceAdapter,\n },\n }\n );\n }\n\n if (!this.mongoDBService) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `${message} (MongoDBService is not available)`,\n resourceType: this.resourceConfiguration.resourceIdentifier,\n persistenceAdapter,\n },\n }\n );\n }\n }\n\n private getResourceIdValue(resource: Record<string, any> | null | undefined): string | null {\n if (!resource) return null;\n\n /**\n * `_id` ONLY. The `?? resource.id` arm that used to be here was adapter shape leaking into the\n * resource layer: `id` is Mongoose's built-in virtual, exposed only on surrogate-primary-key\n * resources (where `toObject` enables virtuals) and never produced by PostgreSQL at all.\n *\n * It was also dead: `_id` is present on every row from both adapters and is evaluated first.\n * Keeping it implied a second identity key that the resource system does not have, and would\n * have quietly returned a MongoDB-only value the day `_id` was genuinely absent — which is\n * precisely when a caller most needs the `null` this now returns.\n */\n const rawId = resource._id;\n if (typeof rawId === 'string' && rawId.length > 0) {\n return rawId;\n }\n\n if (rawId && typeof rawId.toString === 'function') {\n const stringified = rawId.toString();\n return stringified.length > 0 ? stringified : null;\n }\n\n return null;\n }\n\n private hasExplicitFileFieldMutations(\n resourceType: ResourceType,\n data: Record<string, any>\n ): boolean {\n const fileFields = this.fileFieldDetection.detectFileFields(resourceType);\n return fileFields.some(({ fieldName }) => hasExplicitCanonicalFieldMutation(data, fieldName));\n }\n\n private getGeneratedPdfFileFields(resourceType: ResourceType): FileFieldMetadata[] {\n return this.fileFieldDetection.detectFileFields(resourceType).filter(\n (fileField) => fileField.fileMetadata.generation?.source === FileGenerationSource.PDF_TEMPLATE,\n );\n }\n\n /**\n * Refuse a write that must materialize a generated document but cannot commit\n * it with the row.\n *\n * The question is NOT \"is this resource on PostgreSQL?\" — that was only ever a\n * proxy, correct while FILES happens to be MongoDB. The question is whether the\n * declared boundary {this resource, FILES-as-ATOMIC} can commit atomically, and\n * the unit of work already owns it. Routing here means the refusal follows FILES\n * if FILES ever moves, instead of silently inverting.\n *\n * Fail-closed when the unit of work is unavailable: this is a guard, and a guard\n * that cannot evaluate its condition has not established it. Returning \"supported\"\n * would let a dangling document reference commit on the one path built to prevent it.\n */\n private assertGeneratedFileMaterializationCommitsWithRow(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n message: string,\n additionalContext?: Record<string, unknown>,\n ): void {\n const assessment = this.resourcePersistenceUnitOfWork?.assessCompatibility(\n createResourceWritePersistenceRequest({\n resourceType,\n fileParticipation: ResourceWriteFileParticipation.ATOMIC_MATERIALIZATION,\n }),\n );\n\n /**\n * Same fallback discipline as the routing helper: when the boundary cannot be\n * assessed, ask the question directly rather than assume an answer. Failing\n * closed on a missing unit of work sounded prudent and was wrong — several\n * integration containers do not bind one, and refusing there would block\n * generated documents on MongoDB, where they are perfectly safe.\n */\n const generatedDocumentCommitsWithRow = assessment\n ? assessment.compatible\n : this.getResolvedPersistenceAdapterForResource(resourceType) === this.getFileMetadataAdapter();\n\n if (generatedDocumentCommitsWithRow) {\n return;\n }\n\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message,\n resourceType,\n ...additionalContext,\n compatibilityStatus: assessment?.status,\n resourceAdapterMap: assessment?.resourceAdapterMap,\n },\n });\n }\n\n /**\n * Must this resource's file-metadata work be committed SEPARATELY from the row?\n *\n * Replaces `adapter === POSTGRESQL` at the file-work call sites. That comparison\n * was never the real question — it was a proxy that happens to be right only while\n * FILES sits on MongoDB, and would invert silently the day FILES moved. The real\n * question is whether FILES can join this write's transaction, which the unit of\n * work answers from the declared boundary.\n *\n * Returns FALSE when the unit of work is unavailable, which is the current\n * behaviour on the default adapter (join the ambient transaction). Unlike the\n * generated-document guard, \"unknown\" cannot fail closed here: the alternative\n * branch OPENS a transaction, and doing that unnecessarily fails outright on a\n * standalone MongoDB. Guessing wrong in this direction is also self-announcing —\n * the repository refuses a transaction whose `databaseType` is not its own — so a\n * wrong inline is a loud error, never a silent cross-adapter write.\n */\n private fileMetadataRequiresSeparateCommit(resourceType: ResourceType): boolean {\n const assessment = this.resourcePersistenceUnitOfWork?.assessCompatibility(\n createResourceWritePersistenceRequest({\n resourceType,\n fileParticipation: ResourceWriteFileParticipation.METADATA,\n }),\n );\n\n /**\n * `compensatedParticipantResourceMap` is meaningful ONLY on a compatible\n * assessment — it is empty on every refused one, by design. Reading it without\n * checking `compatible` first therefore reports \"nothing to compensate\" for an\n * assessment that determined nothing, which is how this shipped wrong: PostgreSQL\n * integration lanes have no unit of work bound, so file work was silently routed\n * into the SQL transaction instead of Mongo.\n */\n if (assessment?.compatible) {\n return Object.keys(assessment.compensatedParticipantResourceMap).length > 0;\n }\n\n /**\n * Fallback when the boundary could not be assessed: ask the question directly.\n *\n * This needs no unit of work, and it is FACT rather than assumption — the earlier\n * revision guessed a direction here (via an `UndeterminableFileCouplingPolicy`\n * argument) and guessed wrong for PostgreSQL. The coupling model gives the richer\n * answer when it is available; when it is not, \"is this resource on the FILES\n * adapter?\" is still exactly what the old adapter comparison asked, minus the\n * literal — so it follows FILES if FILES moves.\n */\n return this.getResolvedPersistenceAdapterForResource(resourceType) !== this.getFileMetadataAdapter();\n }\n\n private assertGeneratedPdfCreationSupported(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n ): void {\n if (this.getGeneratedPdfFileFields(resourceType).length === 0) {\n return;\n }\n\n this.assertGeneratedFileMaterializationCommitsWithRow(\n resourceType,\n executionContext,\n 'Generated PDF creation is not yet supported for PostgreSQL-backed resources because FILES metadata is Mongo-backed and cannot be committed atomically with the parent row.',\n );\n }\n\n private async materializeGeneratedPdfFieldsForCreate(\n data: Record<string, any>,\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<{\n data: Record<string, any>;\n materializations: GeneratedPdfMaterializationRecord[];\n }> {\n const generatedPdfFields = this.getGeneratedPdfFileFields(resourceType);\n if (generatedPdfFields.length === 0) {\n return { data, materializations: [] };\n }\n\n const materializations: GeneratedPdfMaterializationRecord[] = [];\n const locale = getConfiguredPrimaryLanguage(this.appConfigService.config);\n\n try {\n for (const fileField of generatedPdfFields) {\n await this.materializeGeneratedPdfFieldAtPath({\n rootData: data,\n currentValue: data,\n pathTokens: fileField.fieldName.split('.').filter(Boolean),\n tokenIndex: 0,\n fileField,\n resourceType,\n executionContext,\n repositoryOptions: this.buildFileRepositoryOptions(options),\n locale,\n materializations,\n });\n }\n } catch (error) {\n await this.cleanupGeneratedPdfMaterializations(materializations, executionContext);\n throw error;\n }\n\n return { data, materializations };\n }\n\n private async materializeGeneratedPdfFieldAtPath(params: {\n rootData: Record<string, any>;\n currentValue: unknown;\n pathTokens: string[];\n tokenIndex: number;\n fileField: FileFieldMetadata;\n resourceType: ResourceType;\n executionContext: ExecutionContext<any>;\n repositoryOptions?: RepositoryOptions;\n locale: string;\n materializations: GeneratedPdfMaterializationRecord[];\n }): Promise<void> {\n if (params.pathTokens.length === 0) {\n return;\n }\n\n if (Array.isArray(params.currentValue)) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, params.executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: 'Generated PDF fields inside arrays are not supported in v1.',\n resourceType: params.resourceType,\n fieldName: params.fileField.fieldName,\n },\n });\n }\n\n if (!params.currentValue || typeof params.currentValue !== 'object') {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, params.executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `Generated PDF field \"${params.fileField.fieldName}\" cannot be materialized because its parent path is not an object.`,\n resourceType: params.resourceType,\n fieldName: params.fileField.fieldName,\n },\n });\n }\n\n const owner = params.currentValue as Record<string, any>;\n const fieldKey = params.pathTokens[params.tokenIndex];\n const isLeaf = params.tokenIndex === params.pathTokens.length - 1;\n\n if (isLeaf) {\n const generated = await this.pdfGenerationOrchestrator.generateForField({\n resourceType: params.resourceType,\n parentRecord: params.rootData,\n fieldName: params.fileField.fieldName,\n fileMetadata: params.fileField.fileMetadata,\n executionContext: params.executionContext,\n repositoryOptions: params.repositoryOptions,\n renderPhase: PdfGenerationRenderPhase.CREATE,\n locale: params.locale,\n defaultLocale: params.locale,\n });\n\n owner[fieldKey] = {\n fileId: generated.fileId,\n updatedAt: generated.updatedAt,\n };\n params.materializations.push({\n ...generated,\n resourceType: params.resourceType,\n fieldName: params.fileField.fieldName,\n });\n return;\n }\n\n if (owner[fieldKey] === null || owner[fieldKey] === undefined) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, params.executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `Generated PDF field \"${params.fileField.fieldName}\" cannot be materialized because required parent container \"${fieldKey}\" is missing.`,\n resourceType: params.resourceType,\n fieldName: params.fileField.fieldName,\n missingParentKey: fieldKey,\n },\n });\n }\n\n if (typeof owner[fieldKey] !== 'object') {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, params.executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `Generated PDF field \"${params.fileField.fieldName}\" cannot be materialized because parent container \"${fieldKey}\" is not an object.`,\n resourceType: params.resourceType,\n fieldName: params.fileField.fieldName,\n parentKey: fieldKey,\n },\n });\n }\n\n await this.materializeGeneratedPdfFieldAtPath({\n ...params,\n currentValue: owner[fieldKey],\n tokenIndex: params.tokenIndex + 1,\n });\n }\n\n private async cleanupGeneratedPdfMaterializations(\n materializations: GeneratedPdfMaterializationRecord[],\n executionContext: ExecutionContext<any>,\n ): Promise<void> {\n if (materializations.length === 0) {\n return;\n }\n\n const results = await Promise.allSettled(\n materializations.map((materialization) => materialization.cleanup()),\n );\n\n results.forEach((result, index) => {\n if (result.status === 'rejected') {\n const materialization = materializations[index];\n this.logger.warn('Generated PDF cleanup failed after resource operation rollback', {\n resourceType: materialization.resourceType,\n fieldName: materialization.fieldName,\n fileId: materialization.fileId,\n operationIdentifier: executionContext.operation.operationIdentifier,\n ...projectCaughtErrorLogFields(result.reason),\n });\n }\n });\n }\n\n private buildGeneratedPdfProcessingOptions(\n materializations: GeneratedPdfMaterializationRecord[],\n materializationsByRow?: readonly GeneratedPdfMaterializationRecord[][],\n ): {\n frameworkGeneratedPdfFileIdsByField?: Record<string, readonly string[]>;\n frameworkGeneratedPdfFileIdsByFieldByRow?: readonly Record<string, readonly string[]>[];\n } | undefined {\n if (materializations.length === 0) {\n return undefined;\n }\n\n const fileIdsByField: Record<string, string[]> = {};\n for (const materialization of materializations) {\n fileIdsByField[materialization.fieldName] = [\n ...(fileIdsByField[materialization.fieldName] ?? []),\n materialization.fileId,\n ];\n }\n\n const options: {\n frameworkGeneratedPdfFileIdsByField: Record<string, readonly string[]>;\n frameworkGeneratedPdfFileIdsByFieldByRow?: readonly Record<string, readonly string[]>[];\n } = { frameworkGeneratedPdfFileIdsByField: fileIdsByField };\n\n if (materializationsByRow) {\n options.frameworkGeneratedPdfFileIdsByFieldByRow = materializationsByRow.map((rowMaterializations) => {\n const rowFileIdsByField: Record<string, string[]> = {};\n for (const materialization of rowMaterializations) {\n rowFileIdsByField[materialization.fieldName] = [\n ...(rowFileIdsByField[materialization.fieldName] ?? []),\n materialization.fileId,\n ];\n }\n return rowFileIdsByField;\n });\n }\n\n return options;\n }\n\n private buildGeneratedFileFieldPatch(\n fieldName: string,\n value: { fileId: string; updatedAt: Date },\n ): Record<string, any> {\n const tokens = fieldName.split('.').filter(Boolean);\n if (tokens.length === 0) {\n return {};\n }\n\n const root: Record<string, any> = {};\n let current = root;\n for (let index = 0; index < tokens.length - 1; index += 1) {\n const token = tokens[index];\n current[token] = {};\n current = current[token];\n }\n current[tokens[tokens.length - 1]] = value;\n return root;\n }\n\n private buildGeneratedFileRepositoryPatch(\n fieldName: string,\n value: { fileId: string; updatedAt: Date },\n ): Record<string, any> {\n return fieldName.includes('.')\n ? { [fieldName]: value }\n : this.buildGeneratedFileFieldPatch(fieldName, value);\n }\n\n private getGeneratedFileIdAtPath(\n source: unknown,\n fieldName: string,\n ): string | undefined {\n const tokens = fieldName.split('.').filter(Boolean);\n let current: unknown = source;\n for (const token of tokens) {\n if (!current || typeof current !== 'object' || Array.isArray(current)) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[token];\n }\n\n if (!current || typeof current !== 'object' || Array.isArray(current)) {\n return undefined;\n }\n const fileId = (current as Record<string, unknown>).fileId;\n return typeof fileId === 'string' && fileId.length > 0\n ? fileId\n : undefined;\n }\n\n private async processBulkCreateFileFields(\n parentResults: any[],\n parentDataArray: Record<string, any>[],\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n processingOptions?: {\n frameworkGeneratedPdfFileIdsByField?: Record<string, readonly string[]>;\n frameworkGeneratedPdfFileIdsByFieldByRow?: readonly Record<string, readonly string[]>[];\n },\n ): Promise<void> {\n if (!Array.isArray(parentResults) || parentResults.length !== parentDataArray.length) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operation: CoreResourceOperation.CREATE_MANY,\n reason: 'Bulk create file processing requires one parent result per input payload',\n parentResultsCount: Array.isArray(parentResults) ? parentResults.length : 'not-array',\n payloadCount: parentDataArray.length,\n },\n }\n );\n }\n\n for (let index = 0; index < parentResults.length; index += 1) {\n const parentResult = parentResults[index];\n const resourceId = this.getResourceIdValue(parentResult);\n if (!resourceId) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operation: CoreResourceOperation.CREATE_MANY,\n reason: 'Bulk create file processing requires each created parent to expose an id',\n index,\n },\n }\n );\n }\n\n await this.fileOperationHandler.processFileFieldsForCreate(\n parentDataArray[index],\n resourceType,\n resourceId,\n executionContext,\n options,\n processingOptions?.frameworkGeneratedPdfFileIdsByFieldByRow\n ? { frameworkGeneratedPdfFileIdsByField: processingOptions.frameworkGeneratedPdfFileIdsByFieldByRow[index] ?? {} }\n : processingOptions,\n );\n }\n }\n\n private async loadBulkParentStateMap(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType | undefined,\n options?: RepositoryOptions\n ): Promise<Map<string, any>> {\n const currentStates = await this.loadBulkTargetResources(\n executionContext,\n id_or_ids_or_filter,\n options\n );\n\n return new Map(\n (Array.isArray(currentStates) ? currentStates : [])\n .map((item) => [this.getResourceIdValue(item), item] as const)\n .filter((entry): entry is [string, any] => !!entry[0])\n );\n }\n\n private async loadBulkTargetResources(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType | undefined,\n options?: RepositoryOptions\n ): Promise<any[]> {\n if (!id_or_ids_or_filter) {\n return [];\n }\n\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const repository = this.repositoriesRegistry.getRepositoryOrThrow(resourceType);\n\n if (typeof id_or_ids_or_filter === 'string') {\n const currentState = await repository.read(executionContext, id_or_ids_or_filter, options);\n return currentState ? [currentState] : [];\n }\n\n // `listForInternalScan`, not the public `list`: this resolves the TARGETS of a bulk\n // mutation (pre-hook snapshots, file-field mutation, audit snapshots) — framework\n // machinery, not a user-facing collection read. The public door requires a declared\n // default LIST operation, which a bulk-capable resource does not necessarily expose\n // (e.g. `organizationFeatures` / `applicationFeatures` declare UPDATE_MANY-like\n // operations and NO LIST) — same wrong-door class as the dormancy batch and the\n // subject-export read (wildo-ai/wildo-ai#34). A declared LIST is still reused\n // verbatim (hooks included), so LIST-declaring resources are byte-identical.\n const snapshotCandidates = await repository.listForInternalScan(\n executionContext,\n id_or_ids_or_filter as any,\n options\n ) as any[];\n const snapshotIds = (Array.isArray(snapshotCandidates) ? snapshotCandidates : [])\n .map((item) => this.getResourceIdValue(item))\n .filter((id): id is string => !!id);\n const currentStates = await Promise.all(\n snapshotIds.map((id) => repository.read(executionContext, id, options))\n );\n\n return (Array.isArray(currentStates) ? currentStates : []).filter(Boolean);\n }\n\n private async processBulkUpdateFileFields(\n parentResults: any[],\n currentStatesById: Map<string, any>,\n parentPatch: Record<string, any>,\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions\n ): Promise<void> {\n if (!Array.isArray(parentResults)) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operation: CoreResourceOperation.UPDATE_MANY,\n reason: 'Bulk update file processing requires an array of parent results',\n },\n }\n );\n }\n\n for (const parentResult of parentResults) {\n const resourceId = this.getResourceIdValue(parentResult);\n if (!resourceId) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operation: CoreResourceOperation.UPDATE_MANY,\n reason: 'Bulk update file processing requires each updated parent to expose an id',\n },\n }\n );\n }\n\n const currentState = currentStatesById.get(resourceId);\n if (!currentState) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operation: CoreResourceOperation.UPDATE_MANY,\n reason: 'Bulk update file processing requires a pre-update snapshot for every updated parent',\n resourceId,\n },\n }\n );\n }\n\n await this.fileOperationHandler.processFileFieldsForUpdate(\n parentPatch,\n currentState,\n resourceType,\n resourceId,\n executionContext,\n options\n );\n }\n }\n\n /**\n * Extract nested data for UPDATE operations, including delete arrays.\n * Returns { parentData, nestedData, deleteData }.\n */\n private extractNestedDataForUpdate(\n data: any,\n relationships: ResourceRelationship[]\n ): { parentData: any; nestedData: Record<string, any>; deleteData: Record<string, string[]> } {\n const parentData = { ...data };\n const nestedData: Record<string, any> = {};\n const deleteData: Record<string, string[]> = {};\n\n for (const rel of relationships) {\n const nestedConfig = this.getResolvedNestedMutationConfig(rel, CoreResourceOperation.UPDATE);\n if (!nestedConfig) continue;\n\n const fieldName = this.getNestedFieldName(rel);\n const deleteFieldName = `_${fieldName}ToDelete`;\n\n if (fieldName in parentData) {\n nestedData[fieldName] = parentData[fieldName];\n delete parentData[fieldName];\n }\n\n if (nestedConfig.allowDelete && deleteFieldName in parentData) {\n deleteData[fieldName] = parentData[deleteFieldName] || [];\n delete parentData[deleteFieldName];\n }\n }\n\n return { parentData, nestedData, deleteData };\n }\n\n /**\n * Filter child relationships by evaluating discriminator/condition against the parent resource.\n *\n * This is the central runtime gate for conditional relationships in the services layer.\n * It ensures that nested CRUD operations and lifecycle cascades only apply to child\n * relationships whose conditions match the current parent resource's data.\n *\n * ## Evaluation Logic\n *\n * For each relationship:\n * 1. If `discriminator` is present: check `String(parentResource[discriminatorField])`\n * against `values`. If no match → exclude.\n * 2. If `condition` is present: call `condition(parentResource)`.\n * If it returns false → exclude.\n * 3. Relationships without discriminator or condition always pass through.\n *\n * When both discriminator and condition are present, AND semantics apply —\n * discriminator is checked first, then condition.\n *\n * ## Application Points\n *\n * This method is called at 4 critical points in the CRUD lifecycle:\n *\n * 1. **Nested CREATE** (inside transaction): After creating the parent, filters\n * child relationships using `parentResult` before processing nested creates.\n * This prevents creating children for relationships that don't apply to this parent.\n *\n * 2. **Nested READ**: After reading the parent, filters child relationships using\n * the read `result` before fetching nested children for the response.\n *\n * 3. **Nested UPDATE** (inside transaction): After updating the parent, filters\n * child relationships using `parentResult` before processing nested updates.\n *\n * 4. **Lifecycle DELETE**: Filters lifecycle relationships using pre-delete parent\n * snapshots to determine which children should cascade-delete.\n * - `DELETE`: uses the single `currentState`\n * - `DELETE_MANY`: uses the pre-delete snapshot set loaded for the matched parents,\n * so discriminator/condition gating still fails closed per deleted parent\n *\n * ## String Coercion\n *\n * Uses the shared relationship-activation utility in `saas-models`, preserving\n * the same `String()` coercion semantics used across backend and frontend\n * runtime evaluation.\n *\n * @param relationships - Child relationships to filter\n * @param parentResource - The parent resource's data to evaluate conditions against\n * @returns Relationships whose discriminator/condition match the parent (or have no conditions)\n */\n private filterRelationshipsByParent(\n relationships: ResourceRelationship[],\n parentResource: Record<string, any>\n ): ResourceRelationship[] {\n return Resources_SharedUtils.filterRelationshipsActiveForParent(\n relationships,\n parentResource,\n {\n onConditionError: 'throw',\n }\n );\n }\n\n /**\n * Process nested operations for CREATE/UPDATE.\n * Handles creating/updating/deleting children and attaching them to parent result.\n */\n private async processNestedOperations(\n operation: CoreResourceOperation,\n parentResult: any,\n nestedData: Record<string, any>,\n deleteData: Record<string, string[]>,\n relationships: ResourceRelationship[],\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions\n ): Promise<void> {\n const parentId = parentResult._id || parentResult.id;\n\n if (!parentId) {\n this.logDebug('No parent ID found, skipping nested operations');\n return;\n }\n\n const relationshipsByFieldName = new Map(\n relationships.map(rel => [this.getNestedFieldName(rel), rel] as const)\n );\n\n // Process deletions first (for UPDATE only)\n if (operation === CoreResourceOperation.UPDATE || operation === CoreResourceOperation.UPDATE_MANY) {\n for (const [fieldName, idsToDelete] of Object.entries(deleteData)) {\n if (!idsToDelete || idsToDelete.length === 0) continue;\n\n const rel = relationshipsByFieldName.get(fieldName);\n if (!rel) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n parentResourceType: this.resourceConfiguration.resourceIdentifier,\n fieldName,\n operation,\n reason: 'nested delete field is not active for the current parent state or does not map to an allowed relationship',\n },\n }\n );\n }\n\n const nestedConfig = this.getResolvedNestedMutationConfig(rel, CoreResourceOperation.UPDATE);\n if (!nestedConfig?.allowDelete) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n parentResourceType: this.resourceConfiguration.resourceIdentifier,\n childResourceType: rel.resourceType2,\n fieldName,\n operation,\n reason: 'nested deletes are not enabled for this relationship',\n },\n }\n );\n }\n\n this.logDebug('Deleting nested children', { fieldName, count: idsToDelete.length });\n\n for (const childId of idsToDelete) {\n // Build relationship context for child DELETE\n const relationshipContext: import('@wildo-ai/saas-models').ExecutionContext_RelationshipContext = {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n relationshipField: this.getFKFieldForRelationship(rel),\n resourceId: parentId\n };\n\n // Create sub-call context with correct operation\n const subContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n rel.resourceType2,\n CoreResourceOperation.DELETE,\n undefined,\n childId,\n relationshipContext\n );\n\n // Authorization: DELETE operation on child resource is checked via enabledCondition\n // in doByExecutionContext when servicesRegistry.delete is called\n await this.servicesRegistry.delete(\n rel.resourceType2,\n subContext,\n childId,\n options\n );\n }\n }\n }\n\n // Process creates and updates\n for (const [fieldName, items] of Object.entries(nestedData)) {\n if (!items) continue;\n\n const rel = relationshipsByFieldName.get(fieldName);\n if (!rel) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n parentResourceType: this.resourceConfiguration.resourceIdentifier,\n fieldName,\n operation,\n reason: 'nested field is not active for the current parent state or does not map to an allowed relationship',\n },\n }\n );\n }\n\n const nestedConfig = this.getResolvedNestedMutationConfig(rel, operation);\n\n if (!nestedConfig) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n parentResourceType: this.resourceConfiguration.resourceIdentifier,\n childResourceType: rel.resourceType2,\n fieldName,\n operation,\n reason: 'nested operations are not enabled for this relationship',\n },\n }\n );\n }\n\n const fkField = this.getFKFieldForRelationship(rel);\n const processedChildren: any[] = [];\n const itemsArray = Array.isArray(items) ? items : [items];\n const isCreateOperation = operation === CoreResourceOperation.CREATE || operation === CoreResourceOperation.CREATE_MANY;\n const isUpdateOperation = operation === CoreResourceOperation.UPDATE || operation === CoreResourceOperation.UPDATE_MANY;\n\n for (const item of itemsArray) {\n const hasId = !!(item._id || item.id);\n\n if (hasId && nestedConfig.allowUpdate && isUpdateOperation) {\n // Update existing child\n const childId = item._id || item.id;\n const childData = { ...item, [fkField]: parentId };\n delete childData._id; // Remove _id from update data\n\n // Build relationship context for child UPDATE\n const relationshipContext: import('@wildo-ai/saas-models').ExecutionContext_RelationshipContext = {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n relationshipField: fkField,\n resourceId: parentId\n };\n\n // Create sub-call context with correct operation\n const subContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n rel.resourceType2,\n CoreResourceOperation.UPDATE,\n undefined,\n childId,\n relationshipContext\n );\n\n // Authorization: UPDATE operation on child resource is checked via enabledCondition\n // in doByExecutionContext when servicesRegistry.update is called\n const updatedChild = await this.servicesRegistry.update(\n rel.resourceType2,\n subContext,\n childId,\n childData,\n options\n );\n\n if (updatedChild) {\n processedChildren.push(updatedChild);\n }\n } else if (!hasId && nestedConfig.allowCreate) {\n // Create new child\n const childData = { ...item, [fkField]: parentId };\n\n // Build relationship context for child CREATE\n const relationshipContext: import('@wildo-ai/saas-models').ExecutionContext_RelationshipContext = {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n relationshipField: fkField,\n resourceId: parentId\n };\n\n // Create sub-call context with correct operation (no resourceId for CREATE)\n const subContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n rel.resourceType2,\n CoreResourceOperation.CREATE,\n undefined,\n undefined, // No resourceId for CREATE - it doesn't exist yet\n relationshipContext\n );\n\n // Authorization: CREATE operation on child resource is checked via enabledCondition\n // in doByExecutionContext when servicesRegistry.create is called\n const createdChild = await this.servicesRegistry.create(\n rel.resourceType2,\n subContext,\n childData,\n options\n );\n\n if (createdChild) {\n processedChildren.push(createdChild);\n }\n } else {\n const action = hasId ? 'update_existing' : 'create_new';\n const reason = hasId\n ? (\n isCreateOperation\n ? 'nested create payloads cannot reference existing child ids'\n : 'nested updates are not enabled for this relationship'\n )\n : 'nested creates are not enabled for this relationship';\n\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n parentResourceType: this.resourceConfiguration.resourceIdentifier,\n childResourceType: rel.resourceType2,\n fieldName,\n action,\n reason,\n operation,\n },\n }\n );\n }\n }\n\n // Attach children to parent result — 1:1 gets single/null, 1:N gets array\n if (isOneToOneCardinality(rel.cardinality2)) {\n parentResult[fieldName] = processedChildren[0] || null;\n } else {\n parentResult[fieldName] = processedChildren;\n }\n }\n }\n\n /**\n * Bulk variant of processNestedOperations().\n * Reuses the single-parent orchestration path for each returned parent result,\n * preserving sub-call execution contexts and relationship activation checks.\n *\n * Contract:\n * - CREATE_MANY expects per-row nested payloads and receives one nested envelope\n * per created parent result.\n * - UPDATE_MANY currently uses broadcast semantics for nested create/update payloads:\n * the same validated nested envelope is replayed for every matched parent result.\n * - UPDATE_MANY nested deletes are intentionally more restrictive and are rejected\n * earlier when a shared delete payload would target multiple parents ambiguously.\n */\n private async processBulkNestedOperations(\n operation: CoreResourceOperation,\n parentResults: any[],\n nestedDataArray: Record<string, any>[],\n deleteDataArray: Record<string, string[]>[],\n relationships: ResourceRelationship[],\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions\n ): Promise<void> {\n if (!Array.isArray(parentResults) || parentResults.length === 0) {\n return;\n }\n\n if (parentResults.length !== nestedDataArray.length) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operation,\n parentResultsCount: parentResults.length,\n nestedPayloadCount: nestedDataArray.length,\n reason: 'bulk nested orchestration requires one nested payload envelope per parent result',\n },\n }\n );\n }\n\n for (let index = 0; index < parentResults.length; index += 1) {\n const parentResult = parentResults[index];\n const nestedData = nestedDataArray[index] ?? {};\n const deleteData = deleteDataArray[index] ?? {};\n\n if (!parentResult || (!Object.keys(nestedData).length && !Object.keys(deleteData).length)) {\n continue;\n }\n\n const activeRelationships = this.filterRelationshipsByParent(relationships, parentResult);\n if (activeRelationships.length === 0) {\n continue;\n }\n\n await this.processNestedOperations(\n operation,\n parentResult,\n nestedData,\n deleteData,\n activeRelationships,\n executionContext,\n options\n );\n }\n }\n\n /**\n * Process nested read operations - include children in READ response.\n */\n private async processNestedRead(\n parentResult: any,\n relationships: ResourceRelationship[],\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions\n ): Promise<void> {\n if (!parentResult) return;\n\n const parentId = parentResult._id || parentResult.id;\n\n if (!parentId) return;\n\n for (const rel of relationships) {\n const readConfig = this.getResolvedNestedReadConfig(rel);\n if (!readConfig) continue;\n\n const fieldName = this.getNestedFieldName(rel);\n const fkField = this.getFKFieldForRelationship(rel);\n\n // Build filter to find children\n const filter: any = { [fkField]: parentId };\n\n // Apply maxItems limit if specified\n const limit = readConfig.maxItems;\n\n // Build relationship context for child nested fetch\n const relationshipContext: import('@wildo-ai/saas-models').ExecutionContext_RelationshipContext = {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n relationshipField: fkField,\n resourceId: parentId\n };\n\n const childrenOptions = { ...options } as any;\n childrenOptions.dataMode = readConfig.dataMode;\n\n // Attach to parent result — 1:1 gets single/null, 1:N gets array\n if (isOneToOneCardinality(rel.cardinality2)) {\n const subContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n rel.resourceType2,\n CoreResourceOperation.READ,\n { dataMode: readConfig.dataMode },\n undefined,\n relationshipContext\n );\n const child = await this.servicesRegistry.read(\n rel.resourceType2,\n subContext,\n filter,\n childrenOptions\n );\n parentResult[fieldName] = child ?? null;\n } else {\n const subContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n rel.resourceType2,\n CoreResourceOperation.LIST,\n { dataMode: readConfig.dataMode },\n undefined,\n relationshipContext\n );\n const children = await this.servicesRegistry.list(\n rel.resourceType2,\n subContext,\n filter,\n limit ? { limit } : undefined,\n childrenOptions\n );\n parentResult[fieldName] = Array.isArray(children) ? children : [];\n }\n }\n }\n\n /**\n * Execute lifecycle operations for child resources based on relationship configuration.\n * Handles onParentDelete cascade for all child relationships with lifecycle.onParentDelete.enabled = true.\n */\n private async executeLifecycleOperations(\n operation: CoreResourceOperation,\n result: any,\n executionContext: ExecutionContext<any>,\n currentState?: any,\n options?: RepositoryOptions\n ): Promise<void> {\n\n // Only handle DELETE operations for lifecycle\n if (operation !== CoreResourceOperation.DELETE && operation !== CoreResourceOperation.DELETE_MANY) {\n return;\n }\n\n const resourceRelationships = this.resourceConfiguration.resourceRelationships;\n const childRelationships = getChildDirectionRelationships(resourceRelationships);\n\n // Find relationships with lifecycle.onParentDelete.enabled = true\n let lifecycleRelationships = childRelationships.filter(rel =>\n this.getResolvedLifecycleOnParentDelete(rel)?.enabled === true\n );\n\n if (lifecycleRelationships.length === 0) {\n return;\n }\n\n // Application point #4: Lifecycle DELETE — filter lifecycle relationships using\n // the available pre-delete parent snapshots so cascades only apply where the\n // relationship is active for the concrete parent variant being deleted.\n if (operation === CoreResourceOperation.DELETE && currentState) {\n lifecycleRelationships = this.filterRelationshipsByParent(lifecycleRelationships, currentState);\n if (lifecycleRelationships.length === 0) {\n return;\n }\n }\n\n this.logDebug('Executing lifecycle operations for delete', {\n operation,\n relationshipsCount: lifecycleRelationships.length,\n resourceType: this.resourceConfiguration.resourceIdentifier\n });\n\n // Get parent ID(s) from result\n const parentIds: string[] = operation === CoreResourceOperation.DELETE_MANY\n ? (\n Array.isArray(result)\n ? result.map((item: any) => (typeof item === 'string' ? item : this.getResourceIdValue(item))).filter(Boolean)\n : result?.deletedIds || []\n )\n : (() => {\n if (typeof result === 'string') {\n return [result];\n }\n const resultId = result?._id ?? result?.id;\n if (resultId) {\n return [String(resultId)];\n }\n const currentStateId = currentState ? this.getResourceIdValue(currentState) : undefined;\n return currentStateId ? [currentStateId] : [];\n })();\n\n if (parentIds.length === 0) {\n this.logDebug('No parent IDs found in result, skipping lifecycle operations');\n return;\n }\n\n // Process each child relationship with lifecycle config\n for (const relationship of lifecycleRelationships) {\n // `mode` + `strategy` are read inside dispatchLifecycleCascadeForRelationship (the ONE dispatcher,\n // shared with the grandchild recursion) — only the depth budget is resolved here.\n const lifecycleConfig = this.getResolvedLifecycleOnParentDelete(relationship)!;\n const maxDepth = lifecycleConfig.maxDepth || 1;\n let relationshipParentIds = parentIds;\n\n if (operation === CoreResourceOperation.DELETE_MANY && Array.isArray(currentState)) {\n const currentStatesById = new Map(\n currentState.map((item) => [this.getResourceIdValue(item), item] as const)\n .filter((entry): entry is [string, any] => !!entry[0])\n );\n relationshipParentIds = parentIds.filter((parentId) => {\n const parentSnapshot = currentStatesById.get(parentId);\n if (!parentSnapshot) {\n return false;\n }\n\n return this.filterRelationshipsByParent([relationship], parentSnapshot).length > 0;\n });\n }\n\n if (relationshipParentIds.length === 0) {\n continue;\n }\n\n await this.dispatchLifecycleCascadeForRelationship(\n relationship,\n relationshipParentIds,\n executionContext,\n 0, // currentDepth — top of the cascade\n maxDepth,\n new Set(), // visitedResourceIds for circular reference detection\n options,\n );\n }\n }\n\n /**\n * THE single (strategy × mode) cascade dispatcher for `onParentDelete`. Every entry into the\n * cascade — the top-level post-delete dispatch AND the grandchild recursion inside\n * {@link deleteChildrenImmediate} — MUST route through here, so the teardown strategy is honored at\n * EVERY depth, not just depth 0.\n *\n * ⚠️ This centralization is load-bearing, not stylistic. When the dispatch lived inline at the top\n * level only, the grandchild recursion called `deleteChildrenImmediate` directly and read just\n * `enabled` + `maxDepth` — so a grandchild edge declaring `IMPERSONALIZE_AND_RETAIN` was silently\n * HARD-DELETED (destroying data a legal-retention obligation required keeping), and a grandchild\n * declaring `mode: LAZY` was silently deleted immediately. Both axes are now honored at depth.\n *\n * FAIL-CLOSED: a missing/unknown arm throws rather than falling through to data loss (an unintended\n * DELETE) or to leaving personal data behind (a skipped IMPERSONALIZE).\n */\n /**\n * @returns whether a teardown actually RAN for this edge.\n *\n * `false` means the cascade declined to act — the child had no registered service or repository, or\n * the depth budget was already spent. It does NOT mean \"no rows existed\": discovery finding zero\n * children is a teardown that ran and had nothing to do, which is `true`.\n *\n * **Why this is a return value and not fire-and-forget.** `SubjectErasureReport.edges[].executed` is\n * the COMPLIANCE RECEIPT for a data-protection request, and it used to be set `true` unconditionally\n * once this method returned — so an edge skipped for a missing registration was reported as torn\n * down. A receipt that overstates an erasure is worse than no receipt. The delete cascade ignores\n * this value (its contract is \"throw or succeed\"), which is why the defect could live here unnoticed.\n */\n private async dispatchLifecycleCascadeForRelationship(\n relationship: any,\n parentIds: string[],\n executionContext: ExecutionContext<any>,\n currentDepth: number,\n maxDepth: number,\n visitedResourceIds: Set<string>,\n options?: RepositoryOptions,\n ): Promise<boolean> {\n const lifecycleConfig = this.getResolvedLifecycleOnParentDelete(relationship)!;\n const mode = lifecycleConfig.mode || ChildLifecycleMode.IMMEDIATE;\n // The teardown STRATEGY (what happens to the child) is orthogonal to the MODE (when it happens).\n // Default DELETE preserves today's hard-delete cascade; IMPERSONALIZE_AND_RETAIN scrubs+retains.\n const strategy = lifecycleConfig.strategy || ChildLifecycleStrategy.DELETE;\n\n switch (strategy) {\n case ChildLifecycleStrategy.DELETE:\n if (mode === ChildLifecycleMode.IMMEDIATE) {\n return await this.deleteChildrenImmediate(\n relationship,\n parentIds,\n executionContext,\n currentDepth,\n maxDepth,\n visitedResourceIds,\n options\n );\n } else if (mode === ChildLifecycleMode.LAZY) {\n return await this.queueChildDeletion(relationship, parentIds, executionContext);\n } else {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: `Unknown ChildLifecycleMode '${mode}' for the DELETE strategy — refusing to cascade (fail-closed).`,\n childResourceType: relationship.resourceType2,\n mode,\n },\n });\n }\n break;\n\n case ChildLifecycleStrategy.IMPERSONALIZE_AND_RETAIN:\n if (mode === ChildLifecycleMode.IMMEDIATE) {\n return await this.impersonalizeChildrenImmediate(\n relationship,\n parentIds,\n executionContext,\n currentDepth, // v1 impersonalize does not recurse further\n maxDepth,\n visitedResourceIds,\n options\n );\n } else {\n // LAZY (async) retain-and-scrub is not yet implemented. Fail closed rather than\n // silently hard-deleting (data loss) or skipping the scrub (personal data left behind).\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: `IMPERSONALIZE_AND_RETAIN is supported only with mode = IMMEDIATE (async/LAZY retain-and-scrub is not yet implemented).`,\n childResourceType: relationship.resourceType2,\n mode,\n },\n });\n }\n break;\n\n default: {\n // Compile-time exhaustiveness: adding a ChildLifecycleStrategy member without giving it a\n // cascade arm above becomes a TYPE error here, not a silent runtime-only discovery.\n const _exhaustiveStrategyCheck: never = strategy;\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: `Unknown ChildLifecycleStrategy '${_exhaustiveStrategyCheck}' — refusing to cascade (fail-closed).`,\n childResourceType: relationship.resourceType2,\n strategy,\n },\n });\n }\n }\n }\n\n /**\n * Execute composition `onParentCreate` seeding — the creation half of the\n * composition lifecycle, symmetric with {@link executeLifecycleOperations}\n * (delete cascade). For every child relationship declared with\n * `lifecycle.onParentCreate.enabled = true`, eagerly create the composition\n * child so the \"part\" co-exists with its \"whole\".\n *\n * Seeds through the trusted-system-write seam (`createAsSystem`), preserving\n * Guard-1 (`systemAccessPolicy.create` fail-closed opt-in) + Guard-4 (privileged\n * write audit). Base seed = the injected parent FK; the child's create pipeline\n * applies its Zod schema defaults, optionally overlaid by\n * `initialData.override(ctx)` for derived fields (Tier-2).\n *\n * Runs from the post-create hook. A parent created inside a transaction queues\n * the seed loop on that transaction's post-commit boundary; a parent created\n * without a transaction runs it immediately. This prevents an aborted or\n * database-driver-retried parent attempt from leaking independently committed\n * child rows while preserving mixed-adapter, non-fatal seed semantics.\n *\n * IMMEDIATE therefore means \"immediately after commit,\" NOT atomic with the\n * parent. An absent child self-heals via the omit-empty-1:1 context-embed. A\n * seed failure (a child that hasn't opted into `systemAccessPolicy.create`, or\n * a unique-FK conflict on an already-seeded child) is swallowed + logged so it\n * can never 500 the parent create; the warn-first boot guard is where a genuine\n * misconfiguration is surfaced.\n *\n * Re-entrancy: `createAsSystem` forwards `options`, so a seeded child that is\n * itself a composition parent re-enters this method at `compositionSeedDepth + 1`,\n * bounded by each relationship's `maxDepth`. (The delete cascade's repository-tier\n * depth guard is not reusable — this path re-enters at the service tier.)\n */\n private async executeCompositionSeedingForCreate(\n result: any,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions\n ): Promise<void> {\n const resourceRelationships = this.resourceConfiguration.resourceRelationships;\n const childRelationships = getChildDirectionRelationships(resourceRelationships);\n\n let seedRelationships = childRelationships.filter(\n (rel) => this.getResolvedLifecycleOnParentCreate(rel)?.enabled === true\n );\n if (seedRelationships.length === 0) {\n return;\n }\n\n // Only seed relationships active for the concrete created parent variant\n // (mirrors the delete cascade's discriminator-aware filtering).\n seedRelationships = this.filterRelationshipsByParent(seedRelationships, result);\n if (seedRelationships.length === 0) {\n return;\n }\n\n const parentId = this.getResourceIdValue(result);\n if (!parentId) {\n this.logDebug('Composition seeding skipped: no parent id on create result');\n return;\n }\n\n // SystemAccess is injected on ServicesRegistryHandlerBackendService and reached\n // from here (ServiceResourceBackendService) via the registry — mirrors :2885.\n const systemAccess = this.servicesRegistry.getSystemAccessService?.();\n if (!systemAccess) {\n this.logDebug('Composition seeding skipped: SystemAccessService unavailable');\n return;\n }\n\n const currentDepth = options?.compositionSeedDepth ?? 0;\n if (options?.transaction) {\n const transaction = options.transaction;\n const postCommitParentResult = cloneResourceTransactionAttemptInput(\n result,\n );\n const postCommitOptions: RepositoryOptions = {\n compositionSeedDepth: currentDepth,\n ...(options.compositionSeedRequestInput !== undefined && {\n compositionSeedRequestInput:\n cloneResourceTransactionAttemptInput(\n options.compositionSeedRequestInput,\n ),\n }),\n };\n registerTransactionPostCommitEffect(transaction, {\n key: [\n 'composition-seed-after-parent-commit',\n String(this.resourceConfiguration.resourceIdentifier),\n parentId,\n String(currentDepth),\n ].join(':'),\n execute: () =>\n this.executeCompositionSeedingForCreate(\n postCommitParentResult,\n executionContext,\n postCommitOptions,\n ),\n });\n return;\n }\n\n for (const relationship of seedRelationships) {\n const seedConfig = this.getResolvedLifecycleOnParentCreate(relationship)!;\n const maxDepth = seedConfig.maxDepth ?? 1;\n if (currentDepth >= maxDepth) {\n this.logDebug('Composition seed depth cap reached; skipping child seed', {\n childResourceType: relationship.resourceType2,\n currentDepth,\n maxDepth,\n });\n continue;\n }\n\n const childResourceType = relationship.resourceType2 as ResourceType;\n const foreignKeyField = relationship.foreignKeyField;\n if (!foreignKeyField) {\n this.logDebug('Composition seed skipped: relationship declares no foreignKeyField', {\n childResourceType,\n });\n continue;\n }\n\n // A feature-gated child resource (e.g. lifecycle-state when\n // `config.lifecycle.enabled` is false) is EXCLUDED from the runtime registry at\n // assembly time (`start-application` → `excludedResourceTypes` removes the config\n // + standalone relationships + field ids). But the PARENT's compiled\n // `childRelationships` are derived from the pre-exclusion relationship set, so\n // they still reference the excluded child. Seeding it would reach\n // `createAsSystem` → `getResourceConfiguration` → an opaque\n // `resources_registry_initialization_failed` (config absent). Skip cleanly when\n // the child is not registered — the disabled feature means the child simply does\n // not exist to seed. Mirrors the onParentDelete cascade's `if (!childService)`\n // skip in `deleteChildrenImmediate`; uses the safe (undefined-returning)\n // `tryGetResourceConfiguration` rather than the throwing `getResourceConfiguration`.\n if (!this.resourcesRegistry.tryGetResourceConfiguration(childResourceType)) {\n this.logDebug('Composition seed skipped: child resource not registered (feature-gated / excluded from registry)', {\n childResourceType,\n });\n continue;\n }\n\n // Base seed = the injected parent FK; the child create pipeline applies its\n // Zod schema defaults. `override(ctx)` overlays derived fields (Tier-2).\n let seedData: Record<string, unknown> = { [foreignKeyField]: parentId };\n const override = seedConfig.initialData?.override;\n if (override) {\n try {\n const overlay = override({\n parentObject: (result ?? {}) as Record<string, unknown>,\n parentResourceType: this.resourceConfiguration.resourceIdentifier as string,\n initiatorIds: {\n userId: executionContext.initiatorIds?.userId,\n organizationId: executionContext.initiatorIds?.organizationId,\n applicationId: executionContext.initiatorIds?.applicationId,\n },\n // Tier-2 input-derived threading: the create input the provisioning\n // path set on `create(parent, …, { compositionSeedRequestInput })`\n // (e.g. a registration/SSO/SCIM name payload that has no home on the\n // parent row). Absent for pure-defaults children + re-entrant seeds.\n requestInput: options?.compositionSeedRequestInput,\n });\n // An override may DECLINE the seed for this parent-create by returning\n // `undefined` (the required input was absent — e.g. an org-admin invite\n // create carries no name; the invitee supplies it later at acceptance).\n // Skip cleanly rather than attempt a create that would fail validation.\n if (overlay === undefined) {\n this.logDebug('Composition seed override declined for this create; skipping child seed', {\n childResourceType,\n });\n continue;\n }\n seedData = { ...seedData, ...overlay };\n } catch (overrideError) {\n this.logger.warn('Composition seed override threw; skipping child seed', {\n childResourceType,\n ...projectCaughtErrorLogFields(overrideError),\n });\n continue;\n }\n }\n\n try {\n // Pass ONLY the re-entrancy depth — never the parent's other options\n // (transaction / ifMatchVersion / fieldTimestamps are parent-specific).\n await systemAccess.createAsSystem(childResourceType, seedData, {\n compositionSeedDepth: currentDepth + 1,\n });\n this.logDebug('Composition child seeded', { childResourceType, parentId });\n } catch (seedError) {\n // A `WildoError_Backend` is a PLAIN OBJECT (not an Error instance): `String()`\n // yields \"[object Object]\" and `.message` is undefined, so the previous\n // `instanceof Error ? .message : String()` masked every engine-thrown seed\n // failure. The human-readable cause lives in `context.message` (+\n // `context.originalError` for a wrapped Mongoose/driver error); a native error\n // (e.g. a raw Mongoose ValidationError) keeps its stack. Un-masks the swallow.\n this.logger.warn('Composition child seed failed (swallowed)', {\n childResourceType,\n parentId,\n error: isWildoBackendError(seedError)\n ? { customMessageReference: seedError.customMessageReference, context: seedError.context }\n : seedError instanceof Error\n ? (seedError.stack ?? seedError.message)\n : String(seedError),\n });\n }\n }\n }\n\n /**\n * SHARED child-discovery for the `onParentDelete` cascade — used by BOTH strategies\n * (`deleteChildrenImmediate` and `impersonalizeChildrenImmediate`) so there is ONE discovery + cycle\n * guard, never a forked cascade. Finds the children of `parentIds` via the FK relationship (adapter-\n * neutral repository read/list), de-duplicates against the shared `visitedResourceIds` cycle set, and\n * returns the survivors. The caller applies the DEPTH guard BEFORE calling this, and the strategy-\n * specific teardown (delete vs impersonalize) + any grandchild recursion AFTER.\n *\n * ⚠️ The DEPTH guard is deliberately NOT here — it is the CALLER's responsibility (each strategy\n * applies it before calling this), because only the caller knows whether it recurses. Do not move\n * it in, and do not drop it from a new strategy.\n *\n * Returns `null` when there is nothing to cascade: no child service, no children, or every child\n * already visited in this chain.\n */\n private async discoverCascadeChildren(\n relationship: any,\n parentIds: string[],\n executionContext: ExecutionContext<any>,\n cascadeStrategy: ChildLifecycleStrategy,\n visitedResourceIds: Set<string>,\n options?: RepositoryOptions,\n ): Promise<{\n childResourceType: ResourceType;\n fkField: string;\n // `undefined` on the (common) no-transaction path — `buildRepositoryOptionsForResource` returns\n // the caller's `options` verbatim. Keep the `| undefined` honest: `strict` is off in this\n // package, so a lying non-optional type would only surface as a runtime TypeError in a future\n // strategy that dereferences it without optional chaining.\n childRepositoryOptions: RepositoryOptions | undefined;\n newChildIds: string[];\n childSnapshotsById: Map<string, any>;\n } | null> {\n const childResourceType = relationship.resourceType2;\n const fkField = this.getFKFieldForRelationship(relationship);\n\n // Get child service from registry\n const childService = this.servicesRegistry.getService(childResourceType);\n if (!childService) {\n // FAIL-CLOSED for the retain strategy. A missing child service is a MISCONFIGURATION, not a\n // benign \"nothing to do\" — and for IMPERSONALIZE_AND_RETAIN silently skipping means personal\n // data survives an erasure while the parent delete commits (the exact outcome this cascade's\n // other guards refuse). DELETE keeps its historical tolerance (skip ⇒ orphaned rows, already\n // the pre-existing contract), but now says so at WARN instead of DEBUG.\n if (cascadeStrategy === ChildLifecycleStrategy.IMPERSONALIZE_AND_RETAIN) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `IMPERSONALIZE_AND_RETAIN cascade cannot scrub child resource \"${childResourceType}\": no service is ` +\n `registered for it in this process. Refusing to skip — that would leave personal data behind after ` +\n `an erasure while the parent delete commits.`,\n childResourceType,\n fkField,\n relationshipField: this.getNestedFieldName(relationship),\n },\n }\n );\n }\n this.logger.warn('Child service not found, skipping lifecycle cascade', {\n childResourceType,\n cascadeStrategy,\n });\n return null;\n }\n\n // Build filter to find children with parent FK in parentIds.\n // Child discovery must stay adapter-neutral: use repository operations\n // rather than reaching into Mongo-specific model internals.\n const filter = { [fkField]: { $in: parentIds } };\n const childRepositoryOptions = this.buildRepositoryOptionsForResource(\n childResourceType,\n executionContext,\n options\n );\n\n // Child DISCOVERY authoritatively constrains the FK via the explicit `{ [fkField]: { $in:\n // parentIds } }` filter above, so the child's ambient contextual filter must NOT re-apply the\n // parent's `fkField` execution-context value onto the SAME path: for a single parent it is a\n // redundant restatement, and for a multi-parent cascade it actively conflicts (the parent EC\n // carries one id while the discovery lists several). When the parent's resource field identifier\n // equals the child's FK (e.g. TODOS' `todoId` is the occurrences child FK), that collision made\n // a recurring-todo delete fail with `api_call_initiator_parameter_inconsistent`. Excluding only\n // `fkField` from the CONTEXTUAL filter for discovery leaves tenant scope (organizationId/…) fully\n // enforced — and it is scoped to discovery only; the returned `childRepositoryOptions` used for\n // the actual child delete (by explicit ids) is intentionally left untouched. Adapter-neutral:\n // both repositories honour the `string[]` field-exclusion form.\n const existingExclusion = childRepositoryOptions?.excludeContextualFilter;\n const childDiscoveryOptions: RepositoryOptions = {\n ...(childRepositoryOptions ?? {}),\n excludeContextualFilter:\n existingExclusion === true\n ? true\n : [...(Array.isArray(existingExclusion) ? existingExclusion : []), fkField],\n };\n\n // Find children first (we need their IDs for the teardown + recursion)\n const childRepository = this.repositoriesRegistry.getRepository(childResourceType);\n\n /**\n * A missing child REPOSITORY gets the same policy as a missing child SERVICE above — because the\n * two sets can diverge, and dereferencing this is a bare `TypeError` naming nothing.\n *\n * They are not initialized from the same input: `initializeServices()` walks the entire RESOURCE\n * registry (`getResourceTypes()`), while repositories are created only for the configuration map\n * handed to `initializeRepositories()`. In an ordinary application boot those coincide, so this\n * branch is unreachable — but nothing structurally holds them in lockstep, and when they drift the\n * failure was `Cannot read properties of undefined (reading 'supportsOperation')` from inside a\n * cascade, with no resource named and no indication that a registration was the cause.\n *\n * Measured, not hypothesized: this is what stopped the erasure-completion integration lane, and it\n * is the same class of failure recorded (as `…(reading 'filter')`) when that lane was first\n * attempted on 2026-08-05 and abandoned as \"harness completeness\".\n *\n * The strategy split is deliberately IDENTICAL to the service branch: skipping is the historical\n * DELETE contract (orphaned rows), but for IMPERSONALIZE_AND_RETAIN it would leave personal data\n * behind while the parent delete commits.\n */\n if (!childRepository) {\n if (cascadeStrategy === ChildLifecycleStrategy.IMPERSONALIZE_AND_RETAIN) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `IMPERSONALIZE_AND_RETAIN cascade cannot scrub child resource \"${childResourceType}\": a service is ` +\n `registered for it but no REPOSITORY is. Refusing to skip — that would leave personal data behind ` +\n `after an erasure while the parent delete commits.`,\n childResourceType,\n fkField,\n relationshipField: this.getNestedFieldName(relationship),\n },\n }\n );\n }\n this.logger.warn('Child repository not found, skipping lifecycle cascade', {\n childResourceType,\n cascadeStrategy,\n reason: 'a service is registered for this resource but no repository is',\n });\n return null;\n }\n\n let children: any[] = [];\n\n if (isOneToOneCardinality(relationship.cardinality2)) {\n if (!childRepository.supportsOperation(CoreResourceOperation.READ)) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Lifecycle cascade requires READ support on child resource \"${childResourceType}\" ` +\n `to discover 1:1 dependents.`,\n childResourceType,\n fkField,\n relationshipField: this.getNestedFieldName(relationship),\n },\n }\n );\n }\n\n const child = await childRepository.read(executionContext, filter, childDiscoveryOptions);\n children = child ? [child] : [];\n } else {\n if (!childRepository.supportsOperation(CoreResourceOperation.LIST)) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Lifecycle cascade requires LIST support on child resource \"${childResourceType}\" ` +\n `to discover dependent children.`,\n childResourceType,\n fkField,\n relationshipField: this.getNestedFieldName(relationship),\n },\n }\n );\n }\n\n const listedChildren = await childRepository.list(executionContext, filter, childDiscoveryOptions);\n children = Array.isArray(listedChildren) ? listedChildren : [];\n }\n\n if (!children || children.length === 0) {\n // Discovery RAN and found no dependents. This is materially different from a DECLINE (a missing\n // child repository/service, or a spent depth budget), which returns `null` and is the caller's\n // `executed = false` arm. Per the SubjectErasureEdgeOutcome.executed contract, an empty result is\n // \"a teardown that ran with nothing to do\" and MUST be reported as executed = true — otherwise a\n // healthy subject with no rows on an edge is misrecorded on the compliance receipt as data left\n // live. Return an empty-but-valid discovery so the callers reach their `executed = true` path\n // (each guards the empty case before any bulk write, so no empty-filter teardown can run).\n this.logDebug('No children found to cascade', { childResourceType, fkField });\n return { childResourceType, fkField, childRepositoryOptions, newChildIds: [], childSnapshotsById: new Map<string, any>() };\n }\n\n const childIds = children.map((c: any) => c._id?.toString() || c.id);\n const childSnapshotsById = new Map<string, any>();\n for (const child of children) {\n const childId = child?._id?.toString() || child?.id;\n if (childId) {\n childSnapshotsById.set(childId, child);\n }\n }\n\n // Guard 2: Circular reference detection\n // Check if any child ID was already visited in this cascade chain.\n // This prevents infinite loops when resources reference each other.\n // Note: This detects same-chain circular refs (A→B→A). Cross-branch circular refs\n // (A→B→C→A where C is reached via a different parent) are rare and would require\n // more complex graph traversal to detect fully.\n const newChildIds: string[] = [];\n for (const childId of childIds) {\n const resourceKey = `${childResourceType}:${childId}`;\n if (visitedResourceIds.has(resourceKey)) {\n this.logDebug('Circular reference detected, skipping child', {\n childResourceType,\n childId,\n resourceKey,\n note: 'This resource was already processed in this cascade chain, preventing infinite loop'\n });\n continue;\n }\n visitedResourceIds.add(resourceKey);\n newChildIds.push(childId);\n }\n\n if (newChildIds.length === 0) {\n this.logDebug('All children skipped due to circular references', { childResourceType });\n return null;\n }\n\n this.logDebug('Found children to cascade', {\n childResourceType,\n count: newChildIds.length,\n skipped: childIds.length - newChildIds.length,\n });\n\n return { childResourceType, fkField, childRepositoryOptions, newChildIds, childSnapshotsById };\n }\n\n /**\n * Delete child resources immediately (synchronous, within the same transaction) — the DELETE\n * teardown strategy of the `onParentDelete` cascade. Discovers the children through the shared\n * {@link discoverCascadeChildren}, recurses into grandchildren via the shared\n * {@link dispatchLifecycleCascadeForRelationship} (so each deeper edge gets ITS OWN strategy), runs\n * the file-cleanup contract, then removes the rows.\n *\n * Owns the DEPTH guard (discovery deliberately does not) plus circular-reference detection, to\n * prevent infinite loops on cyclic FK graphs.\n *\n * @param relationship - The relationship configuration\n * @param parentIds - IDs of parent resources being deleted\n * @param executionContext - Execution context for the operation\n * @param currentDepth - Current recursion depth (starts at 0)\n * @param maxDepth - Maximum allowed depth (from lifecycle config, default 1)\n * @param visitedResourceIds - Set of visited resource IDs to prevent circular references\n * @param options - Repository options (carries the parent's transaction, when present)\n */\n private async deleteChildrenImmediate(\n relationship: any,\n parentIds: string[],\n executionContext: ExecutionContext<any>,\n currentDepth: number = 0,\n maxDepth: number = 1,\n visitedResourceIds: Set<string> = new Set(),\n options?: RepositoryOptions\n ): Promise<boolean> {\n // Guard 1: Depth limit check\n if (currentDepth >= maxDepth) {\n this.logDebug('Max depth reached, stopping lifecycle delete', {\n currentDepth,\n maxDepth,\n childResourceType: relationship.resourceType2\n });\n // The depth budget is spent, so nothing was torn down at this edge — see the dispatcher's\n // @returns contract, which the erasure receipt reads.\n return false;\n }\n\n const childResourceType = relationship.resourceType2;\n const fkField = this.getFKFieldForRelationship(relationship);\n\n this.logDebug('Deleting children immediately', {\n childResourceType,\n fkField,\n parentIdsCount: parentIds.length,\n currentDepth,\n maxDepth\n });\n\n try {\n const discovered = await this.discoverCascadeChildren(\n relationship,\n parentIds,\n executionContext,\n ChildLifecycleStrategy.DELETE,\n visitedResourceIds,\n options,\n );\n if (!discovered) return false; // discovery declined (no service/repository) — nothing was torn down\n const { newChildIds, childSnapshotsById, childRepositoryOptions } = discovered;\n // Discovery RAN but found no dependents on this edge — a teardown that ran with nothing to do.\n // Return true (processed) per the dispatcher's @returns contract, BEFORE any capability check or\n // bulk delete, so an empty id set can never reach `deleteMany([])` (whose empty-filter semantics\n // would be catastrophic). This is the `executed = true` receipt for a healthy no-rows edge.\n if (newChildIds.length === 0) {\n return true;\n }\n // VARIANT-AGNOSTIC CASCADE: the onParentDelete teardown deletes children directly through the RAW\n // repository (below) and gates ONLY on the child declaring a DELETE / DELETE_MANY *operation*\n // (the capability checks that follow) — NOT on that operation's variant type. So a child whose\n // DELETE is `API_CALL` (an owner-facing revoke route), `INTERNAL_CALL`, or `REPOSITORY_ONLY` all\n // cascade-delete identically; the variant governs only the HTTP/service surface, never this teardown.\n // (Recorded when OAUTH_CONSENT_GRANTS added an owner-facing API_CALL DELETE and needed the USERS\n // composition cascade to still remove its grants — it does, because of exactly this.)\n const childRepository = this.repositoriesRegistry.getRepository(childResourceType);\n\n const supportsDeleteMany = childRepository.supportsOperation(CoreResourceOperation.DELETE_MANY);\n const supportsDelete = childRepository.supportsOperation(CoreResourceOperation.DELETE);\n if (!supportsDeleteMany && !supportsDelete) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Lifecycle delete requires DELETE_MANY or DELETE support on child resource \"${childResourceType}\".`,\n childResourceType,\n relationshipField: this.getNestedFieldName(relationship),\n },\n }\n );\n }\n\n // Recursively delete grandchildren before mutating the current child level.\n // This keeps deeper failures from leaving the current child rows already\n // deleted while descendants remain behind.\n // Activation must still be evaluated against each deleted child snapshot before we recurse;\n // otherwise discriminator/condition-gated lifecycle relationships would over-delete deeper\n // descendants just because the FK chain exists.\n if (currentDepth + 1 < maxDepth) {\n const childConfig = this.resourcesRegistry.tryGetResourceConfiguration(childResourceType);\n if (childConfig?.resourceRelationships) {\n const grandchildRelationships = getChildDirectionRelationships(childConfig.resourceRelationships).filter(\n (rel: any) => this.getResolvedLifecycleOnParentDelete(rel)?.enabled === true\n );\n\n for (const grandchildRel of grandchildRelationships) {\n const grandchildLifecycleConfig = this.getResolvedLifecycleOnParentDelete(grandchildRel)!;\n const grandchildMaxDepth = grandchildLifecycleConfig.maxDepth || 1;\n const activeGrandchildParentIds = newChildIds.filter(childId => {\n const childSnapshot = childSnapshotsById.get(childId);\n if (!childSnapshot) {\n return false;\n }\n\n return this.filterRelationshipsByParent([grandchildRel], childSnapshot).length > 0;\n });\n\n if (activeGrandchildParentIds.length === 0) {\n continue;\n }\n\n // Recurse through THE shared (strategy × mode) dispatcher — never straight into\n // `deleteChildrenImmediate`. The grandchild edge declares its OWN teardown strategy: a\n // grandchild on an IMPERSONALIZE_AND_RETAIN edge must be scrubbed-and-retained, not\n // hard-deleted, even though we reached it from a DELETE cascade. (Its parent — the child\n // level — IS being deleted, so the grandchild's `onParentDelete` precondition is met; only\n // the teardown differs.)\n await this.dispatchLifecycleCascadeForRelationship(\n grandchildRel,\n activeGrandchildParentIds,\n executionContext,\n currentDepth + 1,\n Math.min(maxDepth, grandchildMaxDepth + currentDepth + 1), // Respect both limits\n visitedResourceIds, // Share visited set to prevent cross-branch circular refs\n options\n );\n }\n }\n }\n\n // Keep lifecycle depth ownership in this method, but do not bypass the\n // file cleanup contract. Child resources with file fields must run through\n // the same file-delete orchestration before their repository delete lands.\n if (this.fileFieldDetection.hasFileFields(childResourceType)) {\n for (const childId of newChildIds) {\n if (this.fileMetadataRequiresSeparateCommit(childResourceType)) {\n await this.executeFileMetadataWork(\n executionContext,\n childRepositoryOptions,\n async (fileOptions) => this.fileOperationHandler.processFileFieldsForDelete(\n childResourceType,\n childId,\n executionContext,\n fileOptions\n )\n );\n } else {\n await this.fileOperationHandler.processFileFieldsForDelete(\n childResourceType,\n childId,\n executionContext,\n childRepositoryOptions\n );\n }\n }\n }\n\n // The repository call must still stay adapter-agnostic: pass the generic\n // ids array contract instead of a Mongo-specific `{ _id: { $in: ... } }`\n // filter shape.\n if (supportsDeleteMany) {\n await childRepository.deleteMany(executionContext, newChildIds, childRepositoryOptions);\n } else if (supportsDelete) {\n for (const childId of newChildIds) {\n await childRepository.delete(executionContext, childId, childRepositoryOptions);\n }\n }\n\n // RAG removal seam — ROW DELETE (lifecycle cascade). The cascade deletes children through the\n // RAW child repository (above), never through the child's own service dispatch, so the child's\n // single-delete seam cannot fire — this call is the child rows' only chunk-removal path.\n // Registered post-commit on the cascade's ambient transaction (when one exists) so an aborted\n // parent delete keeps the children's chunks intact along with the children.\n await this.runRagChunkRemovalForDeletedRows(\n childResourceType,\n newChildIds,\n 'lifecycle-cascade-delete',\n childRepositoryOptions ?? options,\n );\n\n this.logDebug('Children deleted successfully', {\n childResourceType,\n deletedCount: newChildIds.length\n });\n } catch (error) {\n this.logger.error('Failed to delete children in lifecycle operation', {\n childResourceType,\n fkField,\n currentDepth,\n ...projectCaughtErrorLogFields(error)\n });\n // Re-throw to ensure parent delete fails if child delete fails\n throw error;\n }\n\n // A teardown RAN. Discovery finding zero children counts — the edge was processed and had nothing\n // to remove, which is materially different from declining to process it. A failure never reaches\n // here (the catch above re-throws), so this cannot report success for a broken teardown.\n return true;\n }\n\n /**\n * IMPERSONALIZE_AND_RETAIN sibling of {@link deleteChildrenImmediate}: instead of hard-deleting a\n * deleted parent's children, scrub their personal fields IN PLACE and flip them to `RETAINED`, so\n * each row survives for a legal/audit retention obligation (GDPR Art. 17(3)(b)). Shares the exact\n * child-discovery + cycle guard via {@link discoverCascadeChildren}; only the teardown diverges.\n *\n * ⚠️ **Not** the anonymous-user concept — impersonalization scrubs personal data OUT of a KEPT row;\n * it is the opposite direction from anonymous-session ownership transposition. Never conflate them.\n *\n * **v1 scope — DIRECT children only, NO recursion.** The parent-delete cascade impersonalizes the\n * immediate children the deleted parent owned; a retained (kept) child still has a valid parent for\n * ITS OWN children, so nothing is orphaned and no grandchild descent is required here. The\n * whole-subtree scrub (a subject-erasure walking every descendant — architecture doc D8) is the\n * separate direct-subject-erasure orchestrator's job (v1.5), NOT this parent-delete cascade.\n *\n * Files ARE handled, but by TREATMENT rather than wholesale (gate G-FILE): a file field the author\n * marked `.impersonalizeWith()` has its file deleted, because a field-scrub cannot reach inside a\n * blob; a KEEP/untreated file field survives with the retained row. \"Keep the record\" must not\n * silently become \"keep the personal data\".\n *\n * The scrub write goes through {@link SystemAccessBackendService.updateManyAsSystem} — the same\n * fail-closed trusted-write primitive the resource factory documents as the impersonalize writer. It\n * synthesises a super-admin system context, re-attaches the DTO-stripped `retentionStatus` /\n * `impersonalizedAt` markers (both `.excludeFromUpdate()`) past the strict parse, and best-effort\n * audits the privileged write. The parent-delete transaction rides through `childRepositoryOptions`\n * (already adapter-validated by discovery), keeping the scrub atomic with the parent delete.\n */\n /**\n * THE impersonalize-and-retain WRITE — scrub the given rows in place and mark them `RETAINED`.\n *\n * Cascade-agnostic on purpose: it takes explicit row ids and knows nothing about relationships,\n * discovery or depth. That is what lets the parent-delete cascade AND the direct subject-erasure\n * entry point (`impersonalizeSubjectAsSystem`) share ONE definition of what \"impersonalize these\n * rows\" means. Splitting them would let the two drift on the exact thing that must not drift: what\n * counts as erased.\n *\n * Order of operations, each load-bearing:\n * 1. **Retention-governance assert** — the `retentionStatus` / `impersonalizedAt` markers and the\n * `updateMany` / `seeRetained` grants are factory-injected ONLY for a retention-governed\n * resource. Without them there is nowhere to record the flip and no grant to write with.\n * 2. **Trusted-writer assert** — refuse rather than silently skip the scrub when SystemAccessService\n * is unbound (skipping would leave personal data behind after an erasure).\n * 3. **Scrub + markers in ONE write**, preserving every scrub key past the strict update DTO (some\n * field classes — templatable file fields — are omitted from the DTO and in no derived preserve\n * set; their value would otherwise be dropped while the row still flipped to RETAINED).\n * 4. **File erasure AFTER the write**, by treatment, so a failed/rolled-back scrub never destroys\n * files for rows that were not actually retained. FILES is always MongoDB-backed, so HOW the\n * erasure is sequenced depends on the ambient transaction's adapter — see\n * {@link eraseImpersonalizedRowFiles} for the cross-adapter split-brain this closes.\n */\n /**\n * The `USERS` ids whose sessions a scrub of these rows must end, per the resource's AUTHORED\n * `dataSubjectPolicy`.\n *\n * The linkage is never inferred from the shape of a foreign key. On almost every resource a user FK\n * names the OWNER or the ACTOR — `TODOS` carries `createdByUserId`, `assignedToUserId` and\n * `escalationContactUserId` — so inferring one would revoke the sessions of authors and assignees\n * instead of the data subject. Only an explicit declaration is honoured:\n * - `SELF_PRINCIPAL` — the row IS the person; its own id is the user id (no read needed).\n * - `LINKED_PRINCIPAL` — the declared `sessionPrincipalField` holds the user id.\n * - `NO_PRINCIPAL` / undeclared — no principal; nothing is revoked.\n *\n * Best-effort: a lookup failure must never abort a scrub the data subject is entitled to. It is\n * reported as a FAILURE rather than as \"no principals\", because an unresolved principal means the\n * person may still hold a live session and the two must not look alike.\n */\n private async resolveScrubSessionPrincipals(\n resourceType: ResourceType,\n rowIds: string[],\n resourceConfiguration: { dataSubjectPolicy?: ResourceDataSubjectPolicy },\n systemAccess: SystemAccessBackendService,\n options?: RepositoryOptions,\n errorContext?: Record<string, unknown>,\n ): Promise<{ userIds: string[]; lookupFailed: boolean }> {\n const policy = resourceConfiguration.dataSubjectPolicy;\n if (!policy || policy.kind === ResourceDataSubjectKind.NO_PRINCIPAL) {\n return { userIds: [], lookupFailed: false };\n }\n if (policy.kind === ResourceDataSubjectKind.SELF_PRINCIPAL) {\n return { userIds: [...new Set(rowIds)], lookupFailed: false };\n }\n const principalField = policy.sessionPrincipalField;\n if (!principalField) {\n return { userIds: [], lookupFailed: false };\n }\n try {\n const resolved = new Set<string>();\n // Chunked by id AND paged to completion: an unpaginated list silently caps at the DEFAULT limit\n // of 20, and an explicit limit is still bounded by whatever ceiling the resource's LIST\n // operation declares. Either would drop principals with nothing saying so.\n const CHUNK = 100;\n for (let offset = 0; offset < rowIds.length; offset += CHUNK) {\n const chunk = rowIds.slice(offset, offset + CHUNK);\n for (let page = 1; ; page++) {\n const result = await systemAccess.listAsSystem<Record<string, unknown>>(\n resourceType,\n { _id: { $in: chunk } },\n { page, limit: chunk.length },\n options,\n );\n const rows = Array.isArray(result) ? result : result.data;\n for (const row of rows) {\n const value = row[principalField];\n if (typeof value === 'string' && value.length > 0) {\n resolved.add(value);\n }\n }\n if (Array.isArray(result)) break;\n const { limit, total } = result.pagination;\n if (rows.length === 0 || page * limit >= total) break;\n }\n }\n return { userIds: [...resolved], lookupFailed: false };\n } catch (error) {\n this.logger.warn(\n 'Could not resolve the scrubbed subject\\'s session principals; sessions may survive the erasure',\n { resourceType, principalField, rowCount: rowIds.length, ...(errorContext ?? {}), ...projectCaughtErrorLogFields(error) },\n );\n return { userIds: [], lookupFailed: true };\n }\n }\n\n /**\n * Schedule the session revocation for after the transaction commits.\n *\n * Fire-and-forget by design: the rows are already scrubbed and durable, so throwing here would\n * invite a retry of an erasure whose local half succeeded. A failure is logged at ERROR — loudly,\n * because it means an erased person may still be browsing on a live token.\n */\n private scheduleScrubSessionRevocation(\n resourceType: ResourceType,\n principals: { userIds: string[]; lookupFailed: boolean },\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n errorContext?: Record<string, unknown>,\n ): void {\n if (principals.lookupFailed) {\n this.logger.error(\n 'A scrubbed subject\\'s session principals could not be resolved, so NO session was revoked',\n { resourceType, ...(errorContext ?? {}) },\n );\n return;\n }\n if (principals.userIds.length === 0) {\n return;\n }\n const revocation = this.servicesRegistry.getSubjectSessionRevocationService?.();\n if (!revocation?.isRegistered) {\n this.logger.error(\n 'No session revoker is registered, so a scrubbed subject\\'s sessions were NOT revoked',\n { resourceType, principalCount: principals.userIds.length, ...(errorContext ?? {}) },\n );\n return;\n }\n\n const ambientTransaction = options?.transaction;\n const revokeAll = async (): Promise<void> => {\n for (const userId of principals.userIds) {\n try {\n await revocation.revokeAllSessionsForUser(userId);\n } catch (error) {\n this.logger.error(\n 'Failed to revoke a scrubbed subject\\'s sessions; they may remain live until their tokens expire',\n { resourceType, userId, ...(errorContext ?? {}), ...projectCaughtErrorLogFields(error) },\n );\n }\n }\n };\n\n // Outside a transaction (a direct impersonalize with no ambient one) the write is already durable,\n // so there is nothing to wait for.\n if (!ambientTransaction) {\n void revokeAll();\n return;\n }\n registerTransactionPostCommitEffect(ambientTransaction, {\n key: ['subject-session-revocation', String(resourceType), ...principals.userIds].join(':'),\n execute: revokeAll,\n });\n }\n\n public async impersonalizeRowsInPlace(\n resourceType: ResourceType,\n rowIds: string[],\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n /** Extra diagnostic context for the cascade caller (relationship provenance). */\n errorContext?: Record<string, unknown>,\n ): Promise<{ principalUserIds: string[]; lookupFailed: boolean }> {\n if (rowIds.length === 0) {\n return { principalUserIds: [], lookupFailed: false };\n }\n\n const resourceConfiguration = this.resourcesRegistry.getResourceConfiguration(resourceType);\n if (!resourceConfiguration.retentionPolicy) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Impersonalize-and-retain requires resource \"${resourceType}\" to opt into retentionPolicy ` +\n `(the retentionStatus marker + updateMany grant are factory-injected only for ` +\n `retention-governed resources).`,\n resourceType,\n ...(errorContext ?? {}),\n },\n }\n );\n }\n\n const systemAccess = this.servicesRegistry.getSystemAccessService?.();\n if (!systemAccess) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message:\n `Impersonalize-and-retain requires SystemAccessService (the trusted updateManyAsSystem scrub ` +\n `writer), but it is not bound in this container.`,\n resourceType,\n ...(errorContext ?? {}),\n },\n }\n );\n }\n\n // The marker written here is the WRITE side of the hide rule — the value this patch stamps is, by\n // definition, the value every read/write/aggregate path excludes. It therefore comes from the same\n // retention authority the hide predicate negates, so the two can never name different statuses (or\n // different field spellings) after a rename.\n // ── SESSION principals, resolved BEFORE the scrub ────────────────────────────────────────────\n //\n // Every path that scrubs a person's row funnels through this method — the erasure subject, a\n // direct `impersonalizeSubjectAsSystem`, and a parent-delete cascade impersonalizing a child — so\n // resolving here is what makes \"an erased person's session ends\" hold by construction rather than\n // being re-applied at each entry point (and missed at two of them, which is what #32 recorded).\n //\n // BEFORE the write, because afterwards the row is RETAINED and hidden from every ordinary read,\n // and the only see-through door demands a privileged HUMAN plus a written justification.\n const sessionPrincipals = await this.resolveScrubSessionPrincipals(\n resourceType,\n rowIds,\n resourceConfiguration,\n systemAccess,\n options,\n errorContext,\n );\n\n const scrubPatch = buildImpersonalizeScrubPatch(resourceConfiguration.mainSchema);\n const data: Record<string, unknown> = {\n ...scrubPatch,\n ...buildRetentionMarkerStampPatch(),\n impersonalizedAt: new Date(),\n };\n\n await systemAccess.updateManyAsSystem(\n resourceType,\n rowIds,\n data,\n { ...options, preserveServerInjectedFields: Object.keys(data) },\n );\n\n // POST-COMMIT, for the same reason the file erasure below defers: the local scrub must be durable\n // before a session is ended, or a rolled-back erasure would leave a real user logged out of an\n // account that still exists. The reverse order is the worse failure.\n this.scheduleScrubSessionRevocation(resourceType, sessionPrincipals, executionContext, options, errorContext);\n\n // RAG removal seam — FIELD IMPERSONALIZATION. Every path that scrubs a person's row funnels\n // through this method (the #32 chokepoint argument), so hooking here is what makes\n // \"RAG_SOURCE + IMPERSONALIZE_WITH ⇒ chunks deleted in the same decision\" hold for the erasure\n // subject, a direct impersonalize, AND the parent-delete cascade at once. The scrubbed field set\n // comes from the WRITER (`buildImpersonalizeScrubPatch`) — the same derive-from-the-writer rule\n // the zero-scrub guard follows — and the intersection with declared RAG-source fields happens in\n // the shared util. Post-commit on the ambient transaction: a rolled-back scrub keeps its chunks.\n await this.runRagChunkRemovalForFields(\n resourceType,\n rowIds,\n Object.keys(scrubPatch),\n 'impersonalize-scrub',\n options,\n );\n\n // A field-level scrub cannot reach INSIDE a stored blob, so a file field marked personal is only\n // erased by deleting the file. Files on KEEP/untreated fields survive — that is how a\n // legally-required artifact stays with its retained record.\n if (this.fileFieldDetection.hasFileFields(resourceType)) {\n await this.eraseImpersonalizedRowFiles(\n resourceType,\n rowIds,\n Object.keys(scrubPatch),\n executionContext,\n options,\n );\n }\n\n // Returned so the erasure receipt can evidence it. The cascade and the direct-impersonalize\n // callers have no report and ignore this.\n return { principalUserIds: sessionPrincipals.userIds, lookupFailed: sessionPrincipals.lookupFailed };\n }\n\n /**\n * Erase the personal files of rows that were just impersonalized-and-retained, sequenced so a\n * rolled-back scrub can NEVER destroy files for rows that stayed live.\n *\n * FILES is always MongoDB-backed, while the impersonalized resource may not be — and that asymmetry\n * is the whole problem this method exists to solve. Three cases, each load-bearing:\n *\n * 1. **No ambient transaction** — the scrub write already committed on its own, so there is nothing\n * left to roll back. Erase inline.\n * 2. **Ambient MongoDB transaction** — FILES joins the SAME native session, so the file deletions\n * are part of the scrub's atomic unit: a rollback un-deletes them. Erase inline.\n * 3. **Ambient NON-Mongo transaction (today: PostgreSQL)** — the file work CANNOT join it.\n * `executeFileMetadataWork` would open an INDEPENDENT MongoDB transaction that commits\n * immediately, so a later rollback of the PostgreSQL parent would leave a LIVE, un-scrubbed row\n * whose files are already marked DELETED — and hard-deleted by the cleanup batch ~30 days later.\n * Silent, unrecoverable data destruction on a row that was never erased. So the erasure is\n * DEFERRED to a post-commit effect on the parent transaction: it runs only if the parent really\n * commits, and simply never runs if it aborts (an aborted attempt's queue is unreachable).\n *\n * The FILES-is-Mongo assertion is made EAGERLY in case 3, before deferral: a misconfiguration must\n * fail the transaction, not surface after it has already committed.\n *\n * ⚠️ **Limitation of case 3, by construction.** A post-commit effect runs after an irreversible\n * commit, so its failure is REPORTED, never thrown (see `drainTransactionPostCommitEffects`) — a\n * failed deferred erasure leaves the row retained with its personal files still present. That is\n * strictly better than the split-brain it replaces (which destroyed files for LIVE rows), but it is\n * an at-least-once obligation, not an atomic one: the effect logs at ERROR with the row identity so\n * the failure is actionable, and a durable retry belongs to the retention-clock disposal job rather\n * than to this write path. Cases 1 and 2 carry no such caveat.\n */\n private async eraseImpersonalizedRowFiles(\n resourceType: ResourceType,\n rowIds: string[],\n scrubbedFieldNames: string[],\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<void> {\n const ambientTransaction = options?.transaction;\n const isCrossAdapterTransaction = !!ambientTransaction\n && ambientTransaction.databaseType !== this.getFileMetadataAdapter();\n\n if (!isCrossAdapterTransaction) {\n for (const rowId of rowIds) {\n await this.fileOperationHandler.processFileFieldsForImpersonalize(\n resourceType,\n rowId,\n scrubbedFieldNames,\n executionContext,\n options,\n );\n }\n return;\n }\n\n // The parent transaction is about to be handed the erasure; strip it from the options the\n // deferred work will use. It is committed by the time the effect runs, so carrying it would be\n // meaningless at best and would re-enter a dead native session at worst. Every other option\n // (version fences, seed depth) is preserved.\n const { transaction: _committedParentTransaction, ...postCommitOptions } = options ?? {};\n\n for (const rowId of rowIds) {\n registerTransactionPostCommitEffect(ambientTransaction, {\n key: ['retention-impersonalize-file-erasure', String(resourceType), rowId].join(':'),\n execute: async () => {\n try {\n await this.executeFileMetadataWork(\n executionContext,\n postCommitOptions as RepositoryOptions,\n async (fileOptions) => this.fileOperationHandler.processFileFieldsForImpersonalize(\n resourceType,\n rowId,\n scrubbedFieldNames,\n executionContext,\n fileOptions,\n )\n );\n } catch (error) {\n // The parent commit is irreversible and the drain never rethrows, so an unlogged failure\n // here would be an invisible compliance gap: a row wearing an \"erased\" label whose\n // personal files are still readable.\n this.logger.error('Deferred impersonalize file erasure FAILED after parent commit', {\n resourceType,\n rowId,\n scrubbedFieldNames,\n parentTransactionId: ambientTransaction.id,\n parentDatabaseType: ambientTransaction.databaseType,\n ...projectCaughtErrorLogFields(error),\n });\n throw error;\n }\n },\n });\n }\n }\n\n /**\n * ROW-DELETE half of the RAG chunk-removal invariant: once these rows' deletion is durable, every\n * chunk derived from them is removed. Called from the single-delete path, both bulk-delete paths,\n * the cascade teardown, and (via the shared batch context) the retention sweep — the full seam\n * inventory and the shared failure/transaction contract live in\n * `~wildo-backend-lib/rag/utils/rag-chunk-removal.backend.utils`.\n *\n * A missing removal context (minimal container) is a silent no-op BY DESIGN — see\n * {@link ServicesRegistryHandlerBackendService.getRagChunkRemovalContext}.\n */\n private async runRagChunkRemovalForDeletedRows(\n resourceType: ResourceType,\n resourceIds: string[],\n seam: string,\n options?: RepositoryOptions,\n ): Promise<void> {\n const removalContext = this.servicesRegistry.getRagChunkRemovalContext?.();\n if (!removalContext) return;\n await scheduleRagChunkRemovalForDeletedRows(removalContext, {\n resourceType,\n resourceIds,\n seam,\n transaction: options?.transaction,\n });\n }\n\n /**\n * The deleted row ids of a bulk-delete result, for the RAG removal seam. Mirrors the id extraction\n * `executeLifecycleOperations` performs for the cascade (string entries, row objects, or a\n * `deletedIds` envelope), falling back to the pre-delete snapshots when the repository result\n * carries no ids at all.\n */\n private collectDeletedRowIdsForRagRemoval(result: any, currentStates?: any[]): string[] {\n if (Array.isArray(result)) {\n // An EMPTY array is an answer (\"nothing was deleted\"), not a gap — no fallback, or a raced\n // bulk delete would remove chunks for rows that are still live.\n return result\n .map((item: any) => (typeof item === 'string' ? item : this.getResourceIdValue(item)))\n .filter((id: string | undefined): id is string => Boolean(id));\n }\n if (Array.isArray(result?.deletedIds)) {\n return result.deletedIds.filter(Boolean);\n }\n // A result shape carrying no ids at all: fall back to the pre-delete snapshots. Over-deletion is\n // the safe direction for a DERIVED tier — a chunk removed for a surviving row costs a re-index;\n // a chunk kept for a deleted row is the privacy gap this seam exists to close.\n return (currentStates ?? [])\n .map((row) => this.getResourceIdValue(row))\n .filter((id): id is string => Boolean(id));\n }\n\n /**\n * FIELD-LEVEL half of the RAG chunk-removal invariant: a field whose value was destroyed\n * (impersonalize scrub) loses its chunk set in the same decision. The intersection with the\n * resource's declared RAG-source fields happens inside the shared util, so an unrelated scrub\n * removes nothing.\n */\n private async runRagChunkRemovalForFields(\n resourceType: ResourceType,\n resourceIds: string[],\n affectedFieldNames: string[],\n seam: string,\n options?: RepositoryOptions,\n ): Promise<void> {\n const removalContext = this.servicesRegistry.getRagChunkRemovalContext?.();\n if (!removalContext) return;\n await scheduleRagChunkRemovalForFields(removalContext, {\n resourceType,\n resourceIds,\n affectedFieldNames,\n seam,\n transaction: options?.transaction,\n });\n }\n\n /**\n * WRITE half of the RAG derived-data invariant: a committed service-tier write that touched a\n * `.ragSource()` field re-derives that field's chunk set (delete-then-replace inside the store —\n * the DL1 ledger upsert). Called from ONE place, `executeFrameworkManagedPostCommitEffects`,\n * which every write door's dispatch reaches post-commit; the decision logic (write-verb filter,\n * changed-field intersection, retained-row exclusion) lives in\n * `~wildo-backend-lib/rag/utils/rag-ingestion-trigger.backend.utils`.\n *\n * DETACHED FROM THE REQUEST on purpose (`setImmediate`, the guidance/milestone/lifecycle\n * evaluator discipline in the same chokepoint): a FILE_EXTRACTION field's ingestion downloads and\n * parses the file, and a user write must neither wait on nor fail from corpus derivation — the\n * ledger + hourly sweep bound anything a crashed process drops here. Occurrence-keyed post-commit\n * dedup is inherited from the chokepoint itself: the `resource-post-commit` registration key\n * already carries `frameworkPostCommitEffectOccurrenceId`, so this hook runs at most once per\n * service-operation occurrence with no second dedup layer.\n */\n private runRagChunkIngestionForWrite(\n resolvedOperation: ResourceConfiguration_Operation<any, any, any>,\n operationPath: ResourceConfiguration_OperationPath<any, any>,\n executionContext: ExecutionContext<any>,\n inputData: unknown,\n committedState: unknown,\n ): void {\n const ingestionContext = this.servicesRegistry.getRagIngestionContext?.();\n if (!ingestionContext) return;\n\n // A custom operation's effective verb is the core operation it borrows (`resourceOperationLike`);\n // a core operation's identifier IS its verb. Non-write verbs (read/list/delete/…) return here,\n // so no timer is queued for the overwhelmingly common non-ingesting dispatches.\n //\n // `resourceOperationLike` is OPTIONAL, so the fallback below can land on a custom operation's own\n // identifier string, which is in no core-verb set — the operation then participates in nothing.\n // That gap is REPORTED rather than guessed at (inferring the verb from `httpVerb` would hand\n // `ingestRow` a payload that is not a row, and a missing field reads as a corpus that went away,\n // i.e. a DELETE of live chunks); see `isUndeclaredCustomOperationIdentifier`.\n const declaredOperationLike = (resolvedOperation as unknown as { resourceOperationLike?: CoreResourceOperation }).resourceOperationLike;\n const operationIdentifier = String(operationPath.operationIdentifier);\n const operationLike = declaredOperationLike ?? (operationIdentifier as CoreResourceOperation);\n if (!RAG_INGESTION_WRITE_OPERATIONS.has(operationLike)) {\n if (isUndeclaredCustomOperationIdentifier(declaredOperationLike, operationIdentifier)) {\n reportRagIngestionSkippedUndeclaredCustomOperation(ingestionContext, {\n resourceType: operationPath.resourceIdentifier as ResourceType,\n operationIdentifier,\n });\n }\n return;\n }\n\n setImmediate(() => {\n runRagIngestionForServiceWrite(ingestionContext, {\n resourceType: operationPath.resourceIdentifier as ResourceType,\n operationLike,\n inputData,\n committedState,\n executionContext,\n seam: 'service-write',\n }).catch((err: unknown) => {\n // `runRagIngestionForServiceWrite` owns its failure contract (log-never-throw); this catch\n // only guards the detachment itself so a contract regression cannot become an unhandled\n // rejection in the request-less microtask.\n this.logDebug('RAG ingestion trigger rejected outside its failure contract', {\n error: describeCaughtError(err),\n });\n });\n });\n }\n\n private async impersonalizeChildrenImmediate(\n relationship: any,\n parentIds: string[],\n executionContext: ExecutionContext<any>,\n currentDepth: number = 0,\n maxDepth: number = 1,\n visitedResourceIds: Set<string> = new Set(),\n options?: RepositoryOptions\n ): Promise<boolean> {\n // Guard 1: Depth limit check. v1 impersonalize never recurses, so currentDepth is always 0 here;\n // the guard is kept for signature-parity with deleteChildrenImmediate + defence-in-depth.\n if (currentDepth >= maxDepth) {\n this.logDebug('Max depth reached, stopping lifecycle impersonalize', {\n currentDepth,\n maxDepth,\n childResourceType: relationship.resourceType2\n });\n // Nothing scrubbed at this edge. Reported as such rather than as a completed teardown — for an\n // erasure this is the difference between a truthful receipt and one that overstates it.\n return false;\n }\n\n const childResourceType = relationship.resourceType2;\n const fkField = this.getFKFieldForRelationship(relationship);\n\n this.logDebug('Impersonalizing children immediately (retain-and-scrub)', {\n childResourceType,\n fkField,\n parentIdsCount: parentIds.length,\n currentDepth,\n maxDepth\n });\n\n try {\n const discovered = await this.discoverCascadeChildren(\n relationship,\n parentIds,\n executionContext,\n ChildLifecycleStrategy.IMPERSONALIZE_AND_RETAIN,\n visitedResourceIds,\n options,\n );\n if (!discovered) return false; // discovery declined (no service/repository) — nothing was torn down\n const { newChildIds, childRepositoryOptions } = discovered;\n // Discovery RAN but found no dependents — a scrub that ran with nothing to do. Return true\n // (processed) BEFORE calling impersonalizeRowsInPlace, so an empty id set can never widen into an\n // all-rows scrub. This is the `executed = true` receipt for a healthy no-rows edge.\n if (newChildIds.length === 0) {\n return true;\n }\n\n // The post-discovery half is the SHARED core, so the cascade and the direct subject-erasure\n // entry point cannot drift on what \"impersonalize these rows\" means.\n await this.impersonalizeRowsInPlace(\n childResourceType,\n newChildIds,\n executionContext,\n childRepositoryOptions,\n // Cascade provenance: the generic core reports `resourceType`, but a cascade failure is more\n // diagnosable when it also names the row as a CHILD and points at the edge that reached it.\n { childResourceType, relationshipField: this.getNestedFieldName(relationship), fkField },\n );\n\n this.logDebug('Children impersonalized-and-retained successfully', {\n childResourceType,\n retainedCount: newChildIds.length\n });\n } catch (error) {\n this.logger.error('Failed to impersonalize children in lifecycle operation', {\n childResourceType,\n fkField,\n currentDepth,\n ...projectCaughtErrorLogFields(error)\n });\n // Re-throw to ensure the parent delete fails if the child scrub fails (transactional integrity).\n throw error;\n }\n\n // A scrub RAN (zero children included — the edge was processed). See the dispatcher's @returns.\n return true;\n }\n\n /**\n * THE v1 SUBJECT-ERASURE ORCHESTRATOR — what a \"delete my account\" request executes.\n *\n * An erasure is NOT a delete. The subject row SURVIVES: it is scrubbed and flipped to `RETAINED`,\n * so foreign keys from legally-retained financial rows keep resolving to an anonymized person\n * instead of dangling. What actually disappears is everything the subject owned that carries no\n * retention obligation — the profile with the name, the bio and the avatar file.\n *\n * ## Why an orchestrator is needed at all (the non-obvious part)\n *\n * The dependents are NOT torn down automatically. The `USERS → USER_PROFILES` cascade is\n * DELETE-driven — it fires from the parent's delete post-op logic — and an erasure never deletes\n * the subject. So without this method, `impersonalizeSubjectAsSystem` would scrub the user row and\n * leave the profile (the row that actually holds the personal data) fully intact, which is the\n * precise opposite of what the request asked for. This method fires each dependent's declared\n * teardown explicitly.\n *\n * ## Two halves, in this order\n *\n * 1. **Dependents** — every child-direction edge is classified\n * ({@link classifySubjectErasureDisposition}) and the ones that opted into a teardown are\n * dispatched through {@link dispatchLifecycleCascadeForRelationship} — THE shared\n * (strategy × mode) cascade dispatcher. No teardown logic is written here: the erasure reuses\n * the exact code path a parent delete would have taken, so the two triggers cannot drift on\n * what a `DELETE` or an `IMPERSONALIZE_AND_RETAIN` edge means.\n * 2. **The subject** — {@link impersonalizeRowsInPlace}, the shared scrub core (retention assert,\n * trusted-writer assert, scrub patch + markers in one write, treatment-driven file erasure).\n *\n * **Dependents first, deliberately.** If a teardown fails, the subject is left NOT yet marked\n * erased — which is both the safer intermediate state (nothing wears an \"erased\" label while its\n * personal data is still live) and the retryable one (a re-run re-discovers zero remaining\n * dependents and completes). The reverse order would freeze the subject as `RETAINED` — hidden and\n * immutable — while its dependents still held the personal data, and the retry could no longer\n * re-scrub the frozen row.\n *\n * ## Fail loud, BEFORE the first write\n *\n * Every edge is classified up front and the whole erasure is refused if ANY edge is\n * `UNCLASSIFIED` (an owned dependent nobody declared a teardown for) or `UNSUPPORTED_DEFERRED`\n * (a `mode: LAZY` edge that would defer personal-data removal to a queue). Classifying up front\n * rather than per-edge-as-we-go is what makes the refusal safe: an erasure that discovers an\n * unclassified edge halfway through would already have deleted rows, leaving a half-erased\n * subject no retry can reason about.\n *\n * ## Atomicity, and its exact limit\n *\n * The whole erasure runs inside ONE transaction on the SUBJECT's persistence adapter\n * ({@link executeResourceTransaction}, reusing an ambient transaction when the caller already\n * owns one). Dependents on a DIFFERENT adapter throw `CONFIGURATION` from the shared discovery\n * rather than silently committing outside that boundary — the same limit the parent-delete cascade\n * has always had.\n *\n * ⚠️ The one gap this inherits (it lives in the shared scrub core, not here): for a\n * PostgreSQL-backed resource, FILE metadata work runs against Mongo and therefore cannot join the\n * subject's SQL transaction. File erasure is deferred to the post-commit boundary there, so a\n * rolled-back erasure never destroys files, but a file erasure that fails AFTER commit is logged\n * rather than rolled back.\n *\n * ## v1 limitation — condition-gated edges are not activation-filtered\n *\n * A parent DELETE narrows its cascade with `filterRelationshipsByParent`, so an edge that is only\n * active for a particular parent VARIANT (a discriminated or condition-gated relationship) does not\n * fire for a parent it does not apply to. That filter needs the parent ROW, and an erasure takes\n * explicit ids rather than rows — deliberately, since resolving them would add a system READ grant\n * to the erasure's fail-closed surface. So v1 dispatches every enabled edge and lets FK discovery\n * find nothing on the inapplicable ones, which matches what the delete cascade itself does when no\n * snapshot is available. Harmless for a subject whose edges are unconditional (every `USERS` edge\n * is); a genuinely condition-gated subject wants the snapshot-based filter added here first.\n *\n * @param subjectResourceType - the erasure subject's resource type. MUST be the resource this\n * service instance is bound to (asserted) — the transaction is opened on ITS adapter, and the\n * child edges are read from ITS configuration.\n * @param subjectIds - the explicit subject rows to erase. An erasure is not a query.\n * @param executionContext - the privileged context the erasure runs under (synthesised by\n * {@link SystemAccessBackendService.eraseSubjectAsSystem}).\n * @param options - repository options; carries an ambient transaction when the caller owns one.\n * @returns the per-edge {@link SubjectErasureReport} — the compliance artifact of the request.\n */\n public async eraseSubjectInPlace(\n subjectResourceType: ResourceType,\n subjectIds: string[],\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<SubjectErasureReport> {\n // The transaction is opened on THIS service's adapter and the edges come from THIS service's\n // configuration, so a mismatched resourceType would silently erase against the wrong graph.\n if (subjectResourceType !== this.resourceConfiguration.resourceIdentifier) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message:\n `Subject erasure must run on the subject's own service instance: asked to erase ` +\n `\"${subjectResourceType}\" on the service bound to ` +\n `\"${this.resourceConfiguration.resourceIdentifier}\".`,\n subjectResourceType,\n boundResourceType: this.resourceConfiguration.resourceIdentifier,\n },\n }\n );\n }\n\n if (subjectIds.length === 0) {\n return {\n subjectResourceType,\n subjectIds: [],\n edges: [],\n subjectImpersonalized: false,\n externalEffects: [],\n };\n }\n\n // Fail-closed BEFORE any teardown: a subject that cannot be retained cannot be erased (there is\n // no retentionStatus marker to flip and no derived grant to flip it with). The shared core\n // asserts this too, but it runs LAST — checking here is what stops an erasure from deleting the\n // dependents and only then discovering it cannot retain the subject.\n if (!this.resourceConfiguration.retentionPolicy) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Subject erasure requires resource \"${subjectResourceType}\" to opt into ` +\n `retentionPolicy: the subject row is RETAINED (scrubbed and kept) rather than ` +\n `deleted, so that foreign keys from retained records still resolve to an anonymized ` +\n `subject. Without it there is no retentionStatus marker to flip.`,\n subjectResourceType,\n },\n }\n );\n }\n\n const childRelationships = getChildDirectionRelationships(\n this.resourceConfiguration.resourceRelationships,\n );\n\n // Classify EVERY edge before touching anything — see \"Fail loud, BEFORE the first write\".\n const classifications = childRelationships.map((relationship) => ({\n relationship,\n classification: classifySubjectErasureDisposition(relationship),\n }));\n\n const blocking = classifications\n .filter(({ classification }) => isBlockingSubjectErasureDisposition(classification.disposition));\n\n if (blocking.length > 0) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Subject erasure of \"${subjectResourceType}\" is REFUSED: ${blocking.length} of its ` +\n `dependent relationship(s) have no executable erasure disposition. Refusing rather ` +\n `than guessing — deleting could destroy data a retention obligation required ` +\n `keeping, and skipping could leave personal data behind while reporting the subject ` +\n `erased.`,\n subjectResourceType,\n unresolvedEdges: blocking.map(({ relationship, classification }) => ({\n childResourceType: classification.childResourceType,\n relationshipField: this.getNestedFieldName(relationship),\n disposition: classification.disposition,\n reason: classification.reason,\n })),\n },\n }\n );\n }\n\n this.logDebug('Executing subject erasure', {\n subjectResourceType,\n subjectCount: subjectIds.length,\n edgeCount: classifications.length,\n });\n\n return this.executeResourceTransaction(\n executionContext,\n async (optionsWithTransaction) => {\n const edges: SubjectErasureEdgeOutcome[] = [];\n\n for (const { relationship, classification } of classifications) {\n // EXHAUSTIVE on purpose, rather than an `is it one of the two executing members` test: a\n // future disposition added without an arm here becomes a TYPE error instead of an edge\n // that silently reports `executed: false` and leaves personal data behind.\n let executed = false;\n\n switch (classification.disposition) {\n case SubjectErasureDisposition.DELETE:\n case SubjectErasureDisposition.IMPERSONALIZE_AND_RETAIN: {\n // Route through THE shared (strategy × mode) dispatcher — the same one a parent delete\n // uses — so each edge gets its own declared teardown at its own declared depth, and a\n // future teardown strategy is honoured here for free.\n const lifecycleConfig = this.getResolvedLifecycleOnParentDelete(relationship)!;\n /**\n * Taken FROM the dispatcher, never assumed.\n *\n * This was `executed = true` unconditionally, which made the receipt claim a teardown for\n * an edge the cascade had declined — a child with no registered service or repository is\n * skipped, and skipping returns normally. `SubjectErasureReport` is the evidence that\n * answers \"was this subject's data removed?\", so an overstatement here is a compliance\n * defect, not a logging inaccuracy.\n */\n executed = await this.dispatchLifecycleCascadeForRelationship(\n relationship,\n subjectIds,\n executionContext,\n 0, // currentDepth — top of the cascade\n lifecycleConfig.maxDepth || 1,\n new Set(), // per-edge visited set, matching executeLifecycleOperations\n optionsWithTransaction,\n );\n if (!executed) {\n // LOUD: the disposition says this edge should have been torn down and it was not, so\n // the subject's data is partly still live. The skip itself is warned deeper down with\n // the missing registration named; this says what it MEANS for the erasure.\n this.logger.error('Subject erasure did NOT tear down a declared edge', {\n subjectResourceType,\n childResourceType: classification.childResourceType,\n disposition: classification.disposition,\n reason: 'the cascade declined the edge — see the preceding warning for the missing registration',\n });\n }\n break;\n }\n\n case SubjectErasureDisposition.RETAINED_BY_DECLARATION:\n case SubjectErasureDisposition.NOT_OWNED:\n // Deliberately untouched — the rows are not discovered at all, so the erasure cannot\n // accidentally act on them.\n break;\n\n case SubjectErasureDisposition.UNCLASSIFIED:\n case SubjectErasureDisposition.UNSUPPORTED_DEFERRED:\n default: {\n // Unreachable: the pre-flight refusal rejects every blocking disposition before the\n // transaction opens. Kept as defence-in-depth so a future edit that weakens that\n // pre-flight fails loudly here instead of silently skipping an edge — and so the\n // `never` binding makes an unhandled new member a compile error.\n const unexecutableDisposition: never = classification.disposition as never;\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message:\n `Subject erasure reached the teardown loop with a non-executable disposition ` +\n `'${String(unexecutableDisposition)}' — the pre-flight classification refusal ` +\n `should have rejected it. Refusing to continue (fail-closed).`,\n subjectResourceType,\n childResourceType: classification.childResourceType,\n relationshipField: this.getNestedFieldName(relationship),\n },\n }\n );\n }\n }\n\n edges.push({ ...classification, executed });\n }\n\n // The subject LAST: dependents are gone (or retained by declaration), so flipping the\n // subject to RETAINED now is the final, irreversible step of the erasure.\n const subjectSessionRevocation = await this.impersonalizeRowsInPlace(\n subjectResourceType,\n subjectIds,\n executionContext,\n optionsWithTransaction,\n { erasureSubject: true },\n );\n\n const report: SubjectErasureReport = {\n subjectResourceType,\n subjectIds,\n edges,\n subjectImpersonalized: true,\n // Whose sessions this erasure ended — a LOCAL fence write applied at the scrub chokepoint,\n // so it is evidenced here rather than among the external effects.\n sessionRevocation: {\n principalUserIds: subjectSessionRevocation.principalUserIds,\n lookupFailed: subjectSessionRevocation.lookupFailed,\n },\n // Populated by the caller AFTER this transaction commits — external effects cannot join a\n // database transaction, so running them here would either hold the transaction open across\n // a third-party network call or let a rollback undo local rows whose provider-side\n // counterpart was already erased. See `eraseSubjectAsSystem`.\n externalEffects: [],\n };\n\n // The erasure is a compliance event: record what was torn down, what was retained, and the\n // configuration that justified each, so a data-protection response never has to be\n // reconstructed from the resource graph months later.\n this.logger.info('Subject erasure completed', {\n subjectResourceType,\n subjectCount: subjectIds.length,\n edges: edges.map((edge) => ({\n childResourceType: edge.childResourceType,\n disposition: edge.disposition,\n executed: edge.executed,\n })),\n });\n\n return report;\n },\n options,\n );\n }\n\n /**\n * Queue child resources for async deletion (eventual consistency).\n *\n * LAZY mode provides eventual consistency by queuing deletion operations\n * for asynchronous processing. This improves performance for bulk deletions\n * but requires a queue system to be implemented.\n *\n * Current implementation: Placeholder that throws NOT_IMPLEMENTED error.\n *\n * Future implementation (Phase 6.1-6.2):\n * When the queue system is implemented, this method should:\n * 1. Get the DELETE operation for the child resource type\n * 2. Use `operation.internalDto` for serializing queue payloads\n * - `internalDto` includes `isBackendOnly` fields needed for backend-to-backend communication\n * - Date coercion is already applied in `internalDto`\n * 3. Serialize resource data using `operation.internalDto.parse()` for validation\n * 4. Enqueue job with validated payload\n *\n * Example (when queue system is ready):\n * ```typescript\n * const childResourceConfig = this.resourcesRegistry.resourceConfigurations[relationship.resourceType2];\n * const deleteOperation = childResourceConfig.operations.find(\n * op => op.operationIdentifier === CoreResourceOperation.DELETE\n * );\n * if (!deleteOperation?.internalDto) {\n * throw new Error('DELETE operation or internalDto not found');\n * }\n *\n * // Validate and serialize using internalDto\n * const queuePayload = {\n * resourceType: relationship.resourceType2,\n * operationIdentifier: CoreResourceOperation.DELETE,\n * data: deleteOperation.internalDto.parse({ _id: childId, ...otherFields }),\n * executionContext: { ... },\n * };\n *\n * await this.queueService.enqueueResourceOperation(deleteOperation, queuePayload.data, executionContext);\n * ```\n *\n * @see Phase 6.1 - Use internalDto for Queue Payloads\n * @see Phase 6.2 - Validate Queue Payloads Against internalDto\n */\n /**\n * Assemble everything the framework holds about ONE data subject — the disclosure counterpart of\n * {@link eraseSubjectInPlace}.\n *\n * ## What it walks, and why that is not the erasure walk\n *\n * Both traverse the subject's child-direction edges through the same shared authority, so they can\n * never disagree about what an edge SAYS. They disagree about what it MEANS:\n * {@link classifySubjectExportDisposition} additionally includes edges the erasure calls\n * `NOT_OWNED` when the far side holds a foreign key back to the subject — an audit log or a\n * membership is not the subject's to delete, but Art. 15 covers \"all personal data concerning him\n * or her\" and must disclose it. That divergence is real on the shipped graph, not hypothetical.\n *\n * ## Two fail-loud gates, BOTH before the first read\n *\n * 1. **Authorization** — every resource whose rows would enter the bundle must declare\n * `systemAccessPolicy.exportSubject = ALLOWED`. Missing opt-ins REFUSE the export and are\n * named. Skipping them instead would emit a bundle that is incomplete without saying so,\n * which is the same class of lie as the routed export operations this capability replaced.\n * 2. **Art. 20 provenance** — for `PORTABILITY_ART_20` only, every field of every included\n * resource must resolve a provenance (its own `.portabilityProvenance()` or its resource's\n * `portabilityPolicy.defaultProvenance`). Undeclared fields REFUSE, because neither guess is\n * conservative: excluding under-delivers a legal right, including over-shares\n * controller-derived data. `ACCESS_ART_15` skips this gate entirely — access discloses\n * everything regardless of provenance, so an application can answer access requests before\n * annotating anything.\n *\n * Gating up front rather than per-edge-as-we-go is what makes the refusal safe: a half-assembled\n * bundle that discovered an ungranted resource at edge seven has already read six resources' worth\n * of personal data into memory for a request that will not complete.\n *\n * ## No transaction, deliberately\n *\n * Unlike the erasure this writes nothing, so there is nothing to roll back and no cross-adapter\n * atomicity limit: dependents on a different persistence adapter are simply a second query. A\n * subject export is a point-in-time snapshot and does not claim otherwise.\n *\n * @param subjectResourceType the subject's resource type. MUST be the resource this service\n * instance is bound to (asserted) — the edges come from ITS configuration.\n * @param subjectIds the explicit subject rows to export. An export is not a query.\n * @param purpose WHICH right is being answered. Drives edge inclusion AND field narrowing.\n * @param executionContext the privileged context (synthesised by `exportSubjectAsSystem`).\n * @returns the {@link SubjectExportBundle} — the personal data, paired with the report that\n * justifies its shape. Only the report is safe to log.\n */\n public async exportSubjectInPlace(\n subjectResourceType: ResourceType,\n subjectIds: string[],\n purpose: SubjectExportPurpose,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<SubjectExportBundle> {\n // The edges come from THIS service's configuration, so a mismatched resourceType would silently\n // export against the wrong graph — the disclosure analogue of erasing the wrong one.\n if (subjectResourceType !== this.resourceConfiguration.resourceIdentifier) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message:\n `Subject export must run on the subject's own service instance: asked to export ` +\n `\"${subjectResourceType}\" on the service bound to ` +\n `\"${this.resourceConfiguration.resourceIdentifier}\".`,\n subjectResourceType,\n boundResourceType: this.resourceConfiguration.resourceIdentifier,\n },\n }\n );\n }\n\n const emptyReport = (): SubjectExportBundle => ({\n report: {\n purpose,\n subjectResourceType,\n subjectIds: [],\n edges: [],\n fieldsExcludedAsDerived: [],\n fieldsWithheldAsNonDisclosable: [],\n totalRecordCount: 0,\n },\n slices: [],\n });\n\n if (subjectIds.length === 0) {\n return emptyReport();\n }\n\n const classifications = enumerateSubjectExportRelationshipTraversals(\n subjectResourceType,\n this.resourceConfiguration.resourceRelationships,\n purpose,\n );\n\n // The subject's OWN resource is always in the bundle — it is the thing being disclosed — so it\n // joins the included set for both gates below rather than being special-cased past them.\n const includedResourceTypes: ResourceType[] = [\n subjectResourceType,\n ...classifications\n .filter(({ classification }) => isIncludedSubjectExportEdgeDisposition(classification.disposition))\n .map(({ classification }) => classification.relatedResourceType),\n ];\n\n const nonDisclosableResourceTypes = this.resolveSubjectExportDisclosureBlocks(\n includedResourceTypes,\n purpose,\n executionContext,\n );\n const disclosableResourceTypes = includedResourceTypes\n .filter((resourceType) => !nonDisclosableResourceTypes.has(resourceType));\n // FORBIDDEN resources are excluded from the provenance walk too: their rows are never read, so\n // demanding an Art. 20 declaration for their fields would refuse an export over data that was\n // never going to be disclosed.\n const { derived: fieldsExcludedAsDerived, withheld: fieldsWithheldAsNonDisclosable } =\n this.resolveSubjectExportFieldExclusions(disclosableResourceTypes, purpose, executionContext);\n // One list for the narrowing: both are \"remove this path from the rows\". They stay SEPARATE on\n // the report because the reasons differ — one is an Art. 20 scope decision the subject can\n // challenge, the other a security floor they cannot.\n const allRemovedFieldPaths = [...fieldsExcludedAsDerived, ...fieldsWithheldAsNonDisclosable];\n\n this.logDebug('Executing subject export', {\n subjectResourceType,\n purpose,\n subjectCount: subjectIds.length,\n edgeCount: classifications.length,\n includedResourceCount: includedResourceTypes.length,\n });\n\n const slices: SubjectExportResourceSlice[] = [];\n const edges: SubjectExportEdgeOutcome[] = [];\n\n // The subject's own rows first — a bundle whose edges resolved but whose subject did not would\n // be a disclosure about a person the report cannot name.\n const subjectRows = await this.readSubjectExportRows(\n subjectResourceType,\n { _id: { $in: subjectIds } },\n executionContext,\n options,\n );\n const narrowedSubjectRows = this.narrowRowsToExportScope(\n subjectResourceType,\n subjectRows,\n allRemovedFieldPaths,\n );\n if (narrowedSubjectRows.length > 0) {\n slices.push({ resourceType: subjectResourceType, rows: narrowedSubjectRows });\n }\n let totalRecordCount = narrowedSubjectRows.length;\n\n for (const { relationship, classification } of classifications) {\n if (\n isIncludedSubjectExportEdgeDisposition(classification.disposition)\n && nonDisclosableResourceTypes.has(classification.relatedResourceType)\n ) {\n // The right covers these rows; the declaration says they may never be handed over. Recorded\n // with the OVERRIDDEN disposition so the report states the real reason — \"we are not allowed\n // to disclose this\" is a different answer from \"this is not your data\".\n edges.push({\n ...classification,\n disposition: SubjectExportEdgeDisposition.EXCLUDED_NOT_DISCLOSABLE,\n reason:\n `${String(classification.relatedResourceType)} declares systemAccessPolicy.exportSubject `\n + `= FORBIDDEN: these rows concern the subject but are declared never-disclosable, so the `\n + `bundle leaves them out rather than refusing the whole export`,\n collected: false,\n recordCount: 0,\n });\n continue;\n }\n\n if (!isIncludedSubjectExportEdgeDisposition(classification.disposition)) {\n // Recorded, not skipped. \"Why is this missing from my export?\" must have an answer carrying\n // the configuration that produced it — that record IS the compliance artifact.\n edges.push({ ...classification, collected: false, recordCount: 0 });\n continue;\n }\n\n const foreignKeyField = this.getFKFieldForRelationship(relationship);\n const rows = await this.readSubjectExportRows(\n classification.relatedResourceType,\n { [foreignKeyField]: { $in: subjectIds } },\n executionContext,\n options,\n );\n const narrowed = this.narrowRowsToExportScope(\n classification.relatedResourceType,\n rows,\n allRemovedFieldPaths,\n );\n\n if (narrowed.length > 0) {\n slices.push({ resourceType: classification.relatedResourceType, rows: narrowed });\n }\n // `collected: true` with `recordCount: 0` is a meaningful, distinct state: the edge WAS read\n // and the subject simply had no rows there. Collapsing it into `collected: false` would make\n // \"we looked and found nothing\" indistinguishable from \"we never looked\".\n edges.push({ ...classification, collected: true, recordCount: narrowed.length });\n totalRecordCount += narrowed.length;\n }\n\n return {\n report: {\n purpose,\n subjectResourceType,\n subjectIds,\n edges,\n fieldsExcludedAsDerived,\n fieldsWithheldAsNonDisclosable,\n totalRecordCount,\n },\n slices,\n };\n }\n\n /**\n * Gate 1 — resolve which resources may be disclosed, refusing on the ones nobody has decided.\n *\n * Fail-closed by omission: a resource with NO declaration REFUSES the export, naming every\n * offender at once so the fix is one pass rather than a discover-one-per-run loop.\n *\n * A resource declared FORBIDDEN is NOT a refusal — it is returned so the caller can leave its\n * edge out and record the omission. Refusing on it would turn a legitimate decision into\n * permanent sabotage: a `USERS` access export whose graph touches a credential store could never\n * run again, whatever else opted in. The one exception is the SUBJECT'S OWN resource, which\n * cannot be \"left out\" of its own export.\n *\n * @returns the FORBIDDEN resource types, for the caller to exclude and report.\n */\n private resolveSubjectExportDisclosureBlocks(\n includedResourceTypes: ResourceType[],\n purpose: SubjectExportPurpose,\n executionContext: ExecutionContext<any>,\n ): ReadonlySet<ResourceType> {\n // TWO different refusals, kept apart on purpose. `FORBIDDEN` is a decision someone TOOK — this\n // resource must never reach a data subject — and it is NOT fixed by opting in. An absent\n // declaration is a decision nobody has taken yet, and opting in IS the fix. Collapsing them\n // would invite a reviewer to \"resolve\" a deliberate exclusion (a credentials store, say) by\n // treating it as an oversight, which is precisely how a security decision gets quietly undone.\n const forbidden: ResourceType[] = [];\n const undeclared: ResourceType[] = [];\n\n for (const resourceType of [...new Set(includedResourceTypes)]) {\n const mode = this.resourcesRegistry.getResourceConfiguration(resourceType)\n ?.systemAccessPolicy?.exportSubject;\n if (mode === ResourceSystemAccessMode.ALLOWED) continue;\n (mode === ResourceSystemAccessMode.FORBIDDEN ? forbidden : undeclared).push(resourceType);\n }\n\n // The SUBJECT'S OWN resource being FORBIDDEN is not an excludable edge — it is the thing being\n // exported. Returning an edges-only bundle would be a disclosure that omits its own subject.\n const subjectResourceType = includedResourceTypes[0]!;\n if (forbidden.includes(subjectResourceType)) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Subject export (${purpose}) is REFUSED: the subject's own resource ` +\n `\"${String(subjectResourceType)}\" declares systemAccessPolicy.exportSubject = FORBIDDEN. ` +\n `A resource that may never be disclosed cannot be an export subject — this is not an ` +\n `edge that can be left out.`,\n purpose,\n subjectResourceType,\n },\n }\n );\n }\n\n if (undeclared.length > 0) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Subject export (${purpose}) is REFUSED: ${undeclared.length} resource(s) that would ` +\n `enter the bundle carry NO disclosure declaration — ${undeclared.join(', ')}. Declare ` +\n `systemAccessPolicy.exportSubject = ResourceSystemAccessMode.ALLOWED on each, or ` +\n `FORBIDDEN to state that they must never be disclosed (FORBIDDEN resources are left ` +\n `OUT of the bundle and recorded, not refused). Refusing rather than skipping an ` +\n `undeclared resource — an export missing one without saying so is an incomplete ` +\n `disclosure presented as a complete one.`,\n purpose,\n undeclaredResourceTypes: undeclared,\n },\n }\n );\n }\n\n return new Set(forbidden);\n }\n\n /**\n * Gate 2 — resolve which fields Art. 20 excludes as controller-derived, refusing on any field\n * whose provenance nobody declared.\n *\n * Returns `resourceType.fieldName` locators for the excluded fields. Empty for\n * `ACCESS_ART_15`, which discloses every field regardless of provenance — that asymmetry is what\n * lets an application answer access requests before annotating a single resource.\n */\n private resolveSubjectExportFieldExclusions(\n includedResourceTypes: ResourceType[],\n purpose: SubjectExportPurpose,\n executionContext: ExecutionContext<any>,\n ): { derived: string[]; withheld: string[] } {\n const excluded: string[] = [];\n const undeclared: string[] = [];\n const withheld: string[] = [];\n\n for (const resourceType of [...new Set(includedResourceTypes)]) {\n const config = this.resourcesRegistry.getResourceConfiguration(resourceType);\n const decisions = compileSubjectExportFieldDecisions({\n resourceType,\n mainSchema: config?.mainSchema,\n defaultProvenance: config?.portabilityPolicy?.defaultProvenance,\n purpose,\n });\n for (const decision of decisions) {\n if (decision.basis === SubjectExportFieldDecisionBasis.WITHHELD_NON_DISCLOSABLE) withheld.push(decision.locator);\n else if (decision.scope === SubjectExportFieldScope.UNDECLARED) undeclared.push(decision.locator);\n else if (decision.scope === SubjectExportFieldScope.EXCLUDED_DERIVED) excluded.push(decision.locator);\n }\n }\n\n // The non-disclosable sweep runs for BOTH rights — a password hash is no more disclosable under\n // Art. 15 than under Art. 20 — but the Art. 20 provenance REFUSAL is portability-only, since\n // access never consults provenance.\n if (purpose === SubjectExportPurpose.ACCESS_ART_15) {\n return { derived: [], withheld };\n }\n\n if (undeclared.length > 0) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Portability export (Art. 20) is REFUSED: ${undeclared.length} field(s) declare no ` +\n `data provenance, so it cannot be decided whether the subject provided them. ` +\n `Declare portabilityPolicy.defaultProvenance on the resource, or ` +\n `.portabilityProvenance() on the field. Refusing rather than guessing — excluding ` +\n `them would under-deliver the subject's right, including them would over-share ` +\n `controller-derived data, and neither is the conservative choice. An ACCESS ` +\n `(Art. 15) export is unaffected and can run today.`,\n undeclaredFields: undeclared,\n },\n }\n );\n }\n\n return { derived: excluded, withheld };\n }\n\n /**\n * Return a deep copy of `value` with every `path` removed, without mutating the source row.\n *\n * Non-mutating on purpose: the rows come from a repository read and may be shared with a cache or\n * another consumer, so stripping in place could delete a derived field from someone else's view\n * of the same document.\n */\n private omitPathsFromValue(value: unknown, paths: string[][]): unknown {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return value;\n\n const source = value as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n\n for (const [key, fieldValue] of Object.entries(source)) {\n const matching = paths.filter((path) => path[0] === key);\n // An exact match at this level removes the field outright.\n if (matching.some((path) => path.length === 1)) continue;\n\n result[key] = matching.length > 0\n ? this.omitPathsFromValue(fieldValue, matching.map((path) => path.slice(1)))\n : fieldValue;\n }\n\n return result;\n }\n\n /** Read the rows of one resource participating in an export, through its own service instance. */\n private async readSubjectExportRows(\n resourceType: ResourceType,\n filter: Record<string, unknown>,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<Record<string, unknown>[]> {\n const repository = this.repositoriesRegistry.getRepository(resourceType);\n // LIST, not READ. `read(executionContext, filter)` resolves to a SINGLE document, so using it\n // here would silently cap every edge at one row — an export that looks successful while\n // disclosing a fraction of what it claims. The cascade discovery makes the same distinction.\n //\n // `listForInternalScan`, not the public `list`: an export participant only needs\n // `systemAccessPolicy.exportSubject` — nothing requires it to expose a user-facing default\n // LIST, and per-owner singletons (e.g. `userLifecycleState`, which declares\n // `exportSubject: ALLOWED` and READ/SEARCH/UPDATE/CREATE/DELETE but NO LIST) made this\n // throw `repository_resource_operation_failed` and 500 the whole subject export (found\n // while fixing the same wrong-door call in the dormancy batch, wildo-ai/wildo-ai#34).\n // Semantics are preserved where it already worked: a declared LIST is reused verbatim\n // (hooks included), and the synthetic no-LIST scan still runs through `_doList` →\n // `buildContextualFilter`, so the retention row-hide keeps applying — an erased subject's\n // hidden rows stay hidden (\"subject export does not set see-through\").\n const rows = await repository.listForInternalScan(executionContext, filter as any, options);\n return Array.isArray(rows) ? (rows as Record<string, unknown>[]) : [];\n }\n\n /**\n * Drop the fields Art. 20 excluded from a resource's rows.\n *\n * Operates on the resolved exclusion list rather than re-deriving per row: the decision is a\n * property of the SCHEMA, so re-asking it per row would be both wasteful and a chance for two rows\n * of the same resource to disagree.\n */\n private narrowRowsToExportScope(\n resourceType: ResourceType,\n rows: Record<string, unknown>[],\n removedFieldPaths: string[],\n ): Record<string, unknown>[] {\n const prefix = `${String(resourceType)}.`;\n const excludedPaths = removedFieldPaths\n .filter((locator) => locator.startsWith(prefix))\n .map((locator) => locator.slice(prefix.length).split('.'));\n if (excludedPaths.length === 0) return rows;\n\n return rows.map((row) => this.omitPathsFromValue(row, excludedPaths) as Record<string, unknown>);\n }\n\n private async queueChildDeletion(\n relationship: ResourceRelationship,\n parentIds: string[],\n executionContext: ExecutionContext<any>\n ): Promise<boolean> {\n // rag-removal-gate: N/A — LAZY cascade deletion is UNIMPLEMENTED (this method only throws).\n // Whoever implements it inherits the chunk-removal obligation: the deferred teardown must call\n // runRagChunkRemovalForDeletedRows for the child rows it eventually deletes, exactly as\n // deleteChildrenImmediate does — a queued delete that skips it strands the children's chunks\n // until the backstop sweep.\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'LAZY cascade mode requires queue system integration. Queue system implementation pending. See Phase 6.1-6.2 for implementation details.',\n relationship: relationship.resourceType2,\n parentIds,\n },\n });\n }\n\n /**\n * Execute additional post-operation logic (non-cascading)\n */\n private async executeAdditionalPostOperationLogic(\n operation: CoreResourceOperation,\n result: any,\n executionContext: ExecutionContext<any>,\n currentState?: any,\n options?: RepositoryOptions,\n ): Promise<void> {\n\n this.logDebug('Executing additional post-operation logic', { operation });\n\n // Dispatch post-operation hooks registered on this resource type\n const resourceType = this.resourceConfiguration.resourceIdentifier as string;\n const dispatch = async (): Promise<void> => {\n await this.servicesRegistry.dispatchPostOperationHooks(\n resourceType,\n operation,\n result,\n executionContext,\n );\n };\n if (options?.transaction) {\n const transaction = options.transaction;\n registerTransactionPostCommitEffect(transaction, {\n key: [\n 'resource-post-operation-hooks',\n resourceType,\n String(operation),\n String((result as { _id?: unknown } | null)?._id ?? 'no-id'),\n transaction.id,\n options.frameworkPostCommitEffectOccurrenceId ?? randomUUID(),\n ].join(':'),\n execute: dispatch,\n });\n return;\n }\n await dispatch();\n }\n\n /**\n * Enrich business context\n */\n private async enrichBusinessContext(\n operation: CoreResourceOperation,\n data: any,\n executionContext: ExecutionContext<any>\n ): Promise<any> {\n\n // Implement business context enrichment here\n // This could include:\n // - Adding computed fields\n // - Loading related resources\n // - Adding user-specific data\n // - Permission-based filtering\n\n return data; // Default: pass through\n }\n\n /**\n * Apply business filter\n */\n private async applyBusinessFilter(\n filter: FilterQuery<any>,\n executionContext: ExecutionContext<any>\n ): Promise<FilterQuery<any>> {\n\n // Implement business filtering logic here\n // This could include:\n // - User permission-based filtering\n // - Organization scope filtering\n // - Security filtering\n\n return filter; // Default: pass through\n }\n\n /**\n * Enhance search query with business logic\n */\n private async enhanceSearchQuery(\n searchQuery: string,\n executionContext: ExecutionContext<any>\n ): Promise<string> {\n\n // Implement search enhancement logic here\n // This could include:\n // - Query expansion\n // - Synonym handling\n // - Permission-based query modification\n\n return searchQuery; // Default: pass through\n }\n\n /**\n * Validate deletion constraints\n */\n private async validateDeletionConstraints(\n data: any,\n executionContext: ExecutionContext<any>\n ): Promise<void> {\n\n // Implement deletion constraint validation here\n // This could include:\n // - Dependency checking\n // - Business rule validation\n // - Permission validation\n\n // Default: allow deletion\n }\n\n // ================================\n // Notification Methods\n // ================================\n\n /**\n * Dispatch notifications (email, badge, WebSocket, M2M) based on operation configuration.\n *\n * Reads ALL notification config from `executionContext.operation` — which is guaranteed\n * to be the correct (possibly variant-resolved) operation thanks to Correction Points\n * 1 and 2 in `doOperation()`. The NotificationDispatcherService also reads\n * `executionContext.operation` extensively (15+ reads across its sub-methods).\n */\n private async dispatchNotifications(\n executionContext: ExecutionContext<any>,\n inputData: any,\n currentResult: any,\n tokenGenerationResult?: TokenGenerationResult | null,\n previousState?: unknown,\n ): Promise<void> {\n await dispatchPostOperationNotificationsBestEffort(\n {\n notificationDispatcher: this.notificationDispatcher,\n populationService: this.populationService,\n logger: this.logger,\n logDebug: this.logDebug,\n },\n executionContext,\n inputData,\n currentResult,\n tokenGenerationResult,\n previousState,\n );\n }\n\n // ================================\n // Helper Methods\n // ================================\n\n\n}\n"]}
|
|
1
|
+
{"version":3,"file":"services-registry-handler.backend.service.js","sourceRoot":"","sources":["../../../../../../src/base-classes/services/services/services-registry-handler.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,kBAAkB,CAAC;AAC1B,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAOzD,OAAO,EAEL,qBAAqB,EACrB,gBAAgB,EAChB,4BAA4B,EAC5B,0BAA0B,EAC1B,+BAA+B,EAE/B,kBAAkB,EAClB,0BAA0B,EAC1B,kCAAkC,EAClC,SAAS,EACT,2BAA2B,EAC3B,4BAA4B,EAC5B,0BAA0B,EAC1B,uBAAuB,EAEvB,QAAQ,EACR,qBAAqB,EACrB,kBAAkB,EAClB,sBAAsB,EACtB,4BAA4B,EAC5B,yBAAyB,EACzB,iCAAiC,EACjC,mCAAmC,EACnC,oBAAoB,EACpB,4BAA4B,EAC5B,uBAAuB,EACvB,+BAA+B,EAC/B,kCAAkC,EAClC,4CAA4C,EAC5C,sCAAsC,EACtC,wBAAwB,EACxB,oCAAoC,EAGpC,8BAA8B,EAC9B,wBAAwB,EACxB,mBAAmB,EACnB,qBAAqB,EAErB,8BAA8B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ACT,gBAAuC;QAGvC,gDAAgD;QAChD,sBAAsB;QACtB,wBAAwB;QACxB,6BAA6B;QAC7B,0BAA0B;QAE1B,0BAA0B;IAC5B,CAAC;IAED,mCAAmC;IACnC,uBAAuB;IACvB,mCAAmC;IAEnC;;;;;;;OAOG;IACK,KAAK,CAAC,qBAAqB,CACjC,gBAAuC,EACvC,SAAc,EACd,aAAkB,EAClB,qBAAoD,EACpD,aAAuB;QAEvB,MAAM,4CAA4C,CAChD;YACE,sBAAsB,EAAE,IAAI,CAAC,sBAAsB;YACnD,iBAAiB,EAAE,IAAI,CAAC,iBAAiB;YACzC,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,QAAQ,EAAE,IAAI,CAAC,QAAQ;SACxB,EACD,gBAAgB,EAChB,SAAS,EACT,aAAa,EACb,qBAAqB,EACrB,aAAa,CACd,CAAC;IACJ,CAAC","sourcesContent":["import 'reflect-metadata';\nimport { randomUUID } from 'node:crypto';\nimport { injectable, inject, optional } from 'inversify';\nimport type {\n ResourceConfiguration,\n ResourceConfiguration_Operation,\n ResourceConfiguration_OperationPath,\n ResourceDataSubjectPolicy,\n} from '@wildo-ai/saas-models';\nimport {\n ResourceType,\n CoreResourceOperation,\n CoreResourceType,\n readBulkOperationSelectorIds,\n stripBulkOperationSelector,\n composeDefaultOperationResponse,\n DEFAULT_PERSISTENCE_ADAPTER,\n PersistenceAdapter,\n selectByPersistenceAdapter,\n ResourcesConfig_OperationPathUtils,\n ErrorType,\n ErrorCustomMessageReference,\n ResourceOperationVariantType,\n ResourceOperationRiskLevel,\n ResourceOperationsUtils,\n createOrUpdateMandatoryDiscardFields,\n DataMode,\n OPERATION_VARIANT_KEY,\n ChildLifecycleMode,\n ChildLifecycleStrategy,\n buildImpersonalizeScrubPatch,\n SubjectErasureDisposition,\n classifySubjectErasureDisposition,\n isBlockingSubjectErasureDisposition,\n SubjectExportPurpose,\n SubjectExportEdgeDisposition,\n SubjectExportFieldScope,\n SubjectExportFieldDecisionBasis,\n compileSubjectExportFieldDecisions,\n enumerateSubjectExportRelationshipTraversals,\n isIncludedSubjectExportEdgeDisposition,\n ResourceSystemAccessMode,\n ResourceOperation_ServiceRuntimeMode,\n ResourceConfiguration_OperationVariant_CustomImplementation_FunctionParameters,\n ResourceSerializationUtils,\n ExecutionContext_ExecutionType,\n CoreConsumableTokenTypes,\n isWildoBackendError,\n Resources_SharedUtils,\n type PersistenceAdapterType,\n ResourceRelationshipBulkAction,\n type ResourceRelationshipBulkActionRequest,\n ResourceRelationshipBulkActionRequestSchema,\n type ResourceRelationshipBulkActionResult,\n type ResourceRelationshipBulkOperationSelector,\n ResourceRelationshipBulkClearOperationRequestSchema,\n type ResourceRelationshipBulkClearOperationRequest,\n ResourceRelationshipBulkCreateOperationRequestSchema,\n type ResourceRelationshipBulkCreateOperationRequest,\n ResourceRelationshipBulkLinkOperationRequestSchema,\n type ResourceRelationshipBulkLinkOperationRequest,\n ResourceRelationshipBulkReplaceOperationRequestSchema,\n type ResourceRelationshipBulkReplaceOperationRequest,\n ResourceRelationshipBulkSetOperationRequestSchema,\n type ResourceRelationshipBulkSetOperationRequest,\n ResourceRelationshipBulkUnlinkOperationRequestSchema,\n type ResourceRelationshipBulkUnlinkOperationRequest,\n ResourceGeneratedOperationKind,\n ResourceDataSubjectKind,\n} from '@wildo-ai/saas-models';\nimport { EnumLikeType, getZodObjectShape, isAuditEvidenceField, isZodObject, unwrapSchema } from '@wildo-ai/zod-decorators';\nimport { isWriteIntegrityExemptExecution } from '~wildo-backend-lib/base-classes/services/repositories/resource-write-integrity.backend';\nimport { collectCandidateReadOnlyFields, filterChangedReadOnlyFields, stringifyPersistedValueForCompare } from '~wildo-backend-lib/base-classes/services/services/read-only-field-change.backend.utils';\nimport { AuditLogsBackendService } from '~wildo-backend-lib/compliance/audit-trails/services/audit-logs.backend.service';\nimport {\n resolveResourceOperationAuditDecision,\n resolveResourceOperationFieldEffect,\n} from '~wildo-backend-lib/base-classes/services/services/resource-operation-audit-emission.backend.utils';\nimport { resolveServerInjectedFieldAllowList } from '~wildo-backend-lib/base-classes/services/services/resource-operation-server-injected-fields.backend.utils';\nimport { buildRetentionMarkerStampPatch } from '~wildo-backend-lib/compliance/privacy/retention-hide-predicate.backend';\nimport { SAAS_SERVICE_TYPES } from '~wildo-backend-lib/inject/models/service-types';\nimport type { SubjectSessionRevocationBackendService } from '~wildo-backend-lib/compliance/privacy/services/subject-session-revocation.backend.service';\nimport { ExecutionContext } from '~wildo-backend-lib/runtime/models/execution-context.backend.schemas';\nimport { RepositoriesRegistryHandlerBackendService } from '~wildo-backend-lib/base-classes/services/repositories/repositories-registry-handler.backend.service';\nimport { ResourceOperationHelperBackendService } from '~wildo-backend-lib/base-classes/services/resource-operations-helper.backend.service';\nimport { RepositoryOptions, ServiceOptions, IdOrIdsOrFilterType } from '~wildo-backend-lib/base-classes/models/repositories.backend.schemas';\nimport {\n Resources_PaginationRequest,\n Resources_PaginatedResult,\n extractFunctionContextNeeds,\n ResourceConfiguration_FunctionWithContextNeeds,\n ResourcesConfigOperationsDtosBuilderUtils,\n} from '@wildo-ai/saas-models';\nimport { LoggerService } from '~wildo-backend-lib/monitoring/logger/services/logger.service';\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 { z } from 'zod';\nimport { PlatformMutualizedHandlerBackendService } from '~wildo-backend-lib/requests/service/platform-mutualized-handler.backend.service';\nimport { ResourcesRegistryBackendService } from '~wildo-backend-lib/resources/services/resources-registry.backend.service';\nimport { ExternalApiHandlerBackendService } from '~wildo-backend-lib/external-providers/services/external-api-handler.backend.service';\nimport {\n ResourceOperationCustomImplementationRegistryBackendService,\n type ResourceOperationCustomImplementationRegistration,\n} from './resource-operation-custom-implementation-registry.backend.service';\nimport {\n createResourceWritePersistenceRequest,\n resolveResourceOperationTransactionPersistenceContract,\n ResourceWriteFileParticipation,\n type ResourceOperationTransactionPersistenceContract,\n} from './resource-operation-transaction-persistence.backend.utils';\nimport {\n ResourceCustomServiceImplementationTransactionalCoreConflictAction,\n type ResourceCustomServiceImplementationTransactionalCoreConflictResolution,\n type ResourceCustomServiceImplementationTransactionalCoreConflictResolver,\n} from './resource-operation-custom-implementation.factory.backend';\nimport { ServerlessServicesHandlerBackendService } from '~wildo-backend-lib/requests/service/serverless-services-handler.backend.service';\nimport { ResourceOperation_CustomServiceImplementationMode } from '@wildo-ai/saas-models';\nimport { ResourceOperation_CustomImplementation_Utils } from './resource-operation-custom-implementation-base.backend.service';\nimport {\n NotificationDispatcherService,\n type NotificationDispatchOptions,\n} from '~wildo-backend-lib/notifications/services/notifications-dispatcher.backend.service';\nimport {\n type ComputationContext,\n ComputationContextFailureMode,\n ResourcePopulationBackendService,\n} from '~wildo-backend-lib/resources/services/resource-population.backend.service';\nimport { VirtualFieldsBackendService } from '~wildo-backend-lib/resources/services/virtual-fields.backend.service';\nimport { MongoDBService } from '~wildo-backend-lib/databases/services/mongodb.service';\nimport { PostgreSQLDatabaseBackendService } from '~wildo-backend-lib/databases/services/postgresql-database.backend.service';\nimport {\n resolveDefaultPersistenceAdapter,\n resolvePersistenceAdapterForConfiguration,\n} from '~wildo-backend-lib/databases/models/resolve-persistence-adapter.backend.utils';\nimport type {\n ResourcePersistenceUnitOfWorkBackendService,\n} from '~wildo-backend-lib/databases/services/resource-persistence-unit-of-work.backend.service';\nimport {\n registerTransactionPostCommitEffect,\n type IDatabaseService,\n type TransactionContext,\n} from '~wildo-backend-lib/databases/models/transaction.shared.schemas';\nimport { FilterQuery } from 'mongoose';\nimport type { ClientSession } from 'mongoose';\nimport { ResourceRelationship, ResourceRelationshipCardinality, ResourceParentResourceRequirement, getContextAddressedCompositionSingletonRelationshipCandidates, isOneToOneCardinality, isArrayCardinality, getChildDirectionRelationships, RelationshipNature, PRIMARY_SCOPE_TO_FIELD_IDENTIFIER } from '@wildo-ai/saas-models';\nimport { ResourcesConfigNamingUtils } from '@wildo-ai/saas-models';\nimport type { TokenGenerationConfig } from '@wildo-ai/saas-models';\nimport type {\n SubjectErasureEdgeOutcome,\n SubjectErasureReport,\n SubjectExportBundle,\n SubjectExportEdgeOutcome,\n SubjectExportReport,\n SubjectExportResourceSlice,\n} from '@wildo-ai/saas-models';\nimport { FileOperationHandlerBackendService } from '~wildo-backend-lib/files/services/file-operation-handler.backend.service';\nimport { FileFieldDetectionBackendService, type FileFieldMetadata } from '~wildo-backend-lib/files/services/file-field-detection.backend.service';\nimport { hasExplicitCanonicalFieldMutation } from '~wildo-backend-lib/files/utils/file-field-schema-path.backend.utils';\nimport type { RagSourceFieldDetectionBackendService } from '~wildo-backend-lib/files/services/rag-source-field-detection.backend.service';\nimport type { RagChunkStoreBackendService } from '~wildo-backend-lib/rag/services/rag-chunk-store.backend.service';\nimport {\n scheduleRagChunkRemovalForDeletedRows,\n scheduleRagChunkRemovalForFields,\n type RagChunkRemovalContext,\n} from '~wildo-backend-lib/rag/utils/rag-chunk-removal.backend.utils';\nimport type { RagIngestionBackendService } from '~wildo-backend-lib/rag/services/rag-ingestion.backend.service';\nimport {\n isUndeclaredCustomOperationIdentifier,\n RAG_INGESTION_WRITE_OPERATIONS,\n reportRagIngestionSkippedUndeclaredCustomOperation,\n runRagIngestionForServiceWrite,\n type RagIngestionTriggerContext,\n} from '~wildo-backend-lib/rag/utils/rag-ingestion-trigger.backend.utils';\nimport { ExecutionContextCreatorBackendService } from '~wildo-backend-lib/runtime/services/execution-context-creator.backend.service';\nimport { QueueBackendService } from '~wildo-backend-lib/queue/queue.backend.service';\nimport { FeatureGateBackendService } from '~wildo-backend-lib/features/services/feature-gate.backend.service';\nimport {\n ConsumableTokenBackendService,\n} from '~wildo-backend-lib/security/consumable-tokens/services/consumable-token.backend.service';\nimport { AppConfigurationService } from '~wildo-backend-lib/config/services/app-configuration.backend.service';\nimport type { TokenGenerationResult } from '~wildo-backend-lib/security/consumable-tokens/services/consumable-token.backend.service';\nimport { GuidanceTriggerEvaluatorBackendService } from '~wildo-backend-lib/guidance/services/guidance-trigger-evaluator.backend.service';\nimport { MilestoneEvaluatorBackendService } from '~wildo-backend-lib/guidance/services/milestone-evaluator.backend.service';\nimport { LifecycleEvaluatorBackendService } from '~wildo-backend-lib/guidance/services/lifecycle-evaluator.backend.service';\nimport type { SAMLMetadataBackendService } from '~wildo-backend-lib/security/authentications/services/auth-methods/saml-metadata.backend.service';\nimport type { SystemAccessBackendService } from '~wildo-backend-lib/base-classes/services/services/system-access.backend.service';\nimport { PdfGenerationOrchestratorBackendService, PdfGenerationRenderPhase, type GeneratePdfForFieldResult } from '~wildo-backend-lib/pdf-templates/services/pdf-generation-orchestrator.backend.service';\nimport { getConfiguredPrimaryLanguage } from '~wildo-backend-lib/config/services/app-configuration.backend.utils';\nimport { FileGenerationSource } from '@wildo-ai/zod-decorators';\nimport { isUnconfinedScopeRootDirectoryRead } from '~wildo-backend-lib/security/authorizations/scope-root-collection-confinement.backend';\n\ninterface PostOperationNotificationDispatcher {\n dispatchResourceRoomNotifications<TResourceConfigOperation extends ResourceConfiguration_Operation<any, any, any>>(\n executionContext: ExecutionContext<TResourceConfigOperation>,\n functionParameters: ResourceConfiguration_OperationVariant_CustomImplementation_FunctionParameters,\n ): Promise<void>;\n dispatchConfiguredNotifications<TResourceConfigOperation extends ResourceConfiguration_Operation<any, any, any>>(\n executionContext: ExecutionContext<TResourceConfigOperation>,\n functionParameters: ResourceConfiguration_OperationVariant_CustomImplementation_FunctionParameters,\n options?: NotificationDispatchOptions,\n ): Promise<void>;\n}\n\ninterface PostOperationNotificationDispatchDeps {\n notificationDispatcher: PostOperationNotificationDispatcher;\n populationService: Pick<ResourcePopulationBackendService, 'analyzeContextNeeds' | 'fetchComputationContext'>;\n logger: Pick<LoggerService, 'error'>;\n logDebug: (message: string, context?: Record<string, unknown>) => void;\n}\n\n/**\n * Resolution outcome for a context-addressed singleton operation (a child resource\n * that is a singleton per parent scope, e.g. one `userProgressionState` per user,\n * addressed by the parent FK rather than by its own `_id`).\n *\n * Discriminated by `kind`:\n * - `resolved` — the singleton row exists; the operation is addressed by its real\n * `_id` (`operationId`/`mutationId`) and `currentObject` is the fetched row.\n * - `absent-read-by-scope` — a READ found no row yet. Rather than fail the read as\n * not-found at this (target-resolution) layer, the read is addressed by the\n * parent-scope `selector` so the core read returns `null` and any registered\n * POSTFIX materialization hook (e.g. scoped progression/guidance state) can\n * create-and-return the row. If no hook is registered, the operation layer emits\n * `CONTROLLER_RESOURCE_NOT_FOUND` after the null read (same HTTP outcome, correct\n * layer). Only ever produced for READ — UPDATE/DELETE on an absent singleton still\n * fail closed with not-found, because a mutation cannot target a non-existent row.\n */\ntype ContextAddressedSingletonOperationTarget =\n | {\n addressedBy: 'parent-context';\n kind: 'resolved';\n selector: Record<string, string>;\n currentObject: Record<string, unknown>;\n operationId: string;\n mutationId: string;\n relationship: ResourceRelationship;\n }\n | {\n addressedBy: 'parent-context';\n kind: 'absent-read-by-scope';\n selector: Record<string, string>;\n relationship: ResourceRelationship;\n };\n\ntype ContextAddressedAssociationOperationTarget = {\n addressedBy: 'association-complete-context';\n selector: Record<string, string>;\n currentObject: Record<string, unknown>;\n operationId: string;\n mutationId: string;\n relationships: ResourceRelationship[];\n};\n\ntype GeneratedPdfMaterializationRecord = GeneratePdfForFieldResult & {\n resourceType: ResourceType;\n fieldName: string;\n rowIndex?: number;\n};\n\n/**\n * Snapshot-isolated values owned by the successful core attempt and consumed\n * only after its transaction commits.\n *\n * The wrapper is frozen when registered. For a deferred transaction effect,\n * arrays and plain DTO records are also copied recursively so code that regains\n * control before the root commit cannot rewrite notification conditions,\n * recipients, or template context. Opaque contract values retain their runtime\n * type and identity, matching the transaction-attempt cloning contract.\n */\ninterface FrameworkManagedPostCommitPayload {\n readonly currentState: any;\n readonly inputData: any;\n readonly transactionallyPreparedTokenGenerationResult: TokenGenerationResult | null;\n readonly transactionalCoreConflictReconciled: boolean;\n}\n\ninterface FrameworkManagedPostCommitExecution {\n readonly payload: FrameworkManagedPostCommitPayload;\n readonly executionContext: ExecutionContext<any>;\n readonly operation: ResourceConfiguration_Operation<any, any, any>;\n readonly resolvedOperation: ResourceConfiguration_Operation<any, any, any>;\n readonly operationPath: ResourceConfiguration_OperationPath<any, any>;\n /**\n * The row as it stood BEFORE the write, for the audit event's before/after evidence.\n *\n * Carried on the EXECUTION rather than the PAYLOAD deliberately. The payload is snapshot-cloned\n * when a transaction defers it, to stop code that regains control before commit from rewriting\n * notification config — a protection the pre-image does not need (it is read-only here and never\n * re-enters the operation). Putting it on the execution also avoids threading a new field through\n * `executeTransactionalCoreAttempt`, since both scheduling sites run the SAME closure built in\n * `doOperation`, where the pre-image is already in scope.\n *\n * `undefined` for CREATE (nothing existed) and for bulk writes (the framework fetches a pre-image\n * only when exactly one id is selected).\n */\n readonly preOperationState?: unknown;\n}\n\ninterface FrameworkManagedPostCommitScheduling {\n readonly registeredByCoreTransaction: boolean;\n readonly transaction: RepositoryOptions['transaction'] | undefined;\n readonly operationPath: ResourceConfiguration_OperationPath<any, any>;\n readonly occurrenceId: string;\n readonly payload: FrameworkManagedPostCommitPayload;\n readonly execute: (payload: FrameworkManagedPostCommitPayload) => Promise<void>;\n}\n\ninterface ResourceOperationCorePhaseResult {\n readonly state: any;\n readonly inputData: any;\n readonly terminalCustomImplUtils: ResourceOperation_CustomImplementation_Utils;\n}\n\ninterface ResourceOperationTransactionalCoreAttemptResult extends ResourceOperationCorePhaseResult {\n readonly tokenGenerationResult: TokenGenerationResult | null;\n readonly consumedIncomingToken: boolean;\n readonly transformedState: unknown;\n}\n\ninterface ResourceOperationReconciledCoreResult extends ResourceOperationCorePhaseResult {\n readonly tokenGenerationResult: TokenGenerationResult | null;\n}\n\ninterface ResourceOperationCoreBoundaryResult extends ResourceOperationCorePhaseResult {\n readonly transactionalCoreConflictReconciled: boolean;\n readonly transactionallyPreparedTokenGenerationResult: TokenGenerationResult | null;\n readonly frameworkPostCommitRegisteredTransactionally: boolean;\n readonly consumableTokenConsumedTransactionally: boolean;\n readonly transactionallyPreparedOutput?: Readonly<{ value: unknown }>;\n}\n\ninterface ResourceOperationTransactionalCoreBoundaryExecution {\n readonly persistenceContract: ResourceOperationTransactionPersistenceContract;\n readonly baseOptions: ServiceOptions | undefined;\n readonly requiresRootOwnership: boolean;\n readonly originalCoreInput: unknown;\n readonly executionContext: ExecutionContext<any>;\n readonly operation: ResourceConfiguration_Operation<any, any, any>;\n readonly customImplUtils: ResourceOperation_CustomImplementation_Utils;\n readonly conflictResolvers: readonly ResourceCustomServiceImplementationTransactionalCoreConflictResolver[];\n readonly executeAttempt: (optionsWithTransaction: ServiceOptions) => Promise<ResourceOperationTransactionalCoreAttemptResult>;\n readonly resolveReconciledResult: (reconciledState: unknown) => Promise<ResourceOperationReconciledCoreResult>;\n}\n\ninterface ResourceOperationTransactionalCoreAttemptExecution {\n readonly optionsWithTransaction: ServiceOptions;\n readonly originalCoreInput: unknown;\n readonly executeCorePhase: (\n options: RepositoryOptions,\n inputData: any,\n ) => Promise<ResourceOperationCorePhaseResult>;\n readonly executionContext: ExecutionContext<any>;\n readonly dataMode: DataMode;\n readonly operation: ResourceConfiguration_Operation<any, any, any>;\n readonly resolvedOperation: ResourceConfiguration_Operation<any, any, any>;\n readonly tokenGeneration: TokenGenerationConfig | undefined;\n readonly operationPath: ResourceConfiguration_OperationPath<any, any>;\n readonly postCommitEffectOccurrenceId: string;\n readonly executePostCommit: (\n payload: FrameworkManagedPostCommitPayload,\n ) => Promise<void>;\n}\n\ninterface ConsumableTokenContextMarkRegistration {\n readonly transaction: NonNullable<RepositoryOptions['transaction']>;\n readonly operationPath: ResourceConfiguration_OperationPath<any, any>;\n readonly occurrenceId: string;\n readonly executionContext: ExecutionContext<any>;\n}\n\ninterface ResourceOperationCorePersistenceExecution {\n readonly operation: ResourceConfiguration_Operation<any, any, any>;\n readonly operationPath: ResourceConfiguration_OperationPath<any, any>;\n readonly coreOperation: CoreResourceOperation;\n readonly executionContext: ExecutionContext<any>;\n readonly target: IdOrIdsOrFilterType | undefined;\n readonly inputData: any;\n readonly currentObject: any;\n readonly options: RepositoryOptions | undefined;\n}\n\ninterface ResourceOperationCoreAttemptContext {\n readonly currentObject: any;\n readonly hookCurrentObject: any;\n readonly computationContext: ComputationContext;\n}\n\ninterface ResourceOperationCorePhaseExecution {\n readonly operation: ResourceConfiguration_Operation<any, any, any>;\n readonly operationPath: ResourceConfiguration_OperationPath<any, any>;\n readonly coreOperation: CoreResourceOperation;\n readonly resourceType: ResourceType;\n readonly executionContext: ExecutionContext<any>;\n readonly target: IdOrIdsOrFilterType | undefined;\n readonly inputData: any;\n readonly options: RepositoryOptions | undefined;\n readonly preflightContext: ResourceOperationCoreAttemptContext;\n readonly customImplUtils: ResourceOperation_CustomImplementation_Utils;\n readonly customImplRegistrations: ResourceOperationCustomImplementationRegistration[];\n readonly customImplPlaceholders: ReadonlySet<ResourceOperation_CustomServiceImplementationMode>;\n readonly refreshTransactionalContext: (\n inputData: any,\n options: RepositoryOptions,\n ) => Promise<ResourceOperationCoreAttemptContext>;\n}\n\ninterface ResourceOperationTerminalCustomPhaseExecution {\n readonly state: any;\n readonly target: IdOrIdsOrFilterType | undefined;\n readonly executionContext: ExecutionContext<any>;\n readonly terminalCustomImplUtils: ResourceOperation_CustomImplementation_Utils;\n readonly customImplRegistrations: ResourceOperationCustomImplementationRegistration[];\n readonly customImplPlaceholders: ReadonlySet<ResourceOperation_CustomServiceImplementationMode>;\n readonly transactionalCoreRequired: boolean;\n readonly transactionalCoreConflictReconciled: boolean;\n readonly operation: ResourceConfiguration_Operation<any, any, any>;\n}\n\n/**\n * Build a fresh input graph for one database-driver transaction attempt.\n *\n * MongoDB may invoke the transaction callback more than once after a\n * transient abort. Prefix hooks are allowed to return augmented DTO objects\n * and older hooks may still mutate plain input objects in place, so sharing\n * the previous callback's graph would make a retry observe server-injected\n * fields as if they had come from the caller. Only arrays and plain DTO\n * records are copied recursively; opaque contract values (for example Date,\n * Buffer, ObjectId, or File-like instances) retain their type and identity.\n */\nfunction cloneResourceTransactionAttemptInput<T>(value: T): T {\n const seen = new WeakMap<object, unknown>();\n\n const cloneDtoValue = (candidate: unknown): unknown => {\n if (candidate === null || typeof candidate !== 'object') {\n return candidate;\n }\n const cached = seen.get(candidate);\n if (cached !== undefined) return cached;\n\n if (Array.isArray(candidate)) {\n const clone: unknown[] = [];\n seen.set(candidate, clone);\n for (const item of candidate) {\n clone.push(cloneDtoValue(item));\n }\n return clone;\n }\n\n const prototype = Object.getPrototypeOf(candidate);\n if (prototype !== Object.prototype && prototype !== null) {\n return candidate;\n }\n\n const clone: Record<string, unknown> = Object.create(prototype);\n seen.set(candidate, clone);\n for (const [key, item] of Object.entries(candidate)) {\n clone[key] = cloneDtoValue(item);\n }\n return clone;\n };\n\n return cloneDtoValue(value) as T;\n}\n\n/**\n * Capture the successful operation values before a caller-owned transaction\n * returns control to its owner.\n *\n * A nested service call completes before the root transaction commits. Its\n * caller may legitimately reuse or mutate the input object, and may also\n * receive a result object sharing nested references with the persisted state.\n * Deferred effects must observe the values that actually participated in the\n * operation, not those later mutations.\n */\nfunction snapshotFrameworkManagedPostCommitPayload(\n payload: FrameworkManagedPostCommitPayload,\n): FrameworkManagedPostCommitPayload {\n return Object.freeze({\n currentState:\n cloneResourceTransactionAttemptInput(payload.currentState),\n inputData:\n cloneResourceTransactionAttemptInput(payload.inputData),\n transactionallyPreparedTokenGenerationResult:\n cloneResourceTransactionAttemptInput(\n payload.transactionallyPreparedTokenGenerationResult,\n ),\n transactionalCoreConflictReconciled:\n payload.transactionalCoreConflictReconciled,\n });\n}\n\n/**\n * Dependencies for {@link maybeProcessTokenGenerationForOperation} — just the token-mint seam, so the\n * config-declared gate is unit-testable with a mocked `processTokenGeneration`.\n */\nexport interface OperationTokenGenerationDeps {\n consumableTokenService: Pick<ConsumableTokenBackendService, 'processTokenGeneration'>;\n}\n\n/**\n * Honor a CREATE/RESEND-like operation's optional `tokenGeneration.condition` gate, then mint the token\n * ONLY when it passes. Extracted (like {@link dispatchPostOperationNotificationsBestEffort}) so the gate is\n * unit-testable in isolation, decoupled from the full operation-execution method.\n *\n * A POLYMORPHIC operation (org-member INVITE vs DIRECT-ADD) sets `condition` to\n * `({ currentObject }) => currentObject.status === INVITED`: the INVITE branch (INVITED) mints the single-use\n * accept token, while a DIRECT-ADD (founder / SSO-JIT / SCIM — status ACTIVE) mints NOTHING, so no live accept\n * token dangles on an already-ACTIVE row. Absent `condition` = always mint.\n *\n * @returns the mint result, or `null` when the condition gated it out (`processTokenGeneration` is not called).\n */\nexport async function maybeProcessTokenGenerationForOperation(\n deps: OperationTokenGenerationDeps,\n tokenGeneration: TokenGenerationConfig,\n currentState: Record<string, any>,\n tokenExecutionContext: {\n organizationId?: string;\n userId?: string;\n resourceType?: string;\n },\n transaction: TransactionContext,\n): Promise<TokenGenerationResult | null> {\n const shouldGenerate = !tokenGeneration.condition\n || tokenGeneration.condition({ currentObject: currentState });\n if (!shouldGenerate) return null;\n return deps.consumableTokenService.processTokenGeneration(\n tokenGeneration,\n currentState,\n tokenExecutionContext,\n transaction,\n );\n}\n\nexport async function dispatchPostOperationNotificationsBestEffort(\n deps: PostOperationNotificationDispatchDeps,\n executionContext: ExecutionContext<any>,\n inputData: any,\n currentResult: any,\n tokenGenerationResult?: TokenGenerationResult | null,\n previousState?: unknown,\n): Promise<void> {\n const resourceRoomParameters: Record<string, any> = {\n inputDto: inputData,\n currentObject: currentResult,\n initiatorIds: executionContext.initiatorIds,\n };\n\n try {\n // Resource-room notifications run first and on thinner inputs on purpose:\n // websocket coherence only needs authoritative object truth + initiator ids,\n // not the richer population/user context required by authored notifications.\n await deps.notificationDispatcher.dispatchResourceRoomNotifications(\n executionContext,\n resourceRoomParameters as any,\n );\n } catch (error) {\n deps.logger.error('Failed to dispatch resource-room notifications', {\n ...projectCaughtErrorLogFields(error),\n operationIdentifier: executionContext.operation.operationIdentifier,\n resourceIdentifier: executionContext.operation.resourceIdentifier,\n });\n }\n\n try {\n // Configured notifications are the richer second phase. They may depend on\n // populated object context, user context, and additional authored delivery\n // channels, so they intentionally run after the lightweight websocket pass.\n const resourceType = executionContext.operation.resourceIdentifier as ResourceType;\n const needs = deps.populationService.analyzeContextNeeds(resourceType);\n const computationContext = await deps.populationService.fetchComputationContext(\n resourceType,\n currentResult,\n needs,\n executionContext,\n );\n\n const functionParameters: Record<string, any> = {\n inputDto: inputData,\n currentObject: currentResult,\n // The pre-image (single-row UPDATE/DELETE only; undefined for CREATE and bulk). Carried for\n // the derived-badge recompute, which re-counts the scope a row moved OUT of on reassignment.\n // (A selector notifying a prior assignee could also use it, but selectors are not fed it yet.)\n previousObject: previousState,\n objectContext: computationContext.objectContext,\n initiatorUserContext: computationContext.userContext,\n initiatorIds: executionContext.initiatorIds,\n };\n\n if (tokenGenerationResult) {\n functionParameters.additionalContext = {\n ...(functionParameters.additionalContext || {}),\n tokenValue: tokenGenerationResult.tokenValue,\n };\n }\n\n await deps.notificationDispatcher.dispatchConfiguredNotifications(\n executionContext,\n functionParameters as any,\n tokenGenerationResult\n ? { emailSubmissionSourceId: tokenGenerationResult.tokenId }\n : undefined,\n );\n\n deps.logDebug('Configured notifications dispatched successfully');\n } catch (error) {\n deps.logger.error('Failed to dispatch configured notifications', {\n ...projectCaughtErrorLogFields(error),\n operationIdentifier: executionContext.operation.operationIdentifier,\n resourceIdentifier: executionContext.operation.resourceIdentifier,\n });\n }\n}\n\n@injectable()\nexport class ServicesRegistryHandlerBackendService {\n\n private readonly services: Map<ResourceType, ServiceResourceBackendService<any, any, any>>;\n private readonly serviceOperationsMap: Map<string, {\n operationPath: ResourceConfiguration_OperationPath<any, any>;\n service: ServiceResourceBackendService<any, any, any>;\n\n }>;\n\n private isInitialized = false;\n protected logDebug: (message: string, context?: Record<string, unknown>) => void;\n\n /**\n * Post-operation hooks: fire after a successful mutation on a resource type.\n * Key = resource type identifier, Value = array of hook callbacks.\n *\n * Failure semantics: errors thrown by post-hooks are caught and logged\n * (fire-and-forget). The mutation has already committed by the time the\n * hook runs; propagating here would report success at the API layer\n * then surface a crash to the caller, corrupting observable state.\n */\n private readonly postOperationHooks: Map<string, PostOperationHookCallback[]> = new Map();\n\n /**\n * Pre-operation hooks: fire BEFORE the core op on a resource type.\n * Key = resource type identifier, Value = array of hook callbacks.\n *\n * Failure semantics (plan §Phase-3 decision P3-A = A1): the FIRST hook\n * that throws short-circuits the dispatch loop and the error\n * propagates unchanged to the caller. This lets pre-hooks act as a\n * real enforcement point (rejecting e.g. a Level-B seed's\n * `beforeCreate` short-circuit the operation) without needing to\n * mutate data via a custom `prefixCoreOperations` impl.\n *\n * Mutation contract: pre-hooks are **observation + veto only** — they\n * do NOT transform the incoming `data`. Enforced by callback shape\n * (no return value). Data mutation stays inside\n * `prefixCoreOperations` of custom operation impls.\n */\n private readonly preOperationHooks: Map<string, PreOperationHookCallback[]> = new Map();\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.RepositoriesRegistryHandlerService) private readonly repositoriesRegistry: RepositoriesRegistryHandlerBackendService,\n @inject(SAAS_SERVICE_TYPES.Logger) private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.ErrorBuilderService) private readonly errorBuilder: ErrorBuilderBackendService,\n @inject(SAAS_SERVICE_TYPES.ResourceRegistryService) private readonly resourcesRegistry: ResourcesRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.ResourceOperationHelperService) private readonly repositoryHelper: ResourceOperationHelperBackendService,\n @inject(SAAS_SERVICE_TYPES.ResourceOperationCustomImplementationRegistryService) private readonly customImplRegistry: ResourceOperationCustomImplementationRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.ResourcePersistenceUnitOfWorkService) private readonly resourcePersistenceUnitOfWork: ResourcePersistenceUnitOfWorkBackendService,\n @inject(SAAS_SERVICE_TYPES.ExternalApiHandlerService) private readonly externalApiHandler: ExternalApiHandlerBackendService,\n @inject(SAAS_SERVICE_TYPES.PlatformMutualizedHandlerService) private readonly platformMutualizedHandler: PlatformMutualizedHandlerBackendService,\n @inject(SAAS_SERVICE_TYPES.ServerlessServicesHandlerService) private readonly serverlessServicesHandler: ServerlessServicesHandlerBackendService,\n @inject(SAAS_SERVICE_TYPES.NotificationDispatcherService) private readonly notificationDispatcher: NotificationDispatcherService,\n @inject(SAAS_SERVICE_TYPES.ResourcePopulationService) private readonly populationService: ResourcePopulationBackendService,\n @inject(SAAS_SERVICE_TYPES.VirtualFieldsService) private readonly virtualFieldsService: VirtualFieldsBackendService,\n @inject(SAAS_SERVICE_TYPES.MongoDBService) private readonly mongoDBService: MongoDBService,\n @inject(SAAS_SERVICE_TYPES.FileOperationHandlerService) private readonly fileOperationHandler: FileOperationHandlerBackendService,\n @inject(SAAS_SERVICE_TYPES.FileFieldDetectionService) private readonly fileFieldDetection: FileFieldDetectionBackendService,\n @inject(SAAS_SERVICE_TYPES.ExecutionContextCreatorBackendService) private readonly executionContextCreator: ExecutionContextCreatorBackendService,\n @inject(SAAS_SERVICE_TYPES.QueueBackendService) private readonly queueService: QueueBackendService,\n @inject(SAAS_SERVICE_TYPES.FeatureGateService) private readonly featureGate: FeatureGateBackendService,\n @inject(SAAS_SERVICE_TYPES.ConsumableTokenService) private readonly consumableTokenService: ConsumableTokenBackendService,\n @inject(SAAS_SERVICE_TYPES.AppConfigService) private readonly appConfigService: AppConfigurationService,\n @inject(SAAS_SERVICE_TYPES.PdfGenerationOrchestrator) private readonly pdfGenerationOrchestrator: PdfGenerationOrchestratorBackendService,\n @inject(SAAS_SERVICE_TYPES.GuidanceTriggerEvaluator) @optional() private readonly guidanceTriggerEvaluator?: GuidanceTriggerEvaluatorBackendService,\n @inject(SAAS_SERVICE_TYPES.MilestoneEvaluator) @optional() private readonly milestoneEvaluator?: MilestoneEvaluatorBackendService,\n @inject(SAAS_SERVICE_TYPES.LifecycleEvaluator) @optional() private readonly lifecycleEvaluator?: LifecycleEvaluatorBackendService,\n @inject(SAAS_SERVICE_TYPES.PostgreSQLDatabaseService) @optional() private readonly postgreSQLDatabaseService?: PostgreSQLDatabaseBackendService,\n @inject(SAAS_SERVICE_TYPES.SAMLMetadataService) @optional() private readonly samlMetadataService?: SAMLMetadataBackendService,\n // Late/optional: exposed to custom-impl utils as the SANCTIONED privileged-access\n // path (readAsSystem/…), so request-triggered ACL bypass is fail-closed + audited\n // instead of hand-rolled via the raw EC creator. `@optional()` keeps minimal test\n // containers constructing; no construction cycle (SystemAccess resolves THIS handler\n // lazily via the container, never in its constructor).\n @inject(SAAS_SERVICE_TYPES.SystemAccessService) @optional() private readonly systemAccessService?: SystemAccessBackendService,\n @inject(SAAS_SERVICE_TYPES.SubjectSessionRevocationService) @optional() private readonly subjectSessionRevocation?: SubjectSessionRevocationBackendService,\n // Late/optional, for the SAME reason as SystemAccess above: the post-commit lane records that a\n // HIGH/CRITICAL resource operation took effect. `@optional()` keeps minimal test containers\n // constructing, and there is no construction cycle — `AuditLogsBackendService` depends on the\n // REPOSITORIES registry, the audit dispatcher and the EC creator, never on this handler.\n // assurance-control: WILDO.AUDIT.SECURITY_EVENT — privileged resource actions are attributable.\n @inject(SAAS_SERVICE_TYPES.AuditLogsService) @optional() private readonly auditLogsService?: AuditLogsBackendService,\n // RAG derived-data tier (plan D3) — the removal-seam pair, exposed to the per-resource services\n // through `getRagChunkRemovalContext()` (like SystemAccess: `ServiceResourceBackendService`'s\n // constructor is invoked POSITIONALLY, so new dependencies land here, never there). `@optional()`\n // keeps minimal test containers constructing; a container missing either simply has no chunk\n // tier, and the seams no-op (the startup capability probe is what refuses a REAL application\n // whose RAG-source resources have no usable store).\n @inject(SAAS_SERVICE_TYPES.RagSourceFieldDetectionService) @optional() private readonly ragSourceFieldDetection?: RagSourceFieldDetectionBackendService,\n @inject(SAAS_SERVICE_TYPES.RagChunkStoreService) @optional() private readonly ragChunkStore?: RagChunkStoreBackendService,\n // RAG write path (plan §3.c) — the ingestion pipeline behind `getRagIngestionContext()`, the\n // removal pair's write-side sibling. Appended LAST and `@optional()` for the same positional-\n // construction reasons documented on the pair above.\n @inject(SAAS_SERVICE_TYPES.RagIngestionService) @optional() private readonly ragIngestion?: RagIngestionBackendService,\n ) {\n this.logger = logger;\n this.errorBuilder = errorBuilder;\n this.services = new Map();\n this.serviceOperationsMap = new Map();\n\n this.logDebug = this.logger.debugByType('ServicesRegistryHandler');\n this.logger.setDebugTypeLogging('ServicesRegistryHandler', false);\n\n this.logDebug('Services registry service created');\n }\n\n /** Exposes SAML metadata service for custom impl utils (DISCOVER_ENDPOINTS). */\n public getSamlMetadataService(): SAMLMetadataBackendService | undefined {\n return this.samlMetadataService;\n }\n\n /**\n * Exposes the system-access service to custom-impl utils as the sanctioned\n * privileged-access path (readAsSystem / listAsSystem / createAsSystem /\n * updateAsSystem — fail-closed + audited). Returns `undefined` only in minimal\n * containers that do not bind it; consumers degrade gracefully.\n */\n public getSystemAccessService(): SystemAccessBackendService | undefined {\n return this.systemAccessService;\n }\n\n /**\n * Exposes the session-revocation port to the per-resource services, whose scrub chokepoint ends an\n * erased person's sessions. A port rather than a direct dependency because `AuthTokenIssuer` already\n * injects THIS class — see {@link SubjectSessionRevocationBackendService}.\n *\n * Returns `undefined` only in a minimal container that does not bind it; the chokepoint then logs\n * loudly rather than silently reporting a terminated session that is still live.\n */\n public getSubjectSessionRevocationService(): SubjectSessionRevocationBackendService | undefined {\n return this.subjectSessionRevocation;\n }\n\n /**\n * The RAG chunk-removal context for the per-resource services' removal seams (row-delete cascade,\n * field impersonalization) — see `rag-chunk-removal.backend.utils.ts` for the ONE failure/\n * transaction discipline every seam shares.\n *\n * A getter on the registry rather than a `ServiceResourceBackendService` constructor parameter for\n * the same reason as `getSystemAccessService`: that constructor is invoked POSITIONALLY from\n * `createService` and from focused tests, so a new parameter shifts existing arguments silently.\n *\n * Returns `undefined` when either half is unbound (minimal test containers). The seams then no-op:\n * for a real application the startup capability probe — not the seams — is what refuses a\n * configuration whose RAG-source resources would have no reachable chunk store.\n */\n public getRagChunkRemovalContext(): RagChunkRemovalContext | undefined {\n if (!this.ragChunkStore || !this.ragSourceFieldDetection) {\n return undefined;\n }\n return {\n ragChunkStore: this.ragChunkStore,\n ragSourceFieldDetection: this.ragSourceFieldDetection,\n logger: this.logger,\n };\n }\n\n /**\n * The RAG ingestion context for the per-resource services' WRITE hook (the changed-field\n * re-index in the framework-managed post-commit chokepoint) — the write-side sibling of\n * {@link getRagChunkRemovalContext}, a getter for the same positional-construction reason.\n *\n * Returns `undefined` when any member is unbound (minimal test containers): the hook then no-ops,\n * and — as for removal — the startup capability probe is what refuses a REAL application whose\n * RAG-source resources would have no reachable chunk store.\n */\n public getRagIngestionContext(): RagIngestionTriggerContext | undefined {\n if (!this.ragIngestion || !this.ragSourceFieldDetection) {\n return undefined;\n }\n return {\n ragIngestion: this.ragIngestion,\n ragSourceFieldDetection: this.ragSourceFieldDetection,\n logger: this.logger,\n };\n }\n\n /**\n * Exposes the audit service to the per-resource services, which record that a HIGH/CRITICAL\n * operation took effect from their post-commit lane.\n *\n * Reached through this getter rather than added to `ServiceResourceBackendService`'s constructor:\n * that constructor is invoked POSITIONALLY from `createService` and from focused tests, so a new\n * parameter shifts existing arguments silently. Same reasoning as `getSystemAccessService`.\n *\n * Returns `undefined` only in minimal containers that do not bind it. That degrades to \"no audit\n * row\", which is the correct behaviour for a test container and is why the emission is guarded\n * rather than asserted — a missing binding must not break the operation.\n */\n public getAuditLogsService(): AuditLogsBackendService | undefined {\n return this.auditLogsService;\n }\n\n // ================================\n // Initialization Methods\n // ================================\n\n /**\n * @param serviceWhiteList - Optional resource types to limit service instantiation to. Mirrors\n * `ControllersRegistryHandlerBackendService.initialize`'s `controllerWhiteList`, and exists for\n * the same reason: a host may hold a registry far wider than the surface it serves.\n *\n * The dev companion is that host — its registry is the union of the observed application's\n * vocabulary, platform-core's and the engine's, and it serves generated routes for a handful of\n * workbench resources. Without this parameter it had to build a service for EVERY resource, and\n * `createService` throwing aborts the whole initialization: one resource whose service\n * implementation the host does not carry would fail its boot outright.\n *\n * Omitted means every resource, which is what an application backend wants and is the behaviour\n * this method has always had.\n */\n public async initializeServices(serviceWhiteList?: readonly string[]): Promise<void> {\n if (this.isInitialized) {\n this.logDebug('Registry already initialized, skipping...');\n return;\n }\n\n const allResourceTypes = this.resourcesRegistry.getResourceTypes();\n const resourceTypes = serviceWhiteList\n ? allResourceTypes.filter((resourceType) => serviceWhiteList.includes(resourceType))\n : allResourceTypes;\n\n if (serviceWhiteList) {\n this.logDebug('Applied service whitelist filter', {\n originalResourceCount: allResourceTypes.length,\n filteredResourceCount: resourceTypes.length,\n whitelistedResources: serviceWhiteList,\n });\n }\n\n this.logDebug('Initializing services', { resourceCount: resourceTypes.length, resourceTypes: resourceTypes });\n\n // First pass: Create all services\n for (const resourceType of resourceTypes) {\n try {\n await this.createService(resourceType);\n } catch (error) {\n\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL, undefined,\n { customMessageReference: ErrorCustomMessageReference.SERVICE_CREATION_FAILED, context: { resourceType, error: describeCaughtError(error) } } );\n }\n }\n\n this.buildOperationPathsMap();\n\n this.isInitialized = true;\n\n this.logDebug('Services registry initialization completed', {\n serviceCount: this.services.size,\n operationPathsCount: this.serviceOperationsMap.size\n });\n }\n\n private async createService( resourceType: ResourceType): Promise<void> {\n this.logDebug('Creating service', { resourceType });\n\n\n const service = ServiceResourceBackendService.createInstance(\n resourceType, this.logger, this.errorBuilder, this.repositoriesRegistry, this,\n this.resourcesRegistry, this.repositoryHelper, this.customImplRegistry,\n this.resourcePersistenceUnitOfWork,\n this.externalApiHandler, this.platformMutualizedHandler, this.serverlessServicesHandler,\n this.notificationDispatcher,\n this.populationService, this.virtualFieldsService, this.mongoDBService,\n this.fileOperationHandler, this.fileFieldDetection,\n this.executionContextCreator,\n this.queueService,\n this.featureGate,\n this.consumableTokenService,\n this.appConfigService,\n this.pdfGenerationOrchestrator,\n this.guidanceTriggerEvaluator,\n this.milestoneEvaluator,\n this.lifecycleEvaluator,\n this.postgreSQLDatabaseService,\n );\n\n this.services.set(resourceType, service);\n\n this.logDebug('Service created successfully', { resourceType });\n }\n\n private buildOperationPathsMap(): void {\n this.logDebug('Building operation paths map');\n\n let totalOperationPaths = 0;\n\n this.services.forEach((service, resourceType) => {\n const resourceConfiguration = this.resourcesRegistry.getResourceConfiguration(resourceType);\n\n if (!resourceConfiguration.operations) {\n return;\n }\n\n resourceConfiguration.operations.forEach(operation => {\n const operationPath = ResourcesConfig_OperationPathUtils.extractOperationPath(operation);\n const operationKey = ResourcesConfig_OperationPathUtils.createOperationPathKey(operationPath);\n\n this.serviceOperationsMap.set(operationKey, { service, operationPath });\n\n totalOperationPaths++;\n });\n });\n\n this.logDebug('Operation paths map built', { totalOperationPaths,operationKeys: Array.from(this.serviceOperationsMap.keys()).slice(0, 5) });\n }\n\n // ================================\n // Service Access Methods\n // ================================\n\n public getService<\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 ): ServiceResourceBackendService<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> | undefined {\n\n const service = this.services.get(resourceType);\n\n if (!service) {\n this.logDebug('Service not found', { resourceType });\n return undefined;\n }\n\n return service as ServiceResourceBackendService<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\n }\n\n public getServiceOrThrow<\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 ): ServiceResourceBackendService<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> {\n\n const service = this.getService<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>(resourceType);\n\n if (!service) {\n throw this.errorBuilder.buildError( ErrorType.NOT_FOUND, undefined, { customMessageReference: ErrorCustomMessageReference.SERVICE_NOT_FOUND, context: { resourceType } } );\n }\n\n return service;\n }\n\n // ================================\n // Execution Methods\n // ================================\n\n public async doByOperationPath<T = any>(\n operationPath: ResourceConfiguration_OperationPath<any, any>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: any,\n options?: RepositoryOptions\n ): Promise<T> {\n\n const operationKey = ResourcesConfig_OperationPathUtils.createOperationPathKey(operationPath);\n const operationInfo = this.serviceOperationsMap.get(operationKey);\n\n if (!operationInfo) {\n throw this.errorBuilder.buildError( ErrorType.NOT_FOUND, executionContext, { customMessageReference: ErrorCustomMessageReference.SERVICE_NOT_FOUND, context: { operationKey, operationPath } } );\n }\n\n this.logDebug('Executing operation by path', { operationPath, operationKey, id_or_ids_or_filter });\n\n return operationInfo.service.doByOperationPath( operationPath, executionContext, id_or_ids_or_filter, data, options );\n }\n\n\n public async doByExecutionContext<T = any>( executionContext: ExecutionContext<any>, data?: any, options?: RepositoryOptions ): Promise<T> {\n\n const operation = executionContext.operation;\n const resourceType = operation.resourceIdentifier as ResourceType;\n\n const service = this.getServiceOrThrow(resourceType);\n\n this.logDebug('Executing operation by execution context', { resourceType, operationIdentifier: operation.operationIdentifier });\n\n return service.doByExecutionContext(executionContext, data, options);\n }\n\n // ════════════════════════════════════════════════════════════════════\n // Convenience methods for programmatic resource operations.\n //\n // These pass the caller's executionContext through to doByOperationPath,\n // which resolves the target operation from the registry. If the caller's\n // executionContext.operation differs from the target operation (e.g., a\n // webhook handler calling create(SUBSCRIPTION, webhookCtx)), doOperation's\n // Correction Point 1 corrects the context before any pipeline logic runs.\n //\n // For proper sub-call depth tracking and cycle detection, callers should\n // use executionContextCreator.createForSubCall() before calling these\n // methods. Without it, operations are functionally correct but skip\n // depth/cycle safety checks.\n //\n // ────────────────────────────────────────────────────────────────────\n // ⚠️ WHAT THESE METHODS DO **NOT** APPLY: the operation's ROLE ACL.\n // ────────────────────────────────────────────────────────────────────\n //\n // Read this before using one of them to serve an EXTERNAL caller.\n //\n // A programmatic operation enters at the SERVICE tier. It therefore gets\n // the repository's contextual filter (tenancy, relationship-FK narrowing,\n // organization-unit narrowing, the anonymous guard and the retention\n // row-hide — all fail-closed, no opt-out) and the whole operation pipeline\n // (Zod validation, enabled conditions, custom impl, hooks). It does NOT\n // get `AuthorizationsBackendService.authorizeInController`, which is\n // mounted at the CONTROLLER tier and is the only place the operation's\n // declared `roles` are checked. A caller whose roles would be refused the\n // operation, but whose tenancy admits the row, succeeds here.\n //\n // That is DELIBERATE, and load-bearing rather than merely tolerated: this\n // surface's dominant population is authentication (registration, OAuth /\n // SAML identity-link resolution, credential lookup, token issuance), SCIM\n // provisioning, billing webhook routing, sweeps and feature resolution —\n // reads that run BEFORE a role-bearing principal exists. Applying the role\n // gate here would deny the reads that ESTABLISH identity. The service tier\n // is INSIDE the trust boundary; the boundary is the controller, because\n // that is where an untrusted principal names an operation.\n //\n // ⇒ If you are building a service-tier surface that takes a CALLER-SUPPLIED\n // query and returns row CONTENT to that caller on their own authority,\n // you are on the boundary and the role gate is yours to apply: call\n // `AuthorizationsBackendService.authorizeInProgrammaticSurface` ONCE PER\n // RESOURCE TYPE before you go looking (never per row — the gate is\n // row-independent, and a post-hoc per-row refusal re-creates the very\n // existence side channel a pre-filter closes). `RagRetrievalBackendService`\n // is the worked example; the full decision is on that method.\n // ════════════════════════════════════════════════════════════════════\n\n public async create<T = any>(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n data: any,\n options?: ServiceOptions\n ): Promise<T> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.CREATE);\n return service.doByOperationPath(operationPath, executionContext, undefined, data, options);\n }\n\n public async createMany<T = any>(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n data: any[],\n options?: ServiceOptions\n ): Promise<T[]> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.CREATE_MANY);\n return service.doByOperationPath(operationPath, executionContext, undefined, data, options);\n }\n\n public async read<T = any>(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n options?: ServiceOptions\n ): Promise<T | null> {\n const service = this.getServiceOrThrow(resourceType);\n // If variantKey is specified, get that variant's operationPath\n const operationPath : ResourceConfiguration_OperationPath<any, any> = options?.variantKey\n ? this.resourcesRegistry.getServiceOperationPath(resourceType, CoreResourceOperation.READ, options.variantKey)\n : this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.READ);\n return service.doByOperationPath(operationPath, executionContext, id_or_ids_or_filter, undefined, options);\n }\n\n public async update<T = any>(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n data: any,\n options?: ServiceOptions\n ): Promise<T | null> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.UPDATE);\n return service.doByOperationPath(operationPath, executionContext, id_or_ids_or_filter, data, options);\n }\n\n public async updateMany<T = any>(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n data: any,\n options?: ServiceOptions\n ): Promise<T[]> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.UPDATE_MANY);\n return service.doByOperationPath(operationPath, executionContext, id_or_ids_or_filter, data, options);\n }\n\n public async delete(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n resourceId: string,\n options?: ServiceOptions\n ): Promise<string> {\n if (typeof resourceId !== 'string' || resourceId.length === 0) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n operation: CoreResourceOperation.DELETE,\n reason: 'ServicesRegistryHandlerBackendService.delete() only accepts a single resource id. Use deleteMany() for ids or filters.',\n resourceType,\n },\n });\n }\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.DELETE);\n return service.doByOperationPath(operationPath, executionContext, resourceId, undefined, options);\n }\n\n public async deleteMany(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n options?: ServiceOptions\n ): Promise<string[]> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.DELETE_MANY);\n return service.doByOperationPath(operationPath, executionContext, id_or_ids_or_filter, undefined, options);\n }\n\n // ════════════════════════════════════════════════════════════════════\n // Custom operations\n // ════════════════════════════════════════════════════════════════════\n\n /**\n * Execute a custom operation on a resource through the full pipeline.\n * Routes through the same operation pipeline as HTTP-triggered custom operations\n * (Zod validation, RBAC, custom impl dispatch, post-operation hooks).\n *\n * @param resourceType - The resource type to execute the operation on\n * @param customOperationIdentifier - The custom operation name (e.g., 'top_up', 'consume')\n * @param executionContext - The execution context for RBAC and scoping\n * @param id_or_ids_or_filter - The resource ID to target (most custom ops require this)\n * @param data - The request payload for the custom operation\n * @param options - Optional service options\n */\n public async executeCustomOperation<T = any>(\n resourceType: ResourceType,\n customOperationIdentifier: string,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: any,\n options?: ServiceOptions,\n ): Promise<T> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath: ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, customOperationIdentifier);\n return service.doByOperationPath(operationPath, executionContext, id_or_ids_or_filter, data, options);\n }\n\n /**\n * Execute an explicit multi-target relationship action.\n *\n * This is the service-level implementation seam behind the planned operation\n * split:\n * - `UPDATE_MANY` stays a bulk patch of the main resource\n * - explicit relationship actions (`set`, `clear`, `create`, `link`,\n * `unlink`) are applied to a named relationship from the current resource's\n * perspective\n */\n public async applyRelationshipActionMany(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n request: ResourceRelationshipBulkActionRequest,\n options?: ServiceOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n const service = this.getServiceOrThrow(resourceType);\n const parsedRequest = ResourceRelationshipBulkActionRequestSchema.parse(request);\n return service.applyRelationshipActionMany(\n executionContext,\n id_or_ids_or_filter,\n parsedRequest,\n options\n );\n }\n\n // ════════════════════════════════════════════════════════════════════\n // Post-operation hooks\n // ════════════════════════════════════════════════════════════════════\n\n /**\n * Register a callback that fires after any successful mutation on a resource type.\n * Hooks are fire-and-forget — errors are logged but do not fail the operation.\n *\n * @param resourceType - The resource type to observe\n * @param callback - Invoked after CREATE, UPDATE, DELETE, or custom mutation succeeds\n */\n public registerPostOperationHook(resourceType: string, callback: PostOperationHookCallback): void {\n const hooks = this.postOperationHooks.get(resourceType) ?? [];\n hooks.push(callback);\n this.postOperationHooks.set(resourceType, hooks);\n this.logDebug('Post-operation hook registered', { resourceType });\n }\n\n /**\n * Dispatch post-operation hooks for a resource type.\n * Called by ServiceResourceBackendService after successful operations.\n * @internal\n */\n public async dispatchPostOperationHooks(\n resourceType: string,\n operationIdentifier: string,\n result: any,\n executionContext: ExecutionContext<any>,\n ): Promise<void> {\n const hooks = this.postOperationHooks.get(resourceType);\n if (!hooks || hooks.length === 0) return;\n\n for (const hook of hooks) {\n try {\n await hook(resourceType, operationIdentifier, result, executionContext);\n } catch (error) {\n this.logger.warn('Post-operation hook failed', {\n resourceType,\n operationIdentifier,\n error: (error as Error).message,\n });\n }\n }\n }\n\n /**\n * Register a callback that fires BEFORE a core operation on a resource type.\n *\n * **Operation coverage** (Phase 5 / P5-H = H1 widened):\n * - Mutating ops: CREATE / CREATE_MANY / UPDATE / UPDATE_MANY /\n * DELETE / DELETE_MANY (Phase-3 baseline).\n * - Read ops: READ / LIST (Phase 5 widening, to support the LAZY\n * seeding guard installed by `wireLazyAccessGuards`). The\n * pre-hook callback receives the raw `id_or_ids_or_filter`\n * (READ) or `filter` (LIST) as its `data` arg; LAZY guards\n * ignore it, but future read-side pre-hooks (audit-on-read,\n * cache-warming, access-policy-enforcement) can inspect it.\n *\n * Operations not in the list above (RELATE_*, custom operations,\n * etc.) do not fire pre-hooks today.\n *\n * Symmetric companion to {@link registerPostOperationHook}. Unlike the\n * post variant, pre-hook failures are **propagated** (plan §Phase-3\n * decision P3-A = A1, reaffirmed for read paths by P5-A = A1):\n * throwing from a pre-hook short-circuits the dispatch loop AND the\n * triggering operation. This is deliberate — pre-hooks are the veto\n * point for Level-B data seeding, LAZY first-access bootstrap, guard\n * checks, and cross-resource consistency rules that should abort\n * the operation. Soft observations belong on the post-hook side.\n *\n * Registration order is preserved by dispatch order (first registered,\n * first invoked). If an earlier hook throws, later hooks in the same\n * bucket do NOT run — rollback of previously-invoked hooks is the\n * caller's responsibility and does not exist in the framework.\n *\n * **Performance**: registered hooks pay an O(1) Map lookup + the\n * hook's own work per invocation. Resources without any registered\n * pre-hook short-circuit in {@link dispatchPreOperationHooks} on the\n * empty-hooks branch — no per-call cost. The READ/LIST widening\n * therefore costs nothing for resources that do not opt into a\n * pre-hook (the common case).\n *\n * @param resourceType - The resource type to observe\n * @param callback - Invoked before CREATE / UPDATE / DELETE / READ / LIST (and their bulk variants where applicable) on this resource type\n */\n public registerPreOperationHook(resourceType: string, callback: PreOperationHookCallback): void {\n const hooks = this.preOperationHooks.get(resourceType) ?? [];\n hooks.push(callback);\n this.preOperationHooks.set(resourceType, hooks);\n this.logDebug('Pre-operation hook registered', { resourceType });\n }\n\n /**\n * `true` iff at least one pre-operation hook is registered for\n * `resourceType`. Used by mutation paths that have to decide whether\n * to perform extra preparatory work for hooks (e.g. `updateMany`\n * loading `currentStates` so the pre-hook payload can carry per-row\n * `_id` anchors — see {@link executePreOperationLogic}). Resources\n * without any subscribed hook MUST NOT pay that cost — the predicate\n * exists exclusively as the gate that keeps the framework\n * pay-for-what-you-use.\n */\n public hasPreOperationHooks(resourceType: string): boolean {\n const hooks = this.preOperationHooks.get(resourceType);\n return Array.isArray(hooks) && hooks.length > 0;\n }\n\n /**\n * Dispatch pre-operation hooks for a resource type.\n * Called by {@link ServiceResourceBackendService} during\n * {@link ServiceResourceBackendService.executePreOperationLogic}\n * BEFORE the core repository call.\n *\n * Short-circuit on first throw — errors propagate unchanged to the\n * caller so the operation surfaces the failure through its normal\n * error-handling path (custom impl `prefixCoreOperations` throws take\n * the same shape from the caller's POV).\n *\n * @internal\n */\n public async dispatchPreOperationHooks(\n resourceType: string,\n operationIdentifier: string,\n data: any,\n executionContext: ExecutionContext<any>,\n ): Promise<void> {\n const hooks = this.preOperationHooks.get(resourceType);\n if (!hooks || hooks.length === 0) return;\n\n for (const hook of hooks) {\n // Intentionally no try/catch — see plan §Phase-3 P3-A=A1. A thrown\n // hook aborts the loop; subsequent hooks in the same bucket do not\n // run and the error propagates to `executePreOperationLogic`, which\n // lets it bubble to the top of the pipeline (same shape as a\n // `prefixCoreOperations` rejection).\n await hook(resourceType, operationIdentifier, data, executionContext);\n }\n }\n\n // ════════════════════════════════════════════════════════════════════\n // Read / List / Search / Count\n // ════════════════════════════════════════════════════════════════════\n\n /**\n * List resources with optional pagination.\n * @param options.paginated - When true, returns { data: T[], pagination: {...} }. Default: false (returns T[])\n * @param options.variantKey - Optional variant key (e.g., 'summary', 'context')\n * @param options.dataMode - Optional data mode for population behavior\n */\n public async list<T = any>(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n filter?: FilterQuery<any>,\n pagination?: Partial<Resources_PaginationRequest>,\n options?: ServiceOptions\n ): Promise<T[] | Resources_PaginatedResult<T>> {\n\n const service = this.getServiceOrThrow(resourceType);\n // If variantKey is specified, get that variant's operationPath\n const operationPath : ResourceConfiguration_OperationPath<any, any> = options?.variantKey\n ? this.resourcesRegistry.getServiceOperationPath(resourceType, CoreResourceOperation.LIST, options.variantKey)\n : this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.LIST);\n const listData = { filter, page: pagination?.page, limit: pagination?.limit };\n return service.doByOperationPath(operationPath, executionContext, undefined, listData, options);\n }\n\n public async search<T = any>(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n searchQuery: string,\n filter?: FilterQuery<any>,\n options?: ServiceOptions\n ): Promise<Resources_PaginatedResult<T>> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.SEARCH);\n return service.doByOperationPath(operationPath, executionContext, undefined, { searchQuery, filter }, options);\n }\n\n public async count( resourceType: ResourceType, executionContext: ExecutionContext<any>, filter?: FilterQuery<any>, options?: ServiceOptions ): Promise<{ count: number }> {\n const service = this.getServiceOrThrow(resourceType);\n const operationPath : ResourceConfiguration_OperationPath<any, any> = this.resourcesRegistry.getServiceOperationPathDefault(resourceType, CoreResourceOperation.COUNT);\n const countData = filter ? { filter } : undefined;\n return service.doByOperationPath(operationPath, executionContext, undefined, countData, options);\n }\n\n // ================================\n // Utility Methods\n // ================================\n\n public getAvailableOperationPaths(): ResourceConfiguration_OperationPath<any, any>[] {\n return Array.from(this.serviceOperationsMap.values()).map(info => info.operationPath);\n }\n\n public hasService(resourceType: ResourceType): boolean {\n return this.services.has(resourceType);\n }\n\n public getRegisteredResourceTypes(): ResourceType[] {\n return Array.from(this.services.keys());\n }\n\n public getServiceCount(): number {\n return this.services.size;\n }\n\n public getDebugInfo(): {\n serviceCount: number;\n operationPathsCount: number;\n resourceTypes: ResourceType[];\n isInitialized: boolean;\n } {\n return {\n serviceCount: this.services.size,\n operationPathsCount: this.serviceOperationsMap.size,\n resourceTypes: Array.from(this.services.keys()),\n isInitialized: this.isInitialized\n };\n }\n}\n\n/**\n * Callback type for post-operation hooks.\n * Fired after a successful mutation (CREATE/UPDATE/DELETE/custom) on a resource.\n */\nexport type PostOperationHookCallback = (\n resourceType: string,\n operationIdentifier: string,\n result: any,\n executionContext: ExecutionContext<any>,\n) => Promise<void>;\n\n/**\n * Callback type for pre-operation hooks.\n * Fired BEFORE the core mutation (CREATE/UPDATE/DELETE) on a resource.\n *\n * Observation + veto only — the return value is `void` (no mutation of\n * incoming `data` through the hook surface). To short-circuit the\n * operation, throw — errors propagate unchanged to the caller (plan\n * §Phase-3 decision P3-A=A1). To transform data, use the custom\n * operation's `prefixCoreOperations` hook instead.\n */\nexport type PreOperationHookCallback = (\n resourceType: string,\n operationIdentifier: string,\n data: any,\n executionContext: ExecutionContext<any>,\n) => Promise<void>;\n\n//============================================================================================================================\n//\n// Service Resource Backend Service\n//\n//============================================================================================================================\n\n\nexport class ServiceResourceBackendService<\n TCustomOperationEnum extends EnumLikeType | undefined = undefined,\n TCoreOperationEnum extends Partial<CoreResourceOperation> | undefined = undefined,\n TMainSchema extends z.ZodTypeAny = z.ZodTypeAny\n> {\n\n private readonly resourceConfiguration: ResourceConfiguration<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\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 resourcesRegistry: ResourcesRegistryBackendService,\n private readonly logger: LoggerService,\n private readonly errorBuilder: ErrorBuilderBackendService,\n private readonly repositoryHelper: ResourceOperationHelperBackendService,\n private readonly customImplRegistry: ResourceOperationCustomImplementationRegistryBackendService,\n private readonly repositoriesRegistry: RepositoriesRegistryHandlerBackendService,\n private readonly servicesRegistry: ServicesRegistryHandlerBackendService,\n private readonly externalApiHandler: ExternalApiHandlerBackendService,\n private readonly platformMutualizedHandler: PlatformMutualizedHandlerBackendService,\n private readonly serverlessServicesHandler: ServerlessServicesHandlerBackendService,\n private readonly notificationDispatcher: NotificationDispatcherService,\n private readonly populationService: ResourcePopulationBackendService,\n private readonly virtualFieldsService: VirtualFieldsBackendService,\n private readonly mongoDBService: MongoDBService,\n private readonly fileOperationHandler: FileOperationHandlerBackendService,\n private readonly fileFieldDetection: FileFieldDetectionBackendService,\n private readonly executionContextCreator: ExecutionContextCreatorBackendService,\n private readonly queueService: QueueBackendService,\n private readonly featureGate: FeatureGateBackendService,\n private readonly consumableTokenService: ConsumableTokenBackendService,\n private readonly appConfigService: AppConfigurationService,\n private readonly pdfGenerationOrchestrator: PdfGenerationOrchestratorBackendService,\n private readonly guidanceTriggerEvaluator?: GuidanceTriggerEvaluatorBackendService,\n private readonly milestoneEvaluator?: MilestoneEvaluatorBackendService,\n private readonly lifecycleEvaluator?: LifecycleEvaluatorBackendService,\n private readonly postgreSQLDatabaseService?: PostgreSQLDatabaseBackendService,\n private readonly resourcePersistenceUnitOfWork?:\n ResourcePersistenceUnitOfWorkBackendService,\n ) {\n this.operationsMap = new Map();\n\n this.resourceConfiguration = this.resourcesRegistry.getResourceConfiguration(resourceType);\n\n this.logDebug = this.logger.debugByType(`ServiceResource_${resourceType}`);\n this.logger.setDebugTypeLogging(`ServiceResource_${resourceType}`, false);\n\n this.initializeOperationsMap();\n\n this.logDebug('Service resource created', {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n operationsCount: this.operationsMap.size\n });\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 logger: LoggerService,\n errorBuilder: ErrorBuilderBackendService,\n repositoriesRegistry: RepositoriesRegistryHandlerBackendService,\n servicesRegistry: ServicesRegistryHandlerBackendService,\n resourcesRegistry: ResourcesRegistryBackendService,\n repositoryHelper: ResourceOperationHelperBackendService,\n customImplRegistry: ResourceOperationCustomImplementationRegistryBackendService,\n resourcePersistenceUnitOfWork: ResourcePersistenceUnitOfWorkBackendService,\n externalApiHandler: ExternalApiHandlerBackendService,\n platformMutualizedHandler: PlatformMutualizedHandlerBackendService,\n serverlessServicesHandler: ServerlessServicesHandlerBackendService,\n notificationDispatcher: NotificationDispatcherService,\n populationService: ResourcePopulationBackendService,\n virtualFieldsService: VirtualFieldsBackendService,\n mongoDBService: MongoDBService,\n fileOperationHandler: FileOperationHandlerBackendService,\n fileFieldDetection: FileFieldDetectionBackendService,\n executionContextCreator: ExecutionContextCreatorBackendService,\n queueService: QueueBackendService,\n featureGate: FeatureGateBackendService,\n consumableTokenService: ConsumableTokenBackendService,\n appConfigService: AppConfigurationService,\n pdfGenerationOrchestrator: PdfGenerationOrchestratorBackendService,\n guidanceTriggerEvaluator?: GuidanceTriggerEvaluatorBackendService,\n milestoneEvaluator?: MilestoneEvaluatorBackendService,\n lifecycleEvaluator?: LifecycleEvaluatorBackendService,\n postgreSQLDatabaseService?: PostgreSQLDatabaseBackendService,\n ): ServiceResourceBackendService<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> {\n\n return new ServiceResourceBackendService(\n resourceType, resourcesRegistry, logger,\n errorBuilder, repositoryHelper, customImplRegistry, repositoriesRegistry,\n servicesRegistry, externalApiHandler, platformMutualizedHandler,\n serverlessServicesHandler, notificationDispatcher,\n populationService, virtualFieldsService, mongoDBService,\n fileOperationHandler, fileFieldDetection,\n executionContextCreator,\n queueService,\n featureGate,\n consumableTokenService,\n appConfigService,\n pdfGenerationOrchestrator,\n guidanceTriggerEvaluator,\n milestoneEvaluator,\n lifecycleEvaluator,\n postgreSQLDatabaseService,\n resourcePersistenceUnitOfWork,\n );\n }\n\n public async applyRelationshipActionMany(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n request: ResourceRelationshipBulkActionRequest,\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const parsedRequest = ResourceRelationshipBulkActionRequestSchema.parse(request);\n let relationship: ResourceRelationship;\n try {\n relationship = this.getRelationshipForBulkAction(parsedRequest.relationshipField);\n } catch (error) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField: parsedRequest.relationshipField,\n resourceType,\n reason: describeCaughtError(error),\n },\n }\n );\n }\n const allowedActions = Resources_SharedUtils.resolveAllowedBulkRelationshipActionsForResource(\n relationship,\n resourceType\n );\n\n if (!allowedActions.includes(parsedRequest.action)) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField: parsedRequest.relationshipField,\n action: parsedRequest.action,\n resourceType,\n allowedActions,\n reason: 'Requested bulk relationship action is not allowed for this relationship from the current resource perspective',\n },\n }\n );\n }\n\n switch (parsedRequest.action) {\n case ResourceRelationshipBulkAction.SET:\n return this.applyReferenceSetActionMany(\n executionContext,\n id_or_ids_or_filter,\n relationship,\n parsedRequest.relationshipField,\n parsedRequest.targetId,\n options\n );\n case ResourceRelationshipBulkAction.CLEAR:\n return this.applyReferenceClearActionMany(\n executionContext,\n id_or_ids_or_filter,\n relationship,\n parsedRequest.relationshipField,\n options\n );\n case ResourceRelationshipBulkAction.CREATE:\n return this.applyCompositionCreateActionMany(\n executionContext,\n id_or_ids_or_filter,\n relationship,\n parsedRequest.relationshipField,\n parsedRequest.data,\n options\n );\n case ResourceRelationshipBulkAction.LINK:\n return this.applyAssociationLinkActionMany(\n executionContext,\n id_or_ids_or_filter,\n relationship,\n parsedRequest.relationshipField,\n parsedRequest.peerIds,\n options\n );\n case ResourceRelationshipBulkAction.UNLINK:\n return this.applyAssociationUnlinkActionMany(\n executionContext,\n id_or_ids_or_filter,\n relationship,\n parsedRequest.relationshipField,\n parsedRequest.peerIds,\n options\n );\n case ResourceRelationshipBulkAction.REPLACE:\n return this.applyAssociationReplaceActionMany(\n executionContext,\n id_or_ids_or_filter,\n relationship,\n parsedRequest.relationshipField,\n parsedRequest.peerIds,\n options\n );\n }\n }\n\n private async executeGeneratedRelationshipBulkOperation(\n resolvedOperation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n operation: { action: ResourceRelationshipBulkAction; relationshipField: string },\n executionContext: ExecutionContext<any>,\n data: any,\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n switch (operation.action) {\n case ResourceRelationshipBulkAction.SET: {\n const request = this.parseGeneratedRelationshipBulkOperationRequest(\n ResourceRelationshipBulkSetOperationRequestSchema,\n operation,\n data,\n executionContext\n );\n await this.assertGeneratedRelationshipBulkOperationEnabled(\n resolvedOperation,\n request,\n executionContext\n );\n return this.applyRelationshipActionMany(\n executionContext,\n this.resolveGeneratedRelationshipBulkSelector(request),\n {\n relationshipField: operation.relationshipField,\n action: ResourceRelationshipBulkAction.SET,\n targetId: request.targetId,\n },\n options\n );\n }\n case ResourceRelationshipBulkAction.CLEAR: {\n const request = this.parseGeneratedRelationshipBulkOperationRequest(\n ResourceRelationshipBulkClearOperationRequestSchema,\n operation,\n data,\n executionContext\n );\n await this.assertGeneratedRelationshipBulkOperationEnabled(\n resolvedOperation,\n request,\n executionContext\n );\n return this.applyRelationshipActionMany(\n executionContext,\n this.resolveGeneratedRelationshipBulkSelector(request),\n {\n relationshipField: operation.relationshipField,\n action: ResourceRelationshipBulkAction.CLEAR,\n },\n options\n );\n }\n case ResourceRelationshipBulkAction.CREATE: {\n const request = this.parseGeneratedRelationshipBulkOperationRequest(\n ResourceRelationshipBulkCreateOperationRequestSchema,\n operation,\n data,\n executionContext\n );\n await this.assertGeneratedRelationshipBulkOperationEnabled(\n resolvedOperation,\n request,\n executionContext\n );\n return this.applyRelationshipActionMany(\n executionContext,\n this.resolveGeneratedRelationshipBulkSelector(request),\n {\n relationshipField: operation.relationshipField,\n action: ResourceRelationshipBulkAction.CREATE,\n data: request.data,\n },\n options\n );\n }\n case ResourceRelationshipBulkAction.LINK: {\n const request = this.parseGeneratedRelationshipBulkOperationRequest(\n ResourceRelationshipBulkLinkOperationRequestSchema,\n operation,\n data,\n executionContext\n );\n await this.assertGeneratedRelationshipBulkOperationEnabled(\n resolvedOperation,\n request,\n executionContext\n );\n return this.applyRelationshipActionMany(\n executionContext,\n this.resolveGeneratedRelationshipBulkSelector(request),\n {\n relationshipField: operation.relationshipField,\n action: ResourceRelationshipBulkAction.LINK,\n peerIds: request.peerIds,\n },\n options\n );\n }\n case ResourceRelationshipBulkAction.UNLINK: {\n const request = this.parseGeneratedRelationshipBulkOperationRequest(\n ResourceRelationshipBulkUnlinkOperationRequestSchema,\n operation,\n data,\n executionContext\n );\n await this.assertGeneratedRelationshipBulkOperationEnabled(\n resolvedOperation,\n request,\n executionContext\n );\n return this.applyRelationshipActionMany(\n executionContext,\n this.resolveGeneratedRelationshipBulkSelector(request),\n {\n relationshipField: operation.relationshipField,\n action: ResourceRelationshipBulkAction.UNLINK,\n peerIds: request.peerIds,\n },\n options\n );\n }\n case ResourceRelationshipBulkAction.REPLACE: {\n const request = this.parseGeneratedRelationshipBulkOperationRequest(\n ResourceRelationshipBulkReplaceOperationRequestSchema,\n operation,\n data,\n executionContext\n );\n await this.assertGeneratedRelationshipBulkOperationEnabled(\n resolvedOperation,\n request,\n executionContext\n );\n return this.applyRelationshipActionMany(\n executionContext,\n this.resolveGeneratedRelationshipBulkSelector(request),\n {\n relationshipField: operation.relationshipField,\n action: ResourceRelationshipBulkAction.REPLACE,\n peerIds: request.peerIds,\n },\n options\n );\n }\n }\n }\n\n private parseGeneratedRelationshipBulkOperationRequest<T>(\n schema: z.ZodType<T>,\n operation: { action: ResourceRelationshipBulkAction; relationshipField: string },\n data: unknown,\n executionContext: ExecutionContext<any>\n ): T {\n try {\n return schema.parse(data);\n } catch (error) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n action: operation.action,\n relationshipField: operation.relationshipField,\n reason: describeCaughtError(error),\n },\n }\n );\n }\n }\n\n private resolveGeneratedRelationshipBulkSelector(\n request:\n | ResourceRelationshipBulkOperationSelector\n | ResourceRelationshipBulkSetOperationRequest\n | ResourceRelationshipBulkClearOperationRequest\n | ResourceRelationshipBulkCreateOperationRequest\n | ResourceRelationshipBulkLinkOperationRequest\n | ResourceRelationshipBulkUnlinkOperationRequest\n | ResourceRelationshipBulkReplaceOperationRequest\n ): IdOrIdsOrFilterType {\n if ('_ids' in request && Array.isArray(request._ids)) {\n return request._ids.length === 1 ? request._ids[0] : request._ids;\n }\n\n if ('filter' in request && request.filter) {\n return request.filter as IdOrIdsOrFilterType;\n }\n\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.BULK_RELATIONSHIP_SELECTOR_REQUIRED,\n });\n }\n\n private async assertGeneratedRelationshipBulkOperationEnabled(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n request:\n | ResourceRelationshipBulkSetOperationRequest\n | ResourceRelationshipBulkClearOperationRequest\n | ResourceRelationshipBulkCreateOperationRequest\n | ResourceRelationshipBulkLinkOperationRequest\n | ResourceRelationshipBulkUnlinkOperationRequest,\n executionContext: ExecutionContext<any>\n ): Promise<void> {\n if (!('enabledCondition' in operation) || !operation.enabledCondition) {\n return;\n }\n\n const selector = this.resolveGeneratedRelationshipBulkSelector(request);\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const singleSelectedId =\n Array.isArray(request._ids) && request._ids.length === 1\n ? request._ids[0]\n : undefined;\n\n const needs = extractFunctionContextNeeds(operation.enabledCondition);\n if (!singleSelectedId && needs.needsObjectContext) {\n throw this.errorBuilder.buildError(\n ErrorType.AUTHORIZATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_DISABLED,\n context: {\n reason: 'Generated bulk relationship operations with multi-target selectors cannot satisfy enabledCondition object-context requirements',\n operationIdentifier: String(operation.operationIdentifier),\n },\n }\n );\n }\n\n const currentObject = singleSelectedId\n ? await this.fetchCurrentObjectForOperation(\n CoreResourceOperation.UPDATE_MANY,\n resourceType,\n singleSelectedId,\n executionContext\n )\n : undefined;\n if (singleSelectedId && needs.needsObjectContext && !currentObject) {\n throw this.errorBuilder.buildError(\n ErrorType.AUTHORIZATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_DISABLED,\n context: {\n reason: 'Generated bulk relationship operations requiring object context cannot run when the selected current object cannot be loaded',\n operationIdentifier: String(operation.operationIdentifier),\n },\n }\n );\n }\n const { objectContext, initiatorUserContext } = await this.fetchContextsForOperationFunction(\n operation.enabledCondition,\n resourceType,\n currentObject,\n executionContext\n );\n // Generated bulk operations only have a persisted current object when the\n // selector is exactly one `_id`. Multi-target selectors deliberately fail\n // closed before this point if `needsObjectContext` is declared.\n const isEnabled = operation.enabledCondition({\n inputDto: request as any,\n currentObject: currentObject as any,\n objectContext,\n initiatorUserContext,\n initiatorIds: executionContext.initiatorIds,\n });\n\n if (!isEnabled) {\n throw this.errorBuilder.buildError(\n ErrorType.AUTHORIZATION,\n executionContext,\n { customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_DISABLED }\n );\n }\n }\n\n private resolveSingleSelectedId(\n id_or_ids_or_filter: IdOrIdsOrFilterType | undefined\n ): string | undefined {\n if (typeof id_or_ids_or_filter === 'string') {\n return id_or_ids_or_filter;\n }\n\n if (\n Array.isArray(id_or_ids_or_filter)\n && id_or_ids_or_filter.length === 1\n && typeof id_or_ids_or_filter[0] === 'string'\n ) {\n return id_or_ids_or_filter[0];\n }\n\n if (id_or_ids_or_filter && typeof id_or_ids_or_filter === 'object'\n && !Array.isArray(id_or_ids_or_filter)\n ) {\n if (\n 'id_or_ids' in id_or_ids_or_filter\n && Array.isArray(id_or_ids_or_filter.id_or_ids)\n && id_or_ids_or_filter.id_or_ids.length === 1\n && typeof id_or_ids_or_filter.id_or_ids[0] === 'string'\n ) {\n return id_or_ids_or_filter.id_or_ids[0];\n }\n\n if (\n 'ids' in id_or_ids_or_filter\n && Array.isArray(id_or_ids_or_filter.ids)\n && id_or_ids_or_filter.ids.length === 1\n && typeof id_or_ids_or_filter.ids[0] === 'string'\n ) {\n return id_or_ids_or_filter.ids[0];\n }\n }\n\n return undefined;\n }\n\n private resolveHookCurrentObject(\n coreOperation: CoreResourceOperation | undefined,\n currentObject: any,\n data: any\n ): any {\n return coreOperation === CoreResourceOperation.CREATE\n || coreOperation === CoreResourceOperation.CREATE_MANY\n ? data\n : currentObject;\n }\n\n private async resolveContextAddressedSingletonOperationTarget(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n coreOperation: CoreResourceOperation | undefined,\n resourceType: ResourceType,\n idOrIdsOrFilter: IdOrIdsOrFilterType | undefined,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<ContextAddressedSingletonOperationTarget | undefined> {\n const operationEffectiveIdentifier = operation.resourceOperationLike ?? operation.operationIdentifier;\n if (\n coreOperation !== CoreResourceOperation.READ\n && coreOperation !== CoreResourceOperation.UPDATE\n && coreOperation !== CoreResourceOperation.DELETE\n ) {\n return undefined;\n }\n\n if (\n operationEffectiveIdentifier !== CoreResourceOperation.READ\n && operationEffectiveIdentifier !== CoreResourceOperation.UPDATE\n && operationEffectiveIdentifier !== CoreResourceOperation.DELETE\n ) {\n return undefined;\n }\n\n // Resolve the context-addressed target for USER *and* MACHINE principals — both are EXTERNAL request\n // principals (scope-bound + role-checked) that address a context-addressed resource via the PARENT SCOPE\n // in the URL (e.g. `GET …/organizations/{orgId}/organization-webhook-config`, which carries no explicit\n // id). The original `USER_REQUEST`-only gate excluded machine tokens (ORGANIZATION_MACHINE/\n // APPLICATION_MACHINE), so a machine read of such a resource resolved NO id and failed\n // `repository_resource_operation_failed` (400). Machine principals now resolve it like a user;\n // INTERNAL/PUBLIC/WEBHOOK/ANONYMOUS/CONSUMABLE are still excluded (they must not reinterpret the parent\n // scope as identity), and role authorization + the tenant-scoped contextual filter still apply.\n if (!executionContext.isUserExecution() && !executionContext.isMachineExecution()) {\n return undefined;\n }\n\n if ('isBulkOperation' in operation && operation.isBulkOperation === true) {\n return undefined;\n }\n\n if (idOrIdsOrFilter !== undefined && idOrIdsOrFilter !== null) {\n return undefined;\n }\n\n if (!operation.resourceRelationships) {\n return undefined;\n }\n\n const candidates = getContextAddressedCompositionSingletonRelationshipCandidates(operation.resourceRelationships)\n .map((candidate) => {\n const parentResourceId = this.resolveParentContextResourceId(\n candidate.parentResourceType,\n candidate.foreignKeyField,\n executionContext\n );\n return parentResourceId\n ? { ...candidate, parentResourceId }\n : undefined;\n })\n .filter((candidate): candidate is {\n relationship: ResourceRelationship;\n foreignKeyField: string;\n parentResourceType: ResourceType;\n parentResourceId: string;\n } => candidate !== undefined);\n\n if (candidates.length === 0) {\n return undefined;\n }\n\n if (candidates.length > 1) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Ambiguous context-addressed singleton mutation target',\n resourceType,\n parentResourceTypes: candidates.map((candidate) => candidate.parentResourceType),\n },\n }\n );\n }\n\n const candidate = candidates[0];\n const selector = { [candidate.foreignKeyField]: candidate.parentResourceId };\n const repo = this.repositoriesRegistry.getRepository(resourceType);\n // Use `listForInternalScan` (NOT the public `list`), mirroring the controller-side\n // authorization probe: context-addressed singletons (e.g. `userProgressionState`)\n // expose only READ to users and declare NO user-facing LIST operation. This probe\n // is framework machinery proving uniqueness by parent FK, so it must scan\n // regardless of a declared LIST surface — `list` would throw\n // `repository_resource_operation_failed` (\"no default LIST operation declared\")\n // exactly on the absent-singleton READ path this resolver now serves.\n if (!repo) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Context-addressed singleton operation requires a registered repository to prove uniqueness',\n resourceType,\n },\n }\n );\n }\n\n const listResult = // `T` is pinned: the repository handle is schema-less here, so the strengthened\n // contract types rows as `unknown` rather than pretending to know them. This probe\n // only needs the persisted-id shape.\n await repo.listForInternalScan<Record<string, unknown>>(executionContext, selector, {\n ...options,\n paginated: false,\n });\n // The paginated-envelope unwrapping that used to live here is gone, not overlooked:\n // `paginated: false` selects the array overload, so the contract now states the shape\n // that the runtime always returned. The branch was unreachable and only looked\n // defensive because the call was cast to `any`.\n const matches = listResult;\n\n if (matches.length === 0) {\n // No singleton row exists yet for this parent scope.\n //\n // READ: do NOT treat absence as a target-resolution failure. Address the read\n // by the parent-scope `selector` so the core read returns null and a registered\n // POSTFIX materialization hook (scoped progression/guidance state) can\n // create-and-return the row. Without a hook the operation layer still emits\n // CONTROLLER_RESOURCE_NOT_FOUND after the null read — same outcome, correct layer.\n // The selector is derived from the execution context (auth/session-scoped, never\n // request input), so the read stays locked to the authenticated scope.\n //\n // UPDATE/DELETE: a mutation cannot be addressed to a non-existent singleton —\n // keep failing closed with not-found.\n if (coreOperation === CoreResourceOperation.READ) {\n return {\n addressedBy: 'parent-context',\n kind: 'absent-read-by-scope',\n selector,\n relationship: candidate.relationship,\n };\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.NOT_FOUND,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: {\n operation: coreOperation,\n selector,\n resourceType,\n },\n }\n );\n }\n\n if (matches.length > 1) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Context-addressed singleton mutation matched multiple rows',\n resourceType,\n selector,\n matchCount: matches.length,\n },\n }\n );\n }\n\n const currentObject = matches[0];\n const operationId = this.extractPersistedResourceId(currentObject);\n if (!operationId) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Context-addressed singleton operation resolved a row without _id',\n resourceType,\n selector,\n },\n }\n );\n }\n\n return {\n addressedBy: 'parent-context',\n kind: 'resolved',\n selector,\n currentObject,\n operationId,\n mutationId: operationId,\n relationship: candidate.relationship,\n };\n }\n\n private async resolveContextAddressedAssociationOperationTarget(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n coreOperation: CoreResourceOperation | undefined,\n resourceType: ResourceType,\n idOrIdsOrFilter: IdOrIdsOrFilterType | undefined,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<ContextAddressedAssociationOperationTarget | undefined> {\n const operationEffectiveIdentifier = operation.resourceOperationLike ?? operation.operationIdentifier;\n if (\n coreOperation !== CoreResourceOperation.READ\n && coreOperation !== CoreResourceOperation.UPDATE\n && coreOperation !== CoreResourceOperation.DELETE\n ) {\n return undefined;\n }\n\n if (\n operationEffectiveIdentifier !== CoreResourceOperation.READ\n && operationEffectiveIdentifier !== CoreResourceOperation.UPDATE\n && operationEffectiveIdentifier !== CoreResourceOperation.DELETE\n ) {\n return undefined;\n }\n\n // Resolve the context-addressed target for USER *and* MACHINE principals — both are EXTERNAL request\n // principals (scope-bound + role-checked) that address a context-addressed resource via the PARENT SCOPE\n // in the URL (e.g. `GET …/organizations/{orgId}/organization-webhook-config`, which carries no explicit\n // id). The original `USER_REQUEST`-only gate excluded machine tokens (ORGANIZATION_MACHINE/\n // APPLICATION_MACHINE), so a machine read of such a resource resolved NO id and failed\n // `repository_resource_operation_failed` (400). Machine principals now resolve it like a user;\n // INTERNAL/PUBLIC/WEBHOOK/ANONYMOUS/CONSUMABLE are still excluded (they must not reinterpret the parent\n // scope as identity), and role authorization + the tenant-scoped contextual filter still apply.\n if (!executionContext.isUserExecution() && !executionContext.isMachineExecution()) {\n return undefined;\n }\n\n if ('isBulkOperation' in operation && operation.isBulkOperation === true) {\n return undefined;\n }\n\n if (idOrIdsOrFilter !== undefined && idOrIdsOrFilter !== null) {\n return undefined;\n }\n\n if (!operation.resourceRelationships) {\n return undefined;\n }\n\n const associationParentRelationships = (operation.resourceRelationships.parentRelationships ?? [])\n .filter((relationship) =>\n relationship.nature === RelationshipNature.ASSOCIATION\n && relationship.jointResourceType === resourceType\n && relationship.resourceType2 === resourceType\n && relationship.cardinality1 === ResourceRelationshipCardinality.ONE\n && relationship.cardinality2 === ResourceRelationshipCardinality.MANY\n );\n if (associationParentRelationships.length === 0) {\n return undefined;\n }\n\n if (associationParentRelationships.length !== 2) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Complete association-context operation target requires exactly two eligible parent relationships',\n resourceType,\n parentResourceTypes: associationParentRelationships.map((relationship) => relationship.resourceType1),\n },\n },\n );\n }\n\n const duplicatedParentResourceTypes = new Set(\n associationParentRelationships.map((relationship) => relationship.resourceType1)\n .filter((resourceType, _index, resourceTypes) =>\n resourceTypes.filter((candidate) => candidate === resourceType).length > 1\n )\n );\n const contextParents = associationParentRelationships\n .map((relationship) => {\n const foreignKeyField = this.resourcesRegistry.resolveForeignKeyField({\n resourceType1: relationship.resourceType1,\n foreignKeyField: relationship.foreignKeyField,\n });\n const parentResourceId = this.resolveAssociationParentContextResourceId(\n relationship.resourceType1,\n foreignKeyField,\n executionContext,\n { allowGenericParentContext: !duplicatedParentResourceTypes.has(relationship.resourceType1) },\n );\n return parentResourceId\n ? { relationship, foreignKeyField, parentResourceId }\n : undefined;\n })\n .filter((candidate): candidate is {\n relationship: ResourceRelationship;\n foreignKeyField: string;\n parentResourceId: string;\n } => candidate !== undefined);\n\n if (contextParents.length < 2) {\n return undefined;\n }\n\n const selector = Object.fromEntries(\n contextParents.map((candidate) => [candidate.foreignKeyField, candidate.parentResourceId])\n );\n if (Object.keys(selector).length !== contextParents.length) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Complete association-context operation target resolved duplicate foreign key fields',\n resourceType,\n foreignKeyFields: contextParents.map((candidate) => candidate.foreignKeyField),\n },\n },\n );\n }\n\n const repo = this.repositoriesRegistry.getRepository(resourceType);\n // Framework-internal uniqueness probe — resolve the junction row's id by its\n // two parent FKs to address a context-addressed READ/UPDATE/DELETE. Use\n // `listForInternalScan` (NOT the public `list`), mirroring the singleton\n // resolver above and the controller-side association authorization probe: an\n // association junction resource may expose READ/UPDATE/DELETE without declaring\n // a user-facing default LIST, in which case `repo.list()` throws\n // `repository_resource_operation_failed` (\"no default LIST operation declared\",\n // INTERNAL/critical 500). `listForInternalScan` synthesizes a REPOSITORY_ONLY\n // scan when no LIST is declared and reuses the declared LIST (with its hooks)\n // otherwise, so this swap removes the latent 500 without changing behavior for\n // junctions that DO expose LIST. Unlike singletons, an absent junction row is a\n // genuine not-found (no lazy materialization), so the 0-rows branch below still\n // fails closed with NOT_FOUND for every verb.\n if (!repo) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Complete association-context operation requires a registered repository to prove uniqueness',\n resourceType,\n },\n },\n );\n }\n\n const listResult = // `T` is pinned: the repository handle is schema-less here, so the strengthened\n // contract types rows as `unknown` rather than pretending to know them. This probe\n // only needs the persisted-id shape.\n await repo.listForInternalScan<Record<string, unknown>>(executionContext, selector, {\n ...options,\n paginated: false,\n });\n // The paginated-envelope unwrapping that used to live here is gone, not overlooked:\n // `paginated: false` selects the array overload, so the contract now states the shape\n // that the runtime always returned. The branch was unreachable and only looked\n // defensive because the call was cast to `any`.\n const matches = listResult;\n\n if (matches.length === 0) {\n throw this.errorBuilder.buildError(\n ErrorType.NOT_FOUND,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: {\n operation: coreOperation,\n selector,\n resourceType,\n },\n },\n );\n }\n\n if (matches.length > 1) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Complete association-context operation matched multiple rows',\n resourceType,\n selector,\n matchCount: matches.length,\n },\n },\n );\n }\n\n const currentObject = matches[0];\n const operationId = this.extractPersistedResourceId(currentObject);\n if (!operationId) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Complete association-context operation resolved a row without _id',\n resourceType,\n selector,\n },\n },\n );\n }\n\n return {\n addressedBy: 'association-complete-context',\n selector,\n currentObject,\n operationId,\n mutationId: operationId,\n relationships: contextParents.map((candidate) => candidate.relationship),\n };\n }\n\n private resolveContextAddressedSingletonMutationTarget(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n coreOperation: CoreResourceOperation | undefined,\n resourceType: ResourceType,\n idOrIdsOrFilter: IdOrIdsOrFilterType | undefined,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<ContextAddressedSingletonOperationTarget | undefined> {\n return this.resolveContextAddressedSingletonOperationTarget(\n operation,\n coreOperation,\n resourceType,\n idOrIdsOrFilter,\n executionContext,\n options,\n );\n }\n\n private resolveContextAddressedAssociationMutationTarget(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n coreOperation: CoreResourceOperation | undefined,\n resourceType: ResourceType,\n idOrIdsOrFilter: IdOrIdsOrFilterType | undefined,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<ContextAddressedAssociationOperationTarget | undefined> {\n return this.resolveContextAddressedAssociationOperationTarget(\n operation,\n coreOperation,\n resourceType,\n idOrIdsOrFilter,\n executionContext,\n options,\n );\n }\n\n private resolveParentContextResourceId(\n parentResourceType: ResourceType,\n foreignKeyField: string,\n executionContext: ExecutionContext<any>\n ): string | undefined {\n const byForeignKey = executionContext.getContextResourceId(foreignKeyField);\n if (byForeignKey) {\n return byForeignKey;\n }\n\n const relationshipContext = executionContext.getRelationshipContext(\n parentResourceType,\n foreignKeyField,\n ) ?? executionContext.getRelationshipContext(parentResourceType);\n if (relationshipContext?.resourceId) {\n return relationshipContext.resourceId;\n }\n\n const parentConfig = this.resourcesRegistry.tryGetResourceConfiguration(\n parentResourceType\n );\n if (!parentConfig) {\n return undefined;\n }\n\n return executionContext.getContextResourceId(parentConfig.resourceFieldIdentifier);\n }\n\n private resolveAssociationParentContextResourceId(\n parentResourceType: ResourceType,\n foreignKeyField: string,\n executionContext: ExecutionContext<any>,\n options?: { allowGenericParentContext?: boolean },\n ): string | undefined {\n const byForeignKey = executionContext.getContextResourceId(foreignKeyField);\n if (byForeignKey) {\n return byForeignKey;\n }\n\n const relationshipContext = executionContext.getRelationshipContext(\n parentResourceType,\n foreignKeyField,\n );\n if (relationshipContext?.resourceId) {\n return relationshipContext.resourceId;\n }\n\n if (options?.allowGenericParentContext !== true) {\n return undefined;\n }\n\n const genericRelationshipContext = executionContext.getRelationshipContext(parentResourceType);\n if (genericRelationshipContext?.resourceId) {\n return genericRelationshipContext.resourceId;\n }\n\n const parentConfig = this.resourcesRegistry.tryGetResourceConfiguration(parentResourceType);\n return parentConfig\n ? executionContext.getContextResourceId(parentConfig.resourceFieldIdentifier)\n : undefined;\n }\n\n private extractPersistedResourceId(currentObject: Record<string, unknown>): string | undefined {\n const id = currentObject._id;\n if (typeof id === 'string') {\n return id;\n }\n if (id && typeof id === 'object' && 'toString' in id && typeof id.toString === 'function') {\n return id.toString();\n }\n return undefined;\n }\n\n private hasContextAddressedSingletonParentScope(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n ): boolean {\n if (!operation.resourceRelationships) {\n return false;\n }\n\n return getContextAddressedCompositionSingletonRelationshipCandidates(operation.resourceRelationships)\n .some((candidate) => this.resolveParentContextResourceId(\n candidate.parentResourceType,\n candidate.foreignKeyField,\n executionContext,\n ) !== undefined);\n }\n\n private hasContextAddressedAssociationParentScope(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n ): boolean {\n if (!operation.resourceRelationships) {\n return false;\n }\n\n const operationResourceType = operation.resourceIdentifier as ResourceType | undefined;\n if (!operationResourceType) {\n return false;\n }\n\n const associationParentRelationships = (operation.resourceRelationships.parentRelationships ?? [])\n .filter((relationship) =>\n relationship.nature === RelationshipNature.ASSOCIATION\n && relationship.jointResourceType === operationResourceType\n && relationship.resourceType2 === operationResourceType\n && relationship.cardinality1 === ResourceRelationshipCardinality.ONE\n && relationship.cardinality2 === ResourceRelationshipCardinality.MANY\n );\n if (associationParentRelationships.length !== 2) {\n return false;\n }\n\n const duplicatedParentResourceTypes = new Set(\n associationParentRelationships.map((relationship) => relationship.resourceType1)\n .filter((resourceType, _index, resourceTypes) =>\n resourceTypes.filter((candidate) => candidate === resourceType).length > 1\n )\n );\n\n return associationParentRelationships.every((relationship) => {\n const foreignKeyField = this.resourcesRegistry.resolveForeignKeyField({\n resourceType1: relationship.resourceType1,\n foreignKeyField: relationship.foreignKeyField,\n });\n return this.resolveAssociationParentContextResourceId(\n relationship.resourceType1,\n foreignKeyField,\n executionContext,\n { allowGenericParentContext: !duplicatedParentResourceTypes.has(relationship.resourceType1) },\n ) !== undefined;\n });\n }\n\n /**\n * Refuse a core UPDATE that ATTEMPTS TO CHANGE a read-only (`.excludeFromUpdate()`) field.\n *\n * Such a field is stripped from the UPDATE request DTO, so a raw `PUT` that sends a NEW value for it\n * — e.g. `PUT /users/{id} { status: 'SUSPENDED' }`, where `status` is a lifecycle field written only\n * through `suspend_user` / `updateAsSystem` — currently strips it and answers `2xx` having changed\n * nothing: the \"answered success, did nothing\" defect this repository treats as worse than an error.\n * The client believes it changed the field; it did not. This turns the silent no-op into an explicit\n * `4xx` so the caller learns the field is not editable through the core update.\n *\n * Runs for BOTH the single `UPDATE` and the bulk `UPDATE_MANY` core operations — the controller\n * re-attaches read-only fields for both, so the guard must cover both or the sibling bulk path keeps\n * the silent no-op (see `.claude/rules/invariant-call-site-enumeration.md`). The two arms differ:\n * - **single (`isBulkUpdate = false`)**: compared against the ALREADY-FETCHED `currentObject` (no extra\n * read) — a payload that merely ECHOES the field at its current value is fine (the common \"PUT the\n * whole object back\" flow) and is NOT refused, only a genuine CHANGE is.\n * - **bulk (`isBulkUpdate = true`)**: there is no single stored row to echo-compare against, and a bulk\n * write sets one value across every matching row, so the mere PRESENCE of a non-exempt read-only\n * field is refused.\n *\n * Trusted system writers are EXEMPT via {@link isWriteIntegrityExemptExecution}: `updateAsSystem` (how\n * `status` is LEGITIMATELY written), seeds, webhooks and anonymous writes go through the system door\n * and re-attach these fields on purpose. Server-injected authoritative writes (a lifecycle verb's\n * prefix hook, carried via `options.preserveServerInjectedFields`) are also skipped. Discriminated-union\n * / non-object mainSchemas are skipped (no flat field set to inspect).\n *\n * LIMITATION: for a read-only field whose value is a plain OBJECT or ARRAY, the single-row echo compare\n * falls back to `stringifyPersistedValueForCompare` (`\"[object Object]\"`), so two distinct object values read\n * as equal and a genuine change is NOT refused — it degrades to the pre-existing silent no-op rather than\n * a loud `4xx`. Bounded: the repository's strict re-parse still strips the field so nothing persists;\n * only the \"loud refusal\" guarantee is unmet, and only for non-scalar read-only fields (ids / enums /\n * dates / version numbers — the overwhelming majority — are handled). The bulk arm is unaffected (it is\n * presence-based, not value-based).\n */\n private async assertNoForbiddenReadOnlyFieldChange(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n target: IdOrIdsOrFilterType | undefined,\n inputData: unknown,\n currentObject: unknown,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n isBulkUpdate = false,\n ): Promise<void> {\n if (isWriteIntegrityExemptExecution(executionContext, options)) return;\n if (!inputData || typeof inputData !== 'object') return;\n // The RESOURCE's full mainSchema (carries the `.excludeFromUpdate()` fields) — NOT `operation.mainSchema`,\n // which for a core UPDATE operation can be a per-operation / request-shaped schema that has already\n // dropped them, so the read-only fields would be invisible here.\n const mainSchema = this.resourceConfiguration.mainSchema as z.ZodTypeAny;\n if (!isZodObject(mainSchema)) return;\n const inputRecord = inputData as Record<string, unknown>;\n\n // Which read-only fields does THIS payload actually carry a value for? The overwhelming majority of\n // updates touch none, so this presence check runs first and the (possible) read below never happens\n // for them. Fields a custom operation AUTHORITATIVELY injected are skipped: a lifecycle verb\n // (`request-deletion`, `suspend`, `activate`, …) sets `status` / `deletionRequestedAt` through its\n // prefix hook and carries them past the repository's strict re-parse via `preserveServerInjectedFields`\n // — legitimate SERVER writes, not a client editing a read-only field. A CLIENT-supplied value\n // (re-attached from the request body by the controller) is NOT in that allow-list, so it is caught.\n // Decision logic is in `collectCandidateReadOnlyFields` / `filterChangedReadOnlyFields` so it can be\n // unit-pinned on both arms (see `read-only-field-change.backend.utils`).\n const serverInjectedFields = new Set(options?.preserveServerInjectedFields ?? []);\n const candidateFields = collectCandidateReadOnlyFields(mainSchema, inputRecord, serverInjectedFields);\n if (candidateFields.length === 0) return;\n\n // ── Bulk (UPDATE_MANY): refuse on PRESENCE ────────────────────────────────────────────────────\n // A filter- or id-set-addressed bulk update has no single stored row to echo-compare against, and a\n // bulk write is a partial \"set field = V on every matching row\". Applying ONE value to a read-only\n // field across many rows (whose stored values differ) is inherently a CHANGE, never the \"PUT the\n // whole object back\" echo the single-row path tolerates — so the mere PRESENCE of a non-exempt\n // read-only field is refused. Without this, the controller RE-ATTACHES read-only fields for\n // UPDATE_MANY too (so the service can see them), they flow to `_doUpdateMany`'s strict re-parse, get\n // stripped, and reproduce the silent-2xx-no-op on the bulk path — the sibling-call-site miss this\n // guard exists to prevent (see `.claude/rules/invariant-call-site-enumeration.md`).\n if (isBulkUpdate) {\n throw this.buildReadOnlyFieldNotEditableError(operation, executionContext, candidateFields);\n }\n\n // ── Single (UPDATE): compare against the stored row; a pure ECHO of the current value is allowed ─\n // Reuse the already-fetched `currentObject` when a hook needed it; otherwise read it now — a cost\n // paid ONLY on the rare update that carries a read-only field.\n let stored = (currentObject && typeof currentObject === 'object') ? (currentObject as Record<string, unknown>) : undefined;\n if (!stored) {\n const id = this.resolveSingleSelectedId(target);\n if (!id) return; // population/filter-addressed update — no single stored row to compare against here\n const repository = this.repositoriesRegistry.getRepository(this.resourceConfiguration.resourceIdentifier as ResourceType);\n if (!repository || typeof (repository as any).read !== 'function') return;\n try {\n const readResult = await (repository as any).read(executionContext, id, options);\n stored = (readResult && typeof readResult === 'object' && !Array.isArray(readResult)) ? readResult : undefined;\n } catch {\n return; // an unreadable target fails the update itself downstream (404); do not mask that here\n }\n if (!stored) return;\n }\n\n const forbiddenFields = filterChangedReadOnlyFields(candidateFields, inputRecord, stored);\n if (forbiddenFields.length === 0) return;\n\n throw this.buildReadOnlyFieldNotEditableError(operation, executionContext, forbiddenFields);\n }\n\n /**\n * The shared `4xx` for a client attempt to write a read-only (`.excludeFromUpdate()`) field — used by\n * both the single-row (CHANGE detected) and bulk (field PRESENT) arms of\n * {@link assertNoForbiddenReadOnlyFieldChange} so the two paths cannot drift in shape.\n */\n private buildReadOnlyFieldNotEditableError(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n forbiddenFields: string[],\n ) {\n return this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n reason: 'read_only_field_not_editable',\n resourceIdentifier: this.resourceConfiguration.resourceIdentifier,\n operationIdentifier: operation.operationIdentifier,\n forbiddenFields,\n },\n });\n }\n\n private ensureExplicitMutationTargetMatchesContext(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n coreOperation: CoreResourceOperation | undefined,\n idOrIdsOrFilter: IdOrIdsOrFilterType | undefined,\n currentObject: Record<string, unknown> | undefined,\n executionContext: ExecutionContext<any>,\n ): void {\n if (\n coreOperation !== CoreResourceOperation.READ\n && coreOperation !== CoreResourceOperation.UPDATE\n && coreOperation !== CoreResourceOperation.DELETE\n ) {\n return;\n }\n\n if (typeof idOrIdsOrFilter !== 'string' || !currentObject || !operation.resourceRelationships) {\n return;\n }\n\n const expectedSelectors: Record<string, string> = {};\n for (const candidate of getContextAddressedCompositionSingletonRelationshipCandidates(operation.resourceRelationships)) {\n const parentResourceId = this.resolveParentContextResourceId(\n candidate.parentResourceType,\n candidate.foreignKeyField,\n executionContext,\n );\n if (parentResourceId) {\n expectedSelectors[candidate.foreignKeyField] = parentResourceId;\n }\n }\n\n const associationParentRelationships = (operation.resourceRelationships.parentRelationships ?? [])\n .filter((relationship) =>\n relationship.nature === RelationshipNature.ASSOCIATION\n && relationship.jointResourceType === operation.resourceIdentifier\n && relationship.resourceType2 === operation.resourceIdentifier\n && relationship.cardinality1 === ResourceRelationshipCardinality.ONE\n && relationship.cardinality2 === ResourceRelationshipCardinality.MANY\n );\n const duplicatedParentResourceTypes = new Set(\n associationParentRelationships.map((relationship) => relationship.resourceType1)\n .filter((resourceType, _index, resourceTypes) =>\n resourceTypes.filter((candidate) => candidate === resourceType).length > 1\n )\n );\n\n // The resource's PRIMARY-SCOPE foreign key (e.g. `organizationId` on an\n // organization-scoped resource) is a LEGITIMATE single-peer addressing\n // context, NOT a partial association. A scope route nests the resource under\n // its primary scope (`/organizations/:orgId/organization-members/:id`) and\n // the explicit `_id` already addresses the row unambiguously within that\n // scope. When an association resource's primary scope COINCIDES with one of\n // its two association peers — the org↔user `organizationMembers` junction is\n // the canonical case, where `organizationId` is BOTH the primary scope AND\n // an association peer — that peer must NOT gate \"complete association\n // context\" completeness. Otherwise a scope-bounded explicit-`_id`\n // read/update/delete (and every custom op that is `resourceOperationLike:\n // UPDATE`, e.g. promote/demote/suspend) fails closed merely because the\n // OTHER, non-primary peer (`userId`) is absent from the route — even though\n // the primary-scope peer is still validated below against `currentObject`\n // and the row is uniquely addressed. Only NON-primary-scope peers gate\n // completeness; the primary-scope peer is always validated (it stays in\n // `expectedSelectors`) but never requires its sibling peer to be present.\n const primaryScopeFieldIdentifier = operation.resourcePrimaryScope\n ? PRIMARY_SCOPE_TO_FIELD_IDENTIFIER[operation.resourcePrimaryScope]\n : undefined;\n\n let resolvedAssociationContextCount = 0;\n let nonPrimaryScopeAssociationParentCount = 0;\n let resolvedNonPrimaryScopeAssociationContextCount = 0;\n const associationForeignKeyFields = associationParentRelationships.map((relationship) =>\n this.resourcesRegistry.resolveForeignKeyField({\n resourceType1: relationship.resourceType1,\n foreignKeyField: relationship.foreignKeyField,\n })\n );\n\n for (const relationship of associationParentRelationships) {\n const foreignKeyField = this.resourcesRegistry.resolveForeignKeyField({\n resourceType1: relationship.resourceType1,\n foreignKeyField: relationship.foreignKeyField,\n });\n const isPrimaryScopePeer =\n primaryScopeFieldIdentifier !== undefined\n && foreignKeyField === primaryScopeFieldIdentifier;\n if (!isPrimaryScopePeer) {\n nonPrimaryScopeAssociationParentCount += 1;\n }\n const parentResourceId = this.resolveAssociationParentContextResourceId(\n relationship.resourceType1,\n foreignKeyField,\n executionContext,\n { allowGenericParentContext: !duplicatedParentResourceTypes.has(relationship.resourceType1) },\n );\n if (parentResourceId) {\n resolvedAssociationContextCount += 1;\n if (!isPrimaryScopePeer) {\n resolvedNonPrimaryScopeAssociationContextCount += 1;\n }\n expectedSelectors[foreignKeyField] = parentResourceId;\n }\n }\n\n if (\n associationParentRelationships.length > 0\n && associationParentRelationships.length !== 2\n && resolvedAssociationContextCount > 0\n ) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operation: coreOperation,\n id_or_ids_or_filter: idOrIdsOrFilter,\n reason: 'Explicit association id has malformed complete-association metadata',\n parentResourceTypes: associationParentRelationships.map((relationship) => relationship.resourceType1),\n resolvedAssociationContextCount,\n },\n });\n }\n\n // Fail closed ONLY for a genuinely partial association context: some — but\n // not all — of the NON-primary-scope peers are present. A primary-scope-only\n // context (the common `/organizations/:orgId/organization-members/:id` route)\n // is NOT partial — the primary-scope peer is validated against `currentObject`\n // below and the explicit `_id` uniquely addresses the row, so it falls\n // through to the per-selector validation. When the resource has no\n // primary-scope peer, `nonPrimaryScopeAssociationParentCount` equals the full\n // peer count, preserving the original all-or-nothing fail-closed behavior.\n if (\n associationParentRelationships.length === 2\n && resolvedNonPrimaryScopeAssociationContextCount > 0\n && resolvedNonPrimaryScopeAssociationContextCount < nonPrimaryScopeAssociationParentCount\n ) {\n throw this.errorBuilder.buildError(ErrorType.NOT_FOUND, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: {\n operation: coreOperation,\n id_or_ids_or_filter: idOrIdsOrFilter,\n reason: 'Explicit association id is scoped by only part of a complete association context',\n expectedForeignKeyFields: associationForeignKeyFields,\n },\n });\n }\n\n for (const [foreignKeyField, expectedValue] of Object.entries(expectedSelectors)) {\n const actualValue = stringifyPersistedValueForCompare(currentObject[foreignKeyField]);\n if (actualValue !== expectedValue) {\n throw this.errorBuilder.buildError(ErrorType.NOT_FOUND, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: {\n operation: coreOperation,\n id_or_ids_or_filter: idOrIdsOrFilter,\n foreignKeyField,\n missingForeignKey: actualValue === undefined,\n },\n });\n }\n }\n }\n\n /**\n * The ONE canonical \"is this dispatch a BULK update?\" discriminant, shared by everything that must\n * branch on it — the read-only-field write guard and the bulk-hook object-context check.\n *\n * A `haveBulkOperation` variant reaches the persistence switch as `coreOperation === UPDATE` with\n * `isBulkOperation === true` (its `operationIdentifier` is `UPDATE`, so\n * `getCoreResourceOperationFromOperation` returns `UPDATE`); a plain / relationship `UPDATE_MANY`\n * reaches it as `coreOperation === UPDATE_MANY`. BOTH are bulk. Keeping this in one method is\n * deliberate: the read-only guard once re-derived it inline and covered only the `UPDATE_MANY` case,\n * so the guard silently skipped the `haveBulkOperation` path — the sibling-call-site drift\n * `.claude/rules/invariant-call-site-enumeration.md` #8 is written to prevent.\n */\n private isBulkUpdateCoreOperation(\n coreOperation: CoreResourceOperation | undefined,\n isBulkOperation: boolean | undefined,\n ): boolean {\n return coreOperation === CoreResourceOperation.UPDATE_MANY\n || (coreOperation === CoreResourceOperation.UPDATE && isBulkOperation === true);\n }\n\n private assertBulkHookObjectContextAvailability(\n coreOperation: CoreResourceOperation | undefined,\n isBulkOperation: boolean | undefined,\n fn: ResourceConfiguration_FunctionWithContextNeeds<any> | undefined,\n currentObject: any,\n executionContext: ExecutionContext<any>,\n operationIdentifier: string,\n hookName: 'enabledCondition' | 'basicPrefixOperation'\n ): void {\n if (!this.isBulkUpdateCoreOperation(coreOperation, isBulkOperation)) {\n return;\n }\n\n const needs = extractFunctionContextNeeds(fn);\n if (!needs.needsObjectContext || currentObject) {\n return;\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.AUTHORIZATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_DISABLED,\n context: {\n reason: `${hookName} requires object context, but this bulk update cannot provide a single persisted current object`,\n operationIdentifier,\n },\n }\n );\n }\n\n\n private initializeOperationsMap(): void {\n if (!this.resourceConfiguration.operations) {\n return;\n }\n\n // Include operations that should be handled by services\n const serviceOperations = this.resourceConfiguration.operations.filter(\n (op): op is ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> =>\n op.variantType === ResourceOperationVariantType.INTERNAL_CALL ||\n op.variantType === ResourceOperationVariantType.API_CALL ||\n op.variantType === ResourceOperationVariantType.CRON_JOB ||\n op.variantType === ResourceOperationVariantType.BATCH_JOB\n );\n\n serviceOperations.forEach(operation => {\n const operationKey = ResourcesConfig_OperationPathUtils.createOperationPathKeyFromOperation(operation as any);\n this.operationsMap.set(operationKey, operation);\n });\n\n this.logDebug('Service operations map initialized', {\n totalOperations: this.resourceConfiguration.operations.length,\n serviceOperations: serviceOperations.length\n });\n }\n\n\n\n\n /**\n * Entry point from registry convenience methods (`create`, `update`, `delete`, etc.)\n * and controller-level `doByOperationPath`.\n *\n * Resolves `operation` from this handler's `operationsMap`. The caller's\n * `executionContext.operation` may point to a DIFFERENT operation (e.g., a parent's\n * operation or a generic webhook operation). `doOperation()` corrects this mismatch\n * via Correction Point 1 before any pipeline logic executes.\n */\n public async doByOperationPath(\n operationPath: ResourceConfiguration_OperationPath<TCustomOperationEnum, TCoreOperationEnum>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n data?: any,\n options?: RepositoryOptions\n ): Promise<any> {\n const operationKey = ResourcesConfig_OperationPathUtils.createOperationPathKey(operationPath);\n const operation = this.operationsMap.get(operationKey);\n\n if (!operation) {\n // CONFIGURATION, not NOT_FOUND — the service tier's copy of the same structural fault the\n // repositories carry: an operation path this resource service does not declare.\n const error = this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Requested service operation path is not registered for this resource service.',\n resourceType: this.resourceConfiguration.resourceIdentifier,\n operationPath,\n operationKey,\n id_or_ids_or_filter,\n },\n }\n );\n throw error;\n }\n\n this.logDebug('Executing operation by path', {\n operationPath,\n operationKey,\n resourceType: this.resourceConfiguration.resourceIdentifier,\n id_or_ids_or_filter\n });\n\n return this.doOperation(operation, executionContext, id_or_ids_or_filter, data, options);\n }\n\n\n /**\n * Entry point from controller-level `doByExecutionContext`.\n *\n * Reads `operation` directly from `executionContext.operation` — guaranteed to match\n * (same object reference). `doOperation()` correction points are no-ops in this path.\n * Context-addressed singleton / complete-association resolution is deliberately\n * USER_REQUEST-only. Internal contexts must already carry the concrete\n * persisted child/junction id; they are not allowed to reinterpret parent\n * context as mutation identity.\n */\n public async doByExecutionContext(\n executionContext: ExecutionContext<ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>>,\n data?: any,\n options?: RepositoryOptions\n ): Promise<any> {\n const operation = executionContext.operation;\n\n // Extract IDs based on resourceFieldIdentifier from execution context\n const id_or_ids_or_filter = this.repositoryHelper.extractIdsFromExecutionContext(executionContext, this.resourceConfiguration.resourceFieldIdentifier);\n\n this.logDebug('Executing operation by execution context', {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n operationIdentifier: operation.operationIdentifier,\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 public resolveOperationForDataMode(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n dataMode: DataMode | undefined,\n ): ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> {\n if (!dataMode || dataMode === DataMode.RAW) {\n return operation;\n }\n\n return this.resolveOperationVariant(operation, dataMode);\n }\n\n /**\n * Helper method to fetch contexts for operation functions (enabledCondition, basicPrefixOperation).\n * Fetches objectContext and userContext only when needed based on function flags.\n *\n * @param fn - Function with optional context needs flags\n * @param resourceType - Resource type for context fetching\n * @param currentObject - Current object (fetched if needed for UPDATE/DELETE)\n * @param executionContext - Execution context\n * @returns Object with objectContext, userContext, and resolved currentObject\n */\n private async fetchContextsForOperationFunction(\n fn: ResourceConfiguration_FunctionWithContextNeeds<any> | undefined,\n resourceType: ResourceType,\n currentObject: any,\n executionContext: ExecutionContext<any>,\n repositoryOptions?: RepositoryOptions,\n ): Promise<{ objectContext?: any; initiatorUserContext?: any; currentObject: any }> {\n const needs = extractFunctionContextNeeds(fn);\n let objectContext: any = undefined;\n let initiatorUserContext: any = undefined;\n\n if (needs.needsObjectContext) {\n const resourceNeeds = this.populationService.analyzeContextNeeds(resourceType);\n const computationContext = await this.populationService.fetchComputationContext(\n resourceType,\n currentObject || {},\n resourceNeeds,\n executionContext,\n repositoryOptions,\n ComputationContextFailureMode.PROPAGATE,\n );\n objectContext = computationContext.objectContext;\n }\n\n // Initiator user context — provided UNCONDITIONALLY (not gated on\n // `needs.needsUserContext`), mirroring the frontend evaluator which always\n // injects `initiatorUserContext` when a user is present\n // (`operation-enabled-condition.frontend.utils.ts`). Two bugs converged here\n // before this:\n //\n // 1. Phantom read: `ExecutionContext` has NO `.user` property (identity is\n // exposed as `executionContext.userId`, from `initiatorIds.userId`). The\n // former `(executionContext as any).user` cast resolved to `undefined`\n // on every request, so `initiatorUserContext?._id` was always undefined.\n // 2. Gating asymmetry: the backend only populated it when the operation\n // function carried a manually-attached `needsUserContext = true` flag,\n // while the frontend supplies it ungated.\n //\n // Together they made any owner-scoped condition (e.g. todos `change_status`\n // member variant: `currentObject.assignedToUserId === initiatorUserContext?._id`)\n // pass on the frontend (button shown enabled) yet fail on the backend\n // (`service_resource_operation_disabled` → 403) — the exact \"shown but\n // blocked\" divergence. The initiator identity is already on the execution\n // context (no fetch), so the `needsUserContext` gate was a pure footgun for\n // this axis and is removed; `needsUserContext` still governs only the\n // (fetch-bearing) object-context path above.\n const initiatorUserId = executionContext.userId;\n if (initiatorUserId) {\n initiatorUserContext = {\n _id: initiatorUserId,\n roles: executionContext.initiatorRoles,\n };\n }\n\n return { objectContext, initiatorUserContext, currentObject };\n }\n\n /**\n * Fetch current object for UPDATE/DELETE operations.\n * For CREATE operations, returns undefined (object doesn't exist yet).\n *\n * @param coreOperation - The core operation type\n * @param resourceType - Resource type\n * @param id_or_ids_or_filter - ID or filter\n * @param executionContext - Execution context\n * @returns Current object or undefined for CREATE\n */\n private async fetchCurrentObjectForOperation(\n coreOperation: CoreResourceOperation | undefined,\n resourceType: ResourceType,\n id_or_ids_or_filter: IdOrIdsOrFilterType | undefined,\n executionContext: ExecutionContext<any>,\n repositoryOptions?: RepositoryOptions,\n ): Promise<any> {\n const isCreateOperation = coreOperation === CoreResourceOperation.CREATE ||\n coreOperation === CoreResourceOperation.CREATE_MANY;\n\n // For CREATE operations, currentObject is undefined (object doesn't exist yet)\n if (isCreateOperation) {\n return undefined;\n }\n\n const singleSelectedId = this.resolveSingleSelectedId(id_or_ids_or_filter);\n\n // For UPDATE/DELETE/READ operations, fetch current object if we have exactly one ID\n if (singleSelectedId) {\n try {\n const repo = this.repositoriesRegistry.getRepository(resourceType);\n if (repo && 'read' in repo) {\n const readResult = await (repo as any).read(\n executionContext,\n singleSelectedId,\n repositoryOptions,\n );\n return Array.isArray(readResult) ? readResult[0] : readResult;\n }\n } catch (error) {\n // Read failures are terminal for single-target mutations. Returning\n // undefined here made downstream hooks/conditions see a fabricated\n // \"no current object\" state while the repository read had actually\n // failed (for example NOT_FOUND or adapter errors).\n this.logDebug('Failed to fetch current object for operation', {\n resourceType,\n id: singleSelectedId,\n error: describeCaughtError(error)\n });\n throw error;\n }\n }\n\n // Fallback: return undefined if we can't determine the object\n return undefined;\n }\n\n private static readonly STEP_UP_EXEMPT_OPERATIONS = new Set([\n CoreResourceOperation.READ,\n CoreResourceOperation.LIST,\n CoreResourceOperation.SEARCH,\n CoreResourceOperation.COUNT,\n ]);\n\n /**\n * W7.1: Enforces step-up re-authentication for sensitive (mutating) operations.\n *\n * Two independent triggers, both satisfied by the SAME proof (a single-use `REAUTH` consumable\n * token in `X-Reauth-Token`, minted by `POST /auth/reauth`):\n *\n * - **Per-user-type freshness policy** (`UserTypeAuthPolicy.stepUpAuth`) — opt-in, off by\n * default, challenges only once `lastAuthenticatedAt` is older than `maxAgeSeconds`.\n * - **Per-operation requirement** (`requiresStepUpAuthentication`) — UNCONDITIONAL for that one\n * operation, and deliberately independent of the policy above: it applies even when the user\n * type declares no `stepUpAuth` at all, and it ignores freshness. An irreversible action wants\n * proof *now*, not proof that the session is younger than five minutes.\n *\n * Skip conditions (all must be false for either trigger to apply):\n * 1. Non-user requests (INTERNAL_CALL, API_KEY, etc.) — exempt, no interactive credential exists\n * 2. Worker executions — already authorized at queue time\n * 3. Sub-calls (subCallDepth > 0) — parent already passed step-up\n * 4. Read-only operations (READ, LIST, SEARCH, COUNT) — exempt\n *\n * A principal with no resolvable `activeUserType` is exempt from the FRESHNESS policy (there is no\n * policy to read) but NOT from a per-operation requirement — the requirement is a property of the\n * operation, and letting an unresolved user type waive it would make the gate depend on\n * configuration completeness. Fail closed.\n *\n * Failing either trigger throws STEP_UP_REQUIRED (HTTP 403); the frontend HTTP client catches that\n * status, obtains a token through its registered step-up handler, and replays the request.\n */\n private async enforceStepUpAuth(\n coreOperation: CoreResourceOperation | null,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n operation?: ResourceConfiguration_Operation<any, any, any>,\n ): Promise<void> {\n if (executionContext.executionType !== ExecutionContext_ExecutionType.USER_REQUEST) return;\n if (options?.isWorkerExecution) return;\n if (executionContext.subCallDepth > 0) return;\n if (coreOperation && ServiceResourceBackendService.STEP_UP_EXEMPT_OPERATIONS.has(coreOperation)) return;\n\n const operationRequiresStepUp = operation?.requiresStepUpAuthentication === true;\n\n const activeUserType = executionContext.activeUserType;\n const authPolicy = activeUserType\n ? this.appConfigService.getUserTypeAuthPolicy(activeUserType)\n : undefined;\n const stepUpConfig = authPolicy?.stepUpAuth;\n\n // Neither trigger fires → nothing to enforce.\n if (!operationRequiresStepUp && !stepUpConfig?.enabled) return;\n\n // Freshness can satisfy the POLICY trigger, but never the per-operation one.\n if (!operationRequiresStepUp) {\n const lastAuthAt = executionContext.lastAuthenticatedAt ?? 0;\n const nowSeconds = Math.floor(Date.now() / 1000);\n if (nowSeconds - lastAuthAt <= stepUpConfig!.maxAgeSeconds) return;\n }\n\n const reAuthTokenValue = executionContext.reAuthTokenValue;\n if (reAuthTokenValue) {\n try {\n const consumed = await this.consumableTokenService.consumeToken(reAuthTokenValue);\n if (consumed.tokenType === CoreConsumableTokenTypes.REAUTH\n && consumed.userId === executionContext.initiatorIds.userId) {\n return;\n }\n } catch (err: unknown) {\n if (isWildoBackendError(err)) {\n this.logDebug('Re-auth token consumption failed', { error: err.customMessageReference });\n }\n }\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.AUTHORIZATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.STEP_UP_REQUIRED,\n context: {\n // Which trigger refused, so an operator reading the log knows whether to look at the\n // user-type policy or at the operation declaration.\n reason: operationRequiresStepUp\n ? 'operation_requires_step_up_authentication'\n : 'authentication_older_than_user_type_max_age',\n ...(operationRequiresStepUp\n ? { operationIdentifier: operation?.operationIdentifier, resourceIdentifier: operation?.resourceIdentifier }\n : { maxAgeSeconds: stepUpConfig!.maxAgeSeconds }),\n },\n },\n );\n }\n\n /**\n * Ask the registered conflict resolvers for one explicit framework action.\n *\n * Resolvers run only after an owned transaction has aborted. A reconciled\n * winner takes precedence immediately; otherwise one or more retry requests\n * collapse into the framework's single bounded retry. Runtime validation is\n * retained because application-owned implementations can bypass TypeScript.\n */\n private async resolveTransactionalCoreConflict(\n error: unknown,\n originalCoreInput: unknown,\n executionContext: ExecutionContext<any>,\n operation: ResourceConfiguration_Operation<any, any, any>,\n customImplUtils: ResourceOperation_CustomImplementation_Utils,\n conflictResolvers: readonly ResourceCustomServiceImplementationTransactionalCoreConflictResolver[],\n ): Promise<ResourceCustomServiceImplementationTransactionalCoreConflictResolution> {\n let retryTransactionRequested = false;\n\n for (const resolveConflict of conflictResolvers) {\n const resolution: unknown = await resolveConflict(\n error,\n cloneResourceTransactionAttemptInput(originalCoreInput),\n executionContext,\n customImplUtils,\n );\n if (\n !resolution\n || typeof resolution !== 'object'\n || !('action' in resolution)\n ) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n context: {\n reason: 'transactional_core_conflict_resolver_returned_invalid_resolution',\n resourceType: operation.resourceIdentifier,\n operationIdentifier: operation.operationIdentifier,\n },\n },\n );\n }\n\n switch (resolution.action) {\n case ResourceCustomServiceImplementationTransactionalCoreConflictAction.RECONCILED:\n if (!('value' in resolution) || resolution.value === undefined) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n context: {\n reason: 'transactional_core_conflict_resolver_reconciled_without_value',\n resourceType: operation.resourceIdentifier,\n operationIdentifier: operation.operationIdentifier,\n },\n },\n );\n }\n return Object.freeze({\n action: ResourceCustomServiceImplementationTransactionalCoreConflictAction.RECONCILED,\n value: resolution.value,\n });\n case ResourceCustomServiceImplementationTransactionalCoreConflictAction.RETRY_TRANSACTION:\n retryTransactionRequested = true;\n break;\n case ResourceCustomServiceImplementationTransactionalCoreConflictAction.UNHANDLED:\n break;\n default:\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n context: {\n reason: 'transactional_core_conflict_resolver_returned_unknown_action',\n resourceType: operation.resourceIdentifier,\n operationIdentifier: operation.operationIdentifier,\n conflictResolutionAction: resolution.action,\n },\n },\n );\n }\n }\n\n return Object.freeze({\n action: retryTransactionRequested\n ? ResourceCustomServiceImplementationTransactionalCoreConflictAction.RETRY_TRANSACTION\n : ResourceCustomServiceImplementationTransactionalCoreConflictAction.UNHANDLED,\n });\n }\n\n /**\n * Own the resource-operation transaction boundary without knowing how one\n * core attempt is implemented or how a reconciled winner is materialized.\n *\n * Database-driver callback retries remain inside `executeTransaction`.\n * Conflict-resolver retries remain outside it and are bounded to one complete\n * replay. Caller-owned transactions are never reconciled here because only\n * their root owner can restart an aborted native transaction.\n */\n private async executeTransactionalCoreBoundary(execution: ResourceOperationTransactionalCoreBoundaryExecution): Promise<ResourceOperationCoreBoundaryResult> {\n const transactionPersistenceRequest = execution.persistenceContract.request;\n if (\n !transactionPersistenceRequest\n || !this.resourcePersistenceUnitOfWork\n ) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n execution.executionContext,\n {\n context: {\n reason: 'resource_operation_transaction_coordinator_unavailable',\n resourceType: execution.operation.resourceIdentifier,\n operationIdentifier: execution.operation.operationIdentifier,\n hasPersistenceRequest: Boolean(transactionPersistenceRequest),\n hasUnitOfWorkService: Boolean(this.resourcePersistenceUnitOfWork),\n },\n },\n );\n }\n\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n const committed =\n await this.resourcePersistenceUnitOfWork.executeTransaction(\n transactionPersistenceRequest,\n execution.executeAttempt,\n execution.baseOptions,\n {\n requiresRootOwnership: execution.requiresRootOwnership,\n },\n );\n return Object.freeze({\n state: committed.state,\n inputData: committed.inputData,\n terminalCustomImplUtils: committed.terminalCustomImplUtils,\n transactionalCoreConflictReconciled: false,\n transactionallyPreparedTokenGenerationResult:\n committed.tokenGenerationResult,\n frameworkPostCommitRegisteredTransactionally: true,\n consumableTokenConsumedTransactionally:\n committed.consumedIncomingToken,\n transactionallyPreparedOutput: Object.freeze({\n value: committed.transformedState,\n }),\n });\n } catch (error) {\n const isConflict =\n isWildoBackendError(error)\n && error.statusCode === 409;\n if (\n !isConflict\n || execution.conflictResolvers.length === 0\n || execution.baseOptions?.transaction\n ) {\n throw error;\n }\n\n const conflictResolution =\n await this.resolveTransactionalCoreConflict(\n error,\n execution.originalCoreInput,\n execution.executionContext,\n execution.operation,\n execution.customImplUtils,\n execution.conflictResolvers,\n );\n if (conflictResolution.action === ResourceCustomServiceImplementationTransactionalCoreConflictAction.RECONCILED) {\n const reconciled = await execution.resolveReconciledResult(conflictResolution.value);\n return Object.freeze({\n state: reconciled.state,\n inputData: reconciled.inputData,\n terminalCustomImplUtils: reconciled.terminalCustomImplUtils,\n transactionalCoreConflictReconciled: true,\n transactionallyPreparedTokenGenerationResult:\n reconciled.tokenGenerationResult,\n frameworkPostCommitRegisteredTransactionally: false,\n consumableTokenConsumedTransactionally: false,\n });\n }\n if (\n conflictResolution.action !== ResourceCustomServiceImplementationTransactionalCoreConflictAction.RETRY_TRANSACTION\n || attempt === 1\n ) {\n throw error;\n }\n }\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n execution.executionContext,\n {\n context: {\n reason: 'transactional_core_boundary_completed_without_result',\n resourceType: execution.operation.resourceIdentifier,\n operationIdentifier: execution.operation.operationIdentifier,\n },\n },\n );\n }\n\n /**\n * Terminal hooks run after a framework-owned root transaction has\n * completed. Never expose its completed native transaction through\n * `utils.serviceOptions`; retain every other option and the successful\n * callback-attempt context snapshot.\n */\n private createTerminalCustomImplUtils(source: ResourceOperation_CustomImplementation_Utils): ResourceOperation_CustomImplementation_Utils {\n const terminalServiceOptions = source.serviceOptions\n ? { ...source.serviceOptions }\n : undefined;\n if (terminalServiceOptions) {\n delete terminalServiceOptions.transaction;\n }\n return {\n ...source,\n serviceOptions: terminalServiceOptions,\n };\n }\n\n /**\n * Dispatch the framework-owned persistence operation for one core attempt.\n *\n * Custom PREFIX/REPLACE/POSTFIX hooks stay outside this method so their\n * authored ordering remains visible in the core phase.\n */\n private async executeCorePersistenceOperation(execution: ResourceOperationCorePersistenceExecution): Promise<any> {\n const {\n operation,\n operationPath,\n coreOperation,\n executionContext,\n target,\n inputData,\n currentObject,\n options,\n } = execution;\n\n if (operation.generatedOperation?.kind === ResourceGeneratedOperationKind.GENERATED_FILE_REGENERATE) {\n return this.executeGeneratedFileRegenerateOperation(\n operation,\n operation.generatedOperation.fieldName,\n executionContext,\n target,\n currentObject,\n options,\n );\n }\n\n // The read-only-field guard's bulk flag, from the ONE canonical discriminant (see\n // `isBulkUpdateCoreOperation`). Both the UPDATE case (a `haveBulkOperation` variant) and the\n // UPDATE_MANY case are bulk; computing it here means the two guard call sites cannot drift — the\n // drift that let the guard silently skip the `haveBulkOperation` path.\n const isBulkUpdate = this.isBulkUpdateCoreOperation(\n coreOperation,\n 'isBulkOperation' in operation ? operation.isBulkOperation : undefined,\n );\n\n switch (coreOperation) {\n // NO read-only-field guard on CREATE / CREATE_MANY, deliberately — do not add one by symmetry with\n // the UPDATE cases below. A `.excludeFromCreate()` field a client sends is SILENTLY STRIPPED by the\n // strict request DTO, and that is the intended mass-assignment-protection contract, pinned by\n // `resource-validation-matrix.e2e.ts` V-14a (\"create with unknown fields → 201, strict-DTO strips\").\n // The UPDATE guard exists because CHANGING an EXISTING immutable field to a new value and answering\n // 2xx is a false success on live data (the `users.status` → magic-link cascade). CREATE has no such\n // hazard: there is no stored value to falsely \"change\", and every `.excludeFromCreate()` field is\n // server-owned (createdAt/updatedAt, `_id`, context-injected FKs, a defaulted status) whose SERVER\n // value is the correct one — so stripping the client's value is right, not a silent defect. Making\n // create refuse-on-presence would be a stricter SECURITY POSTURE, not a bug fix, and would contradict\n // V-14a. Decision recorded 2026-08-11 (see memory `create-side-strip-is-intended-not-a-defect`).\n case CoreResourceOperation.CREATE:\n return this.create(\n operation,\n executionContext,\n inputData,\n options,\n );\n case CoreResourceOperation.CREATE_MANY:\n return this.createMany(\n operation,\n executionContext,\n inputData,\n options,\n );\n case CoreResourceOperation.READ:\n return this.read(\n operation,\n executionContext,\n target,\n options,\n );\n case CoreResourceOperation.UPDATE:\n // Refuse an update that tries to CHANGE a read-only field instead of silently 2xx-ing it.\n //\n // A `haveBulkOperation` variant reaches THIS case, not UPDATE_MANY: its `operationIdentifier` is\n // `UPDATE`, so `getCoreResourceOperationFromOperation` returns `UPDATE` and the bulk-ness rides on\n // the operation's `isBulkOperation` flag (the canonical predicate — see `isBulkUpdateOperation`).\n // That is the ACTUAL working bulk-update mechanism (todos `change_status`/`assign`, org-features,\n // …); a plain core UPDATE_MANY reaching the sibling case below is the rarer INTERNAL_CALL form. So\n // the guard must key on `isBulkOperation` here, or the bulk path stays a silent no-op — the exact\n // sibling-call-site miss `.claude/rules/invariant-call-site-enumeration.md` #8 is written for.\n // Single (isBulk=false): compare to the stored row, an echo is allowed. Bulk: refuse on PRESENCE.\n await this.assertNoForbiddenReadOnlyFieldChange(\n operation, target, inputData, currentObject, executionContext, options, isBulkUpdate,\n );\n return this.update(\n operation,\n executionContext,\n target,\n inputData,\n options,\n );\n case CoreResourceOperation.UPDATE_MANY:\n // The other bulk site: a core UPDATE_MANY (operationIdentifier IS UPDATE_MANY — the INTERNAL_CALL\n // retention-scrub form). `isBulkUpdate` is `true` here (same canonical discriminant); no single\n // stored row exists, so `currentObject` is not passed.\n await this.assertNoForbiddenReadOnlyFieldChange(operation, target, inputData, undefined, executionContext, options, isBulkUpdate);\n return this.updateMany(\n operation,\n executionContext,\n target,\n inputData,\n options,\n );\n case CoreResourceOperation.DELETE:\n return this.delete(\n operation,\n executionContext,\n target,\n options,\n );\n case CoreResourceOperation.DELETE_MANY:\n return this.deleteMany(\n operation,\n executionContext,\n target,\n options,\n );\n case CoreResourceOperation.LIST:\n return this.list(\n operation,\n executionContext,\n inputData?.filter as FilterQuery<any>,\n {\n page: inputData?.page,\n limit: inputData?.limit,\n sort: inputData?.sort,\n },\n options,\n );\n case CoreResourceOperation.COUNT:\n return this.count(\n operation,\n executionContext,\n inputData?.filter as FilterQuery<any>,\n options,\n );\n case CoreResourceOperation.SEARCH:\n return this.search(\n operation,\n executionContext,\n inputData?.searchQuery ?? '',\n inputData?.filter as FilterQuery<any>,\n {\n ...(options ?? {}),\n searchOptions: {\n page: inputData?.page,\n limit: inputData?.limit,\n sort: inputData?.sort,\n },\n } as ServiceOptions & {\n searchOptions: {\n page?: number;\n limit?: number;\n sort?: Record<string, 1 | -1>;\n };\n },\n );\n default:\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference:\n ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operationIdentifier: operation.operationIdentifier,\n operationPath,\n },\n },\n );\n }\n }\n\n /**\n * Execute PREFIX, framework persistence, REPLACE, and POSTFIX for one core\n * attempt.\n *\n * The caller supplies either the preflight state snapshot or, when a native\n * transaction is present, a refresher that re-reads and re-validates that\n * state inside the exact database-driver callback attempt.\n */\n private async executeCorePhase(execution: ResourceOperationCorePhaseExecution): Promise<ResourceOperationCorePhaseResult> {\n const {\n operation,\n operationPath,\n coreOperation,\n resourceType,\n executionContext,\n target,\n customImplUtils,\n customImplRegistrations,\n customImplPlaceholders,\n } = execution;\n const operationIdentifier = operation.operationIdentifier;\n let coreOptions = execution.options;\n let coreInput = execution.inputData;\n let coreState: any;\n let coreContext = execution.preflightContext;\n\n if (coreOptions?.transaction) {\n coreContext = await execution.refreshTransactionalContext(\n coreInput,\n coreOptions,\n );\n }\n\n const {\n currentObject: coreCurrentObject,\n hookCurrentObject: coreHookCurrentObject,\n computationContext: coreComputationContext,\n } = coreContext;\n const coreCustomImplUtils: ResourceOperation_CustomImplementation_Utils = {\n ...customImplUtils,\n serviceOptions: coreOptions,\n objectContext: {\n parents: coreComputationContext.objectContext?.parents || {},\n children: coreComputationContext.objectContext?.children || {},\n },\n initiatorUserContext: coreComputationContext.userContext,\n currentObject: coreHookCurrentObject,\n };\n\n // Snapshot the payload keys before any trusted prefix runs. Only fields\n // added after this point can be forwarded through strict request parsing as\n // server-injected persistence fields.\n const payloadKeysBeforePrefix =\n coreInput\n && typeof coreInput === 'object'\n && !Array.isArray(coreInput)\n ? new Set(Object.keys(coreInput))\n : null;\n\n // Fields a trusted hook DECLARES it owns, preserved regardless of the snapshot above.\n //\n // The added-key diff alone is not sufficient. It infers authorship from \"this key was not in\n // the payload\", but the snapshot is taken HERE — at the service tier, after a LOOSE parse\n // (`z.looseObject`) that passes unknown keys through. A caller that reaches this tier with the\n // field already present (MCP `callTool` forwards its arguments with no strict parse) puts the\n // key into `payloadKeysBeforePrefix`; the hook's own value is then not classified as injected,\n // the repository's strict `requestDto` re-parse strips it, and the operation answers success\n // having written nothing — the exact silent-no-op class the unimplemented-operation guard\n // exists to eliminate, reintroduced through the mechanism meant to fix it.\n //\n // An explicit declaration removes the inference. The value preserved is always the POST-hook\n // value (see `preserveServerInjectedFields`), so a caller-supplied value is overwritten rather\n // than honored, and client reachability of the field is unchanged — that stays governed by the\n // operation's `requestDto` and the schema decorators.\n const authoritativeFieldNames = new Set<string>();\n const declareAuthoritativeFields = (fields: readonly string[] | undefined): void => {\n for (const field of fields ?? []) authoritativeFieldNames.add(field);\n };\n\n if ('authoritativeFields' in operation) {\n // Config-level declaration, for `basicPrefixOperation` — which is authored on the operation\n // variant rather than through a custom-implementation registration and has no other place to\n // declare what it owns.\n declareAuthoritativeFields(\n (operation as { authoritativeFields?: readonly string[] }).authoritativeFields,\n );\n }\n\n if (\n 'basicPrefixOperation' in operation\n && operation.basicPrefixOperation\n ) {\n this.assertBulkHookObjectContextAvailability(\n coreOperation,\n 'isBulkOperation' in operation ? operation.isBulkOperation : false,\n operation.basicPrefixOperation,\n coreCurrentObject,\n executionContext,\n operationIdentifier,\n 'basicPrefixOperation',\n );\n\n const { objectContext, initiatorUserContext } =\n await this.fetchContextsForOperationFunction(\n operation.basicPrefixOperation,\n resourceType,\n coreCurrentObject,\n executionContext,\n coreOptions,\n );\n const inputAdding = operation.basicPrefixOperation({\n inputDto: coreInput,\n currentObject: coreHookCurrentObject,\n objectContext,\n initiatorUserContext,\n initiatorIds: executionContext.initiatorIds,\n });\n\n if (inputAdding && typeof inputAdding === 'object'\n && !Array.isArray(inputAdding)\n ) {\n coreInput = { ...coreInput, ...inputAdding };\n }\n }\n\n if (\n customImplPlaceholders.has(\n ResourceOperation_CustomServiceImplementationMode.PREFIX_CORE_OPERARTIONS,\n )\n ) {\n const prefixRegistrations =\n this.customImplRegistry.resolveRegistrationsForMode(\n customImplRegistrations,\n ResourceOperation_CustomServiceImplementationMode.PREFIX_CORE_OPERARTIONS,\n this.logger,\n );\n for (const registration of prefixRegistrations) {\n declareAuthoritativeFields(registration.authoritativeFields);\n const prefixResult =\n await registration.implementation.prefixCoreOperations(\n target as any,\n coreInput,\n executionContext,\n coreCustomImplUtils,\n );\n if (Array.isArray(coreInput)) {\n if (Array.isArray(prefixResult)) {\n coreInput = prefixResult;\n } else {\n this.logDebug(\n `[CustomImpl] PREFIX handler [${registration.debugLabel}] returned non-array for array input, result ignored`,\n );\n }\n } else if (prefixResult && typeof prefixResult === 'object'\n && !Array.isArray(prefixResult)\n ) {\n coreInput = { ...coreInput, ...prefixResult };\n } else if (prefixResult !== undefined && prefixResult !== null) {\n this.logDebug(\n `[CustomImpl] PREFIX handler [${registration.debugLabel}] returned non-object (${typeof prefixResult}), result ignored`,\n );\n }\n }\n }\n\n // Client-supplied keys were present before the prefixes and are never whitelisted. Only fields\n // INTRODUCED by trusted hooks — or explicitly DECLARED as owned by one via\n // `authoritativeFields` — are preserved. See `resolveServerInjectedFieldAllowList` for why the\n // introduced-key rule alone is not sufficient.\n if (payloadKeysBeforePrefix && coreInput\n && typeof coreInput === 'object'\n && !Array.isArray(coreInput)\n ) {\n const injectedFields = resolveServerInjectedFieldAllowList({\n payloadKeysBeforePrefix,\n postPrefixPayloadKeys: Object.keys(coreInput),\n authoritativeFields: authoritativeFieldNames,\n });\n if (injectedFields.length > 0) {\n coreOptions = {\n ...(coreOptions ?? {}),\n preserveServerInjectedFields: [\n ...(coreOptions?.preserveServerInjectedFields ?? []),\n ...injectedFields,\n ],\n };\n coreCustomImplUtils.serviceOptions = coreOptions;\n }\n }\n\n if (\n 'tokenRevocation' in operation\n && operation.tokenRevocation\n && coreCurrentObject\n ) {\n await this.consumableTokenService.processTokenRevocation(\n operation.tokenRevocation,\n coreCurrentObject,\n { organizationId: executionContext.initiatorIds?.organizationId },\n coreOptions?.transaction,\n );\n }\n\n // A REPLACE_CORE_OPERATIONS custom impl OWNS the operation and produces the\n // authoritative `coreState` below — the core persistence result is discarded.\n // We normally still run the core op (for an ENTITY replace that supplies a\n // target, its write is a tolerated near-no-op). But a COLLECTION-SCOPED custom\n // ACTION — e.g. \"retry all\" / \"purge all\", which borrows a `*_MANY` verb for its\n // id-less collection route and carries NO target selector — would make the core\n // `update`/`delete` throw `missingParameter: id_or_ids_or_filter` HERE, before\n // the replace handler ever runs. Skip the core persistence in exactly that case\n // (a replace impl is present, the core op is a target-requiring mutation, and no\n // target was resolved) so the custom handler is the sole authority. This changes\n // behavior ONLY for ops that were already unreachable (they threw at this line);\n // entity replace ops that DO supply a target are unaffected.\n const willReplaceCore = customImplPlaceholders.has(\n ResourceOperation_CustomServiceImplementationMode.REPLACE_CORE_OPERARTIONS,\n );\n const coreMutationRequiresTarget = coreOperation === CoreResourceOperation.UPDATE\n || coreOperation === CoreResourceOperation.UPDATE_MANY\n || coreOperation === CoreResourceOperation.DELETE\n || coreOperation === CoreResourceOperation.DELETE_MANY;\n const skipCorePersistenceForTargetlessReplace = willReplaceCore && coreMutationRequiresTarget && !target;\n\n coreState = skipCorePersistenceForTargetlessReplace\n ? undefined\n : await this.executeCorePersistenceOperation({\n operation,\n operationPath,\n coreOperation,\n executionContext,\n target,\n inputData: coreInput,\n currentObject: coreCurrentObject,\n options: coreOptions,\n });\n\n if (willReplaceCore) {\n const replaceWinner = this.customImplRegistry.resolveSingleOwner(\n customImplRegistrations,\n ResourceOperation_CustomServiceImplementationMode.REPLACE_CORE_OPERARTIONS,\n this.logger,\n );\n if (replaceWinner) {\n coreState = await replaceWinner.implementation.replaceCoreOperations(\n target as any,\n coreInput,\n executionContext,\n coreCustomImplUtils,\n );\n }\n }\n\n if (\n customImplPlaceholders.has(\n ResourceOperation_CustomServiceImplementationMode.POSTFIX_CORE_OPERARTIONS,\n )\n ) {\n const postfixRegistrations =\n this.customImplRegistry.resolveRegistrationsForMode(\n customImplRegistrations,\n ResourceOperation_CustomServiceImplementationMode.POSTFIX_CORE_OPERARTIONS,\n this.logger,\n );\n for (const registration of postfixRegistrations) {\n this.logDebug(\n `Executing postfixCoreOperations [${registration.debugLabel}]`,\n {\n operationIdentifier,\n currentStateKeys:\n coreState && typeof coreState === 'object'\n ? Object.keys(coreState)\n : typeof coreState,\n },\n );\n coreState = await registration.implementation.postfixCoreOperations(\n target as any,\n coreState,\n executionContext,\n coreCustomImplUtils,\n );\n }\n }\n\n return Object.freeze({\n state: coreState,\n inputData: coreInput,\n terminalCustomImplUtils:\n this.createTerminalCustomImplUtils(coreCustomImplUtils),\n });\n }\n\n private registerConsumableTokenContextMark(registration: ConsumableTokenContextMarkRegistration): void {\n registerTransactionPostCommitEffect(registration.transaction, {\n key: [\n 'consumable-token-context-mark',\n String(registration.operationPath.resourceIdentifier),\n String(registration.operationPath.operationIdentifier),\n registration.transaction.id,\n registration.occurrenceId,\n ].join(':'),\n execute: async () => {\n registration.executionContext.markConsumableTokenConsumed();\n },\n });\n }\n\n /**\n * Execute one database-driver callback attempt, including only work that must\n * commit atomically with the core resource mutation.\n */\n private async executeTransactionalCoreAttempt(\n execution: ResourceOperationTransactionalCoreAttemptExecution,\n ): Promise<ResourceOperationTransactionalCoreAttemptResult> {\n const coreResult = await execution.executeCorePhase(\n execution.optionsWithTransaction,\n cloneResourceTransactionAttemptInput(execution.originalCoreInput),\n );\n const {\n state,\n inputData,\n terminalCustomImplUtils: attemptTerminalCustomImplUtils,\n } = coreResult;\n const transformedState = state == null\n ? state\n : await this.transformOutput(\n execution.executionContext,\n state,\n execution.dataMode,\n execution.resolvedOperation,\n );\n const transaction = execution.optionsWithTransaction.transaction;\n if (!transaction) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n execution.executionContext,\n {\n context: {\n reason: 'transactional_core_missing_transaction_context',\n resourceType: execution.operation.resourceIdentifier,\n operationIdentifier: execution.operation.operationIdentifier,\n },\n },\n );\n }\n\n const tokenGenerationResult =\n execution.tokenGeneration\n && state\n ? await maybeProcessTokenGenerationForOperation(\n { consumableTokenService: this.consumableTokenService },\n execution.tokenGeneration,\n state,\n {\n organizationId:\n execution.executionContext.initiatorIds?.organizationId,\n userId: execution.executionContext.initiatorIds?.userId,\n resourceType: execution.operation.resourceIdentifier,\n },\n transaction,\n )\n : null;\n\n const incomingConsumableToken = execution.executionContext.consumableTokenValue;\n const consumedIncomingToken = Boolean(incomingConsumableToken);\n if (incomingConsumableToken) {\n await this.consumableTokenService.consumeToken(\n incomingConsumableToken,\n transaction,\n );\n this.registerConsumableTokenContextMark({\n transaction,\n operationPath: execution.operationPath,\n occurrenceId: execution.postCommitEffectOccurrenceId,\n executionContext: execution.executionContext,\n });\n }\n\n await this.scheduleFrameworkManagedPostCommitEffects({\n registeredByCoreTransaction: false,\n transaction,\n operationPath: execution.operationPath,\n occurrenceId: execution.postCommitEffectOccurrenceId,\n payload: Object.freeze({\n currentState: state,\n inputData,\n transactionallyPreparedTokenGenerationResult: tokenGenerationResult,\n transactionalCoreConflictReconciled: false,\n }),\n execute: execution.executePostCommit,\n });\n\n return Object.freeze({\n state,\n tokenGenerationResult,\n consumedIncomingToken,\n transformedState,\n inputData,\n terminalCustomImplUtils: attemptTerminalCustomImplUtils,\n });\n }\n\n /**\n * Execute framework-managed work that is outside the database rollback\n * domain.\n *\n * A nested resource operation can run inside another operation's\n * transaction. The caller must therefore invoke this phase only from an\n * immediate no-transaction path or a registered root post-commit effect.\n */\n private async executeFrameworkManagedPostCommitEffects(execution: FrameworkManagedPostCommitExecution): Promise<void> {\n const {\n payload,\n executionContext,\n operation,\n resolvedOperation,\n operationPath,\n preOperationState,\n } = execution;\n const {\n currentState,\n inputData,\n transactionallyPreparedTokenGenerationResult,\n transactionalCoreConflictReconciled,\n } = payload;\n\n if (transactionalCoreConflictReconciled) {\n // This request did not perform the mutation. Request-scoped terminal\n // result transformers still run, but winner-owned effects must not be\n // emitted twice.\n //\n // The audit emission below sits AFTER this guard on purpose: an event here would assert that\n // this request performed a mutation it lost the race for, which is exactly the false record\n // \"emit after commit\" exists to prevent.\n return;\n }\n\n // Audit BEFORE the evaluators. This is the compliance-bearing effect in this lane; the\n // guidance / milestone / lifecycle evaluators below are product behaviour and are deliberately\n // fire-and-forget via `setImmediate`. Ordering them after keeps an evaluator's slow path from\n // delaying the record of what happened.\n await this.emitResourceOperationAudit({\n executionContext,\n resolvedOperation,\n operationPath,\n inputData,\n preOperationState,\n postOperationState: currentState,\n });\n\n const notificationCurrentState =\n resolvedOperation.generatedOperation?.kind === ResourceGeneratedOperationKind.GENERATED_FILE_REGENERATE\n && currentState\n && typeof currentState === 'object'\n && !Array.isArray(currentState)\n && 'resource' in currentState\n ? (currentState as { resource: unknown }).resource\n : currentState;\n\n await this.dispatchNotifications(\n executionContext,\n inputData,\n notificationCurrentState,\n transactionallyPreparedTokenGenerationResult,\n preOperationState,\n );\n\n // RAG INGESTION seam — the service-tier CHANGED-FIELD hook (plan §3.c / H1). Sits in THIS\n // chokepoint because it is the one post-commit point every service-tier write door reaches\n // (create/createMany/update/updateMany, system writes, custom operations, nested mutations, on\n // both the transactional and inline paths) — see `rag-ingestion-trigger.backend.utils.ts` for\n // the full placement argument and the retained-row (impersonalize) exclusion.\n this.runRagChunkIngestionForWrite(resolvedOperation, operationPath, executionContext, inputData, currentState);\n\n // Scheduling itself happens after commit. Evaluator work stays\n // intentionally fire-and-forget and isolated from the request result.\n if (this.guidanceTriggerEvaluator) {\n setImmediate(() => {\n this.guidanceTriggerEvaluator!.evaluateForOperation({\n resourceType: executionContext.operation.resourceIdentifier,\n operationIdentifier: executionContext.operation.operationIdentifier,\n userId: executionContext.initiatorIds?.userId,\n organizationId: executionContext.initiatorIds?.organizationId,\n }).catch((err: unknown) => {\n this.logDebug('Guidance trigger evaluation failed (non-blocking)', {\n error: describeCaughtError(err),\n });\n });\n });\n }\n\n if (this.milestoneEvaluator) {\n setImmediate(() => {\n this.milestoneEvaluator!.evaluateForOperation({\n resourceType: executionContext.operation.resourceIdentifier,\n operationIdentifier: executionContext.operation.operationIdentifier,\n userId: executionContext.initiatorIds?.userId,\n organizationId: executionContext.initiatorIds?.organizationId,\n }).catch((err: unknown) => {\n this.logDebug('Milestone evaluation failed (non-blocking)', {\n error: describeCaughtError(err),\n });\n });\n });\n }\n\n if (this.lifecycleEvaluator) {\n setImmediate(() => {\n this.lifecycleEvaluator!.onOperation({\n // Deliberately NOT normalised to `''`. An execution with no user principal — machine\n // (client-credentials), internal call, cron, public endpoint — has no user scope at all,\n // and an empty-string id is the ABSENCE of a user rather than a user. Every evaluator\n // below distinguishes the two by `undefined`.\n userId: executionContext.initiatorIds?.userId,\n organizationId: executionContext.initiatorIds?.organizationId,\n operationIdentifier: String(operationPath.operationIdentifier),\n resourceIdentifier: operationPath.resourceIdentifier,\n executionContext,\n }).catch((err: unknown) => {\n this.logDebug('Lifecycle activity check failed (non-blocking)', {\n error: describeCaughtError(err),\n });\n });\n });\n }\n }\n\n /**\n * Record that a HIGH / CRITICAL resource operation took effect.\n *\n * # Why here\n *\n * This is the one point that sees EVERY execution surface — API, internal call, repository-only —\n * and it runs only after the mutation is durable, so the row can never assert a change that was\n * rolled back. The HTTP controller cannot do this job: it is blind to the two non-API surfaces,\n * which carry 68 of the catalogue's 149 HIGH/CRITICAL variants, including every SSO-config,\n * auth-policy, SCIM-provisioning and credential write.\n *\n * # Failure model — best-effort, and why that preserves assurance evidence\n *\n * A throw here is caught and logged. Refusing an already-committed business operation cannot undo\n * it; the assurance obligation is instead to produce the event, DETECT delivery failures and\n * tamper-protect the record — all three of\n * which exist (`audit_store_failure_total`, the DB⇄immudb completeness reconciler, and the\n * immutable Layer-2 sink). Throwing post-commit would be strictly worse than best-effort: the\n * caller would be told the operation failed after it had already persisted, which corrupts the\n * accuracy of the very trail the criteria protect.\n *\n * Fail-closed remains correct where refusing still withholds something — a privileged READ, where\n * `SystemAccessBackendService.emitPrivilegedReadAudit` refuses to hand a minion data whose access\n * could not be recorded. A committed write has no such boundary left to hold.\n *\n * assurance-control: WILDO.AUDIT.EVIDENCE_INTEGRITY — privileged resource actions\n * are attributable and their authorization effect is reconstructable.\n */\n private async emitResourceOperationAudit(params: {\n executionContext: ExecutionContext<any>;\n resolvedOperation: ResourceConfiguration_Operation<any, any, any>;\n operationPath: ResourceConfiguration_OperationPath<any, any>;\n inputData: unknown;\n preOperationState: unknown;\n postOperationState: unknown;\n }): Promise<void> {\n const { executionContext, resolvedOperation, operationPath, inputData, preOperationState, postOperationState } = params;\n\n try {\n const decision = resolveResourceOperationAuditDecision(resolvedOperation);\n if (!decision.shouldEmit) {\n return;\n }\n\n const auditLogsService = this.servicesRegistry.getAuditLogsService?.();\n if (!auditLogsService) {\n return;\n }\n\n const operation = resolvedOperation as unknown as {\n riskLevel?: ResourceOperationRiskLevel;\n variantType?: ResourceOperationVariantType;\n variantKey?: string;\n isBulkOperation?: boolean;\n resourceOperationLike?: CoreResourceOperation;\n };\n\n const mainSchema = this.resourceConfiguration.mainSchema as unknown;\n const shape = mainSchema && isZodObject(mainSchema as never)\n ? getZodObjectShape(mainSchema as never)\n : {};\n /**\n * Resolve an evidence path against the resource schema.\n *\n * Accepts a top-level field name or a DOTTED path one level in\n * (`privacy.dataProcessingConsent`). Each hop is unwrapped before descending because a group\n * field is typically a `.default(...)`-wrapped object, and `isZodObject` answers on the\n * wrapper's own type — reading the shape without unwrapping finds nothing and would silently\n * report \"not evidence\" for every nested leaf.\n */\n const isEvidenceField = (path: string): boolean => {\n const [head, ...nested] = path.split('.');\n let fieldSchema = (shape as Record<string, unknown>)[head!];\n for (const segment of nested) {\n if (!fieldSchema) return false;\n const unwrapped = unwrapSchema(fieldSchema as never);\n if (!isZodObject(unwrapped as never)) return false;\n fieldSchema = (getZodObjectShape(unwrapped as never) as Record<string, unknown>)[segment];\n }\n return fieldSchema ? isAuditEvidenceField(fieldSchema as never) : false;\n };\n\n const { changedFields, fieldEvidence } = resolveResourceOperationFieldEffect({\n inputData,\n preOperationState,\n postOperationState,\n isEvidenceField,\n });\n\n // A bulk write names a COUNT rather than an id; a singular write names the row. Reading the\n // id off the post-state (falling back to the pre-image) covers DELETE, whose post-state may\n // not echo the row.\n const isBulk = Array.isArray(postOperationState);\n const singularState = (isBulk ? undefined : postOperationState) ?? preOperationState;\n const resourceId = this.extractPersistedResourceId(\n (singularState ?? {}) as Record<string, unknown>,\n );\n\n await auditLogsService.logResourceOperationPerformed({\n riskLevel: operation.riskLevel ?? ResourceOperationRiskLevel.LOW,\n actorUserId: executionContext.initiatorIds?.userId,\n organizationId: executionContext.initiatorIds?.organizationId,\n applicationId: executionContext.initiatorIds?.applicationId,\n\n resourceType: String(operationPath.resourceIdentifier),\n operationIdentifier: String(operationPath.operationIdentifier),\n variantType: operation.variantType as ResourceOperationVariantType,\n variantKey: operation.variantKey,\n resourceOperationLike: operation.resourceOperationLike,\n isBulkOperation: operation.isBulkOperation,\n\n resourceId,\n affectedRecordCount: isBulk ? (postOperationState as unknown[]).length : undefined,\n\n // Roles AS THEY WERE for this request. `ExecutionContext_RoleInfo` groups roles per\n // primary scope; flatten to the union, because what an auditor checks is whether the actor\n // held a role at all, and the scope it applied in is already implied by the resource.\n initiatorRoles: executionContext.initiatorRoles.flatMap(r => r.roles.map(String)),\n executionType: executionContext.executionType,\n machineCredentialAuthMethod: executionContext.initiatorIds?.machineCredential?.authMethod,\n machineCredentialId: executionContext.initiatorIds?.machineCredential?.credentialId,\n\n subCallDepth: executionContext.subCallDepth,\n\n changedFields: changedFields.length > 0 ? changedFields : undefined,\n fieldEvidence: Object.keys(fieldEvidence).length > 0 ? fieldEvidence : undefined,\n }, executionContext);\n } catch (error) {\n this.logger.warn('Failed to emit the resource-operation audit event', {\n resourceType: String(params.operationPath.resourceIdentifier),\n operationIdentifier: String(params.operationPath.operationIdentifier),\n ...projectCaughtErrorLogFields(error),\n });\n }\n }\n\n /**\n * Keep post-commit work on the owner of the active rollback domain.\n *\n * A core transaction registers its successful-attempt payload before commit.\n * A caller-owned transaction receives the same registration here. With no\n * transaction, the phase executes immediately.\n */\n private async scheduleFrameworkManagedPostCommitEffects(scheduling: FrameworkManagedPostCommitScheduling): Promise<void> {\n if (scheduling.registeredByCoreTransaction) {\n return;\n }\n\n if (!scheduling.transaction) {\n await scheduling.execute(Object.freeze(scheduling.payload));\n return;\n }\n\n const transaction = scheduling.transaction;\n const payload = snapshotFrameworkManagedPostCommitPayload(scheduling.payload);\n registerTransactionPostCommitEffect(transaction, {\n key: [\n 'resource-post-commit',\n String(scheduling.operationPath.resourceIdentifier),\n String(scheduling.operationPath.operationIdentifier),\n String(\n (payload.currentState as { _id?: unknown } | null)?._id ?? 'no-id',\n ),\n transaction.id,\n scheduling.occurrenceId,\n ].join(':'),\n execute: () => scheduling.execute(payload),\n });\n }\n\n /**\n * Run synchronous result-transforming custom phases in the request path.\n *\n * Framework-owned root transactions have committed and drained their\n * post-commit effects before this method is called. Caller-owned transaction\n * shapes with these phases are rejected during preflight.\n */\n private async executeTerminalCustomPhases(execution: ResourceOperationTerminalCustomPhaseExecution): Promise<any> {\n let state = execution.state;\n\n try {\n if (\n execution.customImplPlaceholders.has(\n ResourceOperation_CustomServiceImplementationMode.AFTER_USER_NOTIFICATIONS,\n )\n ) {\n const afterNotificationRegistrations =\n this.customImplRegistry.resolveRegistrationsForMode(\n execution.customImplRegistrations,\n ResourceOperation_CustomServiceImplementationMode.AFTER_USER_NOTIFICATIONS,\n this.logger,\n );\n for (const registration of afterNotificationRegistrations) {\n state = await registration.implementation.afterUserNotifications(\n execution.target as any,\n state,\n execution.executionContext,\n execution.terminalCustomImplUtils,\n );\n }\n }\n\n if (\n execution.customImplPlaceholders.has(\n ResourceOperation_CustomServiceImplementationMode.AT_THE_END,\n )\n ) {\n const atTheEndRegistrations =\n this.customImplRegistry.resolveRegistrationsForMode(\n execution.customImplRegistrations,\n ResourceOperation_CustomServiceImplementationMode.AT_THE_END,\n this.logger,\n );\n for (const registration of atTheEndRegistrations) {\n state = await registration.implementation.atTheEnd(\n execution.target as any,\n state,\n execution.executionContext,\n execution.terminalCustomImplUtils,\n );\n }\n }\n } catch (error) {\n if (execution.transactionalCoreRequired) {\n this.logger.error(\n 'Synchronous terminal custom phase failed after the resource mutation committed',\n {\n transactionCommitted: true,\n transactionConflictReconciled:\n execution.transactionalCoreConflictReconciled,\n resourceType: execution.operation.resourceIdentifier,\n operationIdentifier: execution.operation.operationIdentifier,\n ...projectCaughtErrorLogFields(error),\n },\n );\n }\n throw error;\n }\n\n return state;\n }\n\n /**\n * Central orchestration method — ALL resource operations flow through here.\n *\n * Two entry points:\n * - `doByOperationPath()` — resolves `operation` from the operations map. The caller's\n * `executionContext.operation` may differ (e.g., webhook context with a generic operation).\n * - `doByExecutionContext()` — reads `operation` from `executionContext.operation`.\n * Guaranteed to match (same reference).\n *\n * Two correction points enforce the invariant that `executionContext.operation` always\n * matches the operation being executed:\n * - Correction Point 1 (pre-queue): corrects to the base `operation` parameter.\n * - Correction Point 2 (post-variant): refines to `resolvedOperation` when `dataMode !== RAW`.\n *\n * After correction, ALL downstream reads of `executionContext.operation` — notifications,\n * guidance, milestones, queue serialization, repositories — use the correct 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 frameworkPostCommitEffectOccurrenceId = randomUUID();\n options = {\n ...options,\n // Always replace a caller-provided value: this identity belongs to this\n // exact service-operation occurrence, not to the ambient transaction.\n frameworkPostCommitEffectOccurrenceId,\n };\n\n if(operation.variantType === ResourceOperationVariantType.REPOSITORY_ONLY) {\n throw this.errorBuilder.buildError( ErrorType.INTERNAL, executionContext,\n { customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED });\n }\n\n // ── An acknowledged implementation gap must never answer a success status ──\n // Refused HERE, before the runtime-mode switch, so the operation is not queued either: a\n // job that will never do the work is a delayed lie, not a lesser one.\n //\n // Without this, a custom operation whose `requestDto` nothing consumes falls through to the\n // generic core path, writes nothing, and returns 200 with the unchanged row. That is how\n // `organizationMembers | promote` reported success for a role change it never performed\n // (found by a hostile e2e probe on 2026-08-01; 41 routed operations shared the shape).\n // Acknowledging the gap must CLOSE it, not document it.\n //\n // The declaration is trustworthy because `ApplicationStartupConfigValidatorService` refuses\n // to boot when it disagrees with `resolveResourceOperationImplementationCoverage` in either\n // direction — an unacknowledged gap AND a stale acknowledgement on a now-working operation\n // are both startup errors. So the flag is read directly here rather than re-deriving the\n // verdict (a schema walk) on every request; the two cannot drift apart silently.\n if (operation.unimplementedAcknowledgement) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference:\n ErrorCustomMessageReference.RESOURCE_OPERATION_CUSTOM_IMPLEMENTATION_NOT_IMPLEMENTED,\n context: {\n message:\n 'Operation is declared but not implemented, and refuses rather than reporting a success it did not perform',\n resourceIdentifier: operation.resourceIdentifier,\n operationIdentifier: operation.operationIdentifier,\n variantKey: operation.variantKey,\n acknowledgedReason: operation.unimplementedAcknowledgement.reason,\n trackingRef: operation.unimplementedAcknowledgement.trackingRef,\n },\n },\n );\n }\n\n // ── INVARIANT: executionContext.operation must match the operation being executed ──\n // Correction Point 1 (pre-queue): ensures queue serialization and all non-INLINE\n // dispatch paths use the correct operation. Without this, QueueBackendService.buildJobPayload\n // would serialize the caller's stale operation path.\n if (executionContext.operation !== operation) {\n this.logDebug('Correcting executionContext.operation mismatch', {\n contextOp: `${executionContext.operation.resourceIdentifier}.${executionContext.operation.operationIdentifier}`,\n actualOp: `${operation.resourceIdentifier}.${operation.operationIdentifier}`,\n });\n executionContext = executionContext.withOperation(operation);\n }\n\n // ── A BULK operation takes its target from its payload's `_ids` selector ──\n //\n // A bulk operation's URL is COLLECTION-level plus a `/bulk` segment, so it carries no id path\n // parameter and `extractIdsFromExecutionContext` (the only target source on the\n // `doByExecutionContext` entry) can never resolve one. The rows are named in the body, by the\n // `_ids` selector the DTO builder wraps around every bulk request DTO\n // (`Resources_BulkOperationBaseSchema`). Nothing lifted it, so EVERY client-facing bulk operation\n // reached `update()` / `delete()` / `updateMany()` / `deleteMany()` with an undefined target and\n // was refused as `missingParameter: id_or_ids_or_filter`. Fails closed, never mis-targeted — but\n // the whole generic bulk lane was unreachable from a client, and no test could see it because\n // every backend test passes the target explicitly as `doOperation`'s third argument and so skips\n // this resolution entirely.\n //\n // Resolved HERE rather than in the HTTP controller because `doOperation` is the SINGLE funnel\n // every dispatch surface converges on — `doByExecutionContext` (HTTP controller, batches/cron)\n // and `doByOperationPath` (MCP, queue, programmatic) are its only two entries. The controller is\n // one of four call sites of the same invariant, and MCP is a second broken one: it resolves a\n // target from `options.resourceId`, a SINGLE id, so a bulk tool call has no way to name its rows\n // either. Fixing the funnel covers all of them and cannot drift\n // (`.claude/rules/invariant-call-site-enumeration.md`).\n //\n // An EXPLICIT target always wins: a programmatic caller (`updateManyAsSystem`, the retention\n // scrub, a queue job replaying `job.inputId`) has already named its rows, and a payload-borne\n // selector must never be able to widen or redirect a target the caller authored. So this only\n // ever fills an absent target.\n //\n // The selector is then STRIPPED from the payload: it names rows, it is not a field to write.\n // `_ids` is not in `createOrUpdateMandatoryDiscardFields`, so leaving it in place would carry it\n // to the repository to be silently dropped by the strict re-parse — and would show the\n // read-only-field guard a payload that is not the payload.\n if ('isBulkOperation' in operation && operation.isBulkOperation === true) {\n const selectorIds = readBulkOperationSelectorIds(data);\n if (selectorIds) {\n if (id_or_ids_or_filter === undefined) {\n // One id is passed as a bare string rather than a one-element array, matching\n // `resolveGeneratedRelationshipBulkSelector`: a single-target selector must reach the same\n // single-row code path (pre-image fetch, `enabledCondition` object context) as the\n // non-bulk operation, or a one-row bulk action silently loses per-row semantics.\n id_or_ids_or_filter = selectorIds.length === 1 ? selectorIds[0] : selectorIds;\n }\n data = stripBulkOperationSelector(data);\n }\n }\n\n // ============================================\n // STEP 1: Check serviceRuntimeMode FIRST\n // Skip this check if executing from worker (prevents infinite loop)\n // ============================================\n const runtimeMode = operation.serviceRuntimeMode ?? ResourceOperation_ServiceRuntimeMode.INLINE;\n\n if (!options?.isWorkerExecution && runtimeMode !== ResourceOperation_ServiceRuntimeMode.INLINE) {\n const preRuntimeCoreOperation = ResourceOperationsUtils.getCoreResourceOperationFromOperation(operation);\n const isContextAddressedOperationRuntimeTarget =\n preRuntimeCoreOperation === CoreResourceOperation.READ\n || preRuntimeCoreOperation === CoreResourceOperation.UPDATE\n || preRuntimeCoreOperation === CoreResourceOperation.DELETE;\n const hasContextAddressedParentScope =\n this.hasContextAddressedSingletonParentScope(operation, executionContext)\n || this.hasContextAddressedAssociationParentScope(operation, executionContext);\n const authorizedContextAddressedOperationId = options?.contextAddressedOperationAuthorizationId\n ?? options?.contextAddressedMutationAuthorizationId;\n if (\n id_or_ids_or_filter === undefined\n && authorizedContextAddressedOperationId\n && isContextAddressedOperationRuntimeTarget\n ) {\n id_or_ids_or_filter = authorizedContextAddressedOperationId;\n const authorizedCurrentObject = await this.fetchCurrentObjectForOperation(\n preRuntimeCoreOperation,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n id_or_ids_or_filter,\n executionContext,\n );\n this.ensureExplicitMutationTargetMatchesContext(\n operation,\n preRuntimeCoreOperation,\n id_or_ids_or_filter,\n authorizedCurrentObject,\n executionContext,\n );\n }\n\n if (\n id_or_ids_or_filter === undefined\n && isContextAddressedOperationRuntimeTarget\n && !('isBulkOperation' in operation && operation.isBulkOperation === true)\n ) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Context-addressed operations with non-inline runtime modes require a controller-resolved target id before dispatch',\n operationIdentifier: operation.operationIdentifier,\n runtimeMode,\n },\n }\n );\n }\n\n if (\n id_or_ids_or_filter === undefined\n && preRuntimeCoreOperation === undefined\n && hasContextAddressedParentScope\n && !('isBulkOperation' in operation && operation.isBulkOperation === true)\n ) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'Non-inline context-scoped custom operations must declare resourceOperationLike before dispatch so target identity and authorization cannot fall back to collection scope',\n operationIdentifier: operation.operationIdentifier,\n runtimeMode,\n },\n }\n );\n }\n\n switch (runtimeMode) {\n case ResourceOperation_ServiceRuntimeMode.NONE:\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: { message: 'Operation has serviceRuntimeMode: NONE (disabled)' },\n }\n );\n\n case ResourceOperation_ServiceRuntimeMode.QUEUED:\n // Queue and wait for result via RPC pattern\n return this.executeQueued(executionContext, id_or_ids_or_filter, data, true);\n\n case ResourceOperation_ServiceRuntimeMode.QUEUED_NOT_AWAITABLE:\n // Queue and return immediately\n return this.executeQueued(executionContext, id_or_ids_or_filter, data, false);\n\n case ResourceOperation_ServiceRuntimeMode.BACKGROUND_JOB:\n // Queue with callback pattern (async notification)\n return this.executeBackgroundJob(executionContext, id_or_ids_or_filter, data);\n\n case ResourceOperation_ServiceRuntimeMode.INLINE_NOT_AWAITABLE:\n // Fire and forget - execute async but don't wait\n this.executeInlineAsync(operation, executionContext, id_or_ids_or_filter, data, options);\n return { acknowledged: true };\n }\n }\n\n // ============================================\n // STEP 2: Continue with inline execution (existing logic)\n // ============================================\n const operationIdentifier = String(operation.operationIdentifier);\n\n // CRITICAL FIX: Resolve operation variant BEFORE custom impl lookup\n // If dataMode is specified in options, resolve the variant first so custom impl\n // lookup can match the correct variant operation (e.g., 'context' variant)\n const dataMode = (options as any)?.dataMode ?? DataMode.RAW;\n const resolvedOperation = dataMode !== DataMode.RAW\n ? this.resolveOperationVariant(operation, dataMode)\n : operation;\n\n // Correction Point 2 (post-variant): when dataMode !== RAW, the resolvedOperation\n // may differ from the base operation. Update the context to the variant so all\n // downstream reads (notifications, guidance, milestones, repos) use variant configs.\n if (executionContext.operation !== resolvedOperation) {\n executionContext = executionContext.withOperation(resolvedOperation);\n }\n\n this.logDebug('Operation variant resolution for doOperation', {\n operationIdentifier,\n originalVariantKey: operation.variantKey,\n dataMode,\n resolvedVariantKey: resolvedOperation.variantKey,\n variantResolved: resolvedOperation !== operation\n });\n\n const operationPath = ResourcesConfig_OperationPathUtils.extractOperationPath(\n resolvedOperation as unknown as ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum>\n );\n\n const coreOperation = ResourceOperationsUtils.getCoreResourceOperationFromOperation(resolvedOperation);\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const generatedBulkRelationshipOperation = Resources_SharedUtils.parseRelationshipBulkOperationIdentifier(\n operationIdentifier\n );\n if (generatedBulkRelationshipOperation) {\n await this.featureGate.checkOperationFeatures(resolvedOperation, executionContext, data);\n await this.enforceStepUpAuth(coreOperation, executionContext, options, resolvedOperation);\n return this.executeGeneratedRelationshipBulkOperation(\n resolvedOperation,\n generatedBulkRelationshipOperation,\n executionContext,\n data,\n options\n );\n }\n\n const authorizedContextAddressedOperationId = options?.contextAddressedOperationAuthorizationId\n ?? options?.contextAddressedMutationAuthorizationId;\n if (\n id_or_ids_or_filter === undefined\n && authorizedContextAddressedOperationId\n && (\n coreOperation === CoreResourceOperation.READ\n || coreOperation === CoreResourceOperation.UPDATE\n || coreOperation === CoreResourceOperation.DELETE\n )\n // USER *and* MACHINE principals (both external request principals) may use a controller-authorized\n // context-addressed target id — consistent with the resolver gates above; INTERNAL/PUBLIC/etc. excluded.\n && (executionContext.isUserExecution() || executionContext.isMachineExecution())\n ) {\n id_or_ids_or_filter = authorizedContextAddressedOperationId;\n const authorizedCurrentObject = await this.fetchCurrentObjectForOperation(\n coreOperation,\n resourceType,\n id_or_ids_or_filter,\n executionContext,\n );\n this.ensureExplicitMutationTargetMatchesContext(\n resolvedOperation,\n coreOperation,\n id_or_ids_or_filter,\n authorizedCurrentObject,\n executionContext,\n );\n this.logDebug('Using controller-authorized context-addressed operation target', {\n resourceType,\n operationIdentifier,\n operationId: authorizedContextAddressedOperationId,\n });\n }\n\n const contextAddressedSingletonTarget = await this.resolveContextAddressedSingletonOperationTarget(\n resolvedOperation,\n coreOperation,\n resourceType,\n id_or_ids_or_filter,\n executionContext,\n options,\n );\n if (contextAddressedSingletonTarget) {\n // `resolved` → address the operation by the singleton's real `_id`.\n // `absent-read-by-scope` (READ only) → address the read by the parent-scope\n // selector so it returns null and the POSTFIX materialization hook can run.\n id_or_ids_or_filter = contextAddressedSingletonTarget.kind === 'absent-read-by-scope'\n ? contextAddressedSingletonTarget.selector\n : contextAddressedSingletonTarget.operationId;\n this.logDebug('Resolved context-addressed singleton operation target', {\n resourceType,\n operationIdentifier,\n targetKind: contextAddressedSingletonTarget.kind,\n operationId: contextAddressedSingletonTarget.kind === 'resolved'\n ? contextAddressedSingletonTarget.operationId\n : undefined,\n selector: contextAddressedSingletonTarget.selector,\n parentResourceType: contextAddressedSingletonTarget.relationship.resourceType1,\n });\n }\n\n const contextAddressedAssociationTarget = await this.resolveContextAddressedAssociationOperationTarget(\n resolvedOperation,\n coreOperation,\n resourceType,\n id_or_ids_or_filter,\n executionContext,\n options,\n );\n if (contextAddressedAssociationTarget) {\n id_or_ids_or_filter = contextAddressedAssociationTarget.operationId;\n this.logDebug('Resolved complete association-context operation target', {\n resourceType,\n operationIdentifier,\n operationId: contextAddressedAssociationTarget.operationId,\n selector: contextAddressedAssociationTarget.selector,\n parentResourceTypes: contextAddressedAssociationTarget.relationships.map((relationship) => relationship.resourceType1),\n });\n }\n\n // Lookup custom impl registrations with RESOLVED operation (includes variantKey if dataMode specified)\n const customImplRegistrations = this.customImplRegistry.getRegistrationsForOperation(resolvedOperation);\n const customImplPlaceholders = new Set(\n customImplRegistrations.flatMap(r => r.implementation.getPlaceholders())\n );\n\n /**\n * A configured token belongs to the successful resource mutation. The\n * operation and token therefore share one transaction; only notification\n * submission remains a post-commit effect.\n */\n const transactionPersistenceContract =\n resolveResourceOperationTransactionPersistenceContract(\n resolvedOperation,\n customImplRegistrations,\n );\n const transactionalCoreRequired = transactionPersistenceContract.transactionRequired;\n if (transactionalCoreRequired && transactionPersistenceContract.overrideAllRegistrationLabels.length > 0\n ) {\n /**\n * OVERRIDE_ALL replaces this entire framework pipeline and returns before\n * the UoW callback. Allowing it here would make the authored transaction\n * contract fictitious: neither the business write nor its generated token\n * would be guaranteed to execute in the assessed boundary.\n */\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n context: {\n reason:\n 'override_all_not_supported_for_transaction_requiring_operation',\n resourceType: resolvedOperation.resourceIdentifier,\n operationIdentifier: resolvedOperation.operationIdentifier,\n overrideAllRegistrationLabels:\n transactionPersistenceContract.overrideAllRegistrationLabels,\n },\n },\n );\n }\n const hasSynchronousTerminalCustomPhase =\n customImplPlaceholders.has(\n ResourceOperation_CustomServiceImplementationMode.AFTER_USER_NOTIFICATIONS,\n )\n || customImplPlaceholders.has(\n ResourceOperation_CustomServiceImplementationMode.AT_THE_END,\n );\n if (\n options?.transaction\n && hasSynchronousTerminalCustomPhase\n ) {\n /**\n * A framework-owned root transaction returns only after commit and after\n * its post-commit queue has drained, so terminal result transformers can\n * retain their authored ordering there. A nested operation cannot do the\n * same: it must return its synchronous result while the caller still owns\n * an uncommitted transaction. Running the hook now would place\n * AFTER_USER_NOTIFICATIONS before notifications and could leak effects\n * from an eventual abort; deferring it would lose its result transform.\n * Fail before mutation only for that irreconcilable caller-owned shape.\n */\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n context: {\n reason: 'synchronous_terminal_custom_phase_not_supported_in_transaction',\n transactionOwnership: 'caller',\n resourceType: resolvedOperation.resourceIdentifier,\n operationIdentifier: resolvedOperation.operationIdentifier,\n },\n });\n }\n\n this.logDebug('Custom implementation check', {\n operationIdentifier,\n resourceIdentifier: this.resourceConfiguration.resourceIdentifier,\n registrationCount: customImplRegistrations.length,\n placeholders: [...customImplPlaceholders],\n registrations: customImplRegistrations.map(r => r.debugLabel),\n operationPathKey: ResourcesConfig_OperationPathUtils.createOperationPathKeyFromOperation(resolvedOperation as any),\n usedResolvedOperation: resolvedOperation !== operation\n });\n\n // Fetch current object for UPDATE/DELETE operations (needed for enabledCondition and basicPrefixOperation)\n const currentObject = await this.fetchCurrentObjectForOperation(\n coreOperation,\n resourceType,\n id_or_ids_or_filter,\n executionContext,\n options,\n );\n this.ensureExplicitMutationTargetMatchesContext(\n resolvedOperation,\n coreOperation,\n id_or_ids_or_filter,\n currentObject,\n executionContext,\n );\n const hookCurrentObject = this.resolveHookCurrentObject(coreOperation, currentObject, data);\n\n // Fetch computation context for custom implementations\n const needs = this.populationService.analyzeContextNeeds(resourceType);\n const computationContext = await this.populationService.fetchComputationContext(\n resourceType,\n hookCurrentObject || {},\n needs,\n executionContext,\n options,\n );\n\n const customImplUtils : ResourceOperation_CustomImplementation_Utils = {\n logger: this.logger,\n errorBuilder: this.errorBuilder,\n resourcesRegistry: this.resourcesRegistry,\n servicesRegistry: this.servicesRegistry,\n serviceOptions: options,\n repositoriesRegistry: this.repositoriesRegistry,\n externalApiHandler: this.externalApiHandler,\n platformMutualizedHandler: this.platformMutualizedHandler,\n serverlessServicesHandler: this.serverlessServicesHandler,\n executionContextCreator: this.executionContextCreator,\n systemAccessService: this.servicesRegistry.getSystemAccessService?.(),\n samlMetadataService: this.servicesRegistry.getSamlMetadataService?.(),\n objectContext: {\n parents: computationContext.objectContext?.parents || {},\n children: computationContext.objectContext?.children || {}\n } as { parents: Record<string, any>; children: Record<string, any> },\n initiatorUserContext: computationContext.userContext,\n currentObject: hookCurrentObject\n }\n // Check feature gate — is this capability available for this scope?\n // Runs before enabledCondition because feature availability is independent of RBAC/object state.\n // The gate handles its own bypass logic (INTERNAL_CALL, REPOSITORY_ONLY, system resources).\n await this.featureGate.checkOperationFeatures(resolvedOperation, executionContext, data);\n\n // W7.1: Step-up authentication enforcement — the per-user-type freshness policy AND any\n // per-operation `requiresStepUpAuthentication`. The RESOLVED operation is passed because the\n // flag lives on the variant, and a variant that declares it must be judged on its own terms.\n await this.enforceStepUpAuth(coreOperation, executionContext, options, resolvedOperation);\n\n const assertRequiredMutationTargetExists = (\n attemptCurrentObject: unknown,\n ): void => {\n if (\n attemptCurrentObject == null\n && typeof id_or_ids_or_filter === 'string'\n && (\n coreOperation === CoreResourceOperation.UPDATE\n || coreOperation === CoreResourceOperation.DELETE\n )\n ) {\n // A concurrent delete/revoke is an absent explicit mutation target,\n // not an authored-condition programming error. Classify it before\n // evaluating predicates such as `currentObject.status === ...`.\n throw this.errorBuilder.buildError(\n ErrorType.NOT_FOUND,\n executionContext,\n {\n customMessageReference:\n ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: {\n operation: coreOperation,\n id_or_ids_or_filter,\n },\n },\n );\n }\n };\n\n const assertOperationEnabledForState = async (\n attemptCurrentObject: any,\n attemptHookCurrentObject: any,\n attemptInput: any,\n repositoryOptions?: RepositoryOptions,\n ): Promise<void> => {\n // Only API_CALL and API_CALL_WITH_CALLBACK variants carry this gate.\n if (\n !('enabledCondition' in resolvedOperation)\n || !resolvedOperation.enabledCondition\n ) {\n return;\n }\n\n assertRequiredMutationTargetExists(attemptCurrentObject);\n\n this.assertBulkHookObjectContextAvailability(\n coreOperation,\n 'isBulkOperation' in resolvedOperation\n ? resolvedOperation.isBulkOperation\n : false,\n resolvedOperation.enabledCondition,\n attemptCurrentObject,\n executionContext,\n operationIdentifier,\n 'enabledCondition',\n );\n\n const { objectContext, initiatorUserContext } =\n await this.fetchContextsForOperationFunction(\n resolvedOperation.enabledCondition,\n resourceType,\n attemptCurrentObject,\n executionContext,\n repositoryOptions,\n );\n const isEnabled = resolvedOperation.enabledCondition({\n inputDto: attemptInput,\n currentObject: attemptHookCurrentObject,\n objectContext,\n initiatorUserContext,\n initiatorIds: executionContext.initiatorIds,\n });\n\n if (!isEnabled) {\n throw this.errorBuilder.buildError(\n ErrorType.AUTHORIZATION,\n executionContext,\n {\n customMessageReference:\n ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_DISABLED,\n },\n );\n }\n };\n\n // This is an early rejection only. Transaction-required operations repeat\n // the same state-sensitive check from a callback-local database snapshot\n // before any prefix, token, or repository write.\n await assertOperationEnabledForState(\n currentObject,\n hookCurrentObject,\n data,\n options,\n );\n\n if (customImplPlaceholders.has(ResourceOperation_CustomServiceImplementationMode.OVERRIDE_ALL)) {\n const winner = this.customImplRegistry.resolveSingleOwner(\n customImplRegistrations,\n ResourceOperation_CustomServiceImplementationMode.OVERRIDE_ALL,\n this.logger,\n );\n if (winner) {\n return winner.implementation.overrideAll(id_or_ids_or_filter as any, data, executionContext, customImplUtils);\n }\n }\n\n const preflightCoreContext: ResourceOperationCoreAttemptContext =\n Object.freeze({\n currentObject,\n hookCurrentObject,\n computationContext,\n });\n const refreshTransactionalCoreContext = async (\n attemptInput: any,\n attemptOptions: RepositoryOptions,\n ): Promise<ResourceOperationCoreAttemptContext> => {\n // Driver callbacks may be retried, so no state from an earlier callback\n // or from the outer preflight is authoritative.\n const attemptCurrentObject =\n await this.fetchCurrentObjectForOperation(\n coreOperation,\n resourceType,\n id_or_ids_or_filter,\n executionContext,\n attemptOptions,\n );\n assertRequiredMutationTargetExists(attemptCurrentObject);\n this.ensureExplicitMutationTargetMatchesContext(\n resolvedOperation,\n coreOperation,\n id_or_ids_or_filter,\n attemptCurrentObject,\n executionContext,\n );\n const attemptHookCurrentObject = this.resolveHookCurrentObject(\n coreOperation,\n attemptCurrentObject,\n attemptInput,\n );\n const attemptComputationContext =\n await this.populationService.fetchComputationContext(\n resourceType,\n attemptHookCurrentObject || {},\n needs,\n executionContext,\n attemptOptions,\n );\n await assertOperationEnabledForState(\n attemptCurrentObject,\n attemptHookCurrentObject,\n attemptInput,\n attemptOptions,\n );\n return Object.freeze({\n currentObject: attemptCurrentObject,\n hookCurrentObject: attemptHookCurrentObject,\n computationContext: attemptComputationContext,\n });\n };\n const executeCorePhaseAttempt = (\n attemptOptions: RepositoryOptions | undefined,\n attemptInput: any,\n ): Promise<ResourceOperationCorePhaseResult> =>\n this.executeCorePhase({\n operation: resolvedOperation,\n operationPath,\n coreOperation,\n resourceType,\n executionContext,\n target: id_or_ids_or_filter,\n inputData: attemptInput,\n options: attemptOptions,\n preflightContext: preflightCoreContext,\n customImplUtils,\n customImplRegistrations,\n customImplPlaceholders,\n refreshTransactionalContext: refreshTransactionalCoreContext,\n });\n\n const executeFrameworkManagedPostCommit = (\n payload: FrameworkManagedPostCommitPayload,\n ): Promise<void> =>\n this.executeFrameworkManagedPostCommitEffects({\n payload,\n executionContext,\n operation,\n resolvedOperation,\n operationPath,\n // Captured from `doOperation`'s scope, where it was already fetched for `enabledCondition`\n // and `basicPrefixOperation`. Both scheduling sites — the transactional attempt and the\n // non-transactional path — run THIS closure, so the pre-image reaches the audit emission on\n // either route with no signature threading and no extra read.\n preOperationState: currentObject,\n });\n\n const executeTransactionalAttempt = (\n optionsWithTransaction: ServiceOptions,\n originalCoreInput: unknown,\n ): Promise<ResourceOperationTransactionalCoreAttemptResult> =>\n this.executeTransactionalCoreAttempt({\n optionsWithTransaction,\n originalCoreInput,\n executeCorePhase: executeCorePhaseAttempt,\n executionContext,\n dataMode,\n operation,\n resolvedOperation,\n tokenGeneration: transactionPersistenceContract.tokenGeneration,\n operationPath,\n postCommitEffectOccurrenceId: frameworkPostCommitEffectOccurrenceId,\n executePostCommit: executeFrameworkManagedPostCommit,\n });\n\n const executeCoreBoundary = async (): Promise<ResourceOperationCoreBoundaryResult> => {\n if (transactionalCoreRequired) {\n const originalCoreInput = cloneResourceTransactionAttemptInput(data);\n const conflictResolvers = customImplRegistrations\n .map((registration) => registration.transactionalCoreConflictResolver)\n .filter((resolver): resolver is NonNullable<typeof resolver> => resolver !== undefined);\n return this.executeTransactionalCoreBoundary({\n persistenceContract: transactionPersistenceContract,\n baseOptions: options,\n requiresRootOwnership: hasSynchronousTerminalCustomPhase,\n originalCoreInput,\n executionContext,\n operation,\n customImplUtils,\n conflictResolvers,\n executeAttempt: (optionsWithTransaction) =>\n executeTransactionalAttempt(\n optionsWithTransaction,\n originalCoreInput,\n ),\n resolveReconciledResult: async (reconciledState) =>\n Object.freeze({\n state: reconciledState,\n inputData: data,\n /**\n * No callback attempt committed for this request, so an\n * attempt's captured utils would describe an aborted snapshot.\n * Preserve the request's preflight currentObject contract for\n * its request-scoped terminal result transform instead.\n */\n terminalCustomImplUtils:\n this.createTerminalCustomImplUtils(customImplUtils),\n tokenGenerationResult: null,\n }),\n });\n }\n\n const coreResult = await executeCorePhaseAttempt(options, data);\n return Object.freeze({\n ...coreResult,\n transactionalCoreConflictReconciled: false,\n transactionallyPreparedTokenGenerationResult: null,\n frameworkPostCommitRegisteredTransactionally: false,\n consumableTokenConsumedTransactionally: false,\n });\n };\n\n const coreBoundaryResult = await executeCoreBoundary();\n let currentState = coreBoundaryResult.state;\n data = coreBoundaryResult.inputData;\n const terminalCustomImplUtils = coreBoundaryResult.terminalCustomImplUtils;\n const {\n transactionalCoreConflictReconciled,\n transactionallyPreparedTokenGenerationResult,\n frameworkPostCommitRegisteredTransactionally,\n consumableTokenConsumedTransactionally,\n transactionallyPreparedOutput,\n } = coreBoundaryResult;\n\n // ── TOKEN CONSUMPTION (post-operation, MF2) ─────────────────────\n // Consume the token ONLY after the core operation succeeded (Trap 4).\n // Checks consumableTokenValue presence (not executionType) so it works for BOTH:\n // - ALTERNATIVE tokens (executionType = CONSUMABLE_TOKEN)\n // - ADDITIVE tokens (executionType = USER_REQUEST, token validated alongside JWT)\n // consumptionMode logic (SINGLE_USE vs BOUNDED_REUSE) lives inside consumeToken().\n if (executionContext.consumableTokenValue && !consumableTokenConsumedTransactionally\n ) {\n await this.consumableTokenService.consumeToken(\n executionContext.consumableTokenValue,\n options?.transaction,\n );\n if (options?.transaction) {\n this.registerConsumableTokenContextMark({\n transaction: options.transaction,\n operationPath,\n occurrenceId: frameworkPostCommitEffectOccurrenceId,\n executionContext,\n });\n } else {\n executionContext.markConsumableTokenConsumed();\n }\n }\n\n await this.scheduleFrameworkManagedPostCommitEffects({\n registeredByCoreTransaction: frameworkPostCommitRegisteredTransactionally,\n transaction: options?.transaction,\n operationPath,\n occurrenceId: frameworkPostCommitEffectOccurrenceId,\n payload: Object.freeze({\n currentState,\n inputData: data,\n transactionallyPreparedTokenGenerationResult,\n transactionalCoreConflictReconciled,\n }),\n execute: executeFrameworkManagedPostCommit,\n });\n\n currentState = await this.executeTerminalCustomPhases({\n state: currentState,\n target: id_or_ids_or_filter,\n executionContext,\n terminalCustomImplUtils,\n customImplRegistrations,\n customImplPlaceholders,\n transactionalCoreRequired,\n transactionalCoreConflictReconciled,\n operation: resolvedOperation,\n });\n\n // READ/UPDATE/DELETE can legitimately return null (document not found).\n // Skip Zod output validation for null — callers already handle it.\n if (currentState == null) {\n return null;\n }\n\n // Transform output using resolved operation's internalDto\n // Use the already-resolved operation to avoid double resolution\n const finalResult =\n transactionallyPreparedOutput && !hasSynchronousTerminalCustomPhase\n ? transactionallyPreparedOutput.value\n : await this.transformOutput(\n executionContext,\n currentState,\n dataMode,\n resolvedOperation,\n );\n\n return finalResult;\n }\n\n // ================================\n // Queue Runtime Mode Methods\n // ================================\n\n /**\n * Execute operation via queue with RPC pattern (QUEUED / QUEUED_NOT_AWAITABLE).\n *\n * @param executionContext - The execution context with operation\n * @param id_or_ids_or_filter - Resource ID(s) or filter for the operation\n * @param data - Input data for the operation\n * @param awaitable - If true, wait for result (QUEUED); if false, return immediately (QUEUED_NOT_AWAITABLE)\n * @returns For awaitable: the operation result; otherwise: { jobId, status: 'queued' }\n */\n private async executeQueued(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n data: any,\n awaitable: boolean\n ): Promise<any> {\n // Extract inputId for READ/UPDATE/DELETE operations\n const inputId = this.resolveQueuedSingularTargetIdOrThrow(\n executionContext,\n id_or_ids_or_filter,\n 'Queued',\n );\n\n if (awaitable) {\n // QUEUED: Wait for result via RPC\n return this.queueService.enqueueAndWait(executionContext, data, inputId);\n } else {\n // QUEUED_NOT_AWAITABLE: Fire and forget to queue\n const result = await this.queueService.enqueueOperation(executionContext, data, inputId);\n return { jobId: result.jobId, status: 'queued' };\n }\n }\n\n /**\n * Execute operation via queue with callback pattern (BACKGROUND_JOB).\n * Returns immediately with job tracking info.\n *\n * @param executionContext - The execution context with operation\n * @param id_or_ids_or_filter - Resource ID(s) or filter for the operation\n * @param data - Input data for the operation\n * @returns Job tracking info: { jobId, status: 'processing', message }\n */\n private async executeBackgroundJob(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n data: any\n ): Promise<any> {\n const inputId = this.resolveQueuedSingularTargetIdOrThrow(\n executionContext,\n id_or_ids_or_filter,\n 'Background job',\n );\n\n // Enqueue with callback (async result notification)\n const result = await this.queueService.enqueueWithCallback(executionContext, data, inputId);\n\n // Return immediately with job tracking info\n return {\n jobId: result.jobId,\n status: 'processing',\n message: 'Job has been queued for background processing',\n };\n }\n\n private resolveQueuedSingularTargetIdOrThrow(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType | undefined,\n runtimeLabel: string,\n ): string | undefined {\n const inputId = typeof id_or_ids_or_filter === 'string' ? id_or_ids_or_filter : undefined;\n const coreOperation = ResourceOperationsUtils.getCoreResourceOperationFromOperation(\n executionContext.operation as ResourceConfiguration_Operation<any, any, any>,\n );\n if (\n id_or_ids_or_filter !== undefined\n && inputId === undefined\n && (\n coreOperation === CoreResourceOperation.READ\n || coreOperation === CoreResourceOperation.UPDATE\n || coreOperation === CoreResourceOperation.DELETE\n )\n ) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: `${runtimeLabel} singular resource operations require a concrete string target id`,\n operation: coreOperation,\n resourceType: executionContext.operation.resourceIdentifier,\n },\n });\n }\n\n return inputId;\n }\n\n /**\n * Execute operation inline but don't wait for result (INLINE_NOT_AWAITABLE).\n * Fire and forget pattern - executes in the next tick.\n *\n * @param operation - The operation to execute\n * @param executionContext - The execution context\n * @param id_or_ids_or_filter - Resource ID(s) or filter\n * @param data - Input data\n * @param options - Repository options\n */\n private executeInlineAsync(\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 ): void {\n // Execute in next tick, don't await - use setImmediate for true async\n setImmediate(async () => {\n try {\n // Call doOperation with isWorkerExecution to prevent infinite loop\n await this.doOperation(operation, executionContext, id_or_ids_or_filter, data, {\n ...options,\n isWorkerExecution: true, // Prevents runtime mode check\n });\n } catch (error) {\n this.logger.error('Inline async operation failed', {\n operationPathKey: ResourcesConfig_OperationPathUtils.createOperationPathKeyFromOperation(operation as any),\n ...projectCaughtErrorLogFields(error),\n });\n }\n });\n }\n\n private async callRepository(\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\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n\n const repository = this.repositoriesRegistry.getRepositoryOrThrow(resourceType);\n\n\n const operationRepositoryPath = ResourcesConfig_OperationPathUtils.extractOperationRepositoryPath(operation);\n return repository.doByPath(operationRepositoryPath, executionContext, id_or_ids_or_filter, data, options);\n\n }\n\n\n\n // ================================\n // Business Logic Methods\n // ================================\n\n\n private async create(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n data: any,\n options?: RepositoryOptions\n ): Promise<any> {\n\n this.logDebug('Executing create business operation');\n\n // 0. Clean input data (remove mandatory discard fields)\n const cleanedData = this.repositoryHelper.cleanInputData(data, CoreResourceOperation.CREATE);\n this.logDebug('Data cleaned for create operation', {\n originalKeys: typeof data === 'object' ? Object.keys(data) : 'not-object',\n cleanedKeys: typeof cleanedData === 'object' ? Object.keys(cleanedData) : 'not-object'\n });\n\n // 1. Validate input against operation's requestDto\n const validatedData = await this.validateAndTransformInput(executionContext, cleanedData);\n\n // 2. Extract nested data if nested operations are configured\n const resourceRelationships = this.resourceConfiguration.resourceRelationships;\n const childRelationships = getChildDirectionRelationships(resourceRelationships);\n const relationshipsWithNested = childRelationships.filter(rel =>\n this.getResolvedNestedMutationConfig(rel, CoreResourceOperation.CREATE)\n );\n\n const { parentData, nestedData } = relationshipsWithNested.length > 0\n ? this.extractNestedData(validatedData, relationshipsWithNested, CoreResourceOperation.CREATE)\n : { parentData: validatedData, nestedData: {} };\n\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n this.assertGeneratedPdfCreationSupported(resourceType, executionContext);\n\n // 3. Apply business validation\n const businessValidatedData = await this.applyBusinessValidation(CoreResourceOperation.CREATE, parentData, executionContext);\n\n // 3.5. Validate file fields (fail fast before resource creation)\n // ============================================================================\n // FILE FIELD VALIDATION (Pre-CREATE)\n // ============================================================================\n // This validation runs BEFORE resource creation to fail fast if file references\n // are invalid. However, note the following limitations:\n //\n // 1. Files are validated by fileId lookup but scope validation (ensuring the file\n // belongs to the same organization/user scope) relies on organizationId in\n // ExecutionContext. Scope-based file segregation is not fully implemented.\n //\n // 2. The validation doesn't check if the user has permission to link the specific\n // file - only that the file exists and is in UPLOADED status.\n //\n // 3. For PostgreSQL resources, file metadata lookup still uses MongoDB,\n // which could have latency implications.\n //\n // See: .cursor/plans for file/storage context\n // ============================================================================\n const generatedPdfMaterializations: GeneratedPdfMaterializationRecord[] = [];\n let enrichedData: any;\n let result: any;\n try {\n if (this.fileFieldDetection.hasFileFields(resourceType)) {\n await this.fileOperationHandler.validateFileFieldsForCreate(\n businessValidatedData,\n resourceType,\n executionContext,\n this.buildFileRepositoryOptions(options)\n );\n }\n\n const materialized = await this.materializeGeneratedPdfFieldsForCreate(\n businessValidatedData,\n resourceType,\n executionContext,\n options,\n );\n generatedPdfMaterializations.push(...materialized.materializations);\n const materializedBusinessData = materialized.data;\n\n if (this.fileFieldDetection.hasFileFields(resourceType)) {\n await this.fileOperationHandler.validateFileFieldsForCreate(\n materializedBusinessData,\n resourceType,\n executionContext,\n this.buildFileRepositoryOptions(options),\n this.buildGeneratedPdfProcessingOptions(generatedPdfMaterializations),\n );\n }\n\n // 4. Execute pre-creation business logic\n enrichedData = await this.executePreOperationLogic(CoreResourceOperation.CREATE, materializedBusinessData, executionContext);\n\n // 5. Execute repository operation (create parent) and process nested operations\n result = await this.persistCreatedResourceWithSideEffects({\n operation,\n executionContext,\n enrichedData,\n nestedData,\n relationshipsWithNested,\n resourceType,\n generatedPdfMaterializations,\n options,\n });\n } catch (error) {\n await this.cleanupGeneratedPdfMaterializations(generatedPdfMaterializations, executionContext);\n throw error;\n }\n\n // 8. Execute post-creation business logic (including engine cascading + composition seeding).\n // `options` is threaded so composition-seed re-entrancy depth (compositionSeedDepth)\n // survives createAsSystem → create → post-op (createAsSystem synthesises a fresh EC).\n const processedResult = await this.executePostOperationLogic(CoreResourceOperation.CREATE, result, executionContext, undefined, options);\n\n this.logDebug('Create business operation completed');\n return processedResult;\n }\n\n private async persistCreatedResourceWithSideEffects(params: {\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\n executionContext: ExecutionContext<any>;\n enrichedData: any;\n nestedData: Record<string, any>;\n relationshipsWithNested: ResourceRelationship[];\n resourceType: ResourceType;\n generatedPdfMaterializations: GeneratedPdfMaterializationRecord[];\n options?: RepositoryOptions;\n }): Promise<any> {\n // ALWAYS use transaction for file operations, even without nested operations\n // Extract organizationId early (needed for file operations and transactions)\n const hasFileFields = this.fileFieldDetection.hasFileFields(params.resourceType);\n const hasNestedOperations = params.relationshipsWithNested.length > 0 && Object.keys(params.nestedData).length > 0;\n const fileWorkIsSeparatelyCommitted = this.fileMetadataRequiresSeparateCommit(params.resourceType);\n\n if (hasNestedOperations || hasFileFields) {\n return this.executeResourceTransaction(params.executionContext, async (optionsWithTransaction) => {\n // 1. Create resource within transaction\n const parentResult = await this.callRepository(\n params.operation,\n params.executionContext,\n undefined,\n params.enrichedData,\n {\n ...optionsWithTransaction,\n ...this.buildGeneratedPdfProcessingOptions(params.generatedPdfMaterializations),\n },\n );\n\n const activeRelationships = hasNestedOperations\n ? this.filterRelationshipsByParent(params.relationshipsWithNested, parentResult)\n : [];\n\n if (activeRelationships.length > 0) {\n this.assertNestedMutationAdaptersMatchCurrentResource(activeRelationships, params.executionContext);\n }\n\n const runNestedOperations = async (): Promise<void> => {\n if (activeRelationships.length === 0) {\n return;\n }\n await this.processNestedOperations(\n CoreResourceOperation.CREATE,\n parentResult,\n params.nestedData,\n {},\n activeRelationships,\n params.executionContext,\n optionsWithTransaction\n );\n };\n\n const runFileWork = async (): Promise<void> => {\n if (!hasFileFields) {\n return;\n }\n const resourceId = parentResult?._id?.toString() || parentResult?.id;\n if (!resourceId) {\n return;\n }\n const processFileFields = async (fileOptions: RepositoryOptions | undefined): Promise<void> => {\n await this.fileOperationHandler.processFileFieldsForCreate(\n params.enrichedData,\n params.resourceType,\n resourceId,\n params.executionContext,\n fileOptions,\n this.buildGeneratedPdfProcessingOptions(params.generatedPdfMaterializations),\n );\n };\n\n if (fileWorkIsSeparatelyCommitted) {\n // The row's transaction cannot be shared, so the OUTER options are passed\n // and `executeFileMetadataWork` opens the FILES adapter's own transaction.\n await this.executeFileMetadataWork(params.executionContext, params.options, processFileFields);\n return;\n }\n await processFileFields(optionsWithTransaction);\n };\n\n /**\n * Order by COUPLING, not by adapter.\n *\n * Separately-committed file work runs LAST because it cannot be rolled back\n * with the row: running it after everything that can still fail is the\n * smallest possible window for orphaned file metadata. When it joins the\n * row's transaction no such window exists and the original order stands.\n *\n * Both orders PREDATE this refactor and were selected by adapter with no\n * recorded rationale (single commit, 2026-03-30). They are preserved exactly\n * — unifying them is a behaviour change that deserves its own decision and\n * its own test, not a silent ride along a condition swap.\n */\n if (fileWorkIsSeparatelyCommitted) {\n await runNestedOperations();\n await runFileWork();\n } else {\n await runFileWork();\n await runNestedOperations();\n }\n\n return parentResult;\n }, params.options);\n } else {\n // No file fields, no nested operations - no transaction needed\n return this.callRepository(\n params.operation,\n params.executionContext,\n undefined,\n params.enrichedData,\n {\n ...params.options,\n ...this.buildGeneratedPdfProcessingOptions(params.generatedPdfMaterializations),\n },\n );\n }\n }\n\n private async createMany(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n data: any,\n options?: RepositoryOptions\n ): Promise<any[]> {\n\n this.logDebug('Executing createMany business operation');\n\n const normalizedCreateManyPayload = this.normalizeCreateManyRequestPayload(data, executionContext);\n\n // 0. Clean input data array (remove mandatory discard fields)\n const cleanedDataArray = this.repositoryHelper.cleanInputDataArray(\n normalizedCreateManyPayload.data,\n CoreResourceOperation.CREATE_MANY\n );\n const cleanedRequestPayload = {\n ...normalizedCreateManyPayload,\n data: cleanedDataArray,\n };\n this.logDebug('Data array cleaned for createMany operation', {\n originalCount: normalizedCreateManyPayload.data.length,\n cleanedCount: cleanedDataArray?.length\n });\n\n // 1. Validate input against operation's requestDto\n const validatedData = await this.validateAndTransformInput(executionContext, cleanedRequestPayload);\n\n // 2. Extract nested data per item if nested operations are configured\n const resourceRelationships = this.resourceConfiguration.resourceRelationships;\n const childRelationships = getChildDirectionRelationships(resourceRelationships);\n const relationshipsWithNested = childRelationships.filter(rel =>\n this.getResolvedNestedMutationConfig(rel, CoreResourceOperation.CREATE_MANY)\n );\n\n const validatedDataArray = this.normalizeCreateManyInput(validatedData, executionContext);\n\n const { parentDataArray, nestedDataArray } = relationshipsWithNested.length > 0\n ? this.extractNestedDataArray(validatedDataArray, relationshipsWithNested, CoreResourceOperation.CREATE_MANY, executionContext)\n : { parentDataArray: validatedDataArray, nestedDataArray: [] };\n\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n this.assertGeneratedPdfCreationSupported(resourceType, executionContext);\n\n // 3. Apply business validation\n const businessValidatedData = await this.applyBusinessValidation(CoreResourceOperation.CREATE_MANY, parentDataArray, executionContext);\n\n const hasFileFields = this.fileFieldDetection.hasFileFields(resourceType);\n\n if (hasFileFields) {\n for (const item of businessValidatedData) {\n await this.fileOperationHandler.validateFileFieldsForCreate(\n item,\n resourceType,\n executionContext,\n this.buildFileRepositoryOptions(options)\n );\n }\n }\n\n const generatedPdfMaterializations: GeneratedPdfMaterializationRecord[] = [];\n const generatedPdfMaterializationsByRow: GeneratedPdfMaterializationRecord[][] = [];\n let materializedBusinessData = businessValidatedData;\n try {\n const materializedRows: Record<string, any>[] = [];\n for (const [rowIndex, item] of businessValidatedData.entries()) {\n const materialized = await this.materializeGeneratedPdfFieldsForCreate(\n item,\n resourceType,\n executionContext,\n options,\n );\n const rowMaterializations = materialized.materializations.map((entry) => ({\n ...entry,\n rowIndex,\n }));\n materializedRows.push(materialized.data);\n generatedPdfMaterializationsByRow[rowIndex] = rowMaterializations;\n generatedPdfMaterializations.push(...rowMaterializations);\n }\n materializedBusinessData = materializedRows;\n\n if (hasFileFields) {\n for (const [rowIndex, item] of materializedBusinessData.entries()) {\n await this.fileOperationHandler.validateFileFieldsForCreate(\n item,\n resourceType,\n executionContext,\n this.buildFileRepositoryOptions(options),\n this.buildGeneratedPdfProcessingOptions(generatedPdfMaterializationsByRow[rowIndex] ?? []),\n );\n }\n }\n } catch (error) {\n await this.cleanupGeneratedPdfMaterializations(generatedPdfMaterializations, executionContext);\n throw error;\n }\n\n let enrichedData: any;\n try {\n // 4. Execute pre-creation business logic\n enrichedData = await this.executePreOperationLogic(CoreResourceOperation.CREATE_MANY, materializedBusinessData, executionContext);\n } catch (error) {\n await this.cleanupGeneratedPdfMaterializations(generatedPdfMaterializations, executionContext);\n throw error;\n }\n\n const hasNestedOperations = relationshipsWithNested.length > 0 &&\n nestedDataArray.some(item => Object.keys(item).length > 0);\n const requiresTransactionalBulkCreate = hasNestedOperations || hasFileFields;\n\n let result: any[];\n\n if (requiresTransactionalBulkCreate) {\n if (hasNestedOperations) {\n this.assertNestedMutationAdaptersMatchCurrentResource(relationshipsWithNested, executionContext);\n }\n try {\n result = await this.executeResourceTransaction(executionContext, async (optionsWithTransaction) => {\n const parentResults = await this.callRepository(\n operation,\n executionContext,\n undefined,\n enrichedData,\n {\n ...optionsWithTransaction,\n ...this.buildGeneratedPdfProcessingOptions(generatedPdfMaterializations, generatedPdfMaterializationsByRow),\n },\n );\n\n if (hasFileFields) {\n if (this.fileMetadataRequiresSeparateCommit(resourceType)) {\n await this.executeFileMetadataWork(\n executionContext,\n options,\n async (fileOptions) => this.processBulkCreateFileFields(\n parentResults,\n enrichedData,\n resourceType,\n executionContext,\n fileOptions,\n this.buildGeneratedPdfProcessingOptions(generatedPdfMaterializations, generatedPdfMaterializationsByRow),\n ),\n );\n } else {\n await this.processBulkCreateFileFields(\n parentResults,\n enrichedData,\n resourceType,\n executionContext,\n optionsWithTransaction,\n this.buildGeneratedPdfProcessingOptions(generatedPdfMaterializations, generatedPdfMaterializationsByRow),\n );\n }\n }\n\n await this.processBulkNestedOperations(\n CoreResourceOperation.CREATE_MANY,\n parentResults,\n nestedDataArray,\n [],\n relationshipsWithNested,\n executionContext,\n optionsWithTransaction\n );\n\n return parentResults;\n }, options);\n } catch (error) {\n await this.cleanupGeneratedPdfMaterializations(generatedPdfMaterializations, executionContext);\n throw error;\n }\n } else {\n // 5. Execute repository operation\n try {\n result = await this.callRepository(\n operation,\n executionContext,\n undefined,\n enrichedData,\n {\n ...options,\n ...this.buildGeneratedPdfProcessingOptions(generatedPdfMaterializations, generatedPdfMaterializationsByRow),\n },\n );\n } catch (error) {\n await this.cleanupGeneratedPdfMaterializations(generatedPdfMaterializations, executionContext);\n throw error;\n }\n }\n\n // 6. Execute post-creation business logic (including engine cascading)\n const processedResult = await this.executePostOperationLogic(\n CoreResourceOperation.CREATE_MANY,\n result,\n executionContext,\n undefined,\n options,\n );\n\n this.logDebug('CreateMany business operation completed', { resultCount: processedResult?.length });\n return processedResult;\n }\n\n\n /**\n * Resolve operation variant based on dataMode.\n * Maps dataMode to appropriate variantKey:\n * - RAW -> default variant (no variantKey)\n * - SUMMARY -> 'summary' variant (throws if not found)\n * - CONTEXT -> 'context' variant (throws if not found)\n *\n * Throws error if requested variant doesn't exist (fail-fast).\n */\n private resolveOperationVariant(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n dataMode: DataMode\n ): ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema> {\n // Delegate to the registry's shared data-mode resolution (single source of\n // truth with the controller's authorization-time resolution). RAW → base op;\n // SUMMARY/CONTEXT → keyed auto-variant when declared (READ/LIST); SEARCH-like\n // → base op (search is summary by construction, so it has no distinct\n // data-mode variant); otherwise fail fast on a genuinely missing variant.\n const resolved = this.resourcesRegistry.getOperationForDataMode(operation, dataMode) as ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\n this.logDebug('Resolved operation for dataMode', {\n operationIdentifier: operation.operationIdentifier,\n dataMode,\n resolvedVariantKey: resolved.variantKey,\n fellBackToBaseOperation: resolved === operation,\n });\n return resolved;\n }\n\n private async read(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n options?: ServiceOptions\n ): Promise<any> {\n\n // Phase 5 / P5-H (H1) — pre-operation hook dispatch on READ.\n // Symmetric with the existing CREATE/UPDATE/DELETE pre-hook\n // dispatch sites, this fires the registered pre-operation hooks\n // (notably the Phase-5 LAZY guard installed by\n // `wireLazyAccessGuards`) before any data is read. The `data`\n // payload forwarded to hooks is the raw `id_or_ids_or_filter`\n // — LAZY guards ignore it, but future read-side pre-hooks\n // (audit-on-read, cache-warming, access-policy-enforcement)\n // can inspect the requested key. Cost is O(1) Map lookup +\n // empty for-loop when no hook is registered for the resource.\n // Failure semantics: any throw propagates to the caller (P5-A\n // = A1 short-circuits the read), matching the mutating-op pre\n // -hook contract.\n await this.executePreOperationLogic(\n CoreResourceOperation.READ,\n id_or_ids_or_filter,\n executionContext,\n );\n\n // Extract dataMode from ServiceOptions, or infer from operation's variantKey\n // This allows direct URL calls to /resource/{id}/context to use CONTEXT mode\n let dataMode = options?.dataMode ?? DataMode.RAW;\n\n // If operation already has a variantKey (direct URL call), infer dataMode from it\n if (operation.variantKey === OPERATION_VARIANT_KEY.CONTEXT) {\n dataMode = DataMode.CONTEXT;\n } else if (operation.variantKey === OPERATION_VARIANT_KEY.SUMMARY) {\n dataMode = DataMode.SUMMARY;\n }\n\n // Resolve operation variant based on dataMode\n const resolvedOperation = this.resolveOperationVariant(operation, dataMode);\n\n this.logDebug('Executing read business operation', { id_or_ids_or_filter, dataMode, variantKey: resolvedOperation.variantKey });\n\n // 1. Execute repository operation with resolved variant (uses correct repositoryDto)\n const result = await this.callRepository(resolvedOperation, executionContext, id_or_ids_or_filter, undefined, options);\n\n if (!result) {\n return null;\n }\n\n // 2. Process nested read operations if configured\n const resourceRelationships = this.resourceConfiguration.resourceRelationships;\n const childRelationships = getChildDirectionRelationships(resourceRelationships);\n const relationshipsWithNestedRead = childRelationships.filter(rel =>\n this.getResolvedNestedReadConfig(rel)\n );\n\n // Application point #2: Nested READ — filter by discriminator/condition using\n // the read result (parent data) so we only fetch nested children for relationships\n // that are active for this particular parent resource variant.\n if (relationshipsWithNestedRead.length > 0) {\n const activeReadRelationships = this.filterRelationshipsByParent(relationshipsWithNestedRead, result);\n if (activeReadRelationships.length > 0) {\n await this.processNestedRead(result, activeReadRelationships, executionContext, options);\n }\n }\n\n // 3. Process based on DataMode\n let processedResult = result;\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n\n if (dataMode !== DataMode.RAW) {\n // Analyze context needs for virtual fields\n const needs = this.populationService.analyzeContextNeeds(resourceType);\n\n // Fetch computation context if needed (for virtual field computation only)\n let computationContext: { objectContext?: any; userContext?: any } = {};\n if (needs.needsObjectContext || needs.needsUserContext) {\n computationContext = await this.populationService.fetchComputationContext(\n resourceType, result, needs, executionContext\n );\n }\n\n // Compute virtual fields with fault tolerance\n processedResult = await this.virtualFieldsService.computeVirtualFields(\n resourceType, processedResult, executionContext,\n {\n faultTolerant: true,\n includeContextDependent: needs.needsObjectContext || needs.needsUserContext,\n objectContext: computationContext.objectContext,\n userContext: computationContext.userContext,\n forSummary: dataMode === DataMode.SUMMARY,\n }\n );\n\n // Apply population based on DataMode\n // Extract populateFiles option from ServiceOptions (default: true)\n const populateFiles = options?.populateFiles !== false;\n const populationOptions = { populateFiles };\n\n if (dataMode === DataMode.SUMMARY) {\n processedResult = await this.populationService.populateForSummary(\n resourceType, processedResult, executionContext, populationOptions, options\n );\n } else if (dataMode === DataMode.CONTEXT) {\n processedResult = await this.populationService.populateForContext(\n resourceType, processedResult, executionContext, populationOptions, options\n );\n }\n }\n\n // 3. Apply business context enrichment\n const enrichedResult = await this.enrichBusinessContext(CoreResourceOperation.READ, processedResult, executionContext);\n\n this.logDebug('Read business operation completed', { dataMode });\n return enrichedResult;\n }\n\n\n private async update(\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\n this.logDebug('Executing update business operation', { id_or_ids_or_filter });\n\n if (!id_or_ids_or_filter) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { operation: 'UPDATE', missingParameter: 'id_or_ids_or_filter' },\n });\n }\n\n if (!data) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { operation: 'UPDATE', missingParameter: 'data' },\n });\n }\n\n // 0. Clean input data (remove mandatory discard fields)\n const cleanedData = this.repositoryHelper.cleanInputData(data, CoreResourceOperation.UPDATE);\n this.logDebug('Data cleaned for update operation', {\n originalKeys: typeof data === 'object' ? Object.keys(data) : 'not-object',\n cleanedKeys: typeof cleanedData === 'object' ? Object.keys(cleanedData) : 'not-object'\n });\n\n // 1. Validate input against operation's requestDto\n const validatedData = await this.validateAndTransformInput(executionContext, cleanedData);\n\n // 1.5. Extract nested data if nested operations are configured\n const resourceRelationships = this.resourceConfiguration.resourceRelationships;\n const childRelationships = getChildDirectionRelationships(resourceRelationships);\n const relationshipsWithNested = childRelationships.filter(rel =>\n this.getResolvedNestedMutationConfig(rel, CoreResourceOperation.UPDATE)\n );\n\n const { parentData, nestedData, deleteData } = relationshipsWithNested.length > 0\n ? this.extractNestedDataForUpdate(validatedData, relationshipsWithNested)\n : { parentData: validatedData, nestedData: {}, deleteData: {} };\n\n // 2. Get current state - for single updates only (bulk update skips current state fetching)\n let currentState = null;\n if (typeof id_or_ids_or_filter === 'string') {\n currentState = await this.fetchCurrentObjectForOperation(\n CoreResourceOperation.UPDATE,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n id_or_ids_or_filter,\n executionContext,\n options,\n );\n if (!currentState) {\n throw this.errorBuilder.buildError(ErrorType.NOT_FOUND, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: { operation: 'UPDATE', id_or_ids_or_filter },\n });\n }\n }\n\n // 3. Apply business validation for changes\n const businessValidatedData = await this.applyBusinessValidation(CoreResourceOperation.UPDATE, parentData, executionContext, currentState);\n\n // 3.5. Validate file fields (fail fast before resource update)\n // Note: we only reuse validateFileFieldsForCreate() when this UPDATE path does\n // not have a persisted current state to diff against. When currentState exists,\n // processFileFieldsForUpdate() owns validation of newly introduced file ids\n // inside the same transaction as the parent update.\n // ============================================================================\n // FILE FIELD VALIDATION (Pre-UPDATE)\n // ============================================================================\n // Same limitations as CREATE validation apply here. Additionally:\n //\n // 1. Only NEW file references are validated. The old-to-new file transition\n // (unlinking old files, linking new ones) happens in processFileFieldsForUpdate\n // which runs AFTER the resource update, not during validation.\n //\n // 2. If a file being replaced is still referenced by other resources, this\n // validation doesn't check for that. File reference counting is not implemented.\n //\n // 3. Bulk UPDATE_MANY now has its own dedicated path: it validates explicit\n // file-field mutations and reloads per-parent snapshots before processing\n // file diffs inside the transactional bulk branch.\n //\n // See: .cursor/plans for file/storage context\n // ============================================================================\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n if (this.fileFieldDetection.hasFileFields(resourceType) && !currentState) {\n try {\n await this.fileOperationHandler.validateFileFieldsForCreate(\n businessValidatedData,\n resourceType,\n executionContext,\n this.buildFileRepositoryOptions(options)\n );\n } catch (error) {\n // File validation errors should fail the operation\n throw error;\n }\n }\n\n // 4. Execute pre-update business logic\n const enrichedData = await this.executePreOperationLogic(CoreResourceOperation.UPDATE, businessValidatedData, executionContext, currentState);\n\n // 5. Execute repository operation (update parent) and process nested operations\n // ALWAYS use transaction for file operations, even without nested operations\n // Extract organizationId early (needed for file operations and transactions)\n const hasFileFields = this.fileFieldDetection.hasFileFields(resourceType);\n const hasNestedOperations = relationshipsWithNested.length > 0 && (Object.keys(nestedData).length > 0 || Object.keys(deleteData).length > 0);\n // Note: File operations only for single updates (currentState is only fetched for single updates)\n const canProcessFileFields = hasFileFields && currentState && typeof id_or_ids_or_filter === 'string';\n const fileWorkIsSeparatelyCommitted = this.fileMetadataRequiresSeparateCommit(resourceType);\n let result: any;\n\n if (hasNestedOperations || canProcessFileFields) {\n result = await this.executeResourceTransaction(executionContext, async (optionsWithTransaction) => {\n // 1. Update resource within transaction\n const parentResult = await this.callRepository(operation, executionContext, id_or_ids_or_filter, enrichedData, optionsWithTransaction);\n\n const activeRelationships = hasNestedOperations\n ? this.filterRelationshipsByParent(relationshipsWithNested, parentResult)\n : [];\n\n if (activeRelationships.length > 0) {\n this.assertNestedMutationAdaptersMatchCurrentResource(activeRelationships, executionContext);\n }\n\n const runNestedOperations = async (): Promise<void> => {\n if (activeRelationships.length === 0) {\n return;\n }\n await this.processNestedOperations(\n CoreResourceOperation.UPDATE,\n parentResult,\n nestedData,\n deleteData,\n activeRelationships,\n executionContext,\n optionsWithTransaction\n );\n };\n\n const runFileWork = async (): Promise<void> => {\n if (!canProcessFileFields) {\n return;\n }\n const resourceId = typeof id_or_ids_or_filter === 'string'\n ? id_or_ids_or_filter\n : parentResult?._id?.toString() || parentResult?.id;\n if (!resourceId) {\n return;\n }\n const processFileFields = async (fileOptions: RepositoryOptions | undefined): Promise<void> => {\n await this.fileOperationHandler.processFileFieldsForUpdate(\n enrichedData,\n currentState,\n resourceType,\n resourceId,\n executionContext,\n fileOptions\n );\n };\n\n if (fileWorkIsSeparatelyCommitted) {\n // The row's transaction cannot be shared, so the OUTER options are passed\n // and `executeFileMetadataWork` opens the FILES adapter's own transaction.\n await this.executeFileMetadataWork(executionContext, options, processFileFields);\n return;\n }\n await processFileFields(optionsWithTransaction);\n };\n\n // Order by COUPLING, not by adapter — see the CREATE sibling for the full\n // rationale. Separately-committed file work runs LAST because it cannot roll\n // back with the row; both orders are preserved exactly as they were.\n if (fileWorkIsSeparatelyCommitted) {\n await runNestedOperations();\n await runFileWork();\n } else {\n await runFileWork();\n await runNestedOperations();\n }\n\n return parentResult;\n }, options);\n } else {\n // No file fields, no nested operations - no transaction needed\n result = await this.callRepository(operation, executionContext, id_or_ids_or_filter, enrichedData, options);\n }\n\n // 7. Execute post-update business logic (including engine cascading)\n const processedResult = await this.executePostOperationLogic(\n CoreResourceOperation.UPDATE,\n result,\n executionContext,\n currentState,\n options,\n );\n\n this.logDebug('Update business operation completed');\n return processedResult;\n }\n\n private async executeGeneratedFileRegenerateOperation(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n fieldName: string,\n executionContext: ExecutionContext<any>,\n idOrIdsOrFilter: IdOrIdsOrFilterType | undefined,\n currentObject: any,\n options?: RepositoryOptions,\n ): Promise<{ file: { fileId: string; updatedAt: Date }; resource: any }> {\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const resourceId = typeof idOrIdsOrFilter === 'string'\n ? idOrIdsOrFilter\n : this.getResourceIdValue(currentObject);\n if (!resourceId || !currentObject) {\n throw this.errorBuilder.buildError(ErrorType.NOT_FOUND, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: { operation: operation.operationIdentifier, fieldName, idOrIdsOrFilter },\n });\n }\n\n const fileField = this.fileFieldDetection.getFileFieldMetadata(resourceType, fieldName);\n if (fileField?.fileMetadata.generation?.source !== FileGenerationSource.PDF_TEMPLATE) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `Generated file regenerate operation targets a non-generated PDF field: \"${resourceType}.${fieldName}\".`,\n resourceType,\n fieldName,\n },\n });\n }\n\n this.assertGeneratedFileMaterializationCommitsWithRow(\n resourceType,\n executionContext,\n 'Generated PDF regenerate is not yet supported for PostgreSQL-backed resources because FILES metadata is Mongo-backed and cannot be swapped atomically with the parent row.',\n { fieldName },\n );\n\n const generated = await this.pdfGenerationOrchestrator.generateForField({\n resourceType,\n parentRecord: currentObject,\n fieldName,\n fileMetadata: fileField.fileMetadata,\n executionContext,\n repositoryOptions: this.buildFileRepositoryOptions(options),\n renderPhase: PdfGenerationRenderPhase.REGENERATE,\n locale: getConfiguredPrimaryLanguage(this.appConfigService.config),\n defaultLocale: getConfiguredPrimaryLanguage(this.appConfigService.config),\n });\n const generatedFileValue = {\n fileId: generated.fileId,\n updatedAt: generated.updatedAt,\n };\n const updatePatch = this.buildGeneratedFileFieldPatch(fieldName, generatedFileValue);\n const repositoryPatch = this.buildGeneratedFileRepositoryPatch(fieldName, generatedFileValue);\n const previousGeneratedFileId = this.getGeneratedFileIdAtPath(currentObject, fieldName);\n const processingOptions = this.buildGeneratedPdfProcessingOptions([{\n ...generated,\n resourceType,\n fieldName,\n }]);\n\n try {\n const updatedResource = await this.executeResourceTransaction(executionContext, async (optionsWithTransaction) => {\n const parentResult = await this.callRepository(\n operation,\n executionContext,\n resourceId,\n repositoryPatch,\n {\n ...optionsWithTransaction,\n ...processingOptions,\n },\n );\n\n await this.fileOperationHandler.processFileFieldsForUpdate(\n updatePatch,\n currentObject,\n resourceType,\n resourceId,\n executionContext,\n optionsWithTransaction,\n processingOptions,\n );\n\n await this.fileOperationHandler.softDeleteGeneratedFileReplacement({\n fileId: previousGeneratedFileId,\n replacementFileId: generated.fileId,\n fieldName,\n executionContext,\n options: optionsWithTransaction,\n });\n\n return parentResult;\n }, options);\n\n return {\n file: generatedFileValue,\n resource: updatedResource,\n };\n } catch (error) {\n await this.cleanupGeneratedPdfMaterializations([{\n ...generated,\n resourceType,\n fieldName,\n }], executionContext);\n throw error;\n }\n }\n\n private async updateMany(\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\n this.logDebug('Executing updateMany business operation', { id_or_ids_or_filter });\n\n if (!id_or_ids_or_filter) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { operation: 'UPDATE_MANY', missingParameter: 'id_or_ids_or_filter' },\n });\n }\n\n if (!data) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { operation: 'UPDATE_MANY', missingParameter: 'data' },\n });\n }\n\n // 0. Clean input data (remove mandatory discard fields - preserve _id for updateMany)\n const cleanedData = this.repositoryHelper.cleanInputData(data, CoreResourceOperation.UPDATE_MANY);\n this.logDebug('Data cleaned for updateMany operation', {\n originalKeys: typeof data === 'object' ? Object.keys(data) : 'not-object',\n cleanedKeys: typeof cleanedData === 'object' ? Object.keys(cleanedData) : 'not-object'\n });\n\n // 1. Validate input against operation's requestDto\n const validatedData = await this.validateAndTransformInput(executionContext, cleanedData);\n\n // 1.5. Extract nested data if nested operations are configured\n const resourceRelationships = this.resourceConfiguration.resourceRelationships;\n const childRelationships = getChildDirectionRelationships(resourceRelationships);\n const relationshipsWithNested = childRelationships.filter(rel =>\n this.getResolvedNestedMutationConfig(rel, CoreResourceOperation.UPDATE_MANY)\n );\n\n const { parentData, nestedData, deleteData } = relationshipsWithNested.length > 0\n ? this.extractNestedDataForUpdate(validatedData, relationshipsWithNested)\n : { parentData: validatedData, nestedData: {}, deleteData: {} };\n\n // 2. Apply business validation for bulk changes (no current state fetching for bulk operations)\n const businessValidatedData = await this.applyBusinessValidation(CoreResourceOperation.UPDATE_MANY, parentData, executionContext);\n\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const hasFileFields = this.fileFieldDetection.hasFileFields(resourceType);\n const hasBulkFileMutations = hasFileFields && this.hasExplicitFileFieldMutations(resourceType, businessValidatedData);\n if (hasBulkFileMutations) {\n await this.fileOperationHandler.validateFileFieldsForCreate(\n businessValidatedData,\n resourceType,\n executionContext,\n options\n );\n }\n\n // 3. Execute pre-update business logic.\n //\n // Phase 3.2 fix (review Findings #1/#2): if any pre-operation hook is\n // registered for this resource, load the bulk target snapshots so\n // the hook payload can be materialised as `Array<{...patch, _id}>`\n // inside `executePreOperationLogic` (per-row anchors are required\n // by Level-B seeding's P3-F=F1 invariant — the dispatcher's\n // `runResourceLifecycle` throws CONFIGURATION without `_id`).\n //\n // **Cost gate**: the snapshot load only runs when a hook is actually\n // subscribed — UPDATE_MANY callers without any wired hook keep their\n // pre-Phase-3.2 cost envelope (no extra read). This trade-off is the\n // explicit framework convention: pre-hook registration is the opt-in\n // for the per-row materialisation cost.\n //\n // The resolved `currentStates` are NOT reused beyond pre-hook\n // dispatch — UPDATE_MANY's later transactional / file-mutation\n // paths still load their own per-parent snapshots when needed\n // (see `loadBulkParentStateMap` further down). Re-loading there is\n // intentional: it runs INSIDE the transaction (which the pre-hook\n // load does not), and the snapshot semantics differ.\n const preHookCurrentStates = this.servicesRegistry.hasPreOperationHooks(resourceType)\n ? await this.loadBulkTargetResources(executionContext, id_or_ids_or_filter, options)\n : undefined;\n let enrichedData: any;\n if (preHookCurrentStates !== undefined && preHookCurrentStates.length === 0) {\n // Mirror DELETE_MANY's empty-selector early-exit: no rows ⇒ no\n // pre-hook dispatch (Level-B seeds have nothing to anchor to,\n // and any non-seed hook is observation-only on a zero-row op).\n enrichedData = businessValidatedData;\n } else {\n enrichedData = await this.executePreOperationLogic(\n CoreResourceOperation.UPDATE_MANY,\n businessValidatedData,\n executionContext,\n preHookCurrentStates,\n );\n }\n\n const hasNestedOperations = relationshipsWithNested.length > 0 &&\n (Object.keys(nestedData).length > 0 || Object.keys(deleteData).length > 0);\n const requiresTransactionalBulkUpdate = hasNestedOperations || hasBulkFileMutations;\n\n let result: any[];\n\n if (requiresTransactionalBulkUpdate) {\n // UPDATE_MANY shares the same limitation as CREATE_MANY: once nested payloads\n // or file-field mutations are present, the service currently relies on\n // MongoDBService to own the outer transaction while parent updates and\n // follow-up side effects are replayed.\n this.assertMongoBulkTransactionSupport(\n executionContext,\n hasNestedOperations\n ? 'Bulk nested update transactions currently require MongoDB-backed resources'\n : 'Bulk update file-field transactions currently require MongoDB-backed resources'\n );\n\n result = await this.executeResourceTransaction(\n executionContext,\n async (optionsWithTransaction) => {\n const currentStatesById = hasBulkFileMutations\n ? await this.loadBulkParentStateMap(executionContext, id_or_ids_or_filter, optionsWithTransaction)\n : new Map<string, any>();\n const parentResults = await this.callRepository(\n operation,\n executionContext,\n id_or_ids_or_filter,\n enrichedData,\n optionsWithTransaction\n );\n\n if (Object.keys(deleteData).length > 0 && Array.isArray(parentResults) && parentResults.length > 1) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n operation: CoreResourceOperation.UPDATE_MANY,\n parentResultsCount: parentResults.length,\n reason: 'nested delete payloads in UPDATE_MANY are only supported when the mutation targets exactly one parent resource',\n },\n }\n );\n }\n\n if (hasBulkFileMutations) {\n await this.processBulkUpdateFileFields(\n parentResults,\n currentStatesById,\n enrichedData,\n resourceType,\n executionContext,\n optionsWithTransaction\n );\n }\n\n // Contract: UPDATE_MANY uses broadcast semantics for nested create/update payloads.\n // The validated nestedData object is treated as one shared envelope and replayed\n // once per matched parent result. This is intentional: bulk parent mutation +\n // nested mutation means \"apply this same nested update plan to every parent that\n // matched the bulk selector\". Nested deletes remain stricter because replaying the\n // same child-id delete list across multiple parents is ambiguous and unsafe.\n await this.processBulkNestedOperations(\n CoreResourceOperation.UPDATE_MANY,\n parentResults,\n Array.isArray(parentResults) ? parentResults.map(() => nestedData) : [],\n Array.isArray(parentResults) ? parentResults.map(() => deleteData) : [],\n relationshipsWithNested,\n executionContext,\n optionsWithTransaction\n );\n\n return parentResults;\n },\n options,\n );\n } else {\n // 4. Execute repository operation\n result = await this.callRepository(operation, executionContext, id_or_ids_or_filter, enrichedData, options);\n }\n\n // 5. Execute post-update business logic (including engine cascading)\n const processedResult = await this.executePostOperationLogic(\n CoreResourceOperation.UPDATE_MANY,\n result,\n executionContext,\n undefined,\n options,\n );\n\n this.logDebug('UpdateMany business operation completed', { resultCount: processedResult?.length });\n return processedResult;\n }\n\n private async delete(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<string | string[]> {\n\n this.logDebug('Executing delete business operation', { id_or_ids_or_filter });\n\n if (!id_or_ids_or_filter) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { operation: 'DELETE', missingParameter: 'id_or_ids_or_filter' },\n });\n }\n\n // 1. Get current state - for single deletes only (bulk delete skips current state fetching)\n let currentState = null;\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const hasFileFields = this.fileFieldDetection.hasFileFields(resourceType);\n\n // ============================================================================\n // FILE MANAGEMENT DELETE NOTES\n // ============================================================================\n //\n // Current contract:\n // 1. Parent deletes fail closed if pre-delete file cleanup throws.\n // 2. Mongo-backed parents still keep parent + file metadata work in one Mongo\n // transaction context.\n // 3. PostgreSQL-backed parents use a best-effort split boundary: file metadata\n // cleanup runs through the Mongo-backed FILES seam first, then parent delete\n // runs inside the PostgreSQL transaction.\n //\n // Remaining limitations:\n // 1. Cross-database delete is still best-effort, not one ACID transaction.\n // 2. File storage cleanup stays outside the parent DB rollback boundary and is\n // intentionally owned later by the cleanup batch.\n // 3. Lifecycle-delete coverage for child resources that own file fields is\n // still narrower than the direct parent delete path.\n //\n // NOTE: organizationId validation is intentionally NOT done here. Tenant isolation\n // is enforced at the FilesBackendService level, not duplicated in the service handler.\n // See: .cursor/plans for file/storage context\n //\n // ============================================================================\n\n if (typeof id_or_ids_or_filter === 'string') {\n currentState = await this.fetchCurrentObjectForOperation(\n CoreResourceOperation.DELETE,\n resourceType,\n id_or_ids_or_filter,\n executionContext,\n options,\n );\n if (!currentState) {\n if (\n this.hasContextAddressedSingletonParentScope(operation, executionContext)\n || this.hasContextAddressedAssociationParentScope(operation, executionContext)\n || executionContext.getContextResourceIds().size > 0\n ) {\n throw this.errorBuilder.buildError(ErrorType.NOT_FOUND, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONTROLLER_RESOURCE_NOT_FOUND,\n context: {\n operation: CoreResourceOperation.DELETE,\n id_or_ids_or_filter,\n reason: 'Explicit child id does not match the context-addressed operation scope',\n },\n });\n }\n return '';\n }\n\n // 2. Check business constraints for deletion\n await this.validateDeletionConstraints(currentState, executionContext);\n\n // 3. Execute pre-deletion business logic\n await this.executePreOperationLogic(CoreResourceOperation.DELETE, currentState, executionContext);\n\n // 4. Execute repository operation plus lifecycle cascading inside the\n // resource transaction so child-delete failures can still roll back the\n // parent row on same-adapter paths.\n const result = await this.executeResourceTransaction(executionContext, async (optionsWithTransaction) => {\n if (hasFileFields) {\n if (this.fileMetadataRequiresSeparateCommit(resourceType)) {\n await this.executeFileMetadataWork(\n executionContext,\n options,\n async (fileOptions) => this.fileOperationHandler.processFileFieldsForDelete(\n resourceType,\n id_or_ids_or_filter as string,\n executionContext,\n fileOptions\n )\n );\n } else {\n await this.fileOperationHandler.processFileFieldsForDelete(\n resourceType,\n id_or_ids_or_filter as string,\n executionContext,\n optionsWithTransaction\n );\n }\n }\n\n const deleteResult = await this.callRepository(\n operation,\n executionContext,\n id_or_ids_or_filter,\n undefined,\n optionsWithTransaction\n );\n\n await this.executeLifecycleOperations(\n CoreResourceOperation.DELETE,\n deleteResult,\n executionContext,\n currentState,\n optionsWithTransaction\n );\n\n // RAG removal seam — ROW DELETE (single). Registered post-commit on the delete transaction,\n // so an aborted delete never destroys chunks for a row that survived.\n const deletedRowId = (typeof deleteResult === 'string' && deleteResult.length > 0)\n ? deleteResult\n : (currentState ? this.getResourceIdValue(currentState) : undefined);\n if (deletedRowId) {\n await this.runRagChunkRemovalForDeletedRows(\n resourceType,\n [deletedRowId],\n 'row-delete',\n optionsWithTransaction,\n );\n }\n\n return deleteResult;\n }, options);\n\n // 5. Execute non-cascading post-deletion logic after the delete transaction commits.\n await this.executeAdditionalPostOperationLogic(\n CoreResourceOperation.DELETE,\n result,\n executionContext,\n currentState,\n options,\n );\n\n this.logDebug('Delete business operation completed');\n return result;\n }\n\n const deleteManyOperationPath = this.resourcesRegistry.getServiceOperationPathDefault(\n resourceType,\n CoreResourceOperation.DELETE_MANY\n );\n const deleteManyOperation = this.resourcesRegistry.getOperationFromPath(deleteManyOperationPath) as ResourceConfiguration_Operation<\n TCustomOperationEnum,\n TCoreOperationEnum,\n TMainSchema\n >;\n\n return this.deleteMany(deleteManyOperation, executionContext, id_or_ids_or_filter, options);\n }\n\n private async deleteMany(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter?: IdOrIdsOrFilterType,\n options?: RepositoryOptions\n ): Promise<string[]> {\n\n this.logDebug('Executing deleteMany business operation', { id_or_ids_or_filter });\n\n if (!id_or_ids_or_filter) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { operation: 'DELETE_MANY', missingParameter: 'id_or_ids_or_filter' },\n });\n }\n\n // 1. Fetch resources BEFORE deletion so post-delete lifecycle logic can still\n // evaluate relationship activation against real parent snapshots. The same\n // snapshot set is also reused for pre-delete file handling.\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const hasFileFields = this.fileFieldDetection.hasFileFields(resourceType);\n const childRelationships = getChildDirectionRelationships(\n this.resourceConfiguration.resourceRelationships\n );\n const fileWorkIsSeparatelyCommitted = this.fileMetadataRequiresSeparateCommit(resourceType);\n const hasLifecycleDeleteRelationships = childRelationships\n .some((relationship) => this.getResolvedLifecycleOnParentDelete(relationship)?.enabled === true);\n const hasFileOwningChildRelationships = childRelationships\n .some((relationship) => this.fileFieldDetection.hasFileFields(relationship.resourceType2 as ResourceType));\n const currentStates = await this.loadBulkTargetResources(executionContext, id_or_ids_or_filter, options);\n\n // Pre-deletion business logic dispatch (Phase-3 P3-A=A1: hook throws abort the\n // entire deleteMany before any side-effect — file cleanup, transaction, repo\n // delete, lifecycle cascades, post-hooks). Symmetric with the singular DELETE\n // path at L3143 and with CREATE_MANY/UPDATE_MANY which call this method on\n // their own data shape. The payload is the resolved `currentStates` array (NOT\n // the raw filter) so hooks observe the same row snapshots that the post-hook\n // and lifecycle layers receive. Skipped when no rows matched, matching the\n // singular DELETE early-exit on missing currentState.\n if (currentStates.length > 0) {\n await this.executePreOperationLogic(\n CoreResourceOperation.DELETE_MANY,\n currentStates,\n executionContext,\n );\n }\n\n // ============================================================================\n // FILE MANAGEMENT DELETE_MANY NOTES\n // ============================================================================\n //\n // Current contract:\n // 1. Bulk deletes now keep lifecycle cascades inside the parent resource\n // transaction whenever a shared same-adapter transaction is available.\n // 2. MongoDB-backed bulk deletes with file fields reuse that same\n // transaction for file metadata cleanup plus parent-row deletion.\n // 3. Non-Mongo bulk deletes without lifecycle still fail closed before the\n // repository delete if any resource-level file cleanup throws.\n // 4. File cleanup no longer inherits a foreign PostgreSQL transaction when the\n // parent bulk delete is called inside an outer SQL transaction.\n //\n // Remaining limitations:\n // 1. PostgreSQL-backed bulk deletes still have no shared parent+file rollback\n // boundary because FILES remains Mongo-backed by design.\n // 2. Fetching all resources before deletion can be expensive for large\n // datasets. Consider streaming/pagination for very large deletes.\n // 3. Scope-based cleanup still relies on FilesBackendService boundaries rather\n // than service-layer duplication.\n //\n // NOTE: organizationId validation is intentionally NOT done here. Tenant isolation\n // is enforced at the FilesBackendService level, not duplicated in the service handler.\n //\n // ============================================================================\n\n if (\n this.fileMetadataRequiresSeparateCommit(resourceType)\n && hasFileOwningChildRelationships\n && !hasLifecycleDeleteRelationships\n ) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: 'PostgreSQL bulk delete is not supported for resources with file-owning child relationships unless service-managed lifecycle delete is enabled',\n resourceType,\n },\n }\n );\n }\n\n const processBulkDeleteFileCleanup = async (fileRepositoryOptions?: RepositoryOptions) => {\n const batchSize = 100;\n for (let i = 0; i < currentStates.length; i += batchSize) {\n const batch = currentStates.slice(i, i + batchSize);\n\n for (const resource of batch) {\n const resourceId = resource._id?.toString() || resource.id;\n if (!resourceId) {\n this.logger.warn('Resource missing ID in bulk delete, skipping file processing', {\n resource,\n });\n continue;\n }\n\n await this.fileOperationHandler.processFileFieldsForDelete(\n resourceType,\n resourceId,\n executionContext,\n fileRepositoryOptions\n );\n }\n }\n };\n\n /**\n * A transaction is required when file cleanup will run INSIDE it — that is the\n * only reason the row delete and the cleanup must succeed or fail together.\n * When file work is committed separately there is nothing to bind, so opening a\n * transaction for that reason alone would buy no atomicity (and would fail\n * outright on a standalone MongoDB).\n */\n const requiresTransactionalBulkDelete = hasLifecycleDeleteRelationships\n || (hasFileFields && !fileWorkIsSeparatelyCommitted);\n\n const processBulkDeleteWithinTransaction = async (\n optionsWithTransaction: RepositoryOptions\n ): Promise<string[]> => {\n if (hasFileFields) {\n if (fileWorkIsSeparatelyCommitted) {\n await this.executeFileMetadataWork(\n executionContext,\n optionsWithTransaction,\n async (fileOptions) => processBulkDeleteFileCleanup(fileOptions)\n );\n } else {\n await processBulkDeleteFileCleanup(optionsWithTransaction);\n }\n }\n\n const deleteResult = await this.callRepository(\n operation,\n executionContext,\n id_or_ids_or_filter,\n undefined,\n optionsWithTransaction\n );\n\n if (hasLifecycleDeleteRelationships) {\n await this.executeLifecycleOperations(\n CoreResourceOperation.DELETE_MANY,\n deleteResult,\n executionContext,\n currentStates,\n optionsWithTransaction\n );\n }\n\n // RAG removal seam — ROW DELETE (bulk, transactional path). Post-commit on the bulk\n // transaction; the non-transactional branch below carries its own call.\n await this.runRagChunkRemovalForDeletedRows(\n resourceType,\n this.collectDeletedRowIdsForRagRemoval(deleteResult, currentStates),\n 'row-delete-many',\n optionsWithTransaction,\n );\n\n return deleteResult;\n };\n\n let result: string[];\n\n if (requiresTransactionalBulkDelete) {\n if (hasFileFields && !fileWorkIsSeparatelyCommitted) {\n this.assertMongoBulkTransactionSupport(\n executionContext,\n 'Bulk delete file-field transactions currently require MongoDB-backed resources'\n );\n }\n\n result = await this.executeResourceTransaction(\n executionContext,\n async (optionsWithTransaction) => processBulkDeleteWithinTransaction(optionsWithTransaction),\n options\n );\n\n await this.executeAdditionalPostOperationLogic(\n CoreResourceOperation.DELETE_MANY,\n result,\n executionContext,\n currentStates,\n options,\n );\n } else {\n if (hasFileFields) {\n const fileRepositoryOptions = this.buildFileRepositoryOptions(options);\n if (!this.mongoDBService) {\n this.logger.warn('Transaction support unavailable for file operations during DELETE_MANY, processing sequentially', {\n resourceType,\n reason: 'MongoDBService not available'\n });\n }\n\n // Process file fields for each resource BEFORE deletion so non-Mongo bulk\n // paths still fail closed before the repository mutation lands.\n await processBulkDeleteFileCleanup(fileRepositoryOptions);\n }\n\n // 2. Execute repository operation (delete resources)\n result = await this.callRepository(operation, executionContext, id_or_ids_or_filter, undefined, options);\n\n // RAG removal seam — ROW DELETE (bulk, non-transactional path). The delete is already durable,\n // so this runs inline (still log-not-throw — the shared failure contract).\n await this.runRagChunkRemovalForDeletedRows(\n resourceType,\n this.collectDeletedRowIdsForRagRemoval(result, currentStates),\n 'row-delete-many',\n options,\n );\n\n // 3. Execute post-deletion business logic (including engine cascading)\n await this.executePostOperationLogic(\n CoreResourceOperation.DELETE_MANY,\n result,\n executionContext,\n currentStates,\n options,\n );\n }\n\n this.logDebug('DeleteMany business operation completed', { deletedCount: result?.length });\n return result;\n }\n\n private async list(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n filter?: FilterQuery<any>,\n // `sort` rides alongside page/limit (a local widening — NOT a change to the\n // shared `Resources_PaginationRequest` request DTO) and is forwarded into\n // `listOptions` for the repository to apply. Priority = key order.\n pagination?: Partial<Resources_PaginationRequest> & { sort?: Record<string, 1 | -1> },\n options?: ServiceOptions\n ): Promise<any[] | Resources_PaginatedResult<any>> {\n\n // Phase 5 / P5-H (H1) — pre-operation hook dispatch on LIST.\n // Same rationale as the READ branch above: gives the LAZY\n // guard installed by `wireLazyAccessGuards` (Phase 5.C) a\n // chance to materialize the seed row BEFORE the list scan.\n // The raw `filter` is passed as the hook payload so future\n // read-side pre-hooks can inspect the user's filter intent;\n // the LAZY guard itself ignores it.\n await this.executePreOperationLogic(\n CoreResourceOperation.LIST,\n filter ?? {},\n executionContext,\n );\n\n const paginated = options?.paginated ?? false;\n // Extract dataMode from ServiceOptions, or infer from operation's variantKey\n // This allows direct URL calls to /resource/context to use CONTEXT mode\n let dataMode = options?.dataMode ?? DataMode.RAW;\n\n // If operation already has a variantKey (direct URL call), infer dataMode from it\n if (operation.variantKey === OPERATION_VARIANT_KEY.CONTEXT) {\n dataMode = DataMode.CONTEXT;\n } else if (operation.variantKey === OPERATION_VARIANT_KEY.SUMMARY) {\n dataMode = DataMode.SUMMARY;\n }\n\n // Resolve operation variant based on dataMode\n const resolvedOperation = this.resolveOperationVariant(operation, dataMode);\n\n this.logDebug('Executing list business operation', { hasFilter: !!filter, pagination, paginated, dataMode, variantKey: resolvedOperation.variantKey, hasOptions: !!options });\n\n // 1. Apply business filtering to the provided filter\n const businessFilter = await this.applyBusinessFilter(filter || {}, executionContext);\n\n // 2. Execute repository operation with resolved variant (uses correct repositoryDto) - pass filter and pagination\n const listOptions = pagination ? { ...options, listOptions: pagination } : options;\n const result = await this.callRepository(resolvedOperation, executionContext, businessFilter, undefined, listOptions);\n\n // 3. Process based on DataMode\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n\n const processItems = async (items: any[]): Promise<any[]> => {\n if (dataMode === DataMode.RAW) {\n // No population or virtual fields processing\n return items;\n }\n\n // Analyze context needs for virtual fields\n const needs = this.populationService.analyzeContextNeeds(resourceType);\n const includeContextDependent = needs.needsObjectContext || needs.needsUserContext;\n\n // Process each item with virtual fields\n let processedItems = items;\n if (includeContextDependent) {\n // Process items with computation context (slower path)\n processedItems = await Promise.all(\n items.map(async (item) => {\n const computationContext = await this.populationService.fetchComputationContext(\n resourceType, item, needs, executionContext\n );\n return this.virtualFieldsService.computeVirtualFields(\n resourceType, item, executionContext,\n {\n faultTolerant: true,\n includeContextDependent: true,\n objectContext: computationContext.objectContext,\n userContext: computationContext.userContext,\n forSummary: dataMode === DataMode.SUMMARY,\n }\n );\n })\n );\n } else {\n // Process items without context fetching (fast path)\n processedItems = await Promise.all(\n items.map((item) => this.virtualFieldsService.computeVirtualFields(\n resourceType, item, executionContext, {\n faultTolerant: true,\n forSummary: dataMode === DataMode.SUMMARY,\n }\n ))\n );\n }\n\n // Apply population based on DataMode\n // Extract populateFiles option from ServiceOptions (default: true)\n const populateFiles = options?.populateFiles !== false;\n const populationOptions = { populateFiles };\n\n if (dataMode === DataMode.SUMMARY) {\n return this.populationService.populateListForSummary(resourceType, processedItems, executionContext, populationOptions, options);\n } else if (dataMode === DataMode.CONTEXT) {\n return this.populationService.populateListForContext(resourceType, processedItems, executionContext, populationOptions, options);\n }\n\n return processedItems;\n };\n\n // 4. Handle both raw array and paginated response from repository\n if (paginated && result.data !== undefined) {\n // Repository returned { data: [...], pagination: {...} }\n const processedData = await processItems(result.data);\n const enrichedData = await Promise.all(\n processedData.map((item: any) => this.enrichBusinessContext(CoreResourceOperation.LIST, item, executionContext))\n );\n this.logDebug('List business operation completed (paginated)', { count: enrichedData.length, pagination: result.pagination, dataMode });\n this.recordPlatformDirectoryAccess(operation, executionContext, CoreResourceOperation.LIST, enrichedData.length);\n return { data: enrichedData, pagination: result.pagination };\n } else {\n // Repository returned raw array\n const items = Array.isArray(result) ? result : result.data || [];\n const processedData = await processItems(items);\n const enrichedData = await Promise.all(\n processedData.map((item: any) => this.enrichBusinessContext(CoreResourceOperation.LIST, item, executionContext))\n );\n this.logDebug('List business operation completed (raw)', { count: enrichedData.length, dataMode });\n this.recordPlatformDirectoryAccess(operation, executionContext, CoreResourceOperation.LIST, enrichedData.length);\n return enrichedData;\n }\n }\n\n /**\n * Record an APPLICATION-WIDE directory enumeration, when that is what just happened.\n *\n * assurance-control: WILDO.ACCESS.AUTHORIZATION_DECISION_AUDIT — an unconfined administrative read\n * of application-wide data leaves evidence.\n *\n * ## Why here, and not in the authorizer or the repository\n *\n * The authorizer decides admission BEFORE any rows exist, so it cannot carry `returnedCount` — and\n * the size is the signal that separates \"an operator opened the directory\" from \"an operator\n * exported it\". The repository has the count but exists once PER ADAPTER, so an emission there\n * would be two emissions to keep in step, and audit is not a persistence concern. This seam has\n * the operation, the execution context and the result, and is adapter-neutral.\n *\n * ## Fire-and-forget, deliberately\n *\n * No `await`, and the rejection is swallowed — the same contract as\n * `CROSS_TENANT_ADMINISTRATIVE_ACCESS`. A directory read must not fail because the audit sink is\n * down, and a fail-closed variant would hand anyone a way to disable an administrative surface by\n * breaking the sink. Feature-detected against the service so a partial DI binding (unit suites,\n * minimal containers) cannot turn an observation into a crash.\n */\n private recordPlatformDirectoryAccess(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n executedCoreOperation: CoreResourceOperation,\n returnedCount: number,\n ): void {\n try {\n const resourceConfiguration = this.resourcesRegistry?.getResourceConfiguration?.(\n operation.resourceIdentifier as never,\n );\n if (!resourceConfiguration) return;\n\n // ONE predicate, shared with the confinement authority: a read is a directory read precisely\n // when that authority declines to confine it. Deriving it separately here is how the trail\n // would start claiming \"unconfined\" about reads that had since been confined.\n if (!isUnconfinedScopeRootDirectoryRead({\n executionContext: executionContext as never,\n resourceConfiguration: resourceConfiguration as never,\n executedCoreOperation,\n })) return;\n\n const auditLogsService = this.servicesRegistry?.getAuditLogsService?.();\n if (typeof auditLogsService?.logPlatformDirectoryAccess !== 'function') return;\n\n void auditLogsService.logPlatformDirectoryAccess({\n resourceType: String(operation.resourceIdentifier),\n operationIdentifier: String(operation.operationIdentifier),\n variantType: operation.variantType,\n variantKey: operation.variantKey,\n returnedCount,\n initiatorRoles: (executionContext.initiatorRoles ?? []).flatMap((roleInfo) => roleInfo.roles ?? []),\n executionType: executionContext.executionType,\n actorUserId: executionContext.initiatorIds?.userId,\n applicationId: executionContext.initiatorIds?.applicationId,\n }, executionContext).catch(() => { /* observation only — never fail the read it observes */ });\n } catch {\n /* observation only */\n }\n }\n\n private async search(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n searchQuery: string,\n filter?: FilterQuery<any>,\n options?: ServiceOptions & {\n searchOptions?: {\n fieldsToSearch?: string[];\n page?: number;\n limit?: number;\n sort?: Record<string, 1 | -1>;\n };\n }\n ): Promise<any> {\n\n // Extract dataMode from options (default: RAW)\n const dataMode = (options as any)?.dataMode ?? DataMode.RAW;\n\n // Resolve operation variant based on dataMode\n const resolvedOperation = this.resolveOperationVariant(operation, dataMode);\n\n this.logDebug('Executing search business operation', { searchQuery, hasFilter: !!filter, dataMode, variantKey: resolvedOperation.variantKey });\n\n // 1. Apply business search logic\n const businessFilter = await this.applyBusinessFilter(filter || {}, executionContext);\n const enhancedSearchQuery = await this.enhanceSearchQuery(searchQuery, executionContext);\n\n // 2. Execute repository operation with resolved variant - search doesn't use id_or_ids_or_filter, pass search data via data parameter\n const searchData = { query: enhancedSearchQuery, filter: businessFilter };\n const result = await this.callRepository(resolvedOperation, executionContext, undefined, searchData, options);\n\n // 3. Enrich each item with business context\n const enrichedData = result.data ?\n await Promise.all(result.data.map(item => this.enrichBusinessContext(CoreResourceOperation.SEARCH, item, executionContext))) :\n [];\n\n // 4. Return result with enriched data (transformation happens in doOperation)\n const processedResult = { ...result, data: enrichedData };\n\n this.logDebug('Search business operation completed', { count: enrichedData.length });\n return processedResult;\n }\n\n private async count(\n operation: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>,\n executionContext: ExecutionContext<any>,\n filter?: FilterQuery<any>,\n options?: RepositoryOptions\n ): Promise<{ count: number }> {\n\n this.logDebug('Executing count business operation', { hasFilter: !!filter });\n\n // 1. Apply business filtering\n const businessFilter = await this.applyBusinessFilter(filter || {}, executionContext);\n\n // 2. Execute repository operation - count doesn't use id_or_ids_or_filter, pass filter via data parameter\n const countData = Object.keys(businessFilter).length > 0 ? { filter: businessFilter } : undefined;\n const result = await this.callRepository(operation, executionContext, undefined, countData, options);\n\n this.logDebug('Count business operation completed', { count: result.count });\n return result;\n }\n\n // ================================\n // DTO Validation and Transformation Methods\n // ================================\n\n /**\n * Validate and transform input data using operation's requestDto\n */\n private async validateAndTransformInput(\n executionContext: ExecutionContext<any>,\n data: any\n ): Promise<any> {\n\n const operation = executionContext.operation;\n\n if (!operation.requestDto) {\n this.logDebug('No requestDto defined for operation, skipping validation');\n return data;\n }\n\n try {\n // Strip any `.isWriteOnlySecret()` field the client echoed back as the mask\n // sentinel — it means \"keep the existing stored secret\". UPDATE is a partial\n // `$set`, so removing the field preserves the stored value; on CREATE it is\n // simply omitted. Runs at the service tier so it covers in-process writes too.\n const sanitizedInput = ResourcesConfigOperationsDtosBuilderUtils.stripWriteOnlySecretSentinel(\n operation.requestDto,\n data,\n );\n\n // Validate and transform input — use loose parse to preserve PREFIX-augmented\n // persistence fields that are not part of the API's requestDto schema.\n // Field-level security is enforced at the controller boundary; Mongoose strict\n // mode strips schema-unknown fields at the repository layer.\n const validatedData = (operation.requestDto instanceof z.ZodObject)\n ? z.looseObject(operation.requestDto.shape).parse(sanitizedInput)\n : operation.requestDto.parse(sanitizedInput);\n this.logDebug('Input validation successful');\n return validatedData;\n } catch (error) {\n if (error instanceof z.ZodError) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n stack: error.stack,\n context: {\n operationIdentifier: operation.operationIdentifier,\n inputData: data,\n zodIssues: error.issues,\n }\n });\n }\n throw this.errorBuilder.buildFromStandardError(\n error instanceof Error ? error : new Error('Unknown validation error'),\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n operationIdentifier: operation.operationIdentifier,\n inputData: data,\n }\n }\n );\n }\n }\n\n\n private async transformOutput(\n executionContext: ExecutionContext<any>,\n data: any,\n dataMode: DataMode = DataMode.RAW,\n alreadyResolvedOperation?: ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>\n ): Promise<any> {\n\n const operation = executionContext.operation as ResourceConfiguration_Operation<TCustomOperationEnum, TCoreOperationEnum, TMainSchema>;\n\n // Use already-resolved operation if provided (to avoid double resolution)\n // Otherwise resolve based on dataMode\n const resolvedOperation = alreadyResolvedOperation ?? this.resolveOperationVariant(operation, dataMode);\n\n this.logDebug('Transform output - using resolved operation', {\n operationIdentifier: operation.operationIdentifier,\n dataMode,\n resolvedVariantKey: resolvedOperation.variantKey,\n wasAlreadyResolved: !!alreadyResolvedOperation\n });\n\n // Use internalDto for service-layer validation\n // internalDto MUST exist - it's built by buildAllOperationDtos() for all operations\n if (!resolvedOperation.internalDto) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_TRANSFORMATION_FAILED,\n context: {\n reason: 'Missing internalDto - this indicates a configuration error in buildAllOperationDtos()',\n operationIdentifier: resolvedOperation.operationIdentifier,\n resourceIdentifier: resolvedOperation.resourceIdentifier,\n variantKey: resolvedOperation.variantKey,\n dataMode\n }\n }\n );\n }\n\n this.logDebug('Service transformOutput - resolved operation', {\n operationIdentifier: operation.operationIdentifier,\n dataMode,\n resolvedVariantKey: resolvedOperation.variantKey,\n hasInternalDto: !!resolvedOperation.internalDto\n });\n\n this.logDebug('transformOutput - before validation', {\n dataKeys: data && typeof data === 'object' && !Array.isArray(data) ? Object.keys(data) : 'not plain object',\n hasUserSelfProfile: data && typeof data === 'object' ? 'userSelfProfile' in data : false,\n hasUserSelfPreference: data && typeof data === 'object' ? 'userSelfPreference' in data : false,\n hasOrgMembers: data && typeof data === 'object' ? 'organizationMembers' in data : false\n });\n\n try {\n // Transform and validate output using resolved operation's internalDto\n const effectiveOperation = resolvedOperation.resourceOperationLike || resolvedOperation.operationIdentifier;\n\n // Compose the operation's DECLARED response value from the raw service output BEFORE\n // validating it. This is the single, GENERAL seam between \"what the service/repository layer\n // returns\" and \"what the operation's `internalDto` (and the controller response serializer)\n // expect\" — no per-operation special-casing lives here. For almost every operation this is the\n // identity (the service already returns the resource object / per-item array / `{ count }` /\n // pagination wrapper). The only non-identity cases are the genuine core deletes, whose\n // repository layer returns the deleted id(s) as a bare scalar (`delete(): Promise<string>` —\n // the `_id`, `''` when nothing matched; `deleteMany(): Promise<string[]>`);\n // `composeDefaultOperationResponse` lifts those into `DefaultDeleteResponseSchema` /\n // `DefaultBulkDeleteResponseSchema`. Before this, the raw scalar was parsed straight against\n // the resource object schema and threw `service_resource_transformation_failed` → HTTP 500 on\n // every delete. Composition is pure and total (never throws); the subsequent parse stays inside\n // this `try`, so a genuinely malformed output still surfaces the transformation error below.\n //\n // TWO guards keep this from touching custom operations that merely borrow DELETE/COUNT\n // semantics (`resourceOperationLike`) while returning their OWN shape:\n // 1. Key on the op's own `operationIdentifier`, NOT `effectiveOperation` — a custom op has a\n // custom identifier, so the composer switch falls through to identity for it.\n // 2. Skip entirely when the op declares a `customResponseDto` (`hasCustomResponseDto`) — that\n // op returns its custom shape directly (for example `{ message, domain }`),\n // and its `internalDto` IS that custom schema; composing `{ id: <custom object> }` would\n // wrongly fail validation.\n //\n // ⚠️ The op must actually PRODUCE that custom shape. Skipping composition hands the raw\n // service output to the custom DTO, and a borrowed core DELETE returns a bare id STRING —\n // so a delete-like op declaring a custom object response with no implementation to build\n // it throws `service_resource_transformation_failed` on every call, AFTER the delete has\n // committed. `user_self | delete_account` did exactly that and was removed on 2026-08-01.\n // Mirrors `buildEnhancedResponseDto`, which lets a custom `responseDto` win over the default.\n const outputToValidate = resolvedOperation.hasCustomResponseDto\n ? data\n : composeDefaultOperationResponse(resolvedOperation.operationIdentifier as string, data);\n\n const isBulkArrayOperation = (\n effectiveOperation === CoreResourceOperation.CREATE_MANY\n || effectiveOperation === CoreResourceOperation.UPDATE_MANY\n );\n const isCollectionOperation = (\n effectiveOperation === CoreResourceOperation.LIST\n || effectiveOperation === CoreResourceOperation.SEARCH\n );\n const collectionItemDto = (\n Array.isArray(outputToValidate) && isCollectionOperation\n )\n ? this.extractCollectionItemDto(resolvedOperation.internalDto) ?? resolvedOperation.repositoryDto\n : null;\n\n // `_version` (optimistic-locking counter) and `_field_meta` (CRDT causality) are engine\n // metadata NOT declared in any resource schema, so the `internalDto.parse` below strips\n // them. They must survive to the HTTP response: the frontend Resource Mutation Manager\n // seeds its optimistic-locking version from the READ response and echoes it as `If-Match`\n // on inline updates — stripped, it seeds `0` and every inline update 409s. Snapshot per\n // item before parse and reattach after (mirrors the same guard in\n // `operation-response-serializer.backend.utils`, which covers the controller/webhook parse).\n const preserveEngineMetadata = (source: unknown, parsed: unknown): unknown => {\n if (!source || typeof source !== 'object' || !parsed || typeof parsed !== 'object') return parsed;\n for (const key of ['_field_meta', '_version'] as const) {\n const value = (source as Record<string, unknown>)[key];\n if (value !== undefined && (parsed as Record<string, unknown>)[key] === undefined) {\n (parsed as Record<string, unknown>)[key] = value;\n }\n }\n return parsed;\n };\n\n const transformedData = (\n Array.isArray(outputToValidate) && (isBulkArrayOperation || !!collectionItemDto)\n )\n ? outputToValidate.map((item) => preserveEngineMetadata(item, (collectionItemDto ?? resolvedOperation.internalDto!).parse(item)))\n : preserveEngineMetadata(outputToValidate, resolvedOperation.internalDto.parse(outputToValidate));\n\n this.logDebug('transformOutput - after validation', {\n dataKeys: transformedData && typeof transformedData === 'object' && !Array.isArray(transformedData) ? Object.keys(transformedData) : 'not plain object',\n hasUserSelfProfile: transformedData && typeof transformedData === 'object' ? 'userSelfProfile' in transformedData : false,\n hasUserSelfPreference: transformedData && typeof transformedData === 'object' ? 'userSelfPreference' in transformedData : false,\n hasOrgMembers: transformedData && typeof transformedData === 'object' ? 'organizationMembers' in transformedData : false\n });\n\n this.logDebug('Output transformation successful');\n return transformedData;\n } catch (error) {\n // Output transformation failures are programming/configuration errors.\n // The DTO doesn't match the actual output structure.\n const transformationError = this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_TRANSFORMATION_FAILED,\n context: {\n operationIdentifier: operation.operationIdentifier,\n resourceIdentifier: operation.resourceIdentifier,\n outputDataType: Array.isArray(data) ? 'array' : typeof data,\n outputDataLength: Array.isArray(data) ? data.length : undefined,\n outputDataKeys: data && typeof data === 'object' && !Array.isArray(data) ? Object.keys(data) : undefined,\n /**\n * The CAUSE, which this catch used to drop.\n *\n * It kept only the stack, so the error named the resource and the key LIST but never\n * which field failed or why — and a Zod issue path is the entire diagnostic content of a\n * DTO mismatch. Debugging one meant adding a temporary log to the framework and\n * re-running, every time.\n */\n transformationFailure: describeCaughtError(error),\n },\n stack: error instanceof Error ? error.stack : undefined\n }\n );\n throw transformationError;\n }\n }\n\n private extractCollectionItemDto(dto: z.ZodTypeAny | undefined): z.ZodTypeAny | null {\n if (!(dto instanceof z.ZodObject)) {\n return null;\n }\n\n const dataField = dto.shape?.data;\n const paginationField = dto.shape?.pagination;\n\n if (!(dataField instanceof z.ZodArray) || !paginationField) {\n return null;\n }\n\n return dataField.element as unknown as z.ZodTypeAny;\n }\n\n /**\n * Apply business validation\n */\n private async applyBusinessValidation(\n operation: CoreResourceOperation,\n data: any,\n executionContext: ExecutionContext<any>,\n currentState?: any\n ): Promise<any> {\n\n // Implement business validation logic here\n // This could include:\n // - Business rule validation\n // - Permission checks\n // - Data consistency validation\n // - Cross-resource validation\n\n return data; // Default: pass through\n }\n\n /**\n * Execute pre-operation business logic.\n *\n * Dispatches registered pre-operation hooks for this resource type\n * BEFORE returning the (possibly-enriched) data to the pipeline.\n *\n * Short-circuit contract (plan §Phase-3 P3-A=A1): hook exceptions\n * propagate unchanged — this method performs NO `try/catch` around\n * `dispatchPreOperationHooks` and the pipeline callers already wrap\n * the full operation in their own error-handling so the failure\n * surfaces as a normal operation-level error to the API layer.\n *\n * Mutation contract: pre-hooks are observation + veto only (no return\n * value). Data transformation continues to live in\n * `prefixCoreOperations` of custom operation impls.\n *\n * **Hook-payload contract — `_id` injection for UPDATE / UPDATE_MANY**\n * (Phase 3.2 review fix, Findings #2/#10):\n *\n * The pipeline callers pass the validated **patch** as `data` and the\n * pre-update **row snapshot** as `currentState`. Hooks consuming a\n * patch alone cannot anchor per-row work (Level-B seeds need\n * `triggeringRow._id` to anchor the `DataSeedRun` ledger; cross-resource\n * consistency hooks need to identify the target row). We therefore\n * publish a **hook payload** that lifts `_id` from `currentState` onto\n * the patch for singular `UPDATE`, and an array of `{...currentState,\n * _id}` for bulk `UPDATE_MANY`. The **return value** stays the\n * original `data` so the repository receives only the patch — adding\n * `_id` to the persistence payload would otherwise be rejected by\n * adapters that forbid `_id` mutation.\n *\n * `currentState` shapes accepted:\n * - singular `UPDATE` → object with `_id` (single fetched snapshot).\n * - `UPDATE_MANY` / `DELETE_MANY` → array of objects with `_id`.\n * - other operations → undefined / passthrough (no transform).\n */\n private async executePreOperationLogic(\n operation: CoreResourceOperation,\n data: any,\n executionContext: ExecutionContext<any>,\n currentState?: any\n ): Promise<any> {\n\n const resourceType = this.resourceConfiguration.resourceIdentifier as string;\n\n let hookPayload: any = data;\n if (\n operation === CoreResourceOperation.UPDATE\n && currentState\n && typeof currentState._id === 'string'\n && currentState._id.length > 0\n && data\n && typeof data === 'object'\n && !Array.isArray(data)\n ) {\n // Spread `data` first so the patch's keys are visible to the hook,\n // then assign canonical `_id` last to defeat any accidental `_id`\n // shadowing in the patch (post-validation patches must not carry\n // `_id`, but defensive overlay keeps the contract crash-free).\n hookPayload = { ...data, _id: currentState._id };\n } else if (\n operation === CoreResourceOperation.UPDATE_MANY\n && Array.isArray(currentState)\n && currentState.length > 0\n && data\n && typeof data === 'object'\n && !Array.isArray(data)\n ) {\n // Bulk patch is broadcast across N rows: materialise per-row hook\n // shape `{...patch, _id}` so each downstream Level-B seed dispatch\n // gets the row anchor it needs (P3-F=F1). Skipped when no rows\n // matched the bulk selector (mirrors DELETE_MANY's `length > 0`\n // guard) so empty selectors don't fire spurious hook callbacks.\n hookPayload = currentState\n .filter((row) => row && typeof row._id === 'string' && row._id.length > 0)\n .map((row) => ({ ...data, _id: row._id }));\n }\n\n await this.servicesRegistry.dispatchPreOperationHooks(\n resourceType,\n operation,\n hookPayload,\n executionContext,\n );\n\n return data;\n }\n\n /**\n * Execute post-operation business logic using engine lifecycle operations\n */\n private async executePostOperationLogic(\n operation: CoreResourceOperation,\n result: any,\n executionContext: ExecutionContext<any>,\n currentState?: any,\n options?: RepositoryOptions\n ): Promise<any> {\n\n // Get the current operation configuration\n const operationConfig = executionContext.operation;\n const resourceType = operationConfig.resourceIdentifier;\n\n // Execute lifecycle operations for DELETE (child deletion based on childOperations config)\n // rag-removal-gate: N/A — pure delegation. The deleted ROWS' chunk removal lives in the\n // delete/deleteMany methods that call this; the cascaded CHILDREN's lives in\n // deleteChildrenImmediate. This dispatcher destroys nothing itself.\n if (operation === CoreResourceOperation.DELETE || operation === CoreResourceOperation.DELETE_MANY) {\n await this.executeLifecycleOperations(operation, result, executionContext, currentState);\n }\n\n // Execute composition onParentCreate seeding — eager creation of composition\n // children declared with `lifecycle.onParentCreate.enabled = true`. `options`\n // carries `compositionSeedDepth` for the re-entrancy bound (see the method).\n if (operation === CoreResourceOperation.CREATE) {\n await this.executeCompositionSeedingForCreate(result, executionContext, options);\n }\n\n // Execute other post-operation logic (events, notifications, etc.)\n await this.executeAdditionalPostOperationLogic(\n operation,\n result,\n executionContext,\n currentState,\n options,\n );\n\n return result;\n }\n\n // =============================================================================\n // NESTED OPERATIONS PROCESSING\n // =============================================================================\n\n private getRelationshipFieldNameForCurrentResource(rel: ResourceRelationship): string {\n return Resources_SharedUtils.resolveRelationshipObjectIdentityForResource(\n rel,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n this.getAllResourceFieldIdentifiers()\n ).objectFieldName;\n }\n\n private getRelationshipForBulkAction(relationshipField: string): ResourceRelationship {\n const currentResourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const candidateRelationships = this.resourcesRegistry\n .getResourcesRegistry()\n .resourceRelationships\n .filter((rel) =>\n rel.isDisabled !== true\n && (rel.resourceType1 === currentResourceType || rel.resourceType2 === currentResourceType)\n );\n const matches = candidateRelationships.filter((rel) =>\n this.getRelationshipFieldNameForCurrentResource(rel) === relationshipField\n );\n\n if (matches.length === 1) {\n return matches[0];\n }\n\n if (matches.length > 1) {\n throw new Error(\n `Bulk relationship field \"${relationshipField}\" is ambiguous for resource \"${this.resourceConfiguration.resourceIdentifier}\".`\n );\n }\n\n throw new Error(\n `Bulk relationship field \"${relationshipField}\" does not map to a relationship on resource \"${this.resourceConfiguration.resourceIdentifier}\".`\n );\n }\n\n private async applyReferenceSetActionMany(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n relationship: ResourceRelationship,\n relationshipField: string,\n targetId: string,\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n const relatedReadContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n relationship.resourceType1,\n CoreResourceOperation.READ\n );\n const relatedTarget = await this.servicesRegistry.read(\n relationship.resourceType1,\n relatedReadContext,\n targetId,\n options\n );\n\n if (!relatedTarget) {\n throw this.errorBuilder.buildError(\n ErrorType.NOT_FOUND,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.SET,\n targetId,\n relatedResourceType: relationship.resourceType1,\n },\n }\n );\n }\n\n if (!Resources_SharedUtils.isRelationshipActiveForParent(relationship, relatedTarget, {\n onMissingParentResource: 'exclude',\n onConditionError: 'throw',\n })) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.SET,\n targetId,\n reason: 'Reference relationship is inactive for the selected related resource',\n },\n }\n );\n }\n\n const updateManyContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n CoreResourceOperation.UPDATE_MANY\n );\n const fkField = this.getFKFieldForRelationship(relationship);\n const updatedTargets = await this.servicesRegistry.updateMany(\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n updateManyContext,\n id_or_ids_or_filter,\n { [fkField]: targetId },\n options\n );\n\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.SET,\n matchedTargetIds: this.extractResourceIds(updatedTargets),\n affectedCount: Array.isArray(updatedTargets) ? updatedTargets.length : 0,\n results: Array.isArray(updatedTargets) ? updatedTargets : [],\n };\n }\n\n private async applyReferenceClearActionMany(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n relationship: ResourceRelationship,\n relationshipField: string,\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n if (relationship.parentResourceRequirement === ResourceParentResourceRequirement.MANDATORY) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.CLEAR,\n reason: 'Cannot clear a mandatory parent relationship through bulk reference mutation',\n },\n }\n );\n }\n\n const updateManyContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n CoreResourceOperation.UPDATE_MANY\n );\n const fkField = this.getFKFieldForRelationship(relationship);\n const updatedTargets = await this.servicesRegistry.updateMany(\n this.resourceConfiguration.resourceIdentifier as ResourceType,\n updateManyContext,\n id_or_ids_or_filter,\n { [fkField]: null },\n options\n );\n\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.CLEAR,\n matchedTargetIds: this.extractResourceIds(updatedTargets),\n affectedCount: Array.isArray(updatedTargets) ? updatedTargets.length : 0,\n results: Array.isArray(updatedTargets) ? updatedTargets : [],\n };\n }\n\n private async applyCompositionCreateActionMany(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n relationship: ResourceRelationship,\n relationshipField: string,\n data: Record<string, any>,\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n const fkField = this.getFKFieldForRelationship(relationship);\n if (fkField in data) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.CREATE,\n fkField,\n reason: 'Bulk composition create payload must not provide the relationship foreign key explicitly',\n },\n }\n );\n }\n\n const targetResources = await this.loadBulkTargetResources(\n executionContext,\n id_or_ids_or_filter,\n options\n );\n const createdChildren: any[] = [];\n const matchedTargetIds: string[] = [];\n\n for (const targetResource of targetResources) {\n if (!Resources_SharedUtils.isRelationshipActiveForParent(relationship, targetResource, {\n onMissingParentResource: 'exclude',\n onConditionError: 'throw',\n })) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.CREATE,\n reason: 'Composition relationship is inactive for one of the matched target resources',\n targetResourceId: this.getResourceIdValue(targetResource),\n },\n }\n );\n }\n\n const targetResourceId = this.getResourceIdValue(targetResource);\n if (!targetResourceId) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.CREATE,\n reason: 'Bulk composition create requires every matched target resource to expose an id',\n },\n }\n );\n }\n\n const createContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n relationship.resourceType2,\n CoreResourceOperation.CREATE\n );\n const createdChild = await this.servicesRegistry.create(\n relationship.resourceType2,\n createContext,\n {\n ...data,\n [fkField]: targetResourceId,\n },\n options\n );\n\n matchedTargetIds.push(targetResourceId);\n createdChildren.push(createdChild);\n }\n\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.CREATE,\n matchedTargetIds,\n affectedCount: createdChildren.length,\n results: createdChildren,\n };\n }\n\n private async applyAssociationLinkActionMany(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n relationship: ResourceRelationship,\n relationshipField: string,\n peerIds: string[],\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n const {\n jointResourceType,\n peerResourceType,\n currentForeignKeyField,\n peerForeignKeyField,\n } = this.resolveAssociationBulkIdentity(relationship);\n const uniquePeerIds = [...new Set(peerIds)];\n await this.assertAssociationPeerResourcesExist(\n executionContext,\n relationshipField,\n peerResourceType,\n uniquePeerIds,\n ResourceRelationshipBulkAction.LINK,\n options\n );\n\n const targetResources = await this.loadBulkTargetResources(\n executionContext,\n id_or_ids_or_filter,\n options\n );\n const matchedTargetIds: string[] = [];\n\n for (const targetResource of targetResources) {\n if (!Resources_SharedUtils.isRelationshipActiveForParent(relationship, targetResource, {\n onMissingParentResource: 'exclude',\n onConditionError: 'throw',\n })) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.LINK,\n reason: 'Association relationship is inactive for one of the matched target resources',\n targetResourceId: this.getResourceIdValue(targetResource),\n },\n }\n );\n }\n\n const targetResourceId = this.getResourceIdValue(targetResource);\n if (!targetResourceId) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.LINK,\n reason: 'Bulk association link requires every matched target resource to expose an id',\n },\n }\n );\n }\n\n matchedTargetIds.push(targetResourceId);\n }\n\n const existingRows = matchedTargetIds.length > 0\n ? await this.listAssociationRowsByCurrentAndPeerIds(\n executionContext,\n jointResourceType,\n currentForeignKeyField,\n matchedTargetIds,\n peerForeignKeyField,\n uniquePeerIds,\n options\n )\n : [];\n const existingKeys = new Set(\n existingRows.map((row) => {\n const currentId = row?.[currentForeignKeyField];\n const peerId = row?.[peerForeignKeyField];\n return typeof currentId === 'string' && typeof peerId === 'string'\n ? `${currentId}::${peerId}`\n : undefined;\n })\n .filter((key): key is string => Boolean(key))\n );\n\n const createdRows: any[] = [];\n for (const targetResourceId of matchedTargetIds) {\n for (const peerId of uniquePeerIds) {\n const key = `${targetResourceId}::${peerId}`;\n if (existingKeys.has(key)) {\n continue;\n }\n\n const createContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n jointResourceType,\n CoreResourceOperation.CREATE\n );\n const createdRow = await this.servicesRegistry.create(\n jointResourceType,\n createContext,\n {\n [currentForeignKeyField]: targetResourceId,\n [peerForeignKeyField]: peerId,\n },\n options\n );\n createdRows.push(createdRow);\n }\n }\n\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.LINK,\n matchedTargetIds,\n affectedCount: createdRows.length,\n results: createdRows,\n };\n }\n\n private async applyAssociationUnlinkActionMany(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n relationship: ResourceRelationship,\n relationshipField: string,\n peerIds: string[],\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n const {\n jointResourceType,\n currentForeignKeyField,\n peerForeignKeyField,\n } = this.resolveAssociationBulkIdentity(relationship);\n const uniquePeerIds = [...new Set(peerIds)];\n const targetResources = await this.loadBulkTargetResources(\n executionContext,\n id_or_ids_or_filter,\n options\n );\n const matchedTargetIds: string[] = [];\n\n for (const targetResource of targetResources) {\n if (!Resources_SharedUtils.isRelationshipActiveForParent(relationship, targetResource, {\n onMissingParentResource: 'exclude',\n onConditionError: 'throw',\n })) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.UNLINK,\n reason: 'Association relationship is inactive for one of the matched target resources',\n targetResourceId: this.getResourceIdValue(targetResource),\n },\n }\n );\n }\n\n const targetResourceId = this.getResourceIdValue(targetResource);\n if (!targetResourceId) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.UNLINK,\n reason: 'Bulk association unlink requires every matched target resource to expose an id',\n },\n }\n );\n }\n\n matchedTargetIds.push(targetResourceId);\n }\n\n if (matchedTargetIds.length === 0 || uniquePeerIds.length === 0) {\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.UNLINK,\n matchedTargetIds,\n affectedCount: 0,\n results: [],\n };\n }\n\n const existingRows = await this.listAssociationRowsByCurrentAndPeerIds(\n executionContext,\n jointResourceType,\n currentForeignKeyField,\n matchedTargetIds,\n peerForeignKeyField,\n uniquePeerIds,\n options\n );\n const existingRowIds = existingRows\n .map((row) => this.getResourceIdValue(row))\n .filter((rowId): rowId is string => Boolean(rowId));\n\n if (existingRowIds.length !== existingRows.length) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.UNLINK,\n reason: 'Bulk association unlink requires every junction row to expose an id',\n },\n }\n );\n }\n\n if (existingRowIds.length === 0) {\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.UNLINK,\n matchedTargetIds,\n affectedCount: 0,\n results: [],\n };\n }\n\n const deleteManyContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n jointResourceType,\n CoreResourceOperation.DELETE_MANY\n );\n const deletedRowIds = await this.servicesRegistry.deleteMany(\n jointResourceType,\n deleteManyContext,\n existingRowIds,\n options\n );\n\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.UNLINK,\n matchedTargetIds,\n affectedCount: Array.isArray(deletedRowIds) ? deletedRowIds.length : 0,\n results: Array.isArray(deletedRowIds) ? deletedRowIds : [],\n };\n }\n\n private async applyAssociationReplaceActionMany(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n relationship: ResourceRelationship,\n relationshipField: string,\n peerIds: string[],\n options?: RepositoryOptions\n ): Promise<ResourceRelationshipBulkActionResult> {\n const {\n jointResourceType,\n peerResourceType,\n currentForeignKeyField,\n peerForeignKeyField,\n } = this.resolveAssociationBulkIdentity(relationship);\n const uniquePeerIds = [...new Set(peerIds)];\n await this.assertAssociationPeerResourcesExist(\n executionContext,\n relationshipField,\n peerResourceType,\n uniquePeerIds,\n ResourceRelationshipBulkAction.REPLACE,\n options\n );\n\n const matchedTargetIds = await this.resolveActiveAssociationBulkTargetIds(\n executionContext,\n id_or_ids_or_filter,\n relationship,\n relationshipField,\n ResourceRelationshipBulkAction.REPLACE,\n options\n );\n\n if (matchedTargetIds.length === 0) {\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.REPLACE,\n matchedTargetIds,\n affectedCount: 0,\n results: [],\n };\n }\n\n const existingRows = await this.listAssociationRowsByCurrentIds(\n executionContext,\n jointResourceType,\n currentForeignKeyField,\n matchedTargetIds,\n options\n );\n const desiredKeys = new Set<string>();\n for (const targetResourceId of matchedTargetIds) {\n for (const peerId of uniquePeerIds) {\n desiredKeys.add(`${targetResourceId}::${peerId}`);\n }\n }\n\n const rowsToDelete = existingRows.filter((row) => {\n const currentId = row?.[currentForeignKeyField];\n const peerId = row?.[peerForeignKeyField];\n if (typeof currentId !== 'string' || typeof peerId !== 'string') {\n return false;\n }\n\n return !desiredKeys.has(`${currentId}::${peerId}`);\n });\n const deleteRowIds = rowsToDelete\n .map((row) => this.getResourceIdValue(row))\n .filter((rowId): rowId is string => Boolean(rowId));\n\n if (deleteRowIds.length !== rowsToDelete.length) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action: ResourceRelationshipBulkAction.REPLACE,\n reason: 'Bulk association replace requires every junction row to expose an id',\n },\n }\n );\n }\n\n const existingKeys = new Set(\n existingRows.map((row) => {\n const currentId = row?.[currentForeignKeyField];\n const peerId = row?.[peerForeignKeyField];\n return typeof currentId === 'string' && typeof peerId === 'string'\n ? `${currentId}::${peerId}`\n : undefined;\n })\n .filter((key): key is string => Boolean(key))\n );\n\n const createdRows: any[] = [];\n for (const targetResourceId of matchedTargetIds) {\n for (const peerId of uniquePeerIds) {\n const key = `${targetResourceId}::${peerId}`;\n if (existingKeys.has(key)) {\n continue;\n }\n\n const createContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n jointResourceType,\n CoreResourceOperation.CREATE\n );\n const createdRow = await this.servicesRegistry.create(\n jointResourceType,\n createContext,\n {\n [currentForeignKeyField]: targetResourceId,\n [peerForeignKeyField]: peerId,\n },\n options\n );\n createdRows.push(createdRow);\n }\n }\n\n if (deleteRowIds.length > 0) {\n const deleteManyContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n jointResourceType,\n CoreResourceOperation.DELETE_MANY\n );\n await this.servicesRegistry.deleteMany(\n jointResourceType,\n deleteManyContext,\n deleteRowIds,\n options\n );\n }\n\n return {\n relationshipField,\n action: ResourceRelationshipBulkAction.REPLACE,\n matchedTargetIds,\n affectedCount: createdRows.length + deleteRowIds.length,\n results: [\n ...createdRows,\n ...deleteRowIds,\n ],\n };\n }\n\n /**\n * Extract nested field name from relationship using the shared\n * relationship-object identity rule.\n */\n private getNestedFieldName(rel: ResourceRelationship): string {\n return Resources_SharedUtils.resolveRelationshipObjectIdentity(\n rel,\n rel.resourceType2,\n rel.cardinality2,\n this.getAllResourceFieldIdentifiers()\n ).objectFieldName;\n }\n\n private getAllResourceFieldIdentifiers(): Partial<Record<ResourceType, string>> {\n const registry = this.resourcesRegistry.getResourcesRegistry();\n const allResourceFieldIdentifiers: Partial<Record<ResourceType, string>> = {};\n\n for (const resourceType of Object.keys(registry.resourceConfigurations) as ResourceType[]) {\n const fieldIdentifier = registry.resourceConfigurations[resourceType]?.resourceFieldIdentifier;\n if (typeof fieldIdentifier === 'string' && fieldIdentifier.length > 0) {\n allResourceFieldIdentifiers[resourceType] = fieldIdentifier;\n }\n }\n\n return allResourceFieldIdentifiers;\n }\n\n private extractResourceIds(resources: any[]): string[] {\n if (!Array.isArray(resources)) {\n return [];\n }\n\n return resources\n .map((resource) => this.getResourceIdValue(resource))\n .filter((resourceId): resourceId is string => Boolean(resourceId));\n }\n\n /**\n * Get FK field name for a relationship.\n * Delegates to the registry so backend services do not improvise their own\n * FK fallback semantics.\n */\n private getFKFieldForRelationship(rel: ResourceRelationship): string {\n return this.resourcesRegistry.resolveForeignKeyField({\n resourceType1: rel.resourceType1,\n foreignKeyField: rel.foreignKeyField,\n });\n }\n\n private async resolveActiveAssociationBulkTargetIds(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType,\n relationship: ResourceRelationship,\n relationshipField: string,\n action: ResourceRelationshipBulkAction,\n options?: RepositoryOptions\n ): Promise<string[]> {\n const targetResources = await this.loadBulkTargetResources(\n executionContext,\n id_or_ids_or_filter,\n options\n );\n const matchedTargetIds: string[] = [];\n\n for (const targetResource of targetResources) {\n if (!Resources_SharedUtils.isRelationshipActiveForParent(relationship, targetResource, {\n onMissingParentResource: 'exclude',\n onConditionError: 'throw',\n })) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n relationshipField,\n action,\n reason: 'Association relationship is inactive for one of the matched target resources',\n targetResourceId: this.getResourceIdValue(targetResource),\n },\n }\n );\n }\n\n const targetResourceId = this.getResourceIdValue(targetResource);\n if (!targetResourceId) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action,\n reason: 'Bulk association mutation requires every matched target resource to expose an id',\n },\n }\n );\n }\n\n matchedTargetIds.push(targetResourceId);\n }\n\n return matchedTargetIds;\n }\n\n private resolveAssociationBulkIdentity(relationship: ResourceRelationship): {\n jointResourceType: ResourceType;\n peerResourceType: ResourceType;\n currentForeignKeyField: string;\n peerForeignKeyField: string;\n } {\n const currentResourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const perspective = Resources_SharedUtils.getRelationshipPerspectiveForResource(\n relationship,\n currentResourceType\n );\n\n if (!perspective || !relationship.jointResourceType) {\n throw new Error('Association bulk actions require a non-self association relationship with jointResourceType');\n }\n\n const currentForeignKeyField = this.resourcesRegistry.resolveForeignKeyField({\n resourceType1: currentResourceType,\n foreignKeyField: perspective === 'resourceType1' ? relationship.foreignKeyField : undefined,\n });\n const peerResourceType = perspective === 'resourceType1'\n ? relationship.resourceType2\n : relationship.resourceType1;\n const peerForeignKeyField = this.resourcesRegistry.resolveForeignKeyField({\n resourceType1: peerResourceType,\n foreignKeyField: perspective === 'resourceType2' ? relationship.foreignKeyField : undefined,\n });\n\n return {\n jointResourceType: relationship.jointResourceType,\n peerResourceType,\n currentForeignKeyField,\n peerForeignKeyField,\n };\n }\n\n private async assertAssociationPeerResourcesExist(\n executionContext: ExecutionContext<any>,\n relationshipField: string,\n peerResourceType: ResourceType,\n peerIds: string[],\n action: ResourceRelationshipBulkAction = ResourceRelationshipBulkAction.LINK,\n options?: RepositoryOptions\n ): Promise<void> {\n for (const peerId of peerIds) {\n const readContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n peerResourceType,\n CoreResourceOperation.READ\n );\n const peerResource = await this.servicesRegistry.read(\n peerResourceType,\n readContext,\n peerId,\n options\n );\n\n if (!peerResource) {\n throw this.errorBuilder.buildError(\n ErrorType.NOT_FOUND,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n relationshipField,\n action,\n peerId,\n peerResourceType,\n },\n }\n );\n }\n }\n }\n\n private async listAssociationRowsByCurrentAndPeerIds(\n executionContext: ExecutionContext<any>,\n jointResourceType: ResourceType,\n currentForeignKeyField: string,\n currentIds: string[],\n peerForeignKeyField: string,\n peerIds: string[],\n options?: RepositoryOptions\n ): Promise<any[]> {\n const existingRows: any[] = [];\n const seenRowIds = new Set<string>();\n\n for (const currentId of currentIds) {\n for (const peerId of peerIds) {\n const listContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n jointResourceType,\n CoreResourceOperation.LIST\n );\n const result = await this.servicesRegistry.list(\n jointResourceType,\n listContext,\n {\n [currentForeignKeyField]: currentId,\n [peerForeignKeyField]: peerId,\n },\n undefined,\n options\n );\n const rows = Array.isArray(result) ? result : result.data;\n\n for (const row of rows) {\n const rowId = this.getResourceIdValue(row);\n if (rowId) {\n if (seenRowIds.has(rowId)) {\n continue;\n }\n seenRowIds.add(rowId);\n }\n\n existingRows.push(row);\n }\n }\n }\n\n return existingRows;\n }\n\n private async listAssociationRowsByCurrentIds(\n executionContext: ExecutionContext<any>,\n jointResourceType: ResourceType,\n currentForeignKeyField: string,\n currentIds: string[],\n options?: RepositoryOptions\n ): Promise<any[]> {\n const existingRows: any[] = [];\n const seenRowIds = new Set<string>();\n\n for (const currentId of currentIds) {\n const listContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n jointResourceType,\n CoreResourceOperation.LIST\n );\n const result = await this.servicesRegistry.list(\n jointResourceType,\n listContext,\n {\n [currentForeignKeyField]: currentId,\n },\n undefined,\n options\n );\n const rows = Array.isArray(result) ? result : result.data;\n\n for (const row of rows) {\n const rowId = this.getResourceIdValue(row);\n if (rowId) {\n if (seenRowIds.has(rowId)) {\n continue;\n }\n seenRowIds.add(rowId);\n }\n\n existingRows.push(row);\n }\n }\n\n return existingRows;\n }\n\n private getResolvedNestedMutationConfig(\n rel: ResourceRelationship,\n operation: CoreResourceOperation\n ) {\n return Resources_SharedUtils.resolveRelationshipNestedMutationConfig(rel, operation);\n }\n\n private getResolvedNestedReadConfig(rel: ResourceRelationship) {\n return Resources_SharedUtils.resolveRelationshipNestedReadConfig(rel);\n }\n\n private getResolvedLifecycleOnParentDelete(rel: ResourceRelationship) {\n return Resources_SharedUtils.resolveRelationshipLifecycleOnParentDeleteConfig(rel);\n }\n\n private getResolvedLifecycleOnParentCreate(rel: ResourceRelationship) {\n return Resources_SharedUtils.resolveRelationshipLifecycleOnParentCreateConfig(rel);\n }\n\n /**\n * Extract nested data from request, separating parent data from nested child data.\n * Returns { parentData, nestedData } where nestedData is keyed by field name.\n */\n private extractNestedData(\n data: any,\n relationships: ResourceRelationship[],\n operation: CoreResourceOperation\n ): { parentData: any; nestedData: Record<string, any> } {\n const parentData = { ...data };\n const nestedData: Record<string, any> = {};\n\n for (const rel of relationships) {\n const nestedConfig = this.getResolvedNestedMutationConfig(rel, operation);\n\n if (!nestedConfig) continue;\n\n const fieldName = this.getNestedFieldName(rel);\n\n if (fieldName in parentData) {\n nestedData[fieldName] = parentData[fieldName];\n delete parentData[fieldName];\n }\n }\n\n return { parentData, nestedData };\n }\n\n /**\n * Bulk variant of extractNestedData().\n * Applies the same nested field split to each item independently.\n */\n private extractNestedDataArray(\n dataArray: any[],\n relationships: ResourceRelationship[],\n operation: CoreResourceOperation,\n executionContext: ExecutionContext<any>\n ): { parentDataArray: any[]; nestedDataArray: Record<string, any>[] } {\n if (!Array.isArray(dataArray)) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n operation,\n reason: 'Bulk create expects an array of parent payloads after validation',\n receivedType: typeof dataArray,\n }\n }\n );\n }\n\n const parentDataArray: any[] = [];\n const nestedDataArray: Record<string, any>[] = [];\n\n for (const item of dataArray) {\n const { parentData, nestedData } = this.extractNestedData(item, relationships, operation);\n parentDataArray.push(parentData);\n nestedDataArray.push(nestedData);\n }\n\n return { parentDataArray, nestedDataArray };\n }\n\n /**\n * Normalize bulk create payloads to the array shape expected by the service layer.\n * Some callers may already pass the raw array, while others may use a `{ data: [] }`\n * envelope before controller-level extraction.\n */\n private normalizeCreateManyInput(\n validatedData: any,\n executionContext: ExecutionContext<any>\n ): any[] {\n if (Array.isArray(validatedData)) {\n return validatedData;\n }\n\n if (validatedData && typeof validatedData === 'object' && Array.isArray(validatedData.data)) {\n return validatedData.data;\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n operation: CoreResourceOperation.CREATE_MANY,\n reason: 'Bulk create expects either an array payload or an object with a data array',\n }\n }\n );\n }\n\n /**\n * Normalize the CREATE_MANY request shape so service callers may pass either\n * a raw array or the controller-facing `{ data: [...] }` envelope.\n */\n private normalizeCreateManyRequestPayload(\n data: any,\n executionContext: ExecutionContext<any>\n ): { data: any[] } {\n if (Array.isArray(data)) {\n return { data };\n }\n\n if (data && typeof data === 'object' && Array.isArray(data.data)) {\n return { ...data, data: data.data };\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: {\n operation: CoreResourceOperation.CREATE_MANY,\n reason: 'Bulk create expects either an array payload or an object with a data array',\n }\n }\n );\n }\n\n /**\n * Both resolvers route through the ONE derivation seam (review R2) — previously they read\n * hydrated config directly, so in platform mode they knew nothing of the construction-time\n * `platformPersistenceAdapter` override and agreed with the repositories that actually exist\n * only through the apps-manager env-truth overlay. A pre-hydration service-tier write on a\n * platform resource would have opened a MongoDB transaction against a PostgreSQL repository.\n */\n private getResolvedPersistenceAdapter(): PersistenceAdapterType {\n return resolvePersistenceAdapterForConfiguration(\n this.resourceConfiguration.persistenceAdapter,\n this.appConfigService,\n );\n }\n\n private getResolvedPersistenceAdapterForResource(resourceType: ResourceType): PersistenceAdapterType {\n const resourceConfiguration = this.resourcesRegistry.getResourceConfiguration(resourceType);\n return resolvePersistenceAdapterForConfiguration(\n resourceConfiguration.persistenceAdapter,\n this.appConfigService,\n );\n }\n\n /**\n * The adapter that owns FILE METADATA.\n *\n * Several checks around file work compared against `MONGODB` when what they meant\n * was \"the adapter FILES lives on\". Those coincide today and only today; naming\n * the concept means they follow FILES if it ever moves, instead of inverting in\n * silence. This is the same substitution the routing sites already made — an\n * adapter literal is almost never the question being asked.\n */\n private getFileMetadataAdapter(): PersistenceAdapterType {\n try {\n return this.getResolvedPersistenceAdapterForResource(CoreResourceType.FILES as ResourceType);\n } catch {\n /**\n * FILES is not registered in this registry.\n *\n * Tolerated rather than propagated: this accessor is consulted on ordinary\n * write paths that may have nothing to do with files, and the previous adapter\n * literal never asked the registry anything — so throwing here would turn a\n * total function partial and break callers that were never about FILES at all\n * (it did: five lifecycle-cascade tests, whose registries register only the\n * resources under test).\n *\n * The framework default is the honest answer: with no FILES resource there is\n * no separate store to coordinate with, so nothing should be split out.\n */\n return resolveDefaultPersistenceAdapter(this.appConfigService);\n }\n }\n\n private getResourceDatabaseService(\n executionContext: ExecutionContext<any>\n ): IDatabaseService {\n return this.getDatabaseServiceForAdapter(\n this.getResolvedPersistenceAdapter(),\n executionContext,\n );\n }\n\n /**\n * The database service that owns transactions for ONE adapter.\n *\n * Split out of {@link getResourceDatabaseService} so that a caller which needs a\n * transaction on a DIFFERENT resource's store — file metadata being the only one\n * today — can open it by asking for that resource's adapter, rather than naming\n * `this.mongoDBService` and being right only for as long as FILES stays on MongoDB.\n *\n * The dispatch literals here are the ONE place an adapter name legitimately appears:\n * mapping an adapter to its own service is the definition of dispatch, not a\n * question standing in for something else.\n */\n private getDatabaseServiceForAdapter(\n persistenceAdapter: PersistenceAdapterType,\n executionContext: ExecutionContext<any>\n ): IDatabaseService {\n // Exhaustive selection: the old `=== POSTGRESQL ? pg : mongo` shape handed the Mongo service\n // to any adapter it did not name. A new enum member is a compile error here; an unknown\n // runtime value throws inside the selector instead of opening a MongoDB transaction.\n const { databaseService, serviceName } = selectByPersistenceAdapter<{\n databaseService: IDatabaseService | undefined;\n serviceName: string;\n }>(persistenceAdapter, {\n [PersistenceAdapter.POSTGRESQL]: { databaseService: this.postgreSQLDatabaseService, serviceName: 'PostgreSQLDatabaseService' },\n [PersistenceAdapter.MONGODB]: { databaseService: this.mongoDBService, serviceName: 'MongoDBService' },\n // HTTP_API owns no transaction-capable database service BY CONSTRUCTION — remote rows have\n // no engine transaction (ETL D3: read-only slice; writes are refused). `undefined` routes\n // into the fail-closed refusal below, whose message names the missing capability.\n [PersistenceAdapter.HTTP_API]: { databaseService: undefined, serviceName: 'HTTP_API (no transaction-capable database service exists for API-backed resources)' },\n // Same `undefined`, different reason: introspection has no STORE, not merely no transaction.\n // Rows are recomputed per read from the application's own source.\n [PersistenceAdapter.INTROSPECTION]: { databaseService: undefined, serviceName: 'INTROSPECTION (rows are derived per read; no store and no transaction exist)' },\n });\n\n if (!databaseService) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `${serviceName} is required for ${persistenceAdapter}-backed resource transactions`,\n resourceType: this.resourceConfiguration.resourceIdentifier,\n persistenceAdapter,\n },\n }\n );\n }\n\n return databaseService;\n }\n\n private buildFileRepositoryOptions(options?: RepositoryOptions): RepositoryOptions | undefined {\n if (\n !options?.transaction\n || options.transaction.databaseType === this.getFileMetadataAdapter()\n ) {\n return options;\n }\n\n const { transaction: _ignoredTransaction, ...fileOptions } = options;\n return fileOptions;\n }\n\n private buildRepositoryOptionsForResource(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions\n ): RepositoryOptions | undefined {\n if (!options?.transaction) {\n return options;\n }\n\n const expectedDatabaseType = this.getResolvedPersistenceAdapterForResource(resourceType);\n if (options.transaction.databaseType === expectedDatabaseType) {\n return options;\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: 'Lifecycle deletes across mixed persistence adapters are not supported within a shared resource transaction',\n parentResourceType: this.resourceConfiguration.resourceIdentifier,\n childResourceType: resourceType,\n parentPersistenceAdapter: options.transaction.databaseType,\n childPersistenceAdapter: expectedDatabaseType,\n },\n }\n );\n }\n\n private async executeResourceTransaction<T>(\n executionContext: ExecutionContext<any>,\n callback: (optionsWithTransaction: RepositoryOptions) => Promise<T>,\n options?: RepositoryOptions\n ): Promise<T> {\n const persistenceAdapter = this.getResolvedPersistenceAdapter();\n if (options?.transaction) {\n if (options.transaction.databaseType !== persistenceAdapter) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n context: {\n reason:\n 'resource_transaction_persistence_adapter_mismatch',\n resourceType:\n this.resourceConfiguration.resourceIdentifier,\n resourcePersistenceAdapter: persistenceAdapter,\n transactionDatabaseType:\n options.transaction.databaseType,\n },\n },\n );\n }\n\n /**\n * The caller owns this native transaction. Reuse the exact context\n * directly instead of relying on a database service's AsyncLocalStorage\n * to rediscover it; doing so also makes it impossible for a nested call\n * to open and commit an accidental second transaction.\n */\n return callback(options);\n }\n\n const databaseService = this.getResourceDatabaseService(executionContext);\n\n return databaseService.executeTransaction(\n async (transactionContext) => callback({\n ...options,\n transaction: transactionContext,\n }),\n {\n nestedBehavior: 'reuse',\n }\n );\n }\n\n /**\n * Route file metadata work through the FILES resource adapter instead of\n * leaking the current resource transaction into a different repository backend.\n *\n * The transaction is opened on the FILES adapter's OWN service, resolved through\n * {@link getFileMetadataAdapter}. It used to be opened on `this.mongoDBService`\n * by name — a hardcoding that would have committed file metadata through the wrong\n * connection the moment FILES moved, while every surrounding check reported the move\n * as supported. A `assertMongoBackedFilesResource` guard stood in front of this to\n * make that unreachable; it was removed once the transaction, the guarded writes, and\n * the schema plan all followed FILES rather than naming MongoDB.\n */\n private async executeFileMetadataWork<T>(\n executionContext: ExecutionContext<any>,\n options: RepositoryOptions | undefined,\n callback: (fileOptions: RepositoryOptions | undefined) => Promise<T>\n ): Promise<T> {\n const fileMetadataAdapter = this.getFileMetadataAdapter();\n const fileOptions = this.buildFileRepositoryOptions(options);\n if (fileOptions?.transaction?.databaseType === fileMetadataAdapter) {\n return callback(fileOptions);\n }\n\n return this.getDatabaseServiceForAdapter(fileMetadataAdapter, executionContext).executeTransaction(\n async (transactionContext) => callback({\n ...fileOptions,\n transaction: transactionContext,\n }),\n {\n nestedBehavior: 'reuse',\n }\n );\n }\n\n private assertNestedMutationAdaptersMatchCurrentResource(\n relationships: ResourceRelationship[],\n executionContext: ExecutionContext<any>\n ): void {\n const currentPersistenceAdapter = this.getResolvedPersistenceAdapter();\n const incompatibleNestedResourceTypes = relationships\n .map((relationship) => relationship.resourceType2 as ResourceType)\n .filter((childResourceType) => {\n return this.getResolvedPersistenceAdapterForResource(childResourceType) !== currentPersistenceAdapter;\n });\n\n if (incompatibleNestedResourceTypes.length === 0) {\n return;\n }\n\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: 'Nested mutations across mixed persistence adapters are not supported within a shared resource transaction',\n resourceType: this.resourceConfiguration.resourceIdentifier,\n persistenceAdapter: currentPersistenceAdapter,\n incompatibleNestedResourceTypes,\n },\n }\n );\n }\n\n /**\n * Refuse bulk NESTED or FILE-FIELD mutations on a non-MongoDB-backed resource.\n *\n * This is the one refusal in this file that is a genuine **adapter capability gap**\n * rather than the FILES co-transaction question wearing an adapter literal. Its\n * sibling messages mention bulk NESTED updates, which have nothing to do with file\n * metadata: the limitation is that the PostgreSQL path has no equivalent bulk\n * nested/file transaction implementation yet.\n *\n * So the literal stays, deliberately, and means exactly what it says. It is a\n * PARITY GAP to close (see the plan's Wave 4), not a comparison to re-express —\n * rewriting it in terms of the FILES boundary would claim support that does not\n * exist.\n *\n * Note the two call sites differ: from bulk UPDATE the adapter check is reachable\n * and is the real gate; from bulk DELETE it is unreachable, because the caller has\n * already established the same condition. The second check (`mongoDBService`\n * availability) is live from both.\n */\n private assertMongoBulkTransactionSupport(\n executionContext: ExecutionContext<any>,\n message: string\n ): void {\n const persistenceAdapter = this.getResolvedPersistenceAdapter();\n\n if (persistenceAdapter !== PersistenceAdapter.MONGODB) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message,\n resourceType: this.resourceConfiguration.resourceIdentifier,\n persistenceAdapter,\n },\n }\n );\n }\n\n if (!this.mongoDBService) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `${message} (MongoDBService is not available)`,\n resourceType: this.resourceConfiguration.resourceIdentifier,\n persistenceAdapter,\n },\n }\n );\n }\n }\n\n private getResourceIdValue(resource: Record<string, any> | null | undefined): string | null {\n if (!resource) return null;\n\n /**\n * `_id` ONLY. The `?? resource.id` arm that used to be here was adapter shape leaking into the\n * resource layer: `id` is Mongoose's built-in virtual, exposed only on surrogate-primary-key\n * resources (where `toObject` enables virtuals) and never produced by PostgreSQL at all.\n *\n * It was also dead: `_id` is present on every row from both adapters and is evaluated first.\n * Keeping it implied a second identity key that the resource system does not have, and would\n * have quietly returned a MongoDB-only value the day `_id` was genuinely absent — which is\n * precisely when a caller most needs the `null` this now returns.\n */\n const rawId = resource._id;\n if (typeof rawId === 'string' && rawId.length > 0) {\n return rawId;\n }\n\n if (rawId && typeof rawId.toString === 'function') {\n const stringified = rawId.toString();\n return stringified.length > 0 ? stringified : null;\n }\n\n return null;\n }\n\n private hasExplicitFileFieldMutations(\n resourceType: ResourceType,\n data: Record<string, any>\n ): boolean {\n const fileFields = this.fileFieldDetection.detectFileFields(resourceType);\n return fileFields.some(({ fieldName }) => hasExplicitCanonicalFieldMutation(data, fieldName));\n }\n\n private getGeneratedPdfFileFields(resourceType: ResourceType): FileFieldMetadata[] {\n return this.fileFieldDetection.detectFileFields(resourceType).filter(\n (fileField) => fileField.fileMetadata.generation?.source === FileGenerationSource.PDF_TEMPLATE,\n );\n }\n\n /**\n * Refuse a write that must materialize a generated document but cannot commit\n * it with the row.\n *\n * The question is NOT \"is this resource on PostgreSQL?\" — that was only ever a\n * proxy, correct while FILES happens to be MongoDB. The question is whether the\n * declared boundary {this resource, FILES-as-ATOMIC} can commit atomically, and\n * the unit of work already owns it. Routing here means the refusal follows FILES\n * if FILES ever moves, instead of silently inverting.\n *\n * Fail-closed when the unit of work is unavailable: this is a guard, and a guard\n * that cannot evaluate its condition has not established it. Returning \"supported\"\n * would let a dangling document reference commit on the one path built to prevent it.\n */\n private assertGeneratedFileMaterializationCommitsWithRow(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n message: string,\n additionalContext?: Record<string, unknown>,\n ): void {\n const assessment = this.resourcePersistenceUnitOfWork?.assessCompatibility(\n createResourceWritePersistenceRequest({\n resourceType,\n fileParticipation: ResourceWriteFileParticipation.ATOMIC_MATERIALIZATION,\n }),\n );\n\n /**\n * Same fallback discipline as the routing helper: when the boundary cannot be\n * assessed, ask the question directly rather than assume an answer. Failing\n * closed on a missing unit of work sounded prudent and was wrong — several\n * integration containers do not bind one, and refusing there would block\n * generated documents on MongoDB, where they are perfectly safe.\n */\n const generatedDocumentCommitsWithRow = assessment\n ? assessment.compatible\n : this.getResolvedPersistenceAdapterForResource(resourceType) === this.getFileMetadataAdapter();\n\n if (generatedDocumentCommitsWithRow) {\n return;\n }\n\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message,\n resourceType,\n ...additionalContext,\n compatibilityStatus: assessment?.status,\n resourceAdapterMap: assessment?.resourceAdapterMap,\n },\n });\n }\n\n /**\n * Must this resource's file-metadata work be committed SEPARATELY from the row?\n *\n * Replaces `adapter === POSTGRESQL` at the file-work call sites. That comparison\n * was never the real question — it was a proxy that happens to be right only while\n * FILES sits on MongoDB, and would invert silently the day FILES moved. The real\n * question is whether FILES can join this write's transaction, which the unit of\n * work answers from the declared boundary.\n *\n * Returns FALSE when the unit of work is unavailable, which is the current\n * behaviour on the default adapter (join the ambient transaction). Unlike the\n * generated-document guard, \"unknown\" cannot fail closed here: the alternative\n * branch OPENS a transaction, and doing that unnecessarily fails outright on a\n * standalone MongoDB. Guessing wrong in this direction is also self-announcing —\n * the repository refuses a transaction whose `databaseType` is not its own — so a\n * wrong inline is a loud error, never a silent cross-adapter write.\n */\n private fileMetadataRequiresSeparateCommit(resourceType: ResourceType): boolean {\n const assessment = this.resourcePersistenceUnitOfWork?.assessCompatibility(\n createResourceWritePersistenceRequest({\n resourceType,\n fileParticipation: ResourceWriteFileParticipation.METADATA,\n }),\n );\n\n /**\n * `compensatedParticipantResourceMap` is meaningful ONLY on a compatible\n * assessment — it is empty on every refused one, by design. Reading it without\n * checking `compatible` first therefore reports \"nothing to compensate\" for an\n * assessment that determined nothing, which is how this shipped wrong: PostgreSQL\n * integration lanes have no unit of work bound, so file work was silently routed\n * into the SQL transaction instead of Mongo.\n */\n if (assessment?.compatible) {\n return Object.keys(assessment.compensatedParticipantResourceMap).length > 0;\n }\n\n /**\n * Fallback when the boundary could not be assessed: ask the question directly.\n *\n * This needs no unit of work, and it is FACT rather than assumption — the earlier\n * revision guessed a direction here (via an `UndeterminableFileCouplingPolicy`\n * argument) and guessed wrong for PostgreSQL. The coupling model gives the richer\n * answer when it is available; when it is not, \"is this resource on the FILES\n * adapter?\" is still exactly what the old adapter comparison asked, minus the\n * literal — so it follows FILES if FILES moves.\n */\n return this.getResolvedPersistenceAdapterForResource(resourceType) !== this.getFileMetadataAdapter();\n }\n\n private assertGeneratedPdfCreationSupported(\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n ): void {\n if (this.getGeneratedPdfFileFields(resourceType).length === 0) {\n return;\n }\n\n this.assertGeneratedFileMaterializationCommitsWithRow(\n resourceType,\n executionContext,\n 'Generated PDF creation is not yet supported for PostgreSQL-backed resources because FILES metadata is Mongo-backed and cannot be committed atomically with the parent row.',\n );\n }\n\n private async materializeGeneratedPdfFieldsForCreate(\n data: Record<string, any>,\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<{\n data: Record<string, any>;\n materializations: GeneratedPdfMaterializationRecord[];\n }> {\n const generatedPdfFields = this.getGeneratedPdfFileFields(resourceType);\n if (generatedPdfFields.length === 0) {\n return { data, materializations: [] };\n }\n\n const materializations: GeneratedPdfMaterializationRecord[] = [];\n const locale = getConfiguredPrimaryLanguage(this.appConfigService.config);\n\n try {\n for (const fileField of generatedPdfFields) {\n await this.materializeGeneratedPdfFieldAtPath({\n rootData: data,\n currentValue: data,\n pathTokens: fileField.fieldName.split('.').filter(Boolean),\n tokenIndex: 0,\n fileField,\n resourceType,\n executionContext,\n repositoryOptions: this.buildFileRepositoryOptions(options),\n locale,\n materializations,\n });\n }\n } catch (error) {\n await this.cleanupGeneratedPdfMaterializations(materializations, executionContext);\n throw error;\n }\n\n return { data, materializations };\n }\n\n private async materializeGeneratedPdfFieldAtPath(params: {\n rootData: Record<string, any>;\n currentValue: unknown;\n pathTokens: string[];\n tokenIndex: number;\n fileField: FileFieldMetadata;\n resourceType: ResourceType;\n executionContext: ExecutionContext<any>;\n repositoryOptions?: RepositoryOptions;\n locale: string;\n materializations: GeneratedPdfMaterializationRecord[];\n }): Promise<void> {\n if (params.pathTokens.length === 0) {\n return;\n }\n\n if (Array.isArray(params.currentValue)) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, params.executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: 'Generated PDF fields inside arrays are not supported in v1.',\n resourceType: params.resourceType,\n fieldName: params.fileField.fieldName,\n },\n });\n }\n\n if (!params.currentValue || typeof params.currentValue !== 'object') {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, params.executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `Generated PDF field \"${params.fileField.fieldName}\" cannot be materialized because its parent path is not an object.`,\n resourceType: params.resourceType,\n fieldName: params.fileField.fieldName,\n },\n });\n }\n\n const owner = params.currentValue as Record<string, any>;\n const fieldKey = params.pathTokens[params.tokenIndex];\n const isLeaf = params.tokenIndex === params.pathTokens.length - 1;\n\n if (isLeaf) {\n const generated = await this.pdfGenerationOrchestrator.generateForField({\n resourceType: params.resourceType,\n parentRecord: params.rootData,\n fieldName: params.fileField.fieldName,\n fileMetadata: params.fileField.fileMetadata,\n executionContext: params.executionContext,\n repositoryOptions: params.repositoryOptions,\n renderPhase: PdfGenerationRenderPhase.CREATE,\n locale: params.locale,\n defaultLocale: params.locale,\n });\n\n owner[fieldKey] = {\n fileId: generated.fileId,\n updatedAt: generated.updatedAt,\n };\n params.materializations.push({\n ...generated,\n resourceType: params.resourceType,\n fieldName: params.fileField.fieldName,\n });\n return;\n }\n\n if (owner[fieldKey] === null || owner[fieldKey] === undefined) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, params.executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `Generated PDF field \"${params.fileField.fieldName}\" cannot be materialized because required parent container \"${fieldKey}\" is missing.`,\n resourceType: params.resourceType,\n fieldName: params.fileField.fieldName,\n missingParentKey: fieldKey,\n },\n });\n }\n\n if (typeof owner[fieldKey] !== 'object') {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, params.executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `Generated PDF field \"${params.fileField.fieldName}\" cannot be materialized because parent container \"${fieldKey}\" is not an object.`,\n resourceType: params.resourceType,\n fieldName: params.fileField.fieldName,\n parentKey: fieldKey,\n },\n });\n }\n\n await this.materializeGeneratedPdfFieldAtPath({\n ...params,\n currentValue: owner[fieldKey],\n tokenIndex: params.tokenIndex + 1,\n });\n }\n\n private async cleanupGeneratedPdfMaterializations(\n materializations: GeneratedPdfMaterializationRecord[],\n executionContext: ExecutionContext<any>,\n ): Promise<void> {\n if (materializations.length === 0) {\n return;\n }\n\n const results = await Promise.allSettled(\n materializations.map((materialization) => materialization.cleanup()),\n );\n\n results.forEach((result, index) => {\n if (result.status === 'rejected') {\n const materialization = materializations[index];\n this.logger.warn('Generated PDF cleanup failed after resource operation rollback', {\n resourceType: materialization.resourceType,\n fieldName: materialization.fieldName,\n fileId: materialization.fileId,\n operationIdentifier: executionContext.operation.operationIdentifier,\n ...projectCaughtErrorLogFields(result.reason),\n });\n }\n });\n }\n\n private buildGeneratedPdfProcessingOptions(\n materializations: GeneratedPdfMaterializationRecord[],\n materializationsByRow?: readonly GeneratedPdfMaterializationRecord[][],\n ): {\n frameworkGeneratedPdfFileIdsByField?: Record<string, readonly string[]>;\n frameworkGeneratedPdfFileIdsByFieldByRow?: readonly Record<string, readonly string[]>[];\n } | undefined {\n if (materializations.length === 0) {\n return undefined;\n }\n\n const fileIdsByField: Record<string, string[]> = {};\n for (const materialization of materializations) {\n fileIdsByField[materialization.fieldName] = [\n ...(fileIdsByField[materialization.fieldName] ?? []),\n materialization.fileId,\n ];\n }\n\n const options: {\n frameworkGeneratedPdfFileIdsByField: Record<string, readonly string[]>;\n frameworkGeneratedPdfFileIdsByFieldByRow?: readonly Record<string, readonly string[]>[];\n } = { frameworkGeneratedPdfFileIdsByField: fileIdsByField };\n\n if (materializationsByRow) {\n options.frameworkGeneratedPdfFileIdsByFieldByRow = materializationsByRow.map((rowMaterializations) => {\n const rowFileIdsByField: Record<string, string[]> = {};\n for (const materialization of rowMaterializations) {\n rowFileIdsByField[materialization.fieldName] = [\n ...(rowFileIdsByField[materialization.fieldName] ?? []),\n materialization.fileId,\n ];\n }\n return rowFileIdsByField;\n });\n }\n\n return options;\n }\n\n private buildGeneratedFileFieldPatch(\n fieldName: string,\n value: { fileId: string; updatedAt: Date },\n ): Record<string, any> {\n const tokens = fieldName.split('.').filter(Boolean);\n if (tokens.length === 0) {\n return {};\n }\n\n const root: Record<string, any> = {};\n let current = root;\n for (let index = 0; index < tokens.length - 1; index += 1) {\n const token = tokens[index];\n current[token] = {};\n current = current[token];\n }\n current[tokens[tokens.length - 1]] = value;\n return root;\n }\n\n private buildGeneratedFileRepositoryPatch(\n fieldName: string,\n value: { fileId: string; updatedAt: Date },\n ): Record<string, any> {\n return fieldName.includes('.')\n ? { [fieldName]: value }\n : this.buildGeneratedFileFieldPatch(fieldName, value);\n }\n\n private getGeneratedFileIdAtPath(\n source: unknown,\n fieldName: string,\n ): string | undefined {\n const tokens = fieldName.split('.').filter(Boolean);\n let current: unknown = source;\n for (const token of tokens) {\n if (!current || typeof current !== 'object' || Array.isArray(current)) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[token];\n }\n\n if (!current || typeof current !== 'object' || Array.isArray(current)) {\n return undefined;\n }\n const fileId = (current as Record<string, unknown>).fileId;\n return typeof fileId === 'string' && fileId.length > 0\n ? fileId\n : undefined;\n }\n\n private async processBulkCreateFileFields(\n parentResults: any[],\n parentDataArray: Record<string, any>[],\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n processingOptions?: {\n frameworkGeneratedPdfFileIdsByField?: Record<string, readonly string[]>;\n frameworkGeneratedPdfFileIdsByFieldByRow?: readonly Record<string, readonly string[]>[];\n },\n ): Promise<void> {\n if (!Array.isArray(parentResults) || parentResults.length !== parentDataArray.length) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operation: CoreResourceOperation.CREATE_MANY,\n reason: 'Bulk create file processing requires one parent result per input payload',\n parentResultsCount: Array.isArray(parentResults) ? parentResults.length : 'not-array',\n payloadCount: parentDataArray.length,\n },\n }\n );\n }\n\n for (let index = 0; index < parentResults.length; index += 1) {\n const parentResult = parentResults[index];\n const resourceId = this.getResourceIdValue(parentResult);\n if (!resourceId) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operation: CoreResourceOperation.CREATE_MANY,\n reason: 'Bulk create file processing requires each created parent to expose an id',\n index,\n },\n }\n );\n }\n\n await this.fileOperationHandler.processFileFieldsForCreate(\n parentDataArray[index],\n resourceType,\n resourceId,\n executionContext,\n options,\n processingOptions?.frameworkGeneratedPdfFileIdsByFieldByRow\n ? { frameworkGeneratedPdfFileIdsByField: processingOptions.frameworkGeneratedPdfFileIdsByFieldByRow[index] ?? {} }\n : processingOptions,\n );\n }\n }\n\n private async loadBulkParentStateMap(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType | undefined,\n options?: RepositoryOptions\n ): Promise<Map<string, any>> {\n const currentStates = await this.loadBulkTargetResources(\n executionContext,\n id_or_ids_or_filter,\n options\n );\n\n return new Map(\n (Array.isArray(currentStates) ? currentStates : [])\n .map((item) => [this.getResourceIdValue(item), item] as const)\n .filter((entry): entry is [string, any] => !!entry[0])\n );\n }\n\n private async loadBulkTargetResources(\n executionContext: ExecutionContext<any>,\n id_or_ids_or_filter: IdOrIdsOrFilterType | undefined,\n options?: RepositoryOptions\n ): Promise<any[]> {\n if (!id_or_ids_or_filter) {\n return [];\n }\n\n const resourceType = this.resourceConfiguration.resourceIdentifier as ResourceType;\n const repository = this.repositoriesRegistry.getRepositoryOrThrow(resourceType);\n\n if (typeof id_or_ids_or_filter === 'string') {\n const currentState = await repository.read(executionContext, id_or_ids_or_filter, options);\n return currentState ? [currentState] : [];\n }\n\n // `listForInternalScan`, not the public `list`: this resolves the TARGETS of a bulk\n // mutation (pre-hook snapshots, file-field mutation, audit snapshots) — framework\n // machinery, not a user-facing collection read. The public door requires a declared\n // default LIST operation, which a bulk-capable resource does not necessarily expose\n // (e.g. `organizationFeatures` / `applicationFeatures` declare UPDATE_MANY-like\n // operations and NO LIST) — same wrong-door class as the dormancy batch and the\n // subject-export read (wildo-ai/wildo-ai#34). A declared LIST is still reused\n // verbatim (hooks included), so LIST-declaring resources are byte-identical.\n const snapshotCandidates = await repository.listForInternalScan(\n executionContext,\n id_or_ids_or_filter as any,\n options\n ) as any[];\n const snapshotIds = (Array.isArray(snapshotCandidates) ? snapshotCandidates : [])\n .map((item) => this.getResourceIdValue(item))\n .filter((id): id is string => !!id);\n const currentStates = await Promise.all(\n snapshotIds.map((id) => repository.read(executionContext, id, options))\n );\n\n return (Array.isArray(currentStates) ? currentStates : []).filter(Boolean);\n }\n\n private async processBulkUpdateFileFields(\n parentResults: any[],\n currentStatesById: Map<string, any>,\n parentPatch: Record<string, any>,\n resourceType: ResourceType,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions\n ): Promise<void> {\n if (!Array.isArray(parentResults)) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operation: CoreResourceOperation.UPDATE_MANY,\n reason: 'Bulk update file processing requires an array of parent results',\n },\n }\n );\n }\n\n for (const parentResult of parentResults) {\n const resourceId = this.getResourceIdValue(parentResult);\n if (!resourceId) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operation: CoreResourceOperation.UPDATE_MANY,\n reason: 'Bulk update file processing requires each updated parent to expose an id',\n },\n }\n );\n }\n\n const currentState = currentStatesById.get(resourceId);\n if (!currentState) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operation: CoreResourceOperation.UPDATE_MANY,\n reason: 'Bulk update file processing requires a pre-update snapshot for every updated parent',\n resourceId,\n },\n }\n );\n }\n\n await this.fileOperationHandler.processFileFieldsForUpdate(\n parentPatch,\n currentState,\n resourceType,\n resourceId,\n executionContext,\n options\n );\n }\n }\n\n /**\n * Extract nested data for UPDATE operations, including delete arrays.\n * Returns { parentData, nestedData, deleteData }.\n */\n private extractNestedDataForUpdate(\n data: any,\n relationships: ResourceRelationship[]\n ): { parentData: any; nestedData: Record<string, any>; deleteData: Record<string, string[]> } {\n const parentData = { ...data };\n const nestedData: Record<string, any> = {};\n const deleteData: Record<string, string[]> = {};\n\n for (const rel of relationships) {\n const nestedConfig = this.getResolvedNestedMutationConfig(rel, CoreResourceOperation.UPDATE);\n if (!nestedConfig) continue;\n\n const fieldName = this.getNestedFieldName(rel);\n const deleteFieldName = `_${fieldName}ToDelete`;\n\n if (fieldName in parentData) {\n nestedData[fieldName] = parentData[fieldName];\n delete parentData[fieldName];\n }\n\n if (nestedConfig.allowDelete && deleteFieldName in parentData) {\n deleteData[fieldName] = parentData[deleteFieldName] || [];\n delete parentData[deleteFieldName];\n }\n }\n\n return { parentData, nestedData, deleteData };\n }\n\n /**\n * Filter child relationships by evaluating discriminator/condition against the parent resource.\n *\n * This is the central runtime gate for conditional relationships in the services layer.\n * It ensures that nested CRUD operations and lifecycle cascades only apply to child\n * relationships whose conditions match the current parent resource's data.\n *\n * ## Evaluation Logic\n *\n * For each relationship:\n * 1. If `discriminator` is present: check `String(parentResource[discriminatorField])`\n * against `values`. If no match → exclude.\n * 2. If `condition` is present: call `condition(parentResource)`.\n * If it returns false → exclude.\n * 3. Relationships without discriminator or condition always pass through.\n *\n * When both discriminator and condition are present, AND semantics apply —\n * discriminator is checked first, then condition.\n *\n * ## Application Points\n *\n * This method is called at 4 critical points in the CRUD lifecycle:\n *\n * 1. **Nested CREATE** (inside transaction): After creating the parent, filters\n * child relationships using `parentResult` before processing nested creates.\n * This prevents creating children for relationships that don't apply to this parent.\n *\n * 2. **Nested READ**: After reading the parent, filters child relationships using\n * the read `result` before fetching nested children for the response.\n *\n * 3. **Nested UPDATE** (inside transaction): After updating the parent, filters\n * child relationships using `parentResult` before processing nested updates.\n *\n * 4. **Lifecycle DELETE**: Filters lifecycle relationships using pre-delete parent\n * snapshots to determine which children should cascade-delete.\n * - `DELETE`: uses the single `currentState`\n * - `DELETE_MANY`: uses the pre-delete snapshot set loaded for the matched parents,\n * so discriminator/condition gating still fails closed per deleted parent\n *\n * ## String Coercion\n *\n * Uses the shared relationship-activation utility in `saas-models`, preserving\n * the same `String()` coercion semantics used across backend and frontend\n * runtime evaluation.\n *\n * @param relationships - Child relationships to filter\n * @param parentResource - The parent resource's data to evaluate conditions against\n * @returns Relationships whose discriminator/condition match the parent (or have no conditions)\n */\n private filterRelationshipsByParent(\n relationships: ResourceRelationship[],\n parentResource: Record<string, any>\n ): ResourceRelationship[] {\n return Resources_SharedUtils.filterRelationshipsActiveForParent(\n relationships,\n parentResource,\n {\n onConditionError: 'throw',\n }\n );\n }\n\n /**\n * Process nested operations for CREATE/UPDATE.\n * Handles creating/updating/deleting children and attaching them to parent result.\n */\n private async processNestedOperations(\n operation: CoreResourceOperation,\n parentResult: any,\n nestedData: Record<string, any>,\n deleteData: Record<string, string[]>,\n relationships: ResourceRelationship[],\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions\n ): Promise<void> {\n const parentId = parentResult._id || parentResult.id;\n\n if (!parentId) {\n this.logDebug('No parent ID found, skipping nested operations');\n return;\n }\n\n const relationshipsByFieldName = new Map(\n relationships.map(rel => [this.getNestedFieldName(rel), rel] as const)\n );\n\n // Process deletions first (for UPDATE only)\n if (operation === CoreResourceOperation.UPDATE || operation === CoreResourceOperation.UPDATE_MANY) {\n for (const [fieldName, idsToDelete] of Object.entries(deleteData)) {\n if (!idsToDelete || idsToDelete.length === 0) continue;\n\n const rel = relationshipsByFieldName.get(fieldName);\n if (!rel) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n parentResourceType: this.resourceConfiguration.resourceIdentifier,\n fieldName,\n operation,\n reason: 'nested delete field is not active for the current parent state or does not map to an allowed relationship',\n },\n }\n );\n }\n\n const nestedConfig = this.getResolvedNestedMutationConfig(rel, CoreResourceOperation.UPDATE);\n if (!nestedConfig?.allowDelete) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n parentResourceType: this.resourceConfiguration.resourceIdentifier,\n childResourceType: rel.resourceType2,\n fieldName,\n operation,\n reason: 'nested deletes are not enabled for this relationship',\n },\n }\n );\n }\n\n this.logDebug('Deleting nested children', { fieldName, count: idsToDelete.length });\n\n for (const childId of idsToDelete) {\n // Build relationship context for child DELETE\n const relationshipContext: import('@wildo-ai/saas-models').ExecutionContext_RelationshipContext = {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n relationshipField: this.getFKFieldForRelationship(rel),\n resourceId: parentId\n };\n\n // Create sub-call context with correct operation\n const subContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n rel.resourceType2,\n CoreResourceOperation.DELETE,\n undefined,\n childId,\n relationshipContext\n );\n\n // Authorization: DELETE operation on child resource is checked via enabledCondition\n // in doByExecutionContext when servicesRegistry.delete is called\n await this.servicesRegistry.delete(\n rel.resourceType2,\n subContext,\n childId,\n options\n );\n }\n }\n }\n\n // Process creates and updates\n for (const [fieldName, items] of Object.entries(nestedData)) {\n if (!items) continue;\n\n const rel = relationshipsByFieldName.get(fieldName);\n if (!rel) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n parentResourceType: this.resourceConfiguration.resourceIdentifier,\n fieldName,\n operation,\n reason: 'nested field is not active for the current parent state or does not map to an allowed relationship',\n },\n }\n );\n }\n\n const nestedConfig = this.getResolvedNestedMutationConfig(rel, operation);\n\n if (!nestedConfig) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n parentResourceType: this.resourceConfiguration.resourceIdentifier,\n childResourceType: rel.resourceType2,\n fieldName,\n operation,\n reason: 'nested operations are not enabled for this relationship',\n },\n }\n );\n }\n\n const fkField = this.getFKFieldForRelationship(rel);\n const processedChildren: any[] = [];\n const itemsArray = Array.isArray(items) ? items : [items];\n const isCreateOperation = operation === CoreResourceOperation.CREATE || operation === CoreResourceOperation.CREATE_MANY;\n const isUpdateOperation = operation === CoreResourceOperation.UPDATE || operation === CoreResourceOperation.UPDATE_MANY;\n\n for (const item of itemsArray) {\n const hasId = !!(item._id || item.id);\n\n if (hasId && nestedConfig.allowUpdate && isUpdateOperation) {\n // Update existing child\n const childId = item._id || item.id;\n const childData = { ...item, [fkField]: parentId };\n delete childData._id; // Remove _id from update data\n\n // Build relationship context for child UPDATE\n const relationshipContext: import('@wildo-ai/saas-models').ExecutionContext_RelationshipContext = {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n relationshipField: fkField,\n resourceId: parentId\n };\n\n // Create sub-call context with correct operation\n const subContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n rel.resourceType2,\n CoreResourceOperation.UPDATE,\n undefined,\n childId,\n relationshipContext\n );\n\n // Authorization: UPDATE operation on child resource is checked via enabledCondition\n // in doByExecutionContext when servicesRegistry.update is called\n const updatedChild = await this.servicesRegistry.update(\n rel.resourceType2,\n subContext,\n childId,\n childData,\n options\n );\n\n if (updatedChild) {\n processedChildren.push(updatedChild);\n }\n } else if (!hasId && nestedConfig.allowCreate) {\n // Create new child\n const childData = { ...item, [fkField]: parentId };\n\n // Build relationship context for child CREATE\n const relationshipContext: import('@wildo-ai/saas-models').ExecutionContext_RelationshipContext = {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n relationshipField: fkField,\n resourceId: parentId\n };\n\n // Create sub-call context with correct operation (no resourceId for CREATE)\n const subContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n rel.resourceType2,\n CoreResourceOperation.CREATE,\n undefined,\n undefined, // No resourceId for CREATE - it doesn't exist yet\n relationshipContext\n );\n\n // Authorization: CREATE operation on child resource is checked via enabledCondition\n // in doByExecutionContext when servicesRegistry.create is called\n const createdChild = await this.servicesRegistry.create(\n rel.resourceType2,\n subContext,\n childData,\n options\n );\n\n if (createdChild) {\n processedChildren.push(createdChild);\n }\n } else {\n const action = hasId ? 'update_existing' : 'create_new';\n const reason = hasId\n ? (\n isCreateOperation\n ? 'nested create payloads cannot reference existing child ids'\n : 'nested updates are not enabled for this relationship'\n )\n : 'nested creates are not enabled for this relationship';\n\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n parentResourceType: this.resourceConfiguration.resourceIdentifier,\n childResourceType: rel.resourceType2,\n fieldName,\n action,\n reason,\n operation,\n },\n }\n );\n }\n }\n\n // Attach children to parent result — 1:1 gets single/null, 1:N gets array\n if (isOneToOneCardinality(rel.cardinality2)) {\n parentResult[fieldName] = processedChildren[0] || null;\n } else {\n parentResult[fieldName] = processedChildren;\n }\n }\n }\n\n /**\n * Bulk variant of processNestedOperations().\n * Reuses the single-parent orchestration path for each returned parent result,\n * preserving sub-call execution contexts and relationship activation checks.\n *\n * Contract:\n * - CREATE_MANY expects per-row nested payloads and receives one nested envelope\n * per created parent result.\n * - UPDATE_MANY currently uses broadcast semantics for nested create/update payloads:\n * the same validated nested envelope is replayed for every matched parent result.\n * - UPDATE_MANY nested deletes are intentionally more restrictive and are rejected\n * earlier when a shared delete payload would target multiple parents ambiguously.\n */\n private async processBulkNestedOperations(\n operation: CoreResourceOperation,\n parentResults: any[],\n nestedDataArray: Record<string, any>[],\n deleteDataArray: Record<string, string[]>[],\n relationships: ResourceRelationship[],\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions\n ): Promise<void> {\n if (!Array.isArray(parentResults) || parentResults.length === 0) {\n return;\n }\n\n if (parentResults.length !== nestedDataArray.length) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n operation,\n parentResultsCount: parentResults.length,\n nestedPayloadCount: nestedDataArray.length,\n reason: 'bulk nested orchestration requires one nested payload envelope per parent result',\n },\n }\n );\n }\n\n for (let index = 0; index < parentResults.length; index += 1) {\n const parentResult = parentResults[index];\n const nestedData = nestedDataArray[index] ?? {};\n const deleteData = deleteDataArray[index] ?? {};\n\n if (!parentResult || (!Object.keys(nestedData).length && !Object.keys(deleteData).length)) {\n continue;\n }\n\n const activeRelationships = this.filterRelationshipsByParent(relationships, parentResult);\n if (activeRelationships.length === 0) {\n continue;\n }\n\n await this.processNestedOperations(\n operation,\n parentResult,\n nestedData,\n deleteData,\n activeRelationships,\n executionContext,\n options\n );\n }\n }\n\n /**\n * Process nested read operations - include children in READ response.\n */\n private async processNestedRead(\n parentResult: any,\n relationships: ResourceRelationship[],\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions\n ): Promise<void> {\n if (!parentResult) return;\n\n const parentId = parentResult._id || parentResult.id;\n\n if (!parentId) return;\n\n for (const rel of relationships) {\n const readConfig = this.getResolvedNestedReadConfig(rel);\n if (!readConfig) continue;\n\n const fieldName = this.getNestedFieldName(rel);\n const fkField = this.getFKFieldForRelationship(rel);\n\n // Build filter to find children\n const filter: any = { [fkField]: parentId };\n\n // Apply maxItems limit if specified\n const limit = readConfig.maxItems;\n\n // Build relationship context for child nested fetch\n const relationshipContext: import('@wildo-ai/saas-models').ExecutionContext_RelationshipContext = {\n resourceType: this.resourceConfiguration.resourceIdentifier,\n relationshipField: fkField,\n resourceId: parentId\n };\n\n const childrenOptions = { ...options } as any;\n childrenOptions.dataMode = readConfig.dataMode;\n\n // Attach to parent result — 1:1 gets single/null, 1:N gets array\n if (isOneToOneCardinality(rel.cardinality2)) {\n const subContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n rel.resourceType2,\n CoreResourceOperation.READ,\n { dataMode: readConfig.dataMode },\n undefined,\n relationshipContext\n );\n const child = await this.servicesRegistry.read(\n rel.resourceType2,\n subContext,\n filter,\n childrenOptions\n );\n parentResult[fieldName] = child ?? null;\n } else {\n const subContext = await this.executionContextCreator.createForSubCall(\n executionContext,\n rel.resourceType2,\n CoreResourceOperation.LIST,\n { dataMode: readConfig.dataMode },\n undefined,\n relationshipContext\n );\n const children = await this.servicesRegistry.list(\n rel.resourceType2,\n subContext,\n filter,\n limit ? { limit } : undefined,\n childrenOptions\n );\n parentResult[fieldName] = Array.isArray(children) ? children : [];\n }\n }\n }\n\n /**\n * Execute lifecycle operations for child resources based on relationship configuration.\n * Handles onParentDelete cascade for all child relationships with lifecycle.onParentDelete.enabled = true.\n */\n private async executeLifecycleOperations(\n operation: CoreResourceOperation,\n result: any,\n executionContext: ExecutionContext<any>,\n currentState?: any,\n options?: RepositoryOptions\n ): Promise<void> {\n\n // Only handle DELETE operations for lifecycle\n if (operation !== CoreResourceOperation.DELETE && operation !== CoreResourceOperation.DELETE_MANY) {\n return;\n }\n\n const resourceRelationships = this.resourceConfiguration.resourceRelationships;\n const childRelationships = getChildDirectionRelationships(resourceRelationships);\n\n // Find relationships with lifecycle.onParentDelete.enabled = true\n let lifecycleRelationships = childRelationships.filter(rel =>\n this.getResolvedLifecycleOnParentDelete(rel)?.enabled === true\n );\n\n if (lifecycleRelationships.length === 0) {\n return;\n }\n\n // Application point #4: Lifecycle DELETE — filter lifecycle relationships using\n // the available pre-delete parent snapshots so cascades only apply where the\n // relationship is active for the concrete parent variant being deleted.\n if (operation === CoreResourceOperation.DELETE && currentState) {\n lifecycleRelationships = this.filterRelationshipsByParent(lifecycleRelationships, currentState);\n if (lifecycleRelationships.length === 0) {\n return;\n }\n }\n\n this.logDebug('Executing lifecycle operations for delete', {\n operation,\n relationshipsCount: lifecycleRelationships.length,\n resourceType: this.resourceConfiguration.resourceIdentifier\n });\n\n // Get parent ID(s) from result\n const parentIds: string[] = operation === CoreResourceOperation.DELETE_MANY\n ? (\n Array.isArray(result)\n ? result.map((item: any) => (typeof item === 'string' ? item : this.getResourceIdValue(item))).filter(Boolean)\n : result?.deletedIds || []\n )\n : (() => {\n if (typeof result === 'string') {\n return [result];\n }\n const resultId = result?._id ?? result?.id;\n if (resultId) {\n return [String(resultId)];\n }\n const currentStateId = currentState ? this.getResourceIdValue(currentState) : undefined;\n return currentStateId ? [currentStateId] : [];\n })();\n\n if (parentIds.length === 0) {\n this.logDebug('No parent IDs found in result, skipping lifecycle operations');\n return;\n }\n\n // Process each child relationship with lifecycle config\n for (const relationship of lifecycleRelationships) {\n // `mode` + `strategy` are read inside dispatchLifecycleCascadeForRelationship (the ONE dispatcher,\n // shared with the grandchild recursion) — only the depth budget is resolved here.\n const lifecycleConfig = this.getResolvedLifecycleOnParentDelete(relationship)!;\n const maxDepth = lifecycleConfig.maxDepth || 1;\n let relationshipParentIds = parentIds;\n\n if (operation === CoreResourceOperation.DELETE_MANY && Array.isArray(currentState)) {\n const currentStatesById = new Map(\n currentState.map((item) => [this.getResourceIdValue(item), item] as const)\n .filter((entry): entry is [string, any] => !!entry[0])\n );\n relationshipParentIds = parentIds.filter((parentId) => {\n const parentSnapshot = currentStatesById.get(parentId);\n if (!parentSnapshot) {\n return false;\n }\n\n return this.filterRelationshipsByParent([relationship], parentSnapshot).length > 0;\n });\n }\n\n if (relationshipParentIds.length === 0) {\n continue;\n }\n\n await this.dispatchLifecycleCascadeForRelationship(\n relationship,\n relationshipParentIds,\n executionContext,\n 0, // currentDepth — top of the cascade\n maxDepth,\n new Set(), // visitedResourceIds for circular reference detection\n options,\n );\n }\n }\n\n /**\n * THE single (strategy × mode) cascade dispatcher for `onParentDelete`. Every entry into the\n * cascade — the top-level post-delete dispatch AND the grandchild recursion inside\n * {@link deleteChildrenImmediate} — MUST route through here, so the teardown strategy is honored at\n * EVERY depth, not just depth 0.\n *\n * ⚠️ This centralization is load-bearing, not stylistic. When the dispatch lived inline at the top\n * level only, the grandchild recursion called `deleteChildrenImmediate` directly and read just\n * `enabled` + `maxDepth` — so a grandchild edge declaring `IMPERSONALIZE_AND_RETAIN` was silently\n * HARD-DELETED (destroying data a legal-retention obligation required keeping), and a grandchild\n * declaring `mode: LAZY` was silently deleted immediately. Both axes are now honored at depth.\n *\n * FAIL-CLOSED: a missing/unknown arm throws rather than falling through to data loss (an unintended\n * DELETE) or to leaving personal data behind (a skipped IMPERSONALIZE).\n */\n /**\n * @returns whether a teardown actually RAN for this edge.\n *\n * `false` means the cascade declined to act — the child had no registered service or repository, or\n * the depth budget was already spent. It does NOT mean \"no rows existed\": discovery finding zero\n * children is a teardown that ran and had nothing to do, which is `true`.\n *\n * **Why this is a return value and not fire-and-forget.** `SubjectErasureReport.edges[].executed` is\n * the COMPLIANCE RECEIPT for a data-protection request, and it used to be set `true` unconditionally\n * once this method returned — so an edge skipped for a missing registration was reported as torn\n * down. A receipt that overstates an erasure is worse than no receipt. The delete cascade ignores\n * this value (its contract is \"throw or succeed\"), which is why the defect could live here unnoticed.\n */\n private async dispatchLifecycleCascadeForRelationship(\n relationship: any,\n parentIds: string[],\n executionContext: ExecutionContext<any>,\n currentDepth: number,\n maxDepth: number,\n visitedResourceIds: Set<string>,\n options?: RepositoryOptions,\n ): Promise<boolean> {\n const lifecycleConfig = this.getResolvedLifecycleOnParentDelete(relationship)!;\n const mode = lifecycleConfig.mode || ChildLifecycleMode.IMMEDIATE;\n // The teardown STRATEGY (what happens to the child) is orthogonal to the MODE (when it happens).\n // Default DELETE preserves today's hard-delete cascade; IMPERSONALIZE_AND_RETAIN scrubs+retains.\n const strategy = lifecycleConfig.strategy || ChildLifecycleStrategy.DELETE;\n\n switch (strategy) {\n case ChildLifecycleStrategy.DELETE:\n if (mode === ChildLifecycleMode.IMMEDIATE) {\n return await this.deleteChildrenImmediate(\n relationship,\n parentIds,\n executionContext,\n currentDepth,\n maxDepth,\n visitedResourceIds,\n options\n );\n } else if (mode === ChildLifecycleMode.LAZY) {\n return await this.queueChildDeletion(relationship, parentIds, executionContext);\n } else {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: `Unknown ChildLifecycleMode '${mode}' for the DELETE strategy — refusing to cascade (fail-closed).`,\n childResourceType: relationship.resourceType2,\n mode,\n },\n });\n }\n break;\n\n case ChildLifecycleStrategy.IMPERSONALIZE_AND_RETAIN:\n if (mode === ChildLifecycleMode.IMMEDIATE) {\n return await this.impersonalizeChildrenImmediate(\n relationship,\n parentIds,\n executionContext,\n currentDepth, // v1 impersonalize does not recurse further\n maxDepth,\n visitedResourceIds,\n options\n );\n } else {\n // LAZY (async) retain-and-scrub is not yet implemented. Fail closed rather than\n // silently hard-deleting (data loss) or skipping the scrub (personal data left behind).\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: `IMPERSONALIZE_AND_RETAIN is supported only with mode = IMMEDIATE (async/LAZY retain-and-scrub is not yet implemented).`,\n childResourceType: relationship.resourceType2,\n mode,\n },\n });\n }\n break;\n\n default: {\n // Compile-time exhaustiveness: adding a ChildLifecycleStrategy member without giving it a\n // cascade arm above becomes a TYPE error here, not a silent runtime-only discovery.\n const _exhaustiveStrategyCheck: never = strategy;\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: `Unknown ChildLifecycleStrategy '${_exhaustiveStrategyCheck}' — refusing to cascade (fail-closed).`,\n childResourceType: relationship.resourceType2,\n strategy,\n },\n });\n }\n }\n }\n\n /**\n * Execute composition `onParentCreate` seeding — the creation half of the\n * composition lifecycle, symmetric with {@link executeLifecycleOperations}\n * (delete cascade). For every child relationship declared with\n * `lifecycle.onParentCreate.enabled = true`, eagerly create the composition\n * child so the \"part\" co-exists with its \"whole\".\n *\n * Seeds through the trusted-system-write seam (`createAsSystem`), preserving\n * Guard-1 (`systemAccessPolicy.create` fail-closed opt-in) + Guard-4 (privileged\n * write audit). Base seed = the injected parent FK; the child's create pipeline\n * applies its Zod schema defaults, optionally overlaid by\n * `initialData.override(ctx)` for derived fields (Tier-2).\n *\n * Runs from the post-create hook. A parent created inside a transaction queues\n * the seed loop on that transaction's post-commit boundary; a parent created\n * without a transaction runs it immediately. This prevents an aborted or\n * database-driver-retried parent attempt from leaking independently committed\n * child rows while preserving mixed-adapter, non-fatal seed semantics.\n *\n * IMMEDIATE therefore means \"immediately after commit,\" NOT atomic with the\n * parent. An absent child self-heals via the omit-empty-1:1 context-embed. A\n * seed failure (a child that hasn't opted into `systemAccessPolicy.create`, or\n * a unique-FK conflict on an already-seeded child) is swallowed + logged so it\n * can never 500 the parent create; the warn-first boot guard is where a genuine\n * misconfiguration is surfaced.\n *\n * Re-entrancy: `createAsSystem` forwards `options`, so a seeded child that is\n * itself a composition parent re-enters this method at `compositionSeedDepth + 1`,\n * bounded by each relationship's `maxDepth`. (The delete cascade's repository-tier\n * depth guard is not reusable — this path re-enters at the service tier.)\n */\n private async executeCompositionSeedingForCreate(\n result: any,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions\n ): Promise<void> {\n const resourceRelationships = this.resourceConfiguration.resourceRelationships;\n const childRelationships = getChildDirectionRelationships(resourceRelationships);\n\n let seedRelationships = childRelationships.filter(\n (rel) => this.getResolvedLifecycleOnParentCreate(rel)?.enabled === true\n );\n if (seedRelationships.length === 0) {\n return;\n }\n\n // Only seed relationships active for the concrete created parent variant\n // (mirrors the delete cascade's discriminator-aware filtering).\n seedRelationships = this.filterRelationshipsByParent(seedRelationships, result);\n if (seedRelationships.length === 0) {\n return;\n }\n\n const parentId = this.getResourceIdValue(result);\n if (!parentId) {\n this.logDebug('Composition seeding skipped: no parent id on create result');\n return;\n }\n\n // SystemAccess is injected on ServicesRegistryHandlerBackendService and reached\n // from here (ServiceResourceBackendService) via the registry — mirrors :2885.\n const systemAccess = this.servicesRegistry.getSystemAccessService?.();\n if (!systemAccess) {\n this.logDebug('Composition seeding skipped: SystemAccessService unavailable');\n return;\n }\n\n const currentDepth = options?.compositionSeedDepth ?? 0;\n if (options?.transaction) {\n const transaction = options.transaction;\n const postCommitParentResult = cloneResourceTransactionAttemptInput(\n result,\n );\n const postCommitOptions: RepositoryOptions = {\n compositionSeedDepth: currentDepth,\n ...(options.compositionSeedRequestInput !== undefined && {\n compositionSeedRequestInput:\n cloneResourceTransactionAttemptInput(\n options.compositionSeedRequestInput,\n ),\n }),\n };\n registerTransactionPostCommitEffect(transaction, {\n key: [\n 'composition-seed-after-parent-commit',\n String(this.resourceConfiguration.resourceIdentifier),\n parentId,\n String(currentDepth),\n ].join(':'),\n execute: () =>\n this.executeCompositionSeedingForCreate(\n postCommitParentResult,\n executionContext,\n postCommitOptions,\n ),\n });\n return;\n }\n\n for (const relationship of seedRelationships) {\n const seedConfig = this.getResolvedLifecycleOnParentCreate(relationship)!;\n const maxDepth = seedConfig.maxDepth ?? 1;\n if (currentDepth >= maxDepth) {\n this.logDebug('Composition seed depth cap reached; skipping child seed', {\n childResourceType: relationship.resourceType2,\n currentDepth,\n maxDepth,\n });\n continue;\n }\n\n const childResourceType = relationship.resourceType2 as ResourceType;\n const foreignKeyField = relationship.foreignKeyField;\n if (!foreignKeyField) {\n this.logDebug('Composition seed skipped: relationship declares no foreignKeyField', {\n childResourceType,\n });\n continue;\n }\n\n // A feature-gated child resource (e.g. lifecycle-state when\n // `config.lifecycle.enabled` is false) is EXCLUDED from the runtime registry at\n // assembly time (`start-application` → `excludedResourceTypes` removes the config\n // + standalone relationships + field ids). But the PARENT's compiled\n // `childRelationships` are derived from the pre-exclusion relationship set, so\n // they still reference the excluded child. Seeding it would reach\n // `createAsSystem` → `getResourceConfiguration` → an opaque\n // `resources_registry_initialization_failed` (config absent). Skip cleanly when\n // the child is not registered — the disabled feature means the child simply does\n // not exist to seed. Mirrors the onParentDelete cascade's `if (!childService)`\n // skip in `deleteChildrenImmediate`; uses the safe (undefined-returning)\n // `tryGetResourceConfiguration` rather than the throwing `getResourceConfiguration`.\n if (!this.resourcesRegistry.tryGetResourceConfiguration(childResourceType)) {\n this.logDebug('Composition seed skipped: child resource not registered (feature-gated / excluded from registry)', {\n childResourceType,\n });\n continue;\n }\n\n // Base seed = the injected parent FK; the child create pipeline applies its\n // Zod schema defaults. `override(ctx)` overlays derived fields (Tier-2).\n let seedData: Record<string, unknown> = { [foreignKeyField]: parentId };\n const override = seedConfig.initialData?.override;\n if (override) {\n try {\n const overlay = override({\n parentObject: (result ?? {}) as Record<string, unknown>,\n parentResourceType: this.resourceConfiguration.resourceIdentifier as string,\n initiatorIds: {\n userId: executionContext.initiatorIds?.userId,\n organizationId: executionContext.initiatorIds?.organizationId,\n applicationId: executionContext.initiatorIds?.applicationId,\n },\n // Tier-2 input-derived threading: the create input the provisioning\n // path set on `create(parent, …, { compositionSeedRequestInput })`\n // (e.g. a registration/SSO/SCIM name payload that has no home on the\n // parent row). Absent for pure-defaults children + re-entrant seeds.\n requestInput: options?.compositionSeedRequestInput,\n });\n // An override may DECLINE the seed for this parent-create by returning\n // `undefined` (the required input was absent — e.g. an org-admin invite\n // create carries no name; the invitee supplies it later at acceptance).\n // Skip cleanly rather than attempt a create that would fail validation.\n if (overlay === undefined) {\n this.logDebug('Composition seed override declined for this create; skipping child seed', {\n childResourceType,\n });\n continue;\n }\n seedData = { ...seedData, ...overlay };\n } catch (overrideError) {\n this.logger.warn('Composition seed override threw; skipping child seed', {\n childResourceType,\n ...projectCaughtErrorLogFields(overrideError),\n });\n continue;\n }\n }\n\n try {\n // Pass ONLY the re-entrancy depth — never the parent's other options\n // (transaction / ifMatchVersion / fieldTimestamps are parent-specific).\n await systemAccess.createAsSystem(childResourceType, seedData, {\n compositionSeedDepth: currentDepth + 1,\n });\n this.logDebug('Composition child seeded', { childResourceType, parentId });\n } catch (seedError) {\n // A `WildoError_Backend` is a PLAIN OBJECT (not an Error instance): `String()`\n // yields \"[object Object]\" and `.message` is undefined, so the previous\n // `instanceof Error ? .message : String()` masked every engine-thrown seed\n // failure. The human-readable cause lives in `context.message` (+\n // `context.originalError` for a wrapped Mongoose/driver error); a native error\n // (e.g. a raw Mongoose ValidationError) keeps its stack. Un-masks the swallow.\n this.logger.warn('Composition child seed failed (swallowed)', {\n childResourceType,\n parentId,\n error: isWildoBackendError(seedError)\n ? { customMessageReference: seedError.customMessageReference, context: seedError.context }\n : seedError instanceof Error\n ? (seedError.stack ?? seedError.message)\n : String(seedError),\n });\n }\n }\n }\n\n /**\n * SHARED child-discovery for the `onParentDelete` cascade — used by BOTH strategies\n * (`deleteChildrenImmediate` and `impersonalizeChildrenImmediate`) so there is ONE discovery + cycle\n * guard, never a forked cascade. Finds the children of `parentIds` via the FK relationship (adapter-\n * neutral repository read/list), de-duplicates against the shared `visitedResourceIds` cycle set, and\n * returns the survivors. The caller applies the DEPTH guard BEFORE calling this, and the strategy-\n * specific teardown (delete vs impersonalize) + any grandchild recursion AFTER.\n *\n * ⚠️ The DEPTH guard is deliberately NOT here — it is the CALLER's responsibility (each strategy\n * applies it before calling this), because only the caller knows whether it recurses. Do not move\n * it in, and do not drop it from a new strategy.\n *\n * Returns `null` when there is nothing to cascade: no child service, no children, or every child\n * already visited in this chain.\n */\n private async discoverCascadeChildren(\n relationship: any,\n parentIds: string[],\n executionContext: ExecutionContext<any>,\n cascadeStrategy: ChildLifecycleStrategy,\n visitedResourceIds: Set<string>,\n options?: RepositoryOptions,\n ): Promise<{\n childResourceType: ResourceType;\n fkField: string;\n // `undefined` on the (common) no-transaction path — `buildRepositoryOptionsForResource` returns\n // the caller's `options` verbatim. Keep the `| undefined` honest: `strict` is off in this\n // package, so a lying non-optional type would only surface as a runtime TypeError in a future\n // strategy that dereferences it without optional chaining.\n childRepositoryOptions: RepositoryOptions | undefined;\n newChildIds: string[];\n childSnapshotsById: Map<string, any>;\n } | null> {\n const childResourceType = relationship.resourceType2;\n const fkField = this.getFKFieldForRelationship(relationship);\n\n // Get child service from registry\n const childService = this.servicesRegistry.getService(childResourceType);\n if (!childService) {\n // FAIL-CLOSED for the retain strategy. A missing child service is a MISCONFIGURATION, not a\n // benign \"nothing to do\" — and for IMPERSONALIZE_AND_RETAIN silently skipping means personal\n // data survives an erasure while the parent delete commits (the exact outcome this cascade's\n // other guards refuse). DELETE keeps its historical tolerance (skip ⇒ orphaned rows, already\n // the pre-existing contract), but now says so at WARN instead of DEBUG.\n if (cascadeStrategy === ChildLifecycleStrategy.IMPERSONALIZE_AND_RETAIN) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `IMPERSONALIZE_AND_RETAIN cascade cannot scrub child resource \"${childResourceType}\": no service is ` +\n `registered for it in this process. Refusing to skip — that would leave personal data behind after ` +\n `an erasure while the parent delete commits.`,\n childResourceType,\n fkField,\n relationshipField: this.getNestedFieldName(relationship),\n },\n }\n );\n }\n this.logger.warn('Child service not found, skipping lifecycle cascade', {\n childResourceType,\n cascadeStrategy,\n });\n return null;\n }\n\n // Build filter to find children with parent FK in parentIds.\n // Child discovery must stay adapter-neutral: use repository operations\n // rather than reaching into Mongo-specific model internals.\n const filter = { [fkField]: { $in: parentIds } };\n const childRepositoryOptions = this.buildRepositoryOptionsForResource(\n childResourceType,\n executionContext,\n options\n );\n\n // Child DISCOVERY authoritatively constrains the FK via the explicit `{ [fkField]: { $in:\n // parentIds } }` filter above, so the child's ambient contextual filter must NOT re-apply the\n // parent's `fkField` execution-context value onto the SAME path: for a single parent it is a\n // redundant restatement, and for a multi-parent cascade it actively conflicts (the parent EC\n // carries one id while the discovery lists several). When the parent's resource field identifier\n // equals the child's FK (e.g. TODOS' `todoId` is the occurrences child FK), that collision made\n // a recurring-todo delete fail with `api_call_initiator_parameter_inconsistent`. Excluding only\n // `fkField` from the CONTEXTUAL filter for discovery leaves tenant scope (organizationId/…) fully\n // enforced — and it is scoped to discovery only; the returned `childRepositoryOptions` used for\n // the actual child delete (by explicit ids) is intentionally left untouched. Adapter-neutral:\n // both repositories honour the `string[]` field-exclusion form.\n const existingExclusion = childRepositoryOptions?.excludeContextualFilter;\n const childDiscoveryOptions: RepositoryOptions = {\n ...(childRepositoryOptions ?? {}),\n excludeContextualFilter:\n existingExclusion === true\n ? true\n : [...(Array.isArray(existingExclusion) ? existingExclusion : []), fkField],\n };\n\n // Find children first (we need their IDs for the teardown + recursion)\n const childRepository = this.repositoriesRegistry.getRepository(childResourceType);\n\n /**\n * A missing child REPOSITORY gets the same policy as a missing child SERVICE above — because the\n * two sets can diverge, and dereferencing this is a bare `TypeError` naming nothing.\n *\n * They are not initialized from the same input: `initializeServices()` walks the entire RESOURCE\n * registry (`getResourceTypes()`), while repositories are created only for the configuration map\n * handed to `initializeRepositories()`. In an ordinary application boot those coincide, so this\n * branch is unreachable — but nothing structurally holds them in lockstep, and when they drift the\n * failure was `Cannot read properties of undefined (reading 'supportsOperation')` from inside a\n * cascade, with no resource named and no indication that a registration was the cause.\n *\n * Measured, not hypothesized: this is what stopped the erasure-completion integration lane, and it\n * is the same class of failure recorded (as `…(reading 'filter')`) when that lane was first\n * attempted on 2026-08-05 and abandoned as \"harness completeness\".\n *\n * The strategy split is deliberately IDENTICAL to the service branch: skipping is the historical\n * DELETE contract (orphaned rows), but for IMPERSONALIZE_AND_RETAIN it would leave personal data\n * behind while the parent delete commits.\n */\n if (!childRepository) {\n if (cascadeStrategy === ChildLifecycleStrategy.IMPERSONALIZE_AND_RETAIN) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `IMPERSONALIZE_AND_RETAIN cascade cannot scrub child resource \"${childResourceType}\": a service is ` +\n `registered for it but no REPOSITORY is. Refusing to skip — that would leave personal data behind ` +\n `after an erasure while the parent delete commits.`,\n childResourceType,\n fkField,\n relationshipField: this.getNestedFieldName(relationship),\n },\n }\n );\n }\n this.logger.warn('Child repository not found, skipping lifecycle cascade', {\n childResourceType,\n cascadeStrategy,\n reason: 'a service is registered for this resource but no repository is',\n });\n return null;\n }\n\n let children: any[] = [];\n\n if (isOneToOneCardinality(relationship.cardinality2)) {\n if (!childRepository.supportsOperation(CoreResourceOperation.READ)) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Lifecycle cascade requires READ support on child resource \"${childResourceType}\" ` +\n `to discover 1:1 dependents.`,\n childResourceType,\n fkField,\n relationshipField: this.getNestedFieldName(relationship),\n },\n }\n );\n }\n\n const child = await childRepository.read(executionContext, filter, childDiscoveryOptions);\n children = child ? [child] : [];\n } else {\n if (!childRepository.supportsOperation(CoreResourceOperation.LIST)) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Lifecycle cascade requires LIST support on child resource \"${childResourceType}\" ` +\n `to discover dependent children.`,\n childResourceType,\n fkField,\n relationshipField: this.getNestedFieldName(relationship),\n },\n }\n );\n }\n\n const listedChildren = await childRepository.list(executionContext, filter, childDiscoveryOptions);\n children = Array.isArray(listedChildren) ? listedChildren : [];\n }\n\n if (!children || children.length === 0) {\n // Discovery RAN and found no dependents. This is materially different from a DECLINE (a missing\n // child repository/service, or a spent depth budget), which returns `null` and is the caller's\n // `executed = false` arm. Per the SubjectErasureEdgeOutcome.executed contract, an empty result is\n // \"a teardown that ran with nothing to do\" and MUST be reported as executed = true — otherwise a\n // healthy subject with no rows on an edge is misrecorded on the compliance receipt as data left\n // live. Return an empty-but-valid discovery so the callers reach their `executed = true` path\n // (each guards the empty case before any bulk write, so no empty-filter teardown can run).\n this.logDebug('No children found to cascade', { childResourceType, fkField });\n return { childResourceType, fkField, childRepositoryOptions, newChildIds: [], childSnapshotsById: new Map<string, any>() };\n }\n\n const childIds = children.map((c: any) => c._id?.toString() || c.id);\n const childSnapshotsById = new Map<string, any>();\n for (const child of children) {\n const childId = child?._id?.toString() || child?.id;\n if (childId) {\n childSnapshotsById.set(childId, child);\n }\n }\n\n // Guard 2: Circular reference detection\n // Check if any child ID was already visited in this cascade chain.\n // This prevents infinite loops when resources reference each other.\n // Note: This detects same-chain circular refs (A→B→A). Cross-branch circular refs\n // (A→B→C→A where C is reached via a different parent) are rare and would require\n // more complex graph traversal to detect fully.\n const newChildIds: string[] = [];\n for (const childId of childIds) {\n const resourceKey = `${childResourceType}:${childId}`;\n if (visitedResourceIds.has(resourceKey)) {\n this.logDebug('Circular reference detected, skipping child', {\n childResourceType,\n childId,\n resourceKey,\n note: 'This resource was already processed in this cascade chain, preventing infinite loop'\n });\n continue;\n }\n visitedResourceIds.add(resourceKey);\n newChildIds.push(childId);\n }\n\n if (newChildIds.length === 0) {\n this.logDebug('All children skipped due to circular references', { childResourceType });\n return null;\n }\n\n this.logDebug('Found children to cascade', {\n childResourceType,\n count: newChildIds.length,\n skipped: childIds.length - newChildIds.length,\n });\n\n return { childResourceType, fkField, childRepositoryOptions, newChildIds, childSnapshotsById };\n }\n\n /**\n * Delete child resources immediately (synchronous, within the same transaction) — the DELETE\n * teardown strategy of the `onParentDelete` cascade. Discovers the children through the shared\n * {@link discoverCascadeChildren}, recurses into grandchildren via the shared\n * {@link dispatchLifecycleCascadeForRelationship} (so each deeper edge gets ITS OWN strategy), runs\n * the file-cleanup contract, then removes the rows.\n *\n * Owns the DEPTH guard (discovery deliberately does not) plus circular-reference detection, to\n * prevent infinite loops on cyclic FK graphs.\n *\n * @param relationship - The relationship configuration\n * @param parentIds - IDs of parent resources being deleted\n * @param executionContext - Execution context for the operation\n * @param currentDepth - Current recursion depth (starts at 0)\n * @param maxDepth - Maximum allowed depth (from lifecycle config, default 1)\n * @param visitedResourceIds - Set of visited resource IDs to prevent circular references\n * @param options - Repository options (carries the parent's transaction, when present)\n */\n private async deleteChildrenImmediate(\n relationship: any,\n parentIds: string[],\n executionContext: ExecutionContext<any>,\n currentDepth: number = 0,\n maxDepth: number = 1,\n visitedResourceIds: Set<string> = new Set(),\n options?: RepositoryOptions\n ): Promise<boolean> {\n // Guard 1: Depth limit check\n if (currentDepth >= maxDepth) {\n this.logDebug('Max depth reached, stopping lifecycle delete', {\n currentDepth,\n maxDepth,\n childResourceType: relationship.resourceType2\n });\n // The depth budget is spent, so nothing was torn down at this edge — see the dispatcher's\n // @returns contract, which the erasure receipt reads.\n return false;\n }\n\n const childResourceType = relationship.resourceType2;\n const fkField = this.getFKFieldForRelationship(relationship);\n\n this.logDebug('Deleting children immediately', {\n childResourceType,\n fkField,\n parentIdsCount: parentIds.length,\n currentDepth,\n maxDepth\n });\n\n try {\n const discovered = await this.discoverCascadeChildren(\n relationship,\n parentIds,\n executionContext,\n ChildLifecycleStrategy.DELETE,\n visitedResourceIds,\n options,\n );\n if (!discovered) return false; // discovery declined (no service/repository) — nothing was torn down\n const { newChildIds, childSnapshotsById, childRepositoryOptions } = discovered;\n // Discovery RAN but found no dependents on this edge — a teardown that ran with nothing to do.\n // Return true (processed) per the dispatcher's @returns contract, BEFORE any capability check or\n // bulk delete, so an empty id set can never reach `deleteMany([])` (whose empty-filter semantics\n // would be catastrophic). This is the `executed = true` receipt for a healthy no-rows edge.\n if (newChildIds.length === 0) {\n return true;\n }\n // VARIANT-AGNOSTIC CASCADE: the onParentDelete teardown deletes children directly through the RAW\n // repository (below) and gates ONLY on the child declaring a DELETE / DELETE_MANY *operation*\n // (the capability checks that follow) — NOT on that operation's variant type. So a child whose\n // DELETE is `API_CALL` (an owner-facing revoke route), `INTERNAL_CALL`, or `REPOSITORY_ONLY` all\n // cascade-delete identically; the variant governs only the HTTP/service surface, never this teardown.\n // (Recorded when OAUTH_CONSENT_GRANTS added an owner-facing API_CALL DELETE and needed the USERS\n // composition cascade to still remove its grants — it does, because of exactly this.)\n const childRepository = this.repositoriesRegistry.getRepository(childResourceType);\n\n const supportsDeleteMany = childRepository.supportsOperation(CoreResourceOperation.DELETE_MANY);\n const supportsDelete = childRepository.supportsOperation(CoreResourceOperation.DELETE);\n if (!supportsDeleteMany && !supportsDelete) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Lifecycle delete requires DELETE_MANY or DELETE support on child resource \"${childResourceType}\".`,\n childResourceType,\n relationshipField: this.getNestedFieldName(relationship),\n },\n }\n );\n }\n\n // Recursively delete grandchildren before mutating the current child level.\n // This keeps deeper failures from leaving the current child rows already\n // deleted while descendants remain behind.\n // Activation must still be evaluated against each deleted child snapshot before we recurse;\n // otherwise discriminator/condition-gated lifecycle relationships would over-delete deeper\n // descendants just because the FK chain exists.\n if (currentDepth + 1 < maxDepth) {\n const childConfig = this.resourcesRegistry.tryGetResourceConfiguration(childResourceType);\n if (childConfig?.resourceRelationships) {\n const grandchildRelationships = getChildDirectionRelationships(childConfig.resourceRelationships).filter(\n (rel: any) => this.getResolvedLifecycleOnParentDelete(rel)?.enabled === true\n );\n\n for (const grandchildRel of grandchildRelationships) {\n const grandchildLifecycleConfig = this.getResolvedLifecycleOnParentDelete(grandchildRel)!;\n const grandchildMaxDepth = grandchildLifecycleConfig.maxDepth || 1;\n const activeGrandchildParentIds = newChildIds.filter(childId => {\n const childSnapshot = childSnapshotsById.get(childId);\n if (!childSnapshot) {\n return false;\n }\n\n return this.filterRelationshipsByParent([grandchildRel], childSnapshot).length > 0;\n });\n\n if (activeGrandchildParentIds.length === 0) {\n continue;\n }\n\n // Recurse through THE shared (strategy × mode) dispatcher — never straight into\n // `deleteChildrenImmediate`. The grandchild edge declares its OWN teardown strategy: a\n // grandchild on an IMPERSONALIZE_AND_RETAIN edge must be scrubbed-and-retained, not\n // hard-deleted, even though we reached it from a DELETE cascade. (Its parent — the child\n // level — IS being deleted, so the grandchild's `onParentDelete` precondition is met; only\n // the teardown differs.)\n await this.dispatchLifecycleCascadeForRelationship(\n grandchildRel,\n activeGrandchildParentIds,\n executionContext,\n currentDepth + 1,\n Math.min(maxDepth, grandchildMaxDepth + currentDepth + 1), // Respect both limits\n visitedResourceIds, // Share visited set to prevent cross-branch circular refs\n options\n );\n }\n }\n }\n\n // Keep lifecycle depth ownership in this method, but do not bypass the\n // file cleanup contract. Child resources with file fields must run through\n // the same file-delete orchestration before their repository delete lands.\n if (this.fileFieldDetection.hasFileFields(childResourceType)) {\n for (const childId of newChildIds) {\n if (this.fileMetadataRequiresSeparateCommit(childResourceType)) {\n await this.executeFileMetadataWork(\n executionContext,\n childRepositoryOptions,\n async (fileOptions) => this.fileOperationHandler.processFileFieldsForDelete(\n childResourceType,\n childId,\n executionContext,\n fileOptions\n )\n );\n } else {\n await this.fileOperationHandler.processFileFieldsForDelete(\n childResourceType,\n childId,\n executionContext,\n childRepositoryOptions\n );\n }\n }\n }\n\n // The repository call must still stay adapter-agnostic: pass the generic\n // ids array contract instead of a Mongo-specific `{ _id: { $in: ... } }`\n // filter shape.\n if (supportsDeleteMany) {\n await childRepository.deleteMany(executionContext, newChildIds, childRepositoryOptions);\n } else if (supportsDelete) {\n for (const childId of newChildIds) {\n await childRepository.delete(executionContext, childId, childRepositoryOptions);\n }\n }\n\n // RAG removal seam — ROW DELETE (lifecycle cascade). The cascade deletes children through the\n // RAW child repository (above), never through the child's own service dispatch, so the child's\n // single-delete seam cannot fire — this call is the child rows' only chunk-removal path.\n // Registered post-commit on the cascade's ambient transaction (when one exists) so an aborted\n // parent delete keeps the children's chunks intact along with the children.\n await this.runRagChunkRemovalForDeletedRows(\n childResourceType,\n newChildIds,\n 'lifecycle-cascade-delete',\n childRepositoryOptions ?? options,\n );\n\n this.logDebug('Children deleted successfully', {\n childResourceType,\n deletedCount: newChildIds.length\n });\n } catch (error) {\n this.logger.error('Failed to delete children in lifecycle operation', {\n childResourceType,\n fkField,\n currentDepth,\n ...projectCaughtErrorLogFields(error)\n });\n // Re-throw to ensure parent delete fails if child delete fails\n throw error;\n }\n\n // A teardown RAN. Discovery finding zero children counts — the edge was processed and had nothing\n // to remove, which is materially different from declining to process it. A failure never reaches\n // here (the catch above re-throws), so this cannot report success for a broken teardown.\n return true;\n }\n\n /**\n * IMPERSONALIZE_AND_RETAIN sibling of {@link deleteChildrenImmediate}: instead of hard-deleting a\n * deleted parent's children, scrub their personal fields IN PLACE and flip them to `RETAINED`, so\n * each row survives for a legal/audit retention obligation (GDPR Art. 17(3)(b)). Shares the exact\n * child-discovery + cycle guard via {@link discoverCascadeChildren}; only the teardown diverges.\n *\n * ⚠️ **Not** the anonymous-user concept — impersonalization scrubs personal data OUT of a KEPT row;\n * it is the opposite direction from anonymous-session ownership transposition. Never conflate them.\n *\n * **v1 scope — DIRECT children only, NO recursion.** The parent-delete cascade impersonalizes the\n * immediate children the deleted parent owned; a retained (kept) child still has a valid parent for\n * ITS OWN children, so nothing is orphaned and no grandchild descent is required here. The\n * whole-subtree scrub (a subject-erasure walking every descendant — architecture doc D8) is the\n * separate direct-subject-erasure orchestrator's job (v1.5), NOT this parent-delete cascade.\n *\n * Files ARE handled, but by TREATMENT rather than wholesale (gate G-FILE): a file field the author\n * marked `.impersonalizeWith()` has its file deleted, because a field-scrub cannot reach inside a\n * blob; a KEEP/untreated file field survives with the retained row. \"Keep the record\" must not\n * silently become \"keep the personal data\".\n *\n * The scrub write goes through {@link SystemAccessBackendService.updateManyAsSystem} — the same\n * fail-closed trusted-write primitive the resource factory documents as the impersonalize writer. It\n * synthesises a super-admin system context, re-attaches the DTO-stripped `retentionStatus` /\n * `impersonalizedAt` markers (both `.excludeFromUpdate()`) past the strict parse, and best-effort\n * audits the privileged write. The parent-delete transaction rides through `childRepositoryOptions`\n * (already adapter-validated by discovery), keeping the scrub atomic with the parent delete.\n */\n /**\n * THE impersonalize-and-retain WRITE — scrub the given rows in place and mark them `RETAINED`.\n *\n * Cascade-agnostic on purpose: it takes explicit row ids and knows nothing about relationships,\n * discovery or depth. That is what lets the parent-delete cascade AND the direct subject-erasure\n * entry point (`impersonalizeSubjectAsSystem`) share ONE definition of what \"impersonalize these\n * rows\" means. Splitting them would let the two drift on the exact thing that must not drift: what\n * counts as erased.\n *\n * Order of operations, each load-bearing:\n * 1. **Retention-governance assert** — the `retentionStatus` / `impersonalizedAt` markers and the\n * `updateMany` / `seeRetained` grants are factory-injected ONLY for a retention-governed\n * resource. Without them there is nowhere to record the flip and no grant to write with.\n * 2. **Trusted-writer assert** — refuse rather than silently skip the scrub when SystemAccessService\n * is unbound (skipping would leave personal data behind after an erasure).\n * 3. **Scrub + markers in ONE write**, preserving every scrub key past the strict update DTO (some\n * field classes — templatable file fields — are omitted from the DTO and in no derived preserve\n * set; their value would otherwise be dropped while the row still flipped to RETAINED).\n * 4. **File erasure AFTER the write**, by treatment, so a failed/rolled-back scrub never destroys\n * files for rows that were not actually retained. FILES is always MongoDB-backed, so HOW the\n * erasure is sequenced depends on the ambient transaction's adapter — see\n * {@link eraseImpersonalizedRowFiles} for the cross-adapter split-brain this closes.\n */\n /**\n * The `USERS` ids whose sessions a scrub of these rows must end, per the resource's AUTHORED\n * `dataSubjectPolicy`.\n *\n * The linkage is never inferred from the shape of a foreign key. On almost every resource a user FK\n * names the OWNER or the ACTOR — `TODOS` carries `createdByUserId`, `assignedToUserId` and\n * `escalationContactUserId` — so inferring one would revoke the sessions of authors and assignees\n * instead of the data subject. Only an explicit declaration is honoured:\n * - `SELF_PRINCIPAL` — the row IS the person; its own id is the user id (no read needed).\n * - `LINKED_PRINCIPAL` — the declared `sessionPrincipalField` holds the user id.\n * - `NO_PRINCIPAL` / undeclared — no principal; nothing is revoked.\n *\n * Best-effort: a lookup failure must never abort a scrub the data subject is entitled to. It is\n * reported as a FAILURE rather than as \"no principals\", because an unresolved principal means the\n * person may still hold a live session and the two must not look alike.\n */\n private async resolveScrubSessionPrincipals(\n resourceType: ResourceType,\n rowIds: string[],\n resourceConfiguration: { dataSubjectPolicy?: ResourceDataSubjectPolicy },\n systemAccess: SystemAccessBackendService,\n options?: RepositoryOptions,\n errorContext?: Record<string, unknown>,\n ): Promise<{ userIds: string[]; lookupFailed: boolean }> {\n const policy = resourceConfiguration.dataSubjectPolicy;\n if (!policy || policy.kind === ResourceDataSubjectKind.NO_PRINCIPAL) {\n return { userIds: [], lookupFailed: false };\n }\n if (policy.kind === ResourceDataSubjectKind.SELF_PRINCIPAL) {\n return { userIds: [...new Set(rowIds)], lookupFailed: false };\n }\n const principalField = policy.sessionPrincipalField;\n if (!principalField) {\n return { userIds: [], lookupFailed: false };\n }\n try {\n const resolved = new Set<string>();\n // Chunked by id AND paged to completion: an unpaginated list silently caps at the DEFAULT limit\n // of 20, and an explicit limit is still bounded by whatever ceiling the resource's LIST\n // operation declares. Either would drop principals with nothing saying so.\n const CHUNK = 100;\n for (let offset = 0; offset < rowIds.length; offset += CHUNK) {\n const chunk = rowIds.slice(offset, offset + CHUNK);\n for (let page = 1; ; page++) {\n const result = await systemAccess.listAsSystem<Record<string, unknown>>(\n resourceType,\n { _id: { $in: chunk } },\n { page, limit: chunk.length },\n options,\n );\n const rows = Array.isArray(result) ? result : result.data;\n for (const row of rows) {\n const value = row[principalField];\n if (typeof value === 'string' && value.length > 0) {\n resolved.add(value);\n }\n }\n if (Array.isArray(result)) break;\n const { limit, total } = result.pagination;\n if (rows.length === 0 || page * limit >= total) break;\n }\n }\n return { userIds: [...resolved], lookupFailed: false };\n } catch (error) {\n this.logger.warn(\n 'Could not resolve the scrubbed subject\\'s session principals; sessions may survive the erasure',\n { resourceType, principalField, rowCount: rowIds.length, ...(errorContext ?? {}), ...projectCaughtErrorLogFields(error) },\n );\n return { userIds: [], lookupFailed: true };\n }\n }\n\n /**\n * Schedule the session revocation for after the transaction commits.\n *\n * Fire-and-forget by design: the rows are already scrubbed and durable, so throwing here would\n * invite a retry of an erasure whose local half succeeded. A failure is logged at ERROR — loudly,\n * because it means an erased person may still be browsing on a live token.\n */\n private scheduleScrubSessionRevocation(\n resourceType: ResourceType,\n principals: { userIds: string[]; lookupFailed: boolean },\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n errorContext?: Record<string, unknown>,\n ): void {\n if (principals.lookupFailed) {\n this.logger.error(\n 'A scrubbed subject\\'s session principals could not be resolved, so NO session was revoked',\n { resourceType, ...(errorContext ?? {}) },\n );\n return;\n }\n if (principals.userIds.length === 0) {\n return;\n }\n const revocation = this.servicesRegistry.getSubjectSessionRevocationService?.();\n if (!revocation?.isRegistered) {\n this.logger.error(\n 'No session revoker is registered, so a scrubbed subject\\'s sessions were NOT revoked',\n { resourceType, principalCount: principals.userIds.length, ...(errorContext ?? {}) },\n );\n return;\n }\n\n const ambientTransaction = options?.transaction;\n const revokeAll = async (): Promise<void> => {\n for (const userId of principals.userIds) {\n try {\n await revocation.revokeAllSessionsForUser(userId);\n } catch (error) {\n this.logger.error(\n 'Failed to revoke a scrubbed subject\\'s sessions; they may remain live until their tokens expire',\n { resourceType, userId, ...(errorContext ?? {}), ...projectCaughtErrorLogFields(error) },\n );\n }\n }\n };\n\n // Outside a transaction (a direct impersonalize with no ambient one) the write is already durable,\n // so there is nothing to wait for.\n if (!ambientTransaction) {\n void revokeAll();\n return;\n }\n registerTransactionPostCommitEffect(ambientTransaction, {\n key: ['subject-session-revocation', String(resourceType), ...principals.userIds].join(':'),\n execute: revokeAll,\n });\n }\n\n public async impersonalizeRowsInPlace(\n resourceType: ResourceType,\n rowIds: string[],\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n /** Extra diagnostic context for the cascade caller (relationship provenance). */\n errorContext?: Record<string, unknown>,\n ): Promise<{ principalUserIds: string[]; lookupFailed: boolean }> {\n if (rowIds.length === 0) {\n return { principalUserIds: [], lookupFailed: false };\n }\n\n const resourceConfiguration = this.resourcesRegistry.getResourceConfiguration(resourceType);\n if (!resourceConfiguration.retentionPolicy) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Impersonalize-and-retain requires resource \"${resourceType}\" to opt into retentionPolicy ` +\n `(the retentionStatus marker + updateMany grant are factory-injected only for ` +\n `retention-governed resources).`,\n resourceType,\n ...(errorContext ?? {}),\n },\n }\n );\n }\n\n const systemAccess = this.servicesRegistry.getSystemAccessService?.();\n if (!systemAccess) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message:\n `Impersonalize-and-retain requires SystemAccessService (the trusted updateManyAsSystem scrub ` +\n `writer), but it is not bound in this container.`,\n resourceType,\n ...(errorContext ?? {}),\n },\n }\n );\n }\n\n // The marker written here is the WRITE side of the hide rule — the value this patch stamps is, by\n // definition, the value every read/write/aggregate path excludes. It therefore comes from the same\n // retention authority the hide predicate negates, so the two can never name different statuses (or\n // different field spellings) after a rename.\n // ── SESSION principals, resolved BEFORE the scrub ────────────────────────────────────────────\n //\n // Every path that scrubs a person's row funnels through this method — the erasure subject, a\n // direct `impersonalizeSubjectAsSystem`, and a parent-delete cascade impersonalizing a child — so\n // resolving here is what makes \"an erased person's session ends\" hold by construction rather than\n // being re-applied at each entry point (and missed at two of them, which is what #32 recorded).\n //\n // BEFORE the write, because afterwards the row is RETAINED and hidden from every ordinary read,\n // and the only see-through door demands a privileged HUMAN plus a written justification.\n const sessionPrincipals = await this.resolveScrubSessionPrincipals(\n resourceType,\n rowIds,\n resourceConfiguration,\n systemAccess,\n options,\n errorContext,\n );\n\n const scrubPatch = buildImpersonalizeScrubPatch(resourceConfiguration.mainSchema);\n const data: Record<string, unknown> = {\n ...scrubPatch,\n ...buildRetentionMarkerStampPatch(),\n impersonalizedAt: new Date(),\n };\n\n await systemAccess.updateManyAsSystem(\n resourceType,\n rowIds,\n data,\n { ...options, preserveServerInjectedFields: Object.keys(data) },\n );\n\n // POST-COMMIT, for the same reason the file erasure below defers: the local scrub must be durable\n // before a session is ended, or a rolled-back erasure would leave a real user logged out of an\n // account that still exists. The reverse order is the worse failure.\n this.scheduleScrubSessionRevocation(resourceType, sessionPrincipals, executionContext, options, errorContext);\n\n // RAG removal seam — FIELD IMPERSONALIZATION. Every path that scrubs a person's row funnels\n // through this method (the #32 chokepoint argument), so hooking here is what makes\n // \"RAG_SOURCE + IMPERSONALIZE_WITH ⇒ chunks deleted in the same decision\" hold for the erasure\n // subject, a direct impersonalize, AND the parent-delete cascade at once. The scrubbed field set\n // comes from the WRITER (`buildImpersonalizeScrubPatch`) — the same derive-from-the-writer rule\n // the zero-scrub guard follows — and the intersection with declared RAG-source fields happens in\n // the shared util. Post-commit on the ambient transaction: a rolled-back scrub keeps its chunks.\n await this.runRagChunkRemovalForFields(\n resourceType,\n rowIds,\n Object.keys(scrubPatch),\n 'impersonalize-scrub',\n options,\n );\n\n // A field-level scrub cannot reach INSIDE a stored blob, so a file field marked personal is only\n // erased by deleting the file. Files on KEEP/untreated fields survive — that is how a\n // legally-required artifact stays with its retained record.\n if (this.fileFieldDetection.hasFileFields(resourceType)) {\n await this.eraseImpersonalizedRowFiles(\n resourceType,\n rowIds,\n Object.keys(scrubPatch),\n executionContext,\n options,\n );\n }\n\n // Returned so the erasure receipt can evidence it. The cascade and the direct-impersonalize\n // callers have no report and ignore this.\n return { principalUserIds: sessionPrincipals.userIds, lookupFailed: sessionPrincipals.lookupFailed };\n }\n\n /**\n * Erase the personal files of rows that were just impersonalized-and-retained, sequenced so a\n * rolled-back scrub can NEVER destroy files for rows that stayed live.\n *\n * FILES is always MongoDB-backed, while the impersonalized resource may not be — and that asymmetry\n * is the whole problem this method exists to solve. Three cases, each load-bearing:\n *\n * 1. **No ambient transaction** — the scrub write already committed on its own, so there is nothing\n * left to roll back. Erase inline.\n * 2. **Ambient MongoDB transaction** — FILES joins the SAME native session, so the file deletions\n * are part of the scrub's atomic unit: a rollback un-deletes them. Erase inline.\n * 3. **Ambient NON-Mongo transaction (today: PostgreSQL)** — the file work CANNOT join it.\n * `executeFileMetadataWork` would open an INDEPENDENT MongoDB transaction that commits\n * immediately, so a later rollback of the PostgreSQL parent would leave a LIVE, un-scrubbed row\n * whose files are already marked DELETED — and hard-deleted by the cleanup batch ~30 days later.\n * Silent, unrecoverable data destruction on a row that was never erased. So the erasure is\n * DEFERRED to a post-commit effect on the parent transaction: it runs only if the parent really\n * commits, and simply never runs if it aborts (an aborted attempt's queue is unreachable).\n *\n * The FILES-is-Mongo assertion is made EAGERLY in case 3, before deferral: a misconfiguration must\n * fail the transaction, not surface after it has already committed.\n *\n * ⚠️ **Limitation of case 3, by construction.** A post-commit effect runs after an irreversible\n * commit, so its failure is REPORTED, never thrown (see `drainTransactionPostCommitEffects`) — a\n * failed deferred erasure leaves the row retained with its personal files still present. That is\n * strictly better than the split-brain it replaces (which destroyed files for LIVE rows), but it is\n * an at-least-once obligation, not an atomic one: the effect logs at ERROR with the row identity so\n * the failure is actionable, and a durable retry belongs to the retention-clock disposal job rather\n * than to this write path. Cases 1 and 2 carry no such caveat.\n */\n private async eraseImpersonalizedRowFiles(\n resourceType: ResourceType,\n rowIds: string[],\n scrubbedFieldNames: string[],\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<void> {\n const ambientTransaction = options?.transaction;\n const isCrossAdapterTransaction = !!ambientTransaction\n && ambientTransaction.databaseType !== this.getFileMetadataAdapter();\n\n if (!isCrossAdapterTransaction) {\n for (const rowId of rowIds) {\n await this.fileOperationHandler.processFileFieldsForImpersonalize(\n resourceType,\n rowId,\n scrubbedFieldNames,\n executionContext,\n options,\n );\n }\n return;\n }\n\n // The parent transaction is about to be handed the erasure; strip it from the options the\n // deferred work will use. It is committed by the time the effect runs, so carrying it would be\n // meaningless at best and would re-enter a dead native session at worst. Every other option\n // (version fences, seed depth) is preserved.\n const { transaction: _committedParentTransaction, ...postCommitOptions } = options ?? {};\n\n for (const rowId of rowIds) {\n registerTransactionPostCommitEffect(ambientTransaction, {\n key: ['retention-impersonalize-file-erasure', String(resourceType), rowId].join(':'),\n execute: async () => {\n try {\n await this.executeFileMetadataWork(\n executionContext,\n postCommitOptions as RepositoryOptions,\n async (fileOptions) => this.fileOperationHandler.processFileFieldsForImpersonalize(\n resourceType,\n rowId,\n scrubbedFieldNames,\n executionContext,\n fileOptions,\n )\n );\n } catch (error) {\n // The parent commit is irreversible and the drain never rethrows, so an unlogged failure\n // here would be an invisible compliance gap: a row wearing an \"erased\" label whose\n // personal files are still readable.\n this.logger.error('Deferred impersonalize file erasure FAILED after parent commit', {\n resourceType,\n rowId,\n scrubbedFieldNames,\n parentTransactionId: ambientTransaction.id,\n parentDatabaseType: ambientTransaction.databaseType,\n ...projectCaughtErrorLogFields(error),\n });\n throw error;\n }\n },\n });\n }\n }\n\n /**\n * ROW-DELETE half of the RAG chunk-removal invariant: once these rows' deletion is durable, every\n * chunk derived from them is removed. Called from the single-delete path, both bulk-delete paths,\n * the cascade teardown, and (via the shared batch context) the retention sweep — the full seam\n * inventory and the shared failure/transaction contract live in\n * `~wildo-backend-lib/rag/utils/rag-chunk-removal.backend.utils`.\n *\n * A missing removal context (minimal container) is a silent no-op BY DESIGN — see\n * {@link ServicesRegistryHandlerBackendService.getRagChunkRemovalContext}.\n */\n private async runRagChunkRemovalForDeletedRows(\n resourceType: ResourceType,\n resourceIds: string[],\n seam: string,\n options?: RepositoryOptions,\n ): Promise<void> {\n const removalContext = this.servicesRegistry.getRagChunkRemovalContext?.();\n if (!removalContext) return;\n await scheduleRagChunkRemovalForDeletedRows(removalContext, {\n resourceType,\n resourceIds,\n seam,\n transaction: options?.transaction,\n });\n }\n\n /**\n * The deleted row ids of a bulk-delete result, for the RAG removal seam. Mirrors the id extraction\n * `executeLifecycleOperations` performs for the cascade (string entries, row objects, or a\n * `deletedIds` envelope), falling back to the pre-delete snapshots when the repository result\n * carries no ids at all.\n */\n private collectDeletedRowIdsForRagRemoval(result: any, currentStates?: any[]): string[] {\n if (Array.isArray(result)) {\n // An EMPTY array is an answer (\"nothing was deleted\"), not a gap — no fallback, or a raced\n // bulk delete would remove chunks for rows that are still live.\n return result\n .map((item: any) => (typeof item === 'string' ? item : this.getResourceIdValue(item)))\n .filter((id: string | undefined): id is string => Boolean(id));\n }\n if (Array.isArray(result?.deletedIds)) {\n return result.deletedIds.filter(Boolean);\n }\n // A result shape carrying no ids at all: fall back to the pre-delete snapshots. Over-deletion is\n // the safe direction for a DERIVED tier — a chunk removed for a surviving row costs a re-index;\n // a chunk kept for a deleted row is the privacy gap this seam exists to close.\n return (currentStates ?? [])\n .map((row) => this.getResourceIdValue(row))\n .filter((id): id is string => Boolean(id));\n }\n\n /**\n * FIELD-LEVEL half of the RAG chunk-removal invariant: a field whose value was destroyed\n * (impersonalize scrub) loses its chunk set in the same decision. The intersection with the\n * resource's declared RAG-source fields happens inside the shared util, so an unrelated scrub\n * removes nothing.\n */\n private async runRagChunkRemovalForFields(\n resourceType: ResourceType,\n resourceIds: string[],\n affectedFieldNames: string[],\n seam: string,\n options?: RepositoryOptions,\n ): Promise<void> {\n const removalContext = this.servicesRegistry.getRagChunkRemovalContext?.();\n if (!removalContext) return;\n await scheduleRagChunkRemovalForFields(removalContext, {\n resourceType,\n resourceIds,\n affectedFieldNames,\n seam,\n transaction: options?.transaction,\n });\n }\n\n /**\n * WRITE half of the RAG derived-data invariant: a committed service-tier write that touched a\n * `.ragSource()` field re-derives that field's chunk set (delete-then-replace inside the store —\n * the DL1 ledger upsert). Called from ONE place, `executeFrameworkManagedPostCommitEffects`,\n * which every write door's dispatch reaches post-commit; the decision logic (write-verb filter,\n * changed-field intersection, retained-row exclusion) lives in\n * `~wildo-backend-lib/rag/utils/rag-ingestion-trigger.backend.utils`.\n *\n * DETACHED FROM THE REQUEST on purpose (`setImmediate`, the guidance/milestone/lifecycle\n * evaluator discipline in the same chokepoint): a FILE_EXTRACTION field's ingestion downloads and\n * parses the file, and a user write must neither wait on nor fail from corpus derivation — the\n * ledger + hourly sweep bound anything a crashed process drops here. Occurrence-keyed post-commit\n * dedup is inherited from the chokepoint itself: the `resource-post-commit` registration key\n * already carries `frameworkPostCommitEffectOccurrenceId`, so this hook runs at most once per\n * service-operation occurrence with no second dedup layer.\n */\n private runRagChunkIngestionForWrite(\n resolvedOperation: ResourceConfiguration_Operation<any, any, any>,\n operationPath: ResourceConfiguration_OperationPath<any, any>,\n executionContext: ExecutionContext<any>,\n inputData: unknown,\n committedState: unknown,\n ): void {\n const ingestionContext = this.servicesRegistry.getRagIngestionContext?.();\n if (!ingestionContext) return;\n\n // A custom operation's effective verb is the core operation it borrows (`resourceOperationLike`);\n // a core operation's identifier IS its verb. Non-write verbs (read/list/delete/…) return here,\n // so no timer is queued for the overwhelmingly common non-ingesting dispatches.\n //\n // `resourceOperationLike` is OPTIONAL, so the fallback below can land on a custom operation's own\n // identifier string, which is in no core-verb set — the operation then participates in nothing.\n // That gap is REPORTED rather than guessed at (inferring the verb from `httpVerb` would hand\n // `ingestRow` a payload that is not a row, and a missing field reads as a corpus that went away,\n // i.e. a DELETE of live chunks); see `isUndeclaredCustomOperationIdentifier`.\n const declaredOperationLike = (resolvedOperation as unknown as { resourceOperationLike?: CoreResourceOperation }).resourceOperationLike;\n const operationIdentifier = String(operationPath.operationIdentifier);\n const operationLike = declaredOperationLike ?? (operationIdentifier as CoreResourceOperation);\n if (!RAG_INGESTION_WRITE_OPERATIONS.has(operationLike)) {\n if (isUndeclaredCustomOperationIdentifier(declaredOperationLike, operationIdentifier)) {\n reportRagIngestionSkippedUndeclaredCustomOperation(ingestionContext, {\n resourceType: operationPath.resourceIdentifier as ResourceType,\n operationIdentifier,\n });\n }\n return;\n }\n\n setImmediate(() => {\n runRagIngestionForServiceWrite(ingestionContext, {\n resourceType: operationPath.resourceIdentifier as ResourceType,\n operationLike,\n inputData,\n committedState,\n executionContext,\n seam: 'service-write',\n }).catch((err: unknown) => {\n // `runRagIngestionForServiceWrite` owns its failure contract (log-never-throw); this catch\n // only guards the detachment itself so a contract regression cannot become an unhandled\n // rejection in the request-less microtask.\n this.logDebug('RAG ingestion trigger rejected outside its failure contract', {\n error: describeCaughtError(err),\n });\n });\n });\n }\n\n private async impersonalizeChildrenImmediate(\n relationship: any,\n parentIds: string[],\n executionContext: ExecutionContext<any>,\n currentDepth: number = 0,\n maxDepth: number = 1,\n visitedResourceIds: Set<string> = new Set(),\n options?: RepositoryOptions\n ): Promise<boolean> {\n // Guard 1: Depth limit check. v1 impersonalize never recurses, so currentDepth is always 0 here;\n // the guard is kept for signature-parity with deleteChildrenImmediate + defence-in-depth.\n if (currentDepth >= maxDepth) {\n this.logDebug('Max depth reached, stopping lifecycle impersonalize', {\n currentDepth,\n maxDepth,\n childResourceType: relationship.resourceType2\n });\n // Nothing scrubbed at this edge. Reported as such rather than as a completed teardown — for an\n // erasure this is the difference between a truthful receipt and one that overstates it.\n return false;\n }\n\n const childResourceType = relationship.resourceType2;\n const fkField = this.getFKFieldForRelationship(relationship);\n\n this.logDebug('Impersonalizing children immediately (retain-and-scrub)', {\n childResourceType,\n fkField,\n parentIdsCount: parentIds.length,\n currentDepth,\n maxDepth\n });\n\n try {\n const discovered = await this.discoverCascadeChildren(\n relationship,\n parentIds,\n executionContext,\n ChildLifecycleStrategy.IMPERSONALIZE_AND_RETAIN,\n visitedResourceIds,\n options,\n );\n if (!discovered) return false; // discovery declined (no service/repository) — nothing was torn down\n const { newChildIds, childRepositoryOptions } = discovered;\n // Discovery RAN but found no dependents — a scrub that ran with nothing to do. Return true\n // (processed) BEFORE calling impersonalizeRowsInPlace, so an empty id set can never widen into an\n // all-rows scrub. This is the `executed = true` receipt for a healthy no-rows edge.\n if (newChildIds.length === 0) {\n return true;\n }\n\n // The post-discovery half is the SHARED core, so the cascade and the direct subject-erasure\n // entry point cannot drift on what \"impersonalize these rows\" means.\n await this.impersonalizeRowsInPlace(\n childResourceType,\n newChildIds,\n executionContext,\n childRepositoryOptions,\n // Cascade provenance: the generic core reports `resourceType`, but a cascade failure is more\n // diagnosable when it also names the row as a CHILD and points at the edge that reached it.\n { childResourceType, relationshipField: this.getNestedFieldName(relationship), fkField },\n );\n\n this.logDebug('Children impersonalized-and-retained successfully', {\n childResourceType,\n retainedCount: newChildIds.length\n });\n } catch (error) {\n this.logger.error('Failed to impersonalize children in lifecycle operation', {\n childResourceType,\n fkField,\n currentDepth,\n ...projectCaughtErrorLogFields(error)\n });\n // Re-throw to ensure the parent delete fails if the child scrub fails (transactional integrity).\n throw error;\n }\n\n // A scrub RAN (zero children included — the edge was processed). See the dispatcher's @returns.\n return true;\n }\n\n /**\n * THE v1 SUBJECT-ERASURE ORCHESTRATOR — what a \"delete my account\" request executes.\n *\n * An erasure is NOT a delete. The subject row SURVIVES: it is scrubbed and flipped to `RETAINED`,\n * so foreign keys from legally-retained financial rows keep resolving to an anonymized person\n * instead of dangling. What actually disappears is everything the subject owned that carries no\n * retention obligation — the profile with the name, the bio and the avatar file.\n *\n * ## Why an orchestrator is needed at all (the non-obvious part)\n *\n * The dependents are NOT torn down automatically. The `USERS → USER_PROFILES` cascade is\n * DELETE-driven — it fires from the parent's delete post-op logic — and an erasure never deletes\n * the subject. So without this method, `impersonalizeSubjectAsSystem` would scrub the user row and\n * leave the profile (the row that actually holds the personal data) fully intact, which is the\n * precise opposite of what the request asked for. This method fires each dependent's declared\n * teardown explicitly.\n *\n * ## Two halves, in this order\n *\n * 1. **Dependents** — every child-direction edge is classified\n * ({@link classifySubjectErasureDisposition}) and the ones that opted into a teardown are\n * dispatched through {@link dispatchLifecycleCascadeForRelationship} — THE shared\n * (strategy × mode) cascade dispatcher. No teardown logic is written here: the erasure reuses\n * the exact code path a parent delete would have taken, so the two triggers cannot drift on\n * what a `DELETE` or an `IMPERSONALIZE_AND_RETAIN` edge means.\n * 2. **The subject** — {@link impersonalizeRowsInPlace}, the shared scrub core (retention assert,\n * trusted-writer assert, scrub patch + markers in one write, treatment-driven file erasure).\n *\n * **Dependents first, deliberately.** If a teardown fails, the subject is left NOT yet marked\n * erased — which is both the safer intermediate state (nothing wears an \"erased\" label while its\n * personal data is still live) and the retryable one (a re-run re-discovers zero remaining\n * dependents and completes). The reverse order would freeze the subject as `RETAINED` — hidden and\n * immutable — while its dependents still held the personal data, and the retry could no longer\n * re-scrub the frozen row.\n *\n * ## Fail loud, BEFORE the first write\n *\n * Every edge is classified up front and the whole erasure is refused if ANY edge is\n * `UNCLASSIFIED` (an owned dependent nobody declared a teardown for) or `UNSUPPORTED_DEFERRED`\n * (a `mode: LAZY` edge that would defer personal-data removal to a queue). Classifying up front\n * rather than per-edge-as-we-go is what makes the refusal safe: an erasure that discovers an\n * unclassified edge halfway through would already have deleted rows, leaving a half-erased\n * subject no retry can reason about.\n *\n * ## Atomicity, and its exact limit\n *\n * The whole erasure runs inside ONE transaction on the SUBJECT's persistence adapter\n * ({@link executeResourceTransaction}, reusing an ambient transaction when the caller already\n * owns one). Dependents on a DIFFERENT adapter throw `CONFIGURATION` from the shared discovery\n * rather than silently committing outside that boundary — the same limit the parent-delete cascade\n * has always had.\n *\n * ⚠️ The one gap this inherits (it lives in the shared scrub core, not here): for a\n * PostgreSQL-backed resource, FILE metadata work runs against Mongo and therefore cannot join the\n * subject's SQL transaction. File erasure is deferred to the post-commit boundary there, so a\n * rolled-back erasure never destroys files, but a file erasure that fails AFTER commit is logged\n * rather than rolled back.\n *\n * ## v1 limitation — condition-gated edges are not activation-filtered\n *\n * A parent DELETE narrows its cascade with `filterRelationshipsByParent`, so an edge that is only\n * active for a particular parent VARIANT (a discriminated or condition-gated relationship) does not\n * fire for a parent it does not apply to. That filter needs the parent ROW, and an erasure takes\n * explicit ids rather than rows — deliberately, since resolving them would add a system READ grant\n * to the erasure's fail-closed surface. So v1 dispatches every enabled edge and lets FK discovery\n * find nothing on the inapplicable ones, which matches what the delete cascade itself does when no\n * snapshot is available. Harmless for a subject whose edges are unconditional (every `USERS` edge\n * is); a genuinely condition-gated subject wants the snapshot-based filter added here first.\n *\n * @param subjectResourceType - the erasure subject's resource type. MUST be the resource this\n * service instance is bound to (asserted) — the transaction is opened on ITS adapter, and the\n * child edges are read from ITS configuration.\n * @param subjectIds - the explicit subject rows to erase. An erasure is not a query.\n * @param executionContext - the privileged context the erasure runs under (synthesised by\n * {@link SystemAccessBackendService.eraseSubjectAsSystem}).\n * @param options - repository options; carries an ambient transaction when the caller owns one.\n * @returns the per-edge {@link SubjectErasureReport} — the compliance artifact of the request.\n */\n public async eraseSubjectInPlace(\n subjectResourceType: ResourceType,\n subjectIds: string[],\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<SubjectErasureReport> {\n // The transaction is opened on THIS service's adapter and the edges come from THIS service's\n // configuration, so a mismatched resourceType would silently erase against the wrong graph.\n if (subjectResourceType !== this.resourceConfiguration.resourceIdentifier) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message:\n `Subject erasure must run on the subject's own service instance: asked to erase ` +\n `\"${subjectResourceType}\" on the service bound to ` +\n `\"${this.resourceConfiguration.resourceIdentifier}\".`,\n subjectResourceType,\n boundResourceType: this.resourceConfiguration.resourceIdentifier,\n },\n }\n );\n }\n\n if (subjectIds.length === 0) {\n return {\n subjectResourceType,\n subjectIds: [],\n edges: [],\n subjectImpersonalized: false,\n externalEffects: [],\n };\n }\n\n // Fail-closed BEFORE any teardown: a subject that cannot be retained cannot be erased (there is\n // no retentionStatus marker to flip and no derived grant to flip it with). The shared core\n // asserts this too, but it runs LAST — checking here is what stops an erasure from deleting the\n // dependents and only then discovering it cannot retain the subject.\n if (!this.resourceConfiguration.retentionPolicy) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Subject erasure requires resource \"${subjectResourceType}\" to opt into ` +\n `retentionPolicy: the subject row is RETAINED (scrubbed and kept) rather than ` +\n `deleted, so that foreign keys from retained records still resolve to an anonymized ` +\n `subject. Without it there is no retentionStatus marker to flip.`,\n subjectResourceType,\n },\n }\n );\n }\n\n const childRelationships = getChildDirectionRelationships(\n this.resourceConfiguration.resourceRelationships,\n );\n\n // Classify EVERY edge before touching anything — see \"Fail loud, BEFORE the first write\".\n const classifications = childRelationships.map((relationship) => ({\n relationship,\n classification: classifySubjectErasureDisposition(relationship),\n }));\n\n const blocking = classifications\n .filter(({ classification }) => isBlockingSubjectErasureDisposition(classification.disposition));\n\n if (blocking.length > 0) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Subject erasure of \"${subjectResourceType}\" is REFUSED: ${blocking.length} of its ` +\n `dependent relationship(s) have no executable erasure disposition. Refusing rather ` +\n `than guessing — deleting could destroy data a retention obligation required ` +\n `keeping, and skipping could leave personal data behind while reporting the subject ` +\n `erased.`,\n subjectResourceType,\n unresolvedEdges: blocking.map(({ relationship, classification }) => ({\n childResourceType: classification.childResourceType,\n relationshipField: this.getNestedFieldName(relationship),\n disposition: classification.disposition,\n reason: classification.reason,\n })),\n },\n }\n );\n }\n\n this.logDebug('Executing subject erasure', {\n subjectResourceType,\n subjectCount: subjectIds.length,\n edgeCount: classifications.length,\n });\n\n return this.executeResourceTransaction(\n executionContext,\n async (optionsWithTransaction) => {\n const edges: SubjectErasureEdgeOutcome[] = [];\n\n for (const { relationship, classification } of classifications) {\n // EXHAUSTIVE on purpose, rather than an `is it one of the two executing members` test: a\n // future disposition added without an arm here becomes a TYPE error instead of an edge\n // that silently reports `executed: false` and leaves personal data behind.\n let executed = false;\n\n switch (classification.disposition) {\n case SubjectErasureDisposition.DELETE:\n case SubjectErasureDisposition.IMPERSONALIZE_AND_RETAIN: {\n // Route through THE shared (strategy × mode) dispatcher — the same one a parent delete\n // uses — so each edge gets its own declared teardown at its own declared depth, and a\n // future teardown strategy is honoured here for free.\n const lifecycleConfig = this.getResolvedLifecycleOnParentDelete(relationship)!;\n /**\n * Taken FROM the dispatcher, never assumed.\n *\n * This was `executed = true` unconditionally, which made the receipt claim a teardown for\n * an edge the cascade had declined — a child with no registered service or repository is\n * skipped, and skipping returns normally. `SubjectErasureReport` is the evidence that\n * answers \"was this subject's data removed?\", so an overstatement here is a compliance\n * defect, not a logging inaccuracy.\n */\n executed = await this.dispatchLifecycleCascadeForRelationship(\n relationship,\n subjectIds,\n executionContext,\n 0, // currentDepth — top of the cascade\n lifecycleConfig.maxDepth || 1,\n new Set(), // per-edge visited set, matching executeLifecycleOperations\n optionsWithTransaction,\n );\n if (!executed) {\n // LOUD: the disposition says this edge should have been torn down and it was not, so\n // the subject's data is partly still live. The skip itself is warned deeper down with\n // the missing registration named; this says what it MEANS for the erasure.\n this.logger.error('Subject erasure did NOT tear down a declared edge', {\n subjectResourceType,\n childResourceType: classification.childResourceType,\n disposition: classification.disposition,\n reason: 'the cascade declined the edge — see the preceding warning for the missing registration',\n });\n }\n break;\n }\n\n case SubjectErasureDisposition.RETAINED_BY_DECLARATION:\n case SubjectErasureDisposition.NOT_OWNED:\n // Deliberately untouched — the rows are not discovered at all, so the erasure cannot\n // accidentally act on them.\n break;\n\n case SubjectErasureDisposition.UNCLASSIFIED:\n case SubjectErasureDisposition.UNSUPPORTED_DEFERRED:\n default: {\n // Unreachable: the pre-flight refusal rejects every blocking disposition before the\n // transaction opens. Kept as defence-in-depth so a future edit that weakens that\n // pre-flight fails loudly here instead of silently skipping an edge — and so the\n // `never` binding makes an unhandled new member a compile error.\n const unexecutableDisposition: never = classification.disposition as never;\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message:\n `Subject erasure reached the teardown loop with a non-executable disposition ` +\n `'${String(unexecutableDisposition)}' — the pre-flight classification refusal ` +\n `should have rejected it. Refusing to continue (fail-closed).`,\n subjectResourceType,\n childResourceType: classification.childResourceType,\n relationshipField: this.getNestedFieldName(relationship),\n },\n }\n );\n }\n }\n\n edges.push({ ...classification, executed });\n }\n\n // The subject LAST: dependents are gone (or retained by declaration), so flipping the\n // subject to RETAINED now is the final, irreversible step of the erasure.\n const subjectSessionRevocation = await this.impersonalizeRowsInPlace(\n subjectResourceType,\n subjectIds,\n executionContext,\n optionsWithTransaction,\n { erasureSubject: true },\n );\n\n const report: SubjectErasureReport = {\n subjectResourceType,\n subjectIds,\n edges,\n subjectImpersonalized: true,\n // Whose sessions this erasure ended — a LOCAL fence write applied at the scrub chokepoint,\n // so it is evidenced here rather than among the external effects.\n sessionRevocation: {\n principalUserIds: subjectSessionRevocation.principalUserIds,\n lookupFailed: subjectSessionRevocation.lookupFailed,\n },\n // Populated by the caller AFTER this transaction commits — external effects cannot join a\n // database transaction, so running them here would either hold the transaction open across\n // a third-party network call or let a rollback undo local rows whose provider-side\n // counterpart was already erased. See `eraseSubjectAsSystem`.\n externalEffects: [],\n };\n\n // The erasure is a compliance event: record what was torn down, what was retained, and the\n // configuration that justified each, so a data-protection response never has to be\n // reconstructed from the resource graph months later.\n this.logger.info('Subject erasure completed', {\n subjectResourceType,\n subjectCount: subjectIds.length,\n edges: edges.map((edge) => ({\n childResourceType: edge.childResourceType,\n disposition: edge.disposition,\n executed: edge.executed,\n })),\n });\n\n return report;\n },\n options,\n );\n }\n\n /**\n * Queue child resources for async deletion (eventual consistency).\n *\n * LAZY mode provides eventual consistency by queuing deletion operations\n * for asynchronous processing. This improves performance for bulk deletions\n * but requires a queue system to be implemented.\n *\n * Current implementation: Placeholder that throws NOT_IMPLEMENTED error.\n *\n * Future implementation (Phase 6.1-6.2):\n * When the queue system is implemented, this method should:\n * 1. Get the DELETE operation for the child resource type\n * 2. Use `operation.internalDto` for serializing queue payloads\n * - `internalDto` includes `isBackendOnly` fields needed for backend-to-backend communication\n * - Date coercion is already applied in `internalDto`\n * 3. Serialize resource data using `operation.internalDto.parse()` for validation\n * 4. Enqueue job with validated payload\n *\n * Example (when queue system is ready):\n * ```typescript\n * const childResourceConfig = this.resourcesRegistry.resourceConfigurations[relationship.resourceType2];\n * const deleteOperation = childResourceConfig.operations.find(\n * op => op.operationIdentifier === CoreResourceOperation.DELETE\n * );\n * if (!deleteOperation?.internalDto) {\n * throw new Error('DELETE operation or internalDto not found');\n * }\n *\n * // Validate and serialize using internalDto\n * const queuePayload = {\n * resourceType: relationship.resourceType2,\n * operationIdentifier: CoreResourceOperation.DELETE,\n * data: deleteOperation.internalDto.parse({ _id: childId, ...otherFields }),\n * executionContext: { ... },\n * };\n *\n * await this.queueService.enqueueResourceOperation(deleteOperation, queuePayload.data, executionContext);\n * ```\n *\n * @see Phase 6.1 - Use internalDto for Queue Payloads\n * @see Phase 6.2 - Validate Queue Payloads Against internalDto\n */\n /**\n * Assemble everything the framework holds about ONE data subject — the disclosure counterpart of\n * {@link eraseSubjectInPlace}.\n *\n * ## What it walks, and why that is not the erasure walk\n *\n * Both traverse the subject's child-direction edges through the same shared authority, so they can\n * never disagree about what an edge SAYS. They disagree about what it MEANS:\n * {@link classifySubjectExportDisposition} additionally includes edges the erasure calls\n * `NOT_OWNED` when the far side holds a foreign key back to the subject — an audit log or a\n * membership is not the subject's to delete, but Art. 15 covers \"all personal data concerning him\n * or her\" and must disclose it. That divergence is real on the shipped graph, not hypothetical.\n *\n * ## Two fail-loud gates, BOTH before the first read\n *\n * 1. **Authorization** — every resource whose rows would enter the bundle must declare\n * `systemAccessPolicy.exportSubject = ALLOWED`. Missing opt-ins REFUSE the export and are\n * named. Skipping them instead would emit a bundle that is incomplete without saying so,\n * which is the same class of lie as the routed export operations this capability replaced.\n * 2. **Art. 20 provenance** — for `PORTABILITY_ART_20` only, every field of every included\n * resource must resolve a provenance (its own `.portabilityProvenance()` or its resource's\n * `portabilityPolicy.defaultProvenance`). Undeclared fields REFUSE, because neither guess is\n * conservative: excluding under-delivers a legal right, including over-shares\n * controller-derived data. `ACCESS_ART_15` skips this gate entirely — access discloses\n * everything regardless of provenance, so an application can answer access requests before\n * annotating anything.\n *\n * Gating up front rather than per-edge-as-we-go is what makes the refusal safe: a half-assembled\n * bundle that discovered an ungranted resource at edge seven has already read six resources' worth\n * of personal data into memory for a request that will not complete.\n *\n * ## No transaction, deliberately\n *\n * Unlike the erasure this writes nothing, so there is nothing to roll back and no cross-adapter\n * atomicity limit: dependents on a different persistence adapter are simply a second query. A\n * subject export is a point-in-time snapshot and does not claim otherwise.\n *\n * @param subjectResourceType the subject's resource type. MUST be the resource this service\n * instance is bound to (asserted) — the edges come from ITS configuration.\n * @param subjectIds the explicit subject rows to export. An export is not a query.\n * @param purpose WHICH right is being answered. Drives edge inclusion AND field narrowing.\n * @param executionContext the privileged context (synthesised by `exportSubjectAsSystem`).\n * @returns the {@link SubjectExportBundle} — the personal data, paired with the report that\n * justifies its shape. Only the report is safe to log.\n */\n public async exportSubjectInPlace(\n subjectResourceType: ResourceType,\n subjectIds: string[],\n purpose: SubjectExportPurpose,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<SubjectExportBundle> {\n // The edges come from THIS service's configuration, so a mismatched resourceType would silently\n // export against the wrong graph — the disclosure analogue of erasing the wrong one.\n if (subjectResourceType !== this.resourceConfiguration.resourceIdentifier) {\n throw this.errorBuilder.buildError(\n ErrorType.INTERNAL,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message:\n `Subject export must run on the subject's own service instance: asked to export ` +\n `\"${subjectResourceType}\" on the service bound to ` +\n `\"${this.resourceConfiguration.resourceIdentifier}\".`,\n subjectResourceType,\n boundResourceType: this.resourceConfiguration.resourceIdentifier,\n },\n }\n );\n }\n\n const emptyReport = (): SubjectExportBundle => ({\n report: {\n purpose,\n subjectResourceType,\n subjectIds: [],\n edges: [],\n fieldsExcludedAsDerived: [],\n fieldsWithheldAsNonDisclosable: [],\n totalRecordCount: 0,\n },\n slices: [],\n });\n\n if (subjectIds.length === 0) {\n return emptyReport();\n }\n\n const classifications = enumerateSubjectExportRelationshipTraversals(\n subjectResourceType,\n this.resourceConfiguration.resourceRelationships,\n purpose,\n );\n\n // The subject's OWN resource is always in the bundle — it is the thing being disclosed — so it\n // joins the included set for both gates below rather than being special-cased past them.\n const includedResourceTypes: ResourceType[] = [\n subjectResourceType,\n ...classifications\n .filter(({ classification }) => isIncludedSubjectExportEdgeDisposition(classification.disposition))\n .map(({ classification }) => classification.relatedResourceType),\n ];\n\n const nonDisclosableResourceTypes = this.resolveSubjectExportDisclosureBlocks(\n includedResourceTypes,\n purpose,\n executionContext,\n );\n const disclosableResourceTypes = includedResourceTypes\n .filter((resourceType) => !nonDisclosableResourceTypes.has(resourceType));\n // FORBIDDEN resources are excluded from the provenance walk too: their rows are never read, so\n // demanding an Art. 20 declaration for their fields would refuse an export over data that was\n // never going to be disclosed.\n const { derived: fieldsExcludedAsDerived, withheld: fieldsWithheldAsNonDisclosable } =\n this.resolveSubjectExportFieldExclusions(disclosableResourceTypes, purpose, executionContext);\n // One list for the narrowing: both are \"remove this path from the rows\". They stay SEPARATE on\n // the report because the reasons differ — one is an Art. 20 scope decision the subject can\n // challenge, the other a security floor they cannot.\n const allRemovedFieldPaths = [...fieldsExcludedAsDerived, ...fieldsWithheldAsNonDisclosable];\n\n this.logDebug('Executing subject export', {\n subjectResourceType,\n purpose,\n subjectCount: subjectIds.length,\n edgeCount: classifications.length,\n includedResourceCount: includedResourceTypes.length,\n });\n\n const slices: SubjectExportResourceSlice[] = [];\n const edges: SubjectExportEdgeOutcome[] = [];\n\n // The subject's own rows first — a bundle whose edges resolved but whose subject did not would\n // be a disclosure about a person the report cannot name.\n const subjectRows = await this.readSubjectExportRows(\n subjectResourceType,\n { _id: { $in: subjectIds } },\n executionContext,\n options,\n );\n const narrowedSubjectRows = this.narrowRowsToExportScope(\n subjectResourceType,\n subjectRows,\n allRemovedFieldPaths,\n );\n if (narrowedSubjectRows.length > 0) {\n slices.push({ resourceType: subjectResourceType, rows: narrowedSubjectRows });\n }\n let totalRecordCount = narrowedSubjectRows.length;\n\n for (const { relationship, classification } of classifications) {\n if (\n isIncludedSubjectExportEdgeDisposition(classification.disposition)\n && nonDisclosableResourceTypes.has(classification.relatedResourceType)\n ) {\n // The right covers these rows; the declaration says they may never be handed over. Recorded\n // with the OVERRIDDEN disposition so the report states the real reason — \"we are not allowed\n // to disclose this\" is a different answer from \"this is not your data\".\n edges.push({\n ...classification,\n disposition: SubjectExportEdgeDisposition.EXCLUDED_NOT_DISCLOSABLE,\n reason:\n `${String(classification.relatedResourceType)} declares systemAccessPolicy.exportSubject `\n + `= FORBIDDEN: these rows concern the subject but are declared never-disclosable, so the `\n + `bundle leaves them out rather than refusing the whole export`,\n collected: false,\n recordCount: 0,\n });\n continue;\n }\n\n if (!isIncludedSubjectExportEdgeDisposition(classification.disposition)) {\n // Recorded, not skipped. \"Why is this missing from my export?\" must have an answer carrying\n // the configuration that produced it — that record IS the compliance artifact.\n edges.push({ ...classification, collected: false, recordCount: 0 });\n continue;\n }\n\n const foreignKeyField = this.getFKFieldForRelationship(relationship);\n const rows = await this.readSubjectExportRows(\n classification.relatedResourceType,\n { [foreignKeyField]: { $in: subjectIds } },\n executionContext,\n options,\n );\n const narrowed = this.narrowRowsToExportScope(\n classification.relatedResourceType,\n rows,\n allRemovedFieldPaths,\n );\n\n if (narrowed.length > 0) {\n slices.push({ resourceType: classification.relatedResourceType, rows: narrowed });\n }\n // `collected: true` with `recordCount: 0` is a meaningful, distinct state: the edge WAS read\n // and the subject simply had no rows there. Collapsing it into `collected: false` would make\n // \"we looked and found nothing\" indistinguishable from \"we never looked\".\n edges.push({ ...classification, collected: true, recordCount: narrowed.length });\n totalRecordCount += narrowed.length;\n }\n\n return {\n report: {\n purpose,\n subjectResourceType,\n subjectIds,\n edges,\n fieldsExcludedAsDerived,\n fieldsWithheldAsNonDisclosable,\n totalRecordCount,\n },\n slices,\n };\n }\n\n /**\n * Gate 1 — resolve which resources may be disclosed, refusing on the ones nobody has decided.\n *\n * Fail-closed by omission: a resource with NO declaration REFUSES the export, naming every\n * offender at once so the fix is one pass rather than a discover-one-per-run loop.\n *\n * A resource declared FORBIDDEN is NOT a refusal — it is returned so the caller can leave its\n * edge out and record the omission. Refusing on it would turn a legitimate decision into\n * permanent sabotage: a `USERS` access export whose graph touches a credential store could never\n * run again, whatever else opted in. The one exception is the SUBJECT'S OWN resource, which\n * cannot be \"left out\" of its own export.\n *\n * @returns the FORBIDDEN resource types, for the caller to exclude and report.\n */\n private resolveSubjectExportDisclosureBlocks(\n includedResourceTypes: ResourceType[],\n purpose: SubjectExportPurpose,\n executionContext: ExecutionContext<any>,\n ): ReadonlySet<ResourceType> {\n // TWO different refusals, kept apart on purpose. `FORBIDDEN` is a decision someone TOOK — this\n // resource must never reach a data subject — and it is NOT fixed by opting in. An absent\n // declaration is a decision nobody has taken yet, and opting in IS the fix. Collapsing them\n // would invite a reviewer to \"resolve\" a deliberate exclusion (a credentials store, say) by\n // treating it as an oversight, which is precisely how a security decision gets quietly undone.\n const forbidden: ResourceType[] = [];\n const undeclared: ResourceType[] = [];\n\n for (const resourceType of [...new Set(includedResourceTypes)]) {\n const mode = this.resourcesRegistry.getResourceConfiguration(resourceType)\n ?.systemAccessPolicy?.exportSubject;\n if (mode === ResourceSystemAccessMode.ALLOWED) continue;\n (mode === ResourceSystemAccessMode.FORBIDDEN ? forbidden : undeclared).push(resourceType);\n }\n\n // The SUBJECT'S OWN resource being FORBIDDEN is not an excludable edge — it is the thing being\n // exported. Returning an edges-only bundle would be a disclosure that omits its own subject.\n const subjectResourceType = includedResourceTypes[0]!;\n if (forbidden.includes(subjectResourceType)) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Subject export (${purpose}) is REFUSED: the subject's own resource ` +\n `\"${String(subjectResourceType)}\" declares systemAccessPolicy.exportSubject = FORBIDDEN. ` +\n `A resource that may never be disclosed cannot be an export subject — this is not an ` +\n `edge that can be left out.`,\n purpose,\n subjectResourceType,\n },\n }\n );\n }\n\n if (undeclared.length > 0) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Subject export (${purpose}) is REFUSED: ${undeclared.length} resource(s) that would ` +\n `enter the bundle carry NO disclosure declaration — ${undeclared.join(', ')}. Declare ` +\n `systemAccessPolicy.exportSubject = ResourceSystemAccessMode.ALLOWED on each, or ` +\n `FORBIDDEN to state that they must never be disclosed (FORBIDDEN resources are left ` +\n `OUT of the bundle and recorded, not refused). Refusing rather than skipping an ` +\n `undeclared resource — an export missing one without saying so is an incomplete ` +\n `disclosure presented as a complete one.`,\n purpose,\n undeclaredResourceTypes: undeclared,\n },\n }\n );\n }\n\n return new Set(forbidden);\n }\n\n /**\n * Gate 2 — resolve which fields Art. 20 excludes as controller-derived, refusing on any field\n * whose provenance nobody declared.\n *\n * Returns `resourceType.fieldName` locators for the excluded fields. Empty for\n * `ACCESS_ART_15`, which discloses every field regardless of provenance — that asymmetry is what\n * lets an application answer access requests before annotating a single resource.\n */\n private resolveSubjectExportFieldExclusions(\n includedResourceTypes: ResourceType[],\n purpose: SubjectExportPurpose,\n executionContext: ExecutionContext<any>,\n ): { derived: string[]; withheld: string[] } {\n const excluded: string[] = [];\n const undeclared: string[] = [];\n const withheld: string[] = [];\n\n for (const resourceType of [...new Set(includedResourceTypes)]) {\n const config = this.resourcesRegistry.getResourceConfiguration(resourceType);\n const decisions = compileSubjectExportFieldDecisions({\n resourceType,\n mainSchema: config?.mainSchema,\n defaultProvenance: config?.portabilityPolicy?.defaultProvenance,\n purpose,\n });\n for (const decision of decisions) {\n if (decision.basis === SubjectExportFieldDecisionBasis.WITHHELD_NON_DISCLOSABLE) withheld.push(decision.locator);\n else if (decision.scope === SubjectExportFieldScope.UNDECLARED) undeclared.push(decision.locator);\n else if (decision.scope === SubjectExportFieldScope.EXCLUDED_DERIVED) excluded.push(decision.locator);\n }\n }\n\n // The non-disclosable sweep runs for BOTH rights — a password hash is no more disclosable under\n // Art. 15 than under Art. 20 — but the Art. 20 provenance REFUSAL is portability-only, since\n // access never consults provenance.\n if (purpose === SubjectExportPurpose.ACCESS_ART_15) {\n return { derived: [], withheld };\n }\n\n if (undeclared.length > 0) {\n throw this.errorBuilder.buildError(\n ErrorType.CONFIGURATION,\n executionContext,\n {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message:\n `Portability export (Art. 20) is REFUSED: ${undeclared.length} field(s) declare no ` +\n `data provenance, so it cannot be decided whether the subject provided them. ` +\n `Declare portabilityPolicy.defaultProvenance on the resource, or ` +\n `.portabilityProvenance() on the field. Refusing rather than guessing — excluding ` +\n `them would under-deliver the subject's right, including them would over-share ` +\n `controller-derived data, and neither is the conservative choice. An ACCESS ` +\n `(Art. 15) export is unaffected and can run today.`,\n undeclaredFields: undeclared,\n },\n }\n );\n }\n\n return { derived: excluded, withheld };\n }\n\n /**\n * Return a deep copy of `value` with every `path` removed, without mutating the source row.\n *\n * Non-mutating on purpose: the rows come from a repository read and may be shared with a cache or\n * another consumer, so stripping in place could delete a derived field from someone else's view\n * of the same document.\n */\n private omitPathsFromValue(value: unknown, paths: string[][]): unknown {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return value;\n\n const source = value as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n\n for (const [key, fieldValue] of Object.entries(source)) {\n const matching = paths.filter((path) => path[0] === key);\n // An exact match at this level removes the field outright.\n if (matching.some((path) => path.length === 1)) continue;\n\n result[key] = matching.length > 0\n ? this.omitPathsFromValue(fieldValue, matching.map((path) => path.slice(1)))\n : fieldValue;\n }\n\n return result;\n }\n\n /** Read the rows of one resource participating in an export, through its own service instance. */\n private async readSubjectExportRows(\n resourceType: ResourceType,\n filter: Record<string, unknown>,\n executionContext: ExecutionContext<any>,\n options?: RepositoryOptions,\n ): Promise<Record<string, unknown>[]> {\n const repository = this.repositoriesRegistry.getRepository(resourceType);\n // LIST, not READ. `read(executionContext, filter)` resolves to a SINGLE document, so using it\n // here would silently cap every edge at one row — an export that looks successful while\n // disclosing a fraction of what it claims. The cascade discovery makes the same distinction.\n //\n // `listForInternalScan`, not the public `list`: an export participant only needs\n // `systemAccessPolicy.exportSubject` — nothing requires it to expose a user-facing default\n // LIST, and per-owner singletons (e.g. `userLifecycleState`, which declares\n // `exportSubject: ALLOWED` and READ/SEARCH/UPDATE/CREATE/DELETE but NO LIST) made this\n // throw `repository_resource_operation_failed` and 500 the whole subject export (found\n // while fixing the same wrong-door call in the dormancy batch, wildo-ai/wildo-ai#34).\n // Semantics are preserved where it already worked: a declared LIST is reused verbatim\n // (hooks included), and the synthetic no-LIST scan still runs through `_doList` →\n // `buildContextualFilter`, so the retention row-hide keeps applying — an erased subject's\n // hidden rows stay hidden (\"subject export does not set see-through\").\n const rows = await repository.listForInternalScan(executionContext, filter as any, options);\n return Array.isArray(rows) ? (rows as Record<string, unknown>[]) : [];\n }\n\n /**\n * Drop the fields Art. 20 excluded from a resource's rows.\n *\n * Operates on the resolved exclusion list rather than re-deriving per row: the decision is a\n * property of the SCHEMA, so re-asking it per row would be both wasteful and a chance for two rows\n * of the same resource to disagree.\n */\n private narrowRowsToExportScope(\n resourceType: ResourceType,\n rows: Record<string, unknown>[],\n removedFieldPaths: string[],\n ): Record<string, unknown>[] {\n const prefix = `${String(resourceType)}.`;\n const excludedPaths = removedFieldPaths\n .filter((locator) => locator.startsWith(prefix))\n .map((locator) => locator.slice(prefix.length).split('.'));\n if (excludedPaths.length === 0) return rows;\n\n return rows.map((row) => this.omitPathsFromValue(row, excludedPaths) as Record<string, unknown>);\n }\n\n private async queueChildDeletion(\n relationship: ResourceRelationship,\n parentIds: string[],\n executionContext: ExecutionContext<any>\n ): Promise<boolean> {\n // rag-removal-gate: N/A — LAZY cascade deletion is UNIMPLEMENTED (this method only throws).\n // Whoever implements it inherits the chunk-removal obligation: the deferred teardown must call\n // runRagChunkRemovalForDeletedRows for the child rows it eventually deletes, exactly as\n // deleteChildrenImmediate does — a queued delete that skips it strands the children's chunks\n // until the backstop sweep.\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: {\n message: 'LAZY cascade mode requires queue system integration. Queue system implementation pending. See Phase 6.1-6.2 for implementation details.',\n relationship: relationship.resourceType2,\n parentIds,\n },\n });\n }\n\n /**\n * Execute additional post-operation logic (non-cascading)\n */\n private async executeAdditionalPostOperationLogic(\n operation: CoreResourceOperation,\n result: any,\n executionContext: ExecutionContext<any>,\n currentState?: any,\n options?: RepositoryOptions,\n ): Promise<void> {\n\n this.logDebug('Executing additional post-operation logic', { operation });\n\n // Dispatch post-operation hooks registered on this resource type\n const resourceType = this.resourceConfiguration.resourceIdentifier as string;\n const dispatch = async (): Promise<void> => {\n await this.servicesRegistry.dispatchPostOperationHooks(\n resourceType,\n operation,\n result,\n executionContext,\n );\n };\n if (options?.transaction) {\n const transaction = options.transaction;\n registerTransactionPostCommitEffect(transaction, {\n key: [\n 'resource-post-operation-hooks',\n resourceType,\n String(operation),\n String((result as { _id?: unknown } | null)?._id ?? 'no-id'),\n transaction.id,\n options.frameworkPostCommitEffectOccurrenceId ?? randomUUID(),\n ].join(':'),\n execute: dispatch,\n });\n return;\n }\n await dispatch();\n }\n\n /**\n * Enrich business context\n */\n private async enrichBusinessContext(\n operation: CoreResourceOperation,\n data: any,\n executionContext: ExecutionContext<any>\n ): Promise<any> {\n\n // Implement business context enrichment here\n // This could include:\n // - Adding computed fields\n // - Loading related resources\n // - Adding user-specific data\n // - Permission-based filtering\n\n return data; // Default: pass through\n }\n\n /**\n * Apply business filter\n */\n private async applyBusinessFilter(\n filter: FilterQuery<any>,\n executionContext: ExecutionContext<any>\n ): Promise<FilterQuery<any>> {\n\n // Implement business filtering logic here\n // This could include:\n // - User permission-based filtering\n // - Organization scope filtering\n // - Security filtering\n\n return filter; // Default: pass through\n }\n\n /**\n * Enhance search query with business logic\n */\n private async enhanceSearchQuery(\n searchQuery: string,\n executionContext: ExecutionContext<any>\n ): Promise<string> {\n\n // Implement search enhancement logic here\n // This could include:\n // - Query expansion\n // - Synonym handling\n // - Permission-based query modification\n\n return searchQuery; // Default: pass through\n }\n\n /**\n * Validate deletion constraints\n */\n private async validateDeletionConstraints(\n data: any,\n executionContext: ExecutionContext<any>\n ): Promise<void> {\n\n // Implement deletion constraint validation here\n // This could include:\n // - Dependency checking\n // - Business rule validation\n // - Permission validation\n\n // Default: allow deletion\n }\n\n // ================================\n // Notification Methods\n // ================================\n\n /**\n * Dispatch notifications (email, badge, WebSocket, M2M) based on operation configuration.\n *\n * Reads ALL notification config from `executionContext.operation` — which is guaranteed\n * to be the correct (possibly variant-resolved) operation thanks to Correction Points\n * 1 and 2 in `doOperation()`. The NotificationDispatcherService also reads\n * `executionContext.operation` extensively (15+ reads across its sub-methods).\n */\n private async dispatchNotifications(\n executionContext: ExecutionContext<any>,\n inputData: any,\n currentResult: any,\n tokenGenerationResult?: TokenGenerationResult | null,\n previousState?: unknown,\n ): Promise<void> {\n await dispatchPostOperationNotificationsBestEffort(\n {\n notificationDispatcher: this.notificationDispatcher,\n populationService: this.populationService,\n logger: this.logger,\n logDebug: this.logDebug,\n },\n executionContext,\n inputData,\n currentResult,\n tokenGenerationResult,\n previousState,\n );\n }\n\n // ================================\n // Helper Methods\n // ================================\n\n\n}\n"]}
|