trueppm-api 0.4.0__py3-none-any.whl

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 (799) hide show
  1. trueppm_api/__init__.py +27 -0
  2. trueppm_api/apps/access/__init__.py +0 -0
  3. trueppm_api/apps/access/apps.py +19 -0
  4. trueppm_api/apps/access/groups.py +518 -0
  5. trueppm_api/apps/access/management/__init__.py +0 -0
  6. trueppm_api/apps/access/management/commands/__init__.py +0 -0
  7. trueppm_api/apps/access/management/commands/create_admin.py +346 -0
  8. trueppm_api/apps/access/management/commands/migrate_locked.py +96 -0
  9. trueppm_api/apps/access/management/commands/revoke_api_tokens.py +483 -0
  10. trueppm_api/apps/access/migrations/0001_initial.py +61 -0
  11. trueppm_api/apps/access/migrations/0001_squashed_0012_programmembership_role_title.py +184 -0
  12. trueppm_api/apps/access/migrations/0002_alter_projectmembership_id.py +29 -0
  13. trueppm_api/apps/access/migrations/0003_projectmembership_soft_delete.py +24 -0
  14. trueppm_api/apps/access/migrations/0004_alter_projectmembership_role.py +34 -0
  15. trueppm_api/apps/access/migrations/0005_program_entity_and_membership.py +76 -0
  16. trueppm_api/apps/access/migrations/0006_role_ordinal_spacing.py +113 -0
  17. trueppm_api/apps/access/migrations/0007_projectmembership_joined_at_and_more.py +35 -0
  18. trueppm_api/apps/access/migrations/0008_projectmembership_source_group.py +25 -0
  19. trueppm_api/apps/access/migrations/0009_projectmembership_pm_proj_serverver_idx.py +20 -0
  20. trueppm_api/apps/access/migrations/0010_programmembership_joined_at_and_more.py +38 -0
  21. trueppm_api/apps/access/migrations/0011_alter_programmembership_unique_together_and_more.py +36 -0
  22. trueppm_api/apps/access/migrations/0012_programmembership_role_title.py +17 -0
  23. trueppm_api/apps/access/migrations/0013_squashed_0019_release_0_4.py +302 -0
  24. trueppm_api/apps/access/migrations/0013_userdefinedmentiongroup.py +82 -0
  25. trueppm_api/apps/access/migrations/0014_programmembership_progm_serverver_idx.py +19 -0
  26. trueppm_api/apps/access/migrations/0015_programuserdefinedmentiongroup.py +86 -0
  27. trueppm_api/apps/access/migrations/0016_externalstakeholder.py +67 -0
  28. trueppm_api/apps/access/migrations/0017_viewer_ordinal_one.py +143 -0
  29. trueppm_api/apps/access/migrations/0018_programmembership_sync_seq_and_more.py +52 -0
  30. trueppm_api/apps/access/migrations/0019_programmembership_reinstated_at_and_more.py +22 -0
  31. trueppm_api/apps/access/migrations/__init__.py +0 -0
  32. trueppm_api/apps/access/minter_role.py +38 -0
  33. trueppm_api/apps/access/models.py +588 -0
  34. trueppm_api/apps/access/permissions.py +3263 -0
  35. trueppm_api/apps/access/serializers.py +1007 -0
  36. trueppm_api/apps/access/services.py +878 -0
  37. trueppm_api/apps/access/signals.py +171 -0
  38. trueppm_api/apps/access/tasks.py +50 -0
  39. trueppm_api/apps/access/throttles.py +96 -0
  40. trueppm_api/apps/access/urls.py +191 -0
  41. trueppm_api/apps/access/views.py +1965 -0
  42. trueppm_api/apps/agents/__init__.py +6 -0
  43. trueppm_api/apps/agents/apps.py +11 -0
  44. trueppm_api/apps/agents/canonical.py +73 -0
  45. trueppm_api/apps/agents/deferred.py +108 -0
  46. trueppm_api/apps/agents/management/__init__.py +0 -0
  47. trueppm_api/apps/agents/management/commands/__init__.py +0 -0
  48. trueppm_api/apps/agents/management/commands/audit_prune.py +137 -0
  49. trueppm_api/apps/agents/management/commands/audit_verify.py +101 -0
  50. trueppm_api/apps/agents/middleware.py +44 -0
  51. trueppm_api/apps/agents/migrations/0001_initial.py +231 -0
  52. trueppm_api/apps/agents/migrations/0001_squashed_0003_release_0_4.py +344 -0
  53. trueppm_api/apps/agents/migrations/0002_agentactioncheckpoint.py +71 -0
  54. trueppm_api/apps/agents/migrations/0003_agentactionrefusaldetail.py +58 -0
  55. trueppm_api/apps/agents/migrations/__init__.py +0 -0
  56. trueppm_api/apps/agents/models.py +371 -0
  57. trueppm_api/apps/agents/refusal.py +103 -0
  58. trueppm_api/apps/agents/serializers.py +85 -0
  59. trueppm_api/apps/agents/services.py +397 -0
  60. trueppm_api/apps/agents/signals.py +30 -0
  61. trueppm_api/apps/agents/urls.py +15 -0
  62. trueppm_api/apps/agents/views.py +109 -0
  63. trueppm_api/apps/csvimport/__init__.py +12 -0
  64. trueppm_api/apps/csvimport/apps.py +11 -0
  65. trueppm_api/apps/csvimport/mapping.py +363 -0
  66. trueppm_api/apps/csvimport/migrations/0001_initial.py +74 -0
  67. trueppm_api/apps/csvimport/migrations/0001_squashed_0003_release_0_4.py +90 -0
  68. trueppm_api/apps/csvimport/migrations/0002_schedule_outline_batch_operations.py +37 -0
  69. trueppm_api/apps/csvimport/migrations/0003_csvimportrequest_date_order_and_more.py +26 -0
  70. trueppm_api/apps/csvimport/migrations/__init__.py +0 -0
  71. trueppm_api/apps/csvimport/models.py +111 -0
  72. trueppm_api/apps/csvimport/parser.py +1825 -0
  73. trueppm_api/apps/csvimport/services.py +48 -0
  74. trueppm_api/apps/csvimport/tasks.py +459 -0
  75. trueppm_api/apps/csvimport/template.py +37 -0
  76. trueppm_api/apps/csvimport/urls.py +50 -0
  77. trueppm_api/apps/csvimport/views.py +793 -0
  78. trueppm_api/apps/history/__init__.py +0 -0
  79. trueppm_api/apps/history/apps.py +12 -0
  80. trueppm_api/apps/history/changelog.py +359 -0
  81. trueppm_api/apps/history/diff_policy.py +178 -0
  82. trueppm_api/apps/history/serializers.py +104 -0
  83. trueppm_api/apps/history/signals.py +82 -0
  84. trueppm_api/apps/history/tasks.py +105 -0
  85. trueppm_api/apps/history/urls.py +38 -0
  86. trueppm_api/apps/history/views.py +443 -0
  87. trueppm_api/apps/idempotency/__init__.py +0 -0
  88. trueppm_api/apps/idempotency/apps.py +11 -0
  89. trueppm_api/apps/idempotency/migrations/0001_initial.py +71 -0
  90. trueppm_api/apps/idempotency/migrations/__init__.py +0 -0
  91. trueppm_api/apps/idempotency/mixins.py +226 -0
  92. trueppm_api/apps/idempotency/models.py +75 -0
  93. trueppm_api/apps/idempotency/tasks.py +61 -0
  94. trueppm_api/apps/integrations/__init__.py +13 -0
  95. trueppm_api/apps/integrations/apps.py +59 -0
  96. trueppm_api/apps/integrations/connections.py +806 -0
  97. trueppm_api/apps/integrations/encryption.py +92 -0
  98. trueppm_api/apps/integrations/external_sources.py +863 -0
  99. trueppm_api/apps/integrations/git_automation_services.py +231 -0
  100. trueppm_api/apps/integrations/git_webhook_auth.py +243 -0
  101. trueppm_api/apps/integrations/http.py +597 -0
  102. trueppm_api/apps/integrations/me_work.py +218 -0
  103. trueppm_api/apps/integrations/migrations/0001_initial.py +64 -0
  104. trueppm_api/apps/integrations/migrations/0001_squashed_0006_tasklink_description_tasklink_preview_type_and_more.py +187 -0
  105. trueppm_api/apps/integrations/migrations/0002_tasklink.py +67 -0
  106. trueppm_api/apps/integrations/migrations/0003_tasklink_tasklink_serverver_idx.py +17 -0
  107. trueppm_api/apps/integrations/migrations/0004_tasklink_custom_title_tasklink_labels.py +25 -0
  108. trueppm_api/apps/integrations/migrations/0005_boardautomation.py +56 -0
  109. trueppm_api/apps/integrations/migrations/0006_tasklink_description_tasklink_preview_type_and_more.py +40 -0
  110. trueppm_api/apps/integrations/migrations/0007_squashed_0014_release_0_4.py +225 -0
  111. trueppm_api/apps/integrations/migrations/0007_tasklink_created_at.py +23 -0
  112. trueppm_api/apps/integrations/migrations/0008_integrationcredential_config_externalworkitem.py +66 -0
  113. trueppm_api/apps/integrations/migrations/0009_externalsyncrequest_and_more.py +96 -0
  114. trueppm_api/apps/integrations/migrations/0010_externalworkitem_due_date.py +17 -0
  115. trueppm_api/apps/integrations/migrations/0011_tasklink_sync_seq_tasklink_tasklink_syncseq_idx.py +22 -0
  116. trueppm_api/apps/integrations/migrations/0012_boardautomation_last_delivery_at_and_more.py +42 -0
  117. trueppm_api/apps/integrations/migrations/0013_externalsyncrequest_attempt_count_and_more.py +26 -0
  118. trueppm_api/apps/integrations/migrations/0014_tasklink_created_by.py +27 -0
  119. trueppm_api/apps/integrations/migrations/__init__.py +0 -0
  120. trueppm_api/apps/integrations/models.py +635 -0
  121. trueppm_api/apps/integrations/notification_channels.py +57 -0
  122. trueppm_api/apps/integrations/opengraph.py +229 -0
  123. trueppm_api/apps/integrations/outgoing.py +201 -0
  124. trueppm_api/apps/integrations/providers.py +528 -0
  125. trueppm_api/apps/integrations/registry.py +345 -0
  126. trueppm_api/apps/integrations/serializers.py +453 -0
  127. trueppm_api/apps/integrations/services.py +171 -0
  128. trueppm_api/apps/integrations/tasks.py +734 -0
  129. trueppm_api/apps/integrations/throttles.py +165 -0
  130. trueppm_api/apps/integrations/urls.py +77 -0
  131. trueppm_api/apps/integrations/views.py +1158 -0
  132. trueppm_api/apps/jiraimport/__init__.py +8 -0
  133. trueppm_api/apps/jiraimport/apps.py +11 -0
  134. trueppm_api/apps/jiraimport/migrations/0001_initial.py +72 -0
  135. trueppm_api/apps/jiraimport/migrations/__init__.py +0 -0
  136. trueppm_api/apps/jiraimport/models.py +70 -0
  137. trueppm_api/apps/jiraimport/parser.py +350 -0
  138. trueppm_api/apps/jiraimport/services.py +46 -0
  139. trueppm_api/apps/jiraimport/tasks.py +280 -0
  140. trueppm_api/apps/jiraimport/urls.py +15 -0
  141. trueppm_api/apps/jiraimport/views.py +153 -0
  142. trueppm_api/apps/msproject/__init__.py +0 -0
  143. trueppm_api/apps/msproject/apps.py +11 -0
  144. trueppm_api/apps/msproject/dataclasses.py +153 -0
  145. trueppm_api/apps/msproject/exporter.py +551 -0
  146. trueppm_api/apps/msproject/extended_attributes.py +77 -0
  147. trueppm_api/apps/msproject/importer.py +1095 -0
  148. trueppm_api/apps/msproject/migrations/0001_import_request.py +77 -0
  149. trueppm_api/apps/msproject/migrations/0001_squashed_0002_importrequest_creates_project.py +80 -0
  150. trueppm_api/apps/msproject/migrations/0002_importrequest_creates_project.py +15 -0
  151. trueppm_api/apps/msproject/migrations/__init__.py +0 -0
  152. trueppm_api/apps/msproject/models.py +81 -0
  153. trueppm_api/apps/msproject/parser.py +1276 -0
  154. trueppm_api/apps/msproject/serializers.py +136 -0
  155. trueppm_api/apps/msproject/services.py +58 -0
  156. trueppm_api/apps/msproject/tasks.py +439 -0
  157. trueppm_api/apps/msproject/urls.py +39 -0
  158. trueppm_api/apps/msproject/views.py +531 -0
  159. trueppm_api/apps/notifications/__init__.py +7 -0
  160. trueppm_api/apps/notifications/apps.py +15 -0
  161. trueppm_api/apps/notifications/backfill.py +79 -0
  162. trueppm_api/apps/notifications/categories.py +112 -0
  163. trueppm_api/apps/notifications/delivery_limits.py +258 -0
  164. trueppm_api/apps/notifications/digests.py +462 -0
  165. trueppm_api/apps/notifications/email_backend.py +350 -0
  166. trueppm_api/apps/notifications/email_health.py +128 -0
  167. trueppm_api/apps/notifications/migrations/0001_initial.py +207 -0
  168. trueppm_api/apps/notifications/migrations/0001_squashed_0006_notification_task.py +299 -0
  169. trueppm_api/apps/notifications/migrations/0002_project_notification_preference.py +67 -0
  170. trueppm_api/apps/notifications/migrations/0003_projectnotificationpreference_paused.py +17 -0
  171. trueppm_api/apps/notifications/migrations/0004_clean_unknown_matrix_keys.py +30 -0
  172. trueppm_api/apps/notifications/migrations/0005_notification_body_notification_event_type_and_more.py +27 -0
  173. trueppm_api/apps/notifications/migrations/0006_notification_task.py +25 -0
  174. trueppm_api/apps/notifications/migrations/0007_squashed_0011_release_0_4.py +204 -0
  175. trueppm_api/apps/notifications/migrations/0007_workspaceemailsettings.py +80 -0
  176. trueppm_api/apps/notifications/migrations/0008_notification_snoozed_until.py +17 -0
  177. trueppm_api/apps/notifications/migrations/0009_usernotificationsettings.py +43 -0
  178. trueppm_api/apps/notifications/migrations/0010_projectnotificationpreference_schema_version.py +20 -0
  179. trueppm_api/apps/notifications/migrations/0011_usernotificationsettings_digest_hour_and_more.py +96 -0
  180. trueppm_api/apps/notifications/migrations/__init__.py +0 -0
  181. trueppm_api/apps/notifications/models.py +1148 -0
  182. trueppm_api/apps/notifications/receivers.py +155 -0
  183. trueppm_api/apps/notifications/schema_migrations.py +56 -0
  184. trueppm_api/apps/notifications/serializers.py +1094 -0
  185. trueppm_api/apps/notifications/services.py +1489 -0
  186. trueppm_api/apps/notifications/tasks.py +762 -0
  187. trueppm_api/apps/notifications/throttles.py +98 -0
  188. trueppm_api/apps/notifications/urls.py +97 -0
  189. trueppm_api/apps/notifications/views.py +919 -0
  190. trueppm_api/apps/observability/__init__.py +0 -0
  191. trueppm_api/apps/observability/apps.py +31 -0
  192. trueppm_api/apps/observability/logging.py +213 -0
  193. trueppm_api/apps/observability/migrations/0001_initial.py +35 -0
  194. trueppm_api/apps/observability/migrations/0001_squashed_0003_alter_purgerun_trigger.py +154 -0
  195. trueppm_api/apps/observability/migrations/0002_purgerun_retentionpolicy_retentionschedule.py +131 -0
  196. trueppm_api/apps/observability/migrations/0003_alter_purgerun_trigger.py +21 -0
  197. trueppm_api/apps/observability/migrations/0004_alter_retentionpolicy_key.py +28 -0
  198. trueppm_api/apps/observability/migrations/__init__.py +0 -0
  199. trueppm_api/apps/observability/models.py +141 -0
  200. trueppm_api/apps/observability/otel/__init__.py +45 -0
  201. trueppm_api/apps/observability/otel/attributes.py +247 -0
  202. trueppm_api/apps/observability/otel/export_health.py +533 -0
  203. trueppm_api/apps/observability/otel/instrumentation.py +351 -0
  204. trueppm_api/apps/observability/otel/metrics.py +566 -0
  205. trueppm_api/apps/observability/otel/provider.py +511 -0
  206. trueppm_api/apps/observability/otel/request_attributes.py +204 -0
  207. trueppm_api/apps/observability/purge_registry.py +124 -0
  208. trueppm_api/apps/observability/retention.py +139 -0
  209. trueppm_api/apps/observability/selectors.py +993 -0
  210. trueppm_api/apps/observability/serializers.py +142 -0
  211. trueppm_api/apps/observability/services.py +407 -0
  212. trueppm_api/apps/observability/tasks.py +266 -0
  213. trueppm_api/apps/observability/urls.py +27 -0
  214. trueppm_api/apps/observability/views.py +537 -0
  215. trueppm_api/apps/profiles/__init__.py +0 -0
  216. trueppm_api/apps/profiles/apps.py +15 -0
  217. trueppm_api/apps/profiles/constants.py +54 -0
  218. trueppm_api/apps/profiles/migrations/0001_initial.py +55 -0
  219. trueppm_api/apps/profiles/migrations/0001_squashed_0004_userprofile_role_context.py +125 -0
  220. trueppm_api/apps/profiles/migrations/0002_userprofile_hidden_views.py +17 -0
  221. trueppm_api/apps/profiles/migrations/0003_projectvisit.py +63 -0
  222. trueppm_api/apps/profiles/migrations/0004_userprofile_role_context.py +26 -0
  223. trueppm_api/apps/profiles/migrations/0005_squashed_0009_release_0_4.py +128 -0
  224. trueppm_api/apps/profiles/migrations/0005_userprofile_schedule_in_deliver.py +20 -0
  225. trueppm_api/apps/profiles/migrations/0006_userprofile_date_format_userprofile_timezone.py +36 -0
  226. trueppm_api/apps/profiles/migrations/0007_userpin.py +91 -0
  227. trueppm_api/apps/profiles/migrations/0008_remove_userprofile_schedule_in_deliver.py +71 -0
  228. trueppm_api/apps/profiles/migrations/0009_auth_user_email_upper_idx.py +81 -0
  229. trueppm_api/apps/profiles/migrations/__init__.py +0 -0
  230. trueppm_api/apps/profiles/models.py +276 -0
  231. trueppm_api/apps/profiles/serializers.py +199 -0
  232. trueppm_api/apps/profiles/services.py +541 -0
  233. trueppm_api/apps/profiles/views.py +124 -0
  234. trueppm_api/apps/projects/__init__.py +0 -0
  235. trueppm_api/apps/projects/actual_date_rules.py +163 -0
  236. trueppm_api/apps/projects/amend.py +133 -0
  237. trueppm_api/apps/projects/apps.py +38 -0
  238. trueppm_api/apps/projects/asset_feed.py +459 -0
  239. trueppm_api/apps/projects/asset_views.py +317 -0
  240. trueppm_api/apps/projects/attachment_policy.py +278 -0
  241. trueppm_api/apps/projects/authentication.py +458 -0
  242. trueppm_api/apps/projects/backfill.py +459 -0
  243. trueppm_api/apps/projects/backlog_services.py +324 -0
  244. trueppm_api/apps/projects/backlog_views.py +302 -0
  245. trueppm_api/apps/projects/batch_operation_views.py +264 -0
  246. trueppm_api/apps/projects/blocker_services.py +510 -0
  247. trueppm_api/apps/projects/board_activity.py +462 -0
  248. trueppm_api/apps/projects/board_activity_views.py +186 -0
  249. trueppm_api/apps/projects/board_lanes.py +134 -0
  250. trueppm_api/apps/projects/bulk_settings.py +194 -0
  251. trueppm_api/apps/projects/bundled_templates.py +215 -0
  252. trueppm_api/apps/projects/calendar_settings.py +180 -0
  253. trueppm_api/apps/projects/ceremony_views.py +244 -0
  254. trueppm_api/apps/projects/commit_moment.py +212 -0
  255. trueppm_api/apps/projects/config_notice.py +1330 -0
  256. trueppm_api/apps/projects/custom_field_values.py +266 -0
  257. trueppm_api/apps/projects/decisions_services.py +132 -0
  258. trueppm_api/apps/projects/decisions_views.py +97 -0
  259. trueppm_api/apps/projects/estimation_scale.py +126 -0
  260. trueppm_api/apps/projects/export_bundle.py +423 -0
  261. trueppm_api/apps/projects/fixtures/seeds/atlas-platform-launch.json +4278 -0
  262. trueppm_api/apps/projects/fixtures/seeds/aurora-mobile-app.json +2001 -0
  263. trueppm_api/apps/projects/fixtures/seeds/bayside-civic-center.json +1827 -0
  264. trueppm_api/apps/projects/fixtures/seeds/ga-launch.json +1909 -0
  265. trueppm_api/apps/projects/fixtures/seeds/helios-crm-replacement.json +1410 -0
  266. trueppm_api/apps/projects/guardrail_policy_source.py +269 -0
  267. trueppm_api/apps/projects/inbound_sync.py +555 -0
  268. trueppm_api/apps/projects/iteration_label.py +85 -0
  269. trueppm_api/apps/projects/key_views.py +468 -0
  270. trueppm_api/apps/projects/keys.py +205 -0
  271. trueppm_api/apps/projects/lifecycle.py +191 -0
  272. trueppm_api/apps/projects/management/__init__.py +0 -0
  273. trueppm_api/apps/projects/management/commands/__init__.py +0 -0
  274. trueppm_api/apps/projects/management/commands/backfill_in_progress_status.py +92 -0
  275. trueppm_api/apps/projects/management/commands/create_demo_share_link.py +368 -0
  276. trueppm_api/apps/projects/management/commands/export_program.py +50 -0
  277. trueppm_api/apps/projects/management/commands/import_seed.py +165 -0
  278. trueppm_api/apps/projects/management/commands/load_sample_project.py +514 -0
  279. trueppm_api/apps/projects/management/commands/seed_capacity.py +406 -0
  280. trueppm_api/apps/projects/management/commands/seed_integration_fixtures.py +192 -0
  281. trueppm_api/apps/projects/management/commands/shift_sample_dates.py +120 -0
  282. trueppm_api/apps/projects/mcp_settings.py +305 -0
  283. trueppm_api/apps/projects/methodology.py +178 -0
  284. trueppm_api/apps/projects/migration_helpers.py +75 -0
  285. trueppm_api/apps/projects/migrations/0001_initial.py +208 -0
  286. trueppm_api/apps/projects/migrations/0001_squashed_0094_project_decisions_policy.py +5659 -0
  287. trueppm_api/apps/projects/migrations/0002_alter_uuid_pk_serialize_false.py +57 -0
  288. trueppm_api/apps/projects/migrations/0003_rename_task_project_index.py +25 -0
  289. trueppm_api/apps/projects/migrations/0004_soft_delete_and_dependency_versioned.py +70 -0
  290. trueppm_api/apps/projects/migrations/0005_task_assignee.py +33 -0
  291. trueppm_api/apps/projects/migrations/0006_task_utilization_index.py +31 -0
  292. trueppm_api/apps/projects/migrations/0007_task_is_milestone.py +28 -0
  293. trueppm_api/apps/projects/migrations/0008_baseline.py +119 -0
  294. trueppm_api/apps/projects/migrations/0009_historicaldependency_historicalproject_and_more.py +210 -0
  295. trueppm_api/apps/projects/migrations/0010_risk.py +229 -0
  296. trueppm_api/apps/projects/migrations/0011_task_status.py +27 -0
  297. trueppm_api/apps/projects/migrations/0012_task_status.py +27 -0
  298. trueppm_api/apps/projects/migrations/0013_task_planned_start.py +24 -0
  299. trueppm_api/apps/projects/migrations/0014_short_hex_ids.py +74 -0
  300. trueppm_api/apps/projects/migrations/0015_backfill_short_ids.py +48 -0
  301. trueppm_api/apps/projects/migrations/0016_task_actual_dates.py +42 -0
  302. trueppm_api/apps/projects/migrations/0017_boardcolumnconfig.py +43 -0
  303. trueppm_api/apps/projects/migrations/0018_estimation_governance.py +62 -0
  304. trueppm_api/apps/projects/migrations/0019_backfill_wbs_paths.py +28 -0
  305. trueppm_api/apps/projects/migrations/0020_task_status_5col.py +65 -0
  306. trueppm_api/apps/projects/migrations/0021_boardsavedview.py +64 -0
  307. trueppm_api/apps/projects/migrations/0022_task_status_changed_at_priority_rank.py +35 -0
  308. trueppm_api/apps/projects/migrations/0023_risk_framework_fields.py +96 -0
  309. trueppm_api/apps/projects/migrations/0024_riskcomment.py +52 -0
  310. trueppm_api/apps/projects/migrations/0025_sprint.py +352 -0
  311. trueppm_api/apps/projects/migrations/0026_project_methodology.py +30 -0
  312. trueppm_api/apps/projects/migrations/0027_sprint_retro.py +89 -0
  313. trueppm_api/apps/projects/migrations/0028_normalize_notes_field.py +42 -0
  314. trueppm_api/apps/projects/migrations/0029_complete_implies_full_progress.py +38 -0
  315. trueppm_api/apps/projects/migrations/0030_review_implies_full_progress.py +37 -0
  316. trueppm_api/apps/projects/migrations/0031_task_remaining_points.py +22 -0
  317. trueppm_api/apps/projects/migrations/0032_task_is_subtask_and_sprint_scope_change.py +90 -0
  318. trueppm_api/apps/projects/migrations/0033_task_my_work_index.py +38 -0
  319. trueppm_api/apps/projects/migrations/0034_inbound_task_sync.py +313 -0
  320. trueppm_api/apps/projects/migrations/0035_retro_versioned_and_suggested_assignee.py +173 -0
  321. trueppm_api/apps/projects/migrations/0036_program_entity_and_membership.py +157 -0
  322. trueppm_api/apps/projects/migrations/0037_sprint_capacity_points.py +20 -0
  323. trueppm_api/apps/projects/migrations/0038_taskcomment_commentreaction_commentacknowledgement_and_more.py +233 -0
  324. trueppm_api/apps/projects/migrations/0039_apitoken_and_more.py +88 -0
  325. trueppm_api/apps/projects/migrations/0040_program_general_fields.py +119 -0
  326. trueppm_api/apps/projects/migrations/0041_ceremony_template_and_phase_gate_config.py +210 -0
  327. trueppm_api/apps/projects/migrations/0041_project_general_fields.py +106 -0
  328. trueppm_api/apps/projects/migrations/0042_merge_20260522_0410.py +12 -0
  329. trueppm_api/apps/projects/migrations/0042_program_rollup_config.py +95 -0
  330. trueppm_api/apps/projects/migrations/0042_workflow_color_and_custom_fields.py +94 -0
  331. trueppm_api/apps/projects/migrations/0043_merge_20260522_1118.py +10 -0
  332. trueppm_api/apps/projects/migrations/0044_merge_20260522_rollup.py +10 -0
  333. trueppm_api/apps/projects/migrations/0044_project_archive_program_close.py +119 -0
  334. trueppm_api/apps/projects/migrations/0045_program_risk_policy.py +78 -0
  335. trueppm_api/apps/projects/migrations/0046_merge_20260523_2248.py +12 -0
  336. trueppm_api/apps/projects/migrations/0047_apitokenauditentry_program_and_more.py +55 -0
  337. trueppm_api/apps/projects/migrations/0048_historicalprogram_color_program_color.py +32 -0
  338. trueppm_api/apps/projects/migrations/0049_backlog_item.py +112 -0
  339. trueppm_api/apps/projects/migrations/0050_backlog_item_trgm_search.py +26 -0
  340. trueppm_api/apps/projects/migrations/0051_alter_calendar_working_days_alter_dependency_lag_and_more.py +144 -0
  341. trueppm_api/apps/projects/migrations/0052_recurring_tasks.py +278 -0
  342. trueppm_api/apps/projects/migrations/0053_dependency_dep_pred_serverver_idx_and_more.py +56 -0
  343. trueppm_api/apps/projects/migrations/0054_sprintscopechange_goal_impact_and_more.py +117 -0
  344. trueppm_api/apps/projects/migrations/0055_historicaltask_sprint_pending_and_more.py +51 -0
  345. trueppm_api/apps/projects/migrations/0056_historicalproject_prioritization_model_and_more.py +276 -0
  346. trueppm_api/apps/projects/migrations/0057_historicalsprint_binding_committed_snapshot_and_more.py +58 -0
  347. trueppm_api/apps/projects/migrations/0058_historicaltask_delivery_mode_and_more.py +72 -0
  348. trueppm_api/apps/projects/migrations/0059_forecastsnapshot.py +80 -0
  349. trueppm_api/apps/projects/migrations/0060_historicalprojectsignalprivacypolicy_and_more.py +90 -0
  350. trueppm_api/apps/projects/migrations/0061_baselinetask_story_points.py +17 -0
  351. trueppm_api/apps/projects/migrations/0062_project_is_sample.py +22 -0
  352. trueppm_api/apps/projects/migrations/0063_historicalsprint_wip_limit_sprint_wip_limit.py +22 -0
  353. trueppm_api/apps/projects/migrations/0064_sprinttaskoutcome.py +97 -0
  354. trueppm_api/apps/projects/migrations/0065_historicalsprint_goal_outcome_sprint_goal_outcome.py +32 -0
  355. trueppm_api/apps/projects/migrations/0066_historicalproject_lead_project_lead.py +38 -0
  356. trueppm_api/apps/projects/migrations/0067_sprint_exclude_from_velocity.py +22 -0
  357. trueppm_api/apps/projects/migrations/0068_project_recalculated_at.py +23 -0
  358. trueppm_api/apps/projects/migrations/0069_iteration_label.py +22 -0
  359. trueppm_api/apps/projects/migrations/0070_historicalprogram_iteration_label_and_more.py +32 -0
  360. trueppm_api/apps/projects/migrations/0071_backfill_iteration_label_inherit.py +35 -0
  361. trueppm_api/apps/projects/migrations/0072_pulseresponse_retroboarditem.py +129 -0
  362. trueppm_api/apps/projects/migrations/0073_sprinttaskoutcome_demo_ready.py +17 -0
  363. trueppm_api/apps/projects/migrations/0074_historicaltask_blocked_reason_task_blocked_reason.py +30 -0
  364. trueppm_api/apps/projects/migrations/0075_risk_decimal_short_id.py +42 -0
  365. trueppm_api/apps/projects/migrations/0076_sprinttaskoutcome_review_polish.py +45 -0
  366. trueppm_api/apps/projects/migrations/0077_task_blocker_fields.py +111 -0
  367. trueppm_api/apps/projects/migrations/0078_alter_risktask_unique_together_and_more.py +22 -0
  368. trueppm_api/apps/projects/migrations/0079_historicalproject_status_date_project_status_date.py +22 -0
  369. trueppm_api/apps/projects/migrations/0080_alter_historicaltask_type_alter_task_type.py +46 -0
  370. trueppm_api/apps/projects/migrations/0081_historicalprogram_allow_guests_and_more.py +52 -0
  371. trueppm_api/apps/projects/migrations/0082_project_last_sync_version.py +90 -0
  372. trueppm_api/apps/projects/migrations/0083_historicalprogram_mc_history_attribution_audience_and_more.py +108 -0
  373. trueppm_api/apps/projects/migrations/0084_tasknote.py +71 -0
  374. trueppm_api/apps/projects/migrations/0085_sprint_ix_sprint_velocity.py +33 -0
  375. trueppm_api/apps/projects/migrations/0086_board_card_search_trgm.py +33 -0
  376. trueppm_api/apps/projects/migrations/0087_historicalprogram_task_duration_change_percent_policy_and_more.py +155 -0
  377. trueppm_api/apps/projects/migrations/0088_historicalprogram_allowed_attachment_types_and_more.py +61 -0
  378. trueppm_api/apps/projects/migrations/0089_signalceilingraiseproposal_signalceilingraisevote_and_more.py +157 -0
  379. trueppm_api/apps/projects/migrations/0090_historicaltask_proj_histdate_index.py +59 -0
  380. trueppm_api/apps/projects/migrations/0091_project_board_cadence.py +39 -0
  381. trueppm_api/apps/projects/migrations/0092_program_target_date.py +22 -0
  382. trueppm_api/apps/projects/migrations/0093_cross_project_dependency_consent.py +58 -0
  383. trueppm_api/apps/projects/migrations/0094_project_decisions_policy.py +90 -0
  384. trueppm_api/apps/projects/migrations/0095_poker_session_vote.py +127 -0
  385. trueppm_api/apps/projects/migrations/0095_squashed_0097_release_0_3.py +225 -0
  386. trueppm_api/apps/projects/migrations/0096_crossprojectslipconflict.py +91 -0
  387. trueppm_api/apps/projects/migrations/0097_backlogitem_backlogitem_tags_gin_and_more.py +32 -0
  388. trueppm_api/apps/projects/migrations/0098_historicalproject_show_baselines_and_more.py +52 -0
  389. trueppm_api/apps/projects/migrations/0099_apitoken_scopes.py +48 -0
  390. trueppm_api/apps/projects/migrations/0100_task_dep_serverver_idx_concurrent.py +75 -0
  391. trueppm_api/apps/projects/migrations/0101_dependency_deleted_at_task_deleted_at.py +22 -0
  392. trueppm_api/apps/projects/migrations/0102_project_deleted_at_project_proj_isdel_deletedat_idx.py +25 -0
  393. trueppm_api/apps/projects/migrations/0103_taskdurationchangeevent_task_dur_evt_sprint_idx.py +18 -0
  394. trueppm_api/apps/projects/migrations/0104_historicalproject_stale_task_threshold_days_and_more.py +32 -0
  395. trueppm_api/apps/projects/migrations/0104_trash_restore_1113.py +38 -0
  396. trueppm_api/apps/projects/migrations/0105_historical_changelog_indexes.py +76 -0
  397. trueppm_api/apps/projects/migrations/0106_boardsavedview_schema_version.py +20 -0
  398. trueppm_api/apps/projects/migrations/0106_squashed_0158_release_0_4.py +2357 -0
  399. trueppm_api/apps/projects/migrations/0107_task_activity_event.py +70 -0
  400. trueppm_api/apps/projects/migrations/0108_remove_apitoken_api_token_scope_xor_and_more.py +117 -0
  401. trueppm_api/apps/projects/migrations/0109_projectexportjob.py +82 -0
  402. trueppm_api/apps/projects/migrations/0110_sharelink.py +123 -0
  403. trueppm_api/apps/projects/migrations/0111_projectcalendarlayer.py +67 -0
  404. trueppm_api/apps/projects/migrations/0112_sharelink_expires_at_alter_sharelink_content_kind.py +31 -0
  405. trueppm_api/apps/projects/migrations/0113_alter_historicaltask_percent_complete_and_more.py +35 -0
  406. trueppm_api/apps/projects/migrations/0114_historicalproject_default_member_role_and_more.py +28 -0
  407. trueppm_api/apps/projects/migrations/0115_historicalproject_end_date_shift_threshold_days_and_more.py +22 -0
  408. trueppm_api/apps/projects/migrations/0116_alter_taskactivityevent_event_type.py +28 -0
  409. trueppm_api/apps/projects/migrations/0117_label_tasklabel_label_tasks_and_more.py +126 -0
  410. trueppm_api/apps/projects/migrations/0118_programexportjob.py +82 -0
  411. trueppm_api/apps/projects/migrations/0119_historicalprogram_calendar_program_calendar.py +36 -0
  412. trueppm_api/apps/projects/migrations/0120_alter_backlogitem_item_type.py +29 -0
  413. trueppm_api/apps/projects/migrations/0121_task_three_point_estimate_ordered.py +64 -0
  414. trueppm_api/apps/projects/migrations/0122_task_relation.py +173 -0
  415. trueppm_api/apps/projects/migrations/0123_remove_historicalproject_agile_features_and_more.py +20 -0
  416. trueppm_api/apps/projects/migrations/0124_dependency_is_driving.py +17 -0
  417. trueppm_api/apps/projects/migrations/0125_historicalprogram_estimation_scale_and_more.py +68 -0
  418. trueppm_api/apps/projects/migrations/0126_projectcustomfield_show_on_card_taskcustomfieldvalue.py +80 -0
  419. trueppm_api/apps/projects/migrations/0127_historicalprogram_mcp_enabled_and_more.py +32 -0
  420. trueppm_api/apps/projects/migrations/0128_acceptancecriterion_sync_seq_apitoken_sync_seq_and_more.py +192 -0
  421. trueppm_api/apps/projects/migrations/0129_sharelink_show_milestone_dates.py +20 -0
  422. trueppm_api/apps/projects/migrations/0130_programimportjob.py +85 -0
  423. trueppm_api/apps/projects/migrations/0131_historicalprogram_sprint_picker_ready_only_default_and_more.py +32 -0
  424. trueppm_api/apps/projects/migrations/0132_task_scheduled_start.py +17 -0
  425. trueppm_api/apps/projects/migrations/0133_project_status_date_floor_armed_at.py +17 -0
  426. trueppm_api/apps/projects/migrations/0134_task_edited_at_task_seeded_at_task_source_id_and_more.py +65 -0
  427. trueppm_api/apps/projects/migrations/0135_projecttemplate_templateapplication_and_more.py +175 -0
  428. trueppm_api/apps/projects/migrations/0136_schedule_outline_batch_operations.py +118 -0
  429. trueppm_api/apps/projects/migrations/0137_collapse_dual_scope_api_tokens.py +54 -0
  430. trueppm_api/apps/projects/migrations/0138_apitokenauditentry_api_token_audit_owner_idx.py +18 -0
  431. trueppm_api/apps/projects/migrations/0139_historicaltask_duration_unit_task_duration_unit.py +32 -0
  432. trueppm_api/apps/projects/migrations/0140_historicaltask_auto_container_and_more.py +113 -0
  433. trueppm_api/apps/projects/migrations/0141_historicalproject_draft_started_at_and_more.py +44 -0
  434. trueppm_api/apps/projects/migrations/0142_baseline_calendar_hours_per_day_and_more.py +31 -0
  435. trueppm_api/apps/projects/migrations/0143_sprintcloserequest_failure_reason_and_more.py +42 -0
  436. trueppm_api/apps/projects/migrations/0144_projecttemplate_source_project_and_more.py +35 -0
  437. trueppm_api/apps/projects/migrations/0145_seed_bundled_templates.py +65 -0
  438. trueppm_api/apps/projects/migrations/0146_historicaltask_board_lane_task_board_lane.py +32 -0
  439. trueppm_api/apps/projects/migrations/0147_structuraloperation.py +128 -0
  440. trueppm_api/apps/projects/migrations/0148_task_unique_task_wbs_path_per_project_live.py +76 -0
  441. trueppm_api/apps/projects/migrations/0149_drop_workshops_tables.py +42 -0
  442. trueppm_api/apps/projects/migrations/0150_clear_uncommitted_cpm_output.py +130 -0
  443. trueppm_api/apps/projects/migrations/0151_config_notice_request.py +70 -0
  444. trueppm_api/apps/projects/migrations/0152_aggregate_task_wbs_name_idx.py +20 -0
  445. trueppm_api/apps/projects/migrations/0153_program_sample_anchor_date.py +22 -0
  446. trueppm_api/apps/projects/migrations/0154_object_keys.py +184 -0
  447. trueppm_api/apps/projects/migrations/0155_task_milestone_at_day_end.py +20 -0
  448. trueppm_api/apps/projects/migrations/0156_program_import_job_replaced_project_ids.py +17 -0
  449. trueppm_api/apps/projects/migrations/0157_forecastsnapshot_cpm_finish_at_day_start.py +17 -0
  450. trueppm_api/apps/projects/migrations/0158_baselinetask_finish_at_day_start.py +17 -0
  451. trueppm_api/apps/projects/migrations/__init__.py +0 -0
  452. trueppm_api/apps/projects/models.py +9209 -0
  453. trueppm_api/apps/projects/poker_services.py +154 -0
  454. trueppm_api/apps/projects/poker_views.py +398 -0
  455. trueppm_api/apps/projects/product_backlog_services.py +450 -0
  456. trueppm_api/apps/projects/program_label_services.py +94 -0
  457. trueppm_api/apps/projects/program_label_views.py +189 -0
  458. trueppm_api/apps/projects/program_rollup.py +903 -0
  459. trueppm_api/apps/projects/program_schedule.py +767 -0
  460. trueppm_api/apps/projects/program_views.py +3445 -0
  461. trueppm_api/apps/projects/project_templates.py +422 -0
  462. trueppm_api/apps/projects/receivers.py +234 -0
  463. trueppm_api/apps/projects/refusal_codes.py +140 -0
  464. trueppm_api/apps/projects/reorder_services.py +145 -0
  465. trueppm_api/apps/projects/restructure_hooks.py +54 -0
  466. trueppm_api/apps/projects/retro_board_services.py +368 -0
  467. trueppm_api/apps/projects/retro_services.py +285 -0
  468. trueppm_api/apps/projects/risk_import.py +396 -0
  469. trueppm_api/apps/projects/row_identity.py +113 -0
  470. trueppm_api/apps/projects/schema_migrations.py +228 -0
  471. trueppm_api/apps/projects/schemas/seed_v1.json +492 -0
  472. trueppm_api/apps/projects/schemas/seed_v2.json +891 -0
  473. trueppm_api/apps/projects/seed/__init__.py +61 -0
  474. trueppm_api/apps/projects/seed/demo_landing_overlay.py +532 -0
  475. trueppm_api/apps/projects/seed/exporter.py +1717 -0
  476. trueppm_api/apps/projects/seed/forecast_backfill.py +247 -0
  477. trueppm_api/apps/projects/seed/importer.py +2764 -0
  478. trueppm_api/apps/projects/seed/reanchor.py +551 -0
  479. trueppm_api/apps/projects/seed/reldates.py +126 -0
  480. trueppm_api/apps/projects/seed/replace.py +128 -0
  481. trueppm_api/apps/projects/seed/replay.py +1695 -0
  482. trueppm_api/apps/projects/seed/replay_ctx.py +41 -0
  483. trueppm_api/apps/projects/seed/samples.py +427 -0
  484. trueppm_api/apps/projects/seed/validation.py +1169 -0
  485. trueppm_api/apps/projects/serializers.py +12904 -0
  486. trueppm_api/apps/projects/services.py +7525 -0
  487. trueppm_api/apps/projects/share_serializers.py +142 -0
  488. trueppm_api/apps/projects/share_services.py +373 -0
  489. trueppm_api/apps/projects/share_views.py +395 -0
  490. trueppm_api/apps/projects/sharing_settings.py +187 -0
  491. trueppm_api/apps/projects/signal_privacy_services.py +910 -0
  492. trueppm_api/apps/projects/signal_privacy_views.py +485 -0
  493. trueppm_api/apps/projects/signals.py +132 -0
  494. trueppm_api/apps/projects/slip_conflict.py +288 -0
  495. trueppm_api/apps/projects/sprint_cadence.py +453 -0
  496. trueppm_api/apps/projects/sprint_picker_settings.py +132 -0
  497. trueppm_api/apps/projects/standup.py +304 -0
  498. trueppm_api/apps/projects/standup_views.py +99 -0
  499. trueppm_api/apps/projects/structural_operation_services.py +727 -0
  500. trueppm_api/apps/projects/structural_operation_views.py +311 -0
  501. trueppm_api/apps/projects/surface_visibility.py +126 -0
  502. trueppm_api/apps/projects/task_batch_services.py +379 -0
  503. trueppm_api/apps/projects/task_bulk.py +1244 -0
  504. trueppm_api/apps/projects/task_classification.py +561 -0
  505. trueppm_api/apps/projects/task_classification_defaults.py +95 -0
  506. trueppm_api/apps/projects/task_duration_settings.py +142 -0
  507. trueppm_api/apps/projects/task_grouping.py +754 -0
  508. trueppm_api/apps/projects/tasks.py +1979 -0
  509. trueppm_api/apps/projects/template_divergence.py +168 -0
  510. trueppm_api/apps/projects/template_services.py +160 -0
  511. trueppm_api/apps/projects/template_tasks.py +261 -0
  512. trueppm_api/apps/projects/template_views.py +829 -0
  513. trueppm_api/apps/projects/throttles.py +311 -0
  514. trueppm_api/apps/projects/urls.py +1016 -0
  515. trueppm_api/apps/projects/utilization.py +909 -0
  516. trueppm_api/apps/projects/views.py +21225 -0
  517. trueppm_api/apps/projects/wbs_paths.py +119 -0
  518. trueppm_api/apps/resources/__init__.py +0 -0
  519. trueppm_api/apps/resources/apps.py +8 -0
  520. trueppm_api/apps/resources/capacity.py +121 -0
  521. trueppm_api/apps/resources/migrations/0001_initial.py +68 -0
  522. trueppm_api/apps/resources/migrations/0001_squashed_0013_alter_projectresource_unique_together_and_more.py +281 -0
  523. trueppm_api/apps/resources/migrations/0002_alter_uuid_pk_serialize_false.py +36 -0
  524. trueppm_api/apps/resources/migrations/0003_resource_soft_delete.py +30 -0
  525. trueppm_api/apps/resources/migrations/0004_add_taskresource_resource_index.py +25 -0
  526. trueppm_api/apps/resources/migrations/0005_resource_job_role.py +20 -0
  527. trueppm_api/apps/resources/migrations/0006_skill.py +34 -0
  528. trueppm_api/apps/resources/migrations/0007_resource_skill.py +63 -0
  529. trueppm_api/apps/resources/migrations/0008_project_resource.py +63 -0
  530. trueppm_api/apps/resources/migrations/0009_task_skill_requirement.py +60 -0
  531. trueppm_api/apps/resources/migrations/0010_alter_resourceskill_options_and_more.py +20 -0
  532. trueppm_api/apps/resources/migrations/0011_alter_projectresource_notes.py +17 -0
  533. trueppm_api/apps/resources/migrations/0012_add_resource_user_fk.py +26 -0
  534. trueppm_api/apps/resources/migrations/0013_alter_projectresource_unique_together_and_more.py +53 -0
  535. trueppm_api/apps/resources/migrations/0014_projectresource_sync_seq_resource_sync_seq_and_more.py +37 -0
  536. trueppm_api/apps/resources/migrations/0014_squashed_0015_release_0_4.py +47 -0
  537. trueppm_api/apps/resources/migrations/0015_projectresource_deactivated_with_resource.py +17 -0
  538. trueppm_api/apps/resources/migrations/__init__.py +0 -0
  539. trueppm_api/apps/resources/models.py +298 -0
  540. trueppm_api/apps/resources/serializers.py +426 -0
  541. trueppm_api/apps/resources/services.py +465 -0
  542. trueppm_api/apps/resources/urls.py +28 -0
  543. trueppm_api/apps/resources/views.py +1752 -0
  544. trueppm_api/apps/scheduling/__init__.py +0 -0
  545. trueppm_api/apps/scheduling/apps.py +153 -0
  546. trueppm_api/apps/scheduling/calendars.py +144 -0
  547. trueppm_api/apps/scheduling/deadletter.py +91 -0
  548. trueppm_api/apps/scheduling/finish_reading.py +198 -0
  549. trueppm_api/apps/scheduling/forecast_history_settings.py +215 -0
  550. trueppm_api/apps/scheduling/forecast_staleness.py +313 -0
  551. trueppm_api/apps/scheduling/graph_guard.py +263 -0
  552. trueppm_api/apps/scheduling/management/__init__.py +0 -0
  553. trueppm_api/apps/scheduling/management/commands/__init__.py +0 -0
  554. trueppm_api/apps/scheduling/management/commands/prune_forecast_snapshots.py +53 -0
  555. trueppm_api/apps/scheduling/mc_admission.py +181 -0
  556. trueppm_api/apps/scheduling/migrations/0001_failed_task.py +62 -0
  557. trueppm_api/apps/scheduling/migrations/0001_squashed_0007_projectforecastsnapshot.py +309 -0
  558. trueppm_api/apps/scheduling/migrations/0002_schedulerequest.py +78 -0
  559. trueppm_api/apps/scheduling/migrations/0003_add_schedule_request_reason.py +27 -0
  560. trueppm_api/apps/scheduling/migrations/0004_velocity_suggestion.py +94 -0
  561. trueppm_api/apps/scheduling/migrations/0005_montecarlorun.py +61 -0
  562. trueppm_api/apps/scheduling/migrations/0006_montecarlorun_distribution.py +17 -0
  563. trueppm_api/apps/scheduling/migrations/0007_projectforecastsnapshot.py +65 -0
  564. trueppm_api/apps/scheduling/migrations/0008_alter_schedulerequest_reason.py +28 -0
  565. trueppm_api/apps/scheduling/migrations/0008_folded_schedulerequest_reason.py +34 -0
  566. trueppm_api/apps/scheduling/migrations/0009_alter_schedulerequest_reason.py +29 -0
  567. trueppm_api/apps/scheduling/migrations/0010_failedtask_resolution_note_failedtask_resolved_at_and_more.py +43 -0
  568. trueppm_api/apps/scheduling/migrations/0010_squashed_0016_release_0_4.py +106 -0
  569. trueppm_api/apps/scheduling/migrations/0011_failedtask_project.py +26 -0
  570. trueppm_api/apps/scheduling/migrations/0012_montecarlorun_diagnostic.py +17 -0
  571. trueppm_api/apps/scheduling/migrations/0013_montecarlorun_status_date.py +17 -0
  572. trueppm_api/apps/scheduling/migrations/0014_montecarlorun_plan_version.py +17 -0
  573. trueppm_api/apps/scheduling/migrations/0015_projectforecastsnapshot_cpm_finish_at_day_start.py +17 -0
  574. trueppm_api/apps/scheduling/migrations/0016_montecarlorun_finish_readings.py +32 -0
  575. trueppm_api/apps/scheduling/migrations/__init__.py +0 -0
  576. trueppm_api/apps/scheduling/models.py +542 -0
  577. trueppm_api/apps/scheduling/receivers.py +160 -0
  578. trueppm_api/apps/scheduling/risk_premium.py +334 -0
  579. trueppm_api/apps/scheduling/serializers.py +723 -0
  580. trueppm_api/apps/scheduling/services.py +1251 -0
  581. trueppm_api/apps/scheduling/signals.py +56 -0
  582. trueppm_api/apps/scheduling/tasks.py +2248 -0
  583. trueppm_api/apps/scheduling/telemetry.py +80 -0
  584. trueppm_api/apps/scheduling/units.py +35 -0
  585. trueppm_api/apps/scheduling/urls.py +57 -0
  586. trueppm_api/apps/scheduling/views.py +2908 -0
  587. trueppm_api/apps/sso/__init__.py +0 -0
  588. trueppm_api/apps/sso/apps.py +19 -0
  589. trueppm_api/apps/sso/extensions.py +130 -0
  590. trueppm_api/apps/sso/management/__init__.py +0 -0
  591. trueppm_api/apps/sso/management/commands/__init__.py +0 -0
  592. trueppm_api/apps/sso/management/commands/seed_sso_keycloak.py +172 -0
  593. trueppm_api/apps/sso/migrations/0001_initial.py +119 -0
  594. trueppm_api/apps/sso/migrations/0002_remove_oidcprovider_workspace_ssoproviderpolicy_and_more.py +169 -0
  595. trueppm_api/apps/sso/migrations/__init__.py +0 -0
  596. trueppm_api/apps/sso/models.py +148 -0
  597. trueppm_api/apps/sso/serializers.py +446 -0
  598. trueppm_api/apps/sso/services.py +1473 -0
  599. trueppm_api/apps/sso/urls.py +47 -0
  600. trueppm_api/apps/sso/views.py +935 -0
  601. trueppm_api/apps/sync/__init__.py +0 -0
  602. trueppm_api/apps/sync/apps.py +15 -0
  603. trueppm_api/apps/sync/backfill.py +208 -0
  604. trueppm_api/apps/sync/broadcast.py +369 -0
  605. trueppm_api/apps/sync/conflict.py +262 -0
  606. trueppm_api/apps/sync/consumers.py +548 -0
  607. trueppm_api/apps/sync/migrations/0001_initial.py +59 -0
  608. trueppm_api/apps/sync/migrations/0001_squashed_0002_remove_syncbatch_syncbatch_project_client_batch_uniq_and_more.py +77 -0
  609. trueppm_api/apps/sync/migrations/0002_remove_syncbatch_syncbatch_project_client_batch_uniq_and_more.py +41 -0
  610. trueppm_api/apps/sync/migrations/0003_boardevent.py +46 -0
  611. trueppm_api/apps/sync/migrations/0003_squashed_0005_release_0_4.py +77 -0
  612. trueppm_api/apps/sync/migrations/0004_seed_sync_seq.py +24 -0
  613. trueppm_api/apps/sync/migrations/0005_program_sync_sequence.py +35 -0
  614. trueppm_api/apps/sync/migrations/0006_boardevent_per_project_seq.py +77 -0
  615. trueppm_api/apps/sync/migrations/__init__.py +0 -0
  616. trueppm_api/apps/sync/models.py +272 -0
  617. trueppm_api/apps/sync/pagination.py +231 -0
  618. trueppm_api/apps/sync/sequence.py +488 -0
  619. trueppm_api/apps/sync/serializers.py +688 -0
  620. trueppm_api/apps/sync/tasks.py +260 -0
  621. trueppm_api/apps/sync/throttles.py +175 -0
  622. trueppm_api/apps/sync/upload.py +556 -0
  623. trueppm_api/apps/sync/urls.py +17 -0
  624. trueppm_api/apps/sync/views.py +957 -0
  625. trueppm_api/apps/sync/ws_auth.py +193 -0
  626. trueppm_api/apps/taskruns/__init__.py +0 -0
  627. trueppm_api/apps/taskruns/apps.py +11 -0
  628. trueppm_api/apps/taskruns/migrations/0001_initial.py +92 -0
  629. trueppm_api/apps/taskruns/migrations/__init__.py +0 -0
  630. trueppm_api/apps/taskruns/models.py +68 -0
  631. trueppm_api/apps/taskruns/serializers.py +92 -0
  632. trueppm_api/apps/taskruns/tasks.py +60 -0
  633. trueppm_api/apps/taskruns/tracker.py +286 -0
  634. trueppm_api/apps/taskruns/urls.py +46 -0
  635. trueppm_api/apps/taskruns/views.py +195 -0
  636. trueppm_api/apps/teams/__init__.py +8 -0
  637. trueppm_api/apps/teams/apps.py +16 -0
  638. trueppm_api/apps/teams/migrations/0001_initial.py +139 -0
  639. trueppm_api/apps/teams/migrations/0001_squashed_0002_default_teams.py +159 -0
  640. trueppm_api/apps/teams/migrations/0002_default_teams.py +62 -0
  641. trueppm_api/apps/teams/migrations/0003_team_sync_seq_teammembership_sync_seq.py +22 -0
  642. trueppm_api/apps/teams/migrations/0004_backfill_default_teams_on_upgrade.py +49 -0
  643. trueppm_api/apps/teams/migrations/__init__.py +0 -0
  644. trueppm_api/apps/teams/models.py +145 -0
  645. trueppm_api/apps/teams/permissions.py +149 -0
  646. trueppm_api/apps/teams/serializers.py +95 -0
  647. trueppm_api/apps/teams/services.py +440 -0
  648. trueppm_api/apps/teams/signals.py +61 -0
  649. trueppm_api/apps/teams/urls.py +34 -0
  650. trueppm_api/apps/teams/views.py +201 -0
  651. trueppm_api/apps/timetracking/__init__.py +0 -0
  652. trueppm_api/apps/timetracking/apps.py +9 -0
  653. trueppm_api/apps/timetracking/migrations/0001_initial.py +117 -0
  654. trueppm_api/apps/timetracking/migrations/0001_squashed_0004_release_0_4.py +167 -0
  655. trueppm_api/apps/timetracking/migrations/0002_timesheetsubmission.py +46 -0
  656. trueppm_api/apps/timetracking/migrations/0003_timeentry_deleted_at_timeentry_deleted_by.py +31 -0
  657. trueppm_api/apps/timetracking/migrations/0004_timeentry_sync_seq_and_more.py +24 -0
  658. trueppm_api/apps/timetracking/migrations/__init__.py +0 -0
  659. trueppm_api/apps/timetracking/models.py +178 -0
  660. trueppm_api/apps/timetracking/serializers.py +175 -0
  661. trueppm_api/apps/timetracking/services.py +211 -0
  662. trueppm_api/apps/timetracking/urls.py +47 -0
  663. trueppm_api/apps/timetracking/views.py +597 -0
  664. trueppm_api/apps/webhooks/__init__.py +0 -0
  665. trueppm_api/apps/webhooks/apps.py +8 -0
  666. trueppm_api/apps/webhooks/backfill.py +90 -0
  667. trueppm_api/apps/webhooks/dispatch.py +279 -0
  668. trueppm_api/apps/webhooks/migrations/0001_initial.py +146 -0
  669. trueppm_api/apps/webhooks/migrations/0001_squashed_0007_sprint_lifecycle_events.py +249 -0
  670. trueppm_api/apps/webhooks/migrations/0002_alter_webhook_events.py +32 -0
  671. trueppm_api/apps/webhooks/migrations/0003_delivery_status_created_idx.py +17 -0
  672. trueppm_api/apps/webhooks/migrations/0004_webhook_program_alter_webhook_project_and_more.py +64 -0
  673. trueppm_api/apps/webhooks/migrations/0005_webhook_delivery_sequence_numbers.py +30 -0
  674. trueppm_api/apps/webhooks/migrations/0006_webhook_format_alter_webhook_events_and_more.py +61 -0
  675. trueppm_api/apps/webhooks/migrations/0007_sprint_lifecycle_events.py +63 -0
  676. trueppm_api/apps/webhooks/migrations/0008_risk_baseline_comment_events.py +73 -0
  677. trueppm_api/apps/webhooks/migrations/0009_encrypt_webhook_secret_and_failure_counters.py +100 -0
  678. trueppm_api/apps/webhooks/migrations/0010_alter_webhook_disabled_at.py +21 -0
  679. trueppm_api/apps/webhooks/migrations/0011_webhookeditor.py +48 -0
  680. trueppm_api/apps/webhooks/migrations/0012_alter_webhook_disabled_at.py +21 -0
  681. trueppm_api/apps/webhooks/migrations/__init__.py +0 -0
  682. trueppm_api/apps/webhooks/models.py +437 -0
  683. trueppm_api/apps/webhooks/serializers.py +326 -0
  684. trueppm_api/apps/webhooks/tasks.py +680 -0
  685. trueppm_api/apps/webhooks/urls.py +22 -0
  686. trueppm_api/apps/webhooks/views.py +533 -0
  687. trueppm_api/apps/workflow_engine/__init__.py +0 -0
  688. trueppm_api/apps/workflow_engine/apps.py +23 -0
  689. trueppm_api/apps/workflow_engine/migrations/0001_initial.py +230 -0
  690. trueppm_api/apps/workflow_engine/migrations/0001_squashed_0002_remove_workflowhistoryevent_workflow_history_lookup_idx.py +234 -0
  691. trueppm_api/apps/workflow_engine/migrations/0002_remove_workflowhistoryevent_workflow_history_lookup_idx.py +16 -0
  692. trueppm_api/apps/workflow_engine/migrations/0003_workflowoutboxrow_workflow_outbox_recovery_idx.py +21 -0
  693. trueppm_api/apps/workflow_engine/migrations/__init__.py +0 -0
  694. trueppm_api/apps/workflow_engine/models.py +265 -0
  695. trueppm_api/apps/workflow_engine/tasks.py +371 -0
  696. trueppm_api/apps/workspace/__init__.py +0 -0
  697. trueppm_api/apps/workspace/apps.py +10 -0
  698. trueppm_api/apps/workspace/backfill.py +111 -0
  699. trueppm_api/apps/workspace/export.py +254 -0
  700. trueppm_api/apps/workspace/migrations/0001_initial.py +326 -0
  701. trueppm_api/apps/workspace/migrations/0001_squashed_0014_workspacemembership_availability_effective_from_and_more.py +829 -0
  702. trueppm_api/apps/workspace/migrations/0002_remove_workspace_fiscal_year_start_and_more.py +85 -0
  703. trueppm_api/apps/workspace/migrations/0003_workspaceexportjob.py +73 -0
  704. trueppm_api/apps/workspace/migrations/0004_alter_workspaceinvite_status.py +27 -0
  705. trueppm_api/apps/workspace/migrations/0005_workspace_iteration_label_and_more.py +26 -0
  706. trueppm_api/apps/workspace/migrations/0006_alter_groupmembership_unique_together_and_more.py +45 -0
  707. trueppm_api/apps/workspace/migrations/0007_workspace_public_sharing_override_policy.py +21 -0
  708. trueppm_api/apps/workspace/migrations/0008_workspace_mc_history_attribution_audience_and_more.py +44 -0
  709. trueppm_api/apps/workspace/migrations/0009_workspace_methodology_and_more.py +186 -0
  710. trueppm_api/apps/workspace/migrations/0010_workspace_logo.py +38 -0
  711. trueppm_api/apps/workspace/migrations/0011_historicalworkspace_task_duration_change_percent_override_policy_and_more.py +56 -0
  712. trueppm_api/apps/workspace/migrations/0012_historicalworkspace_allowed_attachment_types_and_more.py +64 -0
  713. trueppm_api/apps/workspace/migrations/0013_auditevent.py +70 -0
  714. trueppm_api/apps/workspace/migrations/0014_workspacemembership_availability_effective_from_and_more.py +39 -0
  715. trueppm_api/apps/workspace/migrations/0015_squashed_0027_release_0_4.py +199 -0
  716. trueppm_api/apps/workspace/migrations/0015_trash_restore_1113.py +34 -0
  717. trueppm_api/apps/workspace/migrations/0016_historicalworkspace_calendar_and_more.py +55 -0
  718. trueppm_api/apps/workspace/migrations/0017_historicalworkspace_estimation_scale_and_more.py +38 -0
  719. trueppm_api/apps/workspace/migrations/0018_historicalworkspace_feedback_enabled_and_more.py +32 -0
  720. trueppm_api/apps/workspace/migrations/0019_historicalworkspace_mcp_enabled_and_more.py +22 -0
  721. trueppm_api/apps/workspace/migrations/0020_viewer_ordinal_one.py +34 -0
  722. trueppm_api/apps/workspace/migrations/0021_group_sync_seq_groupmembership_sync_seq_and_more.py +27 -0
  723. trueppm_api/apps/workspace/migrations/0022_historicalworkspace_sprint_picker_ready_only_default_and_more.py +22 -0
  724. trueppm_api/apps/workspace/migrations/0023_alter_auditevent_event_type.py +32 -0
  725. trueppm_api/apps/workspace/migrations/0024_alter_auditevent_event_type.py +33 -0
  726. trueppm_api/apps/workspace/migrations/0025_alter_auditevent_event_type.py +36 -0
  727. trueppm_api/apps/workspace/migrations/0026_alter_auditevent_event_type.py +37 -0
  728. trueppm_api/apps/workspace/migrations/0027_alter_auditevent_event_type.py +42 -0
  729. trueppm_api/apps/workspace/migrations/__init__.py +0 -0
  730. trueppm_api/apps/workspace/models.py +857 -0
  731. trueppm_api/apps/workspace/permissions.py +187 -0
  732. trueppm_api/apps/workspace/serializers.py +590 -0
  733. trueppm_api/apps/workspace/services.py +967 -0
  734. trueppm_api/apps/workspace/signals.py +37 -0
  735. trueppm_api/apps/workspace/tasks.py +616 -0
  736. trueppm_api/apps/workspace/urls.py +113 -0
  737. trueppm_api/apps/workspace/views.py +1581 -0
  738. trueppm_api/asgi.py +49 -0
  739. trueppm_api/celery.py +40 -0
  740. trueppm_api/core/__init__.py +0 -0
  741. trueppm_api/core/admin_site.py +206 -0
  742. trueppm_api/core/auth_views.py +934 -0
  743. trueppm_api/core/constant_time.py +51 -0
  744. trueppm_api/core/csp.py +54 -0
  745. trueppm_api/core/db.py +87 -0
  746. trueppm_api/core/db_session.py +37 -0
  747. trueppm_api/core/demo_read_only.py +314 -0
  748. trueppm_api/core/exception_handlers.py +157 -0
  749. trueppm_api/core/export_downloads.py +56 -0
  750. trueppm_api/core/extension_providers.py +56 -0
  751. trueppm_api/core/extension_signals.py +147 -0
  752. trueppm_api/core/idempotent.py +260 -0
  753. trueppm_api/core/metadata.py +42 -0
  754. trueppm_api/core/middleware.py +51 -0
  755. trueppm_api/core/openapi.py +1221 -0
  756. trueppm_api/core/password_reset.py +513 -0
  757. trueppm_api/core/protect_conflict.py +100 -0
  758. trueppm_api/core/ratelimit.py +148 -0
  759. trueppm_api/core/redis_throttle.py +82 -0
  760. trueppm_api/core/refresh_cookie_policy.py +156 -0
  761. trueppm_api/core/request_body.py +86 -0
  762. trueppm_api/core/security_checks.py +1034 -0
  763. trueppm_api/core/storage_config.py +105 -0
  764. trueppm_api/core/text_decode.py +168 -0
  765. trueppm_api/core/throttling.py +514 -0
  766. trueppm_api/core/valkey.py +214 -0
  767. trueppm_api/core/valkey_cache.py +66 -0
  768. trueppm_api/core/valkey_checks.py +104 -0
  769. trueppm_api/core/valkey_config.py +39 -0
  770. trueppm_api/core/worker_broker_wait.py +149 -0
  771. trueppm_api/core/worker_heartbeat.py +134 -0
  772. trueppm_api/core/worker_selfheal.py +205 -0
  773. trueppm_api/fields.py +36 -0
  774. trueppm_api/permissions.py +30 -0
  775. trueppm_api/py.typed +0 -0
  776. trueppm_api/routing.py +11 -0
  777. trueppm_api/settings/__init__.py +0 -0
  778. trueppm_api/settings/base.py +2605 -0
  779. trueppm_api/settings/dev.py +296 -0
  780. trueppm_api/settings/prod.py +265 -0
  781. trueppm_api/urls.py +217 -0
  782. trueppm_api/workflows/__init__.py +38 -0
  783. trueppm_api/workflows/backends/__init__.py +6 -0
  784. trueppm_api/workflows/backends/default.py +297 -0
  785. trueppm_api/workflows/consumers/__init__.py +11 -0
  786. trueppm_api/workflows/consumers/requeue_failed_task.py +65 -0
  787. trueppm_api/workflows/interface.py +148 -0
  788. trueppm_api/workflows/registry.py +106 -0
  789. trueppm_api/workflows/services.py +90 -0
  790. trueppm_api/wsgi.py +11 -0
  791. trueppm_api-0.4.0.dist-info/METADATA +273 -0
  792. trueppm_api-0.4.0.dist-info/RECORD +799 -0
  793. trueppm_api-0.4.0.dist-info/WHEEL +4 -0
  794. trueppm_api-0.4.0.dist-info/licenses/LICENSE +201 -0
  795. trueppm_api-0.4.0.dist-info/licenses/NOTICE +7 -0
  796. trueppm_api-0.4.0.dist-info/licenses/NOTICES +104 -0
  797. trueppm_api-0.4.0.dist-info/licenses/licenses/GPL-3.0.txt +674 -0
  798. trueppm_api-0.4.0.dist-info/licenses/licenses/LGPL-3.0.txt +165 -0
  799. trueppm_api-0.4.0.dist-info/licenses/licenses/MPL-2.0.txt +373 -0
