@wildo-ai/saas-backend-lib 1.1.12 → 1.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/dist/esm/base-classes/models/manual-controllers.backend.definition.d.ts.map +1 -1
  2. package/dist/esm/base-classes/models/manual-controllers.backend.definition.js +2 -0
  3. package/dist/esm/base-classes/models/manual-controllers.backend.definition.js.map +1 -1
  4. package/dist/esm/base-classes/services/repositories/stored-field-omission.backend.d.ts +4 -0
  5. package/dist/esm/base-classes/services/repositories/stored-field-omission.backend.d.ts.map +1 -1
  6. package/dist/esm/base-classes/services/repositories/stored-field-omission.backend.js +20 -5
  7. package/dist/esm/base-classes/services/repositories/stored-field-omission.backend.js.map +1 -1
  8. package/dist/esm/base-classes/services/services/resource-operation-custom-implementation-registry.backend.service.d.ts +3 -0
  9. package/dist/esm/base-classes/services/services/resource-operation-custom-implementation-registry.backend.service.d.ts.map +1 -1
  10. package/dist/esm/base-classes/services/services/resource-operation-custom-implementation-registry.backend.service.js +10 -1
  11. package/dist/esm/base-classes/services/services/resource-operation-custom-implementation-registry.backend.service.js.map +1 -1
  12. package/dist/esm/base-classes/services/services/resource-operation-custom-implementation.factory.backend.d.ts +22 -0
  13. package/dist/esm/base-classes/services/services/resource-operation-custom-implementation.factory.backend.d.ts.map +1 -1
  14. package/dist/esm/base-classes/services/services/resource-operation-custom-implementation.factory.backend.js +25 -1
  15. package/dist/esm/base-classes/services/services/resource-operation-custom-implementation.factory.backend.js.map +1 -1
  16. package/dist/esm/base-classes/services/services/resource-operation-transaction-persistence.backend.utils.d.ts +38 -3
  17. package/dist/esm/base-classes/services/services/resource-operation-transaction-persistence.backend.utils.d.ts.map +1 -1
  18. package/dist/esm/base-classes/services/services/resource-operation-transaction-persistence.backend.utils.js +68 -5
  19. package/dist/esm/base-classes/services/services/resource-operation-transaction-persistence.backend.utils.js.map +1 -1
  20. package/dist/esm/base-classes/services/services/resource-status-transition.custom-impl.backend.service.d.ts +2 -2
  21. package/dist/esm/base-classes/services/services/resource-status-transition.custom-impl.backend.service.d.ts.map +1 -1
  22. package/dist/esm/base-classes/services/services/resource-status-transition.custom-impl.backend.service.js +6 -3
  23. package/dist/esm/base-classes/services/services/resource-status-transition.custom-impl.backend.service.js.map +1 -1
  24. package/dist/esm/base-classes/services/services/services-registry-handler.backend.service.d.ts +83 -0
  25. package/dist/esm/base-classes/services/services/services-registry-handler.backend.service.d.ts.map +1 -1
  26. package/dist/esm/base-classes/services/services/services-registry-handler.backend.service.js +217 -14
  27. package/dist/esm/base-classes/services/services/services-registry-handler.backend.service.js.map +1 -1
  28. package/dist/esm/compliance/approval-seals/approval-seal-currency.backend.d.ts +32 -0
  29. package/dist/esm/compliance/approval-seals/approval-seal-currency.backend.d.ts.map +1 -0
  30. package/dist/esm/compliance/approval-seals/approval-seal-currency.backend.js +36 -0
  31. package/dist/esm/compliance/approval-seals/approval-seal-currency.backend.js.map +1 -0
  32. package/dist/esm/compliance/approval-seals/approval-seal-on-record.backend.d.ts +38 -0
  33. package/dist/esm/compliance/approval-seals/approval-seal-on-record.backend.d.ts.map +1 -0
  34. package/dist/esm/compliance/approval-seals/approval-seal-on-record.backend.js +83 -0
  35. package/dist/esm/compliance/approval-seals/approval-seal-on-record.backend.js.map +1 -0
  36. package/dist/esm/compliance/approval-seals/approval-seal-presentation-read.backend.d.ts +36 -0
  37. package/dist/esm/compliance/approval-seals/approval-seal-presentation-read.backend.d.ts.map +1 -0
  38. package/dist/esm/compliance/approval-seals/approval-seal-presentation-read.backend.js +51 -0
  39. package/dist/esm/compliance/approval-seals/approval-seal-presentation-read.backend.js.map +1 -0
  40. package/dist/esm/compliance/approval-seals/approval-seal-relay-store.backend.d.ts +46 -0
  41. package/dist/esm/compliance/approval-seals/approval-seal-relay-store.backend.d.ts.map +1 -1
  42. package/dist/esm/compliance/approval-seals/approval-seal-relay-store.backend.js +68 -0
  43. package/dist/esm/compliance/approval-seals/approval-seal-relay-store.backend.js.map +1 -1
  44. package/dist/esm/compliance/approval-seals/approval-seal-store.backend.d.ts +27 -0
  45. package/dist/esm/compliance/approval-seals/approval-seal-store.backend.d.ts.map +1 -1
  46. package/dist/esm/compliance/approval-seals/approval-seal-store.backend.js +42 -3
  47. package/dist/esm/compliance/approval-seals/approval-seal-store.backend.js.map +1 -1
  48. package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.contracts.d.ts +26 -1
  49. package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.contracts.d.ts.map +1 -1
  50. package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.contracts.js +10 -0
  51. package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.contracts.js.map +1 -1
  52. package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.controller.d.ts +10 -1
  53. package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.controller.d.ts.map +1 -1
  54. package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.controller.js +60 -28
  55. package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.controller.js.map +1 -1
  56. package/dist/esm/compliance/approval-seals/approval-seals-on-record.backend.controller.d.ts +90 -0
  57. package/dist/esm/compliance/approval-seals/approval-seals-on-record.backend.controller.d.ts.map +1 -0
  58. package/dist/esm/compliance/approval-seals/approval-seals-on-record.backend.controller.js +373 -0
  59. package/dist/esm/compliance/approval-seals/approval-seals-on-record.backend.controller.js.map +1 -0
  60. package/dist/esm/compliance/approval-seals/decision-presentation.backend.d.ts +29 -2
  61. package/dist/esm/compliance/approval-seals/decision-presentation.backend.d.ts.map +1 -1
  62. package/dist/esm/compliance/approval-seals/decision-presentation.backend.js +40 -3
  63. package/dist/esm/compliance/approval-seals/decision-presentation.backend.js.map +1 -1
  64. package/dist/esm/compliance/electronic-signatures/pdf-signature-structure.backend.d.ts.map +1 -1
  65. package/dist/esm/compliance/electronic-signatures/pdf-signature-structure.backend.js +34 -6
  66. package/dist/esm/compliance/electronic-signatures/pdf-signature-structure.backend.js.map +1 -1
  67. package/dist/esm/compliance/electronic-signatures/signature-request-evidence-files.backend.d.ts +30 -6
  68. package/dist/esm/compliance/electronic-signatures/signature-request-evidence-files.backend.d.ts.map +1 -1
  69. package/dist/esm/compliance/electronic-signatures/signature-request-evidence-files.backend.js +67 -22
  70. package/dist/esm/compliance/electronic-signatures/signature-request-evidence-files.backend.js.map +1 -1
  71. package/dist/esm/compliance/electronic-signatures/signature-request-poll.batch.backend.service.d.ts.map +1 -1
  72. package/dist/esm/compliance/electronic-signatures/signature-request-poll.batch.backend.service.js +18 -1
  73. package/dist/esm/compliance/electronic-signatures/signature-request-poll.batch.backend.service.js.map +1 -1
  74. package/dist/esm/compliance/electronic-signatures/signature-requests.backend.service.d.ts +66 -1
  75. package/dist/esm/compliance/electronic-signatures/signature-requests.backend.service.d.ts.map +1 -1
  76. package/dist/esm/compliance/electronic-signatures/signature-requests.backend.service.js +161 -14
  77. package/dist/esm/compliance/electronic-signatures/signature-requests.backend.service.js.map +1 -1
  78. package/dist/esm/compliance/electronic-signatures/signed-document-validation.backend.d.ts +47 -0
  79. package/dist/esm/compliance/electronic-signatures/signed-document-validation.backend.d.ts.map +1 -1
  80. package/dist/esm/compliance/electronic-signatures/signed-document-validation.backend.js.map +1 -1
  81. package/dist/esm/external-providers/services/content-safety.backend.service.d.ts +27 -2
  82. package/dist/esm/external-providers/services/content-safety.backend.service.d.ts.map +1 -1
  83. package/dist/esm/external-providers/services/content-safety.backend.service.js +46 -1
  84. package/dist/esm/external-providers/services/content-safety.backend.service.js.map +1 -1
  85. package/dist/esm/external-providers/services/embeddings.backend.service.d.ts.map +1 -1
  86. package/dist/esm/external-providers/services/embeddings.backend.service.js +2 -0
  87. package/dist/esm/external-providers/services/embeddings.backend.service.js.map +1 -1
  88. package/dist/esm/external-providers/services/external-providers-registry.backend.service.d.ts +11 -0
  89. package/dist/esm/external-providers/services/external-providers-registry.backend.service.d.ts.map +1 -1
  90. package/dist/esm/external-providers/services/external-providers-registry.backend.service.js +23 -0
  91. package/dist/esm/external-providers/services/external-providers-registry.backend.service.js.map +1 -1
  92. package/dist/esm/external-providers/services/provider-service-account-token.backend.d.ts +19 -1
  93. package/dist/esm/external-providers/services/provider-service-account-token.backend.d.ts.map +1 -1
  94. package/dist/esm/external-providers/services/provider-service-account-token.backend.js +41 -1
  95. package/dist/esm/external-providers/services/provider-service-account-token.backend.js.map +1 -1
  96. package/dist/esm/files/utils/file-parent-read-context.backend.d.ts +27 -2
  97. package/dist/esm/files/utils/file-parent-read-context.backend.d.ts.map +1 -1
  98. package/dist/esm/files/utils/file-parent-read-context.backend.js +23 -4
  99. package/dist/esm/files/utils/file-parent-read-context.backend.js.map +1 -1
  100. package/dist/esm/flows-actors/content-guardrails/classifier-availability.backend.utils.d.ts +26 -0
  101. package/dist/esm/flows-actors/content-guardrails/classifier-availability.backend.utils.d.ts.map +1 -1
  102. package/dist/esm/flows-actors/content-guardrails/classifier-availability.backend.utils.js +100 -8
  103. package/dist/esm/flows-actors/content-guardrails/classifier-availability.backend.utils.js.map +1 -1
  104. package/dist/esm/flows-actors/content-guardrails/record-owner-policy.backend.d.ts +3 -1
  105. package/dist/esm/flows-actors/content-guardrails/record-owner-policy.backend.d.ts.map +1 -1
  106. package/dist/esm/flows-actors/content-guardrails/record-owner-policy.backend.js +8 -2
  107. package/dist/esm/flows-actors/content-guardrails/record-owner-policy.backend.js.map +1 -1
  108. package/dist/esm/flows-actors/models/function-tools.backend.definitions.d.ts +43 -0
  109. package/dist/esm/flows-actors/models/function-tools.backend.definitions.d.ts.map +1 -1
  110. package/dist/esm/flows-actors/models/function-tools.backend.definitions.js +37 -0
  111. package/dist/esm/flows-actors/models/function-tools.backend.definitions.js.map +1 -1
  112. package/dist/esm/flows-actors/services/agent-work-decisions.backend.service.d.ts +7 -0
  113. package/dist/esm/flows-actors/services/agent-work-decisions.backend.service.d.ts.map +1 -1
  114. package/dist/esm/flows-actors/services/agent-work-decisions.backend.service.js +8 -3
  115. package/dist/esm/flows-actors/services/agent-work-decisions.backend.service.js.map +1 -1
  116. package/dist/esm/flows-actors/services/agents.backend.service.d.ts +31 -6
  117. package/dist/esm/flows-actors/services/agents.backend.service.d.ts.map +1 -1
  118. package/dist/esm/flows-actors/services/agents.backend.service.js +78 -30
  119. package/dist/esm/flows-actors/services/agents.backend.service.js.map +1 -1
  120. package/dist/esm/flows-actors/services/autonomous-agent-turn.backend.service.d.ts.map +1 -1
  121. package/dist/esm/flows-actors/services/autonomous-agent-turn.backend.service.js +4 -0
  122. package/dist/esm/flows-actors/services/autonomous-agent-turn.backend.service.js.map +1 -1
  123. package/dist/esm/flows-actors/services/conversational-execution.backend.service.d.ts +28 -2
  124. package/dist/esm/flows-actors/services/conversational-execution.backend.service.d.ts.map +1 -1
  125. package/dist/esm/flows-actors/services/conversational-execution.backend.service.js +132 -22
  126. package/dist/esm/flows-actors/services/conversational-execution.backend.service.js.map +1 -1
  127. package/dist/esm/flows-actors/services/flow-actor-executions.custom-impl.backend.service.d.ts.map +1 -1
  128. package/dist/esm/flows-actors/services/flow-actor-executions.custom-impl.backend.service.js +12 -8
  129. package/dist/esm/flows-actors/services/flow-actor-executions.custom-impl.backend.service.js.map +1 -1
  130. package/dist/esm/flows-actors/services/flows-actors-registry.service.d.ts +5 -0
  131. package/dist/esm/flows-actors/services/flows-actors-registry.service.d.ts.map +1 -1
  132. package/dist/esm/flows-actors/services/flows-actors-registry.service.js +18 -2
  133. package/dist/esm/flows-actors/services/flows-actors-registry.service.js.map +1 -1
  134. package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.d.ts +33 -0
  135. package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.d.ts.map +1 -1
  136. package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.js +58 -0
  137. package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.js.map +1 -1
  138. package/dist/esm/inbound/services/inbound-delivery-dispatch.backend.service.d.ts +12 -1
  139. package/dist/esm/inbound/services/inbound-delivery-dispatch.backend.service.d.ts.map +1 -1
  140. package/dist/esm/inbound/services/inbound-delivery-dispatch.backend.service.js +23 -4
  141. package/dist/esm/inbound/services/inbound-delivery-dispatch.backend.service.js.map +1 -1
  142. package/dist/esm/inbound/services/inbound-delivery-receiver.backend.service.d.ts +12 -1
  143. package/dist/esm/inbound/services/inbound-delivery-receiver.backend.service.d.ts.map +1 -1
  144. package/dist/esm/inbound/services/inbound-delivery-receiver.backend.service.js +55 -17
  145. package/dist/esm/inbound/services/inbound-delivery-receiver.backend.service.js.map +1 -1
  146. package/dist/esm/inbound/services/inbound-delivery-store.backend.service.d.ts +22 -1
  147. package/dist/esm/inbound/services/inbound-delivery-store.backend.service.d.ts.map +1 -1
  148. package/dist/esm/inbound/services/inbound-delivery-store.backend.service.js +52 -9
  149. package/dist/esm/inbound/services/inbound-delivery-store.backend.service.js.map +1 -1
  150. package/dist/esm/inbound/services/inbound-delivery-stored-body.backend.service.d.ts +79 -0
  151. package/dist/esm/inbound/services/inbound-delivery-stored-body.backend.service.d.ts.map +1 -0
  152. package/dist/esm/inbound/services/inbound-delivery-stored-body.backend.service.js +211 -0
  153. package/dist/esm/inbound/services/inbound-delivery-stored-body.backend.service.js.map +1 -0
  154. package/dist/esm/inbound/services/inbound-delivery-subject-erasure-severance.backend.d.ts +2 -2
  155. package/dist/esm/inbound/services/inbound-delivery-subject-erasure-severance.backend.d.ts.map +1 -1
  156. package/dist/esm/inbound/services/inbound-delivery-subject-erasure-severance.backend.js +9 -1
  157. package/dist/esm/inbound/services/inbound-delivery-subject-erasure-severance.backend.js.map +1 -1
  158. package/dist/esm/index.d.ts +1 -0
  159. package/dist/esm/index.d.ts.map +1 -1
  160. package/dist/esm/index.js +1 -0
  161. package/dist/esm/index.js.map +1 -1
  162. package/dist/esm/inject/models/container.d.ts.map +1 -1
  163. package/dist/esm/inject/models/container.js +6 -0
  164. package/dist/esm/inject/models/container.js.map +1 -1
  165. package/dist/esm/inject/models/service-types.d.ts +5 -0
  166. package/dist/esm/inject/models/service-types.d.ts.map +1 -1
  167. package/dist/esm/inject/models/service-types.js +3 -0
  168. package/dist/esm/inject/models/service-types.js.map +1 -1
  169. package/dist/esm/monitoring/observability/models/observability.backend.schemas.d.ts +5 -0
  170. package/dist/esm/monitoring/observability/models/observability.backend.schemas.d.ts.map +1 -1
  171. package/dist/esm/monitoring/observability/models/observability.backend.schemas.js.map +1 -1
  172. package/dist/esm/monitoring/observability/services/metrics.service.d.ts +34 -1
  173. package/dist/esm/monitoring/observability/services/metrics.service.d.ts.map +1 -1
  174. package/dist/esm/monitoring/observability/services/metrics.service.js +49 -0
  175. package/dist/esm/monitoring/observability/services/metrics.service.js.map +1 -1
  176. package/dist/esm/notifications/webhooks/controllers/webhook-auto-controller.backend.service.d.ts +6 -1
  177. package/dist/esm/notifications/webhooks/controllers/webhook-auto-controller.backend.service.d.ts.map +1 -1
  178. package/dist/esm/notifications/webhooks/controllers/webhook-auto-controller.backend.service.js +15 -4
  179. package/dist/esm/notifications/webhooks/controllers/webhook-auto-controller.backend.service.js.map +1 -1
  180. package/dist/esm/notifications/webhooks/outbound/services/m2m-webhook-delivery-log.custom-impl.backend.service.d.ts.map +1 -1
  181. package/dist/esm/notifications/webhooks/outbound/services/m2m-webhook-delivery-log.custom-impl.backend.service.js +3 -1
  182. package/dist/esm/notifications/webhooks/outbound/services/m2m-webhook-delivery-log.custom-impl.backend.service.js.map +1 -1
  183. package/dist/esm/runtime/services/http-server.backend.service.d.ts +3 -1
  184. package/dist/esm/runtime/services/http-server.backend.service.d.ts.map +1 -1
  185. package/dist/esm/runtime/services/http-server.backend.service.js +11 -3
  186. package/dist/esm/runtime/services/http-server.backend.service.js.map +1 -1
  187. package/dist/esm/runtime/services/utils/inbound-endpoint-raw-body.backend.utils.d.ts +22 -0
  188. package/dist/esm/runtime/services/utils/inbound-endpoint-raw-body.backend.utils.d.ts.map +1 -1
  189. package/dist/esm/runtime/services/utils/inbound-endpoint-raw-body.backend.utils.js +54 -0
  190. package/dist/esm/runtime/services/utils/inbound-endpoint-raw-body.backend.utils.js.map +1 -1
  191. package/dist/esm/security/authentications/services/auth-methods/auth-password-reset.backend.service.d.ts +51 -0
  192. package/dist/esm/security/authentications/services/auth-methods/auth-password-reset.backend.service.d.ts.map +1 -1
  193. package/dist/esm/security/authentications/services/auth-methods/auth-password-reset.backend.service.js +87 -15
  194. package/dist/esm/security/authentications/services/auth-methods/auth-password-reset.backend.service.js.map +1 -1
  195. package/dist/esm/security/authentications/services/custom-impls/siem-delivery-dlq.custom-impl.backend.service.d.ts.map +1 -1
  196. package/dist/esm/security/authentications/services/custom-impls/siem-delivery-dlq.custom-impl.backend.service.js +5 -2
  197. package/dist/esm/security/authentications/services/custom-impls/siem-delivery-dlq.custom-impl.backend.service.js.map +1 -1
  198. package/dist/esm/security/authentications/services/custom-impls/sso-config-domain-verification.custom-impl.backend.service.d.ts.map +1 -1
  199. package/dist/esm/security/authentications/services/custom-impls/sso-config-domain-verification.custom-impl.backend.service.js +65 -24
  200. package/dist/esm/security/authentications/services/custom-impls/sso-config-domain-verification.custom-impl.backend.service.js.map +1 -1
  201. package/dist/esm/security/authorizations/super-admin-floor.backend.utils.d.ts +64 -1
  202. package/dist/esm/security/authorizations/super-admin-floor.backend.utils.d.ts.map +1 -1
  203. package/dist/esm/security/authorizations/super-admin-floor.backend.utils.js +84 -2
  204. package/dist/esm/security/authorizations/super-admin-floor.backend.utils.js.map +1 -1
  205. package/dist/esm/security/oauth-clients/oauth-clients.custom-impl.backend.service.d.ts +14 -0
  206. package/dist/esm/security/oauth-clients/oauth-clients.custom-impl.backend.service.d.ts.map +1 -1
  207. package/dist/esm/security/oauth-clients/oauth-clients.custom-impl.backend.service.js +13 -5
  208. package/dist/esm/security/oauth-clients/oauth-clients.custom-impl.backend.service.js.map +1 -1
  209. package/dist/esm/users/services/anonymous-consent.custom-impl.backend.service.d.ts.map +1 -1
  210. package/dist/esm/users/services/anonymous-consent.custom-impl.backend.service.js +6 -2
  211. package/dist/esm/users/services/anonymous-consent.custom-impl.backend.service.js.map +1 -1
  212. package/dist/esm/users/services/user-force-password-reset.custom-impl.backend.service.d.ts +7 -0
  213. package/dist/esm/users/services/user-force-password-reset.custom-impl.backend.service.d.ts.map +1 -1
  214. package/dist/esm/users/services/user-force-password-reset.custom-impl.backend.service.js +65 -20
  215. package/dist/esm/users/services/user-force-password-reset.custom-impl.backend.service.js.map +1 -1
  216. package/dist/esm/users/services/user-role-administration.custom-impl.backend.service.d.ts.map +1 -1
  217. package/dist/esm/users/services/user-role-administration.custom-impl.backend.service.js +11 -4
  218. package/dist/esm/users/services/user-role-administration.custom-impl.backend.service.js.map +1 -1
  219. package/dist/esm/users/services/user-self-custom-implementations.backend.d.ts.map +1 -1
  220. package/dist/esm/users/services/user-self-custom-implementations.backend.js +4 -2
  221. package/dist/esm/users/services/user-self-custom-implementations.backend.js.map +1 -1
  222. package/dist/esm/users/services/user-super-admin-floor.custom-impl.backend.service.d.ts.map +1 -1
  223. package/dist/esm/users/services/user-super-admin-floor.custom-impl.backend.service.js +16 -0
  224. package/dist/esm/users/services/user-super-admin-floor.custom-impl.backend.service.js.map +1 -1
  225. package/dist/tsconfig.build.tsbuildinfo +1 -1
  226. package/package.json +10 -10