@@ -0,0 +1,1717 @@
1
+ """Export a live program to the canonical JSON seed format (ADR-0109, issue #616).
2
+
3
+ ``export_program`` is the inverse of the importer: it walks a program and emits
4
+ a seed document that re-validates and re-imports. The exporter is deterministic
5
+ — arrays are emitted in a stable order and UUIDs are replaced with derived
6
+ slugs — so the round-trip ``export(import(export(p)))`` is identical to
7
+ ``export(import(p))`` (the #616 guarantee). It strips every derived field
8
+ (server_version, CPM outputs, short_id) by simply never emitting them.
9
+
10
+ By default it emits **v1** (``schema_version: "1.0"``, final-state) so the #616
11
+ byte-identical round-trip is preserved unchanged. Passing ``with_events=True``
12
+ emits **v2** (ADR-0114 §7 / #1109): dates are rewritten as ``anchor``-relative
13
+ offsets and an ordered ``events`` timeline is reconstructed from the history
14
+ tables so a shared program re-imports as the *life* it lived, not a snapshot.
15
+ The v2 path is a self-consistent fixpoint — ``export→import→export`` is
16
+ byte-identical — because every reconstructed event replays to a state that
17
+ reconstructs to the same event, and the importer's synthesizer is naturally
18
+ suppressed (every task with history already carries authored status events).
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import re
25
+ from collections.abc import Callable
26
+ from dataclasses import dataclass, field
27
+ from datetime import date, datetime
28
+ from typing import Any
29
+ from zoneinfo import ZoneInfo
30
+
31
+ from trueppm_api.apps.access.models import ProgramMembership, ProjectMembership, Role
32
+ from trueppm_api.apps.projects.models import (
33
+ AcceptanceCriterion,
34
+ BacklogItem,
35
+ Baseline,
36
+ BaselineTask,
37
+ BoardColumnConfig,
38
+ CeremonyTemplate,
39
+ CommentAcknowledgement,
40
+ CommentReaction,
41
+ Dependency,
42
+ Label,
43
+ Program,
44
+ Project,
45
+ RetroActionItem,
46
+ Risk,
47
+ RiskComment,
48
+ ScopeChangeStatus,
49
+ Sprint,
50
+ SprintRetro,
51
+ SprintScopeChange,
52
+ Task,
53
+ TaskComment,
54
+ TaskLabel,
55
+ TaskNote,
56
+ TaskRecurrenceRule,
57
+ TaskRelation,
58
+ )
59
+ from trueppm_api.apps.resources.models import (
60
+ ProjectResource,
61
+ Resource,
62
+ ResourceSkill,
63
+ TaskResource,
64
+ TaskSkillRequirement,
65
+ )
66
+
67
+ _UTC = ZoneInfo("UTC")
68
+
69
+ # Sentinel distinguishing "no HTTP caller at all" (a management command, run by
70
+ # an operator with direct DB/shell access — already a higher trust tier than any
71
+ # API role) from "an HTTP caller whose user object is falsy" (an async export
72
+ # job's ``requested_by`` can go ``NULL`` via ``on_delete=SET_NULL`` if the
73
+ # requesting account is deleted between enqueue and build). Only the sentinel is
74
+ # treated as trusted; a literal ``None`` from a real request lineage is not
75
+ # (#3627) — see ``_Exporter._resolve_email_visibility``.
76
+ _NO_HTTP_CALLER = object()
77
+
78
+
79
+ @dataclass(order=True)
80
+ class _RawEvent:
81
+ """A reconstructed event before serialization, sortable into replay order.
82
+
83
+ Sort key is ``(when, target, action, seq)``: chronological, with a fully
84
+ deterministic tiebreak so re-export is byte-identical. ``data`` (actor +
85
+ action-specific keys) is excluded from the ordering.
86
+ """
87
+
88
+ when: datetime
89
+ target: str
90
+ action: str
91
+ seq: int
92
+ data: dict[str, Any] = field(compare=False, default_factory=dict)
93
+
94
+
95
+ # Signature of the ``emit`` callback the reconstruction helpers are handed.
96
+ _Emit = Callable[[datetime, str, str, dict[str, Any]], None]
97
+
98
+ # seedDate / seedTimestamp cap a relative offset at 4 digits (~27 years); a date
99
+ # further from the anchor than this falls back to an ISO literal (still a valid
100
+ # seedDate/seedTimestamp) so a very long-lived program still exports cleanly.
101
+ _MAX_REL_OFFSET_DAYS = 9999
102
+
103
+ _ROLE_NAME: dict[int, str] = {
104
+ Role.VIEWER: "VIEWER",
105
+ Role.MEMBER: "MEMBER",
106
+ Role.SCHEDULER: "SCHEDULER",
107
+ Role.ADMIN: "ADMIN",
108
+ Role.OWNER: "OWNER",
109
+ }
110
+
111
+
112
+ #: Event actions that only exist from schema 2.1 (#3603).
113
+ _V21_EVENT_ACTIONS = frozenset({"task.note", "task.react", "task.ack", "time.log"})
114
+
115
+
116
+ #: Weekday names in bitmask order — the authoring shape of a recurrence rule (#3498).
117
+ _WEEKDAY_BITS = (
118
+ ("mon", 1),
119
+ ("tue", 2),
120
+ ("wed", 4),
121
+ ("thu", 8),
122
+ ("fri", 16),
123
+ ("sat", 32),
124
+ ("sun", 64),
125
+ )
126
+
127
+ #: ``Proficiency`` integer -> the seed's authoring name (#3498).
128
+ _PROFICIENCY_NAME = {1: "beginner", 2: "intermediate", 3: "expert"}
129
+
130
+ #: Task keys that only exist from schema 2.1.
131
+ _V21_TASK_KEYS = ("acceptance_criteria", "is_subtask", "recurrence", "skill_requirements")
132
+
133
+
134
+ def _uses_v21(doc: dict[str, Any]) -> bool:
135
+ """Whether an exported document carries any construct introduced in 2.1."""
136
+ program = doc.get("program", {})
137
+ if program.get("backlog_items") or program.get("ceremonies"):
138
+ return True
139
+ if any(resource.get("skills") for resource in doc.get("resources", [])):
140
+ return True
141
+ for project in doc.get("projects", []):
142
+ if project.get("team"):
143
+ return True
144
+ for task in project.get("tasks", []):
145
+ if task.get("type") == "tech_debt" or any(task.get(k) for k in _V21_TASK_KEYS):
146
+ return True
147
+ return any(
148
+ event.get("action") in _V21_EVENT_ACTIONS or "slug" in event or "reply_to" in event
149
+ for event in doc.get("events", [])
150
+ )
151
+
152
+
153
+ def dump_seed(payload: dict[str, Any]) -> str:
154
+ """Canonical serialization: sorted keys, 2-space indent, trailing newline.
155
+
156
+ Centralised so the management command, the REST endpoint, and the round-trip
157
+ test all emit byte-identical output.
158
+ """
159
+ return json.dumps(payload, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
160
+
161
+
162
+ # The seed schema caps every ``slug`` at 40 chars (so a program slug still fits
163
+ # ``Program.code``). Slugs are derived from free-text titles/names, so the
164
+ # exporter must enforce the cap itself — a risk titled longer than ~40 chars
165
+ # would otherwise emit a slug the importer's own schema rejects (#2006).
166
+ _MAX_SLUG_LEN = 40
167
+
168
+
169
+ def _slugify(text: str) -> str:
170
+ slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
171
+ # Truncate to the schema cap, then re-strip so a cut mid-separator can't
172
+ # leave a trailing "-" that violates the kebab-case pattern.
173
+ return slug[:_MAX_SLUG_LEN].strip("-") or "x"
174
+
175
+
176
+ class _SlugAllocator:
177
+ """Assigns unique kebab slugs deterministically (suffix on collision)."""
178
+
179
+ def __init__(self) -> None:
180
+ self._used: set[str] = set()
181
+
182
+ def take(self, text: str) -> str:
183
+ base = _slugify(text)
184
+ candidate = base
185
+ i = 2
186
+ while candidate in self._used:
187
+ suffix = f"-{i}"
188
+ # Keep the disambiguated slug within the 40-char cap by trimming the
189
+ # base to make room for the suffix (and re-stripping any dangling "-").
190
+ candidate = base[: _MAX_SLUG_LEN - len(suffix)].strip("-") + suffix
191
+ i += 1
192
+ self._used.add(candidate)
193
+ return candidate
194
+
195
+
196
+ def _put(target: dict[str, Any], key: str, value: Any) -> None:
197
+ """Emit a key only when meaningful — skips None and empty strings."""
198
+ if value is None or value == "":
199
+ return
200
+ target[key] = value
201
+
202
+
203
+ def _ceremony_entry(ceremony: CeremonyTemplate) -> dict[str, Any]:
204
+ entry: dict[str, Any] = {"name": ceremony.name, "cadence_type": ceremony.cadence_type}
205
+ _put(entry, "cadence_day", ceremony.cadence_day)
206
+ if ceremony.cadence_time is not None:
207
+ entry["cadence_time"] = ceremony.cadence_time.strftime("%H:%M")
208
+ entry["duration_minutes"] = ceremony.duration_minutes
209
+ _put(entry, "owner_role", ceremony.owner_role)
210
+ if not ceremony.enabled:
211
+ entry["enabled"] = False
212
+ return entry
213
+
214
+
215
+ def export_program(
216
+ program: Program,
217
+ *,
218
+ with_events: bool = False,
219
+ requesting_user: Any = _NO_HTTP_CALLER,
220
+ ) -> dict[str, Any]:
221
+ """Serialize ``program`` to a canonical seed document (a ``dict``).
222
+
223
+ Only member projects the ``requesting_user`` holds live ``ProjectMembership`` on
224
+ are included (#4310). Program-level blocks (roster, program backlog, ceremonies)
225
+ are program-scoped and always included; project content never is unless the
226
+ caller can read that project.
227
+
228
+ Args:
229
+ program: the program to export.
230
+ with_events: when ``False`` (default) emit a v1 final-state document,
231
+ preserving the #616 byte-identical round-trip. When ``True`` emit a
232
+ v2 document (ADR-0114 §7 / #1109) with ``anchor``-relative dates and
233
+ a reconstructed ``events`` timeline, so the export re-imports through
234
+ the replay engine as the program's dated life rather than a snapshot.
235
+ requesting_user: the account the export is being produced *for* (#3627).
236
+ ``Resource.email`` and account ``email`` are withheld unless this
237
+ user holds workspace Admin+ — see
238
+ ``_Exporter._resolve_email_visibility``. Omit entirely for a caller
239
+ with no HTTP request context (e.g. the management command, run by an
240
+ operator with shell/DB access already); that is treated as trusted
241
+ and email is included unredacted. A literal ``None`` (an async
242
+ export job whose ``requested_by`` went ``NULL``) is deliberately
243
+ *not* trusted and redacts.
244
+ """
245
+ projects = list(
246
+ Project.objects.filter(program=program, is_deleted=False).order_by("code", "name", "pk")
247
+ )
248
+ # #4310: a Program Admin's authority does not reach a member project's content
249
+ # unless the caller also holds live ProjectMembership on it. The sentinel is the
250
+ # trusted operator path (management command, shell access) and exports every
251
+ # member project; any real caller, including a literal None from a deleted
252
+ # requester, is intersected with its live project memberships. Filtering here
253
+ # rather than in the view means the async bundle and any future caller inherit
254
+ # the same boundary.
255
+ if requesting_user is not _NO_HTTP_CALLER:
256
+ from trueppm_api.apps.access.permissions import live_member_project_ids
257
+
258
+ readable = live_member_project_ids(requesting_user, [p.pk for p in projects])
259
+ projects = [p for p in projects if p.pk in readable]
260
+ return _Exporter(
261
+ program=program,
262
+ projects=projects,
263
+ with_events=with_events,
264
+ requesting_user=requesting_user,
265
+ ).build()
266
+
267
+
268
+ def export_project(project: Project, *, requesting_user: Any = _NO_HTTP_CALLER) -> dict[str, Any]:
269
+ """Serialize a single ``project`` to a canonical seed document (#967).
270
+
271
+ The canonical schema requires a top-level ``program`` block (ADR-0109) but
272
+ ``Project.program`` is nullable (ADR-0070 — standalone projects are
273
+ first-class), so the project is emitted inside a minimal program *synthesized
274
+ from the project itself* (slug/name/methodology). This is uniform whether or
275
+ not the live project belongs to a program, and because the synthesized slug
276
+ is project-derived rather than the parent program's ``code``, re-importing a
277
+ project export creates a fresh program instead of clobbering the live parent
278
+ program's subtree. The #616 round-trip guarantee still holds. See the #967
279
+ addendum in ADR-0109.
280
+
281
+ Args:
282
+ project: the project to export.
283
+ requesting_user: see :func:`export_program` — controls whether
284
+ ``Resource.email`` / account ``email`` are withheld (#3627).
285
+ """
286
+ return _Exporter(
287
+ program=None,
288
+ projects=[project],
289
+ synthetic_program=project,
290
+ requesting_user=requesting_user,
291
+ ).build()
292
+
293
+
294
+ class _Exporter:
295
+ def __init__(
296
+ self,
297
+ *,
298
+ program: Program | None,
299
+ projects: list[Project],
300
+ synthetic_program: Project | None = None,
301
+ with_events: bool = False,
302
+ requesting_user: Any = _NO_HTTP_CALLER,
303
+ ) -> None:
304
+ # ``program`` is the live parent program for a program export, or None
305
+ # for a single-project export (#967), in which case ``synthetic_program``
306
+ # (the project) sources the synthesized program-wrapper block.
307
+ self.program = program
308
+ self.synthetic_program = synthetic_program
309
+ self.projects = projects
310
+ # #3627: whether this export includes real Resource/account email.
311
+ # ``_resources_block``/``_account_entry`` never reach ``ResourceSerializer``
312
+ # (the #891 harvest control), so the exporter enforces the same invariant
313
+ # itself rather than inheriting a serializer it does not use. The
314
+ # endpoint-level gate (IsProjectAdmin/IsProgramAdmin) stays project- or
315
+ # program-scoped and self-grantable by design (creating a project makes
316
+ # you its Owner) — that is what makes the field a workspace-wide harvest
317
+ # once any project Admin can pull the whole catalog into an export. So
318
+ # email is workspace-Admin-only *content*, independent of who can reach
319
+ # the export action at all. See docs/adr/0034 (#3569 amendment) and #3627.
320
+ self._email_visible = self._resolve_email_visibility(requesting_user)
321
+ # #4082: blocker ``reason`` is ADR-0124 contributor voice, readable only by
322
+ # the assignee or an @-mentioned user — NOT by an Admin, so the Admin+
323
+ # endpoint gate does not cover it. Same trust rule as email: the no-HTTP
324
+ # sentinel (management command) is trusted; everything else, including a
325
+ # literal None, is gated per task through ``can_read_blocker_reason``.
326
+ self._blocker_requester = requesting_user
327
+ self._mentioned_task_ids: set[Any] | None = None
328
+ # v2 event-timeline export (#1109). When on, dates become anchor-relative
329
+ # and an ``events`` array is reconstructed from the history tables.
330
+ self.with_events = with_events
331
+ # The reference date for relative offsets (v2 only). The earliest project
332
+ # start is a deterministic, always-present choice (projects require a
333
+ # start_date), and it round-trips: re-import resolves the same absolute
334
+ # dates, so re-export recomputes the same anchor.
335
+ self.anchor: date = min(
336
+ (p.start_date for p in projects if p.start_date is not None), default=date.today()
337
+ )
338
+ # Account identity, captured once accounts are built, so an event actor
339
+ # always resolves to a real account slug (never a dangling ref).
340
+ self._account_user_pks: set[Any] = set()
341
+ self._fallback_actor_slug: str = ""
342
+ self.project_slug = _SlugAllocator()
343
+ self.account_slug = _SlugAllocator()
344
+ self.calendar_slug = _SlugAllocator()
345
+ self.resource_slug = _SlugAllocator()
346
+ # v2.1 comment slugs (#3493), minted only for a comment something refers to
347
+ # (a reply, reaction or acknowledgement). Document-wide, so two tasks'
348
+ # comments can never collide after the 40-char truncation.
349
+ self.comment_slug = _SlugAllocator()
350
+
351
+ # pk -> slug maps, built once so cross-references resolve consistently.
352
+ self.user_slugs: dict[Any, str] = {}
353
+ self.calendar_slugs: dict[Any, str] = {}
354
+ self.resource_slugs: dict[Any, str] = {}
355
+ self.project_slugs: dict[Any, str] = {}
356
+ # task pk -> (project_slug, wbs_path) for global task refs.
357
+ self.task_ref: dict[Any, tuple[str, str]] = {}
358
+ # sprint pk -> slug, scoped per project.
359
+ self.sprint_slugs: dict[Any, str] = {}
360
+ # Risk slugs are allocated per project inside ``_risk_blocks``; recorded
361
+ # here so ``risk.note`` events can target them. Projects are serialized
362
+ # before events, so this is populated by the time the timeline is built.
363
+ self.risk_slugs: dict[Any, str] = {}
364
+ # task pk -> [label slug, …], populated per project in ``_project_block``
365
+ # (ADR-0400 labels folded into the seed, #1958). Label slugs are
366
+ # project-scoped, matching the slug-based (no-UUID) seed contract.
367
+ self.task_label_slugs: dict[Any, list[str]] = {}
368
+ # memoized — _all_resources is consulted by three blocks.
369
+ self._resources_cache: list[Resource] | None = None
370
+
371
+ @staticmethod
372
+ def _resolve_email_visibility(requesting_user: Any) -> bool:
373
+ """True when ``requesting_user`` may see real ``email`` values (#3627).
374
+
375
+ The ``_NO_HTTP_CALLER`` sentinel (the parameter default) means the caller
376
+ has no HTTP request context at all — the management command, run by an
377
+ operator with direct DB/shell access, already a higher trust tier than
378
+ any API role — and is treated as trusted. Every other value, including a
379
+ literal ``None``, goes through the real check: an HTTP-driven export
380
+ passes ``request.user`` (always a real, authenticated user), while an
381
+ async export-job builder passes ``job.requested_by``, which can be
382
+ ``None`` if the requesting account was deleted between enqueue and
383
+ build — and a gone account must not fall back to trusted. Email is
384
+ visible only at workspace Admin+ (``WorkspaceRole.ADMIN``), matching the
385
+ invariant the #3569 amendment records for the other three email-bearing
386
+ routes: the endpoint stays reachable at project/program Admin+
387
+ (self-grantable by creating a project), so the field itself — not the
388
+ endpoint — has to be the workspace-wide gate.
389
+ """
390
+ if requesting_user is _NO_HTTP_CALLER:
391
+ return True
392
+ # Imported locally (not at module scope) to match the existing
393
+ # cross-app-import convention in this package (see attachment_policy.py,
394
+ # calendar_settings.py, etc.) and avoid a load-order dependency on the
395
+ # workspace app from the projects app.
396
+ from trueppm_api.apps.workspace.models import WorkspaceRole
397
+ from trueppm_api.apps.workspace.permissions import workspace_role_for_user
398
+
399
+ role = workspace_role_for_user(requesting_user)
400
+ return role is not None and role >= WorkspaceRole.ADMIN
401
+
402
+ # --- public ------------------------------------------------------------
403
+
404
+ def build(self) -> dict[str, Any]:
405
+ for project in self.projects:
406
+ # From the name, not the key: since ADR-1237 every project has a key
407
+ # (``PC`` for "Platform Core"), and a file-local slug is for a human
408
+ # reading the document. The key itself round-trips in ``code``.
409
+ self.project_slugs[project.pk] = self.project_slug.take(project.name)
410
+
411
+ # Pre-pass: index every task and sprint across ALL projects before
412
+ # emitting any block, so cross-project dependency and risk refs resolve
413
+ # regardless of project ordering.
414
+ self._project_tasks: dict[Any, list[Task]] = {}
415
+ self._project_sprints: dict[Any, list[Sprint]] = {}
416
+ for project in self.projects:
417
+ self._index_project(project)
418
+
419
+ doc: dict[str, Any] = {"schema_version": "2.0" if self.with_events else "1.0"}
420
+ if self.with_events:
421
+ # An explicit anchor pins the offsets so re-import resolves the exact
422
+ # same absolute dates (round-trip determinism), rather than drifting
423
+ # to the next import day.
424
+ doc["anchor"] = self.anchor.isoformat()
425
+ doc["program"] = self._program_block()
426
+ accounts = self._accounts_block()
427
+ # Capture account identity before events so an event actor resolves to a
428
+ # real account slug and the deterministic fallback (OWNER) is known.
429
+ self._capture_account_identity(accounts)
430
+ calendars = self._calendars_block()
431
+ resources = self._resources_block()
432
+ if accounts:
433
+ doc["accounts"] = accounts
434
+ if calendars:
435
+ doc["calendars"] = calendars
436
+ if resources:
437
+ doc["resources"] = resources
438
+ doc["projects"] = [self._project_block(p) for p in self.projects]
439
+ if self.with_events:
440
+ self._put_program_v21(doc["program"])
441
+ events = self._events_block()
442
+ if events:
443
+ doc["events"] = events
444
+ # Declare 2.1 only when the document uses a 2.1 construct, so a program
445
+ # with none still exports as 2.0 and stays importable by a 2.0 build.
446
+ if _uses_v21(doc):
447
+ doc["schema_version"] = "2.1"
448
+ return doc
449
+
450
+ def _backlog_item_entry(self, item: BacklogItem, allocator: _SlugAllocator) -> dict[str, Any]:
451
+ entry: dict[str, Any] = {"slug": allocator.take(item.title), "title": item.title}
452
+ _put(entry, "description", item.description)
453
+ entry["item_type"] = item.item_type
454
+ entry["status"] = item.status
455
+ if item.tags:
456
+ entry["tags"] = list(item.tags)
457
+ _put(entry, "priority_rank", item.priority_rank)
458
+ _put(entry, "story_points", item.story_points)
459
+ ref = self.task_ref.get(item.pulled_task_id) if item.pulled_task_id else None
460
+ if ref is not None:
461
+ entry["pulled_to"] = f"{ref[0]}:{ref[1]}"
462
+ if item.pulled_at is not None:
463
+ entry["pulled_at"] = self._rel_ts(item.pulled_at)
464
+ if item.pulled_by_id in self._account_user_pks:
465
+ entry["pulled_by"] = self._user_slug(item.pulled_by)
466
+ elif item.status == "pulled":
467
+ # The task it became is gone or unexportable; a "pulled" item that
468
+ # names no task would fail validation, so it re-imports as archived.
469
+ entry["status"] = "archived"
470
+ if item.created_by_id in self._account_user_pks:
471
+ entry["created_by"] = self._user_slug(item.created_by)
472
+ entry["created_at"] = self._rel_ts(item.created_at)
473
+ return entry
474
+
475
+ def _export_backlog_items(self) -> list[dict[str, Any]]:
476
+ items = sorted(
477
+ BacklogItem.objects.filter(program=self.program, is_deleted=False),
478
+ key=lambda i: (i.priority_rank is None, i.priority_rank or 0, i.created_at, i.title),
479
+ )
480
+ allocator = _SlugAllocator()
481
+ return [self._backlog_item_entry(item, allocator) for item in items]
482
+
483
+ def _put_program_v21(self, block: dict[str, Any]) -> None:
484
+ """Program backlog and ceremonies (v2.1, #3491/#3603). v2 export only.
485
+
486
+ Built after account identity is captured, so ``pulled_by``/``created_by``
487
+ can be restricted to users that already hold an account slug. Agent actions
488
+ and share links are deliberately never exported: one is audit evidence and
489
+ the other a credential, and every non-sample import rejects both.
490
+ """
491
+ if self.program is None:
492
+ return
493
+ backlog = self._export_backlog_items()
494
+ if backlog:
495
+ block["backlog_items"] = backlog
496
+
497
+ ceremonies = [
498
+ _ceremony_entry(ceremony)
499
+ for ceremony in CeremonyTemplate.objects.filter(
500
+ program=self.program, is_deleted=False
501
+ ).order_by("name", "pk")
502
+ ]
503
+ if ceremonies:
504
+ block["ceremonies"] = ceremonies
505
+
506
+ # --- top-level blocks --------------------------------------------------
507
+
508
+ def _program_block(self) -> dict[str, Any]:
509
+ if self.program is None:
510
+ # Single-project export (#967): synthesize a minimal program wrapper
511
+ # from the project so the seed satisfies the schema's required
512
+ # ``program`` block while staying decoupled from any live parent
513
+ # program (re-import won't clobber it). The slug is slugified to keep
514
+ # it schema-valid (kebab-case) since Project.code is free-form.
515
+ proj = self.synthetic_program
516
+ assert proj is not None # always set when self.program is None
517
+ block: dict[str, Any] = {
518
+ # From the name, for the same reason as project slugs (ADR-1237).
519
+ "slug": _slugify(proj.name),
520
+ "name": proj.name,
521
+ "methodology": proj.methodology,
522
+ }
523
+ _put(block, "description", proj.description)
524
+ return block
525
+ block = {
526
+ "slug": self.program.code or self.project_slug.take(self.program.name),
527
+ "name": self.program.name,
528
+ "methodology": self.program.methodology,
529
+ }
530
+ _put(block, "description", self.program.description)
531
+ _put(block, "color", self.program.color)
532
+ if self.program.lead_id is not None:
533
+ block["lead"] = self._user_slug(self.program.lead)
534
+ return block
535
+
536
+ def _accounts_block(self) -> list[dict[str, Any]]:
537
+ # Every user referenced anywhere in the export needs an account so it
538
+ # re-imports. Membership roles come from ProgramMembership. A single-
539
+ # project export (#967) has no parent program, so the roster is empty and
540
+ # no account carries a program-level role — but the project's own live
541
+ # members are still emitted (#3457), alongside the users it references
542
+ # through task assignments, resource accounts and risk ownership.
543
+ roles, users = self._collect_account_users()
544
+ accounts = [self._account_entry(uid, user, roles) for uid, user in users.items()]
545
+ return sorted(accounts, key=lambda a: a["slug"])
546
+
547
+ def _collect_account_users(self) -> tuple[dict[Any, int], dict[Any, Any]]:
548
+ """Gather every user referenced by the export, in a stable order.
549
+
550
+ Insertion order (program roster, then task assignees, risk owners,
551
+ resource accounts, then live project members) fixes slug-allocation
552
+ order, so the roster must be walked in exactly this sequence for the
553
+ round-trip to stay byte-stable.
554
+ """
555
+ users: dict[Any, Any] = {}
556
+ roles = self._program_roster(users)
557
+ # Project leads (#3098) come before task assignees so a lead who is
558
+ # referenced nowhere else still gets an account entry — without one the
559
+ # exported ``project.lead`` slug would dangle and the document would not
560
+ # re-import. Inserted here rather than appended because insertion order
561
+ # fixes slug allocation, and the round-trip is asserted byte-identical.
562
+ for proj in self.projects:
563
+ if proj.lead_id is not None:
564
+ users[proj.lead_id] = proj.lead
565
+ for task in self._all_tasks():
566
+ if task.assignee_id is not None:
567
+ users[task.assignee_id] = task.assignee
568
+ for risk in Risk.objects.filter(project__in=self.projects).select_related("owner"):
569
+ if risk.owner_id is not None:
570
+ users[risk.owner_id] = risk.owner
571
+ for res in self._all_resources():
572
+ if res.user_id is not None:
573
+ users[res.user_id] = res.user
574
+ self._add_project_member_users(users)
575
+ return roles, users
576
+
577
+ def _add_project_member_users(self, users: dict[Any, Any]) -> None:
578
+ """Add every live project member not already present, walking the projects in order."""
579
+ # Live *project* members, last (#3457). Project and program membership are
580
+ # independent grants (ADR-0070 §RBAC), so a user revoked from the program
581
+ # can still hold a live ProjectMembership. Now that the roster no longer
582
+ # carries revoked members, such a user would reach _member_blocks with no
583
+ # slug and their project grant would be silently dropped from the
584
+ # document — access lost rather than access leaked, but lost all the same.
585
+ # Appended after every existing source rather than inserted beside the
586
+ # roster: this can only add users that would otherwise carry no slug at
587
+ # all, so no already-allocated slug moves and the byte-stable fixpoint is
588
+ # untouched. One query, then regrouped and walked in ``self.projects``
589
+ # order and by username, because insertion order fixes slug allocation
590
+ # and a database's natural row order does not.
591
+ #
592
+ # Ordered by ``user__username`` and NOT by ``user_id``: the slug is
593
+ # derived from the username and two usernames can slugify to the same
594
+ # base, in which case ``_SlugAllocator`` suffixes them ``-2``/``-3`` in
595
+ # *call* order. ``username`` round-trips verbatim through the document;
596
+ # the user PK does not — a re-import mints new users in ``accounts[]``
597
+ # order — so ordering on the id would let a colliding pair swap suffixes
598
+ # on re-export and break the byte-identical fixpoint (#616).
599
+ members_by_project: dict[Any, list[Any]] = {}
600
+ for pm in (
601
+ ProjectMembership.objects.filter(project__in=self.projects, is_deleted=False)
602
+ .select_related("user")
603
+ .order_by("user__username")
604
+ ):
605
+ members_by_project.setdefault(pm.project_id, []).append(pm)
606
+ for proj in self.projects:
607
+ for pm in members_by_project.get(proj.pk, ()):
608
+ users.setdefault(pm.user_id, pm.user)
609
+
610
+ def _program_roster(self, users: dict[Any, Any]) -> dict[Any, int]:
611
+ """Seed ``users`` with the program lead + members; return their roles.
612
+
613
+ A single-project export (#967) has no parent program, so the roster is
614
+ empty and no program-level roles apply.
615
+
616
+ Both ``ProgramMembership`` reads floor on ``is_deleted=False`` (#3457),
617
+ matching the project-side twin in ``_member_blocks``. A revoked membership
618
+ is a tombstone that still owns the ``(program, user)`` slot, and the
619
+ importer's grant deliberately clears that tombstone (``is_deleted: False``)
620
+ so a seed grant always confers access (#3410) — so any revoked member left
621
+ in the roster is handed their role back on import. The floor has to be
622
+ here, on the export side: a revoked member must not be in the document at
623
+ all.
624
+
625
+ The ``lead`` read below is **deliberately not floored**, and must not be
626
+ "fixed" for symmetry. ``Program.lead`` is a display FK distinct from the
627
+ OWNER membership, ``_program_block`` emits its slug unconditionally, and
628
+ ``validate_seed`` requires ``$.program.lead`` to resolve to an
629
+ ``accounts[]`` entry — so dropping a lead whose *membership* was revoked
630
+ would emit a document that fails the exporter's own validator. It confers
631
+ nothing either way: the account is emitted without a ``role`` key, and the
632
+ importer's grant skips a roleless account.
633
+ """
634
+ if self.program is None:
635
+ return {}
636
+ roles = {
637
+ m.user_id: m.role
638
+ for m in ProgramMembership.objects.filter(program=self.program, is_deleted=False)
639
+ }
640
+ if self.program.lead_id is not None:
641
+ users[self.program.lead_id] = self.program.lead
642
+ for m in ProgramMembership.objects.filter(
643
+ program=self.program, is_deleted=False
644
+ ).select_related("user"):
645
+ users[m.user_id] = m.user
646
+ return roles
647
+
648
+ def _account_entry(self, uid: Any, user: Any, roles: dict[Any, int]) -> dict[str, Any]:
649
+ block: dict[str, Any] = {"slug": self._user_slug(user), "username": user.get_username()}
650
+ # #3627: withheld for a non-workspace-Admin caller. Safe for the
651
+ # generic re-import path — accounts are matched by ``username``, never
652
+ # ``email`` (see importer._resolve_accounts) — so dropping the key here
653
+ # never breaks round-trip. ``_put`` already drops falsy values, so
654
+ # passing "" simply omits the key, matching the #3599 precedent of
655
+ # dropping rather than nulling a withheld email.
656
+ _put(block, "email", getattr(user, "email", "") if self._email_visible else "")
657
+ display = f"{user.first_name} {user.last_name}".strip()
658
+ _put(block, "display_name", display)
659
+ if uid in roles:
660
+ block["role"] = _ROLE_NAME[roles[uid]]
661
+ return block
662
+
663
+ def _calendars_block(self) -> list[dict[str, Any]]:
664
+ calendars: dict[Any, Any] = {}
665
+ for project in self.projects:
666
+ if project.calendar is not None:
667
+ calendars[project.calendar.pk] = project.calendar
668
+ for res in self._all_resources():
669
+ if res.calendar is not None:
670
+ calendars[res.calendar.pk] = res.calendar
671
+ blocks = []
672
+ for cal in calendars.values():
673
+ slug = self._calendar_slug(cal)
674
+ block: dict[str, Any] = {"slug": slug, "name": cal.name}
675
+ _put(block, "working_days", cal.working_days)
676
+ _put(block, "hours_per_day", cal.hours_per_day)
677
+ _put(block, "timezone", cal.timezone)
678
+ # Non-working ranges (holidays / PTO, #376). Exported as ISO literals so
679
+ # the export→import→export fixpoint is byte-stable; ordered for
680
+ # determinism. Forecast-snapshot history is deliberately NOT exported —
681
+ # like SprintBurnSnapshot it is derived observational history, not
682
+ # authored structure, so a round-trip drops it (its parameters are not
683
+ # recoverable from the materialized rows).
684
+ exceptions = [
685
+ {
686
+ "exc_start": exc.exc_start.isoformat(),
687
+ "exc_end": exc.exc_end.isoformat(),
688
+ **({"description": exc.description} if exc.description else {}),
689
+ }
690
+ for exc in cal.exceptions.all().order_by("exc_start", "exc_end")
691
+ ]
692
+ if exceptions:
693
+ block["exceptions"] = exceptions
694
+ blocks.append(block)
695
+ return sorted(blocks, key=lambda c: c["slug"])
696
+
697
+ def _resources_block(self) -> list[dict[str, Any]]:
698
+ blocks = []
699
+ for res in self._all_resources():
700
+ slug = self._resource_slug(res)
701
+ block: dict[str, Any] = {"slug": slug, "name": res.name}
702
+ # #3627: withheld for a non-workspace-Admin caller. Safe for the
703
+ # generic re-import path — ``_resolve_resources`` never matches an
704
+ # existing catalog Resource by email on that path (it always creates
705
+ # a fresh row, #1004) — only the server-curated sample loader does,
706
+ # and that path is never fed a redacted export.
707
+ _put(block, "email", res.email if self._email_visible else "")
708
+ _put(block, "job_role", res.job_role)
709
+ _put(block, "max_units", float(res.max_units))
710
+ if res.calendar_id is not None:
711
+ block["calendar"] = self._calendar_slug(res.calendar)
712
+ if res.user_id is not None:
713
+ block["account"] = self._user_slug(res.user)
714
+ if self.with_events:
715
+ # v2.1 (#3498). Ordered on the normalized name so the export is stable.
716
+ skills = [
717
+ {
718
+ "name": rs.skill.name,
719
+ "proficiency": _PROFICIENCY_NAME[rs.proficiency],
720
+ **({"category": rs.skill.category} if rs.skill.category else {}),
721
+ }
722
+ for rs in ResourceSkill.objects.filter(resource=res, is_deleted=False)
723
+ .select_related("skill")
724
+ .order_by("skill__normalized_name", "pk")
725
+ ]
726
+ if skills:
727
+ block["skills"] = skills
728
+ blocks.append(block)
729
+ return sorted(blocks, key=lambda r: r["slug"])
730
+
731
+ # --- per-project -------------------------------------------------------
732
+
733
+ def _index_project(self, project: Project) -> None:
734
+ """Populate global task/sprint slug maps for one project (pre-pass)."""
735
+ pslug = self.project_slugs[project.pk]
736
+ # A task with no wbs_path (e.g. a promoted retro-action backlog item) has
737
+ # no WBS identity and cannot be represented in a seed — the schema requires
738
+ # a wbs_path. Exclude it from both tasks[] and the ref map so refs to it are
739
+ # dropped rather than emitting an invalid "None" path.
740
+ tasks = list(
741
+ Task.objects.filter(project=project, is_deleted=False, wbs_path__isnull=False).order_by(
742
+ "wbs_path", "pk"
743
+ )
744
+ )
745
+ self._project_tasks[project.pk] = tasks
746
+ for task in tasks:
747
+ self.task_ref[task.pk] = (pslug, str(task.wbs_path))
748
+
749
+ sprints = list(
750
+ Sprint.objects.filter(project=project, is_deleted=False).order_by("start_date", "pk")
751
+ )
752
+ self._project_sprints[project.pk] = sprints
753
+ sprint_alloc = _SlugAllocator()
754
+ for sprint in sprints:
755
+ self.sprint_slugs[sprint.pk] = sprint_alloc.take(sprint.name)
756
+
757
+ def _project_block(self, project: Project) -> dict[str, Any]:
758
+ pslug = self.project_slugs[project.pk]
759
+ tasks = self._project_tasks[project.pk]
760
+ sprints = self._project_sprints[project.pk]
761
+
762
+ block: dict[str, Any] = {
763
+ "slug": pslug,
764
+ "name": project.name,
765
+ "methodology": project.methodology,
766
+ "start_date": self._date_str(project.start_date) if project.start_date else None,
767
+ }
768
+ self._put_project_scalars(block, project)
769
+
770
+ board_columns = self._board_column_blocks(project)
771
+ member_blocks = self._member_blocks(project)
772
+
773
+ # Project-scoped labels (ADR-0400, #1089) folded into the seed (#1958) so a
774
+ # re-seed round-trips board-card labels. Slugs are allocated per project
775
+ # (deterministic, kebab-cased) and referenced by ``labels`` on each task
776
+ # block; label identity in the seed is slug-based (no UUID), matching the
777
+ # existing seed contract (UUID-preserving round-trip is 0.5, #1959).
778
+ label_blocks = self._label_blocks(project)
779
+
780
+ sprint_blocks = [self._sprint_block(s) for s in sprints]
781
+ task_blocks = [self._task_block(t) for t in tasks]
782
+ dep_blocks = self._dependency_blocks(project, pslug)
783
+ baseline_blocks = self._baseline_blocks(project, pslug)
784
+ risk_blocks = self._risk_blocks(project, pslug)
785
+ # Insertion order IS the emitted key order, and the export contract is a
786
+ # byte-identical export -> import -> export fixpoint (see
787
+ # ``_member_blocks``), so this sequence is not cosmetic. Note it differs
788
+ # from the computation order above: the blocks are built sprints-first
789
+ # because slug allocation is order-sensitive, but emitted tasks-first.
790
+ for key, value in (
791
+ ("board_columns", board_columns),
792
+ ("members", member_blocks),
793
+ ("labels", label_blocks),
794
+ ("tasks", task_blocks),
795
+ ("dependencies", dep_blocks),
796
+ ("sprints", sprint_blocks),
797
+ ("baselines", baseline_blocks),
798
+ ("risks", risk_blocks),
799
+ ("team", self._team_block(project) if self.with_events else {}),
800
+ ):
801
+ if value:
802
+ block[key] = value
803
+ return block
804
+
805
+ def _team_block(self, project: Project) -> dict[str, Any]:
806
+ """The default team's name and SM/PO facets (v2.1, #3498). v2 export only.
807
+
808
+ Only facet holders are listed: membership itself re-derives from the
809
+ project's members on import, so listing everyone would restate it. The
810
+ default name is omitted, so a project nobody configured exports as before.
811
+ """
812
+ from trueppm_api.apps.teams.models import Team, TeamMembership
813
+
814
+ team = Team.objects.filter(project=project, is_default=True, is_deleted=False).first()
815
+ if team is None:
816
+ return {}
817
+ members: list[dict[str, Any]] = []
818
+ for membership in (
819
+ TeamMembership.objects.filter(team=team, is_deleted=False)
820
+ .exclude(is_scrum_master=False, is_product_owner=False)
821
+ .select_related("user")
822
+ ):
823
+ if membership.user_id not in self._account_user_pks:
824
+ continue
825
+ entry: dict[str, Any] = {"account": self._user_slug(membership.user)}
826
+ if membership.is_scrum_master:
827
+ entry["scrum_master"] = True
828
+ if membership.is_product_owner:
829
+ entry["product_owner"] = True
830
+ members.append(entry)
831
+ if not members and team.name == "Default Team":
832
+ return {}
833
+ block: dict[str, Any] = {"members": sorted(members, key=lambda e: e["account"])}
834
+ if team.name != "Default Team":
835
+ block["name"] = team.name
836
+ return block
837
+
838
+ def _put_project_scalars(self, block: dict[str, Any], project: Project) -> None:
839
+ """Add the project's optional scalar fields, each omitted at its default.
840
+
841
+ A field equal to its default is left out rather than emitted, so a seed
842
+ stays readable and a later change of default does not silently pin every
843
+ exported project to the old value.
844
+ """
845
+ _put(block, "description", project.description)
846
+ _put(block, "code", project.code)
847
+ if project.lead_id is not None:
848
+ block["lead"] = self._user_slug(project.lead)
849
+ if project.calendar_id is not None:
850
+ block["calendar"] = self._calendar_slug(project.calendar)
851
+ if project.default_view and project.default_view != "SCHEDULE":
852
+ block["default_view"] = project.default_view
853
+ if project.estimation_mode and project.estimation_mode != "open":
854
+ block["estimation_mode"] = project.estimation_mode
855
+ if project.health and project.health != "AUTO":
856
+ block["health"] = project.health
857
+
858
+ def _member_blocks(self, project: Project) -> list[dict[str, Any]]:
859
+ """Emit this project's memberships so project-scoped roles round-trip (#3092).
860
+
861
+ Emitted unconditionally rather than only when the roles differ from the
862
+ program roster. A "same as the program" shortcut would make the export
863
+ lossy the moment a role was later changed to match by coincidence, and the
864
+ fixpoint (export -> import -> export) is byte-identical either way because
865
+ a declared ``members`` list re-imports to exactly itself.
866
+
867
+ Only users already carrying an account slug are emitted. ``_user_slug``
868
+ *allocates* on first call, and allocation order is what keeps the export
869
+ byte-stable (see ``_collect_account_users``), so minting one here would
870
+ reorder the roster; a member without an account entry could not be
871
+ re-imported anyway.
872
+
873
+ This used to lean on "every project member also holds a
874
+ ``ProgramMembership``, so is already slugged". That premise is false —
875
+ the two grants are independent (ADR-0070 §RBAC), and once the roster
876
+ stopped carrying revoked members (#3457) a program-revoked, still-live
877
+ project member had no slug and was dropped here in silence. So
878
+ ``_collect_account_users`` now slugs live project members explicitly, as
879
+ its last source; do not restore the assumption.
880
+ """
881
+ rows = ProjectMembership.objects.filter(project=project, is_deleted=False).select_related(
882
+ "user"
883
+ )
884
+ blocks = [
885
+ {"account": self.user_slugs[m.user_id], "role": _ROLE_NAME[m.role]}
886
+ for m in rows
887
+ if m.user_id in self.user_slugs
888
+ ]
889
+ return sorted(blocks, key=lambda b: b["account"])
890
+
891
+ def _board_column_blocks(self, project: Project) -> list[dict[str, Any]]:
892
+ """Emit the project's board configuration, if it has one (#3093).
893
+
894
+ Absent when the project never configured a board — the API serves
895
+ hardcoded defaults in that case, and emitting them would turn "this
896
+ project uses the defaults" into "this project pinned today's defaults",
897
+ which is a different and worse claim on re-import.
898
+
899
+ Optional per-column metadata is emitted only when set, so a plain
900
+ rename round-trips as a rename rather than as a config that also pins
901
+ every null.
902
+ """
903
+ config = BoardColumnConfig.objects.filter(project=project).first()
904
+ if config is None or not config.columns:
905
+ return []
906
+ blocks: list[dict[str, Any]] = []
907
+ for column in config.columns:
908
+ entry: dict[str, Any] = {
909
+ "status": column["status"],
910
+ "label": column.get("label", ""),
911
+ }
912
+ if column.get("visible") is not None:
913
+ entry["visible"] = column["visible"]
914
+ for key in ("color", "wip_limit", "age_threshold_days"):
915
+ if column.get(key) is not None:
916
+ entry[key] = column[key]
917
+ lanes = [
918
+ {
919
+ "key": lane["key"],
920
+ "label": lane["label"],
921
+ **({"wip_limit": lane["wip_limit"]} if lane.get("wip_limit") else {}),
922
+ }
923
+ for lane in (column.get("lanes") or [])
924
+ ]
925
+ if lanes:
926
+ entry["lanes"] = lanes
927
+ blocks.append(entry)
928
+ return blocks
929
+
930
+ def _label_blocks(self, project: Project) -> list[dict[str, Any]]:
931
+ """Emit the project's labels and index each task's label slugs (#1958).
932
+
933
+ Labels are ordered by ``(position, name)`` — their stable display order —
934
+ so the slug allocation is deterministic and the round-trip is byte-stable.
935
+ The per-task slug list is stashed in ``self.task_label_slugs`` for
936
+ ``_task_block`` to read; a label with no attached tasks still round-trips
937
+ (it is a curated catalog entry, so the block is emitted regardless).
938
+ """
939
+ labels = list(Label.objects.filter(project=project).order_by("position", "name", "pk"))
940
+ if not labels:
941
+ return []
942
+ allocator = _SlugAllocator()
943
+ slug_by_label: dict[Any, str] = {}
944
+ blocks: list[dict[str, Any]] = []
945
+ for label in labels:
946
+ slug = allocator.take(label.name)
947
+ slug_by_label[label.pk] = slug
948
+ block: dict[str, Any] = {"slug": slug, "name": label.name, "color": label.color}
949
+ if label.position:
950
+ block["position"] = label.position
951
+ blocks.append(block)
952
+ # Index each task's labels in (position, name) order — the pill-row order —
953
+ # so a task's ``labels`` slug list is deterministic too.
954
+ for tl in (
955
+ TaskLabel.objects.filter(label__project=project)
956
+ .select_related("label")
957
+ .order_by("label__position", "label__name", "label__pk")
958
+ ):
959
+ label_slug = slug_by_label.get(tl.label_id)
960
+ if label_slug is not None:
961
+ self.task_label_slugs.setdefault(tl.task_id, []).append(label_slug)
962
+ return blocks
963
+
964
+ def _task_block(self, task: Task) -> dict[str, Any]:
965
+ block: dict[str, Any] = {"wbs_path": str(task.wbs_path), "name": task.name}
966
+ self._put_task_core(block, task)
967
+ self._put_task_agile(block, task)
968
+ self._put_task_blocker(block, task)
969
+ self._put_task_attachments(block, task)
970
+ self._put_task_estimate(block, task)
971
+ self._put_task_assignments(block, task)
972
+ self._put_task_labels_and_links(block, task)
973
+ if self.with_events:
974
+ self._put_task_criteria(block, task)
975
+ self._put_task_depth(block, task)
976
+ return block
977
+
978
+ def _put_task_depth(self, block: dict[str, Any], task: Task) -> None:
979
+ """Subtask flag, recurrence rule and skill requirements (v2.1, #3498). v2 only.
980
+
981
+ The rule is exported as its authoring shape (weekday names, not the bitmask)
982
+ and ``end_type`` is implied by which end key is present, so a re-import
983
+ reconstructs exactly the row it came from.
984
+ """
985
+ if task.is_subtask:
986
+ block["is_subtask"] = True
987
+ rule = TaskRecurrenceRule.objects.filter(task=task, is_deleted=False).first()
988
+ if rule is not None:
989
+ recurrence: dict[str, Any] = {"frequency": rule.frequency}
990
+ if rule.interval != 1:
991
+ recurrence["interval"] = rule.interval
992
+ days = [name for name, bit in _WEEKDAY_BITS if rule.weekdays & bit]
993
+ if days:
994
+ recurrence["weekdays"] = days
995
+ _put(recurrence, "day_of_month", rule.day_of_month)
996
+ recurrence["time_of_day"] = rule.time_of_day.strftime("%H:%M")
997
+ if rule.end_date is not None:
998
+ recurrence["end_date"] = self._date_str(rule.end_date)
999
+ _put(recurrence, "end_count", rule.end_count)
1000
+ block["recurrence"] = recurrence
1001
+ requirements = [
1002
+ {"skill": req.skill.name, "min_proficiency": _PROFICIENCY_NAME[req.min_proficiency]}
1003
+ for req in TaskSkillRequirement.objects.filter(task=task, is_deleted=False)
1004
+ .select_related("skill")
1005
+ .order_by("skill__normalized_name", "pk")
1006
+ ]
1007
+ if requirements:
1008
+ block["skill_requirements"] = requirements
1009
+
1010
+ def _put_task_criteria(self, block: dict[str, Any], task: Task) -> None:
1011
+ """Acceptance criteria in position order (v2.1, #3492). v2 export only.
1012
+
1013
+ Emitted as final state — ``met`` with its ``met_by``/``met_at`` trail — and
1014
+ never as ``task.ac_met`` beats, the same reason the exporter already skips
1015
+ that action: the end value rides the row, so a beat would apply it twice.
1016
+ ``met_by`` is emitted only for a user who is already an account; minting a
1017
+ slug here would reorder allocation and break the byte-stable round-trip.
1018
+ """
1019
+ rows = AcceptanceCriterion.objects.filter(task=task, is_deleted=False).order_by(
1020
+ "position", "pk"
1021
+ )
1022
+ criteria: list[dict[str, Any]] = []
1023
+ for row in rows:
1024
+ entry: dict[str, Any] = {"text": row.text}
1025
+ for key in ("given", "when", "then"):
1026
+ _put(entry, key, getattr(row, key))
1027
+ if row.met:
1028
+ entry["met"] = True
1029
+ if row.met_by_id is not None and row.met_by_id in self._account_user_pks:
1030
+ entry["met_by"] = self._user_slug(row.met_by)
1031
+ if row.met_at is not None:
1032
+ entry["met_at"] = self._rel_ts(row.met_at)
1033
+ criteria.append(entry)
1034
+ if criteria:
1035
+ block["acceptance_criteria"] = criteria
1036
+
1037
+ def _put_task_core(self, block: dict[str, Any], task: Task) -> None:
1038
+ """Scalar schedule/status fields, each emitted only when non-default."""
1039
+ if task.type and task.type != "task":
1040
+ block["type"] = task.type
1041
+ if task.status and task.status != "NOT_STARTED":
1042
+ block["status"] = task.status
1043
+ if task.is_milestone:
1044
+ block["is_milestone"] = True
1045
+ if task.duration:
1046
+ block["duration"] = task.duration
1047
+ if task.planned_start is not None:
1048
+ block["planned_start"] = self._date_str(task.planned_start)
1049
+ if task.percent_complete:
1050
+ block["percent_complete"] = task.percent_complete
1051
+ _put(block, "notes", task.notes)
1052
+ _put(block, "story_points", task.story_points)
1053
+ _put(block, "remaining_points", task.remaining_points)
1054
+
1055
+ def _put_task_agile(self, block: dict[str, Any], task: Task) -> None:
1056
+ """Assignee, sprint linkage, and agile/governance classification fields."""
1057
+ if task.assignee_id is not None:
1058
+ block["assignee"] = self._user_slug(task.assignee)
1059
+ if task.sprint_id is not None:
1060
+ block["sprint"] = self.sprint_slugs[task.sprint_id]
1061
+ if task.parent_epic_id is not None and task.parent_epic_id in self.task_ref:
1062
+ block["parent_epic"] = self.task_ref[task.parent_epic_id][1]
1063
+ _put(block, "sprint_rank", task.sprint_rank)
1064
+ if task.dor and task.dor != "idea":
1065
+ block["dor"] = task.dor
1066
+ _put(block, "board_lane", task.board_lane)
1067
+ if task.governance_class and task.governance_class != "flow":
1068
+ block["governance_class"] = task.governance_class
1069
+ if task.delivery_mode and task.delivery_mode != "waterfall":
1070
+ block["delivery_mode"] = task.delivery_mode
1071
+ _put(block, "color", task.color)
1072
+
1073
+ def _can_read_blocker_reason(self, task: Task) -> bool:
1074
+ """Apply the ADR-0124 reason gate for the export's requester (#4082).
1075
+
1076
+ Delegates to ``can_read_blocker_reason`` so there is one copy of the
1077
+ rule. That function honors a ``viewer_is_mentioned`` annotation only when
1078
+ it was computed for the same user, so the requester's mentions across the
1079
+ exported projects are fetched once here and stamped on the task, instead
1080
+ of one ``Mention`` query per blocked task.
1081
+ """
1082
+ user = self._blocker_requester
1083
+ if user is _NO_HTTP_CALLER:
1084
+ return True
1085
+ from trueppm_api.apps.notifications.models import Mention
1086
+ from trueppm_api.apps.projects.blocker_services import can_read_blocker_reason
1087
+
1088
+ if user is not None and getattr(user, "is_authenticated", False):
1089
+ if self._mentioned_task_ids is None:
1090
+ self._mentioned_task_ids = set(
1091
+ Mention.objects.filter(
1092
+ mentioned_user_id=user.pk,
1093
+ task_comment__task__project__in=self.projects,
1094
+ ).values_list("task_comment__task_id", flat=True)
1095
+ )
1096
+ task.viewer_is_mentioned_for = user.pk # type: ignore[attr-defined]
1097
+ task.viewer_is_mentioned = task.pk in self._mentioned_task_ids # type: ignore[attr-defined]
1098
+ return can_read_blocker_reason(task, user)
1099
+
1100
+ def _put_task_blocker(self, block: dict[str, Any], task: Task) -> None:
1101
+ """Emit the blocker cluster when the flag is raised (#3094).
1102
+
1103
+ ``blocked_reason`` is the flag-of-record, so its emptiness decides. The
1104
+ derived companions are emitted only when set, and ``blocked_since`` rides
1105
+ along as ``since`` — an unstamped blocker renders no age, and age is the
1106
+ triage signal the flag exists to carry.
1107
+
1108
+ The free-text ``reason`` is emitted only when the requester may read it
1109
+ (ADR-0124, #4082); ``type``/``since``/``blocking_task``/``by`` are the
1110
+ ungated triage signals and always ride along. A cluster without ``reason``
1111
+ still marks the task blocked — the importer supplies a placeholder.
1112
+ """
1113
+ reason = (task.blocked_reason or "").strip()
1114
+ if not reason:
1115
+ return
1116
+ blocked: dict[str, Any] = {}
1117
+ if self._can_read_blocker_reason(task):
1118
+ blocked["reason"] = task.blocked_reason
1119
+ if task.blocked_since is not None:
1120
+ blocked["since"] = self._date_str(task.blocked_since.date())
1121
+ _put(blocked, "type", task.blocker_type)
1122
+ if task.blocking_task_id is not None and task.blocking_task_id in self.task_ref:
1123
+ blocked["blocking_task"] = self.task_ref[task.blocking_task_id][1]
1124
+ if task.blocked_by_id is not None:
1125
+ blocked["by"] = self._user_slug(task.blocked_by)
1126
+ block["blocked"] = blocked
1127
+
1128
+ def _put_task_attachments(self, block: dict[str, Any], task: Task) -> None:
1129
+ """Emit external-link attachments, ordered for a stable round-trip.
1130
+
1131
+ File attachments are skipped rather than half-emitted: a seed is a text
1132
+ document and ``TaskAttachment`` is file XOR ``external_url``, so a file
1133
+ row has nothing expressible. Soft-deleted rows are skipped too — they
1134
+ exist only to keep ``[[attachment:uuid]]`` comment references resolvable.
1135
+ """
1136
+ rows = [
1137
+ row
1138
+ for row in task.attachments.filter(is_deleted=False).order_by("created_at", "pk")
1139
+ if row.external_url
1140
+ ]
1141
+ if not rows:
1142
+ return
1143
+ entries: list[dict[str, Any]] = []
1144
+ for row in rows:
1145
+ entry: dict[str, Any] = {"external_url": row.external_url}
1146
+ _put(entry, "external_title", row.external_title)
1147
+ if row.is_pinned:
1148
+ entry["is_pinned"] = True
1149
+ if row.uploaded_by_id is not None:
1150
+ entry["uploaded_by"] = self._user_slug(row.uploaded_by)
1151
+ entries.append(entry)
1152
+ block["attachments"] = entries
1153
+
1154
+ def _put_task_estimate(self, block: dict[str, Any], task: Task) -> None:
1155
+ if task.optimistic_duration is not None:
1156
+ block["estimate"] = {
1157
+ "optimistic": task.optimistic_duration,
1158
+ "most_likely": task.most_likely_duration,
1159
+ "pessimistic": task.pessimistic_duration,
1160
+ }
1161
+
1162
+ def _put_task_assignments(self, block: dict[str, Any], task: Task) -> None:
1163
+ assignments = [
1164
+ {"resource": self._resource_slug(tr.resource), "units": float(tr.units)}
1165
+ for tr in TaskResource.objects.filter(task=task)
1166
+ .select_related("resource")
1167
+ .order_by("resource__name")
1168
+ ]
1169
+ if assignments:
1170
+ block["assignments"] = assignments
1171
+
1172
+ def _put_task_labels_and_links(self, block: dict[str, Any], task: Task) -> None:
1173
+ label_slugs = self.task_label_slugs.get(task.pk)
1174
+ if label_slugs:
1175
+ block["labels"] = label_slugs
1176
+ links = self._task_relation_blocks(task)
1177
+ if links:
1178
+ block["links"] = links
1179
+
1180
+ def _task_relation_blocks(self, task: Task) -> list[dict[str, Any]]:
1181
+ """Emit this task's outgoing informational relations (ADR-0455).
1182
+
1183
+ Mirrors :meth:`_dependency_blocks`: one block per live ``TaskRelation`` where
1184
+ the task is the *source*, ordered ``(relation_type, target wbs)`` so the
1185
+ round-trip is byte-stable. A relation whose target task is excluded from the
1186
+ export (e.g. a wbs-less promoted task) is dropped, mirroring how a dangling
1187
+ dependency edge is skipped. The target ref is project-qualified only when it
1188
+ crosses a project boundary — the same convention as a dependency predecessor.
1189
+ """
1190
+ src = self.task_ref.get(task.pk)
1191
+ if src is None:
1192
+ return []
1193
+ src_pslug = src[0]
1194
+ blocks: list[dict[str, Any]] = []
1195
+ for rel in (
1196
+ TaskRelation.objects.filter(source=task, is_deleted=False)
1197
+ .select_related("target")
1198
+ .order_by("relation_type", "target__wbs_path", "pk")
1199
+ ):
1200
+ tref = self.task_ref.get(rel.target_id)
1201
+ if tref is None:
1202
+ continue
1203
+ target_ref = tref[1] if tref[0] == src_pslug else f"{tref[0]}:{tref[1]}"
1204
+ block: dict[str, Any] = {"target": target_ref, "link_type": rel.relation_type}
1205
+ _put(block, "note", rel.note)
1206
+ blocks.append(block)
1207
+ return blocks
1208
+
1209
+ def _sprint_block(self, sprint: Sprint) -> dict[str, Any]:
1210
+ block: dict[str, Any] = {
1211
+ "slug": self.sprint_slugs[sprint.pk],
1212
+ "name": sprint.name,
1213
+ "state": sprint.state,
1214
+ "start_date": self._date_str(sprint.start_date) if sprint.start_date else None,
1215
+ "finish_date": self._date_str(sprint.finish_date) if sprint.finish_date else None,
1216
+ }
1217
+ _put(block, "goal", sprint.goal)
1218
+ _put(block, "notes", sprint.notes)
1219
+ _put(block, "committed_points", sprint.committed_points)
1220
+ _put(block, "completed_points", sprint.completed_points)
1221
+ _put(block, "capacity_points", sprint.capacity_points)
1222
+ if sprint.target_milestone_id is not None and sprint.target_milestone_id in self.task_ref:
1223
+ block["target_milestone"] = self.task_ref[sprint.target_milestone_id][1]
1224
+ return block
1225
+
1226
+ def _dependency_blocks(self, project: Project, pslug: str) -> list[dict[str, Any]]:
1227
+ deps = (
1228
+ Dependency.objects.filter(successor__project=project, is_deleted=False)
1229
+ .select_related("predecessor", "successor")
1230
+ .order_by("predecessor__wbs_path", "successor__wbs_path")
1231
+ )
1232
+ blocks = []
1233
+ for dep in deps:
1234
+ pred = self.task_ref.get(dep.predecessor_id)
1235
+ succ = self.task_ref.get(dep.successor_id)
1236
+ if pred is None or succ is None:
1237
+ continue
1238
+ pred_ref = pred[1] if pred[0] == pslug else f"{pred[0]}:{pred[1]}"
1239
+ block: dict[str, Any] = {
1240
+ "predecessor": pred_ref,
1241
+ "successor": succ[1],
1242
+ "dep_type": dep.dep_type,
1243
+ }
1244
+ if dep.lag:
1245
+ block["lag"] = dep.lag
1246
+ blocks.append(block)
1247
+ return blocks
1248
+
1249
+ def _baseline_blocks(self, project: Project, pslug: str) -> list[dict[str, Any]]:
1250
+ blocks = []
1251
+ for baseline in Baseline.objects.filter(project=project).order_by("created_at", "pk"):
1252
+ task_rows = []
1253
+ for bt in BaselineTask.objects.filter(baseline=baseline).order_by("task_name", "pk"):
1254
+ ref = self.task_ref.get(bt.task_id)
1255
+ if ref is None:
1256
+ continue
1257
+ row: dict[str, Any] = {"task": ref[1]}
1258
+ if bt.start is not None:
1259
+ row["start"] = self._date_str(bt.start)
1260
+ if bt.finish is not None:
1261
+ row["finish"] = self._date_str(bt.finish)
1262
+ _put(row, "duration", bt.duration)
1263
+ _put(row, "story_points", bt.story_points)
1264
+ task_rows.append(row)
1265
+ block: dict[str, Any] = {"name": baseline.name, "tasks": task_rows}
1266
+ # Without this the round-trip silently flattens every baseline's
1267
+ # capture date onto import day (#3093), which is the interval
1268
+ # planned-vs-actual is measured over.
1269
+ block["captured_at"] = self._date_str(baseline.created_at.date())
1270
+ if baseline.is_active:
1271
+ block["is_active"] = True
1272
+ blocks.append(block)
1273
+ return blocks
1274
+
1275
+ def _risk_blocks(self, project: Project, pslug: str) -> list[dict[str, Any]]:
1276
+ blocks = []
1277
+ # select_related("owner") + prefetch_related("tasks") keep the per-risk
1278
+ # owner-slug and task-linkage lookups from firing a query inside the loop
1279
+ # (the M2M through rows are batched into a single prefetch query, #2351).
1280
+ risks = (
1281
+ Risk.objects.filter(project=project, is_deleted=False)
1282
+ .select_related("owner")
1283
+ .order_by("title", "pk")
1284
+ .prefetch_related("tasks")
1285
+ )
1286
+ slug_alloc = _SlugAllocator()
1287
+ for risk in risks:
1288
+ risk_slug = slug_alloc.take(risk.title)
1289
+ self.risk_slugs[risk.pk] = risk_slug
1290
+ block: dict[str, Any] = {
1291
+ "slug": risk_slug,
1292
+ "title": risk.title,
1293
+ "status": risk.status,
1294
+ "probability": risk.probability,
1295
+ "impact": risk.impact,
1296
+ }
1297
+ _put(block, "description", risk.description)
1298
+ _put(block, "category", risk.category)
1299
+ _put(block, "response", risk.response)
1300
+ if risk.mitigation_due_date is not None:
1301
+ block["mitigation_due_date"] = self._date_str(risk.mitigation_due_date)
1302
+ _put(block, "trigger", risk.trigger)
1303
+ _put(block, "contingency", risk.contingency)
1304
+ _put(block, "notes", risk.notes)
1305
+ if risk.owner_id is not None:
1306
+ block["owner"] = self._user_slug(risk.owner)
1307
+ refs = []
1308
+ for linked in risk.tasks.all():
1309
+ ref = self.task_ref.get(linked.pk)
1310
+ if ref is None:
1311
+ continue
1312
+ refs.append(ref[1] if ref[0] == pslug else f"{ref[0]}:{ref[1]}")
1313
+ if refs:
1314
+ block["tasks"] = sorted(refs)
1315
+ blocks.append(block)
1316
+ return blocks
1317
+
1318
+ # --- v2 date + event reconstruction ------------------------------------
1319
+
1320
+ def _date_str(self, d: date) -> str:
1321
+ """Emit a date: ISO literal (v1) or an ``anchor``-relative offset (v2)."""
1322
+ return self._rel_date(d) if self.with_events else d.isoformat()
1323
+
1324
+ def _rel_date(self, d: date) -> str:
1325
+ """A ``seedDate`` anchor offset that lands exactly (``!`` = no snap).
1326
+
1327
+ The ``!`` suffix opts out of weekend-snapping so the resolved date is
1328
+ exactly ``anchor + offset`` — essential for round-trip determinism, since
1329
+ a snapped date would drift on re-import.
1330
+ """
1331
+ offset = (d - self.anchor).days
1332
+ if abs(offset) > _MAX_REL_OFFSET_DAYS:
1333
+ return d.isoformat()
1334
+ return f"A{offset:+d}!"
1335
+
1336
+ def _rel_ts(self, dt: datetime) -> str:
1337
+ """A ``seedTimestamp`` anchor offset (event time; never weekend-snapped).
1338
+
1339
+ Replay builds authored event datetimes in UTC (``resolve_timestamp``
1340
+ defaults to UTC), so we normalize to UTC and emit UTC components; a
1341
+ re-import rebuilds the identical instant, closing the round-trip.
1342
+ """
1343
+ u = dt.astimezone(_UTC)
1344
+ offset = (u.date() - self.anchor).days
1345
+ if abs(offset) > _MAX_REL_OFFSET_DAYS:
1346
+ return u.replace(second=0, microsecond=0, tzinfo=None).isoformat()
1347
+ return f"A{offset:+d}T{u.hour:02d}:{u.minute:02d}"
1348
+
1349
+ def _capture_account_identity(self, accounts: list[dict[str, Any]]) -> None:
1350
+ """Record which users are accounts + the deterministic fallback actor.
1351
+
1352
+ Every user emitted into ``accounts[]`` has a slug in ``self.user_slugs``
1353
+ by the time this runs. The fallback actor — used when a history row is
1354
+ attributed to a user who is not (or is no longer) an account — is the
1355
+ lexically-first OWNER account, else the first account. Resolving every
1356
+ event actor to a real account keeps the emitted ``actor`` from dangling
1357
+ and makes it round-trip (replay re-attributes it, re-export reads it).
1358
+ """
1359
+ self._account_user_pks = set(self.user_slugs.keys())
1360
+ if not accounts:
1361
+ return
1362
+ owners = sorted(a["slug"] for a in accounts if a.get("role") == "OWNER")
1363
+ self._fallback_actor_slug = owners[0] if owners else accounts[0]["slug"]
1364
+
1365
+ def _actor_slug(self, user: Any) -> str:
1366
+ """Resolve a history/audit user to an account slug (fallback if not one)."""
1367
+ if user is not None and user.pk in self._account_user_pks:
1368
+ return self._user_slug(user)
1369
+ return self._fallback_actor_slug
1370
+
1371
+ def _events_block(self) -> list[dict[str, Any]]:
1372
+ """Reconstruct the ordered ``events`` timeline from the history tables.
1373
+
1374
+ Emitted event kinds (each a clean export→import→export fixpoint):
1375
+ ``task.status`` (Task history transitions), ``task.points`` (mid-sprint
1376
+ remaining-point changes — the importer births a progressing task's
1377
+ ``remaining_points`` at ``story_points``, so a burned-down value only
1378
+ survives as an event), ``task.comment`` (``TaskComment`` rows),
1379
+ ``sprint.activate`` / ``sprint.close`` (sprint lifecycle timestamps),
1380
+ ``sprint.scope_inject`` (still-PENDING scope rows), and ``retro.action``
1381
+ (retro action items).
1382
+
1383
+ Deliberately *not* reconstructed (documented fidelity gaps, not
1384
+ determinism breaks): ``task.assign`` / ``task.estimate`` / ``task.ac_met``
1385
+ (their end value is already carried by the task's final-state fields set
1386
+ at creation, so re-emitting them as events would double-apply and break
1387
+ the fixpoint); ``risk.status`` (the importer births risks at their final
1388
+ status, so a status event would be a no-op that does not survive a
1389
+ round-trip); ``sprint.scope_resolve`` and ``retro.promote`` (their target
1390
+ row's final state — task dropped from the sprint, or a wbs-less promoted
1391
+ task — cannot replay from the exported snapshot). The task's/sprint's
1392
+ *final* state is always preserved via its fields; only the intermediate
1393
+ audit rows for those specific transitions are not round-tripped.
1394
+ """
1395
+ collected: list[_RawEvent] = []
1396
+ seq = 0
1397
+
1398
+ def emit(when: datetime, action: str, target: str, data: dict[str, Any]) -> None:
1399
+ nonlocal seq
1400
+ collected.append(_RawEvent(when=when, target=target, action=action, seq=seq, data=data))
1401
+ seq += 1
1402
+
1403
+ for project in self.projects:
1404
+ pslug = self.project_slugs[project.pk]
1405
+ for task in self._project_tasks[project.pk]:
1406
+ self._emit_task_history(task, pslug, emit)
1407
+ self._emit_task_comments(task, pslug, emit)
1408
+ for sprint in self._project_sprints[project.pk]:
1409
+ self._emit_sprint_lifecycle(sprint, pslug, emit)
1410
+ self._emit_retro_actions(sprint, pslug, emit)
1411
+ self._emit_scope_injections(project, emit)
1412
+ self._emit_risk_notes(project, emit)
1413
+
1414
+ # Chronological order; ties broken deterministically so re-export is
1415
+ # byte-identical. The array index is the replay tiebreak for same-instant
1416
+ # events (matching the importer's `_resolve_authored` order semantics).
1417
+ collected.sort(key=lambda e: (e.when, e.target, e.action, e.seq))
1418
+ out: list[dict[str, Any]] = []
1419
+ for e in collected:
1420
+ event: dict[str, Any] = {"at": self._rel_ts(e.when), "action": e.action}
1421
+ event.update(e.data)
1422
+ event["target"] = e.target
1423
+ out.append(event)
1424
+ return out
1425
+
1426
+ def _emit_task_history(self, task: Task, pslug: str, emit: _Emit) -> None:
1427
+ """Emit ``task.status`` + ``task.points`` events from Task history.
1428
+
1429
+ The earliest (creation) row establishes the base status/remaining; each
1430
+ later row is inspected for two independent changes:
1431
+
1432
+ - **status** changed → ``task.status`` (from/to). Replay re-creates the
1433
+ task at NOT_STARTED and walks it forward, reproducing the same rows.
1434
+ - **remaining_points** changed *without* a status change → ``task.points``.
1435
+ A remaining change that coincides with a status change is the COMPLETE
1436
+ handler zeroing remaining_points (``_apply_task_status``), which replay
1437
+ re-applies on its own, so emitting a ``task.points`` for it would be a
1438
+ redundant, non-round-tripping write — hence the ``not status_changed``
1439
+ guard.
1440
+ """
1441
+ target = f"task:{pslug}:{task.wbs_path}"
1442
+ prev_status: str | None = None
1443
+ prev_remaining: int | None = None
1444
+ rows = task.history.select_related("history_user").order_by("history_date", "history_id")
1445
+ for row in rows:
1446
+ if prev_status is None:
1447
+ prev_status = row.status
1448
+ prev_remaining = row.remaining_points
1449
+ continue
1450
+ status_changed = row.status != prev_status
1451
+ if status_changed:
1452
+ emit(
1453
+ row.history_date,
1454
+ "task.status",
1455
+ target,
1456
+ {
1457
+ "actor": self._actor_slug(row.history_user),
1458
+ "from": prev_status,
1459
+ "to": row.status,
1460
+ },
1461
+ )
1462
+ prev_status = row.status
1463
+ if (
1464
+ not status_changed
1465
+ and row.remaining_points is not None
1466
+ and row.remaining_points != prev_remaining
1467
+ ):
1468
+ emit(
1469
+ row.history_date,
1470
+ "task.points",
1471
+ target,
1472
+ {
1473
+ "actor": self._actor_slug(row.history_user),
1474
+ "remaining_points": row.remaining_points,
1475
+ },
1476
+ )
1477
+ prev_remaining = row.remaining_points
1478
+
1479
+ def _emit_task_comments(self, task: Task, pslug: str, emit: _Emit) -> None:
1480
+ """Emit comments — and under v2.1, their threads, reactions, acks, and notes.
1481
+
1482
+ A comment gets a ``slug`` only when something refers to it (a reply, a
1483
+ reaction or an acknowledgement), so a program with flat comments exports
1484
+ exactly as it did under 2.0. Reactions and acknowledgements are emitted
1485
+ only for users who already hold an account: attributing them to the
1486
+ fallback actor would invent a reaction nobody gave.
1487
+ """
1488
+ target = f"task:{pslug}:{task.wbs_path}"
1489
+ comments = list(
1490
+ TaskComment.objects.filter(task=task)
1491
+ .select_related("author")
1492
+ .order_by("created_at", "pk")
1493
+ )
1494
+ if not self.with_events or not comments:
1495
+ for c in comments:
1496
+ emit(
1497
+ c.created_at,
1498
+ "task.comment",
1499
+ target,
1500
+ {"actor": self._actor_slug(c.author), "body": c.body},
1501
+ )
1502
+ self._emit_task_notes(task, target, emit)
1503
+ return
1504
+
1505
+ reactions = list(
1506
+ CommentReaction.objects.filter(comment__in=comments, user_id__in=self._account_user_pks)
1507
+ .select_related("user")
1508
+ .order_by("created_at", "pk")
1509
+ )
1510
+ acks = list(
1511
+ CommentAcknowledgement.objects.filter(
1512
+ comment__in=comments, user_id__in=self._account_user_pks
1513
+ )
1514
+ .select_related("user")
1515
+ .order_by("created_at", "pk")
1516
+ )
1517
+ referenced = {c.parent_id for c in comments if c.parent_id is not None}
1518
+ referenced |= {r.comment_id for r in reactions} | {a.comment_id for a in acks}
1519
+ slugs: dict[Any, str] = {}
1520
+ for n, c in enumerate(comments, start=1):
1521
+ if c.pk in referenced:
1522
+ slugs[c.pk] = self.comment_slug.take(f"{pslug}-{task.wbs_path}-comment-{n}")
1523
+
1524
+ for c in comments:
1525
+ data: dict[str, Any] = {"actor": self._actor_slug(c.author), "body": c.body}
1526
+ if c.pk in slugs:
1527
+ data["slug"] = slugs[c.pk]
1528
+ if c.parent_id in slugs:
1529
+ data["reply_to"] = slugs[c.parent_id]
1530
+ emit(c.created_at, "task.comment", target, data)
1531
+ for r in reactions:
1532
+ emit(
1533
+ r.created_at,
1534
+ "task.react",
1535
+ f"comment:{slugs[r.comment_id]}",
1536
+ {"actor": self._user_slug(r.user), "emoji": r.emoji},
1537
+ )
1538
+ for a in acks:
1539
+ emit(
1540
+ a.created_at,
1541
+ "task.ack",
1542
+ f"comment:{slugs[a.comment_id]}",
1543
+ {"actor": self._user_slug(a.user)},
1544
+ )
1545
+ self._emit_task_notes(task, target, emit)
1546
+
1547
+ def _emit_task_notes(self, task: Task, target: str, emit: _Emit) -> None:
1548
+ """Emit ``task.note`` beats from live ``TaskNote`` rows (v2.1, #3492). v2 only.
1549
+
1550
+ A note is append-only like a comment, so replaying it reproduces the row it
1551
+ came from. Per-person logged time is deliberately *not* reconstructed the
1552
+ same way: exporting ``time.log`` would hand every program Admin who can run
1553
+ an export each contributor's hours, which ADR-0104 keeps off management
1554
+ surfaces.
1555
+ """
1556
+ if not self.with_events:
1557
+ return
1558
+ for note in (
1559
+ TaskNote.objects.filter(task=task, is_deleted=False)
1560
+ .select_related("author")
1561
+ .order_by("created_at", "pk")
1562
+ ):
1563
+ data: dict[str, Any] = {"actor": self._actor_slug(note.author), "body": note.body}
1564
+ if note.pinned:
1565
+ data["pinned"] = True
1566
+ if note.decision:
1567
+ data["decision"] = True
1568
+ emit(note.created_at, "task.note", target, data)
1569
+
1570
+ def _emit_risk_notes(self, project: Project, emit: _Emit) -> None:
1571
+ """Emit ``risk.note`` events from RiskComment rows (#3094).
1572
+
1573
+ Safe to reconstruct, unlike ``risk.status``: a comment is an append-only
1574
+ artifact that does not depend on the risk's current status, so replaying
1575
+ it reproduces exactly the rows it came from — the same reason
1576
+ ``task.comment`` round-trips.
1577
+ """
1578
+ for comment in (
1579
+ RiskComment.objects.filter(risk__project=project, risk__is_deleted=False)
1580
+ .select_related("author", "risk")
1581
+ .order_by("created_at", "pk")
1582
+ ):
1583
+ slug = self.risk_slugs.get(comment.risk_id)
1584
+ if slug is None:
1585
+ continue
1586
+ emit(
1587
+ comment.created_at,
1588
+ "risk.note",
1589
+ f"risk:{slug}",
1590
+ {"actor": self._actor_slug(comment.author), "body": comment.message},
1591
+ )
1592
+
1593
+ def _emit_sprint_lifecycle(self, sprint: Sprint, pslug: str, emit: _Emit) -> None:
1594
+ """Emit activate/close from the sprint's lifecycle timestamps.
1595
+
1596
+ ``activated_at`` / ``closed_at`` carry the beat time; the actor is not
1597
+ persisted on the sprint, so the deterministic fallback (OWNER) is used —
1598
+ the sprint's committed/completed points ride their fields (snapshotted at
1599
+ activate/close on replay), and ``goal_outcome`` rides the close event.
1600
+ """
1601
+ target = f"sprint:{pslug}:{self.sprint_slugs[sprint.pk]}"
1602
+ if sprint.activated_at is not None:
1603
+ emit(
1604
+ sprint.activated_at,
1605
+ "sprint.activate",
1606
+ target,
1607
+ {"actor": self._fallback_actor_slug},
1608
+ )
1609
+ if sprint.closed_at is not None:
1610
+ data: dict[str, Any] = {"actor": self._fallback_actor_slug}
1611
+ if sprint.goal_outcome:
1612
+ data["goal_outcome"] = sprint.goal_outcome
1613
+ emit(sprint.closed_at, "sprint.close", target, data)
1614
+
1615
+ def _emit_scope_injections(self, project: Project, emit: _Emit) -> None:
1616
+ """Emit ``sprint.scope_inject`` for still-PENDING scope-change rows.
1617
+
1618
+ Only PENDING rows round-trip cleanly: the injected task is still in its
1619
+ sprint (so replay's ``_apply_scope_inject`` re-creates the audit row), and
1620
+ ``added_at`` is backdated by replay so the timestamp is stable. ACCEPTED /
1621
+ REJECTED rows are skipped — the resolve timestamp is not persisted and a
1622
+ rejected injection removed the task from its sprint.
1623
+ """
1624
+ rows = (
1625
+ SprintScopeChange.objects.filter(
1626
+ sprint__project=project, status=ScopeChangeStatus.PENDING
1627
+ )
1628
+ .select_related("task", "added_by")
1629
+ .order_by("added_at", "pk")
1630
+ )
1631
+ for sc in rows:
1632
+ ref = self.task_ref.get(sc.task_id)
1633
+ if ref is None:
1634
+ continue # task excluded from export (e.g. no wbs_path)
1635
+ data: dict[str, Any] = {"actor": self._actor_slug(sc.added_by)}
1636
+ if sc.goal_impact:
1637
+ data["goal_impact"] = True
1638
+ emit(sc.added_at, "sprint.scope_inject", f"task:{ref[0]}:{ref[1]}", data)
1639
+
1640
+ def _emit_retro_actions(self, sprint: Sprint, pslug: str, emit: _Emit) -> None:
1641
+ """Emit a ``retro.action`` per retro action item on the sprint's retro.
1642
+
1643
+ A non-empty ``SprintRetro.notes`` rides on the last item's beat (as
1644
+ ``notes``) rather than its own event — there is no standalone "open
1645
+ retro" action, so a retro's summary text can only round-trip attached
1646
+ to an action item that already exists (#3497). A retro with notes but
1647
+ no action items cannot be reconstructed as v2 events; that gap predates
1648
+ this change (the retro itself couldn't be created via replay either).
1649
+ """
1650
+ retro = SprintRetro.objects.filter(sprint=sprint).first()
1651
+ if retro is None:
1652
+ return
1653
+ target = f"sprint:{pslug}:{self.sprint_slugs[sprint.pk]}"
1654
+ actor = self._actor_slug(retro.created_by)
1655
+ items = list(
1656
+ # Removed items are soft-deleted (#4591); exporting them would re-import
1657
+ # them as live action items.
1658
+ RetroActionItem.objects.filter(retro=retro, is_deleted=False)
1659
+ .select_related("assignee")
1660
+ .order_by("created_at", "pk")
1661
+ )
1662
+ for i, item in enumerate(items):
1663
+ data: dict[str, Any] = {"actor": actor, "body": item.text}
1664
+ if item.assignee_id is not None and item.assignee_id in self._account_user_pks:
1665
+ data["assignee"] = self._user_slug(item.assignee)
1666
+ if item.story_points is not None:
1667
+ data["points"] = item.story_points
1668
+ if i == len(items) - 1 and retro.notes:
1669
+ data["notes"] = retro.notes
1670
+ emit(item.created_at, "retro.action", target, data)
1671
+
1672
+ # --- slug helpers ------------------------------------------------------
1673
+
1674
+ def _user_slug(self, user: Any) -> str:
1675
+ if user.pk not in self.user_slugs:
1676
+ self.user_slugs[user.pk] = self.account_slug.take(user.get_username())
1677
+ return self.user_slugs[user.pk]
1678
+
1679
+ def _calendar_slug(self, calendar: Any) -> str:
1680
+ if calendar.pk not in self.calendar_slugs:
1681
+ self.calendar_slugs[calendar.pk] = self.calendar_slug.take(calendar.name)
1682
+ return self.calendar_slugs[calendar.pk]
1683
+
1684
+ def _resource_slug(self, resource: Resource) -> str:
1685
+ if resource.pk not in self.resource_slugs:
1686
+ self.resource_slugs[resource.pk] = self.resource_slug.take(resource.name)
1687
+ return self.resource_slugs[resource.pk]
1688
+
1689
+ # --- collection helpers ------------------------------------------------
1690
+
1691
+ def _all_tasks(self) -> list[Task]:
1692
+ return list(
1693
+ Task.objects.filter(project__in=self.projects, is_deleted=False).select_related(
1694
+ "assignee"
1695
+ )
1696
+ )
1697
+
1698
+ def _all_resources(self) -> list[Resource]:
1699
+ # Resources referenced by either a task assignment or the project roster.
1700
+ if self._resources_cache is not None:
1701
+ return self._resources_cache
1702
+ ids = set(
1703
+ TaskResource.objects.filter(task__project__in=self.projects).values_list(
1704
+ "resource_id", flat=True
1705
+ )
1706
+ )
1707
+ ids |= set(
1708
+ ProjectResource.objects.filter(project__in=self.projects, is_deleted=False).values_list(
1709
+ "resource_id", flat=True
1710
+ )
1711
+ )
1712
+ self._resources_cache = list(
1713
+ Resource.objects.filter(pk__in=ids)
1714
+ .select_related("calendar", "user")
1715
+ .order_by("name", "pk")
1716
+ )
1717
+ return self._resources_cache