@@ -1 +1 @@
1
- {"version":3,"file":"agent-work-decisions.backend.service.js","sourceRoot":"","sources":["../../../../src/flows-actors/services/agent-work-decisions.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAkB,MAAM,WAAW,CAAC;AACzE,OAAO,EAAE,2BAA2B,EAAE,2BAA2B,EAAE,4BAA4B,EAAE,MAAM,wFAAwF,CAAC;AAChM,OAAO,EACL,qCAAqC,EACrC,kCAAkC,EAClC,yBAAyB,EACzB,6BAA6B,EAC7B,wBAAwB,EACxB,gCAAgC,EAChC,qBAAqB,EACrB,gBAAgB,EAChB,0BAA0B,EAC1B,w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C,kBAAkB,CAAC,kCAAkC,CAAC,IAAI,YAAY,EAAE,CAAC,aAAa,CAAC,YAAY,CAAC,CACzI,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * # Deciders' decisions on agents' proposals: the record, the override rate and the evaluation export (#1599)\n *\n * Every decision a person takes on something an AGENT proposed — a tool call approved, edited or denied, an\n * actor-system review, an edit to agent-drafted output — is recorded ONCE, as metadata, in `agentWorkDecisions`.\n * With the organization's opt-in, the proposal, the final version and the diff are kept beside it in\n * `agentWorkDecisionContents`. From the metadata alone this service computes the override rate; with a recorded\n * authorisation it exports an organization's decisions as a pseudonymised evaluation dataset, and records the export.\n *\n * ## Written by the winner only, and repaired after a crash (I1–I3)\n *\n * The settle that WINS a decision's compare-and-swap calls {@link recordDecision}; a loser records nothing (I2). The\n * same compare-and-swap stamps `pendingCorrectionRecordRef` on the execution row, and the marker is cleared only once\n * the record exists. A process that dies in between leaves the marker, and {@link repairPendingCorrectionRecords}\n * writes the record from the row's resolution columns (`ROW_REPAIR`, metadata only) (I3). `decisionRef` is unique in\n * every store, so a repair racing the settle, a retried output review and a double settle all converge on one row (I1).\n *\n * ## Tenant-keyed digests (I5)\n *\n * No digest here is an unkeyed hash: see `agent-work-correction.backend.utils.ts`. The key needs the application's\n * primary secret; without it the record keeps the paths and the distance and claims no digest.\n *\n * assurance-control: WILDO.PRIVACY.DATA_MINIMIZATION — the record is metadata only; content is kept under the\n * organization's opt-in, and an export carries pseudonyms and no decider or organization.\n * assurance-control: WILDO.PRIVACY.ERASURE_PROPAGATION — erasing a case scrubs the content kept about it.\n * assurance-control: WILDO.PRIVACY.SECONDARY_USE_AUTHORIZATION — erasing a case marks every dataset that exported it: an\n * exported dataset is a derived copy, which ERASURE_PROPAGATION's intent excludes.\n */\nimport { inject, injectable, optional, type Container } from 'inversify';\nimport { readFailureEndsTheOperation, readOptionsOnItsOwnDatabase, writeFailureEndsTheOperation } from '~wildo-backend-lib/base-classes/services/repositories/resource-write-integrity.backend';\nimport {\n AGENT_WORK_DECISION_OVERRIDE_OUTCOMES,\n AGENT_WORK_DECISION_RATED_OUTCOMES,\n AgentWorkDecisionGrouping,\n AgentWorkDecisionRecordSource,\n AgentWorkDecisionSurface,\n AgentWorkOutputReviewInputSchema,\n CoreResourceOperation,\n CoreResourceType,\n ResourceReferenceTargetSet,\n CorrectionContentCapture,\n ErrorCustomMessageReference,\n ErrorType,\n EvaluationDatasetExportRefusalReason,\n EvaluationDatasetInvalidationReason,\n EvaluationContentWithholdingReason,\n EvaluationExportAuthorizationStatus,\n ExecutionRefKind,\n FlowActorSystem_Kind,\n Resources_SharedUtils,\n HumanDecision_Outcome,\n PersonalDataCategory,\n SortOrder,\n agentWorkOverrideRate,\n type ActorSystem,\n type AgentWorkSubjectRef,\n isSpecialCategoryPersonalData,\n resolveResourcePersonalDataCategories,\n resourceComplianceSchema,\n type AgentWorkCaptureSettings,\n type AgentWorkDecision,\n type AgentWorkDecisionContent,\n type AgentWorkOutputReviewInput,\n type AgentWorkOverrideRate,\n type AgentWorkOverrideRateGroup,\n type AgentWorkOverrideRateRequest,\n type AgentWorkProductRef,\n type EvaluationDatasetExport,\n type EvaluationDatasetExportRequest,\n type EvaluationDatasetExportResult,\n type EvaluationExportAuthorization,\n type ExecutionRef,\n type FlowActorExecution,\n type ResourceType,\n type WorkUnitRef,\n resourceInheritanceVariantSchemas,\n resolveRelationshipOnlyStanding,\n resolveRelationshipWorkAttribution,\n} from '@wildo-ai/saas-models';\n\nimport { SAAS_SERVICE_TYPES } from '~wildo-backend-lib/inject/models/service-types';\nimport { LoggerService } from '~wildo-backend-lib/monitoring/logger/services/logger.service';\nimport { RepositoriesRegistryHandlerBackendService } from '~wildo-backend-lib/base-classes/services/repositories/repositories-registry-handler.backend.service';\nimport type { ServicesRegistryHandlerBackendService } from '~wildo-backend-lib/base-classes/services/services/services-registry-handler.backend.service';\nimport { SeveredColumnExportDisclosure } from '~wildo-backend-lib/base-classes/services/services/subject-reference-severance.backend.schemas';\nimport { createColumnSubjectReferenceSeverer } from '~wildo-backend-lib/base-classes/services/services/subject-reference-severance.backend.utils';\nimport { ErrorBuilderBackendService } from '~wildo-backend-lib/errors/services/error-builder.backend.service';\nimport { describeCaughtError } from '~wildo-backend-lib/errors/utils/error-log-level-classification.backend.utils';\nimport { RelationshipOwnWorkTenantField, relationshipOwnWorkFilter } from '~wildo-backend-lib/flows-actors/models/relationship-own-work.backend.utils';\nimport { registerTransactionPostCommitEffect, type TransactionContext } from '~wildo-backend-lib/databases/models/transaction.shared.schemas';\nimport { CapturedPostCommitEffectKind } from '~wildo-backend-lib/base-classes/models/post-commit-effect-outbox.backend.schemas';\nimport {\n AGENT_WORK_CASE_REMOVAL_ROWS_PER_CAPTURED_EFFECT,\n capturablePostCommitEffect,\n idempotentSideEffectCapture,\n} from '~wildo-backend-lib/base-classes/services/services/post-commit-effect-capture.backend';\nimport type { AppConfigurationService } from '~wildo-backend-lib/config/services/app-configuration.backend.service';\nimport type { ExecutionContext } from '~wildo-backend-lib/runtime/models/execution-context.backend.schemas';\nimport { runOutsideRelationshipProvenanceFrame, runWithRelationshipProvenanceFrame } from '~wildo-backend-lib/runtime/models/relationship-provenance-frame.als.backend';\nimport type { ExecutionContextCreatorBackendService } from '~wildo-backend-lib/runtime/services/execution-context-creator.backend.service';\nimport type { ResourcesRegistryBackendService } from '~wildo-backend-lib/resources/services/resources-registry.backend.service';\nimport type { AuditLogsBackendService } from '~wildo-backend-lib/compliance/audit-trails/services/audit-logs.backend.service';\nimport type { RepositoryOptions } from '~wildo-backend-lib/base-classes/models/repositories.backend.schemas';\nimport type { WorkUnitCaseBackendService } from '~wildo-backend-lib/flows-actors/services/work-unit-case.backend.service';\nimport type { DecisionTimeSource } from '~wildo-backend-lib/flows-actors/services/model-cost.backend.service';\nimport type { FlowsActorsRegistryService } from '~wildo-backend-lib/flows-actors/services/flows-actors-registry.service';\nimport { chatAgentRefOfActorSystem, modelToolNameForFunctionRef } from '~wildo-backend-lib/flows-actors/models/function-tools.backend.definitions';\nimport {\n correctionJsonPatch,\n deriveAgentWorkCorrectionKey,\n deriveEvaluationPseudonymKey,\n EVALUATION_PSEUDONYMISATION_VERSION,\n measureAgentWorkCorrection,\n minimiseContentByDeclaredShape,\n modifiedPathsOf,\n type JsonPatchOperation,\n pseudonymiseIdentifier,\n pseudonymiseKnownIdentifiers,\n schemaDeclaresForeignKeyField,\n type EvaluationContentShape,\n} from '~wildo-backend-lib/flows-actors/utils/agent-work-correction.backend.utils';\nimport { CryptoKey_Purpose } from '@wildo-ai/saas-models';\nimport { applicationSymmetricKeyOf } from '~wildo-backend-lib/security/crypto-keys/application-symmetric-keys.backend';\n\n/** Rows read per page when a summary, an export or a sweep scans records. */\nconst PAGE_SIZE = 500;\n/**\n * How long after a decision the repair sweep leaves its marker alone. The settle writes its record right after the\n * compare-and-swap; repairing inside that window would race it and write a metadata-only ROW_REPAIR record where the\n * settle would have kept content. Idempotent either way (the unique `decisionRef`), so this is about content, not\n * correctness.\n */\nconst REPAIR_GRACE_MS = 2 * 60_000;\n\n/** The owner scope a record is written in: the scope of the paused execution, or of an output review. */\nexport type AgentWorkOwnerScope =\n | { readonly userId: string }\n | { readonly organizationId: string }\n | { readonly applicationId: string };\n\n/** One owner scope's three stores. */\ninterface AgentWorkVariant {\n readonly ownerField: 'userId' | 'organizationId' | 'applicationId';\n readonly executions: CoreResourceType;\n readonly decisions: CoreResourceType;\n readonly contents: CoreResourceType;\n}\n\n/** The three owner scopes, in the order a sweep walks them. */\nexport const AGENT_WORK_VARIANTS: readonly AgentWorkVariant[] = Object.freeze([\n { ownerField: 'userId', executions: CoreResourceType.USER_FLOW_ACTOR_EXECUTIONS, decisions: CoreResourceType.USER_AGENT_WORK_DECISIONS, contents: CoreResourceType.USER_AGENT_WORK_DECISION_CONTENTS },\n { ownerField: 'organizationId', executions: CoreResourceType.ORGANIZATION_FLOW_ACTOR_EXECUTIONS, decisions: CoreResourceType.ORGANIZATION_AGENT_WORK_DECISIONS, contents: CoreResourceType.ORGANIZATION_AGENT_WORK_DECISION_CONTENTS },\n { ownerField: 'applicationId', executions: CoreResourceType.APPLICATION_FLOW_ACTOR_EXECUTIONS, decisions: CoreResourceType.APPLICATION_AGENT_WORK_DECISIONS, contents: CoreResourceType.APPLICATION_AGENT_WORK_DECISION_CONTENTS },\n] as const);\n\nfunction variantOfOwner(owner: AgentWorkOwnerScope): { variant: AgentWorkVariant; ownerId: string } {\n if ('userId' in owner) return { variant: AGENT_WORK_VARIANTS[0]!, ownerId: owner.userId };\n if ('organizationId' in owner) return { variant: AGENT_WORK_VARIANTS[1]!, ownerId: owner.organizationId };\n return { variant: AGENT_WORK_VARIANTS[2]!, ownerId: owner.applicationId };\n}\n\n/** The owner scope of an execution row of `executionResourceType`, read from the row's own owner field. */\nexport function agentWorkOwnerOfExecution(executionResourceType: CoreResourceType, row: Record<string, unknown>): AgentWorkOwnerScope | undefined {\n const variant = AGENT_WORK_VARIANTS.find((candidate) => candidate.executions === executionResourceType);\n const ownerId = variant ? row[variant.ownerField] : undefined;\n if (!variant || typeof ownerId !== 'string' || ownerId.length === 0) return undefined;\n return { [variant.ownerField]: ownerId } as AgentWorkOwnerScope;\n}\n\n/** `items` in consecutive slices of at most `size`, in order (a kept case removal's rows, #2930). */\nfunction chunked<T>(items: readonly T[], size: number): T[][] {\n const chunks: T[][] = [];\n for (let start = 0; start < items.length; start += size) chunks.push(items.slice(start, start + size));\n return chunks;\n}\n\n/** The map key of a case, `resourceType:resourceId`: the one spelling the ledger's `caseKeys` and every join use. */\nexport function agentWorkCaseKey(caseRef: WorkUnitRef): string {\n return `${caseRef.resourceType}:${caseRef.resourceId}`;\n}\n\n/** The map key of a case subject, `resourceType:resourceId`: the spelling of the ledger's `subjectKeys` (#1925). */\nexport function agentWorkSubjectKey(subjectRef: AgentWorkSubjectRef): string {\n return `${subjectRef.resourceType}:${subjectRef.resourceId}`;\n}\n\n/**\n * One work-unit resource's declared case subject field, resolved against the registry (#1925). `subjectResourceType` is\n * absent when the declaration names no foreign key whose relationship the registry can follow: a declaration that\n * cannot be honoured, which every reader treats as \"this case's subject is unknown\" and an export fails closed on.\n */\nexport interface ResolvedCaseSubjectDeclaration {\n readonly caseResourceType: string;\n readonly subjectField: string;\n readonly subjectResourceType?: string;\n}\n\n/** The case subject of one case, as an export reads it. */\nenum CaseSubjectAnswerKind {\n /** The case's resource declares no case subject field: it has no case subject. */\n NO_SUBJECT_DECLARED = 'no_subject_declared',\n /** The declared field holds no value on the row: this case has no case subject. */\n NO_SUBJECT = 'no_subject',\n SUBJECT = 'subject',\n /** The case subject could not be read (the declaration cannot be honoured, or the row is gone): unknown, never \"none\". */\n UNKNOWN = 'unknown',\n}\ntype CaseSubjectAnswer =\n | { readonly kind: CaseSubjectAnswerKind.NO_SUBJECT_DECLARED | CaseSubjectAnswerKind.NO_SUBJECT | CaseSubjectAnswerKind.UNKNOWN }\n | { readonly kind: CaseSubjectAnswerKind.SUBJECT; readonly subjectKey: string };\n\n/** The shape an export reads one record's kept content against, or why it has none (#1923). */\ntype ContentShapeAnswer =\n | { readonly shape: EvaluationContentShape; readonly withheld?: undefined }\n | { readonly shape?: undefined; readonly withheld: EvaluationContentWithholdingReason };\n\n/**\n * One decision to record. `proposal` and `final` are the agent's version and the version the decider kept; they feed\n * the diff statistics and are stored only under the organization's opt-in. `fallbackPaths` are the edited top-level\n * argument NAMES when no final version is known (a repaired record).\n */\nexport interface AgentWorkDecisionWrite {\n readonly owner: AgentWorkOwnerScope;\n readonly decisionRef: string;\n readonly surface: AgentWorkDecisionSurface;\n readonly outcome: HumanDecision_Outcome;\n readonly agentRef: string;\n readonly agentVersion?: string;\n readonly toolName?: string;\n readonly caseRef?: WorkUnitRef | null;\n readonly executionRef?: ExecutionRef;\n readonly taskRef?: string;\n readonly finalWorkProductRef?: AgentWorkProductRef;\n readonly proposal?: unknown;\n readonly final?: unknown;\n readonly fallbackPaths?: readonly string[];\n readonly reasonCode?: string;\n readonly reasonText?: string;\n readonly deciderUserId?: string;\n readonly admittedByRole?: string;\n /** When the proposal was put before the decider — the decision's claim instant, else its request instant (I8). */\n readonly presentedAt: Date;\n readonly decidedAt: Date;\n readonly recordSource: AgentWorkDecisionRecordSource;\n /** The organization the decision was routed in, when there was one: the tenant when no case names one. */\n readonly routeOrganizationId?: string;\n}\n\n/** Whether a write created the record, or found it already there. */\nexport enum AgentWorkRecordResultKind {\n RECORDED = 'recorded',\n ALREADY_RECORDED = 'already_recorded',\n}\n\n/** The execution a settle's marker sits on, so the record's writer can clear it once the record exists. */\nexport interface AgentWorkCorrectionMarker {\n readonly executionResourceType: CoreResourceType;\n readonly executionId: string;\n}\n\n/**\n * The seam the services-registry handler calls when rows are erased or deleted (#1599): a narrow port, so that\n * handler depends on the one method it calls and not on this service's whole surface.\n */\nexport interface AgentWorkCaseRemovalSeam {\n scheduleCaseRemoval(resourceType: ResourceType, rowIds: readonly string[], transaction?: TransactionContext): Promise<void>;\n}\n\n/** What one run of the repair sweep did. */\nexport interface AgentWorkCorrectionRepairResult {\n scanned: number;\n repaired: number;\n cleared: number;\n deferred: number;\n failed: number;\n}\n\n/**\n * The repair sweep's view of the resolution columns: what a settle wrote inside its compare-and-swap (#1594 I4).\n */\nexport type ExecutionResolutionRow = Pick<FlowActorExecution,\n 'executionId' | 'systemRef' | 'caseRef' | 'lastResolvedDecisionRef' | 'decidedByUserId' | 'decidedAt' | 'decisionOutcome'\n | 'decisionToolName' | 'decisionModifiedArgumentNames' | 'pendingCorrectionRecordRef' | 'pendingCorrectionPresentedAt'\n | 'pendingCorrectionOrganizationId' | 'pendingCorrectionAdmittedByRole'> & Record<string, unknown>;\n\n/**\n * Whether an execution row carries what its owed record is written from: an owner, and the resolution its marker names\n * (#1599 I3). The one rule the repair reads, and the one a deletion reads to tell a record that cannot be written YET\n * (keep the row) from one the row can no longer carry (keeping it recovers nothing, #2582).\n */\nexport function owedRecordIsRepairableFromRow(executionResourceType: CoreResourceType, row: ExecutionResolutionRow): boolean {\n const decisionRef = row.pendingCorrectionRecordRef;\n return !!decisionRef\n && !!agentWorkOwnerOfExecution(executionResourceType, row)\n && row.lastResolvedDecisionRef === decisionRef\n && !!row.decisionOutcome\n && !!row.decidedAt;\n}\n\n@injectable()\nexport class AgentWorkDecisionsBackendService implements DecisionTimeSource, AgentWorkCaseRemovalSeam {\n private warnedNoSecret = false;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.Logger) private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.RepositoriesRegistryHandlerService) private readonly repositoriesRegistry: RepositoriesRegistryHandlerBackendService,\n @inject(SAAS_SERVICE_TYPES.ErrorBuilderService) private readonly errorBuilder: ErrorBuilderBackendService,\n /*\n * Everything else is resolved LAZILY through the container: the services-registry handler injects this service\n * (its case-removal seam), and the execution-context creator, the audit trail and the case admission all reach\n * that handler — a constructor dependency on any of them would be a construction cycle.\n */\n @inject(SAAS_SERVICE_TYPES.Container) private readonly container: Container,\n @inject(SAAS_SERVICE_TYPES.AppConfigService) @optional() private readonly appConfig?: AppConfigurationService,\n ) {}\n\n // ─── Recording ────────────────────────────────────────────────────────────\n\n /**\n * Record one decision, and its content when the organization opted in (I4). Idempotent on `decisionRef` (I1).\n * Never throws for a decision that was already recorded; throws only when the store refuses the write, which the\n * settle logs and the repair sweep retries. The content row is written FIRST, so a crash between the two leaves a\n * content row the repair's metadata record then points at, never a record claiming content that does not exist.\n */\n public async recordDecision(\n write: AgentWorkDecisionWrite,\n marker?: AgentWorkCorrectionMarker,\n /**\n * The transaction the record joins (#2865 review F1): a person's erasure repays a conversation's owed record inside\n * its own transaction, so the record and the marker it clears commit or roll back with the erasure. Every read and\n * write below joins it; the decider's standing is read from committed data, which only names an organization.\n */\n options?: { readonly transaction?: TransactionContext },\n ): Promise<AgentWorkRecordResultKind> {\n const { variant, ownerId } = variantOfOwner(write.owner);\n const repositoryOptions = options?.transaction ? { transaction: options.transaction } : undefined;\n const workOrganizationId = await this.workOrganizationOf(write, repositoryOptions);\n const existing = await this.repositoriesRegistry.readUnscopedByKey<AgentWorkDecision>(variant.decisions, { decisionRef: write.decisionRef }, repositoryOptions);\n if (existing) {\n // Review F6: the same reference from ANOTHER owner or tenant is a collision, never a retry of this decision —\n // answering it ALREADY_RECORDED would silently drop the second decision. (An engine settle's reference is a\n // UUID; an output review's is the application's own, which must be unique.)\n if ((existing as Record<string, unknown>)[variant.ownerField] !== ownerId || (existing.workOrganizationId ?? undefined) !== workOrganizationId) {\n throw this.errorBuilder.buildError(ErrorType.CONFLICT, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFLICT,\n context: { message: 'This decision reference is already recorded for another owner or organization; a decision reference must be unique.' },\n });\n }\n if (marker) await this.clearCorrectionMarker(marker, write.decisionRef, repositoryOptions);\n return AgentWorkRecordResultKind.ALREADY_RECORDED;\n }\n\n const key = this.correctionKeyOf(workOrganizationId);\n // An accepted proposal IS the final version: its paths are empty and its two digests equal.\n const final = write.outcome === HumanDecision_Outcome.ACCEPTED && write.final === undefined ? write.proposal : write.final;\n const measure = measureAgentWorkCorrection({\n key: key ?? '',\n ...(write.proposal !== undefined ? { proposal: write.proposal } : {}),\n ...(final !== undefined ? { final } : {}),\n ...(write.fallbackPaths ? { fallbackPaths: write.fallbackPaths } : {}),\n });\n\n // The decider's standing in the tenant the work was done in (#2618, #2722): the representing organization a decision\n // is attributed to, and\n // the one relationship the decider stands there through, whose work the content and the decision then are.\n const decider = await this.standingOfDecider(write.deciderUserId, workOrganizationId);\n const asDecidersWork = <T>(fn: () => Promise<T>): Promise<T> => (decider.relationshipId && workOrganizationId\n ? runWithRelationshipProvenanceFrame({ organizationId: workOrganizationId, relationshipId: decider.relationshipId }, fn)\n : runOutsideRelationshipProvenanceFrame(fn));\n const withContent = write.recordSource !== AgentWorkDecisionRecordSource.ROW_REPAIR\n && AGENT_WORK_DECISION_RATED_OUTCOMES.includes(write.outcome)\n && (measure.proposalJson !== undefined || measure.finalJson !== undefined || !!write.reasonText)\n && await this.contentCaptureHolds(workOrganizationId, write.caseRef ?? undefined);\n if (withContent) {\n // assurance-control: WILDO.PRIVACY.DATA_MINIMIZATION — content is written only under the organization's opt-in (I4).\n await asDecidersWork(() => this.createRow<AgentWorkDecisionContent>(variant.contents, variant.ownerField, ownerId, {\n decisionRef: write.decisionRef,\n ...(write.caseRef ? { caseRef: { resourceType: write.caseRef.resourceType, resourceId: write.caseRef.resourceId } } : {}),\n ...(workOrganizationId ? { workOrganizationId } : {}),\n ...(measure.proposalJson !== undefined ? { proposalJson: measure.proposalJson } : {}),\n ...(measure.finalJson !== undefined ? { finalJson: measure.finalJson } : {}),\n ...(measure.diffJson !== undefined ? { diffJson: measure.diffJson } : {}),\n ...(write.reasonText ? { reasonText: write.reasonText } : {}),\n }, repositoryOptions));\n }\n\n /*\n * #1921 — a reason code says why a decider CORRECTED the agent, so it is recorded only beside an override outcome\n * (modified or rejected). Every door writes through here — the tool approval over the socket and over REST, the\n * actor review, the output review — so this is the one place the invariant holds for all of them; the approval card\n * withholding it on an approval-as-proposed is a convenience, not the control. Dropped rather than refused: the\n * reason is optional evidence, and refusing a valid approval because a reason rode along would stall the decision\n * without making the record any truer than dropping it does.\n */\n const reasonCode = write.reasonCode && AGENT_WORK_DECISION_OVERRIDE_OUTCOMES.includes(write.outcome) ? write.reasonCode : undefined;\n const representingOrganizationId = decider.representingOrganizationId;\n const recorded = await asDecidersWork(async () => this.createRow<AgentWorkDecision>(variant.decisions, variant.ownerField, ownerId, {\n decisionRef: write.decisionRef,\n surface: write.surface,\n outcome: write.outcome,\n ...(workOrganizationId ? { workOrganizationId } : {}),\n ...(representingOrganizationId ? { representingOrganizationId } : {}),\n agentRef: write.agentRef,\n ...(write.agentVersion ? { agentVersion: write.agentVersion } : {}),\n ...(write.toolName ? { toolName: write.toolName } : {}),\n ...(write.caseRef ? { caseRef: { resourceType: write.caseRef.resourceType, resourceId: write.caseRef.resourceId } } : {}),\n ...(write.executionRef ? { executionRef: write.executionRef } : {}),\n ...(write.taskRef ? { taskRef: write.taskRef } : {}),\n ...(write.finalWorkProductRef ? { finalWorkProductRef: write.finalWorkProductRef } : {}),\n modifiedPaths: measure.modifiedPaths,\n ...(measure.editDistance !== undefined ? { editDistance: measure.editDistance } : {}),\n ...(key && measure.proposedDigest ? { proposedDigest: measure.proposedDigest } : {}),\n ...(key && measure.finalDigest ? { finalDigest: measure.finalDigest } : {}),\n ...(reasonCode ? { reasonCode } : {}),\n ...(write.deciderUserId ? { deciderUserId: write.deciderUserId } : {}),\n ...(write.admittedByRole ? { admittedByRole: write.admittedByRole } : {}),\n presentedAt: write.presentedAt,\n decidedAt: write.decidedAt,\n recordSource: write.recordSource,\n contentRecorded: withContent || await this.contentRowExists(variant.contents, write.decisionRef, repositoryOptions),\n }, repositoryOptions));\n if (marker) await this.clearCorrectionMarker(marker, write.decisionRef, repositoryOptions);\n return recorded ? AgentWorkRecordResultKind.RECORDED : AgentWorkRecordResultKind.ALREADY_RECORDED;\n }\n\n /**\n * `recordOutputReview` — an application tells the engine a decider reviewed output an agent drafted into the\n * application's own rows. The case is admitted only if it is a readable row of a work-unit resource; the reason code\n * only if the application declares it. Idempotent on the application's `decisionRef`. Not sealed, and why:\n * `AGENT_WORK_OUTPUT_REVIEW_SEAL` (#2906).\n */\n public async recordOutputReview(input: AgentWorkOutputReviewInput, executionContext: ExecutionContext<any>): Promise<AgentWorkRecordResultKind> {\n const parsed = AgentWorkOutputReviewInputSchema.safeParse(input);\n if (!parsed.success) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { reason: 'agent_work_output_review_invalid', issues: parsed.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`) },\n });\n }\n const review = parsed.data;\n if (review.reasonCode && !this.reasonCodeIsDeclared(review.reasonCode)) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { reason: 'agent_work_reason_code_not_declared' },\n });\n }\n const organizationId = executionContext.initiatorIds?.organizationId;\n const userId = executionContext.initiatorIds?.userId;\n let caseRef: WorkUnitRef | undefined;\n if (review.caseRef) {\n const workUnits = this.container.get<WorkUnitCaseBackendService>(SAAS_SERVICE_TYPES.WorkUnitCaseService);\n const admission = await workUnits.admitClientCaseRef({\n executionType: executionContext.executionType,\n initiatorIds: executionContext.initiatorIds ?? null,\n initiatorRoles: [...(executionContext.initiatorRoles ?? [])],\n }, organizationId, review.caseRef);\n if (admission.admitted === false) {\n throw this.errorBuilder.buildError(ErrorType.NOT_FOUND, executionContext, {\n customMessageReference: ErrorCustomMessageReference.NOT_FOUND,\n context: { reason: 'agent_work_output_review_case_not_admitted', refusal: admission.reason },\n });\n }\n caseRef = admission.caseRef;\n }\n const caseOrganizationId = caseRef ? await this.caseOrganizationOf(caseRef) : undefined;\n const tenant = caseOrganizationId ?? organizationId;\n const owner: AgentWorkOwnerScope | undefined = tenant ? { organizationId: tenant } : userId ? { userId } : undefined;\n if (!owner) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { reason: 'agent_work_output_review_has_no_owner' },\n });\n }\n const decidedAt = new Date();\n return this.recordDecision({\n owner,\n decisionRef: review.decisionRef,\n surface: AgentWorkDecisionSurface.OUTPUT_REVIEW,\n outcome: review.outcome,\n agentRef: review.agentRef,\n ...(review.agentVersion ? { agentVersion: review.agentVersion } : {}),\n ...(caseRef ? { caseRef } : {}),\n ...(review.taskRef ? { taskRef: review.taskRef } : {}),\n ...(review.finalWorkProductRef ? { finalWorkProductRef: review.finalWorkProductRef } : {}),\n ...(review.proposal !== undefined ? { proposal: review.proposal } : {}),\n ...(review.final !== undefined ? { final: review.final } : {}),\n ...(review.reasonCode ? { reasonCode: review.reasonCode } : {}),\n ...(review.reasonText ? { reasonText: review.reasonText } : {}),\n ...(userId ? { deciderUserId: userId } : {}),\n presentedAt: review.presentedAt ? new Date(review.presentedAt) : decidedAt,\n decidedAt,\n recordSource: AgentWorkDecisionRecordSource.SETTLEMENT,\n ...(organizationId ? { routeOrganizationId: organizationId } : {}),\n });\n }\n\n /** Whether the application declares `reasonCode` (`agentWorkReview.reasonCodes`). Nothing declared: nothing is. */\n public reasonCodeIsDeclared(reasonCode: string): boolean {\n return this.declaredReasonCodes().includes(reasonCode);\n }\n\n /**\n * The application's reason-code vocabulary (`agentWorkReview.reasonCodes`), in its declared order (#1921) — what a\n * reviewer's reason picker offers on every decision that reviews agent work. The same list {@link reasonCodeIsDeclared}\n * checks an answer against, so a code the picker offers is never refused. Empty when nothing is declared.\n */\n public declaredReasonCodes(): readonly string[] {\n return this.reviewConfig()?.reasonCodes ?? [];\n }\n\n // ─── Crash repair (I3) ────────────────────────────────────────────────────\n\n /**\n * Write the record of every settled decision whose settle did not get to it, from the execution row's resolution\n * columns, and clear the marker. `ROW_REPAIR`, metadata only. A row whose resolution names another decision than its\n * marker is left and logged: the columns would describe the wrong decision.\n */\n public async repairPendingCorrectionRecords(now: Date = new Date()): Promise<AgentWorkCorrectionRepairResult> {\n const result: AgentWorkCorrectionRepairResult = { scanned: 0, repaired: 0, cleared: 0, deferred: 0, failed: 0 };\n for (const variant of AGENT_WORK_VARIANTS) {\n // Paged by key (review F11): a row that cannot be repaired stays marked and would otherwise sort first forever,\n // starving every row after it.\n let after: string | undefined;\n for (;;) {\n let rows: ExecutionResolutionRow[];\n try {\n rows = await this.repositoriesRegistry.findManyForInfrastructure<ExecutionResolutionRow>(\n variant.executions,\n after ? { $and: [{ pendingCorrectionRecordRef: { $ne: null } }, { _id: { $gt: after } }] } : { pendingCorrectionRecordRef: { $ne: null } },\n undefined,\n undefined,\n { sort: [{ field: '_id', order: SortOrder.ASC }], limit: PAGE_SIZE },\n );\n } catch (error) {\n this.logger.error('[AgentWorkDecisions] The correction repair sweep could not list marked executions for a scope', {\n resourceType: variant.executions, reason: describeCaughtError(error),\n });\n break;\n }\n for (const row of rows) {\n result.scanned += 1;\n const decidedAt = row.decidedAt ? new Date(row.decidedAt) : undefined;\n if (decidedAt && now.getTime() - decidedAt.getTime() < REPAIR_GRACE_MS) { result.deferred += 1; continue; }\n const outcome = await this.repairOwedRecordOfExecution(variant.executions, row);\n if (outcome === AgentWorkRecordResultKind.RECORDED) result.repaired += 1;\n else if (outcome === AgentWorkRecordResultKind.ALREADY_RECORDED) result.cleared += 1;\n else result.failed += 1;\n }\n if (rows.length < PAGE_SIZE) break;\n after = String(rows[rows.length - 1]!._id);\n }\n }\n // Logged unconditionally, like every sweep here: a sweep that silently finds nothing reads as one that stopped.\n this.logger.info('[AgentWorkDecisions] Correction repair sweep complete', { ...result });\n return result;\n }\n\n /**\n * Write the record an execution row still OWES, from its resolution columns (`ROW_REPAIR`, metadata only), and clear\n * the marker. The repair sweep calls it; so does a settle about to OVERWRITE the resolution columns of a row whose\n * previous decision is still owed (review F3) — after that write the columns would describe the new decision and the\n * old record could never be repaired. `undefined` when the row owes nothing, or cannot be repaired (logged).\n */\n public async repairOwedRecordOfExecution(\n executionResourceType: CoreResourceType,\n row: ExecutionResolutionRow,\n /**\n * A person's ERASURE repays the record (#2865 review F1): it joins the erasure's transaction, leaves the erased\n * person off the record when they were its decider, and THROWS instead of answering `undefined`, because a failed\n * write inside a transaction has already aborted it and the erasure must fail rather than carry on inside it.\n */\n erasure?: { readonly transaction?: TransactionContext; readonly erasedUserId: string },\n ): Promise<AgentWorkRecordResultKind | undefined> {\n const decisionRef = row.pendingCorrectionRecordRef;\n if (!decisionRef) return undefined;\n const decidedAt = row.decidedAt ? new Date(row.decidedAt) : undefined;\n const owner = agentWorkOwnerOfExecution(executionResourceType, row);\n if (!owner || !decidedAt || !owedRecordIsRepairableFromRow(executionResourceType, row)) {\n this.logger.error('[AgentWorkDecisions] A marked execution does not carry the resolution its marker names; the record cannot be repaired from it', {\n resourceType: executionResourceType, executionId: row.executionId, decisionRef, lastResolvedDecisionRef: row.lastResolvedDecisionRef,\n });\n return undefined;\n }\n try {\n return await this.recordDecision({\n owner,\n decisionRef,\n surface: AgentWorkDecisionSurface.TOOL_CALL_APPROVAL,\n outcome: row.decisionOutcome as HumanDecision_Outcome,\n agentRef: row.systemRef,\n ...(row.decisionToolName ? { toolName: row.decisionToolName } : {}),\n ...(row.caseRef ? { caseRef: row.caseRef } : {}),\n executionRef: { kind: ExecutionRefKind.CONVERSATIONAL_EXECUTION, id: row.executionId },\n fallbackPaths: row.decisionModifiedArgumentNames ?? [],\n ...(row.decidedByUserId && row.decidedByUserId !== erasure?.erasedUserId ? { deciderUserId: row.decidedByUserId } : {}),\n // Review F4: the route columns are cleared by the settle; the marker kept what the record needs of them.\n ...(row.pendingCorrectionAdmittedByRole ? { admittedByRole: row.pendingCorrectionAdmittedByRole } : {}),\n ...(row.pendingCorrectionOrganizationId ? { routeOrganizationId: row.pendingCorrectionOrganizationId } : {}),\n presentedAt: row.pendingCorrectionPresentedAt ? new Date(row.pendingCorrectionPresentedAt) : decidedAt,\n decidedAt,\n recordSource: AgentWorkDecisionRecordSource.ROW_REPAIR,\n }, { executionResourceType, executionId: row.executionId }, erasure?.transaction ? { transaction: erasure.transaction } : undefined);\n } catch (error) {\n if (erasure) throw error;\n this.logger.error('[AgentWorkDecisions] An owed decision record could not be repaired; the marker stays', {\n resourceType: executionResourceType, executionId: row.executionId, decisionRef, reason: describeCaughtError(error),\n });\n return undefined;\n }\n }\n\n /** Clear an execution's marker, only while it still names this decision (a compare-and-swap). Never throws. */\n private async clearCorrectionMarker(marker: AgentWorkCorrectionMarker, decisionRef: string, options?: RepositoryOptions): Promise<void> {\n try {\n await this.repositoriesRegistry.bulkUpdateForInfrastructure(\n marker.executionResourceType,\n { executionId: marker.executionId, pendingCorrectionRecordRef: decisionRef },\n { clear: ['pendingCorrectionRecordRef', 'pendingCorrectionPresentedAt', 'pendingCorrectionOrganizationId', 'pendingCorrectionAdmittedByRole'] },\n undefined,\n options,\n );\n } catch (error) {\n // Inside a transaction the failure may already have aborted it: rethrow, so its owner fails rather than writing on\n // (the engine's one rule for a caught write failure, #3093).\n if (writeFailureEndsTheOperation(error, options?.transaction !== undefined)) throw error;\n // The record exists; a marker left behind only makes the repair sweep find it again and leave it (idempotent).\n this.logger.warn('[AgentWorkDecisions] A correction marker could not be cleared; the repair sweep will clear it', {\n resourceType: marker.executionResourceType, executionId: marker.executionId, reason: describeCaughtError(error),\n });\n }\n }\n\n // ─── The override rate (D6, I6) ───────────────────────────────────────────\n\n /**\n * The override rate per group over a window. LAPSED, WITHDRAWN and REQUESTER_AUTHORITY_LAPSED are counted as\n * `notDecided` and never enter the rate (I6). Metadata only: no content is read.\n */\n public async summarizeOverrideRate(request: AgentWorkOverrideRateRequest): Promise<AgentWorkOverrideRate> {\n const filter: Record<string, unknown> = {\n decidedAt: { $gte: new Date(request.from), $lt: new Date(request.to) },\n // An organization's override rate (#2618): the decisions on work done in it, and the decisions its own people took\n // in the organizations it represents in. A representing organization reads its people's rate across them; a\n // granting organization reads the decisions taken on its own cases, whoever took them.\n ...(request.organizationId ? { $or: [{ workOrganizationId: request.organizationId }, { representingOrganizationId: request.organizationId }] } : {}),\n ...(request.agentRef ? { agentRef: request.agentRef } : {}),\n };\n const groups = new Map<string, AgentWorkOverrideRateGroup>();\n for (const row of await this.readDecisions(filter)) {\n const { mapKey, key } = overrideRateGroupKeyOf(row, request.groupBy);\n const group = groups.get(mapKey) ?? { key, accepted: 0, acceptedWithModifications: 0, rejected: 0, notDecided: 0, overrideRate: null };\n switch (row.outcome) {\n case HumanDecision_Outcome.ACCEPTED: group.accepted += 1; break;\n case HumanDecision_Outcome.ACCEPTED_WITH_MODIFICATIONS: group.acceptedWithModifications += 1; break;\n case HumanDecision_Outcome.REJECTED: group.rejected += 1; break;\n case HumanDecision_Outcome.LAPSED:\n case HumanDecision_Outcome.WITHDRAWN:\n case HumanDecision_Outcome.REQUESTER_AUTHORITY_LAPSED:\n group.notDecided += 1; break;\n }\n groups.set(mapKey, group);\n }\n return {\n window: { from: request.from, to: request.to },\n groupBy: request.groupBy,\n groups: [...groups.values()].map((group) => ({ ...group, overrideRate: agentWorkOverrideRate(group) })),\n };\n }\n\n /**\n * Decision time per case (#1598's `DecisionTimeSource`): the decisions a person took on each case and\n * `Σ (decidedAt − presentedAt)`. Only decisions someone made count; a lapse is the absence of review, not review.\n */\n public async reviewTimeByCase(caseRefs: readonly WorkUnitRef[], options?: { readonly representingOrganizationId?: string }): Promise<ReadonlyMap<string, { decisionCount: number; reviewDurationMs: number }>> {\n const result = new Map<string, { decisionCount: number; reviewDurationMs: number }>();\n if (caseRefs.length === 0) return result;\n const cases = {\n $or: caseRefs.map((caseRef) => ({ 'caseRef.resourceType': caseRef.resourceType, 'caseRef.resourceId': caseRef.resourceId })),\n };\n // A representing organization's own review time only (#2618): another one working the same case keeps its own.\n const filter = options?.representingOrganizationId\n ? { $and: [cases, relationshipOwnWorkFilter(options.representingOrganizationId, RelationshipOwnWorkTenantField.DECISION)] }\n : cases;\n for (const row of await this.readDecisions(filter)) {\n if (!row.caseRef || !AGENT_WORK_DECISION_RATED_OUTCOMES.includes(row.outcome)) continue;\n const key = agentWorkCaseKey(row.caseRef);\n const entry = result.get(key) ?? { decisionCount: 0, reviewDurationMs: 0 };\n entry.decisionCount += 1;\n entry.reviewDurationMs += Math.max(0, new Date(row.decidedAt).getTime() - new Date(row.presentedAt).getTime());\n result.set(key, entry);\n }\n return result;\n }\n\n // ─── The evaluation export (D7, I7) ───────────────────────────────────────\n\n /**\n * Export one organization's decisions on one agent's proposals over a window, as pseudonymised JSON Lines, and\n * record the export on the ledger. Refused and audited without an ACTIVE authorisation of that organization (I7).\n *\n * This is the ONE door an evaluation dataset leaves through, so both controls live here: kept content is minimised\n * by its declared shape (#1923, {@link minimisedContentOf}), and no case of an excluded case subject leaves (#1925). It is\n * refused as a CONFIGURATION error when an excluded case subject can no longer be found through a declaration.\n *\n * assurance-control: WILDO.PRIVACY.SECONDARY_USE_AUTHORIZATION — no export leaves without an ACTIVE authorisation naming\n * the basis it rests on.\n * assurance-control: WILDO.PRIVACY.COLLECTION_DATA_EXPORT — every export and every refusal is on the audit trail.\n */\n public async exportEvaluationDataset(request: EvaluationDatasetExportRequest, executionContext: ExecutionContext<any>): Promise<EvaluationDatasetExportResult> {\n const actorUserId = executionContext.initiatorIds?.userId;\n const authorization = await this.repositoriesRegistry.readUnscopedByKey<EvaluationExportAuthorization>(\n CoreResourceType.EVALUATION_EXPORT_AUTHORIZATIONS, { organizationId: request.organizationId },\n );\n // An ACTIVE row always carries its basis (the write that would leave one without it is refused); a row that somehow\n // does not is treated as no authorisation, never exported under an unnamed basis.\n if (!authorization || authorization.status !== EvaluationExportAuthorizationStatus.ACTIVE || !authorization.basis) {\n // NOT_GRANTED (the row the settings page creates) is \"nobody granted one\", exactly like no row.\n const reason = authorization?.status === EvaluationExportAuthorizationStatus.REVOKED\n ? EvaluationDatasetExportRefusalReason.AUTHORIZATION_REVOKED\n : EvaluationDatasetExportRefusalReason.NO_AUTHORIZATION;\n await this.auditLogs()?.logEvaluationDatasetExportRefused({\n organizationId: request.organizationId, agentRef: request.agentRef, reason, ...(actorUserId ? { attemptedByUserId: actorUserId } : {}),\n }, executionContext).catch((error: unknown) => this.logger.error('[AgentWorkDecisions] A refused export could not be audited', { reason: describeCaughtError(error) }));\n throw this.errorBuilder.buildError(ErrorType.AUTHORIZATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.AUTHORIZATIONS_ACCESS_DENIED,\n context: { reason: `evaluation_export_refused_${reason}` },\n });\n }\n\n const pseudonymPurposeKey = applicationSymmetricKeyOf(this.appConfig, CryptoKey_Purpose.EVALUATION_PSEUDONYM);\n if (!pseudonymPurposeKey) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: 'An evaluation export pseudonymises under the evaluation-pseudonym key, and this runtime holds none.' },\n });\n }\n const pseudonymKey = deriveEvaluationPseudonymKey(pseudonymPurposeKey, request.organizationId);\n const excluded = new Set(authorization.excludedCaseRefs.map(agentWorkCaseKey));\n const excludedSubjects = new Set((authorization.excludedSubjectRefs ?? []).map(agentWorkSubjectKey));\n const consented = new Set(authorization.subjectConsents.map((consent) => agentWorkCaseKey(consent.caseRef)));\n const privilegedTypes = new Set(this.reviewConfig()?.privilegedCaseResourceTypes ?? []);\n // Art. 6(4)(c): a case whose resource declares special-category (Art. 9) or criminal-offence data leaves only with\n // its case subject's recorded consent too — the same door as privileged work, read from the resource's own schema.\n const needsConsent = (resourceType: string): boolean => privilegedTypes.has(resourceType) || this.declaresRestrictedPersonalData(resourceType);\n\n const caseSubjects = this.resolvedCaseSubjectDeclarations();\n // An exclusion no declaration resolves any more (the application removed or broke its case subject field) would silently\n // stop excluding: refuse the export instead, so a case subject's opt-out never lapses because a configuration changed.\n const unresolvable = this.undeclaredExcludedSubjectRefs(authorization.excludedSubjectRefs ?? [], caseSubjects);\n if (unresolvable.length > 0) {\n this.logger.error('[AgentWorkDecisions] An export authorisation excludes case subjects no case-subject declaration resolves; the export is refused', {\n organizationId: request.organizationId, subjectResourceTypes: [...new Set(unresolvable.map((subjectRef) => subjectRef.resourceType))],\n });\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: 'The export authorisation excludes case subjects of a resource no work-unit resource declares as its case subject (agentWorkReview.caseSubjects), so their cases cannot be found; the export is refused rather than run without the exclusion.' },\n });\n }\n const subjectOfCase = new Map<string, CaseSubjectAnswer>();\n const subjectAnswerOf = async (caseRef: WorkUnitRef): Promise<CaseSubjectAnswer> => {\n const caseKey = agentWorkCaseKey(caseRef);\n const cached = subjectOfCase.get(caseKey);\n if (cached) return cached;\n const answer = await this.subjectOfCase(caseRef, caseSubjects.get(caseRef.resourceType));\n subjectOfCase.set(caseKey, answer);\n return answer;\n };\n\n const candidates = (await this.readDecisions({\n workOrganizationId: request.organizationId,\n agentRef: request.agentRef,\n decidedAt: { $gte: new Date(request.from), $lt: new Date(request.to) },\n })).filter((row) => {\n if (!AGENT_WORK_DECISION_RATED_OUTCOMES.includes(row.outcome)) return false;\n if (!row.caseRef) return true;\n const caseKey = agentWorkCaseKey(row.caseRef);\n if (excluded.has(caseKey)) return false;\n // A privileged case, or one holding special-category or criminal-offence data, leaves only with its case subject's\n // recorded consent (SRA 6.3, ABA 512; GDPR Art. 6(4)(c), Art. 9(2)(a)).\n return !needsConsent(row.caseRef.resourceType) || consented.has(caseKey);\n });\n /*\n * #1925 — a case subject the organization excluded leaves in no export: every case whose declared case subject field names it,\n * opened before or after the exclusion, is read at THIS export. This is the one chokepoint every export passes, so\n * an exclusion cannot be honoured by one door and missed by another. Fail closed: while any case subject is excluded, a\n * case whose case subject cannot be read (its row is gone, or the declaration cannot be honoured) is left out, never\n * assumed to belong to nobody.\n *\n * assurance-control: WILDO.PRIVACY.SECONDARY_USE_AUTHORIZATION — a case subject's opt-out from evaluation use holds for all\n * of its cases, present and future.\n */\n const rows: AgentWorkDecision[] = [];\n for (const row of candidates) {\n if (row.caseRef && excludedSubjects.size > 0) {\n const subject = await subjectAnswerOf(row.caseRef);\n if (subject.kind === CaseSubjectAnswerKind.UNKNOWN) continue;\n if (subject.kind === CaseSubjectAnswerKind.SUBJECT && excludedSubjects.has(subject.subjectKey)) continue;\n }\n rows.push(row);\n }\n\n const lines: string[] = [];\n const caseKeys = new Set<string>();\n const subjectKeys = new Set<string>();\n const pseudonymOf = (identifier: string): string => pseudonymiseIdentifier(pseudonymKey, identifier);\n for (const row of rows) {\n const content = row.contentRecorded ? await this.readContent(row.decisionRef, request.organizationId) : undefined;\n if (row.caseRef) {\n caseKeys.add(agentWorkCaseKey(row.caseRef));\n // The ledger records each case's subject, so a later opt-out of that case subject finds this dataset (#1925).\n const subject = await subjectAnswerOf(row.caseRef);\n if (subject.kind === CaseSubjectAnswerKind.SUBJECT) subjectKeys.add(subject.subjectKey);\n }\n // The identifiers kept content may carry (a tool call names the case it acts on), replaced by their pseudonyms.\n const known = new Map<string, string>(\n [row.caseRef?.resourceId, row.workOrganizationId, row.deciderUserId, row.executionRef?.id, row.taskRef, row.finalWorkProductRef?.resourceId]\n .filter((identifier): identifier is string => typeof identifier === 'string' && identifier.length > 0)\n .map((identifier) => [identifier, pseudonymiseIdentifier(pseudonymKey, identifier)]),\n );\n const kept = content?.proposalJson || content?.finalJson ? this.minimisedContentOf(row, content, pseudonymOf, known) : undefined;\n // Minimisation: what evaluation needs. No decider, no organization; every identifier a pseudonym.\n lines.push(JSON.stringify({\n record: pseudonymiseIdentifier(pseudonymKey, row.decisionRef),\n ...(row.caseRef ? { case: pseudonymiseIdentifier(pseudonymKey, agentWorkCaseKey(row.caseRef)) } : {}),\n agentRef: row.agentRef,\n ...(row.agentVersion ? { agentVersion: row.agentVersion } : {}),\n ...(row.toolName ? { toolName: row.toolName } : {}),\n surface: row.surface,\n outcome: row.outcome,\n modifiedPaths: exportedModifiedPathsOf(row.modifiedPaths ?? [], kept),\n ...(row.editDistance !== undefined ? { editDistance: row.editDistance } : {}),\n ...(row.reasonCode ? { reasonCode: row.reasonCode } : {}),\n reviewDurationMs: Math.max(0, new Date(row.decidedAt).getTime() - new Date(row.presentedAt).getTime()),\n ...(kept && kept.withheld === undefined ? {\n ...(kept.proposal !== undefined ? { proposal: kept.proposal } : {}),\n ...(kept.final !== undefined ? { final: kept.final } : {}),\n ...(kept.diff !== undefined ? { diff: kept.diff } : {}),\n } : {}),\n ...(kept?.withheld ? { contentWithheld: kept.withheld } : {}),\n }));\n }\n\n const exportedAt = new Date();\n const ledger = await this.createRow<EvaluationDatasetExport>(CoreResourceType.EVALUATION_DATASET_EXPORTS, 'organizationId', request.organizationId, {\n ...(actorUserId ? { exportedByUserId: actorUserId } : {}),\n exportedAt,\n authorizationId: authorization._id,\n basis: authorization.basis,\n agentRef: request.agentRef,\n windowFrom: new Date(request.from),\n windowTo: new Date(request.to),\n decisionRefs: rows.map((row) => row.decisionRef),\n caseKeys: [...caseKeys],\n subjectKeys: [...subjectKeys],\n recordCount: rows.length,\n pseudonymisationVersion: EVALUATION_PSEUDONYMISATION_VERSION,\n destination: request.destination,\n });\n const exportId = ledger?._id;\n if (!exportId) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: { reason: 'evaluation_export_ledger_not_written' },\n });\n }\n await this.auditLogs()?.logEvaluationDatasetExported({\n exportId, organizationId: request.organizationId, agentRef: request.agentRef, basis: authorization.basis, recordCount: rows.length,\n windowFrom: request.from, windowTo: request.to, destination: request.destination, ...(actorUserId ? { exportedByUserId: actorUserId } : {}),\n }, executionContext);\n return { exportId, recordCount: rows.length, jsonl: lines.join('\\n'), pseudonymisationVersion: EVALUATION_PSEUDONYMISATION_VERSION };\n }\n\n // ─── Erasure (D5, D7) ─────────────────────────────────────────────────────\n\n /**\n * Rows of a work-unit resource were erased or deleted: scrub the content kept about them, in every scope, and mark\n * every dataset that exported them. The decision records survive — they are the evidence that the work was\n * supervised — and carry no content. Registered after `transaction` commits when there is one: a rolled-back\n * erasure keeps its content. A no-op for a resource that is not a work unit.\n *\n * Called from every delete the engine performs on a row: the services-registry handler's two row-removal seams\n * (service-tier deletes and cascades, and the erasure scrub), the `.ttl()` retention sweep's raw delete and the SYNC\n * seed's orphan delete. A native MongoDB TTL index deletes rows nothing in the engine observes, and is not covered.\n *\n * assurance-control: WILDO.PRIVACY.ERASURE_PROPAGATION — a case's erasure reaches the corrections kept about it.\n * assurance-control: WILDO.PRIVACY.SECONDARY_USE_AUTHORIZATION — and marks the datasets that carried them.\n */\n public async scheduleCaseRemoval(resourceType: ResourceType, rowIds: readonly string[], transaction?: TransactionContext): Promise<void> {\n if (rowIds.length === 0) return;\n let isWorkUnit = false;\n try {\n isWorkUnit = this.container.get<WorkUnitCaseBackendService>(SAAS_SERVICE_TYPES.WorkUnitCaseService).isWorkUnitResourceType(String(resourceType));\n } catch {\n isWorkUnit = false;\n }\n if (!isWorkUnit) return;\n // When the rows went: a late scrub (below) marks the datasets as of the deletion, as this one does.\n const removedAt = new Date();\n const reportFailure = (error: unknown): void => {\n this.logger.error('[AgentWorkDecisions] The content kept about an erased case could not be scrubbed', {\n resourceType, rowCount: rowIds.length, reason: describeCaughtError(error),\n });\n };\n const run = async (): Promise<void> => {\n try {\n await this.removeCaseContent(String(resourceType), rowIds, EvaluationDatasetInvalidationReason.SUBJECT_ERASURE, removedAt);\n } catch (error) {\n reportFailure(error);\n }\n };\n if (!transaction) {\n await run();\n return;\n }\n /*\n * #2930: capturable. Under an attempt its caller asked to capture (a purge the organization-purge sweep runs), the rows'\n * ids are kept in the post-commit effect outbox with the commit, and the caller's next run scrubs them once when this\n * effect never ran: the scrub is an erasure's propagation, and must not be lost to a commit whose outcome was never\n * learned. Idempotent (`removeCaseContent`: a scrubbed content row clears nothing more, a marked dataset is not marked\n * again), so a scrub repeated after a crash between the scrub and its row's claim changes nothing. Kept in rows of at\n * most `AGENT_WORK_CASE_REMOVAL_ROWS_PER_CAPTURED_EFFECT` ids, so a large purge keeps bounded rows.\n */\n registerTransactionPostCommitEffect(transaction, capturablePostCommitEffect({\n key: ['agent-work-case-removal', String(resourceType), ...[...rowIds].sort()].join(':'),\n execute: run,\n capture: idempotentSideEffectCapture({\n kind: CapturedPostCommitEffectKind.AGENT_WORK_CASE_REMOVAL,\n rows: () => chunked(rowIds, AGENT_WORK_CASE_REMOVAL_ROWS_PER_CAPTURED_EFFECT)\n .map((chunk) => ({ payload: { resourceType: String(resourceType), rowIds: chunk, removedAt } })),\n run: (payload) => this.removeCaseContent(payload.resourceType, payload.rowIds, EvaluationDatasetInvalidationReason.SUBJECT_ERASURE, payload.removedAt),\n onFailure: reportFailure,\n }),\n }));\n }\n\n /**\n * Scrub the case's content in every scope, and mark every dataset that exported one of these cases. Idempotent: a\n * scrubbed content row has nothing left to clear, and a dataset already marked keeps its first mark. `invalidatedAt` is\n * when the cases went (#2930: a scrub delivered late by a sweep marks as of the deletion); absent, now.\n */\n public async removeCaseContent(\n resourceType: string,\n rowIds: readonly string[],\n reason: EvaluationDatasetInvalidationReason,\n invalidatedAt: Date = new Date(),\n ): Promise<{ contentsScrubbed: number; datasetsMarked: number }> {\n let contentsScrubbed = 0;\n let datasetsMarked = 0;\n for (const resourceId of rowIds) {\n for (const variant of AGENT_WORK_VARIANTS) {\n contentsScrubbed += await this.repositoriesRegistry.bulkUpdateForInfrastructure(\n variant.contents,\n { 'caseRef.resourceType': resourceType, 'caseRef.resourceId': resourceId },\n { clear: ['proposalJson', 'finalJson', 'diffJson', 'reasonText'] },\n );\n }\n datasetsMarked += await this.repositoriesRegistry.bulkUpdateForInfrastructure(\n CoreResourceType.EVALUATION_DATASET_EXPORTS,\n { caseKeys: `${resourceType}:${resourceId}`, invalidatedAt: null },\n { set: { invalidatedAt, invalidationReason: reason } },\n );\n }\n if (contentsScrubbed > 0 || datasetsMarked > 0) {\n this.logger.info('[AgentWorkDecisions] An erased case\\'s corrections were scrubbed and its datasets marked', { resourceType, contentsScrubbed, datasetsMarked });\n }\n return { contentsScrubbed, datasetsMarked };\n }\n\n /**\n * An organization's export authorisation changed: mark every dataset a withdrawn basis no longer covers\n * (`CONSENT_WITHDRAWN`, #1599 D7), found through the ledger. A revocation marks every dataset exported under the\n * authorisation; a case subject consent removed, or a case newly walled off, marks the datasets that carried that case; a\n * case subject newly excluded (#1925) marks the datasets that carried any of its cases. A dataset already marked keeps its\n * first reason. Returns how many were marked.\n *\n * assurance-control: WILDO.PRIVACY.SECONDARY_USE_AUTHORIZATION — a withdrawn basis reaches every dataset exported under it.\n */\n public async invalidateDatasetsForAuthorizationChange(\n previous: Pick<EvaluationExportAuthorization, 'status' | 'subjectConsents' | 'excludedCaseRefs'> & Partial<Pick<EvaluationExportAuthorization, 'excludedSubjectRefs'>> | undefined,\n next: Pick<EvaluationExportAuthorization, '_id' | 'organizationId' | 'status' | 'subjectConsents' | 'excludedCaseRefs'> & Partial<Pick<EvaluationExportAuthorization, 'excludedSubjectRefs'>>,\n ): Promise<number> {\n if (!previous) return 0;\n const mark = { set: { invalidatedAt: new Date(), invalidationReason: EvaluationDatasetInvalidationReason.CONSENT_WITHDRAWN } };\n let marked = 0;\n // Any exit from ACTIVE withdraws the basis. The write path admits only REVOKED (NOT_GRANTED is refused once a row was\n // granted), and this reads the transition rather than the target so a future status cannot bypass the marking.\n if (previous.status === EvaluationExportAuthorizationStatus.ACTIVE && next.status !== EvaluationExportAuthorizationStatus.ACTIVE) {\n marked += await this.repositoriesRegistry.bulkUpdateForInfrastructure(\n CoreResourceType.EVALUATION_DATASET_EXPORTS, { organizationId: next.organizationId, authorizationId: next._id, invalidatedAt: null }, mark,\n );\n }\n const stillConsented = new Set((next.subjectConsents ?? []).map((consent) => agentWorkCaseKey(consent.caseRef)));\n const previouslyExcluded = new Set((previous.excludedCaseRefs ?? []).map(agentWorkCaseKey));\n const withdrawn = new Set([\n ...(previous.subjectConsents ?? []).map((consent) => agentWorkCaseKey(consent.caseRef)).filter((key) => !stillConsented.has(key)),\n ...(next.excludedCaseRefs ?? []).map(agentWorkCaseKey).filter((key) => !previouslyExcluded.has(key)),\n ]);\n for (const caseKey of withdrawn) {\n marked += await this.repositoriesRegistry.bulkUpdateForInfrastructure(\n CoreResourceType.EVALUATION_DATASET_EXPORTS, { organizationId: next.organizationId, caseKeys: caseKey, invalidatedAt: null }, mark,\n );\n }\n /*\n * #1925 — a case subject newly excluded withdraws every dataset that carried one of its cases, found two ways: through the\n * ledger's `subjectKeys` (the case subject of each case as it stood when exported), and through the case subject's CURRENT cases'\n * `caseKeys`. The second reaches a dataset exported before the application declared its case subject field, or while the\n * case's subject could not be read (review F3): the ledger then recorded no case subject, and the first way alone would\n * fail open. Removing a case subject from the exclusion marks nothing.\n */\n const previouslyExcludedSubjects = new Set((previous.excludedSubjectRefs ?? []).map(agentWorkSubjectKey));\n const newlyExcludedSubjects = (next.excludedSubjectRefs ?? []).filter((subjectRef) => !previouslyExcludedSubjects.has(agentWorkSubjectKey(subjectRef)));\n for (const subjectRef of newlyExcludedSubjects) {\n marked += await this.repositoriesRegistry.bulkUpdateForInfrastructure(\n CoreResourceType.EVALUATION_DATASET_EXPORTS, { organizationId: next.organizationId, subjectKeys: agentWorkSubjectKey(subjectRef), invalidatedAt: null }, mark,\n );\n for (const caseKey of await this.currentCaseKeysOfSubject(subjectRef)) {\n marked += await this.repositoriesRegistry.bulkUpdateForInfrastructure(\n CoreResourceType.EVALUATION_DATASET_EXPORTS, { organizationId: next.organizationId, caseKeys: caseKey, invalidatedAt: null }, mark,\n );\n }\n }\n if (marked > 0) this.logger.info('[AgentWorkDecisions] Datasets a withdrawn export basis no longer covers were marked', { organizationId: next.organizationId, marked });\n return marked;\n }\n\n // ─── Internals ────────────────────────────────────────────────────────────\n\n // ─── Case subjects (#1925) ──────────────────────────────────────────────────────\n\n /**\n * The application's case-subject declarations (`agentWorkReview.caseSubjects`), each resolved to its case subject resource:\n * the resource the declared field's relationship points at. A declaration whose field is not a foreign key of the\n * case resource, or whose relationship cannot be followed, resolves to no case subject resource and is logged.\n */\n public resolvedCaseSubjectDeclarations(): ReadonlyMap<string, ResolvedCaseSubjectDeclaration> {\n const resolved = new Map<string, ResolvedCaseSubjectDeclaration>();\n let registry: ResourcesRegistryBackendService | undefined;\n try {\n registry = this.container.get<ResourcesRegistryBackendService>(SAAS_SERVICE_TYPES.ResourceRegistryService);\n } catch {\n registry = undefined;\n }\n for (const declaration of this.reviewConfig()?.caseSubjects ?? []) {\n const subjectResourceType = registry ? this.subjectResourceTypeOf(registry, declaration.caseResourceType, declaration.subjectField) : undefined;\n if (!subjectResourceType) {\n this.logger.error('[AgentWorkDecisions] A case-subject declaration names no foreign key the registry can follow; exports fail closed on its cases while any case subject is excluded', {\n caseResourceType: declaration.caseResourceType, subjectField: declaration.subjectField,\n });\n }\n resolved.set(declaration.caseResourceType, { ...declaration, ...(subjectResourceType ? { subjectResourceType } : {}) });\n }\n return resolved;\n }\n\n /**\n * The resource types each resource reference target set holds (#2471): what `/application-config` publishes as\n * `resourceReferenceTargets`, so a form offers the types a reference may name and then the rows of the one chosen.\n *\n * Total over `ResourceReferenceTargetSet` by construction: the record is typed by the vocabulary, so a set added to it\n * fails to compile until it is derived here. Each list is sorted, an empty one meaning \"this application has none\".\n * Throws when the resource registry cannot be read, rather than publishing an empty case list that would read as an\n * answer; the caller then omits the field and a form falls back to text inputs.\n */\n public resourceReferenceTargets(): Record<ResourceReferenceTargetSet, string[]> {\n const registry = this.container.get<ResourcesRegistryBackendService>(SAAS_SERVICE_TYPES.ResourceRegistryService);\n const derive: Record<ResourceReferenceTargetSet, () => string[]> = {\n [ResourceReferenceTargetSet.WORK_UNIT_CASES]: () => registry.getResourceTypes()\n .filter((resourceType) => registry.tryGetResourceConfiguration(resourceType)?.workUnit === true)\n .map(String),\n [ResourceReferenceTargetSet.WORK_UNIT_SUBJECTS]: () => [...this.resolvedCaseSubjectDeclarations().values()]\n .map((declaration) => declaration.subjectResourceType)\n .filter((resourceType): resourceType is string => !!resourceType),\n };\n const published = {} as Record<ResourceReferenceTargetSet, string[]>;\n for (const targetSet of Object.values(ResourceReferenceTargetSet)) published[targetSet] = [...new Set(derive[targetSet]())].sort();\n return published;\n }\n\n /**\n * The case subject references an authorisation write excludes that no declaration can ever match: a case subject of a resource\n * no work-unit resource declares as its case subject. An exclusion that excludes nothing would read as a control and be\n * none, so the write refuses it (#1925).\n */\n public undeclaredExcludedSubjectRefs(\n subjectRefs: readonly AgentWorkSubjectRef[],\n declarations: ReadonlyMap<string, ResolvedCaseSubjectDeclaration> = this.resolvedCaseSubjectDeclarations(),\n ): AgentWorkSubjectRef[] {\n if (subjectRefs.length === 0) return [];\n const declaredSubjectTypes = new Set([...declarations.values()]\n .map((declaration) => declaration.subjectResourceType)\n .filter((type): type is string => !!type));\n return subjectRefs.filter((subjectRef) => !declaredSubjectTypes.has(subjectRef.resourceType));\n }\n\n /**\n * The resource a case resource's `subjectField` points at, through the case resource's own relationships: the\n * relationship whose compiled foreign key is `subjectField` HELD by the case resource (read from the compiled holder,\n * never from declaration order, which an author may write either way), and whose other side is the case subject.\n */\n private subjectResourceTypeOf(registry: ResourcesRegistryBackendService, caseResourceType: string, subjectField: string): string | undefined {\n try {\n const configuration = registry.getResourceConfiguration(caseResourceType as ResourceType);\n if (configuration?.workUnit !== true || !schemaDeclaresForeignKeyField(configuration.mainSchema, subjectField)) return undefined;\n const buckets = configuration.resourceRelationships;\n for (const relationship of [...buckets.parentRelationships, ...buckets.childRelationships, ...buckets.selfRelationships]) {\n const compiled = relationship.resolvedSemantics?.persistence?.foreignKey;\n const holder = compiled?.holderResourceType ?? Resources_SharedUtils.resolveForeignKeyHolderResourceType(relationship);\n const field = compiled?.fieldIdentifier ?? relationship.foreignKeyField;\n if (holder !== caseResourceType || field !== subjectField || compiled?.isArray) continue;\n return String(relationship.resourceType1 === caseResourceType ? relationship.resourceType2 : relationship.resourceType1);\n }\n return undefined;\n } catch {\n return undefined;\n }\n }\n\n /** The keys of every case whose declared case subject field names `subjectRef` today, across every declaring case resource. */\n private async currentCaseKeysOfSubject(subjectRef: AgentWorkSubjectRef): Promise<string[]> {\n const keys: string[] = [];\n for (const declaration of this.resolvedCaseSubjectDeclarations().values()) {\n if (declaration.subjectResourceType !== subjectRef.resourceType) continue;\n let after: string | undefined;\n for (;;) {\n const filter = { [declaration.subjectField]: subjectRef.resourceId };\n const page = await this.repositoriesRegistry.findManyForInfrastructure<{ _id: unknown }>(\n declaration.caseResourceType as ResourceType,\n after ? { $and: [filter, { _id: { $gt: after } }] } : filter,\n undefined,\n undefined,\n { sort: [{ field: '_id', order: SortOrder.ASC }], limit: PAGE_SIZE },\n );\n keys.push(...page.map((row) => agentWorkCaseKey({ resourceType: declaration.caseResourceType, resourceId: String(row._id) })));\n if (page.length < PAGE_SIZE) break;\n after = String(page[page.length - 1]!._id);\n }\n }\n return keys;\n }\n\n /** The case subject of one case, read from its row through the declared field. */\n private async subjectOfCase(caseRef: WorkUnitRef, declaration: ResolvedCaseSubjectDeclaration | undefined): Promise<CaseSubjectAnswer> {\n if (!declaration) return { kind: CaseSubjectAnswerKind.NO_SUBJECT_DECLARED };\n if (!declaration.subjectResourceType) return { kind: CaseSubjectAnswerKind.UNKNOWN };\n try {\n const row = await this.repositoriesRegistry.readUnscopedByKey<Record<string, unknown>>(caseRef.resourceType as ResourceType, { _id: caseRef.resourceId });\n if (!row) return { kind: CaseSubjectAnswerKind.UNKNOWN };\n const subjectId = row[declaration.subjectField];\n if (subjectId === undefined || subjectId === null || subjectId === '') return { kind: CaseSubjectAnswerKind.NO_SUBJECT };\n // One case subject per case: a value that is not one id (an array, an object) cannot be matched, so it is unknown (review F7).\n if (typeof subjectId !== 'string' && typeof subjectId !== 'number') return { kind: CaseSubjectAnswerKind.UNKNOWN };\n return { kind: CaseSubjectAnswerKind.SUBJECT, subjectKey: agentWorkSubjectKey({ resourceType: declaration.subjectResourceType, resourceId: String(subjectId) }) };\n } catch {\n return { kind: CaseSubjectAnswerKind.UNKNOWN };\n }\n }\n\n // ─── Content minimisation (#1923) ─────────────────────────────────────────\n\n /**\n * The declared shape a record's kept content is read against: a tool call's arguments by the tool's argument schema\n * (and, for a resource write tool, the resource's main schema and its row-id argument); an output review's proposal\n * and final version by the main schema of the final work product's resource. An actor review's content is free-form.\n */\n private contentShapeOf(row: AgentWorkDecision): ContentShapeAnswer {\n switch (row.surface) {\n case AgentWorkDecisionSurface.TOOL_CALL_APPROVAL: {\n const tool = row.toolName ? this.functionToolOf(row.agentRef, row.toolName) : undefined;\n if (!tool) return { withheld: EvaluationContentWithholdingReason.SHAPE_NOT_RESOLVED };\n const resourceSchemas = tool.argumentsResource ? this.resourceSchemasOf(tool.argumentsResource.resourceType) : undefined;\n // A resource the tool declares but the registry no longer knows: half a shape is not a shape.\n if (tool.argumentsResource && !resourceSchemas) return { withheld: EvaluationContentWithholdingReason.SHAPE_NOT_RESOLVED };\n return { shape: {\n schemas: [tool.inputSchema, ...(resourceSchemas ?? [])],\n ...(tool.argumentsResource?.rowIdArgument ? { identifierKeys: [tool.argumentsResource.rowIdArgument] } : {}),\n } };\n }\n case AgentWorkDecisionSurface.OUTPUT_REVIEW: {\n if (!row.finalWorkProductRef) return { withheld: EvaluationContentWithholdingReason.SURFACE_DECLARES_NO_SHAPE };\n const schemas = this.resourceSchemasOf(row.finalWorkProductRef.resourceType);\n return schemas ? { shape: { schemas } } : { withheld: EvaluationContentWithholdingReason.SHAPE_NOT_RESOLVED };\n }\n case AgentWorkDecisionSurface.ACTOR_REVIEW:\n return { withheld: EvaluationContentWithholdingReason.SURFACE_DECLARES_NO_SHAPE };\n }\n }\n\n /**\n * One record's kept content, minimised for export: each version read against its declared shape, then the record's\n * own identifiers replaced inside what is left, and the diff recomputed from the two minimised versions (a patch of\n * the raw versions would carry the raw values back). Withheld as a whole when either version cannot be vouched for.\n */\n private minimisedContentOf(\n row: AgentWorkDecision,\n content: AgentWorkDecisionContent,\n pseudonymOf: (identifier: string) => string,\n known: ReadonlyMap<string, string>,\n ): { proposal?: unknown; final?: unknown; diff?: unknown; withheld?: EvaluationContentWithholdingReason } {\n const answer = this.contentShapeOf(row);\n if (!answer.shape) return { withheld: answer.withheld };\n const minimise = (json: string | undefined): { value?: unknown; outside: boolean } => {\n if (json === undefined) return { outside: false };\n const minimised = minimiseContentByDeclaredShape(JSON.parse(json), answer.shape, pseudonymOf);\n return minimised === undefined ? { outside: true } : { value: pseudonymiseKnownIdentifiers(minimised, known), outside: false };\n };\n const proposal = minimise(content.proposalJson);\n const final = minimise(content.finalJson);\n if (proposal.outside || final.outside) return { withheld: EvaluationContentWithholdingReason.CONTENT_OUTSIDE_SHAPE };\n return {\n ...(proposal.value !== undefined ? { proposal: proposal.value } : {}),\n ...(final.value !== undefined ? { final: final.value } : {}),\n ...(proposal.value !== undefined && final.value !== undefined ? { diff: correctionJsonPatch(proposal.value, final.value) } : {}),\n };\n }\n\n /**\n * Every schema a row of the resource can have, its main schema and each inheritance variant (#2455), or `undefined`\n * when the registry does not know the resource. The main schema alone read a variant's keys as outside the shape, so\n * the whole record was withheld from export.\n */\n private resourceSchemasOf(resourceType: string): unknown[] | undefined {\n try {\n const configuration = this.container.get<ResourcesRegistryBackendService>(SAAS_SERVICE_TYPES.ResourceRegistryService)\n .tryGetResourceConfiguration(resourceType as ResourceType);\n if (!configuration?.mainSchema) return undefined;\n return [configuration.mainSchema, ...resourceInheritanceVariantSchemas(configuration.inheritenceSchemaDefinition as never)];\n } catch {\n return undefined;\n }\n }\n\n /**\n * The function tool a settled call named: the agent the actor system converses through (the same rule the turn\n * uses), and among its declared tools the one exposed to the model under `toolName`.\n */\n private functionToolOf(systemRef: string, toolName: string) {\n try {\n const registry = this.container.get<FlowsActorsRegistryService>(SAAS_SERVICE_TYPES.FlowsActorsRegistryService);\n const system = registry.getSystem(systemRef, FlowActorSystem_Kind.ACTOR) as ActorSystem | undefined;\n const agentRef = system ? chatAgentRefOfActorSystem(system) : undefined;\n const agent = agentRef ? registry.getAgent(agentRef) : undefined;\n const functionRef = (agent?.capabilities?.tools?.functionRefs ?? []).find((ref) => modelToolNameForFunctionRef(ref) === toolName);\n return functionRef ? registry.getFunctionTool(functionRef) : undefined;\n } catch {\n return undefined;\n }\n }\n\n /** Every decision record matching `filter`, in every scope, read in key-ordered pages. */\n private async readDecisions(filter: Record<string, unknown>): Promise<AgentWorkDecision[]> {\n const rows: AgentWorkDecision[] = [];\n for (const variant of AGENT_WORK_VARIANTS) {\n let after: string | undefined;\n for (;;) {\n const page = await this.repositoriesRegistry.findManyForInfrastructure<AgentWorkDecision>(\n variant.decisions,\n after ? { $and: [filter, { _id: { $gt: after } }] } : filter,\n undefined,\n undefined,\n { sort: [{ field: '_id', order: SortOrder.ASC }], limit: PAGE_SIZE },\n );\n rows.push(...page);\n if (page.length < PAGE_SIZE) break;\n after = String(page[page.length - 1]!._id);\n }\n }\n return rows;\n }\n\n /**\n * The content row of a decision, in whichever scope it was written — and only the tenant's own (review F6): a\n * reference reused in another store can never join its content into this tenant's dataset.\n */\n private async readContent(decisionRef: string, workOrganizationId: string): Promise<AgentWorkDecisionContent | undefined> {\n for (const variant of AGENT_WORK_VARIANTS) {\n const row = await this.repositoriesRegistry.readUnscopedByKey<AgentWorkDecisionContent>(variant.contents, { decisionRef, workOrganizationId });\n if (row) return row;\n }\n return undefined;\n }\n\n /**\n * Whether the decision's content row exists, read in the record's transaction when the content lives on its database.\n * A refused or missing row answers `false`; a store failure of a read that shared the transaction ends the record,\n * since that transaction may already be aborted (`readFailureEndsTheOperation`, #3091).\n */\n private async contentRowExists(contents: CoreResourceType, decisionRef: string, options?: RepositoryOptions): Promise<boolean> {\n const readOptions = readOptionsOnItsOwnDatabase(this.repositoriesRegistry, contents as ResourceType, options);\n try {\n return !!(await this.repositoriesRegistry.readUnscopedByKey(contents, { decisionRef }, readOptions));\n } catch (error) {\n if (readFailureEndsTheOperation(error, readOptions?.transaction !== undefined)) throw error;\n return false;\n }\n }\n\n /**\n * Create a row through the repository, as the engine. The owner FK is named in `preserveServerInjectedFields`\n * because the CREATE DTO drops FK fields. A duplicate `decisionRef` (a concurrent writer won) answers `null`.\n */\n private async createRow<T>(resourceType: CoreResourceType, ownerField: string, ownerId: string, document: Record<string, unknown>, options?: RepositoryOptions): Promise<T | null> {\n const repository = this.repositoriesRegistry.getRepositoryOrThrow(resourceType, {} as ExecutionContext<any>);\n // These resources' CREATE is an INTERNAL_CALL (the service tier's), not REPOSITORY_ONLY: the SERVICE default\n // resolver is the one that serves it. `createForInternalRepositoryOperation` resolves REPOSITORY_ONLY or a\n // URL-bearing default, and neither exists here — which is what failed on the first live run.\n const operation = this.container.get<ResourcesRegistryBackendService>(SAAS_SERVICE_TYPES.ResourceRegistryService)\n .getServiceOperationPathDefault(resourceType, CoreResourceOperation.CREATE);\n const context = await this.container.get<ExecutionContextCreatorBackendService>(SAAS_SERVICE_TYPES.ExecutionContextCreatorBackendService)\n .createForInternalOperation({ operation });\n try {\n return await repository.create(context, { ...document, [ownerField]: ownerId } as T, { ...options, preserveServerInjectedFields: [ownerField] }) as T;\n } catch (error) {\n // Inside a transaction a failed insert has aborted it (both stores), so there is no winner to read in it (#3093).\n if (writeFailureEndsTheOperation(error, options?.transaction !== undefined)) throw error;\n const decisionRef = document['decisionRef'];\n if (typeof decisionRef === 'string') {\n // The unique `decisionRef`: another writer recorded this decision first (I1).\n const winner = await this.repositoriesRegistry.readUnscopedByKey(resourceType, { decisionRef }).catch(() => null);\n if (winner) return null;\n }\n throw error;\n }\n }\n\n /** The tenant the work was done for: the case row's organization, else the route's, else the owner organization. */\n /**\n * The decider's standing in the tenant the work was done in: the representing organization a decision is attributed to\n * (#2618, `resolveRelationshipWorkAttribution`), and the one relationship they stand there through (#2722,\n * `resolveRelationshipOnlyStanding`), whose work the decision and its content are. The rows are written on the\n * engine's own context, outside any operation, so without it they were the tenant's own and every other relationship\n * reaching the tenant's records could read one relationship's corrections (review of the asynchronous writers, M1).\n *\n * Read from their CURRENT role entries there, through the one rebuild of a person's authority. One of the tenant's\n * own, a lapsed decider, an unreadable rebuild or no tenant all answer none, which leaves the decision the tenant's\n * own. Accounting, never authority.\n */\n private async standingOfDecider(deciderUserId: string | undefined, workOrganizationId: string | undefined): Promise<{ representingOrganizationId?: string; relationshipId?: string }> {\n if (!deciderUserId || !workOrganizationId) return {};\n try {\n const creator = this.container.get<ExecutionContextCreatorBackendService>(SAAS_SERVICE_TYPES.ExecutionContextCreatorBackendService);\n const member = await creator.rebuildMemberAuthority({ userId: deciderUserId, organizationId: workOrganizationId });\n // A lapsed standing carries no `auth` (narrowed by shape: this module reaches the creator only lazily, and a value\n // import of its enum would put the construction cycle the container avoids back at module load).\n if (!('auth' in member)) return {};\n const representingOrganizationId = resolveRelationshipWorkAttribution(member.auth.initiatorRoles, workOrganizationId)?.representingOrganizationId;\n const relationships = resolveRelationshipOnlyStanding(member.auth.initiatorRoles, workOrganizationId);\n return {\n ...(representingOrganizationId ? { representingOrganizationId } : {}),\n ...(relationships?.length === 1 ? { relationshipId: relationships[0] } : {}),\n };\n } catch (error) {\n this.logger.info('[AgentWorkDecisions] The decider\\'s standing could not be read; the decision is recorded as the tenant\\'s own', {\n reason: describeCaughtError(error),\n });\n return {};\n }\n }\n\n private async workOrganizationOf(write: AgentWorkDecisionWrite, options?: RepositoryOptions): Promise<string | undefined> {\n const caseOrganizationId = write.caseRef ? await this.caseOrganizationOf(write.caseRef, options) : undefined;\n return caseOrganizationId ?? write.routeOrganizationId ?? ('organizationId' in write.owner ? write.owner.organizationId : undefined);\n }\n\n /** A case row's `organizationId`, read by key with no scope filter: the engine asks, and the answer decides the tenant. */\n private async caseOrganizationOf(caseRef: WorkUnitRef, options?: RepositoryOptions): Promise<string | undefined> {\n const readOptions = readOptionsOnItsOwnDatabase(this.repositoriesRegistry, caseRef.resourceType as ResourceType, options);\n try {\n const row = await this.repositoriesRegistry.readUnscopedByKey<{ organizationId?: unknown }>(caseRef.resourceType as ResourceType, { _id: caseRef.resourceId }, readOptions);\n return typeof row?.organizationId === 'string' && row.organizationId.length > 0 ? row.organizationId : undefined;\n } catch (error) {\n // Inside the caller's transaction a store failure may have aborted it: ended here, not masked (#3091).\n if (readFailureEndsTheOperation(error, readOptions?.transaction !== undefined)) throw error;\n return undefined;\n }\n }\n\n /** Whether the organization keeps content for this case: `WITH_CONTENT`, and the case within its narrowing. */\n private async contentCaptureHolds(organizationId: string | undefined, caseRef: WorkUnitRef | undefined): Promise<boolean> {\n if (!organizationId) return false;\n const settings = await this.repositoriesRegistry.readUnscopedByKey<AgentWorkCaptureSettings>(CoreResourceType.AGENT_WORK_CAPTURE_SETTINGS, { organizationId }).catch(() => null);\n if (settings?.contentCapture !== CorrectionContentCapture.WITH_CONTENT) return false;\n const narrowed = settings.narrowToCaseRefs ?? [];\n if (narrowed.length === 0) return true;\n return !!caseRef && narrowed.some((candidate) => agentWorkCaseKey(candidate) === agentWorkCaseKey(caseRef));\n }\n\n /**\n * Whether a case resource declares special-category (GDPR Art. 9) or criminal-offence data on any field, from its\n * own schema's `.dataCategories(...)`. Fail closed: a resource that cannot be read counts as declaring it.\n */\n private declaresRestrictedPersonalData(resourceType: string): boolean {\n try {\n const configuration = this.container.get<ResourcesRegistryBackendService>(SAAS_SERVICE_TYPES.ResourceRegistryService)\n .getResourceConfiguration(resourceType as ResourceType);\n return resolveResourcePersonalDataCategories(resourceComplianceSchema(configuration)).categories\n .some((category) => isSpecialCategoryPersonalData(category) || category === PersonalDataCategory.CRIMINAL_OFFENCE);\n } catch {\n return true;\n }\n }\n\n /** The tenant's correction key, or `undefined` without the primary secret (the record then claims no digest). */\n private correctionKeyOf(organizationId: string | undefined): string | undefined {\n const purposeKey = applicationSymmetricKeyOf(this.appConfig, CryptoKey_Purpose.AGENT_WORK_CORRECTION_DIGEST);\n if (!purposeKey) {\n if (!this.warnedNoSecret) {\n this.warnedNoSecret = true;\n this.logger.warn('[AgentWorkDecisions] No correction-digest key on this runtime: decision records keep their paths and distance but no digest');\n }\n return undefined;\n }\n return deriveAgentWorkCorrectionKey(purposeKey, organizationId);\n }\n\n private reviewConfig() {\n try {\n return this.appConfig?.isInitialized?.() ? this.appConfig.config.agentWorkReview : undefined;\n } catch {\n return undefined;\n }\n }\n\n private auditLogs(): AuditLogsBackendService | undefined {\n try {\n return this.container.get<AuditLogsBackendService>(SAAS_SERVICE_TYPES.AuditLogsService);\n } catch {\n return undefined;\n }\n }\n}\n\n/**\n * The paths an exported line names (review F6). With minimised content they are read from the MINIMISED patch, so a\n * pseudonymised record key or a withheld or undeclared field is never named by its raw path. Without it, only each\n * path's top-level segment is exported: that is the argument or field name the record already declares, while a deeper\n * segment may be a record key holding an identifier no shape was there to classify.\n */\nfunction exportedModifiedPathsOf(recordedPaths: readonly string[], kept: { diff?: unknown } | undefined): string[] {\n if (Array.isArray(kept?.diff)) return modifiedPathsOf(kept.diff as JsonPatchOperation[]);\n return [...new Set(recordedPaths.map((path) => path.split('/')[0]!))].sort();\n}\n\n/** The group a decision record falls in. A record with no value for the grouping key falls in the empty group. */\nfunction overrideRateGroupKeyOf(row: AgentWorkDecision, groupBy: AgentWorkDecisionGrouping): { mapKey: string; key: AgentWorkOverrideRateGroup['key'] } {\n switch (groupBy) {\n case AgentWorkDecisionGrouping.AGENT:\n return { mapKey: row.agentRef, key: { agentRef: row.agentRef } };\n case AgentWorkDecisionGrouping.TOOL:\n return row.toolName ? { mapKey: row.toolName, key: { toolName: row.toolName } } : { mapKey: '', key: {} };\n case AgentWorkDecisionGrouping.CASE:\n return row.caseRef\n ? { mapKey: agentWorkCaseKey(row.caseRef), key: { caseRef: { resourceType: row.caseRef.resourceType, resourceId: row.caseRef.resourceId } } }\n : { mapKey: '', key: {} };\n case AgentWorkDecisionGrouping.DECIDER:\n return row.deciderUserId ? { mapKey: row.deciderUserId, key: { deciderUserId: row.deciderUserId } } : { mapKey: '', key: {} };\n }\n}\n\n/**\n * Register the agent-work plane's subject-reference severer for a `USERS` erasure (#2865): the decider of a recorded\n * decision, and the person who exported a dataset, in every owner scope. Both are one column holding one user id, on\n * rows the erasure graph does not walk (an organization's or an application's records, and a decision in a thread the\n * person did not own), so the shared column severer clears it inside the erasure's transaction and keeps the row: the\n * decision stays the operator's evidence that agent work was supervised, and the export stays its ledger. A row under a\n * legal hold is left as it is. Resolved against the container at the erasure; a runtime that registers none of these\n * resources (a minion, a platform service) severs nothing.\n *\n * assurance-control: WILDO.PRIVACY.SUBJECT_ERASURE — an erased person's id leaves the decisions they made and the datasets they exported.\n */\nexport function registerAgentWorkErasureSeverance(\n servicesRegistry: Pick<ServicesRegistryHandlerBackendService, 'registerSubjectReferenceSeverer'>,\n container: Container,\n): void {\n const repositories = () => container.get<RepositoriesRegistryHandlerBackendService>(SAAS_SERVICE_TYPES.RepositoriesRegistryHandlerService);\n servicesRegistry.registerSubjectReferenceSeverer(CoreResourceType.USERS, createColumnSubjectReferenceSeverer(\n 'agent-work-deciders',\n [\n // The decisions they took name them (#2958): their ACCESS export discloses each one through this column. On a\n // decision in another person's own thread (the user variant), that person's id is theirs, not the decider's, and\n // is withheld (Art. 15(4)). Decided by practice: a record of an act a person performed is personal data concerning\n // them (Art. 15(1)), as the audit rows naming them already are in the same export.\n // spec-cite: GDPR Art. 15(1), 15(4) (https://gdpr-info.eu/art-15-gdpr/)\n ...AGENT_WORK_VARIANTS.map((variant) => ({\n resourceType: variant.decisions,\n field: 'deciderUserId',\n exportDisclosure: SeveredColumnExportDisclosure.NAMES_SUBJECT,\n ...(variant.ownerField === 'userId' ? { othersDataFields: ['userId'] } : {}),\n })),\n // NOT indexed, deliberately (#2865 review F8): the ledger gains one row per export a person starts, so this search\n // walks a small collection once per erasure, while an index would cost every export write and a migration on every\n // PostgreSQL surface. `deciderUserId` above IS indexed: decisions are the plane's volume.\n //\n // The exports they started name them (#2958): disclosed to them, without the pseudonymised keys of the people and\n // cases whose decisions the dataset carried, which are those people's data (GDPR Recital 26: a pseudonymised key is\n // still personal data). spec-cite: GDPR Recital 26 (https://gdpr-info.eu/recital-26-not-applicable-to-anonymous-data/)\n {\n resourceType: CoreResourceType.EVALUATION_DATASET_EXPORTS,\n field: 'exportedByUserId',\n exportDisclosure: SeveredColumnExportDisclosure.NAMES_SUBJECT,\n othersDataFields: ['subjectKeys', 'caseKeys'],\n },\n ],\n repositories,\n (resourceType) => container.isBound(SAAS_SERVICE_TYPES.RepositoriesRegistryHandlerService) && repositories().hasRepository(resourceType),\n ));\n}\n"]}
1
+ {"version":3,"file":"agent-work-decisions.backend.service.js","sourceRoot":"","sources":["../../../../src/flows-actors/services/agent-work-decisions.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAkB,MAAM,WAAW,CAAC;AACzE,OAAO,EAAE,2BAA2B,EAAE,2BAA2B,EAAE,4BAA4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AAE;QACF,kHAAkH;QAClH,oHAAoH;QACpH,uHAAuH;QACvH;YACE,YAAY,EAAE,gBAAgB,CAAC,0BAA0B;YACzD,KAAK,EAAE,kBAAkB;YACzB,gBAAgB,EAAE,6BAA6B,CAAC,aAAa;YAC7D,gBAAgB,EAAE,CAAC,aAAa,EAAE,UAAU,CAAC;SAC9C;KACF,EACD,YAAY,EACZ,CAAC,YAAY,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,CAAC,kBAAkB,CAAC,kCAAkC,CAAC,IAAI,YAAY,EAAE,CAAC,aAAa,CAAC,YAAY,CAAC,CACzI,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * # Deciders' decisions on agents' proposals: the record, the override rate and the evaluation export (#1599)\n *\n * Every decision a person takes on something an AGENT proposed — a tool call approved, edited or denied, an\n * actor-system review, an edit to agent-drafted output — is recorded ONCE, as metadata, in `agentWorkDecisions`.\n * With the organization's opt-in, the proposal, the final version and the diff are kept beside it in\n * `agentWorkDecisionContents`. From the metadata alone this service computes the override rate; with a recorded\n * authorisation it exports an organization's decisions as a pseudonymised evaluation dataset, and records the export.\n *\n * ## Written by the winner only, and repaired after a crash (I1–I3)\n *\n * The settle that WINS a decision's compare-and-swap calls {@link recordDecision}; a loser records nothing (I2). The\n * same compare-and-swap stamps `pendingCorrectionRecordRef` on the execution row, and the marker is cleared only once\n * the record exists. A process that dies in between leaves the marker, and {@link repairPendingCorrectionRecords}\n * writes the record from the row's resolution columns (`ROW_REPAIR`, metadata only) (I3). `decisionRef` is unique in\n * every store, so a repair racing the settle, a retried output review and a double settle all converge on one row (I1).\n *\n * ## Tenant-keyed digests (I5)\n *\n * No digest here is an unkeyed hash: see `agent-work-correction.backend.utils.ts`. The key needs the application's\n * primary secret; without it the record keeps the paths and the distance and claims no digest.\n *\n * assurance-control: WILDO.PRIVACY.DATA_MINIMIZATION — the record is metadata only; content is kept under the\n * organization's opt-in, and an export carries pseudonyms and no decider or organization.\n * assurance-control: WILDO.PRIVACY.ERASURE_PROPAGATION — erasing a case scrubs the content kept about it.\n * assurance-control: WILDO.PRIVACY.SECONDARY_USE_AUTHORIZATION — erasing a case marks every dataset that exported it: an\n * exported dataset is a derived copy, which ERASURE_PROPAGATION's intent excludes.\n */\nimport { inject, injectable, optional, type Container } from 'inversify';\nimport { readFailureEndsTheOperation, readOptionsOnItsOwnDatabase, writeFailureEndsTheOperation } from '~wildo-backend-lib/base-classes/services/repositories/resource-write-integrity.backend';\nimport {\n AGENT_WORK_DECISION_OVERRIDE_OUTCOMES,\n AGENT_WORK_DECISION_RATED_OUTCOMES,\n AgentWorkDecisionGrouping,\n AgentWorkDecisionRecordSource,\n AgentWorkDecisionSurface,\n AgentWorkOutputReviewInputSchema,\n CoreResourceOperation,\n CoreResourceType,\n ResourceReferenceTargetSet,\n CorrectionContentCapture,\n ErrorCustomMessageReference,\n ErrorType,\n EvaluationDatasetExportRefusalReason,\n EvaluationDatasetInvalidationReason,\n EvaluationContentWithholdingReason,\n EvaluationExportAuthorizationStatus,\n ExecutionRefKind,\n FlowActorSystem_Kind,\n Resources_SharedUtils,\n HumanDecision_Outcome,\n PersonalDataCategory,\n SortOrder,\n agentWorkOverrideRate,\n type ActorSystem,\n type AgentWorkSubjectRef,\n isSpecialCategoryPersonalData,\n resolveResourcePersonalDataCategories,\n resourceComplianceSchema,\n type AgentWorkCaptureSettings,\n type AgentWorkDecision,\n type AgentWorkDecisionContent,\n type AgentWorkOutputReviewInput,\n type AgentWorkOverrideRate,\n type AgentWorkOverrideRateGroup,\n type AgentWorkOverrideRateRequest,\n type AgentWorkProductRef,\n type EvaluationDatasetExport,\n type EvaluationDatasetExportRequest,\n type EvaluationDatasetExportResult,\n type EvaluationExportAuthorization,\n type ExecutionRef,\n type FlowActorExecution,\n type ResourceType,\n type WorkUnitRef,\n resourceInheritanceVariantSchemas,\n resolveRelationshipOnlyStanding,\n resolveRelationshipWorkAttribution,\n} from '@wildo-ai/saas-models';\n\nimport { SAAS_SERVICE_TYPES } from '~wildo-backend-lib/inject/models/service-types';\nimport { LoggerService } from '~wildo-backend-lib/monitoring/logger/services/logger.service';\nimport { RepositoriesRegistryHandlerBackendService } from '~wildo-backend-lib/base-classes/services/repositories/repositories-registry-handler.backend.service';\nimport type { ServicesRegistryHandlerBackendService } from '~wildo-backend-lib/base-classes/services/services/services-registry-handler.backend.service';\nimport { SeveredColumnExportDisclosure } from '~wildo-backend-lib/base-classes/services/services/subject-reference-severance.backend.schemas';\nimport { createColumnSubjectReferenceSeverer } from '~wildo-backend-lib/base-classes/services/services/subject-reference-severance.backend.utils';\nimport { ErrorBuilderBackendService } from '~wildo-backend-lib/errors/services/error-builder.backend.service';\nimport { describeCaughtError } from '~wildo-backend-lib/errors/utils/error-log-level-classification.backend.utils';\nimport { RelationshipOwnWorkTenantField, relationshipOwnWorkFilter } from '~wildo-backend-lib/flows-actors/models/relationship-own-work.backend.utils';\nimport { registerTransactionPostCommitEffect, type TransactionContext } from '~wildo-backend-lib/databases/models/transaction.shared.schemas';\nimport { CapturedPostCommitEffectKind } from '~wildo-backend-lib/base-classes/models/post-commit-effect-outbox.backend.schemas';\nimport {\n AGENT_WORK_CASE_REMOVAL_ROWS_PER_CAPTURED_EFFECT,\n capturablePostCommitEffect,\n idempotentSideEffectCapture,\n} from '~wildo-backend-lib/base-classes/services/services/post-commit-effect-capture.backend';\nimport type { AppConfigurationService } from '~wildo-backend-lib/config/services/app-configuration.backend.service';\nimport type { ExecutionContext } from '~wildo-backend-lib/runtime/models/execution-context.backend.schemas';\nimport { runOutsideRelationshipProvenanceFrame, runWithRelationshipProvenanceFrame } from '~wildo-backend-lib/runtime/models/relationship-provenance-frame.als.backend';\nimport type { ExecutionContextCreatorBackendService } from '~wildo-backend-lib/runtime/services/execution-context-creator.backend.service';\nimport type { ResourcesRegistryBackendService } from '~wildo-backend-lib/resources/services/resources-registry.backend.service';\nimport type { AuditLogsBackendService } from '~wildo-backend-lib/compliance/audit-trails/services/audit-logs.backend.service';\nimport type { RepositoryOptions } from '~wildo-backend-lib/base-classes/models/repositories.backend.schemas';\nimport type { WorkUnitCaseBackendService } from '~wildo-backend-lib/flows-actors/services/work-unit-case.backend.service';\nimport type { DecisionTimeSource } from '~wildo-backend-lib/flows-actors/services/model-cost.backend.service';\nimport type { FlowsActorsRegistryService } from '~wildo-backend-lib/flows-actors/services/flows-actors-registry.service';\nimport { chatAgentRefOfActorSystem, modelToolNameForFunctionRef } from '~wildo-backend-lib/flows-actors/models/function-tools.backend.definitions';\nimport {\n correctionJsonPatch,\n deriveAgentWorkCorrectionKey,\n deriveEvaluationPseudonymKey,\n EVALUATION_PSEUDONYMISATION_VERSION,\n measureAgentWorkCorrection,\n minimiseContentByDeclaredShape,\n modifiedPathsOf,\n type JsonPatchOperation,\n pseudonymiseIdentifier,\n pseudonymiseKnownIdentifiers,\n schemaDeclaresForeignKeyField,\n type EvaluationContentShape,\n} from '~wildo-backend-lib/flows-actors/utils/agent-work-correction.backend.utils';\nimport { CryptoKey_Purpose } from '@wildo-ai/saas-models';\nimport { applicationSymmetricKeyOf } from '~wildo-backend-lib/security/crypto-keys/application-symmetric-keys.backend';\n\n/** Rows read per page when a summary, an export or a sweep scans records. */\nconst PAGE_SIZE = 500;\n/**\n * How long after a decision the repair sweep leaves its marker alone. The settle writes its record right after the\n * compare-and-swap; repairing inside that window would race it and write a metadata-only ROW_REPAIR record where the\n * settle would have kept content. Idempotent either way (the unique `decisionRef`), so this is about content, not\n * correctness.\n */\nconst REPAIR_GRACE_MS = 2 * 60_000;\n\n/** The owner scope a record is written in: the scope of the paused execution, or of an output review. */\nexport type AgentWorkOwnerScope =\n | { readonly userId: string }\n | { readonly organizationId: string }\n | { readonly applicationId: string };\n\n/** One owner scope's three stores. */\ninterface AgentWorkVariant {\n readonly ownerField: 'userId' | 'organizationId' | 'applicationId';\n readonly executions: CoreResourceType;\n readonly decisions: CoreResourceType;\n readonly contents: CoreResourceType;\n}\n\n/** The three owner scopes, in the order a sweep walks them. */\nexport const AGENT_WORK_VARIANTS: readonly AgentWorkVariant[] = Object.freeze([\n { ownerField: 'userId', executions: CoreResourceType.USER_FLOW_ACTOR_EXECUTIONS, decisions: CoreResourceType.USER_AGENT_WORK_DECISIONS, contents: CoreResourceType.USER_AGENT_WORK_DECISION_CONTENTS },\n { ownerField: 'organizationId', executions: CoreResourceType.ORGANIZATION_FLOW_ACTOR_EXECUTIONS, decisions: CoreResourceType.ORGANIZATION_AGENT_WORK_DECISIONS, contents: CoreResourceType.ORGANIZATION_AGENT_WORK_DECISION_CONTENTS },\n { ownerField: 'applicationId', executions: CoreResourceType.APPLICATION_FLOW_ACTOR_EXECUTIONS, decisions: CoreResourceType.APPLICATION_AGENT_WORK_DECISIONS, contents: CoreResourceType.APPLICATION_AGENT_WORK_DECISION_CONTENTS },\n] as const);\n\nfunction variantOfOwner(owner: AgentWorkOwnerScope): { variant: AgentWorkVariant; ownerId: string } {\n if ('userId' in owner) return { variant: AGENT_WORK_VARIANTS[0]!, ownerId: owner.userId };\n if ('organizationId' in owner) return { variant: AGENT_WORK_VARIANTS[1]!, ownerId: owner.organizationId };\n return { variant: AGENT_WORK_VARIANTS[2]!, ownerId: owner.applicationId };\n}\n\n/** The owner scope of an execution row of `executionResourceType`, read from the row's own owner field. */\nexport function agentWorkOwnerOfExecution(executionResourceType: CoreResourceType, row: Record<string, unknown>): AgentWorkOwnerScope | undefined {\n const variant = AGENT_WORK_VARIANTS.find((candidate) => candidate.executions === executionResourceType);\n const ownerId = variant ? row[variant.ownerField] : undefined;\n if (!variant || typeof ownerId !== 'string' || ownerId.length === 0) return undefined;\n return { [variant.ownerField]: ownerId } as AgentWorkOwnerScope;\n}\n\n/** `items` in consecutive slices of at most `size`, in order (a kept case removal's rows, #2930). */\nfunction chunked<T>(items: readonly T[], size: number): T[][] {\n const chunks: T[][] = [];\n for (let start = 0; start < items.length; start += size) chunks.push(items.slice(start, start + size));\n return chunks;\n}\n\n/** The map key of a case, `resourceType:resourceId`: the one spelling the ledger's `caseKeys` and every join use. */\nexport function agentWorkCaseKey(caseRef: WorkUnitRef): string {\n return `${caseRef.resourceType}:${caseRef.resourceId}`;\n}\n\n/** The map key of a case subject, `resourceType:resourceId`: the spelling of the ledger's `subjectKeys` (#1925). */\nexport function agentWorkSubjectKey(subjectRef: AgentWorkSubjectRef): string {\n return `${subjectRef.resourceType}:${subjectRef.resourceId}`;\n}\n\n/**\n * One work-unit resource's declared case subject field, resolved against the registry (#1925). `subjectResourceType` is\n * absent when the declaration names no foreign key whose relationship the registry can follow: a declaration that\n * cannot be honoured, which every reader treats as \"this case's subject is unknown\" and an export fails closed on.\n */\nexport interface ResolvedCaseSubjectDeclaration {\n readonly caseResourceType: string;\n readonly subjectField: string;\n readonly subjectResourceType?: string;\n}\n\n/** The case subject of one case, as an export reads it. */\nenum CaseSubjectAnswerKind {\n /** The case's resource declares no case subject field: it has no case subject. */\n NO_SUBJECT_DECLARED = 'no_subject_declared',\n /** The declared field holds no value on the row: this case has no case subject. */\n NO_SUBJECT = 'no_subject',\n SUBJECT = 'subject',\n /** The case subject could not be read (the declaration cannot be honoured, or the row is gone): unknown, never \"none\". */\n UNKNOWN = 'unknown',\n}\ntype CaseSubjectAnswer =\n | { readonly kind: CaseSubjectAnswerKind.NO_SUBJECT_DECLARED | CaseSubjectAnswerKind.NO_SUBJECT | CaseSubjectAnswerKind.UNKNOWN }\n | { readonly kind: CaseSubjectAnswerKind.SUBJECT; readonly subjectKey: string };\n\n/** The shape an export reads one record's kept content against, or why it has none (#1923). */\ntype ContentShapeAnswer =\n | { readonly shape: EvaluationContentShape; readonly withheld?: undefined }\n | { readonly shape?: undefined; readonly withheld: EvaluationContentWithholdingReason };\n\n/**\n * One decision to record. `proposal` and `final` are the agent's version and the version the decider kept; they feed\n * the diff statistics and are stored only under the organization's opt-in. `fallbackPaths` are the edited top-level\n * argument NAMES when no final version is known (a repaired record).\n */\nexport interface AgentWorkDecisionWrite {\n readonly owner: AgentWorkOwnerScope;\n readonly decisionRef: string;\n readonly surface: AgentWorkDecisionSurface;\n readonly outcome: HumanDecision_Outcome;\n readonly agentRef: string;\n readonly agentVersion?: string;\n readonly toolName?: string;\n readonly caseRef?: WorkUnitRef | null;\n readonly executionRef?: ExecutionRef;\n readonly taskRef?: string;\n readonly finalWorkProductRef?: AgentWorkProductRef;\n readonly proposal?: unknown;\n readonly final?: unknown;\n readonly fallbackPaths?: readonly string[];\n readonly reasonCode?: string;\n readonly reasonText?: string;\n readonly deciderUserId?: string;\n readonly admittedByRole?: string;\n /** When the proposal was put before the decider — the decision's claim instant, else its request instant (I8). */\n readonly presentedAt: Date;\n readonly decidedAt: Date;\n readonly recordSource: AgentWorkDecisionRecordSource;\n /** The organization the decision was routed in, when there was one: the tenant when no case names one. */\n readonly routeOrganizationId?: string;\n}\n\n/** Whether a write created the record, or found it already there. */\nexport enum AgentWorkRecordResultKind {\n RECORDED = 'recorded',\n ALREADY_RECORDED = 'already_recorded',\n}\n\n/** The execution a settle's marker sits on, so the record's writer can clear it once the record exists. */\nexport interface AgentWorkCorrectionMarker {\n readonly executionResourceType: CoreResourceType;\n readonly executionId: string;\n}\n\n/**\n * The seam the services-registry handler calls when rows are erased or deleted (#1599): a narrow port, so that\n * handler depends on the one method it calls and not on this service's whole surface.\n */\nexport interface AgentWorkCaseRemovalSeam {\n scheduleCaseRemoval(resourceType: ResourceType, rowIds: readonly string[], transaction?: TransactionContext): Promise<void>;\n}\n\n/** What one run of the repair sweep did. */\nexport interface AgentWorkCorrectionRepairResult {\n scanned: number;\n repaired: number;\n cleared: number;\n deferred: number;\n failed: number;\n}\n\n/**\n * The repair sweep's view of the resolution columns: what a settle wrote inside its compare-and-swap (#1594 I4).\n */\nexport type ExecutionResolutionRow = Pick<FlowActorExecution,\n 'executionId' | 'systemRef' | 'caseRef' | 'lastResolvedDecisionRef' | 'decidedByUserId' | 'decidedAt' | 'decisionOutcome'\n | 'decisionToolName' | 'decisionModifiedArgumentNames' | 'pendingCorrectionRecordRef' | 'pendingCorrectionPresentedAt'\n | 'pendingCorrectionOrganizationId' | 'pendingCorrectionAdmittedByRole'> & Record<string, unknown>;\n\n/**\n * Whether an execution row carries what its owed record is written from: an owner, and the resolution its marker names\n * (#1599 I3). The one rule the repair reads, and the one a deletion reads to tell a record that cannot be written YET\n * (keep the row) from one the row can no longer carry (keeping it recovers nothing, #2582).\n */\nexport function owedRecordIsRepairableFromRow(executionResourceType: CoreResourceType, row: ExecutionResolutionRow): boolean {\n const decisionRef = row.pendingCorrectionRecordRef;\n return !!decisionRef\n && !!agentWorkOwnerOfExecution(executionResourceType, row)\n && row.lastResolvedDecisionRef === decisionRef\n && !!row.decisionOutcome\n && !!row.decidedAt;\n}\n\n@injectable()\nexport class AgentWorkDecisionsBackendService implements DecisionTimeSource, AgentWorkCaseRemovalSeam {\n private warnedNoSecret = false;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.Logger) private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.RepositoriesRegistryHandlerService) private readonly repositoriesRegistry: RepositoriesRegistryHandlerBackendService,\n @inject(SAAS_SERVICE_TYPES.ErrorBuilderService) private readonly errorBuilder: ErrorBuilderBackendService,\n /*\n * Everything else is resolved LAZILY through the container: the services-registry handler injects this service\n * (its case-removal seam), and the execution-context creator, the audit trail and the case admission all reach\n * that handler — a constructor dependency on any of them would be a construction cycle.\n */\n @inject(SAAS_SERVICE_TYPES.Container) private readonly container: Container,\n @inject(SAAS_SERVICE_TYPES.AppConfigService) @optional() private readonly appConfig?: AppConfigurationService,\n ) {}\n\n // ─── Recording ────────────────────────────────────────────────────────────\n\n /**\n * Record one decision, and its content when the organization opted in (I4). Idempotent on `decisionRef` (I1).\n * Never throws for a decision that was already recorded; throws only when the store refuses the write, which the\n * settle logs and the repair sweep retries. The content row is written FIRST, so a crash between the two leaves a\n * content row the repair's metadata record then points at, never a record claiming content that does not exist.\n */\n public async recordDecision(\n write: AgentWorkDecisionWrite,\n marker?: AgentWorkCorrectionMarker,\n /**\n * The transaction the record joins (#2865 review F1): a person's erasure repays a conversation's owed record inside\n * its own transaction, so the record and the marker it clears commit or roll back with the erasure. Every read and\n * write below joins it; the decider's standing is read from committed data, which only names an organization.\n */\n options?: { readonly transaction?: TransactionContext },\n ): Promise<AgentWorkRecordResultKind> {\n const { variant, ownerId } = variantOfOwner(write.owner);\n const repositoryOptions = options?.transaction ? { transaction: options.transaction } : undefined;\n const workOrganizationId = await this.workOrganizationOf(write, repositoryOptions);\n const existing = await this.repositoriesRegistry.readUnscopedByKey<AgentWorkDecision>(variant.decisions, { decisionRef: write.decisionRef }, repositoryOptions);\n if (existing) {\n // Review F6: the same reference from ANOTHER owner or tenant is a collision, never a retry of this decision —\n // answering it ALREADY_RECORDED would silently drop the second decision. (An engine settle's reference is a\n // UUID; an output review's is the application's own, which must be unique.)\n if ((existing as Record<string, unknown>)[variant.ownerField] !== ownerId || (existing.workOrganizationId ?? undefined) !== workOrganizationId) {\n throw this.errorBuilder.buildError(ErrorType.CONFLICT, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFLICT,\n context: { message: 'This decision reference is already recorded for another owner or organization; a decision reference must be unique.' },\n });\n }\n if (marker) await this.clearCorrectionMarker(marker, write.decisionRef, repositoryOptions);\n return AgentWorkRecordResultKind.ALREADY_RECORDED;\n }\n\n const key = this.correctionKeyOf(workOrganizationId);\n // An accepted proposal IS the final version: its paths are empty and its two digests equal.\n const final = write.outcome === HumanDecision_Outcome.ACCEPTED && write.final === undefined ? write.proposal : write.final;\n const measure = measureAgentWorkCorrection({\n key: key ?? '',\n ...(write.proposal !== undefined ? { proposal: write.proposal } : {}),\n ...(final !== undefined ? { final } : {}),\n ...(write.fallbackPaths ? { fallbackPaths: write.fallbackPaths } : {}),\n });\n\n // The decider's standing in the tenant the work was done in (#2618, #2722): the representing organization a decision\n // is attributed to, and\n // the one relationship the decider stands there through, whose work the content and the decision then are.\n const decider = await this.standingOfDecider(write.deciderUserId, workOrganizationId);\n const asDecidersWork = <T>(fn: () => Promise<T>): Promise<T> => (decider.relationshipId && workOrganizationId\n ? runWithRelationshipProvenanceFrame({ organizationId: workOrganizationId, relationshipId: decider.relationshipId }, fn)\n : runOutsideRelationshipProvenanceFrame(fn));\n const withContent = write.recordSource !== AgentWorkDecisionRecordSource.ROW_REPAIR\n && AGENT_WORK_DECISION_RATED_OUTCOMES.includes(write.outcome)\n && (measure.proposalJson !== undefined || measure.finalJson !== undefined || !!write.reasonText)\n && await this.contentCaptureHolds(workOrganizationId, write.caseRef ?? undefined);\n if (withContent) {\n // assurance-control: WILDO.PRIVACY.DATA_MINIMIZATION — content is written only under the organization's opt-in (I4).\n await asDecidersWork(() => this.createRow<AgentWorkDecisionContent>(variant.contents, variant.ownerField, ownerId, {\n decisionRef: write.decisionRef,\n ...(write.caseRef ? { caseRef: { resourceType: write.caseRef.resourceType, resourceId: write.caseRef.resourceId } } : {}),\n ...(workOrganizationId ? { workOrganizationId } : {}),\n ...(measure.proposalJson !== undefined ? { proposalJson: measure.proposalJson } : {}),\n ...(measure.finalJson !== undefined ? { finalJson: measure.finalJson } : {}),\n ...(measure.diffJson !== undefined ? { diffJson: measure.diffJson } : {}),\n ...(write.reasonText ? { reasonText: write.reasonText } : {}),\n }, repositoryOptions));\n }\n\n /*\n * #1921 — a reason code says why a decider CORRECTED the agent, so it is recorded only beside an override outcome\n * (modified or rejected). Every door writes through here — the tool approval over the socket and over REST, the\n * actor review, the output review — so this is the one place the invariant holds for all of them; the approval card\n * withholding it on an approval-as-proposed is a convenience, not the control. Dropped rather than refused: the\n * reason is optional evidence, and refusing a valid approval because a reason rode along would stall the decision\n * without making the record any truer than dropping it does.\n */\n const reasonCode = write.reasonCode && AGENT_WORK_DECISION_OVERRIDE_OUTCOMES.includes(write.outcome) ? write.reasonCode : undefined;\n const representingOrganizationId = decider.representingOrganizationId;\n const recorded = await asDecidersWork(async () => this.createRow<AgentWorkDecision>(variant.decisions, variant.ownerField, ownerId, {\n decisionRef: write.decisionRef,\n surface: write.surface,\n outcome: write.outcome,\n ...(workOrganizationId ? { workOrganizationId } : {}),\n ...(representingOrganizationId ? { representingOrganizationId } : {}),\n agentRef: write.agentRef,\n ...(write.agentVersion ? { agentVersion: write.agentVersion } : {}),\n ...(write.toolName ? { toolName: write.toolName } : {}),\n ...(write.caseRef ? { caseRef: { resourceType: write.caseRef.resourceType, resourceId: write.caseRef.resourceId } } : {}),\n ...(write.executionRef ? { executionRef: write.executionRef } : {}),\n ...(write.taskRef ? { taskRef: write.taskRef } : {}),\n ...(write.finalWorkProductRef ? { finalWorkProductRef: write.finalWorkProductRef } : {}),\n modifiedPaths: measure.modifiedPaths,\n ...(measure.editDistance !== undefined ? { editDistance: measure.editDistance } : {}),\n ...(key && measure.proposedDigest ? { proposedDigest: measure.proposedDigest } : {}),\n ...(key && measure.finalDigest ? { finalDigest: measure.finalDigest } : {}),\n ...(reasonCode ? { reasonCode } : {}),\n ...(write.deciderUserId ? { deciderUserId: write.deciderUserId } : {}),\n ...(write.admittedByRole ? { admittedByRole: write.admittedByRole } : {}),\n presentedAt: write.presentedAt,\n decidedAt: write.decidedAt,\n recordSource: write.recordSource,\n contentRecorded: withContent || await this.contentRowExists(variant.contents, write.decisionRef, repositoryOptions),\n }, repositoryOptions));\n if (marker) await this.clearCorrectionMarker(marker, write.decisionRef, repositoryOptions);\n return recorded ? AgentWorkRecordResultKind.RECORDED : AgentWorkRecordResultKind.ALREADY_RECORDED;\n }\n\n /**\n * `recordOutputReview` — an application tells the engine a decider reviewed output an agent drafted into the\n * application's own rows. The case is admitted only if it is a readable row of a work-unit resource; the reason code\n * only if the application declares it. Idempotent on the application's `decisionRef`. Not sealed, and why:\n * `AGENT_WORK_OUTPUT_REVIEW_SEAL` (#2906).\n */\n public async recordOutputReview(input: AgentWorkOutputReviewInput, executionContext: ExecutionContext<any>): Promise<AgentWorkRecordResultKind> {\n const parsed = AgentWorkOutputReviewInputSchema.safeParse(input);\n if (!parsed.success) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { reason: 'agent_work_output_review_invalid', issues: parsed.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`) },\n });\n }\n const review = parsed.data;\n if (review.reasonCode && !this.reasonCodeIsDeclared(review.reasonCode)) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { reason: 'agent_work_reason_code_not_declared' },\n });\n }\n const organizationId = executionContext.initiatorIds?.organizationId;\n const userId = executionContext.initiatorIds?.userId;\n let caseRef: WorkUnitRef | undefined;\n if (review.caseRef) {\n const workUnits = this.container.get<WorkUnitCaseBackendService>(SAAS_SERVICE_TYPES.WorkUnitCaseService);\n const admission = await workUnits.admitClientCaseRef({\n executionType: executionContext.executionType,\n initiatorIds: executionContext.initiatorIds ?? null,\n initiatorRoles: [...(executionContext.initiatorRoles ?? [])],\n }, organizationId, review.caseRef);\n if (admission.admitted === false) {\n throw this.errorBuilder.buildError(ErrorType.NOT_FOUND, executionContext, {\n customMessageReference: ErrorCustomMessageReference.NOT_FOUND,\n context: { reason: 'agent_work_output_review_case_not_admitted', refusal: admission.reason },\n });\n }\n caseRef = admission.caseRef;\n }\n const caseOrganizationId = caseRef ? await this.caseOrganizationOf(caseRef) : undefined;\n const tenant = caseOrganizationId ?? organizationId;\n const owner: AgentWorkOwnerScope | undefined = tenant ? { organizationId: tenant } : userId ? { userId } : undefined;\n if (!owner) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_VALIDATION_FAILED,\n context: { reason: 'agent_work_output_review_has_no_owner' },\n });\n }\n const decidedAt = new Date();\n return this.recordDecision({\n owner,\n decisionRef: review.decisionRef,\n surface: AgentWorkDecisionSurface.OUTPUT_REVIEW,\n outcome: review.outcome,\n agentRef: review.agentRef,\n ...(review.agentVersion ? { agentVersion: review.agentVersion } : {}),\n ...(caseRef ? { caseRef } : {}),\n ...(review.taskRef ? { taskRef: review.taskRef } : {}),\n ...(review.finalWorkProductRef ? { finalWorkProductRef: review.finalWorkProductRef } : {}),\n ...(review.proposal !== undefined ? { proposal: review.proposal } : {}),\n ...(review.final !== undefined ? { final: review.final } : {}),\n ...(review.reasonCode ? { reasonCode: review.reasonCode } : {}),\n ...(review.reasonText ? { reasonText: review.reasonText } : {}),\n ...(userId ? { deciderUserId: userId } : {}),\n presentedAt: review.presentedAt ? new Date(review.presentedAt) : decidedAt,\n decidedAt,\n recordSource: AgentWorkDecisionRecordSource.SETTLEMENT,\n ...(organizationId ? { routeOrganizationId: organizationId } : {}),\n });\n }\n\n /** Whether the application declares `reasonCode` (`agentWorkReview.reasonCodes`). Nothing declared: nothing is. */\n public reasonCodeIsDeclared(reasonCode: string): boolean {\n return this.declaredReasonCodes().includes(reasonCode);\n }\n\n /**\n * The application's reason-code vocabulary (`agentWorkReview.reasonCodes`), in its declared order (#1921) — what a\n * reviewer's reason picker offers on every decision that reviews agent work. The same list {@link reasonCodeIsDeclared}\n * checks an answer against, so a code the picker offers is never refused. Empty when nothing is declared.\n */\n public declaredReasonCodes(): readonly string[] {\n return this.reviewConfig()?.reasonCodes ?? [];\n }\n\n // ─── Crash repair (I3) ────────────────────────────────────────────────────\n\n /**\n * Write the record of every settled decision whose settle did not get to it, from the execution row's resolution\n * columns, and clear the marker. `ROW_REPAIR`, metadata only. A row whose resolution names another decision than its\n * marker is left and logged: the columns would describe the wrong decision.\n */\n public async repairPendingCorrectionRecords(now: Date = new Date()): Promise<AgentWorkCorrectionRepairResult> {\n const result: AgentWorkCorrectionRepairResult = { scanned: 0, repaired: 0, cleared: 0, deferred: 0, failed: 0 };\n for (const variant of AGENT_WORK_VARIANTS) {\n // Paged by key (review F11): a row that cannot be repaired stays marked and would otherwise sort first forever,\n // starving every row after it.\n let after: string | undefined;\n for (;;) {\n let rows: ExecutionResolutionRow[];\n try {\n rows = await this.repositoriesRegistry.findManyForInfrastructure<ExecutionResolutionRow>(\n variant.executions,\n after ? { $and: [{ pendingCorrectionRecordRef: { $ne: null } }, { _id: { $gt: after } }] } : { pendingCorrectionRecordRef: { $ne: null } },\n undefined,\n undefined,\n { sort: [{ field: '_id', order: SortOrder.ASC }], limit: PAGE_SIZE },\n );\n } catch (error) {\n this.logger.error('[AgentWorkDecisions] The correction repair sweep could not list marked executions for a scope', {\n resourceType: variant.executions, reason: describeCaughtError(error),\n });\n break;\n }\n for (const row of rows) {\n result.scanned += 1;\n const decidedAt = row.decidedAt ? new Date(row.decidedAt) : undefined;\n if (decidedAt && now.getTime() - decidedAt.getTime() < REPAIR_GRACE_MS) { result.deferred += 1; continue; }\n const outcome = await this.repairOwedRecordOfExecution(variant.executions, row);\n if (outcome === AgentWorkRecordResultKind.RECORDED) result.repaired += 1;\n else if (outcome === AgentWorkRecordResultKind.ALREADY_RECORDED) result.cleared += 1;\n else result.failed += 1;\n }\n if (rows.length < PAGE_SIZE) break;\n after = String(rows[rows.length - 1]!._id);\n }\n }\n // Logged unconditionally, like every sweep here: a sweep that silently finds nothing reads as one that stopped.\n this.logger.info('[AgentWorkDecisions] Correction repair sweep complete', { ...result });\n return result;\n }\n\n /**\n * Write the record an execution row still OWES, from its resolution columns (`ROW_REPAIR`, metadata only), and clear\n * the marker. The repair sweep calls it; so does a settle about to OVERWRITE the resolution columns of a row whose\n * previous decision is still owed (review F3) — after that write the columns would describe the new decision and the\n * old record could never be repaired. `undefined` when the row owes nothing, or cannot be repaired (logged).\n */\n public async repairOwedRecordOfExecution(\n executionResourceType: CoreResourceType,\n row: ExecutionResolutionRow,\n /**\n * A person's ERASURE repays the record (#2865 review F1): it joins the erasure's transaction, leaves the erased\n * person off the record when they were its decider, and THROWS instead of answering `undefined`, because a failed\n * write inside a transaction has already aborted it and the erasure must fail rather than carry on inside it.\n */\n erasure?: { readonly transaction?: TransactionContext; readonly erasedUserId: string },\n /**\n * A DELETION repays the record before the row goes (#2297): it joins the deletion's transaction and THROWS instead of\n * answering `undefined`, for the erasure's reason (a failed write has aborted the transaction). The decider stays.\n */\n inTransaction?: { readonly transaction: TransactionContext },\n ): Promise<AgentWorkRecordResultKind | undefined> {\n const decisionRef = row.pendingCorrectionRecordRef;\n if (!decisionRef) return undefined;\n const decidedAt = row.decidedAt ? new Date(row.decidedAt) : undefined;\n const owner = agentWorkOwnerOfExecution(executionResourceType, row);\n if (!owner || !decidedAt || !owedRecordIsRepairableFromRow(executionResourceType, row)) {\n this.logger.error('[AgentWorkDecisions] A marked execution does not carry the resolution its marker names; the record cannot be repaired from it', {\n resourceType: executionResourceType, executionId: row.executionId, decisionRef, lastResolvedDecisionRef: row.lastResolvedDecisionRef,\n });\n return undefined;\n }\n try {\n return await this.recordDecision({\n owner,\n decisionRef,\n surface: AgentWorkDecisionSurface.TOOL_CALL_APPROVAL,\n outcome: row.decisionOutcome as HumanDecision_Outcome,\n agentRef: row.systemRef,\n ...(row.decisionToolName ? { toolName: row.decisionToolName } : {}),\n ...(row.caseRef ? { caseRef: row.caseRef } : {}),\n executionRef: { kind: ExecutionRefKind.CONVERSATIONAL_EXECUTION, id: row.executionId },\n fallbackPaths: row.decisionModifiedArgumentNames ?? [],\n ...(row.decidedByUserId && row.decidedByUserId !== erasure?.erasedUserId ? { deciderUserId: row.decidedByUserId } : {}),\n // Review F4: the route columns are cleared by the settle; the marker kept what the record needs of them.\n ...(row.pendingCorrectionAdmittedByRole ? { admittedByRole: row.pendingCorrectionAdmittedByRole } : {}),\n ...(row.pendingCorrectionOrganizationId ? { routeOrganizationId: row.pendingCorrectionOrganizationId } : {}),\n presentedAt: row.pendingCorrectionPresentedAt ? new Date(row.pendingCorrectionPresentedAt) : decidedAt,\n decidedAt,\n recordSource: AgentWorkDecisionRecordSource.ROW_REPAIR,\n }, { executionResourceType, executionId: row.executionId }, (erasure?.transaction ?? inTransaction?.transaction) ? { transaction: (erasure?.transaction ?? inTransaction?.transaction)! } : undefined);\n } catch (error) {\n if (erasure || inTransaction) throw error;\n this.logger.error('[AgentWorkDecisions] An owed decision record could not be repaired; the marker stays', {\n resourceType: executionResourceType, executionId: row.executionId, decisionRef, reason: describeCaughtError(error),\n });\n return undefined;\n }\n }\n\n /** Clear an execution's marker, only while it still names this decision (a compare-and-swap). Never throws. */\n private async clearCorrectionMarker(marker: AgentWorkCorrectionMarker, decisionRef: string, options?: RepositoryOptions): Promise<void> {\n try {\n await this.repositoriesRegistry.bulkUpdateForInfrastructure(\n marker.executionResourceType,\n { executionId: marker.executionId, pendingCorrectionRecordRef: decisionRef },\n { clear: ['pendingCorrectionRecordRef', 'pendingCorrectionPresentedAt', 'pendingCorrectionOrganizationId', 'pendingCorrectionAdmittedByRole'] },\n undefined,\n options,\n );\n } catch (error) {\n // Inside a transaction the failure may already have aborted it: rethrow, so its owner fails rather than writing on\n // (the engine's one rule for a caught write failure, #3093).\n if (writeFailureEndsTheOperation(error, options?.transaction !== undefined)) throw error;\n // The record exists; a marker left behind only makes the repair sweep find it again and leave it (idempotent).\n this.logger.warn('[AgentWorkDecisions] A correction marker could not be cleared; the repair sweep will clear it', {\n resourceType: marker.executionResourceType, executionId: marker.executionId, reason: describeCaughtError(error),\n });\n }\n }\n\n // ─── The override rate (D6, I6) ───────────────────────────────────────────\n\n /**\n * The override rate per group over a window. LAPSED, WITHDRAWN and REQUESTER_AUTHORITY_LAPSED are counted as\n * `notDecided` and never enter the rate (I6). Metadata only: no content is read.\n */\n public async summarizeOverrideRate(request: AgentWorkOverrideRateRequest): Promise<AgentWorkOverrideRate> {\n const filter: Record<string, unknown> = {\n decidedAt: { $gte: new Date(request.from), $lt: new Date(request.to) },\n // An organization's override rate (#2618): the decisions on work done in it, and the decisions its own people took\n // in the organizations it represents in. A representing organization reads its people's rate across them; a\n // granting organization reads the decisions taken on its own cases, whoever took them.\n ...(request.organizationId ? { $or: [{ workOrganizationId: request.organizationId }, { representingOrganizationId: request.organizationId }] } : {}),\n ...(request.agentRef ? { agentRef: request.agentRef } : {}),\n };\n const groups = new Map<string, AgentWorkOverrideRateGroup>();\n for (const row of await this.readDecisions(filter)) {\n const { mapKey, key } = overrideRateGroupKeyOf(row, request.groupBy);\n const group = groups.get(mapKey) ?? { key, accepted: 0, acceptedWithModifications: 0, rejected: 0, notDecided: 0, overrideRate: null };\n switch (row.outcome) {\n case HumanDecision_Outcome.ACCEPTED: group.accepted += 1; break;\n case HumanDecision_Outcome.ACCEPTED_WITH_MODIFICATIONS: group.acceptedWithModifications += 1; break;\n case HumanDecision_Outcome.REJECTED: group.rejected += 1; break;\n case HumanDecision_Outcome.LAPSED:\n case HumanDecision_Outcome.WITHDRAWN:\n case HumanDecision_Outcome.REQUESTER_AUTHORITY_LAPSED:\n group.notDecided += 1; break;\n }\n groups.set(mapKey, group);\n }\n return {\n window: { from: request.from, to: request.to },\n groupBy: request.groupBy,\n groups: [...groups.values()].map((group) => ({ ...group, overrideRate: agentWorkOverrideRate(group) })),\n };\n }\n\n /**\n * Decision time per case (#1598's `DecisionTimeSource`): the decisions a person took on each case and\n * `Σ (decidedAt − presentedAt)`. Only decisions someone made count; a lapse is the absence of review, not review.\n */\n public async reviewTimeByCase(caseRefs: readonly WorkUnitRef[], options?: { readonly representingOrganizationId?: string }): Promise<ReadonlyMap<string, { decisionCount: number; reviewDurationMs: number }>> {\n const result = new Map<string, { decisionCount: number; reviewDurationMs: number }>();\n if (caseRefs.length === 0) return result;\n const cases = {\n $or: caseRefs.map((caseRef) => ({ 'caseRef.resourceType': caseRef.resourceType, 'caseRef.resourceId': caseRef.resourceId })),\n };\n // A representing organization's own review time only (#2618): another one working the same case keeps its own.\n const filter = options?.representingOrganizationId\n ? { $and: [cases, relationshipOwnWorkFilter(options.representingOrganizationId, RelationshipOwnWorkTenantField.DECISION)] }\n : cases;\n for (const row of await this.readDecisions(filter)) {\n if (!row.caseRef || !AGENT_WORK_DECISION_RATED_OUTCOMES.includes(row.outcome)) continue;\n const key = agentWorkCaseKey(row.caseRef);\n const entry = result.get(key) ?? { decisionCount: 0, reviewDurationMs: 0 };\n entry.decisionCount += 1;\n entry.reviewDurationMs += Math.max(0, new Date(row.decidedAt).getTime() - new Date(row.presentedAt).getTime());\n result.set(key, entry);\n }\n return result;\n }\n\n // ─── The evaluation export (D7, I7) ───────────────────────────────────────\n\n /**\n * Export one organization's decisions on one agent's proposals over a window, as pseudonymised JSON Lines, and\n * record the export on the ledger. Refused and audited without an ACTIVE authorisation of that organization (I7).\n *\n * This is the ONE door an evaluation dataset leaves through, so both controls live here: kept content is minimised\n * by its declared shape (#1923, {@link minimisedContentOf}), and no case of an excluded case subject leaves (#1925). It is\n * refused as a CONFIGURATION error when an excluded case subject can no longer be found through a declaration.\n *\n * assurance-control: WILDO.PRIVACY.SECONDARY_USE_AUTHORIZATION — no export leaves without an ACTIVE authorisation naming\n * the basis it rests on.\n * assurance-control: WILDO.PRIVACY.COLLECTION_DATA_EXPORT — every export and every refusal is on the audit trail.\n */\n public async exportEvaluationDataset(request: EvaluationDatasetExportRequest, executionContext: ExecutionContext<any>): Promise<EvaluationDatasetExportResult> {\n const actorUserId = executionContext.initiatorIds?.userId;\n const authorization = await this.repositoriesRegistry.readUnscopedByKey<EvaluationExportAuthorization>(\n CoreResourceType.EVALUATION_EXPORT_AUTHORIZATIONS, { organizationId: request.organizationId },\n );\n // An ACTIVE row always carries its basis (the write that would leave one without it is refused); a row that somehow\n // does not is treated as no authorisation, never exported under an unnamed basis.\n if (!authorization || authorization.status !== EvaluationExportAuthorizationStatus.ACTIVE || !authorization.basis) {\n // NOT_GRANTED (the row the settings page creates) is \"nobody granted one\", exactly like no row.\n const reason = authorization?.status === EvaluationExportAuthorizationStatus.REVOKED\n ? EvaluationDatasetExportRefusalReason.AUTHORIZATION_REVOKED\n : EvaluationDatasetExportRefusalReason.NO_AUTHORIZATION;\n await this.auditLogs()?.logEvaluationDatasetExportRefused({\n organizationId: request.organizationId, agentRef: request.agentRef, reason, ...(actorUserId ? { attemptedByUserId: actorUserId } : {}),\n }, executionContext).catch((error: unknown) => this.logger.error('[AgentWorkDecisions] A refused export could not be audited', { reason: describeCaughtError(error) }));\n throw this.errorBuilder.buildError(ErrorType.AUTHORIZATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.AUTHORIZATIONS_ACCESS_DENIED,\n context: { reason: `evaluation_export_refused_${reason}` },\n });\n }\n\n const pseudonymPurposeKey = applicationSymmetricKeyOf(this.appConfig, CryptoKey_Purpose.EVALUATION_PSEUDONYM);\n if (!pseudonymPurposeKey) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: 'An evaluation export pseudonymises under the evaluation-pseudonym key, and this runtime holds none.' },\n });\n }\n const pseudonymKey = deriveEvaluationPseudonymKey(pseudonymPurposeKey, request.organizationId);\n const excluded = new Set(authorization.excludedCaseRefs.map(agentWorkCaseKey));\n const excludedSubjects = new Set((authorization.excludedSubjectRefs ?? []).map(agentWorkSubjectKey));\n const consented = new Set(authorization.subjectConsents.map((consent) => agentWorkCaseKey(consent.caseRef)));\n const privilegedTypes = new Set(this.reviewConfig()?.privilegedCaseResourceTypes ?? []);\n // Art. 6(4)(c): a case whose resource declares special-category (Art. 9) or criminal-offence data leaves only with\n // its case subject's recorded consent too — the same door as privileged work, read from the resource's own schema.\n const needsConsent = (resourceType: string): boolean => privilegedTypes.has(resourceType) || this.declaresRestrictedPersonalData(resourceType);\n\n const caseSubjects = this.resolvedCaseSubjectDeclarations();\n // An exclusion no declaration resolves any more (the application removed or broke its case subject field) would silently\n // stop excluding: refuse the export instead, so a case subject's opt-out never lapses because a configuration changed.\n const unresolvable = this.undeclaredExcludedSubjectRefs(authorization.excludedSubjectRefs ?? [], caseSubjects);\n if (unresolvable.length > 0) {\n this.logger.error('[AgentWorkDecisions] An export authorisation excludes case subjects no case-subject declaration resolves; the export is refused', {\n organizationId: request.organizationId, subjectResourceTypes: [...new Set(unresolvable.map((subjectRef) => subjectRef.resourceType))],\n });\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, executionContext, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: 'The export authorisation excludes case subjects of a resource no work-unit resource declares as its case subject (agentWorkReview.caseSubjects), so their cases cannot be found; the export is refused rather than run without the exclusion.' },\n });\n }\n const subjectOfCase = new Map<string, CaseSubjectAnswer>();\n const subjectAnswerOf = async (caseRef: WorkUnitRef): Promise<CaseSubjectAnswer> => {\n const caseKey = agentWorkCaseKey(caseRef);\n const cached = subjectOfCase.get(caseKey);\n if (cached) return cached;\n const answer = await this.subjectOfCase(caseRef, caseSubjects.get(caseRef.resourceType));\n subjectOfCase.set(caseKey, answer);\n return answer;\n };\n\n const candidates = (await this.readDecisions({\n workOrganizationId: request.organizationId,\n agentRef: request.agentRef,\n decidedAt: { $gte: new Date(request.from), $lt: new Date(request.to) },\n })).filter((row) => {\n if (!AGENT_WORK_DECISION_RATED_OUTCOMES.includes(row.outcome)) return false;\n if (!row.caseRef) return true;\n const caseKey = agentWorkCaseKey(row.caseRef);\n if (excluded.has(caseKey)) return false;\n // A privileged case, or one holding special-category or criminal-offence data, leaves only with its case subject's\n // recorded consent (SRA 6.3, ABA 512; GDPR Art. 6(4)(c), Art. 9(2)(a)).\n return !needsConsent(row.caseRef.resourceType) || consented.has(caseKey);\n });\n /*\n * #1925 — a case subject the organization excluded leaves in no export: every case whose declared case subject field names it,\n * opened before or after the exclusion, is read at THIS export. This is the one chokepoint every export passes, so\n * an exclusion cannot be honoured by one door and missed by another. Fail closed: while any case subject is excluded, a\n * case whose case subject cannot be read (its row is gone, or the declaration cannot be honoured) is left out, never\n * assumed to belong to nobody.\n *\n * assurance-control: WILDO.PRIVACY.SECONDARY_USE_AUTHORIZATION — a case subject's opt-out from evaluation use holds for all\n * of its cases, present and future.\n */\n const rows: AgentWorkDecision[] = [];\n for (const row of candidates) {\n if (row.caseRef && excludedSubjects.size > 0) {\n const subject = await subjectAnswerOf(row.caseRef);\n if (subject.kind === CaseSubjectAnswerKind.UNKNOWN) continue;\n if (subject.kind === CaseSubjectAnswerKind.SUBJECT && excludedSubjects.has(subject.subjectKey)) continue;\n }\n rows.push(row);\n }\n\n const lines: string[] = [];\n const caseKeys = new Set<string>();\n const subjectKeys = new Set<string>();\n const pseudonymOf = (identifier: string): string => pseudonymiseIdentifier(pseudonymKey, identifier);\n for (const row of rows) {\n const content = row.contentRecorded ? await this.readContent(row.decisionRef, request.organizationId) : undefined;\n if (row.caseRef) {\n caseKeys.add(agentWorkCaseKey(row.caseRef));\n // The ledger records each case's subject, so a later opt-out of that case subject finds this dataset (#1925).\n const subject = await subjectAnswerOf(row.caseRef);\n if (subject.kind === CaseSubjectAnswerKind.SUBJECT) subjectKeys.add(subject.subjectKey);\n }\n // The identifiers kept content may carry (a tool call names the case it acts on), replaced by their pseudonyms.\n const known = new Map<string, string>(\n [row.caseRef?.resourceId, row.workOrganizationId, row.deciderUserId, row.executionRef?.id, row.taskRef, row.finalWorkProductRef?.resourceId]\n .filter((identifier): identifier is string => typeof identifier === 'string' && identifier.length > 0)\n .map((identifier) => [identifier, pseudonymiseIdentifier(pseudonymKey, identifier)]),\n );\n const kept = content?.proposalJson || content?.finalJson ? this.minimisedContentOf(row, content, pseudonymOf, known) : undefined;\n // Minimisation: what evaluation needs. No decider, no organization; every identifier a pseudonym.\n lines.push(JSON.stringify({\n record: pseudonymiseIdentifier(pseudonymKey, row.decisionRef),\n ...(row.caseRef ? { case: pseudonymiseIdentifier(pseudonymKey, agentWorkCaseKey(row.caseRef)) } : {}),\n agentRef: row.agentRef,\n ...(row.agentVersion ? { agentVersion: row.agentVersion } : {}),\n ...(row.toolName ? { toolName: row.toolName } : {}),\n surface: row.surface,\n outcome: row.outcome,\n modifiedPaths: exportedModifiedPathsOf(row.modifiedPaths ?? [], kept),\n ...(row.editDistance !== undefined ? { editDistance: row.editDistance } : {}),\n ...(row.reasonCode ? { reasonCode: row.reasonCode } : {}),\n reviewDurationMs: Math.max(0, new Date(row.decidedAt).getTime() - new Date(row.presentedAt).getTime()),\n ...(kept && kept.withheld === undefined ? {\n ...(kept.proposal !== undefined ? { proposal: kept.proposal } : {}),\n ...(kept.final !== undefined ? { final: kept.final } : {}),\n ...(kept.diff !== undefined ? { diff: kept.diff } : {}),\n } : {}),\n ...(kept?.withheld ? { contentWithheld: kept.withheld } : {}),\n }));\n }\n\n const exportedAt = new Date();\n const ledger = await this.createRow<EvaluationDatasetExport>(CoreResourceType.EVALUATION_DATASET_EXPORTS, 'organizationId', request.organizationId, {\n ...(actorUserId ? { exportedByUserId: actorUserId } : {}),\n exportedAt,\n authorizationId: authorization._id,\n basis: authorization.basis,\n agentRef: request.agentRef,\n windowFrom: new Date(request.from),\n windowTo: new Date(request.to),\n decisionRefs: rows.map((row) => row.decisionRef),\n caseKeys: [...caseKeys],\n subjectKeys: [...subjectKeys],\n recordCount: rows.length,\n pseudonymisationVersion: EVALUATION_PSEUDONYMISATION_VERSION,\n destination: request.destination,\n });\n const exportId = ledger?._id;\n if (!exportId) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, executionContext, {\n customMessageReference: ErrorCustomMessageReference.SERVICE_RESOURCE_OPERATION_FAILED,\n context: { reason: 'evaluation_export_ledger_not_written' },\n });\n }\n await this.auditLogs()?.logEvaluationDatasetExported({\n exportId, organizationId: request.organizationId, agentRef: request.agentRef, basis: authorization.basis, recordCount: rows.length,\n windowFrom: request.from, windowTo: request.to, destination: request.destination, ...(actorUserId ? { exportedByUserId: actorUserId } : {}),\n }, executionContext);\n return { exportId, recordCount: rows.length, jsonl: lines.join('\\n'), pseudonymisationVersion: EVALUATION_PSEUDONYMISATION_VERSION };\n }\n\n // ─── Erasure (D5, D7) ─────────────────────────────────────────────────────\n\n /**\n * Rows of a work-unit resource were erased or deleted: scrub the content kept about them, in every scope, and mark\n * every dataset that exported them. The decision records survive — they are the evidence that the work was\n * supervised — and carry no content. Registered after `transaction` commits when there is one: a rolled-back\n * erasure keeps its content. A no-op for a resource that is not a work unit.\n *\n * Called from every delete the engine performs on a row: the services-registry handler's two row-removal seams\n * (service-tier deletes and cascades, and the erasure scrub), the `.ttl()` retention sweep's raw delete and the SYNC\n * seed's orphan delete. A native MongoDB TTL index deletes rows nothing in the engine observes, and is not covered.\n *\n * assurance-control: WILDO.PRIVACY.ERASURE_PROPAGATION — a case's erasure reaches the corrections kept about it.\n * assurance-control: WILDO.PRIVACY.SECONDARY_USE_AUTHORIZATION — and marks the datasets that carried them.\n */\n public async scheduleCaseRemoval(resourceType: ResourceType, rowIds: readonly string[], transaction?: TransactionContext): Promise<void> {\n if (rowIds.length === 0) return;\n let isWorkUnit = false;\n try {\n isWorkUnit = this.container.get<WorkUnitCaseBackendService>(SAAS_SERVICE_TYPES.WorkUnitCaseService).isWorkUnitResourceType(String(resourceType));\n } catch {\n isWorkUnit = false;\n }\n if (!isWorkUnit) return;\n // When the rows went: a late scrub (below) marks the datasets as of the deletion, as this one does.\n const removedAt = new Date();\n const reportFailure = (error: unknown): void => {\n this.logger.error('[AgentWorkDecisions] The content kept about an erased case could not be scrubbed', {\n resourceType, rowCount: rowIds.length, reason: describeCaughtError(error),\n });\n };\n const run = async (): Promise<void> => {\n try {\n await this.removeCaseContent(String(resourceType), rowIds, EvaluationDatasetInvalidationReason.SUBJECT_ERASURE, removedAt);\n } catch (error) {\n reportFailure(error);\n }\n };\n if (!transaction) {\n await run();\n return;\n }\n /*\n * #2930: capturable. Under an attempt its caller asked to capture (a purge the organization-purge sweep runs), the rows'\n * ids are kept in the post-commit effect outbox with the commit, and the caller's next run scrubs them once when this\n * effect never ran: the scrub is an erasure's propagation, and must not be lost to a commit whose outcome was never\n * learned. Idempotent (`removeCaseContent`: a scrubbed content row clears nothing more, a marked dataset is not marked\n * again), so a scrub repeated after a crash between the scrub and its row's claim changes nothing. Kept in rows of at\n * most `AGENT_WORK_CASE_REMOVAL_ROWS_PER_CAPTURED_EFFECT` ids, so a large purge keeps bounded rows.\n */\n registerTransactionPostCommitEffect(transaction, capturablePostCommitEffect({\n key: ['agent-work-case-removal', String(resourceType), ...[...rowIds].sort()].join(':'),\n execute: run,\n capture: idempotentSideEffectCapture({\n kind: CapturedPostCommitEffectKind.AGENT_WORK_CASE_REMOVAL,\n rows: () => chunked(rowIds, AGENT_WORK_CASE_REMOVAL_ROWS_PER_CAPTURED_EFFECT)\n .map((chunk) => ({ payload: { resourceType: String(resourceType), rowIds: chunk, removedAt } })),\n run: (payload) => this.removeCaseContent(payload.resourceType, payload.rowIds, EvaluationDatasetInvalidationReason.SUBJECT_ERASURE, payload.removedAt),\n onFailure: reportFailure,\n }),\n }));\n }\n\n /**\n * Scrub the case's content in every scope, and mark every dataset that exported one of these cases. Idempotent: a\n * scrubbed content row has nothing left to clear, and a dataset already marked keeps its first mark. `invalidatedAt` is\n * when the cases went (#2930: a scrub delivered late by a sweep marks as of the deletion); absent, now.\n */\n public async removeCaseContent(\n resourceType: string,\n rowIds: readonly string[],\n reason: EvaluationDatasetInvalidationReason,\n invalidatedAt: Date = new Date(),\n ): Promise<{ contentsScrubbed: number; datasetsMarked: number }> {\n let contentsScrubbed = 0;\n let datasetsMarked = 0;\n for (const resourceId of rowIds) {\n for (const variant of AGENT_WORK_VARIANTS) {\n contentsScrubbed += await this.repositoriesRegistry.bulkUpdateForInfrastructure(\n variant.contents,\n { 'caseRef.resourceType': resourceType, 'caseRef.resourceId': resourceId },\n { clear: ['proposalJson', 'finalJson', 'diffJson', 'reasonText'] },\n );\n }\n datasetsMarked += await this.repositoriesRegistry.bulkUpdateForInfrastructure(\n CoreResourceType.EVALUATION_DATASET_EXPORTS,\n { caseKeys: `${resourceType}:${resourceId}`, invalidatedAt: null },\n { set: { invalidatedAt, invalidationReason: reason } },\n );\n }\n if (contentsScrubbed > 0 || datasetsMarked > 0) {\n this.logger.info('[AgentWorkDecisions] An erased case\\'s corrections were scrubbed and its datasets marked', { resourceType, contentsScrubbed, datasetsMarked });\n }\n return { contentsScrubbed, datasetsMarked };\n }\n\n /**\n * An organization's export authorisation changed: mark every dataset a withdrawn basis no longer covers\n * (`CONSENT_WITHDRAWN`, #1599 D7), found through the ledger. A revocation marks every dataset exported under the\n * authorisation; a case subject consent removed, or a case newly walled off, marks the datasets that carried that case; a\n * case subject newly excluded (#1925) marks the datasets that carried any of its cases. A dataset already marked keeps its\n * first reason. Returns how many were marked.\n *\n * assurance-control: WILDO.PRIVACY.SECONDARY_USE_AUTHORIZATION — a withdrawn basis reaches every dataset exported under it.\n */\n public async invalidateDatasetsForAuthorizationChange(\n previous: Pick<EvaluationExportAuthorization, 'status' | 'subjectConsents' | 'excludedCaseRefs'> & Partial<Pick<EvaluationExportAuthorization, 'excludedSubjectRefs'>> | undefined,\n next: Pick<EvaluationExportAuthorization, '_id' | 'organizationId' | 'status' | 'subjectConsents' | 'excludedCaseRefs'> & Partial<Pick<EvaluationExportAuthorization, 'excludedSubjectRefs'>>,\n ): Promise<number> {\n if (!previous) return 0;\n const mark = { set: { invalidatedAt: new Date(), invalidationReason: EvaluationDatasetInvalidationReason.CONSENT_WITHDRAWN } };\n let marked = 0;\n // Any exit from ACTIVE withdraws the basis. The write path admits only REVOKED (NOT_GRANTED is refused once a row was\n // granted), and this reads the transition rather than the target so a future status cannot bypass the marking.\n if (previous.status === EvaluationExportAuthorizationStatus.ACTIVE && next.status !== EvaluationExportAuthorizationStatus.ACTIVE) {\n marked += await this.repositoriesRegistry.bulkUpdateForInfrastructure(\n CoreResourceType.EVALUATION_DATASET_EXPORTS, { organizationId: next.organizationId, authorizationId: next._id, invalidatedAt: null }, mark,\n );\n }\n const stillConsented = new Set((next.subjectConsents ?? []).map((consent) => agentWorkCaseKey(consent.caseRef)));\n const previouslyExcluded = new Set((previous.excludedCaseRefs ?? []).map(agentWorkCaseKey));\n const withdrawn = new Set([\n ...(previous.subjectConsents ?? []).map((consent) => agentWorkCaseKey(consent.caseRef)).filter((key) => !stillConsented.has(key)),\n ...(next.excludedCaseRefs ?? []).map(agentWorkCaseKey).filter((key) => !previouslyExcluded.has(key)),\n ]);\n for (const caseKey of withdrawn) {\n marked += await this.repositoriesRegistry.bulkUpdateForInfrastructure(\n CoreResourceType.EVALUATION_DATASET_EXPORTS, { organizationId: next.organizationId, caseKeys: caseKey, invalidatedAt: null }, mark,\n );\n }\n /*\n * #1925 — a case subject newly excluded withdraws every dataset that carried one of its cases, found two ways: through the\n * ledger's `subjectKeys` (the case subject of each case as it stood when exported), and through the case subject's CURRENT cases'\n * `caseKeys`. The second reaches a dataset exported before the application declared its case subject field, or while the\n * case's subject could not be read (review F3): the ledger then recorded no case subject, and the first way alone would\n * fail open. Removing a case subject from the exclusion marks nothing.\n */\n const previouslyExcludedSubjects = new Set((previous.excludedSubjectRefs ?? []).map(agentWorkSubjectKey));\n const newlyExcludedSubjects = (next.excludedSubjectRefs ?? []).filter((subjectRef) => !previouslyExcludedSubjects.has(agentWorkSubjectKey(subjectRef)));\n for (const subjectRef of newlyExcludedSubjects) {\n marked += await this.repositoriesRegistry.bulkUpdateForInfrastructure(\n CoreResourceType.EVALUATION_DATASET_EXPORTS, { organizationId: next.organizationId, subjectKeys: agentWorkSubjectKey(subjectRef), invalidatedAt: null }, mark,\n );\n for (const caseKey of await this.currentCaseKeysOfSubject(subjectRef)) {\n marked += await this.repositoriesRegistry.bulkUpdateForInfrastructure(\n CoreResourceType.EVALUATION_DATASET_EXPORTS, { organizationId: next.organizationId, caseKeys: caseKey, invalidatedAt: null }, mark,\n );\n }\n }\n if (marked > 0) this.logger.info('[AgentWorkDecisions] Datasets a withdrawn export basis no longer covers were marked', { organizationId: next.organizationId, marked });\n return marked;\n }\n\n // ─── Internals ────────────────────────────────────────────────────────────\n\n // ─── Case subjects (#1925) ──────────────────────────────────────────────────────\n\n /**\n * The application's case-subject declarations (`agentWorkReview.caseSubjects`), each resolved to its case subject resource:\n * the resource the declared field's relationship points at. A declaration whose field is not a foreign key of the\n * case resource, or whose relationship cannot be followed, resolves to no case subject resource and is logged.\n */\n public resolvedCaseSubjectDeclarations(): ReadonlyMap<string, ResolvedCaseSubjectDeclaration> {\n const resolved = new Map<string, ResolvedCaseSubjectDeclaration>();\n let registry: ResourcesRegistryBackendService | undefined;\n try {\n registry = this.container.get<ResourcesRegistryBackendService>(SAAS_SERVICE_TYPES.ResourceRegistryService);\n } catch {\n registry = undefined;\n }\n for (const declaration of this.reviewConfig()?.caseSubjects ?? []) {\n const subjectResourceType = registry ? this.subjectResourceTypeOf(registry, declaration.caseResourceType, declaration.subjectField) : undefined;\n if (!subjectResourceType) {\n this.logger.error('[AgentWorkDecisions] A case-subject declaration names no foreign key the registry can follow; exports fail closed on its cases while any case subject is excluded', {\n caseResourceType: declaration.caseResourceType, subjectField: declaration.subjectField,\n });\n }\n resolved.set(declaration.caseResourceType, { ...declaration, ...(subjectResourceType ? { subjectResourceType } : {}) });\n }\n return resolved;\n }\n\n /**\n * The resource types each resource reference target set holds (#2471): what `/application-config` publishes as\n * `resourceReferenceTargets`, so a form offers the types a reference may name and then the rows of the one chosen.\n *\n * Total over `ResourceReferenceTargetSet` by construction: the record is typed by the vocabulary, so a set added to it\n * fails to compile until it is derived here. Each list is sorted, an empty one meaning \"this application has none\".\n * Throws when the resource registry cannot be read, rather than publishing an empty case list that would read as an\n * answer; the caller then omits the field and a form falls back to text inputs.\n */\n public resourceReferenceTargets(): Record<ResourceReferenceTargetSet, string[]> {\n const registry = this.container.get<ResourcesRegistryBackendService>(SAAS_SERVICE_TYPES.ResourceRegistryService);\n const derive: Record<ResourceReferenceTargetSet, () => string[]> = {\n [ResourceReferenceTargetSet.WORK_UNIT_CASES]: () => registry.getResourceTypes()\n .filter((resourceType) => registry.tryGetResourceConfiguration(resourceType)?.workUnit === true)\n .map(String),\n [ResourceReferenceTargetSet.WORK_UNIT_SUBJECTS]: () => [...this.resolvedCaseSubjectDeclarations().values()]\n .map((declaration) => declaration.subjectResourceType)\n .filter((resourceType): resourceType is string => !!resourceType),\n };\n const published = {} as Record<ResourceReferenceTargetSet, string[]>;\n for (const targetSet of Object.values(ResourceReferenceTargetSet)) published[targetSet] = [...new Set(derive[targetSet]())].sort();\n return published;\n }\n\n /**\n * The case subject references an authorisation write excludes that no declaration can ever match: a case subject of a resource\n * no work-unit resource declares as its case subject. An exclusion that excludes nothing would read as a control and be\n * none, so the write refuses it (#1925).\n */\n public undeclaredExcludedSubjectRefs(\n subjectRefs: readonly AgentWorkSubjectRef[],\n declarations: ReadonlyMap<string, ResolvedCaseSubjectDeclaration> = this.resolvedCaseSubjectDeclarations(),\n ): AgentWorkSubjectRef[] {\n if (subjectRefs.length === 0) return [];\n const declaredSubjectTypes = new Set([...declarations.values()]\n .map((declaration) => declaration.subjectResourceType)\n .filter((type): type is string => !!type));\n return subjectRefs.filter((subjectRef) => !declaredSubjectTypes.has(subjectRef.resourceType));\n }\n\n /**\n * The resource a case resource's `subjectField` points at, through the case resource's own relationships: the\n * relationship whose compiled foreign key is `subjectField` HELD by the case resource (read from the compiled holder,\n * never from declaration order, which an author may write either way), and whose other side is the case subject.\n */\n private subjectResourceTypeOf(registry: ResourcesRegistryBackendService, caseResourceType: string, subjectField: string): string | undefined {\n try {\n const configuration = registry.getResourceConfiguration(caseResourceType as ResourceType);\n if (configuration?.workUnit !== true || !schemaDeclaresForeignKeyField(configuration.mainSchema, subjectField)) return undefined;\n const buckets = configuration.resourceRelationships;\n for (const relationship of [...buckets.parentRelationships, ...buckets.childRelationships, ...buckets.selfRelationships]) {\n const compiled = relationship.resolvedSemantics?.persistence?.foreignKey;\n const holder = compiled?.holderResourceType ?? Resources_SharedUtils.resolveForeignKeyHolderResourceType(relationship);\n const field = compiled?.fieldIdentifier ?? relationship.foreignKeyField;\n if (holder !== caseResourceType || field !== subjectField || compiled?.isArray) continue;\n return String(relationship.resourceType1 === caseResourceType ? relationship.resourceType2 : relationship.resourceType1);\n }\n return undefined;\n } catch {\n return undefined;\n }\n }\n\n /** The keys of every case whose declared case subject field names `subjectRef` today, across every declaring case resource. */\n private async currentCaseKeysOfSubject(subjectRef: AgentWorkSubjectRef): Promise<string[]> {\n const keys: string[] = [];\n for (const declaration of this.resolvedCaseSubjectDeclarations().values()) {\n if (declaration.subjectResourceType !== subjectRef.resourceType) continue;\n let after: string | undefined;\n for (;;) {\n const filter = { [declaration.subjectField]: subjectRef.resourceId };\n const page = await this.repositoriesRegistry.findManyForInfrastructure<{ _id: unknown }>(\n declaration.caseResourceType as ResourceType,\n after ? { $and: [filter, { _id: { $gt: after } }] } : filter,\n undefined,\n undefined,\n { sort: [{ field: '_id', order: SortOrder.ASC }], limit: PAGE_SIZE },\n );\n keys.push(...page.map((row) => agentWorkCaseKey({ resourceType: declaration.caseResourceType, resourceId: String(row._id) })));\n if (page.length < PAGE_SIZE) break;\n after = String(page[page.length - 1]!._id);\n }\n }\n return keys;\n }\n\n /** The case subject of one case, read from its row through the declared field. */\n private async subjectOfCase(caseRef: WorkUnitRef, declaration: ResolvedCaseSubjectDeclaration | undefined): Promise<CaseSubjectAnswer> {\n if (!declaration) return { kind: CaseSubjectAnswerKind.NO_SUBJECT_DECLARED };\n if (!declaration.subjectResourceType) return { kind: CaseSubjectAnswerKind.UNKNOWN };\n try {\n const row = await this.repositoriesRegistry.readUnscopedByKey<Record<string, unknown>>(caseRef.resourceType as ResourceType, { _id: caseRef.resourceId });\n if (!row) return { kind: CaseSubjectAnswerKind.UNKNOWN };\n const subjectId = row[declaration.subjectField];\n if (subjectId === undefined || subjectId === null || subjectId === '') return { kind: CaseSubjectAnswerKind.NO_SUBJECT };\n // One case subject per case: a value that is not one id (an array, an object) cannot be matched, so it is unknown (review F7).\n if (typeof subjectId !== 'string' && typeof subjectId !== 'number') return { kind: CaseSubjectAnswerKind.UNKNOWN };\n return { kind: CaseSubjectAnswerKind.SUBJECT, subjectKey: agentWorkSubjectKey({ resourceType: declaration.subjectResourceType, resourceId: String(subjectId) }) };\n } catch {\n return { kind: CaseSubjectAnswerKind.UNKNOWN };\n }\n }\n\n // ─── Content minimisation (#1923) ─────────────────────────────────────────\n\n /**\n * The declared shape a record's kept content is read against: a tool call's arguments by the tool's argument schema\n * (and, for a resource write tool, the resource's main schema and its row-id argument); an output review's proposal\n * and final version by the main schema of the final work product's resource. An actor review's content is free-form.\n */\n private contentShapeOf(row: AgentWorkDecision): ContentShapeAnswer {\n switch (row.surface) {\n case AgentWorkDecisionSurface.TOOL_CALL_APPROVAL: {\n const tool = row.toolName ? this.functionToolOf(row.agentRef, row.toolName) : undefined;\n if (!tool) return { withheld: EvaluationContentWithholdingReason.SHAPE_NOT_RESOLVED };\n const resourceSchemas = tool.argumentsResource ? this.resourceSchemasOf(tool.argumentsResource.resourceType) : undefined;\n // A resource the tool declares but the registry no longer knows: half a shape is not a shape.\n if (tool.argumentsResource && !resourceSchemas) return { withheld: EvaluationContentWithholdingReason.SHAPE_NOT_RESOLVED };\n return { shape: {\n schemas: [tool.inputSchema, ...(resourceSchemas ?? [])],\n ...(tool.argumentsResource?.rowIdArgument ? { identifierKeys: [tool.argumentsResource.rowIdArgument] } : {}),\n } };\n }\n case AgentWorkDecisionSurface.OUTPUT_REVIEW: {\n if (!row.finalWorkProductRef) return { withheld: EvaluationContentWithholdingReason.SURFACE_DECLARES_NO_SHAPE };\n const schemas = this.resourceSchemasOf(row.finalWorkProductRef.resourceType);\n return schemas ? { shape: { schemas } } : { withheld: EvaluationContentWithholdingReason.SHAPE_NOT_RESOLVED };\n }\n case AgentWorkDecisionSurface.ACTOR_REVIEW:\n return { withheld: EvaluationContentWithholdingReason.SURFACE_DECLARES_NO_SHAPE };\n }\n }\n\n /**\n * One record's kept content, minimised for export: each version read against its declared shape, then the record's\n * own identifiers replaced inside what is left, and the diff recomputed from the two minimised versions (a patch of\n * the raw versions would carry the raw values back). Withheld as a whole when either version cannot be vouched for.\n */\n private minimisedContentOf(\n row: AgentWorkDecision,\n content: AgentWorkDecisionContent,\n pseudonymOf: (identifier: string) => string,\n known: ReadonlyMap<string, string>,\n ): { proposal?: unknown; final?: unknown; diff?: unknown; withheld?: EvaluationContentWithholdingReason } {\n const answer = this.contentShapeOf(row);\n if (!answer.shape) return { withheld: answer.withheld };\n const minimise = (json: string | undefined): { value?: unknown; outside: boolean } => {\n if (json === undefined) return { outside: false };\n const minimised = minimiseContentByDeclaredShape(JSON.parse(json), answer.shape, pseudonymOf);\n return minimised === undefined ? { outside: true } : { value: pseudonymiseKnownIdentifiers(minimised, known), outside: false };\n };\n const proposal = minimise(content.proposalJson);\n const final = minimise(content.finalJson);\n if (proposal.outside || final.outside) return { withheld: EvaluationContentWithholdingReason.CONTENT_OUTSIDE_SHAPE };\n return {\n ...(proposal.value !== undefined ? { proposal: proposal.value } : {}),\n ...(final.value !== undefined ? { final: final.value } : {}),\n ...(proposal.value !== undefined && final.value !== undefined ? { diff: correctionJsonPatch(proposal.value, final.value) } : {}),\n };\n }\n\n /**\n * Every schema a row of the resource can have, its main schema and each inheritance variant (#2455), or `undefined`\n * when the registry does not know the resource. The main schema alone read a variant's keys as outside the shape, so\n * the whole record was withheld from export.\n */\n private resourceSchemasOf(resourceType: string): unknown[] | undefined {\n try {\n const configuration = this.container.get<ResourcesRegistryBackendService>(SAAS_SERVICE_TYPES.ResourceRegistryService)\n .tryGetResourceConfiguration(resourceType as ResourceType);\n if (!configuration?.mainSchema) return undefined;\n return [configuration.mainSchema, ...resourceInheritanceVariantSchemas(configuration.inheritenceSchemaDefinition as never)];\n } catch {\n return undefined;\n }\n }\n\n /**\n * The function tool a settled call named: the agent the actor system converses through (the same rule the turn\n * uses), and among its declared tools the one exposed to the model under `toolName`.\n */\n private functionToolOf(systemRef: string, toolName: string) {\n try {\n const registry = this.container.get<FlowsActorsRegistryService>(SAAS_SERVICE_TYPES.FlowsActorsRegistryService);\n const system = registry.getSystem(systemRef, FlowActorSystem_Kind.ACTOR) as ActorSystem | undefined;\n const agentRef = system ? chatAgentRefOfActorSystem(system) : undefined;\n const agent = agentRef ? registry.getAgent(agentRef) : undefined;\n const functionRef = (agent?.capabilities?.tools?.functionRefs ?? []).find((ref) => modelToolNameForFunctionRef(ref) === toolName);\n return functionRef ? registry.getFunctionTool(functionRef) : undefined;\n } catch {\n return undefined;\n }\n }\n\n /** Every decision record matching `filter`, in every scope, read in key-ordered pages. */\n private async readDecisions(filter: Record<string, unknown>): Promise<AgentWorkDecision[]> {\n const rows: AgentWorkDecision[] = [];\n for (const variant of AGENT_WORK_VARIANTS) {\n let after: string | undefined;\n for (;;) {\n const page = await this.repositoriesRegistry.findManyForInfrastructure<AgentWorkDecision>(\n variant.decisions,\n after ? { $and: [filter, { _id: { $gt: after } }] } : filter,\n undefined,\n undefined,\n { sort: [{ field: '_id', order: SortOrder.ASC }], limit: PAGE_SIZE },\n );\n rows.push(...page);\n if (page.length < PAGE_SIZE) break;\n after = String(page[page.length - 1]!._id);\n }\n }\n return rows;\n }\n\n /**\n * The content row of a decision, in whichever scope it was written — and only the tenant's own (review F6): a\n * reference reused in another store can never join its content into this tenant's dataset.\n */\n private async readContent(decisionRef: string, workOrganizationId: string): Promise<AgentWorkDecisionContent | undefined> {\n for (const variant of AGENT_WORK_VARIANTS) {\n const row = await this.repositoriesRegistry.readUnscopedByKey<AgentWorkDecisionContent>(variant.contents, { decisionRef, workOrganizationId });\n if (row) return row;\n }\n return undefined;\n }\n\n /**\n * Whether the decision's content row exists, read in the record's transaction when the content lives on its database.\n * A refused or missing row answers `false`; a store failure of a read that shared the transaction ends the record,\n * since that transaction may already be aborted (`readFailureEndsTheOperation`, #3091).\n */\n private async contentRowExists(contents: CoreResourceType, decisionRef: string, options?: RepositoryOptions): Promise<boolean> {\n const readOptions = readOptionsOnItsOwnDatabase(this.repositoriesRegistry, contents as ResourceType, options);\n try {\n return !!(await this.repositoriesRegistry.readUnscopedByKey(contents, { decisionRef }, readOptions));\n } catch (error) {\n if (readFailureEndsTheOperation(error, readOptions?.transaction !== undefined)) throw error;\n return false;\n }\n }\n\n /**\n * Create a row through the repository, as the engine. The owner FK is named in `preserveServerInjectedFields`\n * because the CREATE DTO drops FK fields. A duplicate `decisionRef` (a concurrent writer won) answers `null`.\n */\n private async createRow<T>(resourceType: CoreResourceType, ownerField: string, ownerId: string, document: Record<string, unknown>, options?: RepositoryOptions): Promise<T | null> {\n const repository = this.repositoriesRegistry.getRepositoryOrThrow(resourceType, {} as ExecutionContext<any>);\n // These resources' CREATE is an INTERNAL_CALL (the service tier's), not REPOSITORY_ONLY: the SERVICE default\n // resolver is the one that serves it. `createForInternalRepositoryOperation` resolves REPOSITORY_ONLY or a\n // URL-bearing default, and neither exists here — which is what failed on the first live run.\n const operation = this.container.get<ResourcesRegistryBackendService>(SAAS_SERVICE_TYPES.ResourceRegistryService)\n .getServiceOperationPathDefault(resourceType, CoreResourceOperation.CREATE);\n const context = await this.container.get<ExecutionContextCreatorBackendService>(SAAS_SERVICE_TYPES.ExecutionContextCreatorBackendService)\n .createForInternalOperation({ operation });\n try {\n return await repository.create(context, { ...document, [ownerField]: ownerId } as T, { ...options, preserveServerInjectedFields: [ownerField] }) as T;\n } catch (error) {\n // Inside a transaction a failed insert has aborted it (both stores), so there is no winner to read in it (#3093).\n if (writeFailureEndsTheOperation(error, options?.transaction !== undefined)) throw error;\n const decisionRef = document['decisionRef'];\n if (typeof decisionRef === 'string') {\n // The unique `decisionRef`: another writer recorded this decision first (I1).\n const winner = await this.repositoriesRegistry.readUnscopedByKey(resourceType, { decisionRef }).catch(() => null);\n if (winner) return null;\n }\n throw error;\n }\n }\n\n /** The tenant the work was done for: the case row's organization, else the route's, else the owner organization. */\n /**\n * The decider's standing in the tenant the work was done in: the representing organization a decision is attributed to\n * (#2618, `resolveRelationshipWorkAttribution`), and the one relationship they stand there through (#2722,\n * `resolveRelationshipOnlyStanding`), whose work the decision and its content are. The rows are written on the\n * engine's own context, outside any operation, so without it they were the tenant's own and every other relationship\n * reaching the tenant's records could read one relationship's corrections (review of the asynchronous writers, M1).\n *\n * Read from their CURRENT role entries there, through the one rebuild of a person's authority. One of the tenant's\n * own, a lapsed decider, an unreadable rebuild or no tenant all answer none, which leaves the decision the tenant's\n * own. Accounting, never authority.\n */\n private async standingOfDecider(deciderUserId: string | undefined, workOrganizationId: string | undefined): Promise<{ representingOrganizationId?: string; relationshipId?: string }> {\n if (!deciderUserId || !workOrganizationId) return {};\n try {\n const creator = this.container.get<ExecutionContextCreatorBackendService>(SAAS_SERVICE_TYPES.ExecutionContextCreatorBackendService);\n const member = await creator.rebuildMemberAuthority({ userId: deciderUserId, organizationId: workOrganizationId });\n // A lapsed standing carries no `auth` (narrowed by shape: this module reaches the creator only lazily, and a value\n // import of its enum would put the construction cycle the container avoids back at module load).\n if (!('auth' in member)) return {};\n const representingOrganizationId = resolveRelationshipWorkAttribution(member.auth.initiatorRoles, workOrganizationId)?.representingOrganizationId;\n const relationships = resolveRelationshipOnlyStanding(member.auth.initiatorRoles, workOrganizationId);\n return {\n ...(representingOrganizationId ? { representingOrganizationId } : {}),\n ...(relationships?.length === 1 ? { relationshipId: relationships[0] } : {}),\n };\n } catch (error) {\n this.logger.info('[AgentWorkDecisions] The decider\\'s standing could not be read; the decision is recorded as the tenant\\'s own', {\n reason: describeCaughtError(error),\n });\n return {};\n }\n }\n\n private async workOrganizationOf(write: AgentWorkDecisionWrite, options?: RepositoryOptions): Promise<string | undefined> {\n const caseOrganizationId = write.caseRef ? await this.caseOrganizationOf(write.caseRef, options) : undefined;\n return caseOrganizationId ?? write.routeOrganizationId ?? ('organizationId' in write.owner ? write.owner.organizationId : undefined);\n }\n\n /** A case row's `organizationId`, read by key with no scope filter: the engine asks, and the answer decides the tenant. */\n private async caseOrganizationOf(caseRef: WorkUnitRef, options?: RepositoryOptions): Promise<string | undefined> {\n const readOptions = readOptionsOnItsOwnDatabase(this.repositoriesRegistry, caseRef.resourceType as ResourceType, options);\n try {\n const row = await this.repositoriesRegistry.readUnscopedByKey<{ organizationId?: unknown }>(caseRef.resourceType as ResourceType, { _id: caseRef.resourceId }, readOptions);\n return typeof row?.organizationId === 'string' && row.organizationId.length > 0 ? row.organizationId : undefined;\n } catch (error) {\n // Inside the caller's transaction a store failure may have aborted it: ended here, not masked (#3091).\n if (readFailureEndsTheOperation(error, readOptions?.transaction !== undefined)) throw error;\n return undefined;\n }\n }\n\n /** Whether the organization keeps content for this case: `WITH_CONTENT`, and the case within its narrowing. */\n private async contentCaptureHolds(organizationId: string | undefined, caseRef: WorkUnitRef | undefined): Promise<boolean> {\n if (!organizationId) return false;\n const settings = await this.repositoriesRegistry.readUnscopedByKey<AgentWorkCaptureSettings>(CoreResourceType.AGENT_WORK_CAPTURE_SETTINGS, { organizationId }).catch(() => null);\n if (settings?.contentCapture !== CorrectionContentCapture.WITH_CONTENT) return false;\n const narrowed = settings.narrowToCaseRefs ?? [];\n if (narrowed.length === 0) return true;\n return !!caseRef && narrowed.some((candidate) => agentWorkCaseKey(candidate) === agentWorkCaseKey(caseRef));\n }\n\n /**\n * Whether a case resource declares special-category (GDPR Art. 9) or criminal-offence data on any field, from its\n * own schema's `.dataCategories(...)`. Fail closed: a resource that cannot be read counts as declaring it.\n */\n private declaresRestrictedPersonalData(resourceType: string): boolean {\n try {\n const configuration = this.container.get<ResourcesRegistryBackendService>(SAAS_SERVICE_TYPES.ResourceRegistryService)\n .getResourceConfiguration(resourceType as ResourceType);\n return resolveResourcePersonalDataCategories(resourceComplianceSchema(configuration)).categories\n .some((category) => isSpecialCategoryPersonalData(category) || category === PersonalDataCategory.CRIMINAL_OFFENCE);\n } catch {\n return true;\n }\n }\n\n /** The tenant's correction key, or `undefined` without the primary secret (the record then claims no digest). */\n private correctionKeyOf(organizationId: string | undefined): string | undefined {\n const purposeKey = applicationSymmetricKeyOf(this.appConfig, CryptoKey_Purpose.AGENT_WORK_CORRECTION_DIGEST);\n if (!purposeKey) {\n if (!this.warnedNoSecret) {\n this.warnedNoSecret = true;\n this.logger.warn('[AgentWorkDecisions] No correction-digest key on this runtime: decision records keep their paths and distance but no digest');\n }\n return undefined;\n }\n return deriveAgentWorkCorrectionKey(purposeKey, organizationId);\n }\n\n private reviewConfig() {\n try {\n return this.appConfig?.isInitialized?.() ? this.appConfig.config.agentWorkReview : undefined;\n } catch {\n return undefined;\n }\n }\n\n private auditLogs(): AuditLogsBackendService | undefined {\n try {\n return this.container.get<AuditLogsBackendService>(SAAS_SERVICE_TYPES.AuditLogsService);\n } catch {\n return undefined;\n }\n }\n}\n\n/**\n * The paths an exported line names (review F6). With minimised content they are read from the MINIMISED patch, so a\n * pseudonymised record key or a withheld or undeclared field is never named by its raw path. Without it, only each\n * path's top-level segment is exported: that is the argument or field name the record already declares, while a deeper\n * segment may be a record key holding an identifier no shape was there to classify.\n */\nfunction exportedModifiedPathsOf(recordedPaths: readonly string[], kept: { diff?: unknown } | undefined): string[] {\n if (Array.isArray(kept?.diff)) return modifiedPathsOf(kept.diff as JsonPatchOperation[]);\n return [...new Set(recordedPaths.map((path) => path.split('/')[0]!))].sort();\n}\n\n/** The group a decision record falls in. A record with no value for the grouping key falls in the empty group. */\nfunction overrideRateGroupKeyOf(row: AgentWorkDecision, groupBy: AgentWorkDecisionGrouping): { mapKey: string; key: AgentWorkOverrideRateGroup['key'] } {\n switch (groupBy) {\n case AgentWorkDecisionGrouping.AGENT:\n return { mapKey: row.agentRef, key: { agentRef: row.agentRef } };\n case AgentWorkDecisionGrouping.TOOL:\n return row.toolName ? { mapKey: row.toolName, key: { toolName: row.toolName } } : { mapKey: '', key: {} };\n case AgentWorkDecisionGrouping.CASE:\n return row.caseRef\n ? { mapKey: agentWorkCaseKey(row.caseRef), key: { caseRef: { resourceType: row.caseRef.resourceType, resourceId: row.caseRef.resourceId } } }\n : { mapKey: '', key: {} };\n case AgentWorkDecisionGrouping.DECIDER:\n return row.deciderUserId ? { mapKey: row.deciderUserId, key: { deciderUserId: row.deciderUserId } } : { mapKey: '', key: {} };\n }\n}\n\n/**\n * Register the agent-work plane's subject-reference severer for a `USERS` erasure (#2865): the decider of a recorded\n * decision, and the person who exported a dataset, in every owner scope. Both are one column holding one user id, on\n * rows the erasure graph does not walk (an organization's or an application's records, and a decision in a thread the\n * person did not own), so the shared column severer clears it inside the erasure's transaction and keeps the row: the\n * decision stays the operator's evidence that agent work was supervised, and the export stays its ledger. A row under a\n * legal hold is left as it is. Resolved against the container at the erasure; a runtime that registers none of these\n * resources (a minion, a platform service) severs nothing.\n *\n * assurance-control: WILDO.PRIVACY.SUBJECT_ERASURE — an erased person's id leaves the decisions they made and the datasets they exported.\n */\nexport function registerAgentWorkErasureSeverance(\n servicesRegistry: Pick<ServicesRegistryHandlerBackendService, 'registerSubjectReferenceSeverer'>,\n container: Container,\n): void {\n const repositories = () => container.get<RepositoriesRegistryHandlerBackendService>(SAAS_SERVICE_TYPES.RepositoriesRegistryHandlerService);\n servicesRegistry.registerSubjectReferenceSeverer(CoreResourceType.USERS, createColumnSubjectReferenceSeverer(\n 'agent-work-deciders',\n [\n // The decisions they took name them (#2958): their ACCESS export discloses each one through this column. On a\n // decision in another person's own thread (the user variant), that person's id is theirs, not the decider's, and\n // is withheld (Art. 15(4)). Decided by practice: a record of an act a person performed is personal data concerning\n // them (Art. 15(1)), as the audit rows naming them already are in the same export.\n // spec-cite: GDPR Art. 15(1), 15(4) (https://gdpr-info.eu/art-15-gdpr/)\n ...AGENT_WORK_VARIANTS.map((variant) => ({\n resourceType: variant.decisions,\n field: 'deciderUserId',\n exportDisclosure: SeveredColumnExportDisclosure.NAMES_SUBJECT,\n ...(variant.ownerField === 'userId' ? { othersDataFields: ['userId'] } : {}),\n })),\n // NOT indexed, deliberately (#2865 review F8): the ledger gains one row per export a person starts, so this search\n // walks a small collection once per erasure, while an index would cost every export write and a migration on every\n // PostgreSQL surface. `deciderUserId` above IS indexed: decisions are the plane's volume.\n //\n // The exports they started name them (#2958): disclosed to them, without the pseudonymised keys of the people and\n // cases whose decisions the dataset carried, which are those people's data (GDPR Recital 26: a pseudonymised key is\n // still personal data). spec-cite: GDPR Recital 26 (https://gdpr-info.eu/recital-26-not-applicable-to-anonymous-data/)\n {\n resourceType: CoreResourceType.EVALUATION_DATASET_EXPORTS,\n field: 'exportedByUserId',\n exportDisclosure: SeveredColumnExportDisclosure.NAMES_SUBJECT,\n othersDataFields: ['subjectKeys', 'caseKeys'],\n },\n ],\n repositories,\n (resourceType) => container.isBound(SAAS_SERVICE_TYPES.RepositoriesRegistryHandlerService) && repositories().hasRepository(resourceType),\n ));\n}\n"]}